Patterns
Nine copy-paste recipes for ulex: multi-tenant onboarding, just-in-time provisioning, the full SCIM lifecycle, SAML SP wiring, headless SSO testing, a webhook receiver with signature verification, zero-downtime credential rotation, auditing your own actions, and migrating from the simulator to a real IdP.
Every recipe here is complete and runnable. Adapt the ids; the shapes are exact.
The TypeScript snippets assume this binding, which is the only ulex-specific setup any of them needs:
// ulex.ts
export const tools = createUlexTools({
apiKey: process.env.ULEX_API_KEY!, // ulex_sk_live_… — never a literal
// environment is inferred from the key. There is nothing to pass here.
});
export type AuditEvent = {
id: string;
action: string;
category: string;
actor_type: "user" | "api_key" | "system" | "service" | "agent";
outcome: "success" | "failure" | "denied";
error_code: string | null;
timestamp: number;
chain: { sequence: number; previous_hash: string | null; entry_hash: string };
};
const tally = <T>(items: T[], key: (item: T) => string): Record<string, number> =>
items.reduce<Record<string, number>>((acc, item) => {
const k = key(item);
acc[k] = (acc[k] ?? 0) + 1;
return acc;
}, {});#1. Multi-tenant onboarding
Goal: onboard a new customer — org, verified domain, connection, three users, one group — idempotently, from a single idempotency key.
// onboard-tenant.ts
interface OnboardInput {
tenantName: string;
domain: string; // acme.example
adminEmail: string;
memberEmails: string[];
webhookUrl: string;
}
const STRATEGY = "mock_sso" as const; // swap to okta_oidc / entra_oidc / saml in production
export async function onboardTenant(input: OnboardInput) {
const domainSlug = input.domain.split(".")[0]!;
const { organization } = await tools.ulex_create_organization({
name: input.tenantName,
slug: domainSlug,
sso_only: true,
// Reuse the same idempotency key across the whole onboard so a crash
// halfway through does not duplicate the org on retry.
idempotency_key: `onboard-${input.domain}`,
});
const { domain } = await tools.ulex_add_domain({
organization_id: organization.id,
domain: input.domain,
verification_strategy: "dns",
});
const verified = await tools.ulex_verify_domain({
organization_id: organization.id,
domain_id: domain.id,
});
if (verified.state !== "verified") {
throw new Error(`domain ${input.domain} is ${verified.state}, expected verified`);
}
const { connection } = await tools.ulex_create_connection({
name: `${input.tenantName} SSO`,
organization_id: organization.id,
domains: [input.domain],
config: {
strategy: STRATEGY,
mock: {
seed_users: [input.adminEmail, ...input.memberEmails].map((email) => ({
email,
first_name: email.split("@")[0]!,
status: "active" as const,
})),
},
},
idempotency_key: `onboard-conn-${input.domain}`,
});
// Not idempotent in the "returns the same object" sense, but transitioning
// an already-active connection is a no-op, so this is safe to repeat.
const active = await tools.ulex_activate_connection({ connection_id: connection.id });
const { group } = await tools.ulex_create_group({
organization_id: organization.id,
name: "All Staff",
slug: "all-staff",
source: "rule",
idempotency_key: `onboard-grp-${input.domain}`,
});
const members: string[] = [];
for (const [index, email] of [input.adminEmail, ...input.memberEmails].entries()) {
const { user } = await tools.ulex_create_user({
email,
email_verified: true,
first_name: email.split("@")[0]!,
idempotency_key: `onboard-user-${email}`,
});
await tools.ulex_add_organization_member({
organization_id: organization.id,
user_id: user.id,
role: index === 0 ? "owner" : "member",
group_ids: [group.id],
});
members.push(user.id);
}
// Point the org at its connection.
//
// `sso_only: true` enforces that members of this organization must authenticate
// via this enterprise connection (password/social logins are refused).
await tools.ulex_update_organization({
organization_id: organization.id,
connection_id: active.id,
default_connection_id: active.id,
sso_only: true,
});
const { webhook } = await tools.ulex_create_webhook({
url: input.webhookUrl,
events: ["dsync.user.created", "dsync.user.deleted", "dsync.user.updated", "user.suspended"],
idempotency_key: `onboard-wh-${input.domain}`,
});
return { organization: organization.id, connection: active.id, group: group.id, members, webhook: webhook.id };
}Checklist before you call this done: connection.state === "active", every domain state === "verified", the admin has role: "owner", and ulex_simulate_login succeeds for the admin.
#2. Just-in-time provisioning
Goal: a user who has never been provisioned logs in through SSO and is created automatically, mapped by verified email domain, with a role derived from a group claim.
Two switches, both on the connection:
{
"config": {
"strategy": "entra_oidc",
"oidc": {
"issuer": "https://login.microsoftonline.com/common/v2.0",
"client_id": "0oa3kq9x2mB7cVd1Rf6sT4pW8L",
"client_secret": "env:ULEX_TEST_ENTRA_SECRET",
"scopes": ["openid", "profile", "email", "groups"],
"allowed_domains": ["acme.example", "globex.example"],
"require_jit_provisioning": false,
"jit_default_role": "member",
"attribute_mapping": {
"email": "preferred_username",
"email_verified": "email_verified",
"first_name": "given_name",
"last_name": "family_name",
"display_name": "name",
"job_title": "jobTitle",
"department": "department",
"external_id": "oid",
"groups": "groups"
}
}
}
}Role mapping, applied after the login completes:
const ROLE_BY_GROUP: Record<string, "owner" | "admin" | "member" | "guest"> = {
"Entra Admins": "admin",
"Entra Owners": "owner",
"Entra Guests": "guest",
};
export async function applyJitRoles(session: {
user_id: string;
organization_id: string;
groups: string[];
}) {
let role: "owner" | "admin" | "member" | "guest" | null = null;
// Most privileged match wins.
for (const [group, candidate] of Object.entries(ROLE_BY_GROUP)) {
if (session.groups.includes(group)) {
if (candidate === "owner") { role = "owner"; break; }
if (candidate === "admin" && role !== "owner") role = "admin";
if (candidate === "guest" && role === null) role = "guest";
}
}
if (!role) return { changed: false, reason: "no_mapped_group" };
const before = await tools.ulex_list_organization_members({
organization_id: session.organization_id,
});
const existing = before.data.find((m) => m.user_id === session.user_id);
if (existing?.role === role) return { changed: false, reason: "already_applied", role };
const membership = await tools.ulex_add_organization_member({
organization_id: session.organization_id,
user_id: session.user_id,
role,
});
return { changed: true, membership_id: membership.id, role };
}Deprovisioning on the way out: subscribe to connection.deactivated and dsync.user.deleted, then call ulex_suspend_user (not delete_user) unless your compliance posture requires hard deletion. Suspension revokes sessions immediately and is reversible; deletion is not.
#3. The SCIM lifecycle
Goal: the complete Okta/Entra → ulex path: register the directory, hand ulex the SCIM base URL and token, create, update, group-assign, and deprovision — and know what each response means.
#3a. Register the directory and fetch the SCIM config
{ "name": "ulex_create_directory", "arguments": {
"name": "Acme (Okta)",
"provider": "okta",
"domain": "acme.example",
"organization_id": "org_01M3PSV8HGTKQFCAYF9GDWGN3C",
"inbound_scim_enabled": true,
"scim_poll_interval_seconds": 900
} }{ "name": "ulex_get_scim_configuration", "arguments": { "directory_id": "dir_01M3PSVBF8038RK2MW2N263Q2B" } }Base URL https://ulexid.com/api/v1/scim/v2
Bearer token scim_7Bq4Nxf2Vk9Lc3MdT6hR8wS1yP5aG0eJ
Auth header Authorization: Bearer scim_7Bq4Nxf2Vk9Lc3MdT6hR8wS1yP5aG0eJPaste those into Okta → Applications → App Integration → Provisioning → SCIM, or Entra → Enterprise applications → Provisioning.
#3b. Create a user (what Okta POSTs)
BASE="https://ulexid.com/api/v1/scim/v2"
SCIM="Authorization: Bearer scim_7Bq4Nxf2Vk9Lc3MdT6hR8wS1yP5aG0eJ"
JSON="Content-Type: application/scim+json"
curl -sS -X POST "$BASE/Users" -H "$SCIM" -H "$JSON" \
-d '{
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
"userName": "pat@acme.example",
"name": { "givenName": "Pat", "familyName": "Iyer", "formatted": "Pat Iyer" },
"displayName": "Pat Iyer",
"emails": [{ "value": "pat@acme.example", "type": "work", "primary": true }],
"active": true,
"title": "Support Engineer",
"department": "Customer Success",
"preferredLanguage": "en-US",
"locale": "en-US",
"externalId": "okta-00u9xK2mB7yLt4N",
"urn:ietf:params:scim:schemas:extension:enterprise:2.0:User": {
"employeeNumber": "E-4417",
"manager": { "value": "usr_01M3PSV9GRT8GQGEG686AR1W9S" }
}
}'{
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
"id": "usr_01M3PSWBPGS08FWV4NV7P9VNFN",
"externalId": "okta-00u9xK2mB7yLt4N",
"userName": "pat@acme.example",
"name": { "givenName": "Pat", "familyName": "Iyer", "formatted": "Pat Iyer" },
"displayName": "Pat Iyer",
"emails": [{ "value": "pat@acme.example", "type": "work", "primary": true }],
"active": true,
"title": "Support Engineer",
"department": "Customer Success",
"preferredLanguage": "en-US",
"locale": "en-US",
"meta": {
"resourceType": "User",
"created": "2026-09-29T14:47:03.000Z",
"lastModified": "2026-09-29T14:47:03.000Z",
"version": "W/\"v1.0\"",
"location": "https://ulexid.com/api/v1/scim/v2/Users/usr_01M3PSWBPGS08FWV4NV7P9VNFN"
}
}#3c. Update, using the optimistic-lock If-Match from meta.version
curl -sS -X PATCH "$BASE/Users/usr_01M3PSWBPGS08FWV4NV7P9VNFN" \
-H "$SCIM" -H "$JSON" -H 'If-Match: W/"v1.0"' \
-d '{
"schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
"Operations": [
{ "op": "replace", "path": "active", "value": false }
]
}'{
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
"id": "usr_01M3PSWBPGS08FWV4NV7P9VNFN",
"userName": "pat@acme.example",
"active": false,
"meta": {
"resourceType": "User",
"created": "2026-09-29T14:47:03.000Z",
"lastModified": "2026-09-29T14:49:41.000Z",
"version": "W/\"v1.1\""
}
}If-Match with a stale version returns 412 and a SCIM error body. That is correct — re-read the user and re-apply.
#3d. Bulk, in one request
curl -sS -X POST "$BASE/Bulk" -H "$SCIM" -H "$JSON" -d '{
"schemas": ["urn:ietf:params:scim:api:messages:2.0:BulkRequest"],
"failOnErrors": 1,
"Operations": [
{ "method": "POST", "path": "/Users", "bulkId": "alex", "data": { "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"], "userName": "alex@acme.example", "name": { "givenName": "Alex", "familyName": "Chen" }, "emails": [{ "value": "alex@acme.example", "primary": true }], "active": true } },
{ "method": "POST", "path": "/Users", "bulkId": "robin", "data": { "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"], "userName": "robin@acme.example", "name": { "givenName": "Robin", "familyName": "Vega" }, "emails": [{ "value": "robin@acme.example", "primary": true }], "active": true } },
{ "method": "POST", "path": "/Groups", "bulkId": "g1", "data": { "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Group"], "displayName": "Support", "members": [{ "value": "alex" }, { "value": "robin" }] } }
]
}'{
"schemas": ["urn:ietf:params:scim:api:messages:2.0:BulkResponse"],
"Operations": [
{ "method": "POST", "bulkId": "alex", "version": "W/\"v1.0\"", "location": "/Users/usr_01M3PSWCNRG3H18C3A2AHBRYRZ", "status": "201" },
{ "method": "POST", "bulkId": "robin", "version": "W/\"v1.0\"", "location": "/Users/usr_01M3PSW0YRNEQQAP9T1JP9FC2Y", "status": "201" },
{ "method": "POST", "bulkId": "g1", "version": "W/\"v1.0\"", "location": "/Groups/grp_01M3PSVED0M9RJTYH5AC72C253", "status": "201" }
]
}Maximum 100 operations per Bulk request. Exceeding it returns 413 scim_bulk_exceeded. With failOnErrors: 1, the first failure aborts the batch and remaining operations are skipped.
#3e. Deprovision
curl -sS -X DELETE "$BASE/Users/usr_01M3PSWBPGS08FWV4NV7P9VNFN" -H "$SCIM" -i | head -1HTTP/2 204 No ContentDeprovisioning: sets status to suspended, revokes all sessions and refresh-token families for that user, emits dsync.user.deleted and user.suspended, and writes user.suspended to the audit log. Upstream polling with deprovision_upstream_removals: true performs the same action when a user disappears from the source directory.
#3f. What emits what
| Action | Webhook events | Audit action |
|---|---|---|
| Create user | dsync.user.created, user.created | user.created |
| Update user | dsync.user.updated, user.updated | user.updated |
| Deprovision | dsync.user.deleted, user.deleted, user.suspended | user.suspended |
| Create group | dsync.group.created | — |
| Update group members | dsync.group.updated | — |
| Delete group | dsync.group.deleted | — |
| Poll sync run | dsync.user.* per change | directory.sync_completed |
#4. SAML SP wiring into a real app
Goal: you are building an app that a customer's Okta/Entra IdP will federate into. ulex is the service provider; your app is the relying party.
{ "name": "ulex_get_saml_sp_metadata", "arguments": { "application_id": "app_01M3PSV7J8TBSPHG95CYSEX32B" } }{
"metadata_xml": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<EntityDescriptor xmlns=\"urn:oasis:names:tc:SAML:2.0:metadata\" entityID=\"https://ulexid.com/api/v1/connections/con_01M3PSVAG0QFJG99R0M5DXSR5A\">…</EntityDescriptor>",
"entity_id": "https://ulexid.com/api/v1/connections/con_01M3PSVAG0QFJG99R0M5DXSR5A",
"acs_url": "https://ulexid.com/api/v1/connections/con_01M3PSVAG0QFJG99R0M5DXSR5A/saml/acs",
"slo_url": "https://ulexid.com/api/v1/connections/con_01M3PSVAG0QFJG99R0M5DXSR5A/saml/slo"
}Configure the customer's IdP with:
| IdP field | Value |
|---|---|
| SSO URL | acs_url above (HTTP-Redirect binding) |
| Audience URI | entity_id above |
| ACS URL | acs_url above |
| Name ID format | urn:oasis:names:tc:SAML:2.0:nameid-format:persistent |
| Required Signed Assertions | yes |
| Signature algorithm | RSA-SHA256 |
Then register the upstream IdP with ulex:
{ "name": "ulex_create_connection", "arguments": {
"name": "Globex SAML",
"organization_id": "org_01M3PSVT404FMFWPN6QAMM2R4P",
"config": {
"strategy": "saml",
"saml": {
"entity_id": "https://globex.okta.com/app/exk9r2mz1hRtXQ2N5s0d7",
"sso_url": "https://globex.okta.com/app/exk9r2mz1hRtXQ2N5s0d7/sso/saml",
"slo_url": "https://globex.okta.com/app/exk9r2mz1hRtXQ2N5s0d7/slo/saml",
"x509_certificate": "MIIE1DCCA3CgAwIBAgIULSJ…",
"name_id_format": "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent",
"want_response_signed": true,
"want_assertion_signed": true,
"signature_validation": "strict",
"allowed_clock_skew_seconds": 120,
"name_id_transformations": "email",
"allow_create": true,
"allow_update": true,
"allow_link": true,
"group_attribute": "groups",
"groups_attribute": "groups",
"active_attribute": "active",
"active_value": "true",
"attribute_mapping": {
"email": "email",
"first_name": "firstName",
"last_name": "lastName",
"display_name": "displayName",
"job_title": "title",
"department": "department",
"external_id": "userId",
"groups": "groups"
}
}
}
} }Validate the certificate and fetch discovery before you cut traffic:
{ "name": "ulex_verify_connection", "arguments": { "connection_id": "con_01M3PSVY108K5TEHHQ82WN30YK" } }{
"valid": true,
"strategy": "saml",
"checks": [
{ "check": "entity_id present", "status": "passed", "detail": "https://acme.okta.com/app/exkxxxx/sso/saml/metadata" },
{ "check": "sso_url present", "status": "passed", "detail": "https://acme.okta.com/app/exkxxxx/sso/saml" },
{ "check": "certificate parses", "status": "passed", "detail": "pinned certificate yields a usable public key" },
{ "check": "name_id_format recognised", "status": "passed", "detail": "email" },
{ "check": "signature algorithm", "status": "passed", "detail": "rsa-sha256 — ulex verifies the algorithm the IdP names, it does not choose it" },
{ "check": "clock skew budget", "status": "passed", "detail": "120s" },
{ "check": "sso_url reachable", "status": "passed", "detail": "HTTP 200" }
]
}A status of skipped means the check does not apply to that strategy. It is not a pass.
Then { "name": "ulex_activate_connection", "arguments": { "connection_id": "con_01M3PSVY108K5TEHHQ82WN30YK" } }.
Full walkthrough including IdP-initiated login and SLO: SAML SP integration.
#5. Testing an SSO flow headlessly
Goal: a regression test that covers success, MFA challenge, wrong password, suspended user, and revoked session — with no browser and no fixtures to keep in sync.
// sso.e2e.ts
import { describe, it, expect } from "vitest";
const APP = "app_01M3PSV7J8TBSPHG95CYSEX32B";
const ORG = "org_01M3PSV8HGTKQFCAYF9GDWGN3C";
const DANA = "dana@acme.example";
const PKCE = {
verifier: "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk",
challenge: "E9MelhoQ2YvW96fl8sW7aTtZbGd0mY6Xl0e8Q1sCk",
} as const;
async function login(email: string) {
return tools.ulex_simulate_login({
application_id: APP,
organization_id: ORG,
email,
response_type: "code",
return_pkce: true,
});
}
async function tokenFor(email: string) {
const grant = await login(email);
expect(grant.outcome).toBe("success");
const tokens = await tools.ulex_exchange_code_for_tokens({
application_id: APP,
code: grant.code,
redirect_uri: "https://app.example.com/auth/callback",
code_verifier: PKCE.verifier,
});
return tokens;
}
describe("SSO", () => {
it("logs a seeded user in and issues a valid token", async () => {
const tokens = await tokenFor(DANA);
const info = await tools.ulex_introspect_token({ token: tokens.access_token });
expect(info.active).toBe(true);
expect(info.sub).toBe("usr_01M3PSV9GRT8GQGEG686AR1W9S");
expect(info.org_id).toBe(ORG);
});
it("rejects an unknown user", async () => {
const attempt = await login("nobody@acme.example");
expect(attempt.outcome).toBe("failure");
expect(attempt.error.code).toBe("user_not_found");
});
it("challenges for MFA and carries amr=mfa once satisfied", async () => {
await tools.ulex_simulate_mfa({ mode: "challenge", email: DANA, method: "totp" });
const challenged = await login(DANA);
expect(challenged.outcome).toBe("challenge");
expect(challenged.error.code).toBe("mfa_required");
await tools.ulex_simulate_mfa({ mode: "satisfy", email: DANA });
const tokens = await tokenFor(DANA);
const claims = JSON.parse(Buffer.from(tokens.access_token.split(".")[1]!, "base64url").toString());
expect(claims.amr).toContain("mfa");
});
it("refuses a suspended user", async () => {
await tools.ulex_suspend_user({ user_id: "usr_01M3PSV9GRT8GQGEG686AR1W9S", reason: "e2e" });
const attempt = await login(DANA);
expect(attempt.error.code).toBe("access_denied");
await tools.ulex_unsuspend_user({ user_id: "usr_01M3PSV9GRT8GQGEG686AR1W9S" });
});
it("invalidates the token when the session is revoked", async () => {
const tokens = await tokenFor(DANA);
expect((await tools.ulex_introspect_token({ token: tokens.access_token })).active).toBe(true);
await tools.ulex_revoke_tokens({ token: tokens.refresh_token, token_type_hint: "refresh_token" });
expect((await tools.ulex_introspect_token({ token: tokens.access_token })).active).toBe(false);
});
it("never lets a code be exchanged twice", async () => {
const grant = await login(DANA);
const args = {
application_id: APP,
code: grant.code,
redirect_uri: "https://app.example.com/auth/callback",
code_verifier: PKCE.verifier,
};
await tools.ulex_exchange_code_for_tokens(args);
const second = await tools.ulex_exchange_code_for_tokens(args);
expect(second.error.code).toBe("invalid_grant");
expect(second.error.retryable).toBe(false); // re-login, do not retry
});
});Run it against a non-HIPAA tenant with allow_mocks: true or the local in-memory server (npx @ulexid/mcp-server). Set ULEX_API_KEY in the environment; never inline it. For isolation, call ulex_reset_simulation in a beforeEach — it clears armed failures and challenges without deleting data.
#6. Webhook receiver with signature verification
Goal: a receiver that is safe: constant-time HMAC comparison, timestamp freshness, replay protection, idempotent by event_id, and it acknowledges in under 5 seconds.
// webhook-receiver.ts
import { createHmac, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";
const SECRET = process.env.ULEX_WEBHOOK_SECRET!; // whsec_3Kq9Xa2mB7yLt4NxZ1pRc6HdE0sJg3AuV8
const TOLERANCE_SECONDS = 300;
function verify(rawBody: Buffer, header: string | undefined): boolean {
if (!header) return false;
const parts = Object.fromEntries(
header.split(",").map((kv) => {
const idx = kv.indexOf("=");
return [kv.slice(0, idx).trim(), kv.slice(idx + 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);
}
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;
data?: Record<string, unknown>;
}
/** Dedupe by event_id. Unbounded in a demo; use a real store in production. */
const seen = new Set<string>();
const MAX_SEEN = 10_000;
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 the exact bytes, not a re-serialised object
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;
if (seen.has(event.event_id)) {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ received: true, duplicate: true }));
return;
}
seen.add(event.event_id);
if (seen.size > MAX_SEEN) seen.delete(seen.values().next().value as string);
// Acknowledge first, process after. ulex gives you 5 seconds before the
// first retry, and a fast 200 turns a 3-attempt storm into one delivery.
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ received: true }));
void handle(event);
});
});
async function handle(event: UlexEvent): Promise<void> {
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 ?? "(unknown)"} (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}`);
}
}
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"));Test it without waiting for a real event:
{ "name": "ulex_send_test_webhook", "arguments": { "webhook_id": "whk_01M3PSVK981SXWGKG9JXHC1P0Y", "event": "user.created" } }Full reference, including the retry schedule and auto-disable threshold: Webhooks.
#7. Rotating credentials without downtime
Two rotations matter: the application client secret, and the tenant signing keys.
#7a. Client secret
{ "name": "ulex_rotate_application_secret", "arguments": {
"application_id": "app_01M3PSV7J8TBSPHG95CYSEX32B",
"grace_period_seconds": 86400
} }{
"client_id": "client_01M3PSV7J8TBSPHG95CYSEX32B",
"client_secret": "cs_Tn4Wv8Kp2LmQ6Rb9Yc3Xd7Fs1Hg0Ja5E",
"previous_secret_expires_at": "2026-09-30T14:55:00.000Z",
"grace_period_seconds": 86400
}The safe sequence. Both secrets are valid for the whole grace window, so there is a window in which to do anything:
t+0s rotate -> new_secret
t+0s write new_secret to secret store
t+0s restart / reload every consumer
t+0s make one real token call with new_secret <- the smoke test
t+0s if that fails: revert to old_secret, investigate, do not proceed
t+10m observe error rate, token endpoint 401 count
t+24h grace expires, old secret dies automatically. Nothing else to do.The old secret never needs an explicit delete; it expires. There is no rotation with no grace period, by design.
#7b. Signing keys
{ "name": "ulex_rotate_signing_keys", "arguments": { "purpose": "access_token", "grace_period_seconds": 604800 } }Signing-key rotation is the dangerous one, because it changes what your resource servers must trust.
1. read current JWKS GET /oauth2/keys -> key_01M3PSVJA0YP2WDPM2RDR15MGH (RS256)
2. rotate POST /tenants/current/rotate-signing-keys
3. read JWKS again -> TWO keys: the new one (state active) and the old (state retiring)
4. every JWKS cache has a TTL. Wait TTL + margin (2x the longest cache you have)
before you assume the old kid is gone from every consumer.
5. only then, at grace expiry, is the old key revoked automatically.If your resource server pins a single kid instead of caching the whole JWKS, rotation breaks it. Fix the cache before you rotate. A JWKS cache with a 15-minute TTL and a kid-keyed map is the correct shape.
// Minimal correct JWKS cache.
const cache = new Map<string, { key: JsonWebKey; expiresAt: number }>();
const JWKS_TTL_MS = 15 * 60_000;
const CLOCK_SKEW_MS = 30_000;
async function getKey(kid: string): Promise<JsonWebKey> {
const hit = cache.get(kid);
if (hit && hit.expiresAt > Date.now()) return hit.key;
const res = await fetch("https://ulexid.com/api/v1/oauth2/keys", {
headers: { Authorization: `Bearer ${process.env.ULEX_API_KEY!}` },
});
const jwks = (await res.json()) as { keys: JsonWebKey[] };
for (const key of jwks.keys) {
cache.set(key.kid!, { key, expiresAt: Date.now() + JWKS_TTL_MS });
}
const found = cache.get(kid);
if (!found) throw new Error(`unknown kid ${kid}; JWKS has ${[...cache.keys()].join(", ")}`);
return found.key;
}
export function isExpired(exp: number): boolean {
return exp * 1000 <= Date.now() - CLOCK_SKEW_MS;
}#8. Auditing your own actions
Goal: prove what you did, from the record, not from memory. This is the deliverable format.
Send a correlation id on every call and it lands in the audit log:
curl -sS -X POST "$BASE/simulator/authenticate" \
-H "Authorization: Bearer $ULEX_API_KEY" \
-H "X-Ulex-Correlation-Id: onboard-acme-2026-09-29" \
-H "X-Ulex-Request-Id: req_01M3PSW9R0175NAW62NYR403R8" \
-H "Content-Type: application/json" \
-d '{"application_id":"app_01M3PSV7J8TBSPHG95CYSEX32B","email":"dana@acme.example","connection_id":"con_01M3PSVAG0QFJG99R0M5DXSR5A"}'Both headers are echoed on the response and both are stored on every audit_event they touch.
Then build the report:
export async function reportOnOwnWork(correlationId: string) {
const events: AuditEvent[] = [];
let cursor: string | undefined;
do {
const page = await tools.ulex_search_audit_logs({
correlation_id: correlationId,
limit: 200,
order: "asc",
starting_after: cursor,
});
events.push(...page.data);
cursor = page.has_more ? (page.next_cursor ?? undefined) : undefined;
} while (cursor);
const failures = events.filter((e) => e.outcome !== "success");
return {
total: events.length,
byAction: tally(events, (e) => e.action),
failures: failures.map((e) => ({ id: e.id, action: e.action, code: e.error_code, ts: e.timestamp })),
chainHead: events.at(-1)?.chain.entry_hash,
};
}Report shape — this is the format to emit, every time:
| # | timestamp (UTC) | action | outcome | actor_type | target | request_id |
| 1 | 14:42:05.000 | application.created | success | agent | app_01M3PSV7J8TBSPHG95CYSEX32B | req_01M3PSW9R0175NAW62NYR403R8 |
| 2 | 14:42:06.000 | organization.created | success | agent | org_01M3PSV8HGTKQFCAYF9GDWGN3C | req_01M3PSW9R0175NAW62NYR403R8 |
| 3 | 14:42:08.000 | connection.activated | success | agent | con_01M3PSVAG0QFJG99R0M5DXSR5A | req_01M3PSW9R0175NAW62NYR403R8 |
| 4 | 14:45:12.000 | authentication.succeeded | success | user | app_01M3PSV7J8TBSPHG95CYSEX32B | req_01M3PSW9R0175NAW62NYR403R8 |
4 events, 0 failures. Chain head sha256:7d9f1b3a… Domain acme.example verified 14:42:10.Chain verification, if you need to prove the log was not edited. Order by the links, not by the order the rows arrive in — there is no sequence field, because a sequence number cannot order two entries written in the same second and trusting the arrival order reports intact chains as broken:
export function verifyChain(events: AuditEvent[]): { valid: boolean; orphanId: string | null } {
const byHash = new Map(events.map((e) => [e.entry_hash, e]));
const linkedTo = new Set(events.map((e) => e.previous_hash).filter((h) => h !== null));
const reachable = new Set<string>();
// Walk back from the tip — the entry nothing links to.
for (const tip of events.filter((e) => !linkedTo.has(e.entry_hash))) {
let cur: AuditEvent | undefined = tip;
while (cur && !reachable.has(cur.entry_hash)) {
reachable.add(cur.entry_hash);
cur = cur.previous_hash ? byHash.get(cur.previous_hash) : undefined;
}
}
const orphan = events.find((e) => !reachable.has(e.entry_hash));
return { valid: !orphan, orphanId: orphan?.id ?? null };
}That checks reachability. Reaching the full verdict also needs each entry's own hash recomputed and the chain's order to agree with the clock — which is what ulex_verify_audit_chain does, and what it reports as hash_mismatch, missing_predecessor, broken_link or unverifiable.
Exports for evidence: GET /audit-events/export?format=ndjson&since=… streams the whole chain; format=csv flattens it for a spreadsheet.
#9. Migrating from simulator to a real IdP
Goal: move an org off mock_sso and onto a real okta_oidc / entra_oidc / saml connection with no app changes and no downtime.
{ "name": "ulex_create_connection", "arguments": {
"name": "Globex Entra (shadow)",
"organization_id": "org_01M3PSVT404FMFWPN6QAMM2R4P",
"config": { "strategy": "entra_oidc", "oidc": {
"issuer": "https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0",
"client_id": "9f3c1a7b-2d4e-6f8a-0b2c-4d6e8f0a2b4c",
"client_secret": "env:ULEX_TEST_ENTRA_SECRET",
"scopes": ["openid", "profile", "email"],
"allowed_domains": ["globex.example"]
} }
} }{ "name": "ulex_verify_connection", "arguments": { "connection_id": "con_01M3PSVZ088BWS19NX9BRWWRQ9" } }If valid is false, stop here. Nothing downstream works.
State stays draft. Your application still routes through the mock_sso connection, so nothing changes for users.
{ "name": "ulex_get_connection", "arguments": { "connection_id": "con_01M3PSVAG0QFJG99R0M5DXSR5A" } }Compare the normalized profile that mock_sso produced against what the real IdP will produce. Fix attribute_mapping until they match. In practice the three things that break are:
external_id— mock uses the email, the real IdP uses an opaque id. Anything you keyed onexternal_idwill change.display_name— mock builds "First Last", Entra returns anameclaim that may already be formatted.groups— mock seeds a flat array of strings; Entra returns group object ids, not display names. Map through a lookup table you control.
{ "name": "ulex_activate_connection", "arguments": { "connection_id": "con_01M3PSVZ088BWS19NX9BRWWRQ9" } }{ "name": "ulex_update_organization", "arguments": {
"organization_id": "org_01M3PSVT404FMFWPN6QAMM2R4P",
"connection_id": "con_01M3PSVZ088BWS19NX9BRWWRQ9",
"default_connection_id": "con_01M3PSVZ088BWS19NX9BRWWRQ9",
"sso_only": true
} }This configures enterprise single sign-on on the org. sso_only: true enforces that members must authenticate through an enterprise SSO connection allowed for this org, refusing direct password sign-in.
{ "name": "ulex_search_audit_logs", "arguments": {
"connection_id": "con_01M3PSVZ088BWS19NX9BRWWRQ9",
"since": "2026-09-29T00:00:00.000Z",
"limit": 200
} }Wait until you see authentication.succeeded on the new connection and zero authentication.failed across a full business day. Then:
{ "name": "ulex_delete_connection", "arguments": { "connection_id": "con_01M3PSVAG0QFJG99R0M5DXSR5A" } }Deleting the mock_sso connection is a soft delete and is reversible for 30 days, but every session that was created through it stays valid until its idle_expires_at. If you need those gone now, call ulex_reset_simulation or revoke the sessions explicitly. Do not assume deleting a connection kills sessions.
#The one-page diff table
| Concern | mock_sso | Real strategy |
|---|---|---|
| Setup | none | IdP app registration, redirect URIs, cert or client secret |
external_id | the email | opaque, IdP-specific |
| Groups | seeded strings | group object ids, usually |
| Certificate expiry | never | watch x509_certificate_expires_at, 30-day warning |
| Network dependency | none | ulex → IdP on every login; handle upstream_timeout |
| Failure modes | force_failure only | everything |
| Audit | same | same |
| Tokens, sessions, webhooks | identical | identical |
The last row is the point: everything downstream of the connection is identical, which is why the migration is a connection swap and not a rewrite.
See SAML SP integration and OIDC client integration for full protocol cutover details.