Skip to main content

Send sign-up events to analytics and CRM

Tell Segment, Mixpanel, Amplitude, PostHog, Salesforce or HubSpot when a person signs up or signs in.

RecipeDraftView source
This page is a draft. The code exists, and not all of it has been run for this page yet. The page says what was checked.
Packages
lumo
Works with
JavaScript / TypeScriptlumo CLIExpress

What it shows​

  1. You connect an analytics destination in the portal, and choose the events that it receives. A CRM connection writes a contact for each new account.
  2. A person signs up. The destination receives user.registered, with a pseudonym in place of the user ID.
  3. For a tool that has no connector, a webhook sends user.created and user.login to a small forwarder of your own.
  4. The forwarder checks the signature, answers at once, and sends the tool one small event with the user ID.

Before you start​

  • The permission settings.manage in the portal for the connectors.
  • An account at the destination: Segment, Mixpanel, Amplitude or PostHog for analytics, HubSpot or Salesforce for the CRM.
  • Check that your plan includes analytics export and CRM sync in the plans matrix. The webhook path needs neither.
  • For the forwarder: a public HTTPS address where it runs, and the inbound address of your tool. An API key with the scopes admin:webhooks:read and admin:webhooks:write creates the webhook.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_API_KEYFor webhook.sh: an API key with the scopes admin:webhooks:read and admin:webhooks:write.
WEBHOOK_URLFor webhook.sh: the public HTTPS address of the deployed forwarder, for example https://hooks.example.com/webhooks.
SECRET_FILEOptional, for webhook.sh. The file that receives the answer of the creation, with the signing secret. Default: ~/lumoauth-forwarder.json.
LUMOAUTH_WEBHOOK_SECRETThe forwarder reads it: the signing secret of the webhook. Set it with export LUMOAUTH_WEBHOOK_SECRET=$(jq -r .data.secret ~/lumoauth-forwarder.json).
FORWARD_URLThe inbound address of your tool, which receives one JSON event for each sign-up and sign-in.
FORWARD_TOKENOptional. A token that the forwarder sends to the tool as Authorization: Bearer.
PORTOptional. The port of the forwarder. Default: 3000.

Connect an analytics destination​

  1. Open Integrations in the portal, and go to the section Analytics, CDP & CRM.
  2. Click Configure on the card of your tool, for example Segment. The page Segment opens.
  3. Enter the credential, for example the Write key, and choose the Data region.
  4. Under Events to forward, tick user.registered and user.login. With none ticked, every event of the list is forwarded.
  5. Leave Send identify calls (email & name) off, unless your agreement with the tool covers names and addresses.
  6. Turn on Enable Segment, click Save configuration, then Send test event.

Connect a CRM​

  1. In the same section, click Configure on the card of HubSpot or Salesforce.
  2. Enter the credentials, for example the Private app access token for HubSpot.
  3. Under What to sync, keep Contacts on user registration on.
  4. Turn on the sync, for example Enable HubSpot sync, click Save configuration, then Test connection.

These steps were written from the docs. Nobody has followed them for this page yet. The connector steps were not followed: they need an account at an analytics tool or a CRM.

Code​

webhook.sh creates the webhook for the forwarder and saves its signing secret. forward.mjs is the forwarder.

Run each command from the recipes folder of the examples repository. Set the folder up once for your language. The connector steps were not followed: they need an account at an analytics tool or a CRM.

operations/analytics-and-crm/js/forward.mjs
// Forward sign-ups and sign-ins to a tool that has no LumoAuth connector.
// The receiver checks the signature of each webhook, answers at once, and
// then sends a small event to the inbound address of the tool.
//
// node operations/analytics-and-crm/js/forward.mjs
import { createHmac, timingSafeEqual } from 'node:crypto';
import express from 'express';

const secret = process.env.LUMOAUTH_WEBHOOK_SECRET;
const forwardUrl = process.env.FORWARD_URL;
const port = Number(process.env.PORT ?? 3000);

if (!secret || !forwardUrl) {
console.error('Set LUMOAUTH_WEBHOOK_SECRET and FORWARD_URL.');
process.exit(1);
}

// The clocks of two servers differ a little. Five minutes is a common limit.
const MAX_AGE_SECONDS = 300;

// The delivery IDs that were handled. A real app keeps them in a store that
// all its instances share.
const seen = new Set();

