diff --git a/.changeset/signed-webhooks.md b/.changeset/signed-webhooks.md new file mode 100644 index 00000000..294a9700 --- /dev/null +++ b/.changeset/signed-webhooks.md @@ -0,0 +1,12 @@ +--- +'seamless-auth-api': minor +--- + +Add signed, retried webhooks (ADR 0005, #418). + +- Admin API under `/admin/webhooks` and `/admin/webhook-deliveries`: create, update, disable and delete endpoints, rotate the signing secret (the old one signs beside the new one for 24 hours), send a test event, list deliveries with a dead letter filter, and redeliver. Every write takes step-up and is audited. +- Payloads are signed with the Standard Webhooks scheme (`webhook-id`, `webhook-timestamp`, `webhook-signature`), so any Standard Webhooks verifier checks them. +- Events are built from committed audit rows, retried eight times over just under 42 hours, then dead-lettered. An endpoint that answers 410, or fails every delivery for three days, is disabled. Deliveries for a disabled endpoint are held, and turning it back on sends what it missed, up to the 30 days deliveries are kept. +- Every callout to an adopter URL refuses link-local, multicast and the API's own host, never follows redirects, and in production refuses private addresses unless the host is listed in the new `CALLOUT_PRIVATE_HOSTS`. +- New env var `CALLOUT_SECRET_ENCRYPTION_KEY` encrypts stored signing secrets. Production requires it once a webhook exists. +- New audit event `session_created`, written once per completed sign-in. Deleting a passkey is now audited as `credentials_deleted`, and passkey registration names the credential. diff --git a/adapter-manifest.json b/adapter-manifest.json index 68a07d00..923aa4d6 100644 --- a/adapter-manifest.json +++ b/adapter-manifest.json @@ -106,6 +106,20 @@ "credential": "access" }, { "method": "POST", "path": "/admin/users/import", "credential": "access" }, + { "method": "GET", "path": "/admin/webhook-deliveries", "credential": "access" }, + { "method": "GET", "path": "/admin/webhook-deliveries/{deliveryId}", "credential": "access" }, + { + "method": "POST", + "path": "/admin/webhook-deliveries/{deliveryId}/redeliver", + "credential": "access" + }, + { "method": "GET", "path": "/admin/webhooks", "credential": "access" }, + { "method": "POST", "path": "/admin/webhooks", "credential": "access" }, + { "method": "DELETE", "path": "/admin/webhooks/{id}", "credential": "access" }, + { "method": "GET", "path": "/admin/webhooks/{id}", "credential": "access" }, + { "method": "PATCH", "path": "/admin/webhooks/{id}", "credential": "access" }, + { "method": "POST", "path": "/admin/webhooks/{id}/secret", "credential": "access" }, + { "method": "POST", "path": "/admin/webhooks/{id}/test", "credential": "access" }, { "method": "GET", "path": "/internal/auth-events/grouped", "credential": "access" }, { "method": "GET", "path": "/internal/auth-events/login-stats", "credential": "access" }, { "method": "GET", "path": "/internal/auth-events/summary", "credential": "access" }, diff --git a/docs/adr/0005-extensibility-callouts.md b/docs/adr/0005-extensibility-callouts.md new file mode 100644 index 00000000..ab8f8364 --- /dev/null +++ b/docs/adr/0005-extensibility-callouts.md @@ -0,0 +1,122 @@ +# ADR 0005: Webhooks, login hooks, custom claims and SIEM streaming + +- **Status:** Accepted +- **Date:** 2026-11-07 +- **Issues:** #417, #418, #419, #420, seamless-auth-types#146. Consumers follow in seamless-auth-oidc-provider#47, seamless-auth-server#269, seamless-auth-admin-dashboard#335 and #336, and seamless-cli#343. + +## Context + +Events are pull-only, and an app cannot change what a sign-in does or what a token carries without forking. Each of the four features makes the API call a URL an adopter chose, so they share one set of rules for reaching it. + +What already exists to build on: + +- `providerFetch` resolves DNS inside the socket's `lookup`, so the address checked is the address connected to. It refuses link-local addresses in every mode, decodes NAT64, 6to4 and IPv4-mapped forms, and never follows redirects. +- Every sign-in completes in `issueSessionAndRespond`, and every first-party token is minted in `mintAccessToken` (ADR 0004). +- `auth_events` is hash chained by a trigger, and the `seamless-auth-events/1` export carries the exact text hashed. +- TOTP seeds are AES-256-GCM encrypted under an env key. + +## Decisions + +### E1. Signatures follow Standard Webhooks + +Webhooks and login hook calls are signed with the [Standard Webhooks](https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md) scheme: headers `webhook-id`, `webhook-timestamp` and `webhook-signature`, HMAC-SHA256 over `${id}.${timestamp}.${body}`, sent as `v1,`. Secrets are `whsec_` and base64 of 32 random bytes. + +- Rotating keeps the old secret signing beside the new one for 24 hours, so the header carries two signatures and a receiver holding either verifies. Only two secrets ever sign. +- Receivers reject a timestamp more than 300 seconds from their clock and dedupe on `webhook-id`. +- Receivers in any language can use an existing verifier. Asymmetric `v1a` is left for later; it would be another signature in the same header. + +### E2. Events come from the committed audit log + +A dispatcher reads `auth_events` past a cursor (`event_dispatch_cursors`) by `seq` and turns matching rows into deliveries. An event is sent only once its row has committed, nothing is lost between happening and being queued, and the SIEM stream (#420) reads the same rows with the same hashes. + +The chain trigger updates the chain head row on every insert and holds that lock until commit, so committed rows always form a gapless prefix of `seq`: the cursor cannot step past a row that is still to commit. On first run the cursor starts at the newest row, so turning webhooks on does not replay history. Replicas take turns through an advisory lock. Delivery workers claim due rows with `FOR UPDATE SKIP LOCKED` and lease them past the request timeout, so a replica that dies mid-send leaves the delivery due again shortly after. The loop polls once a second. + +### E3. A small, versioned event catalog + +| Webhook type | From audit types | +| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `user.created` | `user_created` | +| `user.deleted` | `user_deleted` | +| `user.signed_in` | `session_created` | +| `user.recovered` | `account_recovery_completed` | +| `session.revoked` | `logout_success`, `admin_session_revoked`, `session_evicted`, `oidc_session_revoked` | +| `credential.added` | `registration_success` naming a passkey, `totp_enrollment_success`, `recovery_codes_generated` | +| `credential.removed` | `credentials_deleted` naming a passkey, `totp_disabled` | +| `organization.member_added` / `_updated` / `_removed` | `organization_member_*` | + +`webhook.test` is sent only by the test endpoint. The mapping is one table in `webhookCatalog.ts`, pinned by a test, so a new audit type reaches no receiver until it is added there. + +```json +{ + "id": "delivery uuid, the same as webhook-id", + "type": "user.signed_in", + "version": 1, + "timestamp": "when the event happened", + "data": { "userId": "...", "sessionId": "...", "method": "passkey", "organizationId": null } +} +``` + +- `data` carries identifiers and the few fields a receiver acts on. `user.created` also carries the email or phone the account was made with, read from the user at dispatch. No IP address, user agent or free-form metadata: those go to the SIEM. +- Delivery is at least once and unordered. + +### E4. Retries, dead letters and storage + +- Success is a 2xx within 15 seconds. A redirect is a failure and is not followed. +- Attempts at 0 s, then 5 s, 5 min, 30 min, 2 h, 5 h, 10 h and 24 h after the previous one, with up to 10% jitter: eight attempts, dead just under 42 hours after the event. A longer `Retry-After` is honored, up to 24 hours. +- `410 Gone` disables the endpoint. So do three days in which every delivery failed. Both write `webhook_endpoint_disabled`. +- A delivery stores the exact body sent, so a retry or redelivery sends the same bytes. Responses are read for the status alone, and only the status and a coarse failure reason are kept. Deliveries are pruned after 30 days. +- Redeliver is one attempt now with the same `webhook-id` and body and a fresh timestamp and signature. +- A disabled endpoint still gets its deliveries, held with no attempt due, and a delivery already queued when its endpoint is disabled is held the same way. Turning the endpoint back on releases everything held, so it catches up on what happened while it was off instead of losing it. Deliveries are pruned after 30 days, so that is how far a catch-up reaches. A dead delivery stays dead; redeliver sends it. Decided by Brandon on 2026-11-07, after the webhooks guide found that events during a disable were never queued. + +### E5. Login hooks + +- `post_login` runs once the factor is proven and before the session exists. It may allow or deny. It cannot add claims. +- `pre_token` runs when a token is minted for a new session and on organization switch. It may add claims or deny. It is not called on refresh: its claims are kept on the session, so refresh never waits on an adopter's server. +- One hook per trigger. Timeout 2 seconds by default, 5 at most, one attempt. +- Failure mode per hook, `closed` by default. A timeout, a non-2xx, a body that does not parse, or claims over the budget fail the sign-in when closed and are ignored when open. Every invocation is audited. +- Break-glass sign-in and recovery sessions never call a hook, so a hook that is down cannot lock out the administrator who would fix it. +- The call carries the user, method, organization, OpenID client, IP and user agent, never a token, code or secret. `reason` in the answer is audited and not shown; `userMessage` (200 characters) is. + +### E6. Custom claims + +Sources, lowest precedence first: an instance role, an organization role (while that organization is active), an OpenID Provider client (provider tokens only), then the `pre_token` hook. Values are literal JSON up to depth 3, with names matching `^[a-z][a-z0-9_]{0,63}$`. + +Reserved, refused when written and stripped (and audited) when a hook returns them: JWT registered claims, OpenID and OAuth protocol claims including `act` and `may_act`, Seamless's own claims, the OpenID standard identity claims (so no source can assert an email address the user never proved), and any name starting `seamless_` or `org_`. The list lives in `@seamless-auth/types/customClaim/reserved`, shared with the provider. + +All custom claims together get 1 KiB serialized, on top of ADR 0004's permission budget. Unlike permissions they are never dropped: a static set over the budget is refused when written, and a hook over it has failed. + +### E7. SIEM streaming + +- OTLP/HTTP with JSON encoding to `/v1/logs`, and syslog (RFC 5424) over TLS (RFC 5425) with octet counting. Plain TCP only outside production, never UDP. +- Every record carries the event's `seamless-auth-events/1` line, with `seq`, `prevHash`, `hash` and `payload`, so the chain verifies downstream as an export does. +- Each sink has its own cursor and retries until its destination takes the events, backing off to one minute. There is no dead letter: a sink falls behind and reports its lag. +- Credentials are never stored. A sink names env vars ending `_AUDIT_SINK_SECRET`, the same pattern OAuth providers use. + +### E8. Every callout follows the same reachability rules + +`calloutTransport.ts` serves webhooks, hooks and sinks: + +- `https` only in production, no userinfo, never the API's own issuer host. +- DNS resolves inside the socket's `lookup`, and every address a name resolves to must be allowed, which defeats rebinding. +- Link-local, unspecified, multicast and broadcast addresses are never reachable, in any mode, for any host. +- Other private and loopback addresses are refused in production unless the host is listed in `CALLOUT_PRIVATE_HOSTS`. It is an env var, so nothing written through the API can widen it, and it is separate from `OAUTH_PROVIDER_PRIVATE_HOSTS`, so allowing an internal hook service does not also allow it as an identity provider. +- Redirects are never followed. Responses are capped at 64 KiB. The deadline covers the whole request, so a destination that trickles bytes cannot hold a sign-in open. +- URLs are checked when written and again at connect time. +- Failures are reported as `refused`, `timed_out`, `connection_failed`, `http_status`, `invalid_response` or `too_large`, never with the resolved address or the socket's error text, so the delivery log cannot be used to map the internal network. + +### E9. Signing secrets are encrypted at rest + +They must be read back to sign, so they cannot be hashed. They are AES-256-GCM encrypted under `CALLOUT_SECRET_ENCRYPTION_KEY`, which production requires once a webhook or hook exists, and creating one is refused without it. A secret is shown once, on create and on rotate. + +## Found while building + +- `login_success` is written when `/login` resolves which methods an identifier may use, before any factor is proven, so it cannot be the source of `user.signed_in`. No event recorded that a session was created. `issueSessionAndRespond` now writes `session_created`, with the method and organization. +- Deleting a passkey (`DELETE /users/credentials`) wrote no audit event. It now writes `credentials_deleted` naming the passkey. Reproducing test first. +- Passkey registration and account registration both write `registration_success`. The passkey path now names the credential in metadata, which is how the catalog tells them apart. +- `organization_member_updated` recorded only what was added and removed. It now records the roles after the change too, which the webhook carries. + +## Consequences + +- No `system_config` key is added: every setting is a table behind admin routes with step-up on every write, so the CLI's writable keys do not change. +- Webhooks are at least once and unordered, which the guide (seamless-auth-docs#153) states, along with the retry schedule and dead letters. +- `pre_token` claims are as fresh as the session, not the token. The Auth0 mapping in seamless-auth-docs#154 has to say so. diff --git a/docs/configuration.md b/docs/configuration.md index 9217514e..0f81d507 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -114,15 +114,17 @@ then daily, and each run also logs the audit chain head as an external anchor. S ### Service tokens and secrets -| Variable | Required | Default | Notes | -| ------------------------------ | ------------------------------------ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `SEAMLESS_SERVICE_TOKEN` | Yes | - | Trusted server-adapter and internal bearer secret. No other secret falls back to it. | -| `API_SERVICE_TOKEN` | No | - | Supported fallback name for `SEAMLESS_SERVICE_TOKEN`. Used only when `SEAMLESS_SERVICE_TOKEN` is unset, with an info notice at boot. Setting both to different values stops the server at boot. | -| `REFRESH_TOKEN_LOOKUP_SECRET` | Production | development-only value | HMAC key for indexed refresh-token lookup fingerprints. Always required in production. | -| `TOTP_SECRET_ENCRYPTION_KEY` | Production, once TOTP is used | development-only value | Encrypts stored TOTP secrets (hashed with SHA-256 to derive the key, so any high-entropy value works). Production refuses to start while any TOTP credential exists without it, and `POST /totp/enroll/start` answers `409 secret_required` until it is set. | -| `OAUTH_STATE_SECRET` | Production, once OAuth is configured | development-only value | Signs OAuth state. Production refuses to start with a provider configured and no value, and adding a provider answers `409 secret_required` until it is set. | -| `DECOY_SUBJECT_SECRET` | Production | development-only value | HMAC key the decoy pre-auth subjects on `POST /login` derive from. Always required in production. Rotating it re-maps which subject an unknown identifier gets, which is harmless: decoys are stateless and pre-auth tokens live five minutes. | -| `OAUTH_PROVIDER_PRIVATE_HOSTS` | No | - | Comma-separated OAuth provider hosts allowed to resolve to private or loopback addresses in production, for an on-premises IdP. Other provider hosts must resolve to public addresses. Link-local is always refused. | +| Variable | Required | Default | Notes | +| ------------------------------- | ------------------------------------ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `SEAMLESS_SERVICE_TOKEN` | Yes | - | Trusted server-adapter and internal bearer secret. No other secret falls back to it. | +| `API_SERVICE_TOKEN` | No | - | Supported fallback name for `SEAMLESS_SERVICE_TOKEN`. Used only when `SEAMLESS_SERVICE_TOKEN` is unset, with an info notice at boot. Setting both to different values stops the server at boot. | +| `REFRESH_TOKEN_LOOKUP_SECRET` | Production | development-only value | HMAC key for indexed refresh-token lookup fingerprints. Always required in production. | +| `TOTP_SECRET_ENCRYPTION_KEY` | Production, once TOTP is used | development-only value | Encrypts stored TOTP secrets (hashed with SHA-256 to derive the key, so any high-entropy value works). Production refuses to start while any TOTP credential exists without it, and `POST /totp/enroll/start` answers `409 secret_required` until it is set. | +| `OAUTH_STATE_SECRET` | Production, once OAuth is configured | development-only value | Signs OAuth state. Production refuses to start with a provider configured and no value, and adding a provider answers `409 secret_required` until it is set. | +| `DECOY_SUBJECT_SECRET` | Production | development-only value | HMAC key the decoy pre-auth subjects on `POST /login` derive from. Always required in production. Rotating it re-maps which subject an unknown identifier gets, which is harmless: decoys are stateless and pre-auth tokens live five minutes. | +| `OAUTH_PROVIDER_PRIVATE_HOSTS` | No | - | Comma-separated OAuth provider hosts allowed to resolve to private or loopback addresses in production, for an on-premises IdP. Other provider hosts must resolve to public addresses. Link-local is always refused. | +| `CALLOUT_SECRET_ENCRYPTION_KEY` | Production, once a webhook exists | development-only value | Encrypts stored webhook signing secrets (hashed with SHA-256 to derive the key). Production refuses to start while any webhook exists without it, and creating one answers `409` until it is set. | +| `CALLOUT_PRIVATE_HOSTS` | No | - | Comma-separated webhook hosts allowed to resolve to private or loopback addresses in production, for a receiver inside your own network. Separate from `OAUTH_PROVIDER_PRIVATE_HOSTS`. Link-local, multicast and the unspecified address are always refused, and a webhook can never point at the API's own issuer host. | > None of these falls back to the service token. Development (any `NODE_ENV` other than > `production`) uses a fixed development-only value for each unset one, with a warning. See diff --git a/docs/production-operations.md b/docs/production-operations.md index 74d102c3..d7e05f5f 100644 --- a/docs/production-operations.md +++ b/docs/production-operations.md @@ -98,6 +98,7 @@ Production deployments should define: - `REFRESH_TOKEN_LOOKUP_SECRET` - `TOTP_SECRET_ENCRYPTION_KEY` - `OAUTH_STATE_SECRET` +- `CALLOUT_SECRET_ENCRYPTION_KEY`, once a webhook exists - `SEAMLESS_JWKS_ACTIVE_KID` - `SEAMLESS_JWKS_KEY__PRIVATE` - `SEAMLESS_JWKS_PUBLIC_KEYS` diff --git a/openapi.json b/openapi.json index 49f436fa..0e3b8da3 100644 --- a/openapi.json +++ b/openapi.json @@ -7293,7 +7293,14 @@ "webauthn_login_success", "webauthn_registration_challenge", "webauthn_registration_failed", - "webauthn_registration_suspicious" + "webauthn_registration_suspicious", + "admin_webhook_created", + "admin_webhook_deleted", + "admin_webhook_redelivered", + "admin_webhook_secret_rotated", + "admin_webhook_updated", + "session_created", + "webhook_endpoint_disabled" ] }, { "type": "string" }, @@ -7432,7 +7439,14 @@ "webauthn_login_success", "webauthn_registration_challenge", "webauthn_registration_failed", - "webauthn_registration_suspicious" + "webauthn_registration_suspicious", + "admin_webhook_created", + "admin_webhook_deleted", + "admin_webhook_redelivered", + "admin_webhook_secret_rotated", + "admin_webhook_updated", + "session_created", + "webhook_endpoint_disabled" ] }, { "type": "string" } @@ -14886,6 +14900,7 @@ "session_revoked", "subject_mismatch", "auth_context_mismatch", + "claims_mismatch", "issuer_mismatch", "audience_mismatch", "client_inactive", @@ -14928,6 +14943,7 @@ "session_revoked", "subject_mismatch", "auth_context_mismatch", + "claims_mismatch", "issuer_mismatch", "audience_mismatch", "client_inactive", @@ -15619,7 +15635,12 @@ "phone_number": "string", "phone_number_verified": true, "roles": [null], - "org_id": "string" + "org_id": "string", + "permissions": [null], + "permissions_omitted": null, + "org_roles": [null], + "org_permissions": [null], + "customClaims": null }, "schema": { "type": "object", @@ -15630,7 +15651,177 @@ "phone_number": { "type": "string" }, "phone_number_verified": { "type": "boolean" }, "roles": { "type": "array", "items": { "type": "string" } }, - "org_id": { "type": "string", "nullable": true } + "org_id": { "type": "string", "nullable": true }, + "permissions": { "type": "array", "items": { "type": "string" } }, + "permissions_omitted": { "type": "boolean", "enum": [true] }, + "org_roles": { "type": "array", "items": { "type": "string" } }, + "org_permissions": { "type": "array", "items": { "type": "string" } }, + "customClaims": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + } + ] + } + } + ] + }, + "default": {} + } }, "required": ["sub", "roles", "org_id"] } @@ -32748,6 +32939,2686 @@ } } } + }, + "/admin/webhooks": { + "get": { + "summary": "List webhook endpoints", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { "endpoints": [null] }, + "schema": { + "type": "object", + "properties": { + "endpoints": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "url": { "type": "string" }, + "description": { "type": "string", "nullable": true }, + "eventTypes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + } + }, + "enabled": { "type": "boolean" }, + "disabledReason": { + "type": "string", + "nullable": true, + "enum": ["gone", "failing", "manual", null] + }, + "version": { "type": "number", "enum": [1] }, + "previousSecretExpiresAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "createdAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "updatedAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": [ + "id", + "url", + "description", + "eventTypes", + "enabled", + "disabledReason", + "version", + "previousSecretExpiresAt", + "createdAt", + "updatedAt" + ] + } + } + }, + "required": ["endpoints"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + }, + "post": { + "summary": "Create a webhook endpoint", + "description": "Returns the signing secret once. It cannot be read back.", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "url": { "type": "string", "maxLength": 2048 }, + "description": { "type": "string", "minLength": 1, "maxLength": 500 }, + "eventTypes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + }, + "minItems": 1 + }, + "enabled": { "type": "boolean" } + }, + "required": ["url", "eventTypes"] + } + } + } + }, + "responses": { + "201": { + "description": "HTTP 201", + "content": { + "application/json": { + "example": { + "endpoint": { + "id": "string", + "url": "string", + "description": "string", + "eventTypes": [null], + "enabled": true, + "disabledReason": null, + "version": null, + "previousSecretExpiresAt": null, + "createdAt": null, + "updatedAt": null + }, + "secret": "string" + }, + "schema": { + "type": "object", + "properties": { + "endpoint": { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "url": { "type": "string" }, + "description": { "type": "string", "nullable": true }, + "eventTypes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + } + }, + "enabled": { "type": "boolean" }, + "disabledReason": { + "type": "string", + "nullable": true, + "enum": ["gone", "failing", "manual", null] + }, + "version": { "type": "number", "enum": [1] }, + "previousSecretExpiresAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "createdAt": { "type": "string", "nullable": true, "format": "date-time" }, + "updatedAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": [ + "id", + "url", + "description", + "eventTypes", + "enabled", + "disabledReason", + "version", + "previousSecretExpiresAt", + "createdAt", + "updatedAt" + ] + }, + "secret": { "type": "string", "pattern": "^whsec_[A-Za-z0-9+/]{43}=$" } + }, + "required": ["endpoint", "secret"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "409": { + "description": "HTTP 409", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, + "/admin/webhooks/{id}": { + "get": { + "summary": "Get a webhook endpoint", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { + "endpoint": { + "id": "string", + "url": "string", + "description": "string", + "eventTypes": [null], + "enabled": true, + "disabledReason": null, + "version": null, + "previousSecretExpiresAt": null, + "createdAt": null, + "updatedAt": null + } + }, + "schema": { + "type": "object", + "properties": { + "endpoint": { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "url": { "type": "string" }, + "description": { "type": "string", "nullable": true }, + "eventTypes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + } + }, + "enabled": { "type": "boolean" }, + "disabledReason": { + "type": "string", + "nullable": true, + "enum": ["gone", "failing", "manual", null] + }, + "version": { "type": "number", "enum": [1] }, + "previousSecretExpiresAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "createdAt": { "type": "string", "nullable": true, "format": "date-time" }, + "updatedAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": [ + "id", + "url", + "description", + "eventTypes", + "enabled", + "disabledReason", + "version", + "previousSecretExpiresAt", + "createdAt", + "updatedAt" + ] + } + }, + "required": ["endpoint"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + }, + "patch": { + "summary": "Update a webhook endpoint", + "description": "Turning an endpoint back on clears why it was disabled.", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "id", + "in": "path" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "url": { "type": "string", "maxLength": 2048 }, + "description": { + "type": "string", + "nullable": true, + "minLength": 1, + "maxLength": 500 + }, + "eventTypes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + }, + "minItems": 1 + }, + "enabled": { "type": "boolean" } + } + } + } + } + }, + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { + "endpoint": { + "id": "string", + "url": "string", + "description": "string", + "eventTypes": [null], + "enabled": true, + "disabledReason": null, + "version": null, + "previousSecretExpiresAt": null, + "createdAt": null, + "updatedAt": null + } + }, + "schema": { + "type": "object", + "properties": { + "endpoint": { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "url": { "type": "string" }, + "description": { "type": "string", "nullable": true }, + "eventTypes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + } + }, + "enabled": { "type": "boolean" }, + "disabledReason": { + "type": "string", + "nullable": true, + "enum": ["gone", "failing", "manual", null] + }, + "version": { "type": "number", "enum": [1] }, + "previousSecretExpiresAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "createdAt": { "type": "string", "nullable": true, "format": "date-time" }, + "updatedAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": [ + "id", + "url", + "description", + "eventTypes", + "enabled", + "disabledReason", + "version", + "previousSecretExpiresAt", + "createdAt", + "updatedAt" + ] + } + }, + "required": ["endpoint"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + }, + "delete": { + "summary": "Delete a webhook endpoint", + "description": "Also deletes its delivery history.", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { "message": "string", "token": "string", "delivery": null }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "token": { "type": "string" }, + "delivery": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["otp_email"] }, + "to": { "type": "string" }, + "token": { "type": "string" }, + "purpose": { "type": "string", "enum": ["account_recovery"] } + }, + "required": ["kind", "to", "token"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["otp_sms"] }, + "to": { "type": "string" }, + "token": { "anyOf": [{ "type": "string" }, { "type": "number" }] }, + "purpose": { "type": "string", "enum": ["account_recovery"] } + }, + "required": ["kind", "to", "token"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["magic_link_email"] }, + "to": { "type": "string" }, + "token": { "type": "string" }, + "magicLinkUrl": { "type": "string" } + }, + "required": ["kind", "to", "magicLinkUrl"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["enrollment_invite_email"] }, + "to": { "type": "string" }, + "signInUrl": { "type": "string" } + }, + "required": ["kind", "to", "signInUrl"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["account_notice_email"] }, + "notice": { + "type": "string", + "enum": [ + "account_recovery_opened", + "account_recovery_completed", + "recovery_code_used", + "identity_changed", + "application_notice" + ] + }, + "to": { "type": "string" }, + "subject": { "type": "string" }, + "text": { "type": "string" }, + "cancelUrl": { "type": "string" }, + "application": { + "type": "object", + "properties": { + "clientId": { "type": "string" }, + "name": { "type": "string" } + }, + "required": ["clientId", "name"] + } + }, + "required": ["kind", "notice", "to", "subject", "text"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["account_notice_sms"] }, + "notice": { + "type": "string", + "enum": [ + "account_recovery_opened", + "account_recovery_completed", + "recovery_code_used", + "identity_changed", + "application_notice" + ] + }, + "to": { "type": "string" }, + "text": { "type": "string" }, + "cancelUrl": { "type": "string" }, + "application": { + "type": "object", + "properties": { + "clientId": { "type": "string" }, + "name": { "type": "string" } + }, + "required": ["clientId", "name"] + } + }, + "required": ["kind", "notice", "to", "text"] + } + ] + } + }, + "required": ["message"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, + "/admin/webhooks/{id}/secret": { + "post": { + "summary": "Rotate a webhook signing secret", + "description": "Returns the new secret once. The previous one keeps signing beside it for 24 hours.", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { "secret": "string", "previousSecretExpiresAt": null }, + "schema": { + "type": "object", + "properties": { + "secret": { "type": "string", "pattern": "^whsec_[A-Za-z0-9+/]{43}=$" }, + "previousSecretExpiresAt": { + "type": "string", + "nullable": true, + "format": "date-time" + } + }, + "required": ["secret", "previousSecretExpiresAt"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "409": { + "description": "HTTP 409", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, + "/admin/webhooks/{id}/test": { + "post": { + "summary": "Send a test event", + "description": "Sends `webhook.test` once, now, whatever the endpoint subscribes to.", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { "ok": true, "failure": null, "statusCode": 0, "durationMs": 0 }, + "schema": { + "type": "object", + "properties": { + "ok": { "type": "boolean" }, + "failure": { + "type": "string", + "nullable": true, + "enum": [ + "refused", + "misconfigured", + "timed_out", + "connection_failed", + "http_status", + "invalid_response", + "too_large", + null + ] + }, + "statusCode": { "type": "integer", "nullable": true }, + "durationMs": { "type": "integer", "minimum": 0 } + }, + "required": ["ok", "failure", "statusCode", "durationMs"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, + "/admin/webhook-deliveries": { + "get": { + "summary": "List webhook deliveries", + "description": "Newest first. `status=dead` is the dead letter view. Kept for 30 days.", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": false, + "name": "endpointId", + "in": "query" + }, + { + "schema": { "type": "string", "enum": ["pending", "succeeded", "failed", "dead"] }, + "required": false, + "name": "status", + "in": "query" + }, + { + "schema": { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + }, + "required": false, + "name": "eventType", + "in": "query" + }, + { + "schema": { "type": "integer", "minimum": 1, "maximum": 100, "default": 50 }, + "required": false, + "name": "limit", + "in": "query" + }, + { + "schema": { "type": "string", "maxLength": 200 }, + "required": false, + "name": "cursor", + "in": "query" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { "deliveries": [null], "nextCursor": "string" }, + "schema": { + "type": "object", + "properties": { + "deliveries": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "endpointId": { "type": "string", "minLength": 1 }, + "eventType": { + "anyOf": [ + { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + }, + { "type": "string", "enum": ["webhook.test"] } + ] + }, + "status": { + "type": "string", + "enum": ["pending", "succeeded", "failed", "dead"] + }, + "attempts": { "type": "integer", "minimum": 0 }, + "nextAttemptAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "lastAttemptAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "lastStatusCode": { "type": "integer", "nullable": true }, + "lastFailure": { + "type": "string", + "nullable": true, + "enum": [ + "refused", + "misconfigured", + "timed_out", + "connection_failed", + "http_status", + "invalid_response", + "too_large", + null + ] + }, + "createdAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": [ + "id", + "endpointId", + "eventType", + "status", + "attempts", + "nextAttemptAt", + "lastAttemptAt", + "lastStatusCode", + "lastFailure", + "createdAt" + ] + } + }, + "nextCursor": { "type": "string", "nullable": true } + }, + "required": ["deliveries", "nextCursor"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, + "/admin/webhook-deliveries/{deliveryId}": { + "get": { + "summary": "Get a webhook delivery and its event", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "deliveryId", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { + "delivery": { + "id": "string", + "endpointId": "string", + "eventType": null, + "status": null, + "attempts": 0, + "nextAttemptAt": null, + "lastAttemptAt": null, + "lastStatusCode": 0, + "lastFailure": null, + "createdAt": null, + "event": null + } + }, + "schema": { + "type": "object", + "properties": { + "delivery": { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "endpointId": { "type": "string", "minLength": 1 }, + "eventType": { + "anyOf": [ + { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + }, + { "type": "string", "enum": ["webhook.test"] } + ] + }, + "status": { + "type": "string", + "enum": ["pending", "succeeded", "failed", "dead"] + }, + "attempts": { "type": "integer", "minimum": 0 }, + "nextAttemptAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "lastAttemptAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "lastStatusCode": { "type": "integer", "nullable": true }, + "lastFailure": { + "type": "string", + "nullable": true, + "enum": [ + "refused", + "misconfigured", + "timed_out", + "connection_failed", + "http_status", + "invalid_response", + "too_large", + null + ] + }, + "createdAt": { "type": "string", "nullable": true, "format": "date-time" }, + "event": { + "oneOf": [ + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["user.created"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { "type": "string", "minLength": 1 }, + "email": { "type": "string", "nullable": true }, + "phone": { "type": "string", "nullable": true } + }, + "required": ["userId", "email", "phone"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["user.deleted"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { "userId": { "type": "string", "minLength": 1 } }, + "required": ["userId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["user.signed_in"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { "type": "string", "minLength": 1 }, + "sessionId": { + "type": "string", + "nullable": true, + "minLength": 1 + }, + "method": { "type": "string", "nullable": true }, + "organizationId": { + "type": "string", + "nullable": true, + "minLength": 1 + } + }, + "required": ["userId", "sessionId", "method", "organizationId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["user.recovered"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { "userId": { "type": "string", "minLength": 1 } }, + "required": ["userId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["session.revoked"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { + "type": "string", + "nullable": true, + "minLength": 1 + }, + "sessionId": { + "type": "string", + "nullable": true, + "minLength": 1 + }, + "reason": { + "type": "string", + "enum": ["logout", "admin", "evicted", "provider"] + } + }, + "required": ["userId", "sessionId", "reason"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["credential.added"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { "type": "string", "minLength": 1 }, + "kind": { + "type": "string", + "enum": ["passkey", "totp", "recovery_codes"] + }, + "credentialId": { + "type": "string", + "nullable": true, + "minLength": 1 + } + }, + "required": ["userId", "kind", "credentialId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["credential.removed"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { "type": "string", "minLength": 1 }, + "kind": { + "type": "string", + "enum": ["passkey", "totp", "recovery_codes"] + }, + "credentialId": { + "type": "string", + "nullable": true, + "minLength": 1 + } + }, + "required": ["userId", "kind", "credentialId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["organization.member_added"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "organizationId": { "type": "string", "minLength": 1 }, + "userId": { "type": "string", "minLength": 1 }, + "roles": { "type": "array", "items": { "type": "string" } } + }, + "required": ["organizationId", "userId", "roles"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { + "type": "string", + "enum": ["organization.member_updated"] + }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "organizationId": { "type": "string", "minLength": 1 }, + "userId": { "type": "string", "minLength": 1 }, + "roles": { "type": "array", "items": { "type": "string" } } + }, + "required": ["organizationId", "userId", "roles"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { + "type": "string", + "enum": ["organization.member_removed"] + }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "organizationId": { "type": "string", "minLength": 1 }, + "userId": { "type": "string", "minLength": 1 }, + "roles": { "type": "array", "items": { "type": "string" } } + }, + "required": ["organizationId", "userId", "roles"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["webhook.test"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "endpointId": { "type": "string", "minLength": 1 } + }, + "required": ["endpointId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + } + ] + } + }, + "required": [ + "id", + "endpointId", + "eventType", + "status", + "attempts", + "nextAttemptAt", + "lastAttemptAt", + "lastStatusCode", + "lastFailure", + "createdAt", + "event" + ] + } + }, + "required": ["delivery"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, + "/admin/webhook-deliveries/{deliveryId}/redeliver": { + "post": { + "summary": "Redeliver a webhook", + "description": "One attempt now, with the same `webhook-id` and body and a fresh timestamp and signature.", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "deliveryId", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { + "delivery": { + "id": "string", + "endpointId": "string", + "eventType": null, + "status": null, + "attempts": 0, + "nextAttemptAt": null, + "lastAttemptAt": null, + "lastStatusCode": 0, + "lastFailure": null, + "createdAt": null, + "event": null + } + }, + "schema": { + "type": "object", + "properties": { + "delivery": { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "endpointId": { "type": "string", "minLength": 1 }, + "eventType": { + "anyOf": [ + { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + }, + { "type": "string", "enum": ["webhook.test"] } + ] + }, + "status": { + "type": "string", + "enum": ["pending", "succeeded", "failed", "dead"] + }, + "attempts": { "type": "integer", "minimum": 0 }, + "nextAttemptAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "lastAttemptAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "lastStatusCode": { "type": "integer", "nullable": true }, + "lastFailure": { + "type": "string", + "nullable": true, + "enum": [ + "refused", + "misconfigured", + "timed_out", + "connection_failed", + "http_status", + "invalid_response", + "too_large", + null + ] + }, + "createdAt": { "type": "string", "nullable": true, "format": "date-time" }, + "event": { + "oneOf": [ + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["user.created"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { "type": "string", "minLength": 1 }, + "email": { "type": "string", "nullable": true }, + "phone": { "type": "string", "nullable": true } + }, + "required": ["userId", "email", "phone"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["user.deleted"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { "userId": { "type": "string", "minLength": 1 } }, + "required": ["userId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["user.signed_in"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { "type": "string", "minLength": 1 }, + "sessionId": { + "type": "string", + "nullable": true, + "minLength": 1 + }, + "method": { "type": "string", "nullable": true }, + "organizationId": { + "type": "string", + "nullable": true, + "minLength": 1 + } + }, + "required": ["userId", "sessionId", "method", "organizationId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["user.recovered"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { "userId": { "type": "string", "minLength": 1 } }, + "required": ["userId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["session.revoked"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { + "type": "string", + "nullable": true, + "minLength": 1 + }, + "sessionId": { + "type": "string", + "nullable": true, + "minLength": 1 + }, + "reason": { + "type": "string", + "enum": ["logout", "admin", "evicted", "provider"] + } + }, + "required": ["userId", "sessionId", "reason"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["credential.added"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { "type": "string", "minLength": 1 }, + "kind": { + "type": "string", + "enum": ["passkey", "totp", "recovery_codes"] + }, + "credentialId": { + "type": "string", + "nullable": true, + "minLength": 1 + } + }, + "required": ["userId", "kind", "credentialId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["credential.removed"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { "type": "string", "minLength": 1 }, + "kind": { + "type": "string", + "enum": ["passkey", "totp", "recovery_codes"] + }, + "credentialId": { + "type": "string", + "nullable": true, + "minLength": 1 + } + }, + "required": ["userId", "kind", "credentialId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["organization.member_added"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "organizationId": { "type": "string", "minLength": 1 }, + "userId": { "type": "string", "minLength": 1 }, + "roles": { "type": "array", "items": { "type": "string" } } + }, + "required": ["organizationId", "userId", "roles"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { + "type": "string", + "enum": ["organization.member_updated"] + }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "organizationId": { "type": "string", "minLength": 1 }, + "userId": { "type": "string", "minLength": 1 }, + "roles": { "type": "array", "items": { "type": "string" } } + }, + "required": ["organizationId", "userId", "roles"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { + "type": "string", + "enum": ["organization.member_removed"] + }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "organizationId": { "type": "string", "minLength": 1 }, + "userId": { "type": "string", "minLength": 1 }, + "roles": { "type": "array", "items": { "type": "string" } } + }, + "required": ["organizationId", "userId", "roles"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["webhook.test"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "endpointId": { "type": "string", "minLength": 1 } + }, + "required": ["endpointId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + } + ] + } + }, + "required": [ + "id", + "endpointId", + "eventType", + "status", + "attempts", + "nextAttemptAt", + "lastAttemptAt", + "lastStatusCode", + "lastFailure", + "createdAt", + "event" + ] + } + }, + "required": ["delivery"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } } } } diff --git a/package-lock.json b/package-lock.json index 7004eecb..5240e709 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,7 +13,7 @@ "@seamless-auth/messaging": "^0.3.1", "@seamless-auth/messaging-aws": "^0.3.1", "@seamless-auth/messaging-twilio": "^0.3.1", - "@seamless-auth/types": "^0.38.0", + "@seamless-auth/types": "^0.40.0", "@simplewebauthn/server": "^14.0.3", "base64url": "^3.0.1", "bcrypt-ts": "^9.0.2", @@ -2927,9 +2927,9 @@ } }, "node_modules/@seamless-auth/types": { - "version": "0.38.0", - "resolved": "https://registry.npmjs.org/@seamless-auth/types/-/types-0.38.0.tgz", - "integrity": "sha512-qALF5GFQEv+9yucQdn179cpTdEMMH/PjtZWAHatWk1qUEOzb1ElOqoBZgC4/THAk6u4aLgDyuDt/dCD/BzloqA==", + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@seamless-auth/types/-/types-0.40.0.tgz", + "integrity": "sha512-NpFVCWE0VSNrBK9M4yBxsloyQgGHXP6B8/QmDPxsFz48/qV6jcDqdUpuV4PAJslG9B9X+4BcnTSQzI+iPSRNsA==", "license": "Apache-2.0", "dependencies": { "zod": "^4.5.0" diff --git a/package.json b/package.json index 855c3341..fcac97f4 100644 --- a/package.json +++ b/package.json @@ -52,7 +52,7 @@ "@seamless-auth/messaging": "^0.3.1", "@seamless-auth/messaging-aws": "^0.3.1", "@seamless-auth/messaging-twilio": "^0.3.1", - "@seamless-auth/types": "^0.38.0", + "@seamless-auth/types": "^0.40.0", "@simplewebauthn/server": "^14.0.3", "base64url": "^3.0.1", "bcrypt-ts": "^9.0.2", diff --git a/src/config/authSecrets.ts b/src/config/authSecrets.ts index cf74d12d..ac4b38d3 100644 --- a/src/config/authSecrets.ts +++ b/src/config/authSecrets.ts @@ -23,6 +23,7 @@ export const AUTH_SECRETS = { DECOY_SUBJECT_SECRET: 'the decoy subjects /login answers for unknown identifiers', TOTP_SECRET_ENCRYPTION_KEY: 'every stored TOTP secret', OAUTH_STATE_SECRET: 'OAuth sign-ins in progress', + CALLOUT_SECRET_ENCRYPTION_KEY: 'every stored webhook and login hook signing secret', } as const; export type AuthSecretName = keyof typeof AUTH_SECRETS; @@ -53,6 +54,8 @@ function devFallback(name: AuthSecretName, env: EnvSource) { return `dev-oauth-state:${app}`; case 'DECOY_SUBJECT_SECRET': return `dev-decoy-subject:${app}`; + case 'CALLOUT_SECRET_ENCRYPTION_KEY': + return `dev-callout-secret:${app}:${env.ISSUER ?? 'local'}`; } } @@ -78,10 +81,16 @@ export function isAuthSecretSet(name: AuthSecretName, env: EnvSource = process.e return Boolean(env[name]?.trim()); } -/** The secrets a configuration needs, given whether any TOTP credential is stored. */ +export type StoredSecrets = { + totpCredentialsExist: boolean; + /** Any webhook endpoint or login hook, each of which holds an encrypted signing secret. */ + calloutSecretsExist?: boolean; +}; + +/** The secrets a configuration needs, given which encrypted secrets are stored. */ export function authSecretsRequiredBy( config: Pick, - { totpCredentialsExist }: { totpCredentialsExist: boolean }, + { totpCredentialsExist, calloutSecretsExist = false }: StoredSecrets, ): AuthSecretName[] { const required: AuthSecretName[] = ['REFRESH_TOKEN_LOOKUP_SECRET', 'DECOY_SUBJECT_SECRET']; @@ -95,6 +104,10 @@ export function authSecretsRequiredBy( required.push('OAUTH_STATE_SECRET'); } + if (calloutSecretsExist) { + required.push('CALLOUT_SECRET_ENCRYPTION_KEY'); + } + return required; } @@ -114,17 +127,28 @@ export function productionSecretMissing(name: AuthSecretName, env: EnvSource = p */ export function assertAuthSecrets( config: Pick, - totpCredentialsExist: boolean, + stored: StoredSecrets, env: EnvSource = process.env, ) { if (!isProduction(env)) return; - const missing = authSecretsRequiredBy(config, { totpCredentialsExist }).filter( + const missing = authSecretsRequiredBy(config, stored).filter( (name) => !isAuthSecretSet(name, env), ); if (missing.length === 0) return; + // This key never had a service token fallback: a webhook or login hook cannot be created in + // production without it, so it is only missing here if it was removed, and the service token + // would not read the stored secrets either. + if (missing.length === 1 && missing[0] === 'CALLOUT_SECRET_ENCRYPTION_KEY') { + throw new Error( + 'Refusing to start: CALLOUT_SECRET_ENCRYPTION_KEY is not set, and webhook or login hook ' + + 'signing secrets are stored under it. Restore the value they were created with, or ' + + 'delete the webhooks and hooks and create them again. See docs/production-operations.md.', + ); + } + throw new Error( `Refusing to start: ${missing.join(', ')} ${missing.length === 1 ? 'is' : 'are'} not set. ` + `Each protects ${missing.map((name) => AUTH_SECRETS[name]).join('; ')}. ` + diff --git a/src/controllers/organizations.ts b/src/controllers/organizations.ts index 883be58b..afe9cce0 100644 --- a/src/controllers/organizations.ts +++ b/src/controllers/organizations.ts @@ -351,6 +351,7 @@ export async function updateMember(req: RouteRequest, res: Response) { req, metadata: { organizationId, + roles: nextRoles, rolesAdded: nextRoles.filter((role) => !currentRoles.includes(role)), rolesRemoved: currentRoles.filter((role) => !nextRoles.includes(role)), ...(req.body.scopes === undefined ? {} : { scopes: membership.scopes }), diff --git a/src/controllers/user.ts b/src/controllers/user.ts index e5d17a89..cda2290a 100644 --- a/src/controllers/user.ts +++ b/src/controllers/user.ts @@ -217,6 +217,13 @@ export const deleteCredential = async (req: Request, res: Response) => { await cred.destroy(); + await AuthEventService.log({ + userId: authUser.id, + type: 'credentials_deleted', + req, + metadata: { credential: 'passkey', credentialId: cred.id }, + }); + return res.json({ message: 'Credential deleted' }); } catch (err) { logger.error(`Failed to delete credential: ${err}`); diff --git a/src/controllers/webauthn.ts b/src/controllers/webauthn.ts index 0a93e7d7..a50e4aa9 100644 --- a/src/controllers/webauthn.ts +++ b/src/controllers/webauthn.ts @@ -389,13 +389,17 @@ const verifyWebAuthnRegistration = async (req: Request, res: Response) => { userId: user.id, type: 'registration_success', req, - metadata: breakGlassOverride - ? { - severity: 'high', - breakGlassWaived: ['authenticator_policy'], - authenticatorPolicyRefusal: verdict.detail, - } - : {}, + metadata: { + credential: 'passkey', + credentialId: created.id, + ...(breakGlassOverride + ? { + severity: 'high', + breakGlassWaived: ['authenticator_policy'], + authenticatorPolicyRefusal: verdict.detail, + } + : {}), + }, }); if (breakGlassOverride) { diff --git a/src/controllers/webhooks.ts b/src/controllers/webhooks.ts new file mode 100644 index 00000000..fd672f15 --- /dev/null +++ b/src/controllers/webhooks.ts @@ -0,0 +1,185 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import type { WebhookDeliveryQuery } from '@seamless-auth/types'; +import { Request, Response } from 'express'; + +import { AuthEventService } from '../services/authEventService.js'; +import { + createEndpoint, + deleteEndpoint, + getDelivery, + getEndpoint, + listDeliveries as listDeliveryRecords, + listEndpoints, + redeliver as redeliverRecord, + rotateEndpointSecret, + sendTestEvent, + serializeDelivery, + serializeEndpoint, + updateEndpoint, + WebhookError, +} from '../services/webhookService.js'; +import { AuthenticatedRequest, RouteRequest } from '../types/types.js'; + +function actorUserId(req: Request) { + return (req as AuthenticatedRequest).user?.id ?? null; +} + +/** + * The audit log is append-only, so a URL is recorded without its query string, where a receiver + * may have put a token. + */ +function auditedUrl(url: string) { + const parsed = new URL(url); + return `${parsed.origin}${parsed.pathname}`; +} + +function sendError(res: Response, error: unknown) { + if (error instanceof WebhookError) { + return res.status(error.status).json({ error: error.message }); + } + + throw error; +} + +export async function listWebhooks(_req: Request, res: Response) { + const endpoints = await listEndpoints(); + return res.json({ endpoints: endpoints.map(serializeEndpoint) }); +} + +export async function getWebhook(req: RouteRequest, res: Response) { + try { + return res.json({ endpoint: serializeEndpoint(await getEndpoint(req.params.id)) }); + } catch (error) { + return sendError(res, error); + } +} + +export async function createWebhook(req: Request, res: Response) { + try { + const { endpoint, secret } = await createEndpoint(req.body, actorUserId(req)); + + await AuthEventService.log({ + actorUserId: actorUserId(req), + type: 'admin_webhook_created', + req, + metadata: { + endpointId: endpoint.id, + url: auditedUrl(endpoint.url), + eventTypes: endpoint.eventTypes, + }, + }); + + return res.status(201).json({ endpoint: serializeEndpoint(endpoint), secret }); + } catch (error) { + return sendError(res, error); + } +} + +export async function updateWebhook(req: RouteRequest, res: Response) { + try { + const { endpoint, released } = await updateEndpoint(req.params.id, req.body); + + await AuthEventService.log({ + actorUserId: actorUserId(req), + type: 'admin_webhook_updated', + req, + metadata: { + endpointId: endpoint.id, + changed: Object.keys(req.body), + ...(released ? { releasedDeliveries: released } : {}), + }, + }); + + return res.json({ endpoint: serializeEndpoint(endpoint) }); + } catch (error) { + return sendError(res, error); + } +} + +export async function deleteWebhook(req: RouteRequest, res: Response) { + try { + const endpoint = await deleteEndpoint(req.params.id); + + await AuthEventService.log({ + actorUserId: actorUserId(req), + type: 'admin_webhook_deleted', + req, + metadata: { endpointId: endpoint.id, url: auditedUrl(endpoint.url) }, + }); + + return res.json({ message: 'Webhook deleted' }); + } catch (error) { + return sendError(res, error); + } +} + +export async function rotateWebhookSecret(req: RouteRequest, res: Response) { + try { + const { endpoint, secret, previousSecretExpiresAt } = await rotateEndpointSecret(req.params.id); + + await AuthEventService.log({ + actorUserId: actorUserId(req), + type: 'admin_webhook_secret_rotated', + req, + metadata: { endpointId: endpoint.id }, + }); + + return res.json({ secret, previousSecretExpiresAt: previousSecretExpiresAt.toISOString() }); + } catch (error) { + return sendError(res, error); + } +} + +export async function testWebhook(req: RouteRequest, res: Response) { + try { + return res.json(await sendTestEvent(req.params.id)); + } catch (error) { + return sendError(res, error); + } +} + +export async function listWebhookDeliveries(req: Request, res: Response) { + try { + const { deliveries, nextCursor } = await listDeliveryRecords( + req.query as unknown as WebhookDeliveryQuery, + ); + return res.json({ deliveries: deliveries.map(serializeDelivery), nextCursor }); + } catch (error) { + return sendError(res, error); + } +} + +export async function getWebhookDelivery(req: RouteRequest, res: Response) { + try { + const delivery = await getDelivery(req.params.deliveryId); + return res.json({ + delivery: { ...serializeDelivery(delivery), event: JSON.parse(delivery.payload) }, + }); + } catch (error) { + return sendError(res, error); + } +} + +export async function redeliverWebhook(req: RouteRequest, res: Response) { + try { + const delivery = await redeliverRecord(req.params.deliveryId); + + await AuthEventService.log({ + actorUserId: actorUserId(req), + type: 'admin_webhook_redelivered', + req, + metadata: { deliveryId: delivery.id, endpointId: delivery.endpointId }, + }); + + return res.json({ + delivery: { ...serializeDelivery(delivery), event: JSON.parse(delivery.payload) }, + }); + } catch (error) { + return sendError(res, error); + } +} diff --git a/src/generated/api.ts b/src/generated/api.ts index f17bc323..38decf96 100644 --- a/src/generated/api.ts +++ b/src/generated/api.ts @@ -6900,6 +6900,13 @@ export interface paths { | 'webauthn_registration_challenge' | 'webauthn_registration_failed' | 'webauthn_registration_suspicious' + | 'admin_webhook_created' + | 'admin_webhook_deleted' + | 'admin_webhook_redelivered' + | 'admin_webhook_secret_rotated' + | 'admin_webhook_updated' + | 'session_created' + | 'webhook_endpoint_disabled' ) | string | ( @@ -7033,6 +7040,13 @@ export interface paths { | 'webauthn_registration_challenge' | 'webauthn_registration_failed' | 'webauthn_registration_suspicious' + | 'admin_webhook_created' + | 'admin_webhook_deleted' + | 'admin_webhook_redelivered' + | 'admin_webhook_secret_rotated' + | 'admin_webhook_updated' + | 'session_created' + | 'webhook_endpoint_disabled' ) | string )[]; @@ -14601,6 +14615,7 @@ export interface paths { | 'session_revoked' | 'subject_mismatch' | 'auth_context_mismatch' + | 'claims_mismatch' | 'issuer_mismatch' | 'audience_mismatch' | 'client_inactive' @@ -14647,6 +14662,7 @@ export interface paths { | 'session_revoked' | 'subject_mismatch' | 'auth_context_mismatch' + | 'claims_mismatch' | 'issuer_mismatch' | 'audience_mismatch' | 'client_inactive' @@ -15402,7 +15418,18 @@ export interface paths { * "roles": [ * null * ], - * "org_id": "string" + * "org_id": "string", + * "permissions": [ + * null + * ], + * "permissions_omitted": null, + * "org_roles": [ + * null + * ], + * "org_permissions": [ + * null + * ], + * "customClaims": null * } */ 'application/json': { @@ -15413,6 +15440,74 @@ export interface paths { phone_number_verified?: boolean; roles: string[]; org_id: string | null; + permissions?: string[]; + /** @enum {boolean} */ + permissions_omitted?: true; + org_roles?: string[]; + org_permissions?: string[]; + /** @default {} */ + customClaims: { + [key: string]: + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + }; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + }; + }; + }; + }; }; }; }; @@ -32078,6 +32173,2245 @@ export interface paths { patch?: never; trace?: never; }; + '/admin/webhooks': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** List webhook endpoints */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "endpoints": [ + * null + * ] + * } + */ + 'application/json': { + endpoints: { + id: string; + url: string; + description: string | null; + eventTypes: ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + )[]; + enabled: boolean; + /** @enum {string|null} */ + disabledReason: 'gone' | 'failing' | 'manual' | null; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + previousSecretExpiresAt: string | null; + /** Format: date-time */ + createdAt: string | null; + /** Format: date-time */ + updatedAt: string | null; + }[]; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + put?: never; + /** + * Create a webhook endpoint + * @description Returns the signing secret once. It cannot be read back. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + 'application/json': { + url: string; + description?: string; + eventTypes: ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + )[]; + enabled?: boolean; + }; + }; + }; + responses: { + /** @description HTTP 201 */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "endpoint": { + * "id": "string", + * "url": "string", + * "description": "string", + * "eventTypes": [ + * null + * ], + * "enabled": true, + * "disabledReason": null, + * "version": null, + * "previousSecretExpiresAt": null, + * "createdAt": null, + * "updatedAt": null + * }, + * "secret": "string" + * } + */ + 'application/json': { + endpoint: { + id: string; + url: string; + description: string | null; + eventTypes: ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + )[]; + enabled: boolean; + /** @enum {string|null} */ + disabledReason: 'gone' | 'failing' | 'manual' | null; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + previousSecretExpiresAt: string | null; + /** Format: date-time */ + createdAt: string | null; + /** Format: date-time */ + updatedAt: string | null; + }; + secret: string; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 409 */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + '/admin/webhooks/{id}': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Get a webhook endpoint */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "endpoint": { + * "id": "string", + * "url": "string", + * "description": "string", + * "eventTypes": [ + * null + * ], + * "enabled": true, + * "disabledReason": null, + * "version": null, + * "previousSecretExpiresAt": null, + * "createdAt": null, + * "updatedAt": null + * } + * } + */ + 'application/json': { + endpoint: { + id: string; + url: string; + description: string | null; + eventTypes: ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + )[]; + enabled: boolean; + /** @enum {string|null} */ + disabledReason: 'gone' | 'failing' | 'manual' | null; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + previousSecretExpiresAt: string | null; + /** Format: date-time */ + createdAt: string | null; + /** Format: date-time */ + updatedAt: string | null; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + put?: never; + post?: never; + /** + * Delete a webhook endpoint + * @description Also deletes its delivery history. + */ + delete: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "token": "string", + * "delivery": null + * } + */ + 'application/json': { + message: string; + token?: string; + delivery?: + | { + /** @enum {string} */ + kind: 'otp_email'; + to: string; + token: string; + /** @enum {string} */ + purpose?: 'account_recovery'; + } + | { + /** @enum {string} */ + kind: 'otp_sms'; + to: string; + token: string | number; + /** @enum {string} */ + purpose?: 'account_recovery'; + } + | { + /** @enum {string} */ + kind: 'magic_link_email'; + to: string; + token?: string; + magicLinkUrl: string; + } + | { + /** @enum {string} */ + kind: 'enrollment_invite_email'; + to: string; + signInUrl: string; + } + | { + /** @enum {string} */ + kind: 'account_notice_email'; + /** @enum {string} */ + notice: + | 'account_recovery_opened' + | 'account_recovery_completed' + | 'recovery_code_used' + | 'identity_changed' + | 'application_notice'; + to: string; + subject: string; + text: string; + cancelUrl?: string; + application?: { + clientId: string; + name: string; + }; + } + | { + /** @enum {string} */ + kind: 'account_notice_sms'; + /** @enum {string} */ + notice: + | 'account_recovery_opened' + | 'account_recovery_completed' + | 'recovery_code_used' + | 'identity_changed' + | 'application_notice'; + to: string; + text: string; + cancelUrl?: string; + application?: { + clientId: string; + name: string; + }; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + options?: never; + head?: never; + /** + * Update a webhook endpoint + * @description Turning an endpoint back on clears why it was disabled. + */ + patch: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + 'application/json': { + url?: string; + description?: string | null; + eventTypes?: ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + )[]; + enabled?: boolean; + }; + }; + }; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "endpoint": { + * "id": "string", + * "url": "string", + * "description": "string", + * "eventTypes": [ + * null + * ], + * "enabled": true, + * "disabledReason": null, + * "version": null, + * "previousSecretExpiresAt": null, + * "createdAt": null, + * "updatedAt": null + * } + * } + */ + 'application/json': { + endpoint: { + id: string; + url: string; + description: string | null; + eventTypes: ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + )[]; + enabled: boolean; + /** @enum {string|null} */ + disabledReason: 'gone' | 'failing' | 'manual' | null; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + previousSecretExpiresAt: string | null; + /** Format: date-time */ + createdAt: string | null; + /** Format: date-time */ + updatedAt: string | null; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + trace?: never; + }; + '/admin/webhooks/{id}/secret': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Rotate a webhook signing secret + * @description Returns the new secret once. The previous one keeps signing beside it for 24 hours. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "secret": "string", + * "previousSecretExpiresAt": null + * } + */ + 'application/json': { + secret: string; + /** Format: date-time */ + previousSecretExpiresAt: string | null; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 409 */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + '/admin/webhooks/{id}/test': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Send a test event + * @description Sends `webhook.test` once, now, whatever the endpoint subscribes to. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "ok": true, + * "failure": null, + * "statusCode": 0, + * "durationMs": 0 + * } + */ + 'application/json': { + ok: boolean; + /** @enum {string|null} */ + failure: + | 'refused' + | 'misconfigured' + | 'timed_out' + | 'connection_failed' + | 'http_status' + | 'invalid_response' + | 'too_large' + | null; + statusCode: number | null; + durationMs: number; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + '/admin/webhook-deliveries': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List webhook deliveries + * @description Newest first. `status=dead` is the dead letter view. Kept for 30 days. + */ + get: { + parameters: { + query?: { + endpointId?: string; + status?: 'pending' | 'succeeded' | 'failed' | 'dead'; + eventType?: + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed'; + limit?: number; + cursor?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "deliveries": [ + * null + * ], + * "nextCursor": "string" + * } + */ + 'application/json': { + deliveries: { + id: string; + endpointId: string; + eventType: + | ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + ) + | 'webhook.test'; + /** @enum {string} */ + status: 'pending' | 'succeeded' | 'failed' | 'dead'; + attempts: number; + /** Format: date-time */ + nextAttemptAt: string | null; + /** Format: date-time */ + lastAttemptAt: string | null; + lastStatusCode: number | null; + /** @enum {string|null} */ + lastFailure: + | 'refused' + | 'misconfigured' + | 'timed_out' + | 'connection_failed' + | 'http_status' + | 'invalid_response' + | 'too_large' + | null; + /** Format: date-time */ + createdAt: string | null; + }[]; + nextCursor: string | null; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + '/admin/webhook-deliveries/{deliveryId}': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Get a webhook delivery and its event */ + get: { + parameters: { + query?: never; + header?: never; + path: { + deliveryId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "delivery": { + * "id": "string", + * "endpointId": "string", + * "eventType": null, + * "status": null, + * "attempts": 0, + * "nextAttemptAt": null, + * "lastAttemptAt": null, + * "lastStatusCode": 0, + * "lastFailure": null, + * "createdAt": null, + * "event": null + * } + * } + */ + 'application/json': { + delivery: { + id: string; + endpointId: string; + eventType: + | ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + ) + | 'webhook.test'; + /** @enum {string} */ + status: 'pending' | 'succeeded' | 'failed' | 'dead'; + attempts: number; + /** Format: date-time */ + nextAttemptAt: string | null; + /** Format: date-time */ + lastAttemptAt: string | null; + lastStatusCode: number | null; + /** @enum {string|null} */ + lastFailure: + | 'refused' + | 'misconfigured' + | 'timed_out' + | 'connection_failed' + | 'http_status' + | 'invalid_response' + | 'too_large' + | null; + /** Format: date-time */ + createdAt: string | null; + event: + | { + id: string; + /** @enum {string} */ + type: 'user.created'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + email: string | null; + phone: string | null; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'user.deleted'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'user.signed_in'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + sessionId: string | null; + method: string | null; + organizationId: string | null; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'user.recovered'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'session.revoked'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string | null; + sessionId: string | null; + /** @enum {string} */ + reason: 'logout' | 'admin' | 'evicted' | 'provider'; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'credential.added'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + /** @enum {string} */ + kind: 'passkey' | 'totp' | 'recovery_codes'; + credentialId: string | null; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'credential.removed'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + /** @enum {string} */ + kind: 'passkey' | 'totp' | 'recovery_codes'; + credentialId: string | null; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'organization.member_added'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + organizationId: string; + userId: string; + roles: string[]; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'organization.member_updated'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + organizationId: string; + userId: string; + roles: string[]; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'organization.member_removed'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + organizationId: string; + userId: string; + roles: string[]; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'webhook.test'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + endpointId: string; + }; + }; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + '/admin/webhook-deliveries/{deliveryId}/redeliver': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Redeliver a webhook + * @description One attempt now, with the same `webhook-id` and body and a fresh timestamp and signature. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + deliveryId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "delivery": { + * "id": "string", + * "endpointId": "string", + * "eventType": null, + * "status": null, + * "attempts": 0, + * "nextAttemptAt": null, + * "lastAttemptAt": null, + * "lastStatusCode": 0, + * "lastFailure": null, + * "createdAt": null, + * "event": null + * } + * } + */ + 'application/json': { + delivery: { + id: string; + endpointId: string; + eventType: + | ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + ) + | 'webhook.test'; + /** @enum {string} */ + status: 'pending' | 'succeeded' | 'failed' | 'dead'; + attempts: number; + /** Format: date-time */ + nextAttemptAt: string | null; + /** Format: date-time */ + lastAttemptAt: string | null; + lastStatusCode: number | null; + /** @enum {string|null} */ + lastFailure: + | 'refused' + | 'misconfigured' + | 'timed_out' + | 'connection_failed' + | 'http_status' + | 'invalid_response' + | 'too_large' + | null; + /** Format: date-time */ + createdAt: string | null; + event: + | { + id: string; + /** @enum {string} */ + type: 'user.created'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + email: string | null; + phone: string | null; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'user.deleted'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'user.signed_in'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + sessionId: string | null; + method: string | null; + organizationId: string | null; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'user.recovered'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'session.revoked'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string | null; + sessionId: string | null; + /** @enum {string} */ + reason: 'logout' | 'admin' | 'evicted' | 'provider'; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'credential.added'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + /** @enum {string} */ + kind: 'passkey' | 'totp' | 'recovery_codes'; + credentialId: string | null; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'credential.removed'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + /** @enum {string} */ + kind: 'passkey' | 'totp' | 'recovery_codes'; + credentialId: string | null; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'organization.member_added'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + organizationId: string; + userId: string; + roles: string[]; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'organization.member_updated'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + organizationId: string; + userId: string; + roles: string[]; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'organization.member_removed'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + organizationId: string; + userId: string; + roles: string[]; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'webhook.test'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + endpointId: string; + }; + }; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; } export type webhooks = Record; export interface components { diff --git a/src/lib/authEventCategories.ts b/src/lib/authEventCategories.ts index b8f39a25..db7b4277 100644 --- a/src/lib/authEventCategories.ts +++ b/src/lib/authEventCategories.ts @@ -64,11 +64,13 @@ const EXACT_CATEGORIES: Readonly> = { notification_sent: 'system', // Session lifecycle sits with login, which is where logout_ already lands, and // an eviction is a direct consequence of a sign-in rather than an admin action. + session_created: 'login', session_evicted: 'login', session_exchange_replayed: 'login', session_exchanged: 'login', user_created: 'registration', user_deleted: 'system', + webhook_endpoint_disabled: 'system', }; // `suspicious` is checked first so security signals stay in one bucket rather than diff --git a/src/lib/calloutSigning.ts b/src/lib/calloutSigning.ts new file mode 100644 index 00000000..21d6f16c --- /dev/null +++ b/src/lib/calloutSigning.ts @@ -0,0 +1,94 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes } from 'node:crypto'; + +import { + WEBHOOK_ID_HEADER, + WEBHOOK_SECRET_PREFIX, + WEBHOOK_SIGNATURE_HEADER, + WEBHOOK_SIGNATURE_VERSION, + WEBHOOK_TIMESTAMP_HEADER, +} from '@seamless-auth/types'; + +import { authSecret } from '../config/authSecrets.js'; + +/** + * Standard Webhooks signing (ADR 0005, D1), for webhooks and login hook calls alike. The secret + * is `whsec_` and base64 of 32 random bytes, and the HMAC key is those decoded bytes. + */ +export function generateCalloutSecret() { + return `${WEBHOOK_SECRET_PREFIX}${randomBytes(32).toString('base64')}`; +} + +function secretKey(secret: string) { + return Buffer.from(secret.slice(WEBHOOK_SECRET_PREFIX.length), 'base64'); +} + +export function calloutSignature(id: string, timestamp: number, body: string, secret: string) { + const signature = createHmac('sha256', secretKey(secret)) + .update(`${id}.${timestamp}.${body}`) + .digest('base64'); + + return `${WEBHOOK_SIGNATURE_VERSION},${signature}`; +} + +/** + * The three Standard Webhooks headers. While a secret rotates, both secrets sign, separated by a + * space, so a receiver holding either one verifies. + */ +export function signedCalloutHeaders( + id: string, + body: string, + secrets: readonly string[], + now: Date = new Date(), +): Record { + const timestamp = Math.floor(now.getTime() / 1000); + + return { + 'content-type': 'application/json', + [WEBHOOK_ID_HEADER]: id, + [WEBHOOK_TIMESTAMP_HEADER]: String(timestamp), + [WEBHOOK_SIGNATURE_HEADER]: secrets + .map((secret) => calloutSignature(id, timestamp, body, secret)) + .join(' '), + }; +} + +const CIPHER = 'aes-256-gcm'; + +export type EncryptedCalloutSecret = { + ciphertext: string; + iv: string; + tag: string; +}; + +// Signing secrets have to be read back to sign, so they cannot be hashed (ADR 0005, D9). +function encryptionKey() { + return createHash('sha256').update(authSecret('CALLOUT_SECRET_ENCRYPTION_KEY')).digest(); +} + +export function encryptCalloutSecret(secret: string): EncryptedCalloutSecret { + const iv = randomBytes(12); + const cipher = createCipheriv(CIPHER, encryptionKey(), iv); + const ciphertext = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]); + + return { + ciphertext: ciphertext.toString('base64'), + iv: iv.toString('base64'), + tag: cipher.getAuthTag().toString('base64'), + }; +} + +export function decryptCalloutSecret({ ciphertext, iv, tag }: EncryptedCalloutSecret) { + const decipher = createDecipheriv(CIPHER, encryptionKey(), Buffer.from(iv, 'base64')); + decipher.setAuthTag(Buffer.from(tag, 'base64')); + + return Buffer.concat([ + decipher.update(Buffer.from(ciphertext, 'base64')), + decipher.final(), + ]).toString('utf8'); +} diff --git a/src/lib/calloutTransport.ts b/src/lib/calloutTransport.ts new file mode 100644 index 00000000..7c32410d --- /dev/null +++ b/src/lib/calloutTransport.ts @@ -0,0 +1,268 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import type { LookupAddress } from 'node:dns'; +import { lookup } from 'node:dns/promises'; +import { request as httpRequest } from 'node:http'; +import { request as httpsRequest } from 'node:https'; +import { BlockList, isIP, type LookupFunction } from 'node:net'; + +import type { CalloutFailure } from '@seamless-auth/types'; + +import { inList, neverReachable, nonPublic, unmapIPv4 } from './outboundAddress.js'; + +type EnvSource = Record; + +/** + * Hosts on a private address that webhooks, login hooks and audit sinks may reach in production + * (ADR 0005, D8). An env var, so it is the operator's call: nothing written through the API can + * widen it. Kept apart from `OAUTH_PROVIDER_PRIVATE_HOSTS`, so allowing an internal hook service + * does not also allow it as an identity provider. + */ +export const CALLOUT_PRIVATE_HOSTS_ENV = 'CALLOUT_PRIVATE_HOSTS'; + +// Multicast and broadcast never answer a request, and reaching them is only ever a probe. +const calloutNeverReachable = new BlockList(); +calloutNeverReachable.addSubnet('224.0.0.0', 4, 'ipv4'); +calloutNeverReachable.addAddress('255.255.255.255', 'ipv4'); +calloutNeverReachable.addSubnet('ff00::', 8, 'ipv6'); + +export class CalloutError extends Error { + readonly failure: CalloutFailure; + + constructor(failure: CalloutFailure, message: string) { + super(message); + this.name = 'CalloutError'; + this.failure = failure; + } +} + +function isProduction(env: EnvSource) { + return env.NODE_ENV === 'production'; +} + +function bare(hostname: string) { + return hostname.replace(/^\[|\]$/g, '').toLowerCase(); +} + +function privateHostsAllowed(env: EnvSource) { + return new Set( + (env[CALLOUT_PRIVATE_HOSTS_ENV] ?? '') + .split(',') + .map((host) => host.trim().toLowerCase()) + .filter(Boolean), + ); +} + +function hostMayBePrivate(hostname: string, env: EnvSource) { + return !isProduction(env) || privateHostsAllowed(env).has(bare(hostname)); +} + +function addressAllowed(address: string, hostAllowlisted: boolean) { + return ( + !inList(neverReachable, address) && + !inList(calloutNeverReachable, address) && + (hostAllowlisted || !inList(nonPublic, address)) + ); +} + +function issuerHost(env: EnvSource) { + try { + return env.ISSUER ? new URL(env.ISSUER).hostname.toLowerCase() : null; + } catch { + return null; + } +} + +/** Whether a host may be the target of a callout, before any DNS. */ +export function calloutHostProblem(hostname: string, env: EnvSource = process.env): string | null { + const host = bare(hostname); + + if (!host) return 'has no host'; + if (host === issuerHost(env)) return 'must not point at this server'; + + if (isIP(unmapIPv4(host)) && !addressAllowed(host, hostMayBePrivate(host, env))) { + return isProduction(env) && + !inList(neverReachable, host) && + !inList(calloutNeverReachable, host) + ? `points at a non-public address; list the host in ${CALLOUT_PRIVATE_HOSTS_ENV} to allow it` + : 'points at an address that is never reachable'; + } + + return null; +} + +/** + * What is wrong with a callout URL, for the API to refuse it when written. The same checks run + * again at connect time, where DNS is also checked. + */ +export function calloutUrlProblem(value: string, env: EnvSource = process.env): string | null { + let url: URL; + try { + url = new URL(value); + } catch { + return 'is not a valid URL'; + } + + if (url.protocol !== 'https:' && url.protocol !== 'http:') return 'must use https'; + if (isProduction(env) && url.protocol !== 'https:') return 'must use https'; + if (url.username || url.password) return 'must not carry a username or password'; + + return calloutHostProblem(url.hostname, env); +} + +type LookupCallback = ( + error: Error | null, + address: string | LookupAddress[], + family?: number, +) => void; + +/** + * DNS for the callout's own socket, so the addresses checked are the ones connected to and a + * name cannot answer one way for a check and another for the connection. Every address a name + * resolves to must be allowed, not just the first. + */ +export function calloutLookup(env: EnvSource = process.env): LookupFunction { + const guarded = ( + hostname: string, + options: { family?: number | string; all?: boolean }, + callback: LookupCallback, + ) => { + const family = + options.family === 6 || options.family === 'IPv6' + ? 6 + : options.family === 4 || options.family === 'IPv4' + ? 4 + : 0; + + lookup(hostname, { all: true, verbatim: true, family }).then( + (addresses) => { + const allowed = hostMayBePrivate(hostname, env); + if ( + addresses.length === 0 || + addresses.some((entry) => !addressAllowed(entry.address, allowed)) + ) { + callback(new CalloutError('refused', `${hostname} resolves to a refused address`), []); + return; + } + + if (options.all) { + callback(null, addresses); + } else { + callback(null, addresses[0].address, addresses[0].family); + } + }, + (error: Error) => callback(error, []), + ); + }; + + return guarded as unknown as LookupFunction; +} + +/** Throws a `refused` CalloutError for a URL no callout may reach. */ +export function assertCalloutDestination(target: string, env: EnvSource = process.env): URL { + const problem = calloutUrlProblem(target, env); + if (problem) throw new CalloutError('refused', `Callout URL ${problem}`); + return new URL(target); +} + +export type CalloutRequest = { + method?: 'GET' | 'POST'; + headers?: Record; + body?: string; + timeoutMs: number; + maxResponseBytes: number; +}; + +export type CalloutResponse = { + status: number; + headers: Record; + body: Buffer; +}; + +const USER_AGENT = 'seamless-auth-api'; + +/** + * One HTTP request to an adopter-supplied URL. Redirects are not followed: a 3xx comes back as a + * response, and the caller treats it as a failure, since following it would carry a signed body + * to a host that was never checked. + */ +export function calloutRequest( + target: string, + { method = 'POST', headers = {}, body, timeoutMs, maxResponseBytes }: CalloutRequest, + env: EnvSource = process.env, +): Promise { + let url: URL; + try { + url = assertCalloutDestination(target, env); + } catch (error) { + return Promise.reject(error); + } + + const send = url.protocol === 'https:' ? httpsRequest : httpRequest; + const outgoing: Record = { 'user-agent': USER_AGENT, ...headers }; + if (body !== undefined) outgoing['content-length'] = String(Buffer.byteLength(body)); + + return new Promise((resolve, reject) => { + let settled = false; + const fail = (error: CalloutError) => { + if (settled) return; + settled = true; + clearTimeout(timer); + request.destroy(); + reject(error); + }; + + const request = send( + url, + { method, headers: outgoing, lookup: calloutLookup(env) }, + (response) => { + const chunks: Buffer[] = []; + let size = 0; + + response.on('data', (chunk: Buffer) => { + size += chunk.length; + if (size > maxResponseBytes) { + fail(new CalloutError('too_large', 'Callout response is too large')); + return; + } + chunks.push(chunk); + }); + response.on('error', () => + fail(new CalloutError('connection_failed', 'Callout response failed')), + ); + response.on('end', () => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve({ + status: response.statusCode ?? 502, + headers: response.headers, + body: Buffer.concat(chunks), + }); + }); + }, + ); + + // A whole-request deadline rather than a socket idle timeout, so a destination that + // trickles a byte at a time cannot hold a sign-in open. + const timer = setTimeout( + () => fail(new CalloutError('timed_out', 'Callout timed out')), + timeoutMs, + ); + timer.unref(); + + request.on('error', (error: Error) => + fail( + error instanceof CalloutError + ? error + : new CalloutError('connection_failed', 'Callout connection failed'), + ), + ); + + request.end(body); + }); +} diff --git a/src/lib/oauthProviderPolicy.ts b/src/lib/oauthProviderPolicy.ts index 1f1048c2..82949d98 100644 --- a/src/lib/oauthProviderPolicy.ts +++ b/src/lib/oauthProviderPolicy.ts @@ -8,11 +8,12 @@ import type { LookupAddress } from 'node:dns'; import { lookup } from 'node:dns/promises'; import { request as httpRequest } from 'node:http'; import { request as httpsRequest } from 'node:https'; -import { BlockList, isIP, type LookupFunction } from 'node:net'; +import { isIP, type LookupFunction } from 'node:net'; import { missingOAuthProviderEndpoints } from '@seamless-auth/types'; import type { OAuthProviderConfig } from '../schemas/systemConfig.schema.js'; +import { inList, neverReachable, nonPublic, unmapIPv4 } from './outboundAddress.js'; import { sendProviderRequest } from './providerTransport.js'; type EnvSource = Record; @@ -30,88 +31,6 @@ export const PRIVATE_PROVIDER_HOSTS_ENV = 'OAUTH_PROVIDER_PRIVATE_HOSTS'; const PROVIDER_URL_FIELDS = ['authorizationUrl', 'tokenUrl', 'userInfoUrl', 'jwksUri'] as const; -const nonPublic = new BlockList(); -nonPublic.addSubnet('0.0.0.0', 8, 'ipv4'); -nonPublic.addSubnet('10.0.0.0', 8, 'ipv4'); -nonPublic.addSubnet('100.64.0.0', 10, 'ipv4'); -nonPublic.addSubnet('127.0.0.0', 8, 'ipv4'); -nonPublic.addSubnet('169.254.0.0', 16, 'ipv4'); -nonPublic.addSubnet('172.16.0.0', 12, 'ipv4'); -nonPublic.addSubnet('192.0.0.0', 24, 'ipv4'); -nonPublic.addSubnet('192.168.0.0', 16, 'ipv4'); -nonPublic.addSubnet('198.18.0.0', 15, 'ipv4'); -nonPublic.addSubnet('224.0.0.0', 3, 'ipv4'); -nonPublic.addAddress('::', 'ipv6'); -nonPublic.addAddress('::1', 'ipv6'); -nonPublic.addSubnet('64:ff9b:1::', 48, 'ipv6'); -nonPublic.addSubnet('fc00::', 7, 'ipv6'); -nonPublic.addSubnet('fe80::', 10, 'ipv6'); -nonPublic.addSubnet('ff00::', 8, 'ipv6'); - -// Never reachable, even for an allowlisted host: link-local carries cloud instance -// metadata, and the unspecified address means this machine. -const neverReachable = new BlockList(); -neverReachable.addSubnet('0.0.0.0', 8, 'ipv4'); -neverReachable.addSubnet('169.254.0.0', 16, 'ipv4'); -neverReachable.addAddress('::', 'ipv6'); -neverReachable.addSubnet('fe80::', 10, 'ipv6'); - -function unmapIPv4(address: string) { - const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address); - return mapped ? mapped[1] : address; -} - -function ipv6Hextets(address: string): number[] | null { - let text = address; - const dotted = /(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(text); - if (dotted) { - const [a, b, c, d] = dotted.slice(1).map(Number); - text = `${text.slice(0, dotted.index)}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`; - } - - const [head, tail] = text.split('::'); - const left = head ? head.split(':') : []; - const right = tail ? tail.split(':') : []; - const fill = text.includes('::') ? 8 - left.length - right.length : 0; - const parts = [...left, ...Array(fill).fill('0'), ...right].map((part) => - parseInt(part, 16), - ); - - return parts.length === 8 && parts.every((part) => part >= 0 && part <= 0xffff) ? parts : null; -} - -/** - * The IPv4 address an IPv6 address carries, for the forms a gateway turns back into - * IPv4: IPv4-mapped and IPv4-compatible, NAT64 (64:ff9b::/96) and 6to4 (2002::/16). - * Classifying only the IPv6 form would let `[64:ff9b::a9fe:a9fe]` reach 169.254.169.254 - * through a NAT64 gateway. - */ -function embeddedIPv4(address: string): string | null { - const h = ipv6Hextets(address); - if (!h) return null; - - const quad = (high: number, low: number) => - `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`; - const zeros = (from: number, to: number) => h.slice(from, to).every((part) => part === 0); - - if (zeros(0, 5) && h[5] === 0xffff) return quad(h[6], h[7]); - if (zeros(0, 6) && (h[6] !== 0 || h[7] > 1)) return quad(h[6], h[7]); - if (h[0] === 0x64 && h[1] === 0xff9b && zeros(2, 6)) return quad(h[6], h[7]); - if (h[0] === 0x2002) return quad(h[1], h[2]); - - return null; -} - -function inList(list: BlockList, address: string) { - const plain = unmapIPv4(address.replace(/^\[|\]$/g, '')); - const version = isIP(plain); - if (!version) return false; - if (version === 4) return list.check(plain, 'ipv4'); - - const carried = embeddedIPv4(plain); - return list.check(plain, 'ipv6') || (carried !== null && list.check(carried, 'ipv4')); -} - function addressAllowed(address: string, hostAllowlisted: boolean) { return !inList(neverReachable, address) && (hostAllowlisted || !inList(nonPublic, address)); } diff --git a/src/lib/outboundAddress.ts b/src/lib/outboundAddress.ts new file mode 100644 index 00000000..0638c440 --- /dev/null +++ b/src/lib/outboundAddress.ts @@ -0,0 +1,89 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import { BlockList, isIP } from 'node:net'; + +export const nonPublic = new BlockList(); +nonPublic.addSubnet('0.0.0.0', 8, 'ipv4'); +nonPublic.addSubnet('10.0.0.0', 8, 'ipv4'); +nonPublic.addSubnet('100.64.0.0', 10, 'ipv4'); +nonPublic.addSubnet('127.0.0.0', 8, 'ipv4'); +nonPublic.addSubnet('169.254.0.0', 16, 'ipv4'); +nonPublic.addSubnet('172.16.0.0', 12, 'ipv4'); +nonPublic.addSubnet('192.0.0.0', 24, 'ipv4'); +nonPublic.addSubnet('192.168.0.0', 16, 'ipv4'); +nonPublic.addSubnet('198.18.0.0', 15, 'ipv4'); +nonPublic.addSubnet('224.0.0.0', 3, 'ipv4'); +nonPublic.addAddress('::', 'ipv6'); +nonPublic.addAddress('::1', 'ipv6'); +nonPublic.addSubnet('64:ff9b:1::', 48, 'ipv6'); +nonPublic.addSubnet('fc00::', 7, 'ipv6'); +nonPublic.addSubnet('fe80::', 10, 'ipv6'); +nonPublic.addSubnet('ff00::', 8, 'ipv6'); + +// Never reachable, even for an allowlisted host: link-local carries cloud instance +// metadata, and the unspecified address means this machine. +export const neverReachable = new BlockList(); +neverReachable.addSubnet('0.0.0.0', 8, 'ipv4'); +neverReachable.addSubnet('169.254.0.0', 16, 'ipv4'); +neverReachable.addAddress('::', 'ipv6'); +neverReachable.addSubnet('fe80::', 10, 'ipv6'); + +export function unmapIPv4(address: string) { + const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address); + return mapped ? mapped[1] : address; +} + +function ipv6Hextets(address: string): number[] | null { + let text = address; + const dotted = /(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(text); + if (dotted) { + const [a, b, c, d] = dotted.slice(1).map(Number); + text = `${text.slice(0, dotted.index)}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`; + } + + const [head, tail] = text.split('::'); + const left = head ? head.split(':') : []; + const right = tail ? tail.split(':') : []; + const fill = text.includes('::') ? 8 - left.length - right.length : 0; + const parts = [...left, ...Array(fill).fill('0'), ...right].map((part) => + parseInt(part, 16), + ); + + return parts.length === 8 && parts.every((part) => part >= 0 && part <= 0xffff) ? parts : null; +} + +/** + * The IPv4 address an IPv6 address carries, for the forms a gateway turns back into + * IPv4: IPv4-mapped and IPv4-compatible, NAT64 (64:ff9b::/96) and 6to4 (2002::/16). + * Classifying only the IPv6 form would let `[64:ff9b::a9fe:a9fe]` reach 169.254.169.254 + * through a NAT64 gateway. + */ +function embeddedIPv4(address: string): string | null { + const h = ipv6Hextets(address); + if (!h) return null; + + const quad = (high: number, low: number) => + `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`; + const zeros = (from: number, to: number) => h.slice(from, to).every((part) => part === 0); + + if (zeros(0, 5) && h[5] === 0xffff) return quad(h[6], h[7]); + if (zeros(0, 6) && (h[6] !== 0 || h[7] > 1)) return quad(h[6], h[7]); + if (h[0] === 0x64 && h[1] === 0xff9b && zeros(2, 6)) return quad(h[6], h[7]); + if (h[0] === 0x2002) return quad(h[1], h[2]); + + return null; +} + +export function inList(list: BlockList, address: string) { + const plain = unmapIPv4(address.replace(/^\[|\]$/g, '')); + const version = isIP(plain); + if (!version) return false; + if (version === 4) return list.check(plain, 'ipv4'); + + const carried = embeddedIPv4(plain); + return list.check(plain, 'ipv6') || (carried !== null && list.check(carried, 'ipv4')); +} diff --git a/src/migrations/20261107120000-add-webhooks.cjs b/src/migrations/20261107120000-add-webhooks.cjs new file mode 100644 index 00000000..5885ad7f --- /dev/null +++ b/src/migrations/20261107120000-add-webhooks.cjs @@ -0,0 +1,93 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +'use strict'; + +/** + * Signed, retried webhooks (ADR 0005). Deliveries are made from committed audit rows, read past + * a cursor in `event_dispatch_cursors`, so an event is sent only once its row exists and none is + * lost between happening and being queued. A delivery's id is its `webhook-id`, and it stays the + * same across retries and redelivery. `(endpointId, authEventSeq)` is unique so that a dispatch + * repeated after a crash cannot queue the same event twice. + * + * @type {import('sequelize-cli').Migration} + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query(` + CREATE TABLE IF NOT EXISTS public.webhook_endpoints ( + id uuid NOT NULL, + url character varying(2048) NOT NULL, + description text, + "eventTypes" character varying(64)[] NOT NULL, + enabled boolean NOT NULL DEFAULT true, + "disabledReason" character varying(20), + version integer NOT NULL DEFAULT 1, + "secretCiphertext" text NOT NULL, + "secretIv" text NOT NULL, + "secretTag" text NOT NULL, + "previousSecretCiphertext" text, + "previousSecretIv" text, + "previousSecretTag" text, + "previousSecretExpiresAt" timestamp with time zone, + "failingSince" timestamp with time zone, + "createdBy" uuid, + "createdAt" timestamp with time zone NOT NULL, + "updatedAt" timestamp with time zone NOT NULL, + CONSTRAINT webhook_endpoints_pkey PRIMARY KEY (id), + CONSTRAINT webhook_endpoints_disabled_reason + CHECK ("disabledReason" IS NULL OR "disabledReason" IN ('gone', 'failing', 'manual')) + ); + + CREATE TABLE IF NOT EXISTS public.webhook_deliveries ( + id uuid NOT NULL, + "endpointId" uuid NOT NULL, + "eventType" character varying(64) NOT NULL, + "authEventSeq" bigint, + payload text NOT NULL, + status character varying(20) NOT NULL, + attempts integer NOT NULL DEFAULT 0, + "nextAttemptAt" timestamp with time zone, + "lastAttemptAt" timestamp with time zone, + "lastStatusCode" integer, + "lastFailure" character varying(32), + "createdAt" timestamp with time zone NOT NULL, + "updatedAt" timestamp with time zone NOT NULL, + CONSTRAINT webhook_deliveries_pkey PRIMARY KEY (id), + CONSTRAINT webhook_deliveries_endpoint_fkey + FOREIGN KEY ("endpointId") REFERENCES public.webhook_endpoints(id) ON DELETE CASCADE, + CONSTRAINT webhook_deliveries_status + CHECK (status IN ('pending', 'succeeded', 'failed', 'dead')), + CONSTRAINT webhook_deliveries_event_once UNIQUE ("endpointId", "authEventSeq") + ); + + CREATE INDEX IF NOT EXISTS webhook_deliveries_due_idx + ON public.webhook_deliveries ("nextAttemptAt") + WHERE status IN ('pending', 'failed'); + + CREATE INDEX IF NOT EXISTS webhook_deliveries_endpoint_created_idx + ON public.webhook_deliveries ("endpointId", "createdAt" DESC); + + CREATE INDEX IF NOT EXISTS webhook_deliveries_created_idx + ON public.webhook_deliveries ("createdAt"); + + CREATE TABLE IF NOT EXISTS public.event_dispatch_cursors ( + name character varying(100) NOT NULL, + "lastSeq" bigint NOT NULL, + "updatedAt" timestamp with time zone NOT NULL, + CONSTRAINT event_dispatch_cursors_pkey PRIMARY KEY (name) + ); + `); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query(` + DROP TABLE IF EXISTS public.webhook_deliveries; + DROP TABLE IF EXISTS public.webhook_endpoints; + DROP TABLE IF EXISTS public.event_dispatch_cursors; + `); + }, +}; diff --git a/src/models/webhookDeliveries.ts b/src/models/webhookDeliveries.ts new file mode 100644 index 00000000..8264e11d --- /dev/null +++ b/src/models/webhookDeliveries.ts @@ -0,0 +1,84 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import type { CalloutFailure, WebhookDeliveryStatus } from '@seamless-auth/types'; +import { DataTypes, Model, Optional, Sequelize } from 'sequelize'; + +export interface WebhookDeliveryAttributes { + /** The `webhook-id` header and the event's `id`. */ + id: string; + endpointId: string; + eventType: string; + /** The audit row the event came from. Null for a test event. */ + authEventSeq: string | null; + /** The exact body signed and sent, so a retry or redelivery sends the same bytes. */ + payload: string; + status: WebhookDeliveryStatus; + attempts: number; + nextAttemptAt: Date | null; + lastAttemptAt: Date | null; + lastStatusCode: number | null; + lastFailure: CalloutFailure | null; + createdAt?: Date; + updatedAt?: Date; +} + +type WebhookDeliveryCreationAttributes = Optional< + WebhookDeliveryAttributes, + | 'authEventSeq' + | 'attempts' + | 'nextAttemptAt' + | 'lastAttemptAt' + | 'lastStatusCode' + | 'lastFailure' + | 'createdAt' + | 'updatedAt' +>; + +export class WebhookDelivery + extends Model + implements WebhookDeliveryAttributes +{ + declare id: string; + declare endpointId: string; + declare eventType: string; + declare authEventSeq: string | null; + declare payload: string; + declare status: WebhookDeliveryStatus; + declare attempts: number; + declare nextAttemptAt: Date | null; + declare lastAttemptAt: Date | null; + declare lastStatusCode: number | null; + declare lastFailure: CalloutFailure | null; + declare readonly createdAt: Date; + declare readonly updatedAt: Date; +} + +const initializeWebhookDeliveryModel = (sequelize: Sequelize) => { + WebhookDelivery.init( + { + id: { type: DataTypes.UUID, primaryKey: true, allowNull: false }, + endpointId: { type: DataTypes.UUID, allowNull: false }, + eventType: { type: DataTypes.STRING(64), allowNull: false }, + authEventSeq: { type: DataTypes.BIGINT, allowNull: true }, + payload: { type: DataTypes.TEXT, allowNull: false }, + status: { type: DataTypes.STRING(20), allowNull: false }, + attempts: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 }, + nextAttemptAt: { type: DataTypes.DATE, allowNull: true }, + lastAttemptAt: { type: DataTypes.DATE, allowNull: true }, + lastStatusCode: { type: DataTypes.INTEGER, allowNull: true }, + lastFailure: { type: DataTypes.STRING(32), allowNull: true }, + }, + { + sequelize, + tableName: 'webhook_deliveries', + modelName: 'WebhookDelivery', + }, + ); + return WebhookDelivery; +}; + +export default initializeWebhookDeliveryModel; diff --git a/src/models/webhookEndpoints.ts b/src/models/webhookEndpoints.ts new file mode 100644 index 00000000..9ff68479 --- /dev/null +++ b/src/models/webhookEndpoints.ts @@ -0,0 +1,107 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import type { WebhookDisabledReason, WebhookEventType } from '@seamless-auth/types'; +import { DataTypes, Model, Optional, Sequelize } from 'sequelize'; + +export interface WebhookEndpointAttributes { + id: string; + url: string; + description: string | null; + eventTypes: WebhookEventType[]; + enabled: boolean; + disabledReason: WebhookDisabledReason | null; + version: number; + secretCiphertext: string; + secretIv: string; + secretTag: string; + previousSecretCiphertext: string | null; + previousSecretIv: string | null; + previousSecretTag: string | null; + previousSecretExpiresAt: Date | null; + /** When the current run of failed deliveries began. Cleared by any success. */ + failingSince: Date | null; + createdBy: string | null; + createdAt?: Date; + updatedAt?: Date; +} + +type WebhookEndpointCreationAttributes = Optional< + WebhookEndpointAttributes, + | 'id' + | 'description' + | 'enabled' + | 'disabledReason' + | 'version' + | 'previousSecretCiphertext' + | 'previousSecretIv' + | 'previousSecretTag' + | 'previousSecretExpiresAt' + | 'failingSince' + | 'createdBy' + | 'createdAt' + | 'updatedAt' +>; + +export class WebhookEndpoint + extends Model + implements WebhookEndpointAttributes +{ + declare id: string; + declare url: string; + declare description: string | null; + declare eventTypes: WebhookEventType[]; + declare enabled: boolean; + declare disabledReason: WebhookDisabledReason | null; + declare version: number; + declare secretCiphertext: string; + declare secretIv: string; + declare secretTag: string; + declare previousSecretCiphertext: string | null; + declare previousSecretIv: string | null; + declare previousSecretTag: string | null; + declare previousSecretExpiresAt: Date | null; + declare failingSince: Date | null; + declare createdBy: string | null; + declare readonly createdAt: Date; + declare readonly updatedAt: Date; +} + +const initializeWebhookEndpointModel = (sequelize: Sequelize) => { + WebhookEndpoint.init( + { + id: { + type: DataTypes.UUID, + primaryKey: true, + defaultValue: DataTypes.UUIDV4, + allowNull: false, + }, + url: { type: DataTypes.STRING(2048), allowNull: false }, + description: { type: DataTypes.TEXT, allowNull: true }, + eventTypes: { type: DataTypes.ARRAY(DataTypes.STRING(64)), allowNull: false }, + enabled: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true }, + disabledReason: { type: DataTypes.STRING(20), allowNull: true }, + version: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 1 }, + secretCiphertext: { type: DataTypes.TEXT, allowNull: false }, + secretIv: { type: DataTypes.TEXT, allowNull: false }, + secretTag: { type: DataTypes.TEXT, allowNull: false }, + previousSecretCiphertext: { type: DataTypes.TEXT, allowNull: true }, + previousSecretIv: { type: DataTypes.TEXT, allowNull: true }, + previousSecretTag: { type: DataTypes.TEXT, allowNull: true }, + previousSecretExpiresAt: { type: DataTypes.DATE, allowNull: true }, + failingSince: { type: DataTypes.DATE, allowNull: true }, + createdBy: { type: DataTypes.UUID, allowNull: true }, + }, + { + sequelize, + tableName: 'webhook_endpoints', + modelName: 'WebhookEndpoint', + }, + ); + return WebhookEndpoint; +}; + +export default initializeWebhookEndpointModel; diff --git a/src/routes/webhooks.routes.ts b/src/routes/webhooks.routes.ts new file mode 100644 index 00000000..b695fbbe --- /dev/null +++ b/src/routes/webhooks.routes.ts @@ -0,0 +1,209 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import { + createWebhook, + deleteWebhook, + getWebhook, + getWebhookDelivery, + listWebhookDeliveries, + listWebhooks, + redeliverWebhook, + rotateWebhookSecret, + testWebhook, + updateWebhook, +} from '../controllers/webhooks.js'; +import { createRouter } from '../lib/createRouter.js'; +import { requireAdmin } from '../middleware/requireAdmin.js'; +import { requireStepUp } from '../middleware/requireStepUp.js'; +import { ErrorSchema, MessageSchema } from '../schemas/generic.responses.js'; +import { StepUpRequiredErrorSchema } from '../schemas/stepUp.responses.js'; +import { + CalloutTestResponseSchema, + CreateWebhookEndpointRequestSchema, + UpdateWebhookEndpointRequestSchema, + WebhookDeliveryIdParamSchema, + WebhookDeliveryListResponseSchema, + WebhookDeliveryQuerySchema, + WebhookDeliveryResponseSchema, + WebhookEndpointCreatedResponseSchema, + WebhookEndpointIdParamSchema, + WebhookEndpointListResponseSchema, + WebhookEndpointResponseSchema, + WebhookSecretRotatedResponseSchema, +} from '../schemas/webhook.schemas.js'; + +/** + * Signed, retried webhooks (ADR 0005). Sending a test event and redelivering are writes: each + * makes a signed request to a URL an administrator chose, so they take step-up like the rest. + */ +const router = createRouter('/admin'); + +const tags = ['Admin', 'Webhooks']; +const read = { auth: 'access', tags, middleware: [requireAdmin('read')] }; +const write = { auth: 'access', tags, middleware: [requireAdmin('write'), requireStepUp()] }; + +router.get( + '/webhooks', + { + ...read, + summary: 'List webhook endpoints', + schemas: { response: { 200: WebhookEndpointListResponseSchema } }, + }, + listWebhooks, +); + +router.post( + '/webhooks', + { + ...write, + summary: 'Create a webhook endpoint', + description: 'Returns the signing secret once. It cannot be read back.', + schemas: { + body: CreateWebhookEndpointRequestSchema, + response: { + 201: WebhookEndpointCreatedResponseSchema, + 400: ErrorSchema, + 403: StepUpRequiredErrorSchema, + 409: ErrorSchema, + }, + }, + }, + createWebhook, +); + +router.get( + '/webhooks/:id', + { + ...read, + summary: 'Get a webhook endpoint', + schemas: { + params: WebhookEndpointIdParamSchema, + response: { 200: WebhookEndpointResponseSchema, 404: ErrorSchema }, + }, + }, + getWebhook, +); + +router.patch( + '/webhooks/:id', + { + ...write, + summary: 'Update a webhook endpoint', + description: 'Turning an endpoint back on clears why it was disabled.', + schemas: { + params: WebhookEndpointIdParamSchema, + body: UpdateWebhookEndpointRequestSchema, + response: { + 200: WebhookEndpointResponseSchema, + 400: ErrorSchema, + 403: StepUpRequiredErrorSchema, + 404: ErrorSchema, + }, + }, + }, + updateWebhook, +); + +router.delete( + '/webhooks/:id', + { + ...write, + summary: 'Delete a webhook endpoint', + description: 'Also deletes its delivery history.', + schemas: { + params: WebhookEndpointIdParamSchema, + response: { 200: MessageSchema, 403: StepUpRequiredErrorSchema, 404: ErrorSchema }, + }, + }, + deleteWebhook, +); + +router.post( + '/webhooks/:id/secret', + { + ...write, + summary: 'Rotate a webhook signing secret', + description: + 'Returns the new secret once. The previous one keeps signing beside it for 24 hours.', + schemas: { + params: WebhookEndpointIdParamSchema, + response: { + 200: WebhookSecretRotatedResponseSchema, + 403: StepUpRequiredErrorSchema, + 404: ErrorSchema, + 409: ErrorSchema, + }, + }, + }, + rotateWebhookSecret, +); + +router.post( + '/webhooks/:id/test', + { + ...write, + summary: 'Send a test event', + description: 'Sends `webhook.test` once, now, whatever the endpoint subscribes to.', + schemas: { + params: WebhookEndpointIdParamSchema, + response: { + 200: CalloutTestResponseSchema, + 403: StepUpRequiredErrorSchema, + 404: ErrorSchema, + }, + }, + }, + testWebhook, +); + +router.get( + '/webhook-deliveries', + { + ...read, + summary: 'List webhook deliveries', + description: 'Newest first. `status=dead` is the dead letter view. Kept for 30 days.', + schemas: { + query: WebhookDeliveryQuerySchema, + response: { 200: WebhookDeliveryListResponseSchema, 400: ErrorSchema }, + }, + }, + listWebhookDeliveries, +); + +router.get( + '/webhook-deliveries/:deliveryId', + { + ...read, + summary: 'Get a webhook delivery and its event', + schemas: { + params: WebhookDeliveryIdParamSchema, + response: { 200: WebhookDeliveryResponseSchema, 404: ErrorSchema }, + }, + }, + getWebhookDelivery, +); + +router.post( + '/webhook-deliveries/:deliveryId/redeliver', + { + ...write, + summary: 'Redeliver a webhook', + description: + 'One attempt now, with the same `webhook-id` and body and a fresh timestamp and signature.', + schemas: { + params: WebhookDeliveryIdParamSchema, + response: { + 200: WebhookDeliveryResponseSchema, + 403: StepUpRequiredErrorSchema, + 404: ErrorSchema, + }, + }, + }, + redeliverWebhook, +); + +export default router.router; diff --git a/src/schemas/authEvent.types.ts b/src/schemas/authEvent.types.ts index 0b565e29..7fdd5568 100644 --- a/src/schemas/authEvent.types.ts +++ b/src/schemas/authEvent.types.ts @@ -137,6 +137,13 @@ export const AUTH_EVENT_TYPES = [ 'webauthn_registration_challenge', 'webauthn_registration_failed', 'webauthn_registration_suspicious', + 'admin_webhook_created', + 'admin_webhook_deleted', + 'admin_webhook_redelivered', + 'admin_webhook_secret_rotated', + 'admin_webhook_updated', + 'session_created', + 'webhook_endpoint_disabled', ] as const; export const AuthEventTypeEnum = z.enum(AUTH_EVENT_TYPES); diff --git a/src/schemas/webhook.schemas.ts b/src/schemas/webhook.schemas.ts new file mode 100644 index 00000000..6c27382b --- /dev/null +++ b/src/schemas/webhook.schemas.ts @@ -0,0 +1,20 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +export { + CalloutTestResponseSchema, + CreateWebhookEndpointRequestSchema, + UpdateWebhookEndpointRequestSchema, + WebhookDeliveryIdParamSchema, + WebhookDeliveryListResponseSchema, + WebhookDeliveryQuerySchema, + WebhookDeliveryResponseSchema, + WebhookEndpointCreatedResponseSchema, + WebhookEndpointIdParamSchema, + WebhookEndpointListResponseSchema, + WebhookEndpointResponseSchema, + WebhookSecretRotatedResponseSchema, +} from '@seamless-auth/types'; diff --git a/src/server.ts b/src/server.ts index 307295db..326fb403 100644 --- a/src/server.ts +++ b/src/server.ts @@ -15,6 +15,7 @@ import { assertServiceTokenConfig } from './config/serviceToken.js'; import { connectToDb } from './db.js'; import { initializeModels } from './models/index.js'; import { TotpCredential } from './models/totpCredentials.js'; +import { WebhookEndpoint } from './models/webhookEndpoints.js'; import { startAuditMaintenance } from './services/auditRetention.js'; import { warnOnBreakGlassMisconfiguration } from './services/breakGlassService.js'; import { initializeMetadataService } from './services/metadataServiceBootstrap.js'; @@ -23,6 +24,7 @@ import { startBackchannelLogoutSweep } from './services/oidcBackchannelLogout.js import { startOidcPayloadPurge } from './services/oidcPayloadStore.js'; import { recordBootstrapPolicyVersion } from './services/policyVersionService.js'; import { assertSchemaCurrent } from './services/schemaGuard.js'; +import { startWebhookDelivery } from './services/webhookService.js'; import getLogger from './utils/logger.js'; import { initDevSigningKey } from './utils/signingKeyStore.js'; @@ -46,7 +48,10 @@ async function startServer() { await recordBootstrapPolicyVersion(); // After bootstrap, since which secrets are needed depends on the stored config. - assertAuthSecrets(await getSystemConfig(), (await TotpCredential.count()) > 0); + assertAuthSecrets(await getSystemConfig(), { + totpCredentialsExist: (await TotpCredential.count()) > 0, + calloutSecretsExist: (await WebhookEndpoint.count()) > 0, + }); await warnOnBreakGlassMisconfiguration(); // After config is bootstrapped, since it decides whether attestation is @@ -67,6 +72,7 @@ async function startServer() { startAuditMaintenance(); startOidcPayloadPurge(); startBackchannelLogoutSweep(); + startWebhookDelivery(); } catch (err) { logger.error('Failed to start server:', err); process.exit(1); diff --git a/src/services/oidcClientRegistry.ts b/src/services/oidcClientRegistry.ts index a3bd4b52..adfe14ff 100644 --- a/src/services/oidcClientRegistry.ts +++ b/src/services/oidcClientRegistry.ts @@ -220,5 +220,6 @@ export async function getOidcAccountClaims(userId: string): Promise | null; + created_at: Date; +}; + +export type WebhookSubject = { email: string | null; phone: string | null }; + +export type WebhookEventBody = Extract; + +type Built = { type: WebhookEventType; data: WebhookEventBody['data'] }; + +const SESSION_REVOKED: Readonly> = { + logout_success: 'logout', + admin_session_revoked: 'admin', + session_evicted: 'evicted', + oidc_session_revoked: 'provider', +}; + +const ORGANIZATION_MEMBER: Readonly> = { + organization_member_added: 'organization.member_added', + organization_member_updated: 'organization.member_updated', + organization_member_removed: 'organization.member_removed', +}; + +function text(value: unknown): string | null { + return typeof value === 'string' && value ? value : null; +} + +function strings(value: unknown): string[] { + return Array.isArray(value) + ? value.filter((item): item is string => typeof item === 'string') + : []; +} + +/** + * Which audit types become which webhook (ADR 0005, D3). The audit types are internal and many; + * the webhook catalog is a public contract, so this table is the whole mapping and + * `tests/unit/services/webhookCatalog.spec.ts` pins it. An audit type added later reaches no + * receiver until it is added here. + */ +export const WEBHOOK_SOURCE_TYPES: Readonly> = { + user_created: 'user.created', + user_deleted: 'user.deleted', + session_created: 'user.signed_in', + account_recovery_completed: 'user.recovered', + logout_success: 'session.revoked', + admin_session_revoked: 'session.revoked', + session_evicted: 'session.revoked', + oidc_session_revoked: 'session.revoked', + registration_success: 'credential.added', + totp_enrollment_success: 'credential.added', + recovery_codes_generated: 'credential.added', + credentials_deleted: 'credential.removed', + totp_disabled: 'credential.removed', + organization_member_added: 'organization.member_added', + organization_member_updated: 'organization.member_updated', + organization_member_removed: 'organization.member_removed', +}; + +function credentialKind(event: DispatchableAuthEvent): CredentialKind | null { + switch (event.type) { + case 'totp_enrollment_success': + case 'totp_disabled': + return 'totp'; + case 'recovery_codes_generated': + return 'recovery_codes'; + default: + // `registration_success` is also written when an account is registered, and + // `credentials_deleted` when an account is deleted. Only the rows that name a passkey are + // about a credential. + return event.metadata?.credential === 'passkey' ? 'passkey' : null; + } +} + +/** + * The session a revocation is about. For a sign-out and a provider revocation that is the session + * the request came from. An administrator's revocation and an eviction name it in metadata, + * because the request's own session is the administrator's or the new one. Signing out everywhere + * names no single session. + */ +function revokedSessionId(event: DispatchableAuthEvent): string | null { + switch (event.type) { + case 'logout_success': + return event.metadata?.scope === 'current_session' ? event.session_id : null; + case 'oidc_session_revoked': + return event.session_id; + default: + return text(event.metadata?.sessionId); + } +} + +/** + * The webhook an audit row becomes, or null when it becomes none. `subject` is read from the + * user at dispatch, for `user.created`, which carries the address the account was made with. + */ +export function webhookEventFor( + event: DispatchableAuthEvent, + subject: WebhookSubject | null, +): Built | null { + const type = WEBHOOK_SOURCE_TYPES[event.type]; + if (!type) return null; + + const userId = event.user_id; + + switch (type) { + case 'user.created': + return userId + ? { + type, + data: { userId, email: subject?.email ?? null, phone: subject?.phone ?? null }, + } + : null; + case 'user.deleted': + case 'user.recovered': + return userId ? { type, data: { userId } } : null; + case 'user.signed_in': + return userId + ? { + type, + data: { + userId, + sessionId: event.session_id, + method: text(event.metadata?.method), + organizationId: text(event.metadata?.organizationId), + }, + } + : null; + case 'session.revoked': + return { + type, + data: { + userId, + sessionId: revokedSessionId(event), + reason: SESSION_REVOKED[event.type], + }, + }; + case 'credential.added': + case 'credential.removed': { + const kind = credentialKind(event); + return userId && kind + ? { type, data: { userId, kind, credentialId: text(event.metadata?.credentialId) } } + : null; + } + default: { + const organizationId = text(event.metadata?.organizationId); + if (!userId || !organizationId || !ORGANIZATION_MEMBER[event.type]) return null; + return { + type, + data: { + organizationId, + userId, + roles: event.type === 'organization_member_removed' ? [] : strings(event.metadata?.roles), + }, + }; + } + } +} diff --git a/src/services/webhookService.ts b/src/services/webhookService.ts new file mode 100644 index 00000000..37e77171 --- /dev/null +++ b/src/services/webhookService.ts @@ -0,0 +1,683 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import { randomUUID } from 'node:crypto'; + +import { + type CalloutFailure, + type CalloutTestResponse, + type CreateWebhookEndpointRequest, + type UpdateWebhookEndpointRequest, + WEBHOOK_FAILING_DISABLE_SECONDS, + WEBHOOK_PAYLOAD_VERSION, + WEBHOOK_RETRY_SCHEDULE_SECONDS, + WEBHOOK_SECRET_ROTATION_OVERLAP_SECONDS, + WEBHOOK_TEST_EVENT_TYPE, + WEBHOOK_TIMEOUT_MS, + type WebhookDeliveryQuery, + type WebhookDeliveryStatus, + type WebhookEventType, +} from '@seamless-auth/types'; +import { fn, Op, QueryTypes, type Transaction, type WhereOptions } from 'sequelize'; + +import { productionSecretMissing } from '../config/authSecrets.js'; +import { + decryptCalloutSecret, + encryptCalloutSecret, + generateCalloutSecret, + signedCalloutHeaders, +} from '../lib/calloutSigning.js'; +import { CalloutError, calloutRequest, calloutUrlProblem } from '../lib/calloutTransport.js'; +import { getSequelize } from '../models/index.js'; +import { User } from '../models/users.js'; +import { WebhookDelivery, type WebhookDeliveryAttributes } from '../models/webhookDeliveries.js'; +import { WebhookEndpoint } from '../models/webhookEndpoints.js'; +import getLogger from '../utils/logger.js'; +import { AuthEventService } from './authEventService.js'; +import { + type DispatchableAuthEvent, + WEBHOOK_SOURCE_TYPES, + webhookEventFor, +} from './webhookCatalog.js'; + +const logger = getLogger('webhooks'); + +export class WebhookError extends Error { + constructor( + readonly status: number, + message: string, + ) { + super(message); + this.name = 'WebhookError'; + } +} + +// A receiver only needs to say yes or no, so its body is read for the status alone. +const MAX_RESPONSE_BYTES = 64 * 1024; +const DISPATCH_BATCH = 500; +const DELIVERY_BATCH = 50; +const DELIVERY_RETENTION_DAYS = 30; +const CURSOR_NAME = 'webhooks'; +// Distinct from the audit maintenance lock, so the two never wait on each other. +const DISPATCH_LOCK_KEY = 72_641_002; + +function now() { + return new Date(); +} + +function addSeconds(at: Date, seconds: number) { + return new Date(at.getTime() + seconds * 1000); +} + +export function serializeEndpoint(endpoint: WebhookEndpoint) { + const rotating = + endpoint.previousSecretExpiresAt && endpoint.previousSecretExpiresAt > now() + ? endpoint.previousSecretExpiresAt.toISOString() + : null; + + return { + id: endpoint.id, + url: endpoint.url, + description: endpoint.description ?? null, + eventTypes: endpoint.eventTypes, + enabled: endpoint.enabled, + disabledReason: endpoint.disabledReason ?? null, + version: WEBHOOK_PAYLOAD_VERSION, + previousSecretExpiresAt: rotating, + createdAt: endpoint.createdAt.toISOString(), + updatedAt: endpoint.updatedAt.toISOString(), + }; +} + +export function serializeDelivery(delivery: WebhookDelivery) { + return { + id: delivery.id, + endpointId: delivery.endpointId, + eventType: delivery.eventType, + status: delivery.status, + attempts: delivery.attempts, + nextAttemptAt: delivery.nextAttemptAt?.toISOString() ?? null, + lastAttemptAt: delivery.lastAttemptAt?.toISOString() ?? null, + lastStatusCode: delivery.lastStatusCode ?? null, + lastFailure: delivery.lastFailure ?? null, + createdAt: delivery.createdAt.toISOString(), + }; +} + +function assertUrl(url: string) { + const problem = calloutUrlProblem(url); + if (problem) throw new WebhookError(400, `url ${problem}`); +} + +function assertSecretKey() { + if (productionSecretMissing('CALLOUT_SECRET_ENCRYPTION_KEY')) { + throw new WebhookError( + 409, + 'CALLOUT_SECRET_ENCRYPTION_KEY must be set before a webhook can be created', + ); + } +} + +function secretColumns(secret: string) { + const { ciphertext, iv, tag } = encryptCalloutSecret(secret); + return { secretCiphertext: ciphertext, secretIv: iv, secretTag: tag }; +} + +/** Every secret that signs right now: the current one, and the previous one while it overlaps. */ +export function signingSecrets(endpoint: WebhookEndpoint, at: Date = now()): string[] { + const secrets = [ + decryptCalloutSecret({ + ciphertext: endpoint.secretCiphertext, + iv: endpoint.secretIv, + tag: endpoint.secretTag, + }), + ]; + + if ( + endpoint.previousSecretCiphertext && + endpoint.previousSecretIv && + endpoint.previousSecretTag && + endpoint.previousSecretExpiresAt && + endpoint.previousSecretExpiresAt > at + ) { + secrets.push( + decryptCalloutSecret({ + ciphertext: endpoint.previousSecretCiphertext, + iv: endpoint.previousSecretIv, + tag: endpoint.previousSecretTag, + }), + ); + } + + return secrets; +} + +export async function listEndpoints() { + return WebhookEndpoint.findAll({ order: [['createdAt', 'ASC']] }); +} + +export async function getEndpoint(id: string) { + const endpoint = await WebhookEndpoint.findByPk(id); + if (!endpoint) throw new WebhookError(404, 'Webhook not found'); + return endpoint; +} + +export async function createEndpoint( + input: CreateWebhookEndpointRequest, + actorUserId: string | null, +) { + assertUrl(input.url); + assertSecretKey(); + + const secret = generateCalloutSecret(); + const endpoint = await WebhookEndpoint.create({ + url: input.url, + description: input.description ?? null, + eventTypes: input.eventTypes, + enabled: input.enabled ?? true, + createdBy: actorUserId, + ...secretColumns(secret), + }); + + return { endpoint, secret }; +} + +export async function updateEndpoint(id: string, input: UpdateWebhookEndpointRequest) { + const endpoint = await getEndpoint(id); + if (input.url !== undefined) assertUrl(input.url); + const reenabling = input.enabled === true && !endpoint.enabled; + + await endpoint.update({ + ...(input.url !== undefined ? { url: input.url } : {}), + ...(input.description !== undefined ? { description: input.description } : {}), + ...(input.eventTypes !== undefined ? { eventTypes: input.eventTypes } : {}), + ...(input.enabled !== undefined + ? { + enabled: input.enabled, + disabledReason: input.enabled ? null : 'manual', + failingSince: null, + } + : {}), + }); + + // Releases what was held while it was off. Deliveries are pruned after 30 days, so that is how + // far back a catch-up reaches. A dead delivery stays dead; redeliver sends it. + const released = reenabling + ? ( + await WebhookDelivery.update( + // The database's clock, which the due check compares against, so a skewed app clock + // cannot leave released deliveries not yet due. + { nextAttemptAt: fn('now') as unknown as Date }, + { + where: { + endpointId: endpoint.id, + status: { [Op.in]: ['pending', 'failed'] }, + nextAttemptAt: null, + }, + }, + ) + )[0] + : 0; + + return { endpoint, released }; +} + +export async function deleteEndpoint(id: string) { + const endpoint = await getEndpoint(id); + await endpoint.destroy(); + return endpoint; +} + +/** + * The old secret keeps signing for a day beside the new one, so receivers move over without a + * dropped delivery. Rotating again within that day ends the old secret's overlap early: only two + * secrets ever sign. + */ +export async function rotateEndpointSecret(id: string) { + assertSecretKey(); + const endpoint = await getEndpoint(id); + const secret = generateCalloutSecret(); + const previousSecretExpiresAt = addSeconds(now(), WEBHOOK_SECRET_ROTATION_OVERLAP_SECONDS); + + await endpoint.update({ + previousSecretCiphertext: endpoint.secretCiphertext, + previousSecretIv: endpoint.secretIv, + previousSecretTag: endpoint.secretTag, + previousSecretExpiresAt, + ...secretColumns(secret), + }); + + return { endpoint, secret, previousSecretExpiresAt }; +} + +function body(id: string, type: string, timestamp: Date, data: unknown) { + return JSON.stringify({ + id, + type, + version: WEBHOOK_PAYLOAD_VERSION, + timestamp: timestamp.toISOString(), + data, + }); +} + +type Attempt = { + ok: boolean; + statusCode: number | null; + failure: CalloutFailure | null; + retryAfterSeconds: number | null; + durationMs: number; +}; + +function retryAfter(header: string | string[] | undefined): number | null { + const value = Array.isArray(header) ? header[0] : header; + if (!value) return null; + const seconds = Number(value); + if (Number.isFinite(seconds) && seconds >= 0) return seconds; + const date = Date.parse(value); + return Number.isNaN(date) ? null : Math.max(0, (date - Date.now()) / 1000); +} + +/** One signed POST. Anything but a 2xx is a failure, including a redirect, which is not followed. */ +export async function sendSigned( + url: string, + id: string, + payload: string, + secrets: string[], + timeoutMs: number = WEBHOOK_TIMEOUT_MS, +): Promise { + const started = Date.now(); + try { + const response = await calloutRequest(url, { + method: 'POST', + headers: signedCalloutHeaders(id, payload, secrets), + body: payload, + timeoutMs, + maxResponseBytes: MAX_RESPONSE_BYTES, + }); + const ok = response.status >= 200 && response.status < 300; + + return { + ok, + statusCode: response.status, + failure: ok ? null : 'http_status', + retryAfterSeconds: retryAfter(response.headers['retry-after']), + durationMs: Date.now() - started, + }; + } catch (error) { + return { + ok: false, + statusCode: null, + failure: error instanceof CalloutError ? error.failure : 'connection_failed', + retryAfterSeconds: null, + durationMs: Date.now() - started, + }; + } +} + +/** + * When the next attempt is due, or null when there is none and the delivery is dead. A + * `Retry-After` longer than the schedule's own delay is honored, up to the schedule's longest. + */ +export function nextAttemptAt(attempts: number, at: Date, retryAfterSeconds: number | null) { + const scheduled = WEBHOOK_RETRY_SCHEDULE_SECONDS[attempts]; + if (scheduled === undefined) return null; + + const longest = WEBHOOK_RETRY_SCHEDULE_SECONDS[WEBHOOK_RETRY_SCHEDULE_SECONDS.length - 1]; + const wait = Math.max(scheduled, Math.min(retryAfterSeconds ?? 0, longest)); + // Up to 10% later, so endpoints that failed together do not retry together. + return addSeconds(at, wait * (1 + Math.random() * 0.1)); +} + +async function recordOutcome( + delivery: WebhookDelivery, + endpoint: WebhookEndpoint, + attempt: Attempt, +) { + const at = now(); + const attempts = delivery.attempts + 1; + const next = attempt.ok ? null : nextAttemptAt(attempts, at, attempt.retryAfterSeconds); + const status: WebhookDeliveryStatus = attempt.ok ? 'succeeded' : next ? 'failed' : 'dead'; + + await delivery.update({ + status, + attempts, + nextAttemptAt: next, + lastAttemptAt: at, + lastStatusCode: attempt.statusCode, + lastFailure: attempt.failure, + }); + + if (attempt.ok) { + if (endpoint.failingSince) await endpoint.update({ failingSince: null }); + return; + } + + // 410 is the receiver saying the endpoint is gone for good. + if (attempt.statusCode === 410) { + await disableEndpoint(endpoint, 'gone'); + return; + } + + const failingSince = endpoint.failingSince ?? at; + if (at.getTime() - failingSince.getTime() >= WEBHOOK_FAILING_DISABLE_SECONDS * 1000) { + await disableEndpoint(endpoint, 'failing'); + } else if (!endpoint.failingSince) { + await endpoint.update({ failingSince }); + } +} + +async function disableEndpoint(endpoint: WebhookEndpoint, reason: 'gone' | 'failing') { + if (!endpoint.enabled) return; + await endpoint.update({ enabled: false, disabledReason: reason }); + logger.warn(`Webhook ${endpoint.id} disabled: ${reason}`); + await AuthEventService.logContext({ + type: 'webhook_endpoint_disabled', + metadata: { endpointId: endpoint.id, reason }, + }); +} + +export async function attemptDelivery(delivery: WebhookDelivery, endpoint: WebhookEndpoint) { + const attempt = await sendSigned( + endpoint.url, + delivery.id, + delivery.payload, + signingSecrets(endpoint), + ); + await recordOutcome(delivery, endpoint, attempt); + return attempt; +} + +/** Sends `webhook.test` to one endpoint now, whatever it subscribes to, and logs it as a delivery. */ +export async function sendTestEvent(id: string): Promise { + const endpoint = await getEndpoint(id); + const deliveryId = randomUUID(); + const delivery = await WebhookDelivery.create({ + id: deliveryId, + endpointId: endpoint.id, + eventType: WEBHOOK_TEST_EVENT_TYPE, + payload: body(deliveryId, WEBHOOK_TEST_EVENT_TYPE, now(), { endpointId: endpoint.id }), + status: 'pending', + nextAttemptAt: null, + }); + + const attempt = await sendSigned( + endpoint.url, + delivery.id, + delivery.payload, + signingSecrets(endpoint), + ); + // A test is one attempt: it is never retried and never disables the endpoint. + await delivery.update({ + status: attempt.ok ? 'succeeded' : 'dead', + attempts: 1, + lastAttemptAt: now(), + lastStatusCode: attempt.statusCode, + lastFailure: attempt.failure, + }); + + return { + ok: attempt.ok, + failure: attempt.failure, + statusCode: attempt.statusCode, + durationMs: attempt.durationMs, + }; +} + +export async function getDelivery(deliveryId: string) { + const delivery = await WebhookDelivery.findByPk(deliveryId); + if (!delivery) throw new WebhookError(404, 'Delivery not found'); + return delivery; +} + +/** + * One attempt now, with the same `webhook-id` and body and a fresh timestamp and signature, so a + * receiver that already has the event can drop it. + */ +export async function redeliver(deliveryId: string) { + const delivery = await getDelivery(deliveryId); + const endpoint = await getEndpoint(delivery.endpointId); + await attemptDelivery(delivery, endpoint); + return delivery; +} + +function encodeCursor(delivery: WebhookDelivery) { + return Buffer.from(`${delivery.createdAt.toISOString()}|${delivery.id}`).toString('base64url'); +} + +function decodeCursor(cursor: string): { createdAt: Date; id: string } { + const [createdAt, id] = Buffer.from(cursor, 'base64url').toString('utf8').split('|'); + const at = new Date(createdAt); + if (!id || Number.isNaN(at.getTime())) throw new WebhookError(400, 'Invalid cursor'); + return { createdAt: at, id }; +} + +export async function listDeliveries(query: WebhookDeliveryQuery) { + const conditions: WhereOptions[] = []; + if (query.endpointId) conditions.push({ endpointId: query.endpointId }); + if (query.status) conditions.push({ status: query.status }); + if (query.eventType) conditions.push({ eventType: query.eventType }); + if (query.cursor) { + const { createdAt, id } = decodeCursor(query.cursor); + conditions.push({ + [Op.or]: [{ createdAt: { [Op.lt]: createdAt } }, { createdAt, id: { [Op.lt]: id } }], + }); + } + + const rows = await WebhookDelivery.findAll({ + where: conditions.length ? { [Op.and]: conditions } : {}, + order: [ + ['createdAt', 'DESC'], + ['id', 'DESC'], + ], + limit: query.limit + 1, + }); + + const page = rows.slice(0, query.limit); + return { + deliveries: page, + nextCursor: rows.length > query.limit ? encodeCursor(page[page.length - 1]) : null, + }; +} + +type CursorRow = { lastSeq: string }; +type HeadRow = { head: string }; + +async function subjectFor(event: DispatchableAuthEvent, transaction: Transaction) { + if (WEBHOOK_SOURCE_TYPES[event.type] !== 'user.created' || !event.user_id) return null; + const user = await User.findByPk(event.user_id, { + attributes: ['email', 'phone'], + transaction, + }); + return user ? { email: user.email ?? null, phone: user.phone ?? null } : null; +} + +/** + * Turns committed audit rows past the cursor into deliveries (ADR 0005, D2). Rows are read by + * `seq`, and the chain trigger holds the chain head row from insert to commit, so committed rows + * always form a gapless prefix: a cursor never steps past a row still to commit. On first run the + * cursor starts at the newest row, so turning webhooks on does not replay history. + * + * Returns how many audit rows were read, so the loop knows whether to run again at once. + */ +export async function dispatchWebhooks(): Promise { + const sequelize = getSequelize(); + + return sequelize.transaction(async (transaction) => { + const [{ locked }] = await sequelize.query<{ locked: boolean }>( + 'SELECT pg_try_advisory_xact_lock(:key) AS locked', + { replacements: { key: DISPATCH_LOCK_KEY }, type: QueryTypes.SELECT, transaction }, + ); + if (!locked) return 0; + + const [cursor] = await sequelize.query( + 'SELECT "lastSeq" FROM public.event_dispatch_cursors WHERE name = :name', + { replacements: { name: CURSOR_NAME }, type: QueryTypes.SELECT, transaction }, + ); + + if (!cursor) { + const [{ head }] = await sequelize.query( + 'SELECT coalesce(max(seq), 0) AS head FROM public.auth_events', + { type: QueryTypes.SELECT, transaction }, + ); + await sequelize.query( + 'INSERT INTO public.event_dispatch_cursors (name, "lastSeq", "updatedAt") VALUES (:name, :head, now())', + { replacements: { name: CURSOR_NAME, head }, transaction }, + ); + return 0; + } + + const rows = await sequelize.query( + `SELECT seq, type, user_id, session_id, metadata, created_at + FROM public.auth_events + WHERE seq > :last + ORDER BY seq + LIMIT :limit`, + { + replacements: { last: cursor.lastSeq, limit: DISPATCH_BATCH }, + type: QueryTypes.SELECT, + transaction, + }, + ); + if (rows.length === 0) return 0; + + // Disabled endpoints get their deliveries too, held with no attempt due, so turning one back + // on catches it up instead of losing what happened while it was off (ADR 0005, E4). + const endpoints = await WebhookEndpoint.findAll({ transaction }); + + for (const row of rows) { + const subscribed = endpoints.filter((endpoint) => + endpoint.eventTypes.includes(WEBHOOK_SOURCE_TYPES[row.type] as WebhookEventType), + ); + if (subscribed.length === 0) continue; + + const event = webhookEventFor(row, await subjectFor(row, transaction)); + if (!event) continue; + + for (const endpoint of subscribed) { + const id = randomUUID(); + await sequelize.query( + `INSERT INTO public.webhook_deliveries + (id, "endpointId", "eventType", "authEventSeq", payload, status, attempts, + "nextAttemptAt", "createdAt", "updatedAt") + VALUES (:id, :endpointId, :eventType, :seq, :payload, 'pending', 0, + CASE WHEN :held THEN NULL ELSE now() END, now(), now()) + ON CONFLICT ("endpointId", "authEventSeq") DO NOTHING`, + { + replacements: { + id, + endpointId: endpoint.id, + held: !endpoint.enabled, + eventType: event.type, + seq: row.seq, + payload: body(id, event.type, new Date(row.created_at), event.data), + }, + transaction, + }, + ); + } + } + + await sequelize.query( + 'UPDATE public.event_dispatch_cursors SET "lastSeq" = :seq, "updatedAt" = now() WHERE name = :name', + { replacements: { seq: rows[rows.length - 1].seq, name: CURSOR_NAME }, transaction }, + ); + + return rows.length; + }); +} + +/** + * Claims due deliveries and sends them. A claim pushes `nextAttemptAt` past the request timeout + * inside a short transaction with SKIP LOCKED, so two replicas never send the same attempt and a + * replica that dies mid-send leaves the delivery due again shortly after. + */ +export async function deliverDue(): Promise { + const sequelize = getSequelize(); + const lease = addSeconds(now(), WEBHOOK_TIMEOUT_MS / 1000 + 30); + + const claimed = await sequelize.transaction(async (transaction) => { + const rows = await sequelize.query<{ id: string }>( + `SELECT id FROM public.webhook_deliveries + WHERE status IN ('pending', 'failed') AND "nextAttemptAt" <= now() + ORDER BY "nextAttemptAt" + LIMIT :limit + FOR UPDATE SKIP LOCKED`, + { replacements: { limit: DELIVERY_BATCH }, type: QueryTypes.SELECT, transaction }, + ); + if (rows.length === 0) return []; + + const ids = rows.map((row) => row.id); + await WebhookDelivery.update( + { nextAttemptAt: lease }, + { where: { id: { [Op.in]: ids } }, transaction }, + ); + return ids; + }); + + if (claimed.length === 0) return 0; + + const deliveries = await WebhookDelivery.findAll({ where: { id: { [Op.in]: claimed } } }); + const endpoints = new Map( + ( + await WebhookEndpoint.findAll({ + where: { id: { [Op.in]: [...new Set(deliveries.map((d) => d.endpointId))] } }, + }) + ).map((endpoint) => [endpoint.id, endpoint]), + ); + + await Promise.all( + deliveries.map(async (delivery) => { + const endpoint = endpoints.get(delivery.endpointId); + // Disabled after it was queued: hold the delivery until the endpoint is turned back on. + if (!endpoint || !endpoint.enabled) { + await delivery.update({ nextAttemptAt: null }); + return; + } + await attemptDelivery(delivery, endpoint); + }), + ); + + return claimed.length; +} + +export async function pruneDeliveries(at: Date = now()) { + return WebhookDelivery.destroy({ + where: { createdAt: { [Op.lt]: addSeconds(at, -DELIVERY_RETENTION_DAYS * 24 * 60 * 60) } }, + }); +} + +const TICK_MS = 1000; +const PRUNE_EVERY_TICKS = 3600; + +/** One pass of dispatch and delivery. Errors are logged, not thrown, so the loop keeps running. */ +export async function runWebhookTick(tick: number) { + try { + while ((await dispatchWebhooks()) === DISPATCH_BATCH) { + // A full batch means more rows are waiting. + } + while ((await deliverDue()) === DELIVERY_BATCH) { + // Likewise for due deliveries. + } + if (tick % PRUNE_EVERY_TICKS === 0) await pruneDeliveries(); + } catch (error) { + logger.error(`Webhook tick failed: ${(error as Error).message}`); + } +} + +/** Polls once a second. The loop is cheap when idle: two indexed reads. */ +export function startWebhookDelivery() { + let tick = 0; + let running = false; + const timer = setInterval(() => { + if (running) return; + running = true; + void runWebhookTick(tick++).finally(() => { + running = false; + }); + }, TICK_MS); + timer.unref(); + return timer; +} diff --git a/tests/integration/admin/adminStepUp.spec.ts b/tests/integration/admin/adminStepUp.spec.ts index 7f36f542..ad7dd745 100644 --- a/tests/integration/admin/adminStepUp.spec.ts +++ b/tests/integration/admin/adminStepUp.spec.ts @@ -43,6 +43,12 @@ const GUARDED = [ 'PATCH /admin/permissions/{permissionName}', 'DELETE /admin/permissions/{permissionName}', 'PUT /admin/roles/{kind}/{roleName}/permissions', + 'POST /admin/webhooks', + 'PATCH /admin/webhooks/{id}', + 'DELETE /admin/webhooks/{id}', + 'POST /admin/webhooks/{id}/secret', + 'POST /admin/webhooks/{id}/test', + 'POST /admin/webhook-deliveries/{deliveryId}/redeliver', 'POST /admin/users', 'POST /admin/users/import', 'DELETE /admin/users', diff --git a/tests/integration/admin/webhooks.spec.ts b/tests/integration/admin/webhooks.spec.ts new file mode 100644 index 00000000..25c6272c --- /dev/null +++ b/tests/integration/admin/webhooks.spec.ts @@ -0,0 +1,274 @@ +import { Application } from 'express'; +import request from 'supertest'; +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('../../../src/lib/calloutTransport.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, calloutRequest: vi.fn() }; +}); + +import { createApp } from '../../../src/app'; +import { calloutRequest } from '../../../src/lib/calloutTransport.js'; +import { encryptCalloutSecret } from '../../../src/lib/calloutSigning.js'; +import { Session } from '../../../src/models/sessions.js'; +import { WebhookDelivery } from '../../../src/models/webhookDeliveries.js'; +import { WebhookEndpoint } from '../../../src/models/webhookEndpoints.js'; +import { AuthEventService } from '../../../src/services/authEventService.js'; +import { buildFreshStepUpSession } from '../../factories/sessionFactory'; + +let app: Application; + +const now = new Date('2026-11-07T12:00:00.000Z'); +const endpointId = '5b8a1c2d-3e4f-4a5b-8c6d-7e8f9a0b1c2d'; +const deliveryId = '6c9b2d3e-4f5a-4b6c-9d7e-8f9a0b1c2d3e'; + +function buildEndpoint(overrides: Record = {}) { + const sealed = encryptCalloutSecret('whsec_' + Buffer.alloc(32, 2).toString('base64')); + const record: any = { + id: endpointId, + url: 'https://hooks.example.com/seamless', + description: null, + eventTypes: ['user.created'], + enabled: true, + disabledReason: null, + version: 1, + secretCiphertext: sealed.ciphertext, + secretIv: sealed.iv, + secretTag: sealed.tag, + previousSecretCiphertext: null, + previousSecretIv: null, + previousSecretTag: null, + previousSecretExpiresAt: null, + failingSince: null, + createdAt: now, + updatedAt: now, + ...overrides, + }; + record.update = vi.fn(async (values: Record) => Object.assign(record, values)); + record.destroy = vi.fn(); + return record; +} + +function buildDelivery(overrides: Record = {}) { + const record: any = { + id: deliveryId, + endpointId, + eventType: 'user.created', + authEventSeq: '10', + payload: JSON.stringify({ + id: deliveryId, + type: 'user.created', + version: 1, + timestamp: now.toISOString(), + data: { userId: 'u', email: null, phone: null }, + }), + status: 'dead', + attempts: 8, + nextAttemptAt: null, + lastAttemptAt: now, + lastStatusCode: 500, + lastFailure: 'http_status', + createdAt: now, + ...overrides, + }; + record.update = vi.fn(async (values: Record) => Object.assign(record, values)); + return record; +} + +beforeAll(async () => { + app = await createApp(); +}); + +beforeEach(() => { + vi.clearAllMocks(); + (Session.findOne as any).mockResolvedValue(buildFreshStepUpSession()); +}); + +describe('webhook endpoints', () => { + it('lists endpoints without their secrets', async () => { + vi.mocked(WebhookEndpoint.findAll).mockResolvedValue([buildEndpoint()]); + + const res = await request(app).get('/admin/webhooks'); + + expect(res.status).toBe(200); + expect(res.body.endpoints[0]).toMatchObject({ id: endpointId, version: 1 }); + expect(JSON.stringify(res.body)).not.toMatch(/secret(Ciphertext|Iv|Tag)|whsec_/); + }); + + it('creates an endpoint, returns the secret once and audits it', async () => { + vi.mocked(WebhookEndpoint.create).mockImplementation(async (values: any) => + buildEndpoint(values), + ); + + const res = await request(app) + .post('/admin/webhooks') + .send({ url: 'https://hooks.example.com/a?token=abc', eventTypes: ['user.created'] }); + + expect(res.status).toBe(201); + expect(res.body.secret).toMatch(/^whsec_/); + // The audit log is permanent, so a token in the query string must not reach it. + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'admin_webhook_created', + metadata: expect.objectContaining({ url: 'https://hooks.example.com/a' }), + }), + ); + }); + + it('refuses a URL pointing at the cloud metadata address', async () => { + const res = await request(app) + .post('/admin/webhooks') + .send({ url: 'http://169.254.169.254/latest', eventTypes: ['user.created'] }); + + expect(res.status).toBe(400); + expect(res.body.error).toContain('never reachable'); + expect(WebhookEndpoint.create).not.toHaveBeenCalled(); + }); + + it('refuses an unknown event type and the test type', async () => { + for (const eventTypes of [['user.renamed'], ['webhook.test']]) { + const res = await request(app) + .post('/admin/webhooks') + .send({ url: 'https://hooks.example.com/a', eventTypes }); + expect(res.status).toBe(400); + } + }); + + it('reads, updates and deletes an endpoint, auditing each write', async () => { + const record = buildEndpoint(); + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(record); + + expect((await request(app).get(`/admin/webhooks/${endpointId}`)).status).toBe(200); + + const updated = await request(app) + .patch(`/admin/webhooks/${endpointId}`) + .send({ enabled: false }); + expect(updated.status).toBe(200); + expect(updated.body.endpoint).toMatchObject({ enabled: false, disabledReason: 'manual' }); + + const deleted = await request(app).delete(`/admin/webhooks/${endpointId}`); + expect(deleted.status).toBe(200); + expect(record.destroy).toHaveBeenCalled(); + + const types = vi.mocked(AuthEventService.log).mock.calls.map(([options]) => options.type); + expect(types).toEqual(['admin_webhook_updated', 'admin_webhook_deleted']); + }); + + it('records how many held deliveries turning an endpoint back on released', async () => { + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue( + buildEndpoint({ enabled: false, disabledReason: 'gone' }), + ); + vi.mocked(WebhookDelivery.update).mockResolvedValue([2] as never); + + const res = await request(app).patch(`/admin/webhooks/${endpointId}`).send({ enabled: true }); + + expect(res.status).toBe(200); + expect(res.body.endpoint).toMatchObject({ enabled: true, disabledReason: null }); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'admin_webhook_updated', + metadata: expect.objectContaining({ releasedDeliveries: 2 }), + }), + ); + }); + + it('answers 404 for an endpoint that does not exist', async () => { + for (const send of [ + () => request(app).get(`/admin/webhooks/${endpointId}`), + () => request(app).patch(`/admin/webhooks/${endpointId}`).send({ enabled: true }), + () => request(app).delete(`/admin/webhooks/${endpointId}`), + () => request(app).post(`/admin/webhooks/${endpointId}/secret`), + () => request(app).post(`/admin/webhooks/${endpointId}/test`), + ]) { + expect((await send()).status).toBe(404); + } + }); + + it('rotates the secret and returns the new one', async () => { + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(buildEndpoint()); + + const res = await request(app).post(`/admin/webhooks/${endpointId}/secret`); + + expect(res.status).toBe(200); + expect(res.body.secret).toMatch(/^whsec_/); + expect(res.body.previousSecretExpiresAt).toBeDefined(); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ type: 'admin_webhook_secret_rotated' }), + ); + }); + + it('sends a test event and reports the result', async () => { + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(buildEndpoint()); + vi.mocked(WebhookDelivery.create).mockImplementation(async (values: any) => + buildDelivery(values), + ); + vi.mocked(calloutRequest).mockResolvedValue({ + status: 200, + headers: {}, + body: Buffer.alloc(0), + }); + + const res = await request(app).post(`/admin/webhooks/${endpointId}/test`); + + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ ok: true, failure: null, statusCode: 200 }); + }); +}); + +describe('webhook deliveries', () => { + it('lists deliveries, filtered to dead letters', async () => { + vi.mocked(WebhookDelivery.findAll).mockResolvedValue([buildDelivery()]); + + const res = await request(app).get('/admin/webhook-deliveries?status=dead'); + + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ deliveries: [{ id: deliveryId }], nextCursor: null }); + }); + + it('refuses a cursor it did not issue', async () => { + const res = await request(app).get('/admin/webhook-deliveries?cursor=nope'); + + expect(res.status).toBe(400); + }); + + it('shows a delivery with its event', async () => { + vi.mocked(WebhookDelivery.findByPk).mockResolvedValue(buildDelivery()); + + const res = await request(app).get(`/admin/webhook-deliveries/${deliveryId}`); + + expect(res.status).toBe(200); + expect(res.body.delivery.event).toMatchObject({ type: 'user.created', id: deliveryId }); + }); + + it('redelivers and audits it', async () => { + const record = buildDelivery(); + vi.mocked(WebhookDelivery.findByPk).mockResolvedValue(record); + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(buildEndpoint()); + vi.mocked(calloutRequest).mockResolvedValue({ + status: 202, + headers: {}, + body: Buffer.alloc(0), + }); + + const res = await request(app).post(`/admin/webhook-deliveries/${deliveryId}/redeliver`); + + expect(res.status).toBe(200); + expect(res.body.delivery).toMatchObject({ status: 'succeeded', attempts: 9 }); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ type: 'admin_webhook_redelivered' }), + ); + }); + + it('answers 404 for a delivery that does not exist', async () => { + expect((await request(app).get(`/admin/webhook-deliveries/${deliveryId}`)).status).toBe(404); + expect( + (await request(app).post(`/admin/webhook-deliveries/${deliveryId}/redeliver`)).status, + ).toBe(404); + }); + + it('rethrows an unexpected error', async () => { + vi.mocked(WebhookDelivery.findAll).mockRejectedValue(new Error('database down')); + + expect((await request(app).get('/admin/webhook-deliveries')).status).toBe(500); + }); +}); diff --git a/tests/integration/oidc/oidcEdge.spec.ts b/tests/integration/oidc/oidcEdge.spec.ts index bdd37254..d47cf6aa 100644 --- a/tests/integration/oidc/oidcEdge.spec.ts +++ b/tests/integration/oidc/oidcEdge.spec.ts @@ -406,7 +406,7 @@ describe('keys, clients and accounts', () => { }); it('returns account claims only for the user behind a grant-bound session', async () => { - const claims = { sub: USER, roles: [], org_id: null }; + const claims = { sub: USER, roles: [], org_id: null, customClaims: {} }; const path = `/oidc/accounts/${USER}?clientId=app&sessionId=${SESSION}`; vi.mocked(findGrantBoundSession).mockResolvedValue({ id: SESSION, userId: USER } as never); vi.mocked(getOidcAccountClaims).mockResolvedValueOnce(claims); diff --git a/tests/integration/organizations/organizationRoleSecurity.spec.ts b/tests/integration/organizations/organizationRoleSecurity.spec.ts index c0ec26d8..bfa8aebb 100644 --- a/tests/integration/organizations/organizationRoleSecurity.spec.ts +++ b/tests/integration/organizations/organizationRoleSecurity.spec.ts @@ -209,6 +209,7 @@ describe('organization membership audit', () => { userId: memberId, metadata: { organizationId: testOrganizationId, + roles: ['admin'], rolesAdded: ['admin'], rolesRemoved: ['member'], }, diff --git a/tests/integration/user/user.spec.ts b/tests/integration/user/user.spec.ts index 83ca1370..19b16713 100644 --- a/tests/integration/user/user.spec.ts +++ b/tests/integration/user/user.spec.ts @@ -6,6 +6,7 @@ import { createApp } from '../../../src/app'; import { Credential } from '../../../src/models/credentials.js'; import { Session } from '../../../src/models/sessions.js'; import { User } from '../../../src/models/users.js'; +import { AuthEventService } from '../../../src/services/authEventService.js'; import { buildCredential } from '../../factories/credentialFactory.js'; import { buildFreshStepUpSession } from '../../factories/sessionFactory.js'; @@ -177,6 +178,26 @@ describe('DELETE /users/credentials', () => { expect(cred.destroy).toHaveBeenCalled(); }); + // Removing a passkey changes what the account can sign in with, so it has to leave an + // audit record, and the credential.removed webhook is built from it. + it('audits the removal of a passkey', async () => { + const cred = buildCredential(); + + (Credential.findOne as any).mockResolvedValue(cred); + (Credential.count as any).mockResolvedValue(2); + + const res = await request(app).delete('/users/credentials').send({ id: 'cred-1' }); + + expect(res.status).toBe(200); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + userId: 'user-1', + type: 'credentials_deleted', + metadata: expect.objectContaining({ credential: 'passkey', credentialId: cred.id }), + }), + ); + }); + it('rejects deleting last credential', async () => { const cred = buildCredential(); diff --git a/tests/postgres/webhooks.spec.ts b/tests/postgres/webhooks.spec.ts new file mode 100644 index 00000000..2e1fa8c7 --- /dev/null +++ b/tests/postgres/webhooks.spec.ts @@ -0,0 +1,175 @@ +import { createServer, type IncomingHttpHeaders, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import { getSequelize, initializeModels } from '../../src/models/index.js'; +import { WebhookDelivery } from '../../src/models/webhookDeliveries.js'; +import { WebhookEndpoint } from '../../src/models/webhookEndpoints.js'; +import { AuthEventService } from '../../src/services/authEventService.js'; +import { + createEndpoint, + deliverDue, + dispatchWebhooks, + updateEndpoint, +} from '../../src/services/webhookService.js'; + +let server: Server; +let port: number; +const received: { headers: IncomingHttpHeaders; body: string }[] = []; +let answer = 200; + +beforeAll(async () => { + await initializeModels(); + + server = createServer((req, res) => { + let body = ''; + req.on('data', (chunk) => (body += chunk)); + req.on('end', () => { + received.push({ headers: req.headers, body }); + res.statusCode = answer; + res.end(); + }); + }); + await new Promise((done) => server.listen(0, '127.0.0.1', done)); + port = (server.address() as AddressInfo).port; +}); + +beforeEach(async () => { + received.length = 0; + answer = 200; + await getSequelize().query( + 'DELETE FROM webhook_deliveries; DELETE FROM webhook_endpoints; DELETE FROM event_dispatch_cursors;', + ); +}); + +afterAll(async () => { + server.closeAllConnections(); + await new Promise((done) => server.close(() => done())); + await getSequelize().close(); +}); + +async function logEvent(type: string, userId: string, metadata: Record = {}) { + await AuthEventService.logContext({ type: type as never, userId, metadata }); +} + +describe('webhook dispatch against the audit chain', () => { + it('starts after the newest event, then delivers each new one once, signed', async () => { + const { secret } = await createEndpoint( + { url: `http://127.0.0.1:${port}/hook`, eventTypes: ['user.deleted'] }, + null, + ); + + // Before the cursor exists: history is not replayed. + await logEvent('user_deleted', '11111111-1111-4111-8111-111111111111'); + expect(await dispatchWebhooks()).toBe(0); + + await logEvent('user_deleted', '22222222-2222-4222-8222-222222222222'); + await logEvent('login_failed', '22222222-2222-4222-8222-222222222222'); + expect(await dispatchWebhooks()).toBe(2); + // Running again finds nothing new and queues nothing twice. + expect(await dispatchWebhooks()).toBe(0); + + const deliveries = await WebhookDelivery.findAll(); + expect(deliveries).toHaveLength(1); + + expect(await deliverDue()).toBe(1); + expect(received).toHaveLength(1); + + const [{ headers, body }] = received; + expect(JSON.parse(body)).toMatchObject({ + id: deliveries[0].id, + type: 'user.deleted', + data: { userId: '22222222-2222-4222-8222-222222222222' }, + }); + expect(headers['webhook-id']).toBe(deliveries[0].id); + expect(headers['webhook-signature']).toMatch(/^v1,/); + expect(secret).toMatch(/^whsec_/); + + await deliveries[0].reload(); + expect(deliveries[0]).toMatchObject({ status: 'succeeded', attempts: 1 }); + }); + + it('cannot queue the same audit row twice for one endpoint', async () => { + const { endpoint } = await createEndpoint( + { url: `http://127.0.0.1:${port}/hook`, eventTypes: ['user.deleted'] }, + null, + ); + const insert = () => + getSequelize().query( + `INSERT INTO webhook_deliveries (id, "endpointId", "eventType", "authEventSeq", payload, + status, attempts, "createdAt", "updatedAt") + VALUES (gen_random_uuid(), :endpointId, 'user.deleted', 7, '{}', 'pending', 0, now(), now()) + ON CONFLICT ("endpointId", "authEventSeq") DO NOTHING`, + { replacements: { endpointId: endpoint.id } }, + ); + + await insert(); + await insert(); + + expect(await WebhookDelivery.count()).toBe(1); + }); + + it('schedules a retry after a failure and holds the lease from a second worker', async () => { + await createEndpoint( + { url: `http://127.0.0.1:${port}/hook`, eventTypes: ['user.deleted'] }, + null, + ); + await dispatchWebhooks(); + await logEvent('user_deleted', '33333333-3333-4333-8333-333333333333'); + await dispatchWebhooks(); + + answer = 503; + expect(await deliverDue()).toBe(1); + // Not due again until the schedule says so. + expect(await deliverDue()).toBe(0); + + const [delivery] = await WebhookDelivery.findAll(); + expect(delivery).toMatchObject({ status: 'failed', attempts: 1, lastStatusCode: 503 }); + expect(delivery.nextAttemptAt!.getTime()).toBeGreaterThan(Date.now()); + + const [endpoint] = await WebhookEndpoint.findAll(); + expect(endpoint.failingSince).not.toBeNull(); + }); + + it('holds events for a disabled endpoint and delivers them once it is turned back on', async () => { + const { endpoint } = await createEndpoint( + { url: `http://127.0.0.1:${port}/hook`, eventTypes: ['user.deleted'] }, + null, + ); + await dispatchWebhooks(); + await updateEndpoint(endpoint.id, { enabled: false }); + + await logEvent('user_deleted', '55555555-5555-4555-8555-555555555555'); + await dispatchWebhooks(); + + // Queued, but nothing is due while the endpoint is off. + expect(await WebhookDelivery.count()).toBe(1); + expect(await deliverDue()).toBe(0); + expect(received).toHaveLength(0); + + const { released } = await updateEndpoint(endpoint.id, { enabled: true }); + expect(released).toBe(1); + + expect(await deliverDue()).toBe(1); + expect(received).toHaveLength(1); + expect(JSON.parse(received[0].body)).toMatchObject({ + type: 'user.deleted', + data: { userId: '55555555-5555-4555-8555-555555555555' }, + }); + }); + + it('deletes an endpoint with its deliveries', async () => { + const { endpoint } = await createEndpoint( + { url: `http://127.0.0.1:${port}/hook`, eventTypes: ['user.deleted'] }, + null, + ); + await dispatchWebhooks(); + await logEvent('user_deleted', '44444444-4444-4444-8444-444444444444'); + await dispatchWebhooks(); + + await endpoint.destroy(); + + expect(await WebhookDelivery.count()).toBe(0); + }); +}); diff --git a/tests/setup/mocks.ts b/tests/setup/mocks.ts index f19ca2b8..23b647e2 100644 --- a/tests/setup/mocks.ts +++ b/tests/setup/mocks.ts @@ -193,6 +193,25 @@ vi.mock('../../src/models/permissions.js', () => ({ }, })); +vi.mock('../../src/models/webhookEndpoints.js', () => ({ + WebhookEndpoint: { + create: vi.fn(), + findAll: vi.fn(async () => []), + findByPk: vi.fn(async () => null), + count: vi.fn(async () => 0), + }, +})); + +vi.mock('../../src/models/webhookDeliveries.js', () => ({ + WebhookDelivery: { + create: vi.fn(), + findAll: vi.fn(async () => []), + findByPk: vi.fn(async () => null), + update: vi.fn(), + destroy: vi.fn(async () => 0), + }, +})); + vi.mock('../../src/models/rolePermissions.js', () => ({ RolePermission: { sequelize: { @@ -359,6 +378,7 @@ vi.mock('bcrypt-ts', () => ({ vi.mock('../../src/services/authEventService.js', () => ({ AuthEventService: { log: vi.fn(), + logContext: vi.fn(), notificationSent: vi.fn(), refreshTokenFailed: vi.fn(), requestSuspicious: vi.fn(), diff --git a/tests/unit/config/authSecrets.spec.ts b/tests/unit/config/authSecrets.spec.ts index b439ade4..ee3a7465 100644 --- a/tests/unit/config/authSecrets.spec.ts +++ b/tests/unit/config/authSecrets.spec.ts @@ -28,6 +28,7 @@ describe('authSecret', () => { ); expect(authSecret('TOTP_SECRET_ENCRYPTION_KEY', {})).toBe('dev-totp-secret:local:local'); expect(authSecret('OAUTH_STATE_SECRET', {})).toBe('dev-oauth-state:local'); + expect(authSecret('CALLOUT_SECRET_ENCRYPTION_KEY', {})).toBe('dev-callout-secret:local:local'); expect(authSecret('DECOY_SUBJECT_SECRET', {})).toBe('dev-decoy-subject:local'); }); }); @@ -51,6 +52,48 @@ describe('authSecretsRequiredBy', () => { }); }); +describe('the callout secret key', () => { + it('is needed once a webhook or login hook stores a signing secret', () => { + expect( + authSecretsRequiredBy( + { oauth_providers: [] }, + { totpCredentialsExist: false, calloutSecretsExist: true }, + ), + ).toContain('CALLOUT_SECRET_ENCRYPTION_KEY'); + expect( + authSecretsRequiredBy({ oauth_providers: [] }, { totpCredentialsExist: false }), + ).not.toContain('CALLOUT_SECRET_ENCRYPTION_KEY'); + }); +}); + +describe('assertAuthSecrets for the callout key', () => { + const production = { + NODE_ENV: 'production', + REFRESH_TOKEN_LOOKUP_SECRET: 'a', + DECOY_SUBJECT_SECRET: 'b', + }; + + it('refuses to start without it once webhooks exist, and does not suggest the service token', () => { + expect(() => + assertAuthSecrets( + { oauth_providers: [] }, + { totpCredentialsExist: false, calloutSecretsExist: true }, + production, + ), + ).toThrow(/Restore the value they were created with/); + }); + + it('starts with it set', () => { + expect(() => + assertAuthSecrets( + { oauth_providers: [] }, + { totpCredentialsExist: false, calloutSecretsExist: true }, + { ...production, CALLOUT_SECRET_ENCRYPTION_KEY: 'c' }, + ), + ).not.toThrow(); + }); +}); + describe('productionSecretMissing', () => { it('is true only in production without the secret', () => { expect(productionSecretMissing('OAUTH_STATE_SECRET', production)).toBe(true); @@ -63,28 +106,44 @@ describe('productionSecretMissing', () => { describe('assertAuthSecrets', () => { it('passes outside production and when everything needed is set', () => { - expect(() => assertAuthSecrets({ oauth_providers: [provider] }, true, {})).not.toThrow(); expect(() => - assertAuthSecrets({ oauth_providers: [] }, false, { - ...production, - REFRESH_TOKEN_LOOKUP_SECRET: 'a', - DECOY_SUBJECT_SECRET: 'b', - }), + assertAuthSecrets({ oauth_providers: [provider] }, { totpCredentialsExist: true }, {}), + ).not.toThrow(); + expect(() => + assertAuthSecrets( + { oauth_providers: [] }, + { totpCredentialsExist: false }, + { + ...production, + REFRESH_TOKEN_LOOKUP_SECRET: 'a', + DECOY_SUBJECT_SECRET: 'b', + }, + ), ).not.toThrow(); }); it('names every missing secret and how to keep existing data valid', () => { - expect(() => assertAuthSecrets({ oauth_providers: [provider] }, true, production)).toThrow( + expect(() => + assertAuthSecrets( + { oauth_providers: [provider] }, + { totpCredentialsExist: true }, + production, + ), + ).toThrow( /REFRESH_TOKEN_LOOKUP_SECRET, DECOY_SUBJECT_SECRET, TOTP_SECRET_ENCRYPTION_KEY, OAUTH_STATE_SECRET are not set[\s\S]*current SEAMLESS_SERVICE_TOKEN value/, ); }); it('uses the singular for one missing secret', () => { expect(() => - assertAuthSecrets({ oauth_providers: [] }, false, { - ...production, - REFRESH_TOKEN_LOOKUP_SECRET: 'a', - }), + assertAuthSecrets( + { oauth_providers: [] }, + { totpCredentialsExist: false }, + { + ...production, + REFRESH_TOKEN_LOOKUP_SECRET: 'a', + }, + ), ).toThrow('DECOY_SUBJECT_SECRET is not set'); }); }); diff --git a/tests/unit/lib/calloutSigning.spec.ts b/tests/unit/lib/calloutSigning.spec.ts new file mode 100644 index 00000000..98da1ab0 --- /dev/null +++ b/tests/unit/lib/calloutSigning.spec.ts @@ -0,0 +1,115 @@ +import { createHmac, timingSafeEqual } from 'node:crypto'; + +import { CalloutSecretSchema } from '@seamless-auth/types'; +import { describe, expect, it, vi } from 'vitest'; + +import { + calloutSignature, + decryptCalloutSecret, + encryptCalloutSecret, + generateCalloutSecret, + signedCalloutHeaders, +} from '../../../src/lib/calloutSigning.js'; + +// The shared setup makes randomBytes constant, and these tests need distinct secrets. +vi.unmock('crypto'); + +/** A receiver's check, written from the Standard Webhooks spec rather than from our signer. */ +function verifies(secret: string, id: string, timestamp: string, body: string, header: string) { + const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64'); + const expected = createHmac('sha256', key).update(`${id}.${timestamp}.${body}`).digest(); + + return header.split(' ').some((entry) => { + const [version, signature] = entry.split(','); + const given = Buffer.from(signature ?? '', 'base64'); + return version === 'v1' && given.length === expected.length && timingSafeEqual(given, expected); + }); +} + +describe('callout secrets', () => { + it('generates a whsec_ secret of 32 random bytes', () => { + const secret = generateCalloutSecret(); + + expect(CalloutSecretSchema.safeParse(secret).success).toBe(true); + expect(generateCalloutSecret()).not.toBe(secret); + }); + + it('round-trips through encryption at rest', () => { + const secret = generateCalloutSecret(); + const sealed = encryptCalloutSecret(secret); + + expect(sealed.ciphertext).not.toContain(secret.slice(6)); + expect(decryptCalloutSecret(sealed)).toBe(secret); + }); + + it('refuses a ciphertext that was tampered with', () => { + const sealed = encryptCalloutSecret(generateCalloutSecret()); + const flipped = Buffer.from(sealed.ciphertext, 'base64'); + flipped[0] ^= 1; + + expect(() => + decryptCalloutSecret({ ...sealed, ciphertext: flipped.toString('base64') }), + ).toThrow(); + }); + + it('cannot be read under another key', () => { + const sealed = encryptCalloutSecret(generateCalloutSecret()); + vi.stubEnv('CALLOUT_SECRET_ENCRYPTION_KEY', 'a different key'); + + expect(() => decryptCalloutSecret(sealed)).toThrow(); + }); +}); + +describe('signedCalloutHeaders', () => { + const body = '{"type":"user.created"}'; + const at = new Date('2026-11-07T12:00:00.000Z'); + + it('signs id, timestamp and body the way a Standard Webhooks receiver checks them', () => { + const secret = generateCalloutSecret(); + const headers = signedCalloutHeaders('msg_1', body, [secret], at); + + expect(headers['content-type']).toBe('application/json'); + expect(headers['webhook-id']).toBe('msg_1'); + expect(headers['webhook-timestamp']).toBe(String(at.getTime() / 1000)); + expect( + verifies(secret, 'msg_1', headers['webhook-timestamp'], body, headers['webhook-signature']), + ).toBe(true); + }); + + it('does not verify a changed body, id or timestamp', () => { + const secret = generateCalloutSecret(); + const headers = signedCalloutHeaders('msg_1', body, [secret], at); + const ts = headers['webhook-timestamp']; + const signature = headers['webhook-signature']; + + expect(verifies(secret, 'msg_1', ts, `${body} `, signature)).toBe(false); + expect(verifies(secret, 'msg_2', ts, body, signature)).toBe(false); + expect(verifies(secret, 'msg_1', String(Number(ts) + 1), body, signature)).toBe(false); + expect(verifies(generateCalloutSecret(), 'msg_1', ts, body, signature)).toBe(false); + }); + + it('signs with both secrets while one rotates, so either verifies', () => { + const current = generateCalloutSecret(); + const previous = generateCalloutSecret(); + const headers = signedCalloutHeaders('msg_1', body, [current, previous], at); + const ts = headers['webhook-timestamp']; + + expect(headers['webhook-signature'].split(' ')).toHaveLength(2); + expect(verifies(current, 'msg_1', ts, body, headers['webhook-signature'])).toBe(true); + expect(verifies(previous, 'msg_1', ts, body, headers['webhook-signature'])).toBe(true); + }); + + it('defaults the timestamp to now', () => { + vi.useFakeTimers({ now: at }); + try { + const headers = signedCalloutHeaders('msg_1', body, [generateCalloutSecret()]); + expect(headers['webhook-timestamp']).toBe(String(at.getTime() / 1000)); + } finally { + vi.useRealTimers(); + } + }); + + it('formats one signature as v1 and base64', () => { + expect(calloutSignature('a', 1, 'b', generateCalloutSecret())).toMatch(/^v1,[A-Za-z0-9+/]+=*$/); + }); +}); diff --git a/tests/unit/lib/calloutTransport.spec.ts b/tests/unit/lib/calloutTransport.spec.ts new file mode 100644 index 00000000..a2f35574 --- /dev/null +++ b/tests/unit/lib/calloutTransport.spec.ts @@ -0,0 +1,311 @@ +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { + CALLOUT_PRIVATE_HOSTS_ENV, + CalloutError, + calloutHostProblem, + calloutLookup, + calloutRequest, + calloutUrlProblem, +} from '../../../src/lib/calloutTransport.js'; + +const production = { NODE_ENV: 'production', ISSUER: 'https://auth.example.com' }; +const development = { NODE_ENV: 'development', ISSUER: 'http://localhost:5312' }; + +let server: Server | null = null; + +async function serve(handler: Parameters[1]) { + server = createServer(handler); + await new Promise((done) => server!.listen(0, '127.0.0.1', done)); + return (server.address() as AddressInfo).port; +} + +afterEach(async () => { + if (server) { + server.closeAllConnections(); + await new Promise((done) => server!.close(() => done())); + server = null; + } +}); + +async function failureOf(promise: Promise) { + try { + await promise; + } catch (error) { + expect(error).toBeInstanceOf(CalloutError); + return (error as CalloutError).failure; + } + throw new Error('expected the callout to fail'); +} + +describe('calloutUrlProblem', () => { + it.each([ + ['not a url', 'is not a valid URL'], + ['ftp://hooks.example.com/', 'must use https'], + ['http://hooks.example.com/', 'must use https'], + ['https://user:pass@hooks.example.com/', 'must not carry a username or password'], + ['https://auth.example.com/hooks', 'must not point at this server'], + ['https://127.0.0.1/hook', `list the host in ${CALLOUT_PRIVATE_HOSTS_ENV}`], + ['https://10.0.0.5/hook', `list the host in ${CALLOUT_PRIVATE_HOSTS_ENV}`], + ['https://[::1]/hook', `list the host in ${CALLOUT_PRIVATE_HOSTS_ENV}`], + ['https://169.254.169.254/latest/meta-data', 'never reachable'], + // NAT64 for 169.254.169.254: a gateway would turn it back into the metadata address. + ['https://[64:ff9b::a9fe:a9fe]/', 'never reachable'], + ['https://[::ffff:169.254.169.254]/', 'never reachable'], + ['https://224.0.0.1/', 'never reachable'], + ['https://0.0.0.0/', 'never reachable'], + ])('refuses %j in production', (url, problem) => { + expect(calloutUrlProblem(url, production)).toContain(problem); + }); + + it('accepts a public https URL in production', () => { + expect(calloutUrlProblem('https://hooks.example.com/seamless', production)).toBeNull(); + }); + + it('admits a private host only when the operator lists it', () => { + const env = { ...production, [CALLOUT_PRIVATE_HOSTS_ENV]: 'hooks.internal, 10.0.0.5' }; + + expect(calloutUrlProblem('https://10.0.0.5/hook', env)).toBeNull(); + expect(calloutUrlProblem('https://10.0.0.6/hook', env)).toContain('non-public'); + }); + + it('never admits the metadata address, even when the operator lists it', () => { + const env = { ...production, [CALLOUT_PRIVATE_HOSTS_ENV]: '169.254.169.254' }; + + expect(calloutUrlProblem('https://169.254.169.254/', env)).toContain('never reachable'); + }); + + it('allows http and private hosts outside production, but never link-local', () => { + expect(calloutUrlProblem('http://127.0.0.1:9000/hook', development)).toBeNull(); + expect(calloutUrlProblem('http://169.254.169.254/', development)).toContain('never reachable'); + }); + + it('refuses a missing host', () => { + expect(calloutHostProblem('', production)).toBe('has no host'); + }); + + it('ignores an issuer it cannot parse', () => { + expect(calloutHostProblem('hooks.example.com', { ISSUER: 'not a url' })).toBeNull(); + }); +}); + +describe('calloutLookup', () => { + function resolve(hostname: string, env: Record, all = false) { + return new Promise<{ error: Error | null; address: unknown }>((done) => + (calloutLookup(env) as any)(hostname, { all }, (error: Error | null, address: unknown) => + done({ error, address }), + ), + ); + } + + // A name is checked at connect time, so DNS that answers with a private address is refused + // even though the URL looked public when it was written. + it('refuses a name that resolves to loopback in production', async () => { + const { error } = await resolve('localhost', production); + + expect(error).toBeInstanceOf(CalloutError); + expect((error as CalloutError).failure).toBe('refused'); + }); + + it('admits a listed name in production', async () => { + const { error, address } = await resolve('localhost', { + ...production, + [CALLOUT_PRIVATE_HOSTS_ENV]: 'localhost', + }); + + expect(error).toBeNull(); + expect(typeof address).toBe('string'); + }); + + it('returns every address when asked for all of them', async () => { + const { error, address } = await resolve('localhost', development, true); + + expect(error).toBeNull(); + expect(Array.isArray(address)).toBe(true); + }); + + it.each([ + [4, 'IPv4'], + [6, 'IPv6'], + ])('honors a requested family (%s)', async (family) => { + const result = await new Promise<{ error: Error | null }>((done) => + (calloutLookup(development) as any)('localhost', { family }, (error: Error | null) => + done({ error }), + ), + ); + // Either family may be absent on the host; what matters is that the lookup ran. + expect(result.error === null || result.error instanceof Error).toBe(true); + }); + + it('passes a DNS failure through', async () => { + const { error } = await resolve('does-not-exist.invalid', development); + + expect(error).toBeInstanceOf(Error); + expect(error).not.toBeInstanceOf(CalloutError); + }); +}); + +describe('calloutRequest', () => { + const base = { timeoutMs: 2000, maxResponseBytes: 1024 }; + + it('posts the body and returns the status, headers and body', async () => { + let received = ''; + const port = await serve((req, res) => { + req.on('data', (chunk) => (received += chunk)); + req.on('end', () => { + res.setHeader('retry-after', '5'); + res.end('ok'); + }); + }); + + const response = await calloutRequest( + `http://127.0.0.1:${port}/hook`, + { ...base, body: '{"a":1}', headers: { 'x-test': '1' } }, + development, + ); + + expect(received).toBe('{"a":1}'); + expect(response.status).toBe(200); + expect(response.headers['retry-after']).toBe('5'); + expect(response.body.toString()).toBe('ok'); + }); + + it('sends a GET without a body', async () => { + const port = await serve((req, res) => res.end(req.method)); + + const response = await calloutRequest( + `http://127.0.0.1:${port}/`, + { ...base, method: 'GET' }, + development, + ); + + expect(response.body.toString()).toBe('GET'); + }); + + it('does not follow a redirect', async () => { + let hits = 0; + const port = await serve((req, res) => { + hits += 1; + res.statusCode = 307; + res.setHeader('location', 'http://169.254.169.254/latest/meta-data'); + res.end(); + }); + + const response = await calloutRequest(`http://127.0.0.1:${port}/`, base, development); + + expect(response.status).toBe(307); + expect(hits).toBe(1); + }); + + it('refuses loopback in production before connecting', async () => { + let hits = 0; + const port = await serve((_req, res) => { + hits += 1; + res.end(); + }); + + expect(await failureOf(calloutRequest(`https://127.0.0.1:${port}/`, base, production))).toBe( + 'refused', + ); + expect(hits).toBe(0); + }); + + it('refuses a name that resolves to loopback in production', async () => { + const port = await serve((_req, res) => res.end()); + + expect(await failureOf(calloutRequest(`https://localhost:${port}/`, base, production))).toBe( + 'refused', + ); + }); + + it('times out a destination that never answers', async () => { + const port = await serve(() => { + // Never responds. + }); + + expect( + await failureOf( + calloutRequest(`http://127.0.0.1:${port}/`, { ...base, timeoutMs: 100 }, development), + ), + ).toBe('timed_out'); + }); + + it('stops reading a response that is too large', async () => { + const port = await serve((_req, res) => res.end('x'.repeat(4096))); + + expect( + await failureOf( + calloutRequest( + `http://127.0.0.1:${port}/`, + { ...base, maxResponseBytes: 100 }, + development, + ), + ), + ).toBe('too_large'); + }); + + it('reports a refused connection without the socket error', async () => { + const port = await serve((_req, res) => res.end()); + server!.close(); + server = null; + + const failure = calloutRequest(`http://127.0.0.1:${port}/`, base, development); + + await expect(failure).rejects.toMatchObject({ + failure: 'connection_failed', + message: 'Callout connection failed', + }); + }); + + it('reports a response that breaks off mid-body', async () => { + const port = await serve((_req, res) => { + res.writeHead(200, { 'content-length': '100' }); + res.write('partial'); + setTimeout(() => res.socket?.destroy(), 10); + }); + + expect(await failureOf(calloutRequest(`http://127.0.0.1:${port}/`, base, development))).toBe( + 'connection_failed', + ); + }); +}); + +describe('calloutRequest status fallback', () => { + beforeEach(() => { + vi.resetModules(); + }); + + it('treats a missing status code as a bad gateway', async () => { + vi.doMock('node:http', async (importOriginal) => { + const actual = await importOriginal(); + const { EventEmitter } = await import('node:events'); + return { + ...actual, + request: (_url: unknown, _options: unknown, onResponse: (r: unknown) => void) => { + const request = new EventEmitter() as any; + request.destroy = () => {}; + request.end = () => { + const response = new EventEmitter() as any; + response.headers = {}; + onResponse(response); + response.emit('end'); + }; + return request; + }, + }; + }); + + const { calloutRequest: isolated } = await import('../../../src/lib/calloutTransport.js'); + const response = await isolated('http://127.0.0.1:1/', base(), development); + + expect(response.status).toBe(502); + vi.doUnmock('node:http'); + }); + + function base() { + return { timeoutMs: 1000, maxResponseBytes: 1024 }; + } +}); diff --git a/tests/unit/models/models.spec.ts b/tests/unit/models/models.spec.ts index 409e8fc8..8d90dbc3 100644 --- a/tests/unit/models/models.spec.ts +++ b/tests/unit/models/models.spec.ts @@ -16,6 +16,8 @@ vi.unmock('../../../src/models/organizationMemberships.js'); vi.unmock('../../../src/models/organizationRoles.js'); vi.unmock('../../../src/models/permissions.js'); vi.unmock('../../../src/models/rolePermissions.js'); +vi.unmock('../../../src/models/webhookDeliveries.js'); +vi.unmock('../../../src/models/webhookEndpoints.js'); vi.unmock('../../../src/models/webauthnChallenges.js'); vi.unmock('../../../src/models/userExternalIds.js'); vi.unmock('../../../src/models/policyVersions.js'); diff --git a/tests/unit/services/oidcClientRegistry.spec.ts b/tests/unit/services/oidcClientRegistry.spec.ts index 03e6a78c..0fd3462e 100644 --- a/tests/unit/services/oidcClientRegistry.spec.ts +++ b/tests/unit/services/oidcClientRegistry.spec.ts @@ -373,6 +373,7 @@ describe('getOidcAccountClaims', () => { phone_number_verified: false, roles: ['user'], org_id: 'org-1', + customClaims: {}, }); }); diff --git a/tests/unit/services/sessionIssueService.spec.ts b/tests/unit/services/sessionIssueService.spec.ts index fbaf45e6..ca14ed71 100644 --- a/tests/unit/services/sessionIssueService.spec.ts +++ b/tests/unit/services/sessionIssueService.spec.ts @@ -38,6 +38,7 @@ vi.mock('../../../src/utils/utils.js', () => ({ import { getSystemConfig } from '../../../src/config/getSystemConfig.js'; import { Credential } from '../../../src/models/credentials.js'; +import { AuthEventService } from '../../../src/services/authEventService.js'; import { createRefreshTokenLookup, generateRefreshToken, @@ -129,6 +130,39 @@ describe('issueSessionAndRespond', () => { }); }); + // The one record that a sign-in completed, which the user.signed_in webhook is built from. + it('records that a session was created, with the method and organization', async () => { + const req = mockReq(); + + await issueSessionAndRespond({ user: mockUser, req, res: mockRes(), method: 'email_otp' }); + + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + userId: mockUser.id, + sessionId: 'session-1', + type: 'session_created', + metadata: { method: 'email_otp', organizationId: null }, + }), + ); + }); + + it('marks a recovery session in the record', async () => { + await issueSessionAndRespond({ + user: mockUser, + req: mockReq(), + res: mockRes(), + method: 'account_recovery', + recovery: true, + }); + + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'session_created', + metadata: expect.objectContaining({ recovery: true }), + }), + ); + }); + it('records the sign-in method and time for the provider auth context', async () => { await issueSessionAndRespond({ user: mockUser, diff --git a/tests/unit/services/webhookCatalog.spec.ts b/tests/unit/services/webhookCatalog.spec.ts new file mode 100644 index 00000000..197e9d84 --- /dev/null +++ b/tests/unit/services/webhookCatalog.spec.ts @@ -0,0 +1,196 @@ +import { WEBHOOK_EVENT_TYPES, WebhookEventSchema } from '@seamless-auth/types'; +import { describe, expect, it } from 'vitest'; + +import { AUTH_EVENT_TYPES } from '../../../src/schemas/authEvent.types.js'; +import { + type DispatchableAuthEvent, + WEBHOOK_SOURCE_TYPES, + webhookEventFor, +} from '../../../src/services/webhookCatalog.js'; + +function row(type: string, overrides: Partial = {}): DispatchableAuthEvent { + return { + seq: '10', + type, + user_id: 'user-1', + session_id: 'session-1', + metadata: null, + created_at: new Date('2026-11-07T12:00:00.000Z'), + ...overrides, + }; +} + +function parses(built: ReturnType) { + expect(built).not.toBeNull(); + return WebhookEventSchema.parse({ + id: 'delivery-1', + version: 1, + timestamp: '2026-11-07T12:00:00.000Z', + ...built, + }); +} + +describe('webhook catalog', () => { + // The catalog is a public contract. Adding an audit type must not change what receivers get + // unless this table changes with it. + it('pins which audit types become which webhook', () => { + expect(WEBHOOK_SOURCE_TYPES).toEqual({ + user_created: 'user.created', + user_deleted: 'user.deleted', + session_created: 'user.signed_in', + account_recovery_completed: 'user.recovered', + logout_success: 'session.revoked', + admin_session_revoked: 'session.revoked', + session_evicted: 'session.revoked', + oidc_session_revoked: 'session.revoked', + registration_success: 'credential.added', + totp_enrollment_success: 'credential.added', + recovery_codes_generated: 'credential.added', + credentials_deleted: 'credential.removed', + totp_disabled: 'credential.removed', + organization_member_added: 'organization.member_added', + organization_member_updated: 'organization.member_updated', + organization_member_removed: 'organization.member_removed', + }); + }); + + it('maps only audit types that exist, and reaches every catalog type', () => { + for (const source of Object.keys(WEBHOOK_SOURCE_TYPES)) { + expect(AUTH_EVENT_TYPES).toContain(source); + } + expect([...new Set(Object.values(WEBHOOK_SOURCE_TYPES))].sort()).toEqual( + [...WEBHOOK_EVENT_TYPES].sort(), + ); + }); + + it('ignores audit types outside the catalog', () => { + expect(webhookEventFor(row('login_success'), null)).toBeNull(); + expect(webhookEventFor(row('login_failed'), null)).toBeNull(); + }); + + it('builds user.created with the address the account was made with', () => { + const event = parses( + webhookEventFor(row('user_created'), { email: 'a@example.com', phone: null }), + ); + expect(event.data).toEqual({ userId: 'user-1', email: 'a@example.com', phone: null }); + }); + + it('builds user.created without an address when the user is already gone', () => { + expect(parses(webhookEventFor(row('user_created'), null)).data).toEqual({ + userId: 'user-1', + email: null, + phone: null, + }); + }); + + it.each(['user_created', 'user_deleted', 'account_recovery_completed', 'session_created'])( + 'drops %s without a user', + (type) => { + expect(webhookEventFor(row(type, { user_id: null }), null)).toBeNull(); + }, + ); + + it('builds user.deleted and user.recovered', () => { + expect(parses(webhookEventFor(row('user_deleted'), null)).type).toBe('user.deleted'); + expect(parses(webhookEventFor(row('account_recovery_completed'), null)).type).toBe( + 'user.recovered', + ); + }); + + it('builds user.signed_in from session_created, with no network detail', () => { + const event = parses( + webhookEventFor( + row('session_created', { metadata: { method: 'passkey', organizationId: 'org-1' } }), + null, + ), + ); + + expect(event.data).toEqual({ + userId: 'user-1', + sessionId: 'session-1', + method: 'passkey', + organizationId: 'org-1', + }); + }); + + it.each([ + ['logout_success', { scope: 'current_session' }, 'session-1', 'logout'], + ['logout_success', { scope: 'all_sessions' }, null, 'logout'], + // The request's own session is the administrator's, never the one revoked. + ['admin_session_revoked', { sessionId: 'target' }, 'target', 'admin'], + ['admin_session_revoked', { targetUser: 'user-1' }, null, 'admin'], + ['session_evicted', { sessionId: 'old' }, 'old', 'evicted'], + ['oidc_session_revoked', { reason: 'logout' }, 'session-1', 'provider'], + ])('builds session.revoked from %s %j', (type, metadata, sessionId, reason) => { + const event = parses(webhookEventFor(row(type, { metadata }), null)); + expect(event.data).toEqual({ userId: 'user-1', sessionId, reason }); + }); + + it.each([ + [ + 'registration_success', + { credential: 'passkey', credentialId: 'cred-1' }, + 'passkey', + 'cred-1', + ], + ['totp_enrollment_success', null, 'totp', null], + ['recovery_codes_generated', null, 'recovery_codes', null], + ])('builds credential.added from %s', (type, metadata, kind, credentialId) => { + const event = parses(webhookEventFor(row(type, { metadata }), null)); + expect(event).toMatchObject({ type: 'credential.added', data: { kind, credentialId } }); + }); + + it.each([ + ['credentials_deleted', { credential: 'passkey', credentialId: 'cred-1' }, 'passkey'], + ['totp_disabled', null, 'totp'], + ])('builds credential.removed from %s', (type, metadata, kind) => { + expect(parses(webhookEventFor(row(type, { metadata }), null))).toMatchObject({ + type: 'credential.removed', + data: { kind }, + }); + }); + + // Account registration and account deletion write the same audit types without naming a passkey. + it('drops registration_success and credentials_deleted that are not about a passkey', () => { + expect(webhookEventFor(row('registration_success', { metadata: {} }), null)).toBeNull(); + expect( + webhookEventFor( + row('credentials_deleted', { metadata: { reason: 'User deleted account' } }), + null, + ), + ).toBeNull(); + expect(webhookEventFor(row('totp_disabled', { user_id: null }), null)).toBeNull(); + }); + + it.each([ + ['organization_member_added', ['member'], ['member']], + ['organization_member_updated', ['admin', 7], ['admin']], + ['organization_member_removed', ['admin'], []], + ])('builds the organization event from %s', (type, roles, expected) => { + const event = parses( + webhookEventFor(row(type, { metadata: { organizationId: 'org-1', roles } }), null), + ); + expect(event.data).toEqual({ organizationId: 'org-1', userId: 'user-1', roles: expected }); + }); + + it('builds roles as empty when the row carries none', () => { + expect( + parses( + webhookEventFor( + row('organization_member_added', { metadata: { organizationId: 'o' } }), + null, + ), + ).data, + ).toMatchObject({ roles: [] }); + }); + + it('drops an organization event without an organization or user', () => { + expect(webhookEventFor(row('organization_member_added', { metadata: {} }), null)).toBeNull(); + expect( + webhookEventFor( + row('organization_member_added', { user_id: null, metadata: { organizationId: 'o' } }), + null, + ), + ).toBeNull(); + }); +}); diff --git a/tests/unit/services/webhookService.spec.ts b/tests/unit/services/webhookService.spec.ts new file mode 100644 index 00000000..67ee47c6 --- /dev/null +++ b/tests/unit/services/webhookService.spec.ts @@ -0,0 +1,801 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const { query, transaction } = vi.hoisted(() => { + const query = vi.fn(); + const transaction = vi.fn(async (fn: (t: unknown) => unknown) => fn({ id: 'tx' })); + return { query, transaction }; +}); + +vi.mock('../../../src/models/index.js', () => ({ + getSequelize: () => ({ query, transaction }), +})); + +vi.mock('../../../src/models/webhookEndpoints.js', () => ({ + WebhookEndpoint: { + findAll: vi.fn(), + findByPk: vi.fn(), + create: vi.fn(), + }, +})); + +vi.mock('../../../src/models/webhookDeliveries.js', () => ({ + WebhookDelivery: { + findAll: vi.fn(), + findByPk: vi.fn(), + create: vi.fn(), + update: vi.fn(), + destroy: vi.fn(), + }, +})); + +vi.mock('../../../src/lib/calloutTransport.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, calloutRequest: vi.fn() }; +}); + +import { CalloutError, calloutRequest } from '../../../src/lib/calloutTransport.js'; +import { encryptCalloutSecret, generateCalloutSecret } from '../../../src/lib/calloutSigning.js'; +import { User } from '../../../src/models/users.js'; +import { WebhookDelivery } from '../../../src/models/webhookDeliveries.js'; +import { WebhookEndpoint } from '../../../src/models/webhookEndpoints.js'; +import { AuthEventService } from '../../../src/services/authEventService.js'; +import { + attemptDelivery, + createEndpoint, + deleteEndpoint, + deliverDue, + dispatchWebhooks, + getDelivery, + getEndpoint, + listDeliveries, + listEndpoints, + nextAttemptAt, + pruneDeliveries, + redeliver, + rotateEndpointSecret, + runWebhookTick, + sendSigned, + sendTestEvent, + serializeDelivery, + serializeEndpoint, + signingSecrets, + startWebhookDelivery, + updateEndpoint, + WebhookError, +} from '../../../src/services/webhookService.js'; + +const at = new Date('2026-11-07T12:00:00.000Z'); +const secret = 'whsec_' + Buffer.alloc(32, 1).toString('base64'); + +function endpoint(overrides: Record = {}) { + const sealed = encryptCalloutSecret(secret); + const record: any = { + id: 'endpoint-1', + url: 'https://hooks.example.com/seamless', + description: null, + eventTypes: ['user.created'], + enabled: true, + disabledReason: null, + version: 1, + secretCiphertext: sealed.ciphertext, + secretIv: sealed.iv, + secretTag: sealed.tag, + previousSecretCiphertext: null, + previousSecretIv: null, + previousSecretTag: null, + previousSecretExpiresAt: null, + failingSince: null, + createdAt: at, + updatedAt: at, + ...overrides, + }; + record.update = vi.fn(async (changes: Record) => Object.assign(record, changes)); + record.destroy = vi.fn(); + return record; +} + +function delivery(overrides: Record = {}) { + const record: any = { + id: 'delivery-1', + endpointId: 'endpoint-1', + eventType: 'user.created', + authEventSeq: '10', + payload: '{"type":"user.created"}', + status: 'pending', + attempts: 0, + nextAttemptAt: at, + lastAttemptAt: null, + lastStatusCode: null, + lastFailure: null, + createdAt: at, + ...overrides, + }; + record.update = vi.fn(async (changes: Record) => Object.assign(record, changes)); + return record; +} + +function responds(status: number, headers: Record = {}) { + vi.mocked(calloutRequest).mockResolvedValue({ status, headers, body: Buffer.alloc(0) }); +} + +beforeEach(() => { + transaction.mockImplementation(async (fn: (t: unknown) => unknown) => fn({ id: 'tx' })); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('endpoints', () => { + it('creates an endpoint with an encrypted secret and returns the secret once', async () => { + vi.mocked(WebhookEndpoint.create).mockImplementation(async (values: any) => endpoint(values)); + + const { endpoint: created, secret: issued } = await createEndpoint( + { url: 'https://hooks.example.com/a', eventTypes: ['user.created'] }, + 'admin-1', + ); + + const stored = vi.mocked(WebhookEndpoint.create).mock.calls[0][0] as any; + expect(issued).toMatch(/^whsec_/); + expect(stored.secretCiphertext).toBeDefined(); + expect(JSON.stringify(stored)).not.toContain(issued.slice(6)); + expect(stored).toMatchObject({ enabled: true, description: null, createdBy: 'admin-1' }); + expect(created.url).toBe('https://hooks.example.com/a'); + }); + + it('keeps an explicit description and enabled flag', async () => { + vi.mocked(WebhookEndpoint.create).mockImplementation(async (values: any) => endpoint(values)); + + await createEndpoint( + { + url: 'https://hooks.example.com/a', + eventTypes: ['user.created'], + description: 'CRM', + enabled: false, + }, + null, + ); + + expect(vi.mocked(WebhookEndpoint.create).mock.calls[0][0]).toMatchObject({ + description: 'CRM', + enabled: false, + }); + }); + + it('refuses a URL no callout may reach', async () => { + await expect( + createEndpoint({ url: 'http://169.254.169.254/', eventTypes: ['user.created'] }, null), + ).rejects.toMatchObject({ status: 400 }); + expect(WebhookEndpoint.create).not.toHaveBeenCalled(); + }); + + it('refuses to store a secret in production without the encryption key', async () => { + vi.stubEnv('NODE_ENV', 'production'); + vi.stubEnv('CALLOUT_SECRET_ENCRYPTION_KEY', ''); + + await expect( + createEndpoint({ url: 'https://hooks.example.com/a', eventTypes: ['user.created'] }, null), + ).rejects.toMatchObject({ status: 409 }); + }); + + it('lists, reads and deletes', async () => { + const record = endpoint(); + vi.mocked(WebhookEndpoint.findAll).mockResolvedValue([record]); + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(record); + + expect(await listEndpoints()).toEqual([record]); + expect(await getEndpoint('endpoint-1')).toBe(record); + expect(await deleteEndpoint('endpoint-1')).toBe(record); + expect(record.destroy).toHaveBeenCalled(); + }); + + it('answers 404 for a missing endpoint', async () => { + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(null); + + await expect(getEndpoint('missing')).rejects.toBeInstanceOf(WebhookError); + }); + + it('updates fields, and turning an endpoint on clears why it was off', async () => { + const record = endpoint({ enabled: false, disabledReason: 'failing', failingSince: at }); + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(record); + vi.mocked(WebhookDelivery.update).mockResolvedValue([0] as never); + + await updateEndpoint('endpoint-1', { + url: 'https://hooks.example.com/b', + description: null, + eventTypes: ['user.deleted'], + enabled: true, + }); + + expect(record).toMatchObject({ + url: 'https://hooks.example.com/b', + eventTypes: ['user.deleted'], + enabled: true, + disabledReason: null, + failingSince: null, + }); + }); + + // Events that happened while it was off were queued on hold; turning it back on sends them. + it('releases the deliveries held while it was off when it is turned back on', async () => { + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(endpoint({ enabled: false })); + vi.mocked(WebhookDelivery.update).mockResolvedValue([4] as never); + + const { released } = await updateEndpoint('endpoint-1', { enabled: true }); + + expect(released).toBe(4); + const [values, options] = vi.mocked(WebhookDelivery.update).mock.calls[0] as any; + expect(values.nextAttemptAt).toMatchObject({ fn: 'now' }); + expect(options.where).toMatchObject({ endpointId: 'endpoint-1', nextAttemptAt: null }); + const [statusOp] = Object.getOwnPropertySymbols(options.where.status); + expect(options.where.status[statusOp]).toEqual(['pending', 'failed']); + }); + + it('releases nothing for an endpoint that was already on, or is being turned off', async () => { + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(endpoint()); + expect((await updateEndpoint('endpoint-1', { enabled: true })).released).toBe(0); + + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(endpoint()); + expect((await updateEndpoint('endpoint-1', { enabled: false })).released).toBe(0); + + expect(WebhookDelivery.update).not.toHaveBeenCalled(); + }); + + it('records a manual disable', async () => { + const record = endpoint(); + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(record); + + await updateEndpoint('endpoint-1', { enabled: false }); + + expect(record.disabledReason).toBe('manual'); + }); + + it('refuses an update to a URL no callout may reach', async () => { + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(endpoint()); + + await expect( + updateEndpoint('endpoint-1', { url: 'https://user:pw@hooks.example.com/' }), + ).rejects.toMatchObject({ status: 400 }); + }); + + it('rotates the secret, keeping the old one signing for a day', async () => { + vi.useFakeTimers({ now: at }); + const record = endpoint(); + const oldCiphertext = record.secretCiphertext; + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(record); + + const { secret: issued, previousSecretExpiresAt } = await rotateEndpointSecret('endpoint-1'); + + expect(record.previousSecretCiphertext).toBe(oldCiphertext); + expect(previousSecretExpiresAt.toISOString()).toBe('2026-11-08T12:00:00.000Z'); + expect(signingSecrets(record)).toEqual([issued, secret]); + }); + + it('stops signing with the previous secret once its overlap ends', () => { + const sealed = encryptCalloutSecret(generateCalloutSecret()); + const record = endpoint({ + previousSecretCiphertext: sealed.ciphertext, + previousSecretIv: sealed.iv, + previousSecretTag: sealed.tag, + previousSecretExpiresAt: new Date(at.getTime() - 1), + }); + + expect(signingSecrets(record, at)).toEqual([secret]); + expect(serializeEndpoint(record).previousSecretExpiresAt).toBeNull(); + }); + + it('serializes an endpoint mid-rotation', () => { + const future = new Date(Date.now() + 60_000); + expect(serializeEndpoint(endpoint({ previousSecretExpiresAt: future }))).toMatchObject({ + previousSecretExpiresAt: future.toISOString(), + version: 1, + }); + }); +}); + +describe('sendSigned', () => { + it('signs the request and treats a 2xx as delivered', async () => { + responds(204); + + const attempt = await sendSigned('https://hooks.example.com/', 'id-1', '{}', [secret]); + + const [, request] = vi.mocked(calloutRequest).mock.calls[0]; + expect(request.headers?.['webhook-id']).toBe('id-1'); + expect(request.headers?.['webhook-signature']).toMatch(/^v1,/); + expect(attempt).toMatchObject({ ok: true, statusCode: 204, failure: null }); + }); + + it.each([ + [301, 'a redirect, which is not followed'], + [500, 'a server error'], + ])('treats %s as a failure (%s)', async (status) => { + responds(status); + + expect(await sendSigned('https://hooks.example.com/', 'id', '{}', [secret])).toMatchObject({ + ok: false, + statusCode: status, + failure: 'http_status', + }); + }); + + it.each([ + ['120', 120], + ['Sat, 07 Nov 2026 12:10:00 GMT', 600], + ['soon', null], + ])('reads Retry-After %j', async (header, seconds) => { + vi.useFakeTimers({ now: at }); + responds(429, { 'retry-after': header }); + + const attempt = await sendSigned('https://hooks.example.com/', 'id', '{}', [secret]); + + expect(attempt.retryAfterSeconds).toBe(seconds); + }); + + it('reads the first of repeated Retry-After headers', async () => { + vi.mocked(calloutRequest).mockResolvedValue({ + status: 503, + headers: { 'retry-after': ['30', '60'] }, + body: Buffer.alloc(0), + }); + + expect( + (await sendSigned('https://hooks.example.com/', 'id', '{}', [secret])).retryAfterSeconds, + ).toBe(30); + }); + + it('reports a transport failure by its coarse reason', async () => { + vi.mocked(calloutRequest).mockRejectedValue(new CalloutError('refused', 'internal detail')); + + expect(await sendSigned('https://hooks.example.com/', 'id', '{}', [secret])).toMatchObject({ + ok: false, + failure: 'refused', + statusCode: null, + }); + }); + + it('reports an unexpected error as a failed connection', async () => { + vi.mocked(calloutRequest).mockRejectedValue(new Error('boom')); + + expect((await sendSigned('https://hooks.example.com/', 'id', '{}', [secret])).failure).toBe( + 'connection_failed', + ); + }); +}); + +describe('nextAttemptAt', () => { + beforeEach(() => { + vi.spyOn(Math, 'random').mockReturnValue(0); + }); + + it('follows the schedule, then stops', () => { + expect(nextAttemptAt(1, at, null)?.toISOString()).toBe('2026-11-07T12:00:05.000Z'); + expect(nextAttemptAt(7, at, null)?.toISOString()).toBe('2026-11-08T12:00:00.000Z'); + expect(nextAttemptAt(8, at, null)).toBeNull(); + }); + + it('honors a longer Retry-After, up to the longest step', () => { + expect(nextAttemptAt(1, at, 600)?.toISOString()).toBe('2026-11-07T12:10:00.000Z'); + expect(nextAttemptAt(1, at, 10 * 86400)?.toISOString()).toBe('2026-11-08T12:00:00.000Z'); + expect(nextAttemptAt(3, at, 1)?.toISOString()).toBe('2026-11-07T12:30:00.000Z'); + }); +}); + +describe('attemptDelivery', () => { + beforeEach(() => { + vi.spyOn(Math, 'random').mockReturnValue(0); + vi.useFakeTimers({ now: at }); + }); + + it('marks a delivered event and clears a failing streak', async () => { + responds(200); + const record = delivery(); + const target = endpoint({ failingSince: new Date(at.getTime() - 1000) }); + + await attemptDelivery(record, target); + + expect(record).toMatchObject({ status: 'succeeded', attempts: 1, nextAttemptAt: null }); + expect(target.failingSince).toBeNull(); + }); + + it('leaves a healthy endpoint alone on success', async () => { + responds(200); + const target = endpoint(); + + await attemptDelivery(delivery(), target); + + expect(target.update).not.toHaveBeenCalled(); + }); + + it('schedules a retry and starts the failing streak', async () => { + responds(500); + const record = delivery(); + const target = endpoint(); + + await attemptDelivery(record, target); + + expect(record).toMatchObject({ + status: 'failed', + attempts: 1, + lastStatusCode: 500, + lastFailure: 'http_status', + }); + expect(record.nextAttemptAt.toISOString()).toBe('2026-11-07T12:00:05.000Z'); + expect(target.failingSince).toEqual(at); + }); + + it('dead-letters a delivery after the last scheduled attempt', async () => { + responds(500); + const record = delivery({ attempts: 7 }); + + await attemptDelivery(record, endpoint({ failingSince: at })); + + expect(record).toMatchObject({ status: 'dead', attempts: 8, nextAttemptAt: null }); + }); + + it('disables an endpoint that answers 410, and audits it', async () => { + responds(410); + const target = endpoint(); + + await attemptDelivery(delivery(), target); + + expect(target).toMatchObject({ enabled: false, disabledReason: 'gone' }); + expect(AuthEventService.logContext).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'webhook_endpoint_disabled', + metadata: { endpointId: 'endpoint-1', reason: 'gone' }, + }), + ); + }); + + it('disables an endpoint whose deliveries have all failed for three days', async () => { + responds(503); + const target = endpoint({ failingSince: new Date(at.getTime() - 3 * 86400 * 1000) }); + + await attemptDelivery(delivery(), target); + + expect(target).toMatchObject({ enabled: false, disabledReason: 'failing' }); + }); + + it('keeps the start of a failing streak', async () => { + responds(503); + const since = new Date(at.getTime() - 3600 * 1000); + const target = endpoint({ failingSince: since }); + + await attemptDelivery(delivery(), target); + + expect(target.failingSince).toBe(since); + expect(target.update).not.toHaveBeenCalled(); + }); + + it('does not disable an endpoint twice', async () => { + responds(410); + const target = endpoint({ enabled: false, disabledReason: 'manual' }); + + await attemptDelivery(delivery(), target); + + expect(target.disabledReason).toBe('manual'); + expect(AuthEventService.logContext).not.toHaveBeenCalled(); + }); +}); + +describe('test events and redelivery', () => { + it('sends webhook.test once and logs it, without touching the endpoint', async () => { + responds(500); + const target = endpoint(); + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(target); + vi.mocked(WebhookDelivery.create).mockImplementation(async (values: any) => delivery(values)); + + const result = await sendTestEvent('endpoint-1'); + + const created = vi.mocked(WebhookDelivery.create).mock.calls[0][0] as any; + expect(JSON.parse(created.payload)).toMatchObject({ + type: 'webhook.test', + version: 1, + data: { endpointId: 'endpoint-1' }, + }); + expect(result).toMatchObject({ ok: false, failure: 'http_status', statusCode: 500 }); + expect(target.update).not.toHaveBeenCalled(); + }); + + it('reports a passing test', async () => { + responds(200); + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(endpoint()); + const record = delivery({ eventType: 'webhook.test' }); + vi.mocked(WebhookDelivery.create).mockResolvedValue(record); + + expect((await sendTestEvent('endpoint-1')).ok).toBe(true); + expect(record.status).toBe('succeeded'); + }); + + it('redelivers with the same id and body', async () => { + responds(200); + const record = delivery({ status: 'dead', attempts: 8 }); + vi.mocked(WebhookDelivery.findByPk).mockResolvedValue(record); + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(endpoint()); + + await redeliver('delivery-1'); + + const [, request] = vi.mocked(calloutRequest).mock.calls[0]; + expect(request.headers?.['webhook-id']).toBe('delivery-1'); + expect(request.body).toBe(record.payload); + expect(record.status).toBe('succeeded'); + }); + + it('answers 404 for a missing delivery', async () => { + vi.mocked(WebhookDelivery.findByPk).mockResolvedValue(null); + + await expect(getDelivery('missing')).rejects.toMatchObject({ status: 404 }); + }); +}); + +describe('listDeliveries', () => { + it('pages newest first with an opaque cursor', async () => { + const rows = [ + delivery({ id: 'c', createdAt: new Date(at.getTime() + 2) }), + delivery({ id: 'b', createdAt: new Date(at.getTime() + 1) }), + delivery({ id: 'a', createdAt: at }), + ]; + vi.mocked(WebhookDelivery.findAll).mockResolvedValue(rows); + + const page = await listDeliveries({ + limit: 2, + endpointId: '11111111-1111-4111-8111-111111111111', + status: 'dead', + eventType: 'user.created', + }); + + expect(page.deliveries.map((d: any) => d.id)).toEqual(['c', 'b']); + expect(page.nextCursor).not.toBeNull(); + + vi.mocked(WebhookDelivery.findAll).mockResolvedValue([rows[2]]); + const next = await listDeliveries({ limit: 2, cursor: page.nextCursor! }); + + expect(next).toMatchObject({ nextCursor: null }); + expect(vi.mocked(WebhookDelivery.findAll).mock.calls[1][0]).toMatchObject({ limit: 3 }); + }); + + it('lists with no filters', async () => { + vi.mocked(WebhookDelivery.findAll).mockResolvedValue([]); + + expect(await listDeliveries({ limit: 50 })).toEqual({ deliveries: [], nextCursor: null }); + }); + + it('refuses a cursor it did not issue', async () => { + await expect(listDeliveries({ limit: 10, cursor: 'garbage' })).rejects.toMatchObject({ + status: 400, + }); + }); + + it('serializes a delivery', () => { + expect(serializeDelivery(delivery({ nextAttemptAt: null }))).toEqual({ + id: 'delivery-1', + endpointId: 'endpoint-1', + eventType: 'user.created', + status: 'pending', + attempts: 0, + nextAttemptAt: null, + lastAttemptAt: null, + lastStatusCode: null, + lastFailure: null, + createdAt: at.toISOString(), + }); + }); +}); + +describe('dispatchWebhooks', () => { + function queries(...answers: unknown[]) { + for (const answer of answers) query.mockResolvedValueOnce(answer); + } + + it('does nothing while another replica holds the lock', async () => { + queries([{ locked: false }]); + + expect(await dispatchWebhooks()).toBe(0); + expect(query).toHaveBeenCalledTimes(1); + }); + + it('starts the cursor at the newest row instead of replaying history', async () => { + queries([{ locked: true }], [], [{ head: '42' }], undefined); + + expect(await dispatchWebhooks()).toBe(0); + expect(query.mock.calls[3][0]).toContain('INSERT INTO public.event_dispatch_cursors'); + expect(query.mock.calls[3][1].replacements).toMatchObject({ head: '42' }); + }); + + it('returns at once when no row is past the cursor', async () => { + queries([{ locked: true }], [{ lastSeq: '42' }], []); + + expect(await dispatchWebhooks()).toBe(0); + expect(WebhookEndpoint.findAll).not.toHaveBeenCalled(); + }); + + it('queues one delivery per subscribed endpoint and advances the cursor', async () => { + const created = new Date('2026-11-07T11:59:00.000Z'); + queries( + [{ locked: true }], + [{ lastSeq: '9' }], + [ + { + seq: '10', + type: 'user_created', + user_id: 'user-1', + session_id: null, + metadata: null, + created_at: created, + }, + // Nobody subscribes to sign-ins here. + { + seq: '11', + type: 'session_created', + user_id: 'user-1', + session_id: 's', + metadata: { method: 'passkey' }, + created_at: created, + }, + // Subscribed, but this row is about an account rather than a passkey. + { + seq: '12', + type: 'registration_success', + user_id: 'user-1', + session_id: null, + metadata: {}, + created_at: created, + }, + ], + ); + query.mockResolvedValue(undefined); + vi.mocked(WebhookEndpoint.findAll).mockResolvedValue([ + endpoint({ id: 'a', eventTypes: ['user.created', 'credential.added'] }), + endpoint({ id: 'b', eventTypes: ['user.created'], enabled: false }), + ]); + vi.mocked(User.findByPk).mockResolvedValue({ email: 'a@example.com', phone: null } as any); + + expect(await dispatchWebhooks()).toBe(3); + + const inserts = query.mock.calls.filter(([sql]) => + sql.includes('INSERT INTO public.webhook_deliveries'), + ); + expect(inserts).toHaveLength(2); + expect(inserts.map(([, options]) => options.replacements.endpointId)).toEqual(['a', 'b']); + // A disabled endpoint's delivery is queued on hold, with no attempt due. + expect(inserts.map(([, options]) => options.replacements.held)).toEqual([false, true]); + expect(inserts[0][0]).toContain('CASE WHEN :held THEN NULL ELSE now() END'); + const payload = JSON.parse(inserts[0][1].replacements.payload); + expect(payload).toEqual({ + id: inserts[0][1].replacements.id, + type: 'user.created', + version: 1, + timestamp: created.toISOString(), + data: { userId: 'user-1', email: 'a@example.com', phone: null }, + }); + expect(inserts[0][0]).toContain('ON CONFLICT ("endpointId", "authEventSeq") DO NOTHING'); + + const advance = query.mock.calls.at(-1)!; + expect(advance[0]).toContain('UPDATE public.event_dispatch_cursors'); + expect(advance[1].replacements).toMatchObject({ seq: '12' }); + }); + + it('builds user.created without an address once the user is gone', async () => { + queries( + [{ locked: true }], + [{ lastSeq: '9' }], + [ + { + seq: '10', + type: 'user_created', + user_id: 'u', + session_id: null, + metadata: null, + created_at: at, + }, + ], + ); + query.mockResolvedValue(undefined); + vi.mocked(WebhookEndpoint.findAll).mockResolvedValue([endpoint()]); + vi.mocked(User.findByPk).mockResolvedValue(null); + + await dispatchWebhooks(); + + const insert = query.mock.calls.find(([sql]) => sql.includes('webhook_deliveries'))!; + expect(JSON.parse(insert[1].replacements.payload).data.email).toBeNull(); + }); + + it('reads no user for an event that does not carry an address', async () => { + queries( + [{ locked: true }], + [{ lastSeq: '9' }], + [ + { + seq: '10', + type: 'user_deleted', + user_id: 'u', + session_id: null, + metadata: null, + created_at: at, + }, + ], + ); + query.mockResolvedValue(undefined); + vi.mocked(WebhookEndpoint.findAll).mockResolvedValue([ + endpoint({ eventTypes: ['user.deleted'] }), + ]); + + await dispatchWebhooks(); + + expect(User.findByPk).not.toHaveBeenCalled(); + }); +}); + +describe('deliverDue', () => { + it('returns at once when nothing is due', async () => { + query.mockResolvedValueOnce([]); + + expect(await deliverDue()).toBe(0); + expect(WebhookDelivery.update).not.toHaveBeenCalled(); + }); + + it('leases the claimed rows, then sends each to its endpoint', async () => { + responds(200); + query.mockResolvedValueOnce([{ id: 'd1' }, { id: 'd2' }]); + const first = delivery({ id: 'd1' }); + const second = delivery({ id: 'd2', endpointId: 'gone' }); + vi.mocked(WebhookDelivery.findAll).mockResolvedValue([first, second]); + vi.mocked(WebhookEndpoint.findAll).mockResolvedValue([endpoint()]); + + expect(await deliverDue()).toBe(2); + + expect(query.mock.calls[0][0]).toContain('FOR UPDATE SKIP LOCKED'); + expect(vi.mocked(WebhookDelivery.update).mock.calls[0][0]).toHaveProperty('nextAttemptAt'); + expect(first.status).toBe('succeeded'); + // Its endpoint was deleted or disabled after it was queued: held, not sent. + expect(second.nextAttemptAt).toBeNull(); + expect(calloutRequest).toHaveBeenCalledTimes(1); + }); +}); + +describe('the delivery loop', () => { + it('prunes deliveries older than 30 days', async () => { + vi.mocked(WebhookDelivery.destroy).mockResolvedValue(3 as never); + + expect(await pruneDeliveries(at)).toBe(3); + const where = vi.mocked(WebhookDelivery.destroy).mock.calls[0][0] as any; + const [op] = Object.getOwnPropertySymbols(where.where.createdAt); + const cutoff = where.where.createdAt[op] as Date; + expect(cutoff.toISOString()).toBe('2026-10-08T12:00:00.000Z'); + }); + + it('runs dispatch and delivery until each comes back short, and prunes on the hour', async () => { + query.mockImplementation(async (sql: string) => + sql.includes('pg_try_advisory_xact_lock') ? [{ locked: false }] : [], + ); + vi.mocked(WebhookDelivery.destroy).mockResolvedValue(0 as never); + + await runWebhookTick(0); + expect(WebhookDelivery.destroy).toHaveBeenCalledTimes(1); + + await runWebhookTick(1); + expect(WebhookDelivery.destroy).toHaveBeenCalledTimes(1); + }); + + it('keeps going after a failed tick', async () => { + transaction.mockRejectedValue(new Error('database down')); + + await expect(runWebhookTick(1)).resolves.toBeUndefined(); + }); + + it('polls once a second and skips a tick while one is running', async () => { + vi.useFakeTimers(); + let release: () => void = () => {}; + transaction.mockImplementation( + () => new Promise((resolve) => (release = () => resolve(0))) as never, + ); + + const timer = startWebhookDelivery(); + await vi.advanceTimersByTimeAsync(1000); + await vi.advanceTimersByTimeAsync(1000); + expect(transaction).toHaveBeenCalledTimes(1); + + release(); + clearInterval(timer); + }); +});