Send change events
To let IdentityFlow act on a membership or deputy change before the next
sign-in or cache expiry, your directory posts a signed HTTP request to a
webhook registered with hooks.http.webhook(name, definition). IdentityFlow
validates the signature and body, stores one or more durable change envelopes
identified by (source, eventId), answers 202, and applies the changes in
the background.
When you need this: whenever pending dialogs use
assignee sources, or when an
account’s cached principals must be invalidated before principalCacheTtl
(15 minutes by default) expires. Before you start: you have a hooks file
registering your identity provider (and, for dialog refreshes, an assignee
resolver); see
Connect your identity provider.
First, describe the JSON body your directory posts with a Valibot schema
(@identity-flow/sdk/valibot):
const EventId = v.pipe(v.string(), v.minLength(1), v.maxLength(512));
/** The JSON body your directory posts when something changes. */const DirectoryChange = v.variant('type', [ v.strictObject({ type: v.literal('deputies-changed'), eventId: EventId, personId: v.string(), version: v.string(), }), v.strictObject({ type: v.literal('login-changed'), eventId: EventId, origin: v.string(), subject: v.string(), }),]);Then register the webhook inside the same defineHooks module that registers
the provider and resolver:
hooks.http.webhook('directory-changed', { body: DirectoryChange, auth: { type: 'hmac-sha256', secret: () => requiredEnv('ACME_WEBHOOK_SECRET'), signatureHeader: 'x-acme-signature', timestampHeader: 'x-acme-timestamp', maxClockSkew: '5 minutes', }, map(change) { const command = change.type === 'deputies-changed' ? hooks.commands.assignees.sourceChanged({ providerId: PROVIDER_ID, sourceKey: `deputies-of:${change.personId}`, sourceVersion: change.version, }) : hooks.commands.identity.invalidate({ providerId: PROVIDER_ID, account: { origin: change.origin, subject: change.subject }, }); const envelope = { source: 'acme-directory', eventId: change.eventId, command }; return hooks.commands.envelope(envelope); },});map turns the validated body into one change envelope or an array of
envelopes. Build envelopes only with hooks.commands; there are two commands:
hooks.commands.assignees.sourceChanged({ providerId, sourceKey, sourceVersion? })refreshes every pending dialog whose assignee source has this provider and source key. See Assignee sources.hooks.commands.identity.invalidate({ providerId, account: { origin, subject } })discards the stored principals of that login, so the next read asks your provider again.
A webhook may emit commands only for a provider or resolver that the same hooks
file registers. hooks.commands.envelope({ source, eventId, occurredAt?, command })
validates the envelope; occurredAt is an optional ISO timestamp.
The host serves the webhook at:
POST https://<your IdentityFlow host>/-hooks/<hook>/<webhook>
For the example above (defineHooks('acme-directory', …) and
hooks.http.webhook('directory-changed', …)), the path is
/-hooks/acme-directory/directory-changed. Your directory must send two
headers, named by the webhook definition (the two header names must differ):
- Timestamp header (
x-acme-timestamphere): the current Unix time in whole seconds, formatted as a decimal integer. - Signature header (
x-acme-signaturehere):sha256=followed by 64 lowercase hex characters.
Compute HMAC-SHA256 with the shared secret over these five parts joined by a
single LF (\n, 0x0a) byte: identity-flow-webhook-v1, the timestamp header
value, the hook name, the webhook name, and the exact raw request body bytes.
The request is refused when the timestamp differs from the host’s clock by more
than maxClockSkew. The host invokes the secret callback on every request,
so read the secret from the environment or a secret store rather than
hardcoding it in the hooks file.
This script signs and sends one change event with openssl and curl to test
the endpoint:
#!/bin/sh# Signs one change event and posts it to IdentityFlow.# Usage: ACME_WEBHOOK_SECRET=… ./send-change-event.sh https://flow.example.com '<json body>'set -eu
base_url=$1body=$2hook=acme-directorywebhook=directory-changedtimestamp=$(date +%s)
signature=$( printf 'identity-flow-webhook-v1\n%s\n%s\n%s\n%s' "$timestamp" "$hook" "$webhook" "$body" | openssl dgst -sha256 -hmac "$ACME_WEBHOOK_SECRET" -r | cut -d ' ' -f 1)
curl --silent --show-error --request POST "$base_url/-hooks/$hook/$webhook" \ --header 'content-type: application/json' \ --header "x-acme-signature: sha256=$signature" \ --header "x-acme-timestamp: $timestamp" \ --data-binary "$body"Use this script only for manual checks. In production, compute the signature inside your directory service so the shared secret never appears in a process list or shell history.
When implementing the sender in Go:
- Marshal the JSON payload into a
[]byteonce, compute the MAC over those exact bytes, and send that same byte slice as thehttp.NewRequestWithContextbody — do not re-marshal or pretty-print after signing. - Build the HMAC with
crypto/hmac,crypto/sha256, andencoding/hex: write"identity-flow-webhook-v1\n" + timestamp + "\n" + hook + "\n" + webhook + "\n", then write the raw JSON[]byte, and format the header as"sha256=" + hex.EncodeToString(mac.Sum(nil))(lowercase hex). - Format the timestamp header with
strconv.FormatInt(time.Now().Unix(), 10)fresh on every attempt — never reuse a pre-signed header across retries, because a stale timestamp fails with403once older thanmaxClockSkew. - Generate a unique
eventIdper logical directory change and reuse the exact sameeventIdand body when retrying429,503, or network failures.
IdentityFlow validates a webhook call in this exact order and stops at the first failure:
- The caller’s address is within the rate limit: a burst of 8 requests, then 1 per second.
- The URL names a registered hook and webhook.
- Both authentication headers are present.
- The body is at most 1,000,000 bytes, or the lower
limits.bodyBytesof the definition. - The HMAC-SHA256 signature matches and the timestamp is within
maxClockSkew. - The body is valid JSON and matches the
bodyschema. mapreturns at least one envelope, and no more than 1,000, or the lowerlimits.eventsPerRequest.- Every envelope is stored durably. An envelope whose
(source, eventId)was already stored with the same content is reported asduplicate; with different content, the whole request is refused with409.
The secret lookup, schema validation and map share a 5-second budget per
request and a concurrency cap of 8 callback executions per webhook (released
before durable storage); further requests receive 503.
| Status | error in the body | Meaning | What the sender does |
|---|---|---|---|
| 202 | none | Stored. The body is { results: [{ source, eventId, status }] }, with status accepted or duplicate for each envelope. | Nothing. |
| 400 | invalid_request_body | Not JSON, fails the schema, maps to no envelope, or names a provider this hooks file does not register. | Fix the body or the hooks file. |
| 401 | authentication_required | A header is missing. | Send both headers. |
| 403 | authentication_failed | Wrong signature, or a stale timestamp. | Check the secret, the signed bytes and the clock; sign each attempt afresh. |
| 404 | webhook_not_found | No such hook or webhook. | Check the URL. |
| 409 | change_event_conflict | An eventId was reused for different content. | Use a new eventId for new content. |
| 413 | request_too_large | Too many bytes or too many envelopes. | Split the request. |
| 429 | rate_limit_exceeded | Rate limit reached. Retry-After says how many seconds to wait. | Retry later with the same body and eventId, signed again with the current time. |
| 503 | change_ingress_unavailable | The secret callback, the schema or map threw or timed out, or the host is busy. | Retry later with the same body and eventId, signed again with the current time. |
Keep maxClockSkew short, a few minutes at most: together with (source, eventId)
deduplication, it limits replay of captured requests.
maxClockSkew: '5 minutes',- with eventId, stops replays
The 202 response means every change envelope is stored durably in PostgreSQL.
IdentityFlow applies it afterwards, in the background, and never during
workflow replay:
- For
assignees.sourceChanged, a background worker calls your resolver for every pending dialog referencing that(providerId, sourceKey). If a refresh fails (for example because your directory is unreachable), IdentityFlow makes up to 8 attempts in total (the first attempt plus up to 7 retries, waiting 1 second before the first retry and doubling the wait up to 5 minutes). After the last attempt, the refresh appears under Failed work for that instance, where an account withoperatoraccess can replay it; see Operate running workflows. Tune attempts and polling in thechangesblock. - For
identity.invalidate, IdentityFlow retries failures the same way. After the last attempt it drops the background job without surfacing it in Failed work: reads keep using cached principals untilprincipalCacheTtlexpires, while every command always asks the provider fresh.
If your directory cannot send outbound webhooks, register a pull or
subscription adapter with hooks.lifecycle.startup(name, start) and submit the
same envelopes through submit(envelope). See Hooks API.
Test your webhook body schema and map logic without HTTP or a database using
createHookTestHost().http.map:
test('maps each directory change to one change envelope', async () => { const host = createHookTestHost(); host.load(createDirectoryHooks(() => createTestDirectory({})));
await expect( host.http.map('acme-directory', 'directory-changed', { type: 'deputies-changed', eventId: 'evt-1001', personId: 'p-1001', version: '18', }), ).resolves.toEqual({ source: 'acme-directory', eventId: 'evt-1001', command: { type: 'assignees.sourceChanged', version: 1, providerId: 'acme', sourceKey: 'deputies-of:p-1001', sourceVersion: '18', }, }); await expect( host.http.map('acme-directory', 'directory-changed', { type: 'login-changed', eventId: 'evt-1002', origin: 'company-sso', subject: 'login-alex', }), ).resolves.toMatchObject({ eventId: 'evt-1002', command: { type: 'identity.invalidate', account: { origin: 'company-sso', subject: 'login-alex' }, }, }); await expect( host.http.map('acme-directory', 'directory-changed', { type: 'unknown', eventId: 'evt-1003' }), ).rejects.toThrow();});host.http.map starts after HTTP transport and HMAC-SHA256 verification. It
does not verify header distinctness or cross-provider command ownership; verify
live HTTP signing against a running host with the signing script above before
pointing your directory at production.
Next: Assignee sources to wire pending dialogs to your change events, and Hooks API for every webhook option and limit.