/** Checks one signature header. Returns the delivery ID, or null. */
function verify(header, rawBody) {
if (!header) return null;
// The header is "kid=...,t=<unix time>,id=<delivery ID>,v1=<hex HMAC>".
const fields = Object.fromEntries(
header.split(',').map((field) => {
const at = field.indexOf('=');
return [field.slice(0, at), field.slice(at + 1)];
}),
);
if (!fields.t || !fields.id || !fields.v1) return null;
if (Math.abs(Date.now() / 1000 - Number(fields.t)) > MAX_AGE_SECONDS) return null;
const expected = createHmac('sha256', secret).update(`${fields.t}.${fields.id}.`).update(rawBody).digest();
const given = Buffer.from(fields.v1, 'hex');
return given.length === expected.length && timingSafeEqual(given, expected) ? fields.id : null;
}

/**
* What the tool receives. The person is named by the LumoAuth user ID. A
* sign-up also carries the email address, which a CRM needs for a contact.
* Nothing else of the webhook leaves your server.
*/
function toolEvent(event, envelope) {
const data = envelope.data;
switch (event) {
case 'user.created':
// The new account is the target of the event.
return { type: 'signed_up', user_id: data.target_id, email: data.metadata?.email ?? data.target_name, at: envelope.timestamp };
case 'user.login':
// The person who signed in is the actor of the event.
return { type: 'signed_in', user_id: data.actor_id, method: data.metadata?.method ?? null, at: envelope.timestamp };
default:
return null;
}
}

async function forward(item) {
const headers = { 'Content-Type': 'application/json' };
// Many tools put their token in the inbound address. Others want a header.
if (process.env.FORWARD_TOKEN) headers.Authorization = `Bearer ${process.env.FORWARD_TOKEN}`;
const answer = await fetch(forwardUrl, { method: 'POST', headers, body: JSON.stringify(item) });
return answer.status;
}

const app = express();

// express.raw keeps the bytes of the body, which the signature covers.
app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
// For 24 hours after a rotation, the second header holds a signature that
// was made with the secret from before the rotation.
const deliveryId =
verify(req.get('X-LumoAuth-Signature'), req.body) ?? verify(req.get('X-LumoAuth-Signature-Previous'), req.body);
if (!deliveryId) {
console.log('rejected: no valid signature');
return res.status(401).json({ error: 'invalid_signature' });
}
const event = req.get('X-LumoAuth-Event');
// A repeat is answered with 200 too, so that LumoAuth stops sending it.
if (seen.has(deliveryId)) {
console.log(`${event}: repeat, not forwarded`);
return res.json({ received: true });
}
seen.add(deliveryId);

// Answer first: LumoAuth waits 5 seconds, then counts the delivery as failed.
res.json({ received: true });

const item = toolEvent(event, JSON.parse(req.body.toString('utf8')));
if (!item) return console.log(`${event}: not forwarded`);
forward(item)
.then((status) => console.log(`${event} -> ${item.type} ${item.user_id}: the tool answered ${status}`))
.catch((error) => console.log(`${event} -> ${item.type} ${item.user_id}: not delivered (${error.message})`));
});

app.listen(port, '127.0.0.1', () => console.log(`listening on http://localhost:${port}/webhooks`));
node operations/analytics-and-crm/js/forward.mjs

Compiles. Not run against an organization. The forwarder ran locally against deliveries that were signed with the documented scheme, in the shape of real user.created and user.login events, and it sent them to a local stand-in for the tool. No delivery from an organization reached it: the test organization had no public receiver.

Check the result​

Output
listening on http://localhost:3000/webhooks
user.created -> signed_up 01a22000-bbaf-7256-b895-a33a8bdb4ab4: the tool answered 202
user.login -> signed_in 01a22000-bbaf-7256-b895-a33a8bdb4ab4: the tool answered 202
  • The tool receives {"type": "signed_up", "user_id": "…", "email": "…", "at": "…"} for a sign-up, and {"type": "signed_in", "user_id": "…", "method": "password", "at": "…"} for a sign-in. No event carries a password, a token or the signing secret.
  • At an analytics destination, the event is user.registered or user.login. Its distinct_id is a pseudonym that is stable for the person, not the user ID.
  • In HubSpot or Salesforce, the new person is a contact, found by the email address.
  • The portal shows sent and failed counters and the last error on the page of each connector.

Limits​

  • An analytics destination receives a fixed list of events. Other audit events are never forwarded.
  • The CRM gets a contact only for an account that a person creates: by sign-up, by accepting an invitation, or at the first sign-in with a social or SAML connection. Accounts that an administrator, the Admin API, SCIM, HR sync or LDAP creates are not sent.
  • The forwarder handles user.created for every new account, however it was created. Filter on the event data if your tool wants only sign-ups.
  • A webhook sends no event about a person whose processing is restricted under GDPR, except user.deleted.
  • The forwarder keeps the delivery IDs in memory. With more than one instance, keep them in a store that all instances share.