Webhooks
Receive ulex identity events safely: the exact payload, HMAC-SHA256 signature verification with constant-time comparison, idempotent processing, the retry schedule, the auto-disable threshold, ordering, and a complete receiver you can copy.
#1. Register the endpoint
curl -sS -X POST "$BASE/webhooks" \
-H "Authorization: Bearer $ULEX_API_KEY" -H "Content-Type: application/json" \
-H "Idempotency-Key: 3c9d1f77-0b2e-4a58-9d61-5e7a2c40b913" \
-d '{
"url": "https://hooks.example.com/ulex",
"events": ["dsync.user.created", "dsync.user.updated", "dsync.user.deleted", "user.suspended", "session.created"],
"description": "Identity events for the Acme Support pipeline",
"api_version": "2025-01-01"
}'{
"webhook": {
"id": "whk_01M3PSVK981SXWGKG9JXHC1P0Y",
"object": "webhook",
"url": "https://hooks.example.com/ulex",
"status": "enabled",
"events": ["dsync.user.created", "dsync.user.updated", "dsync.user.deleted", "user.suspended", "session.created"],
"secret_prefix": "whsec_3Kq9",
"failure_count": 0,
"api_version": "2025-01-01",
"created_at": "2026-09-29T14:42:17.000Z"
},
"secret": "whsec_3Kq9Xa2mB7yLt4NxZ1pRc6HdE0sJg3AuV8",
"signature_algorithm": "HMAC-SHA256",
"signature_header": "Ulex-Signature",
"signature_example": "t=1790693112,v1=8JmQ1vZ0Xh4n7cW2sT5yP9rB3kD6fG1aH0mNqU4wE7iO2pL5xC8vB1nMg0jKhR3tFyD7wZq2"
}secret is returned exactly once. It is stored encrypted and is not retrievable again — not by GET /webhooks/{id}, not by any MCP tool. To rotate: create a second endpoint with the new secret, deploy it, cut traffic over, then delete the first. There is no in-place rotation because there is no way to re-reveal the old secret during the overlap.
Unknown event names are rejected at create time. The set is closed and append-only; a new event is a version bump, never a rename.
#2. The request
POST /ulex HTTP/1.1
Host: hooks.example.com
Content-Type: application/json
Ulex-Signature: t=1790693112,v1=8JmQ1vZ0Xh4n7cW2sT5yP9rB3kD6fG1aH0mNqU4wE7iO2pL5xC8vB1nMg0jKhR3tFyD7wZq2
Ulex-Delivery-Id: dlv_01M3PSVM8G1BF1SQ3FQ0FPKJJA
Ulex-Event: dsync.user.created
Ulex-Attempt: 1
X-Ulex-Request-Id: req_01M3PSW9R0175NAW62NYR403R8{
"id": "evt_01M3PSW3WGDDFJFJHZ4QJNNFZD",
"object": "event",
"api_version": "2025-01-01",
"environment": "prod",
"tenant_id": "ten_01M3PSV6K0HFZ62YZ6AKB191WW",
"event": "dsync.user.created",
"event_id": "evt_01M3PSW3WGDDFJFJHZ4QJNNFZD",
"created_at": "2026-09-29T14:42:18.000Z",
"attempt": 1,
"livemode": true,
"request_id": "req_01M3PSW9R0175NAW62NYR403R8",
"data": {
"user": {
"id": "usr_01M3PSWBPGS08FWV4NV7P9VNFN",
"object": "user",
"email": "pat@acme.example",
"email_verified": true,
"first_name": "Pat",
"last_name": "Iyer",
"display_name": "Pat Iyer",
"job_title": "Support Engineer",
"department": "Customer Success",
"status": "active",
"directory_id": "dir_01M3PSVBF8038RK2MW2N263Q2B"
},
"membership": {
"id": "mem_01M3PSW0YRNEQQAP9T1JP9FC2Y",
"organization_id": "org_01M3PSV8HGTKQFCAYF9GDWGN3C",
"role": "member",
"group_ids": ["grp_01M3PSVED0M9RJTYH5AC72C253"]
},
"organization": { "id": "org_01M3PSV8HGTKQFCAYF9GDWGN3C", "name": "Acme Corp", "slug": "acme" }
}
}| Field | Use |
|---|---|
event_id | the deduplication key. Identical across every retry of one event |
attempt | 1-based, increments on retry |
livemode | false on tenants with allow_mocks: true or in local mode. Do not build alerting on it |
data.previous_attributes | present on update events, only the keys that changed |
data | event-specific; always contains the resource plus its membership and organization where applicable |
#3. Verify the signature
Signed payload: the literal string ` ${timestamp}. ` concatenated with the exact request bytes.
import { createHmac, timingSafeEqual } from "node:crypto";
export function verifyUlexSignature(
rawBody: Buffer,
header: string | undefined,
secret: string,
toleranceSeconds = 300,
nowMs = Date.now(),
): boolean {
if (!header) return false;
const parts: Record<string, string> = {};
for (const pair of header.split(",")) {
const i = pair.indexOf("=");
if (i > 0) parts[pair.slice(0, i).trim()] = pair.slice(i + 1).trim();
}
const { t: timestamp, v1: signature } = parts;
if (!timestamp || !signature) return false;
// Freshness: without this, a captured body replays forever.
const age = Math.abs(nowMs / 1000 - Number(timestamp));
if (!Number.isFinite(age) || age > toleranceSeconds) return false;
const expected = createHmac("sha256", secret)
.update(`${timestamp}.`)
.update(rawBody)
.digest("hex");
const a = Buffer.from(expected, "utf8");
const b = Buffer.from(signature, "utf8");
return a.length === b.length && timingSafeEqual(a, b);
}Four rules, none optional:
- Verify raw bytes. Buffer the request, verify, then parse. Re-serialising parsed JSON changes key order and whitespace, which breaks the HMAC. This is the most common integration failure.
- Constant-time compare.
timingSafeEqual, never===. - Check the timestamp. A correct signature on a two-hour-old body is still a replay.
- Ignore the length difference.
timingSafeEqualthrows on length mismatch; compare lengths first, as above.
#4. Acknowledge in under five seconds
| Rule | Value |
|---|---|
| Timeout | 5 s |
| Success | any 2xx |
| Failure | anything else, a timeout, or a connection error |
| Max attempts | 8 |
| Backoff | 10 s, 30 s, 2 m, 8 m, 30 m, 2 h, 8 h, with jitter |
| Rate | 25 requests/second per endpoint |
| Auto-disable | 8 consecutive failures → status: "disabled" |
| Re-enable | POST /webhooks/{id}/enable, manual only |
// Wrong: 8 seconds of work before the 200.
app.post("/ulex", async (req, res) => {
const event = verify(req);
await provisionEverythingFor(event); // takes 8 seconds
res.status(200).end();
});
// Right: 200 immediately, work after.
app.post("/ulex", (req, res) => {
const event = verify(req);
res.status(200).json({ received: true });
queue.enqueue(event).catch(logAndAlert);
});A slow handler turns one event into eight deliveries, and after eight the endpoint auto-disables and you silently stop hearing about identity changes. A fast 200 costs nothing.
#5. Process idempotently
Delivery is at-least-once. The same event_id will arrive more than once.
export class EventDeduper {
private readonly seen = new Set<string>();
constructor(private readonly max = 10_000) {}
isDuplicate(eventId: string): boolean {
if (this.seen.has(eventId)) return true;
this.seen.add(eventId);
if (this.seen.size > this.max) this.seen.delete(this.seen.values().next().value as string);
return false;
}
}In production use a real store — a unique index on event_id in Postgres is the correct primitive, because it deduplicates across processes and survives a restart. An in-memory Set deduplicates within one process lifetime only.
CREATE TABLE ulex_events (
event_id TEXT PRIMARY KEY,
event TEXT NOT NULL,
received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
processed_at TIMESTAMPTZ
);
-- INSERT … ON CONFLICT (event_id) DO NOTHING; rows_returned = 0 means duplicate.#6. Events are not ordered
A retry storm can deliver dsync.user.updated before dsync.user.created. Do not depend on arrival order.
| Event | Safe assumption |
|---|---|
*.created | the resource exists when this arrives |
*.updated | the resource may or may not exist yet; upsert, do not update |
*.deleted | treat as "make it absent", idempotently |
user.suspended | the user is locked out; your own session store should be updated |
async function handle(event: UlexEvent): Promise<void> {
switch (event.event) {
case "dsync.user.created":
case "dsync.user.updated": {
const user = event.data?.user as { id: string; email: string };
// Upsert, never update. The updated event can arrive first.
await users.upsert({ id: user.id, email: user.email, ...pickProfile(event.data) });
break;
}
case "dsync.user.deleted":
case "user.suspended": {
const user = event.data?.user as { id: string } | undefined;
if (user?.id) await users.suspend(user.id);
await sessions.revokeAllFor(user?.id);
break;
}
case "session.revoked":
await sessions.revoke(event.data?.session_id as string);
break;
default:
logger.info({ event: event.event }, "unhandled ulex event");
}
}#7. A complete receiver
// webhook-receiver.ts
import { createHmac, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";
const SECRET = process.env.ULEX_WEBHOOK_SECRET!;
const TOLERANCE_SECONDS = 300;
const MAX_SEEN = 10_000;
const seen = new Set<string>();
interface UlexEvent {
id: string;
object: "event";
api_version: string;
environment: string;
tenant_id: string;
event: string;
event_id: string;
created_at: string;
attempt: number;
livemode: boolean;
request_id?: string;
data?: Record<string, unknown> & { previous_attributes?: Record<string, unknown> };
}
function verify(rawBody: Buffer, header: string | undefined): boolean {
if (!header) return false;
const parts: Record<string, string> = {};
for (const pair of header.split(",")) {
const i = pair.indexOf("=");
if (i > 0) parts[pair.slice(0, i).trim()] = pair.slice(i + 1).trim();
}
const timestamp = parts.t;
const signature = parts.v1;
if (!timestamp || !signature) return false;
const age = Math.abs(Date.now() / 1000 - Number(timestamp));
if (!Number.isFinite(age) || age > TOLERANCE_SECONDS) return false;
const expected = createHmac("sha256", SECRET).update(`${timestamp}.`).update(rawBody).digest("hex");
const a = Buffer.from(expected, "utf8");
const b = Buffer.from(signature, "utf8");
return a.length === b.length && timingSafeEqual(a, b);
}
function isDuplicate(eventId: string): boolean {
if (seen.has(eventId)) return true;
seen.add(eventId);
if (seen.size > MAX_SEEN) seen.delete(seen.values().next().value as string);
return false;
}
const server = createServer((req, res) => {
if (req.method !== "POST" || req.url !== "/ulex") {
res.writeHead(404).end();
return;
}
const chunks: Buffer[] = [];
req.on("data", (c: Buffer) => chunks.push(c));
req.on("end", () => {
const raw = Buffer.concat(chunks); // verify these exact bytes
if (!verify(raw, req.headers["ulex-signature"] as string | undefined)) {
res.writeHead(400, { "content-type": "application/json" });
res.end(JSON.stringify({ error: "bad_signature" }));
return;
}
const event = JSON.parse(raw.toString("utf8")) as UlexEvent;
const duplicate = isDuplicate(event.event_id);
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ received: true, duplicate }));
if (!duplicate) void handle(event);
});
});
async function handle(event: UlexEvent): Promise<void> {
try {
switch (event.event) {
case "dsync.user.created":
case "dsync.user.updated":
case "dsync.user.deleted": {
const user = event.data?.user as { id: string; email: string } | undefined;
console.log(`[ulex] ${event.event} ${user?.email} (attempt ${event.attempt})`);
break;
}
case "user.suspended":
await revokeSessionsFor((event.data as { user: { id: string } })?.user?.id);
break;
default:
console.log(`[ulex] unhandled ${event.event}`);
}
} catch (err) {
console.error("[ulex] handler failed", err);
}
}
async function revokeSessionsFor(_userId: string): Promise<void> {
// Your app's session store, not ulex's.
}
server.listen(8080, () => console.log("ulex webhook receiver on :8080"));#8. Test it
curl -sS -X POST "$BASE/webhooks/whk_01M3PSVK981SXWGKG9JXHC1P0Y/test" \
-H "Authorization: Bearer $ULEX_API_KEY" -H "Content-Type: application/json" \
-d '{"event":"user.created"}'{
"id": "dlv_01M3PSW2X8E8H2CCW1AX67T8C1",
"object": "webhook_delivery",
"webhook_id": "whk_01M3PSVK981SXWGKG9JXHC1P0Y",
"event": "user.created",
"event_id": "evt_01M3PSW5V0FYTW40CESDH2EDCK",
"status": "in_flight",
"attempt": 1,
"max_attempts": 8
}Then poll the outcome:
curl -sS "$BASE/webhook-deliveries/dlv_01M3PSW2X8E8H2CCW1AX67T8C1" -H "Authorization: Bearer $ULEX_API_KEY" | jq{
"id": "dlv_01M3PSW2X8E8H2CCW1AX67T8C1",
"object": "webhook_delivery",
"status": "delivered",
"attempt": 1,
"max_attempts": 8,
"response_status": 200,
"response_body": "{\"received\":true}",
"duration_ms": 84,
"delivered_at": "2026-09-29T14:42:18.000Z"
}A test delivery is a real delivery: same queue, same signature, same retries.
#9. Diagnose a broken endpoint
curl -sS -G "$BASE/webhooks/whk_01M3PSVK981SXWGKG9JXHC1P0Y/deliveries?status=failed" \
-H "Authorization: Bearer $ULEX_API_KEY" | jq '.data[] | {id, event, attempt, response_status, error, next_attempt_at}'
curl -sS "$BASE/webhooks/whk_01M3PSVK981SXWGKG9JXHC1P0Y" -H "Authorization: Bearer $ULEX_API_KEY" \
| jq '{status, failure_count, disabled_at, disabled_reason, last_delivery_status}'response_status | Meaning |
|---|---|
2xx | delivered |
null with an error | connection refused, DNS failure, TLS error, or the 5 s timeout |
400 | your receiver rejected the signature. It is your bug, not a network problem |
401/403 | something in front of your receiver is authenticating |
429 | you are rate limiting yourself at 25 rps |
5xx | your handler is throwing |
301/302 | you are redirecting. ulex does not follow redirects; fix the URL |
{
"id": "dlv_01M3PSW2X8E8H2CCW1AX67T8C1",
"object": "webhook_delivery",
"status": "dead_lettered",
"attempt": 8,
"max_attempts": 8,
"response_status": null,
"error": "connect ECONNREFUSED 10.0.0.7:8080",
"created_at": "2026-09-29T14:00:00.000Z"
}#10. When it auto-disables
After 8 consecutive failures:
{
"id": "whk_01M3PSVK981SXWGKG9JXHC1P0Y",
"object": "webhook",
"status": "disabled",
"failure_count": 8,
"disabled_at": "2026-09-29T16:30:00.000Z",
"disabled_reason": "8 consecutive delivery failures"
}curl -sS -X POST "$BASE/webhooks/whk_01M3PSVK981SXWGKG9JXHC1P0Y/enable" -H "Authorization: Bearer $ULEX_API_KEY"Re-enabling resets failure_count to 0. It is always manual: an endpoint that failed eight times has a problem a retry will not fix.
Events raised while the endpoint is disabled are not replayed on re-enable. They are retained as webhook_delivery records with status: "dead_lettered" for 30 days. If you were offline, you must reconcile:
curl -sS -G "$BASE/webhooks/whk_01M3PSVK981SXWGKG9JXHC1P0Y/deliveries?status=dead_lettered" \
-H "Authorization: Bearer $ULEX_API_KEY" | jq '.data[].event_id'Then re-fetch current state for each affected user with GET /users/{id}. Do not try to replay the payloads; the user objects in them are a point-in-time snapshot.
#11. Which events to subscribe to
| Goal | Events |
|---|---|
| Mirror a customer directory | dsync.user.created, dsync.user.updated, dsync.user.deleted, dsync.group.* |
| Lock users out fast | user.suspended, session.revoked, dsync.user.deleted |
| Drive your own app's provisioning | user.created, user.updated, organization.created, organization.updated |
| Catch misconfiguration | connection.activated, connection.deactivated, domain.verified |
| Alert on agent behaviour | mcp.tool_invoked |
| Delivery receipts | deployment.started, deployment.succeeded, deployment.failed, deployment.cancelled |
| Credential hygiene | api_key.created, api_key.revoked |
If you subscribe to all 34 events you will process a lot of noise. mcp.tool_invoked is sampled (every 100th call, plus 100% of the destructive ones) precisely so you can see the shape of an agent's activity without drowning in it.