diff --git a/deployment/idunn/recipe.toml b/deployment/idunn/recipe.toml index 8179280..48c3577 100644 --- a/deployment/idunn/recipe.toml +++ b/deployment/idunn/recipe.toml @@ -138,16 +138,11 @@ route_required = true optional_environment = [ "CULTMESH_URI_ODIN_RUDP", "GC_ACCESS_APP_BIFROST_BACKEND_CALLBACK_URLS", - "GC_ACCESS_APP_BIFROST_RUNTIME_IDS", "GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE", "GC_ACCESS_APP_GHOSTLIGHT_BACKEND_CALLBACK_URLS", "GC_ACCESS_APP_GHOSTLIGHT_RUNTIME_IDS", "GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET_FILE", - "GC_ACCESS_APP_REPIXELIZER_BACKEND_CALLBACK_URLS", - "GC_ACCESS_APP_REPIXELIZER_RUNTIME_IDS", "GC_ACCESS_APP_REPIXELIZER_SHARED_SECRET_FILE", - "GC_ACCESS_APP_STREAMPIXELS_BACKEND_CALLBACK_URLS", - "GC_ACCESS_APP_STREAMPIXELS_RUNTIME_IDS", "GC_ACCESS_APP_STREAMPIXELS_SHARED_SECRET_FILE", "GC_ACCESS_APPLY_SCHEMA_ON_STARTUP", "GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT", @@ -161,7 +156,6 @@ optional_environment = [ "GC_ACCESS_PRIVATE_COMMAND_PORT", "GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID", "GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE", - "GC_ACCESS_PROVIDER_GITHUB_CLIENT_ID", "GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET_FILE", "GC_ACCESS_PROVIDER_GOOGLE_CLIENT_ID", "GC_ACCESS_PROVIDER_GOOGLE_CLIENT_SECRET_FILE", @@ -169,13 +163,11 @@ optional_environment = [ "GC_ACCESS_PROVIDER_JOYSTICK_CLIENT_SECRET_FILE", "GC_ACCESS_PROVIDER_PATREON_CLIENT_ID", "GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET_FILE", - "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID", "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET_FILE", "GC_ACCESS_PROVIDER_TWITCH_CLIENT_ID", "GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET_FILE", "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID", "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET_FILE", - "GC_ACCESS_REFRESH_TTL_SECONDS", "GC_ACCESS_SESSION_TTL_SECONDS", "GC_ACCESS_SIGNING_KEY_ID", "GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP", @@ -200,7 +192,7 @@ schema_generation = "heimdall-v1" [[state.slots]] id = "service" -relative_path = "cultcache/heimdall.service.cc" +relative_path = "heimdall.service.cc" kind = "cultcache-file" schema = "heimdall.service_state.v1" writer = "process-bound-single-writer" diff --git a/docs/app-profiles/bifrost.md b/docs/app-profiles/bifrost.md index 9a7926c..976452f 100644 --- a/docs/app-profiles/bifrost.md +++ b/docs/app-profiles/bifrost.md @@ -77,37 +77,3 @@ patron points locally. This route is a bridge from auth-owned Patreon evidence to Bifrost-owned governance meaning. Heimdall still does not own points, votes, tiers, ledger history, or payout policy. - -## App-asserted step-up - -Bifrost's profile carries `stepUpAssertion: { methods: ["bifrost-passkey", -"bifrost-email-code"] }`, the only such grant. With its secret and a member's -live Heimdall bearer, Bifrost calls `POST /v1/apps/bifrost/step-up` with -`{method, nonce}` after it has checked the factor itself, and receives an access -token for the same session whose `step_up_at` and `step_up_method` satisfy -Heimdall's unlink check. Bifrost must send a fresh nonce per assertion, keep -the returned token only for the action it is for, and never send a method it did -not verify: Heimdall cannot tell. Contract, codes, limits and what it does not -prove are in `docs/service-contract.md`. - -Precondition and limit: Bifrost can call this only while it holds the member's -Heimdall bearer, which it deliberately does not today. Holding it in a cookie -ticket would turn cookie theft into bearer theft and, with a passkey or email -code, into unlink power. And unlink accepts any method: a `bifrost-email-code` -proof can unlink an identity a Google re-authentication would have guarded. -Requiring a method per route is the later hardening (identity moves). - -## Identity moves - -Bifrost's profile carries `identityMoves: { accountProofMethods: -["bifrost-passkey"] }`, the only such grant (its methods are a subset of -`stepUpAssertion.methods`). With its secret, `POST /v1/apps/bifrost/identity-moves` -moves logins from one Heimdall account to another when it presents fresh proofs -of both: Bifrost's merge saga owns survivor choice, preview and undo timing; -Heimdall moves what the proofs cover. A proof through one login moves only that -login; an asserted `bifrost-passkey` proof covers the whole source account; -`bifrost-email-code` proves an inbox and does not. A multi-login source without a -passkey therefore needs one fresh sign-in per login. Until the Google client is -live, a member's strong proof is the asserted passkey only; Discord and Patreon -give weak (300 s) proofs. Contract, refusal order and idempotency are in -`docs/service-contract.md`. diff --git a/docs/architecture.md b/docs/architecture.md index 956b1db..12fbd4f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -336,49 +336,6 @@ access token (`revoked`) or no refresh is due (`current`; due means a known expiry within 5 minutes, a stored refresh token, and a runtime that refreshes). It never decides that a refresh happens. -### One writer for `linked_identities` moves - -An identity belongs to the account that holds it. `upsertLinkedIdentity` writes -the holder's own row (`ON CONFLICT (provider, provider_user_id) DO UPDATE ... -WHERE linked_identities.account_id = EXCLUDED.account_id`; it never sets -`account_id`) and throws `IdentityHeldElsewhereError` when another account holds -the identity. `unlinkLinkedIdentity` is the only delete: one transaction locks -the account row, refuses the account's last identity, and deletes the row only -for the account that holds it. The store role therefore holds DELETE on -`linked_identities`, checked at startup. The HTTP side (`/v1/me/identities`) is -in `service-contract.md`; an unlink needs a step-up proof inside 600 seconds. - -`moveIdentities` is the only statement that sets `linked_identities.account_id` -to another account, reached only through `POST /v1/apps/{app}/identity-moves`. -One transaction locks both accounts in id order (opposite moves queue, they do -not deadlock), answers a repeated `moveId` from its `identity_moves` row, -re-checks the proof sessions, applies `decideMove` (one pure function both stores -call, so memory and Postgres cannot disagree), moves the rows with credentials -stripped, revokes the source's sessions, expires its pending links and unredeemed -completions, and appends the row. `identity_moves` is append-only (SELECT and -INSERT only, checked at startup). An alias (an account with no login and an -unreversed move from it) is derived inside the transaction to refuse moves into -or out of it, never stored; nothing resolves an alias to its destination, because -no consumer needs it and a chain of moves would make one hop wrong. - -### Step-up proof has two sources - -An access token's `step_up_at` is set in exactly two places: the `sign_in` -step-up callback (Heimdall asked the provider to re-authenticate; label -`provider:`) and `assertStepUp`, the app-asserted route (the app says it -checked a factor; label from the profile's `stepUpAssertion.methods`). Both -feed the one reader, `proofTier` in `claims.ts` (unlink and identity moves both -read it: `strong` is a step-up inside 600 s, `weak` a sign-in inside 300 s via -`auth_at`), and a refresh sets neither. `proofCovers` says what a proof speaks -for: only a strong proof whose method the profile lists as an account proof -covers the whole account; any other proof covers the one login in -`auth_identity_id`. The -asserted route trusts the calling app and is bounded by the app secret, a live -bearer for that app, the method allowlist, a nonce claimed once per session -through `claimOAuthStateUse` (phase `step_up_assert`, no new table or grant; -retained to the session expiry as of the claim, which a refresh may slide past), -and in-process fixed-window limits (`src/fixed-window.ts`). - ### Three nested guards 1. **Single flight, per process.** `refreshesInFlight` is keyed by store, then diff --git a/docs/service-contract.md b/docs/service-contract.md index 2412fbb..0469186 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -236,11 +236,10 @@ Launch note: implemented yet - Repixelizer launch can configure Discord and Patreon on its provider buttons -### Google (OpenID Connect, link-only; mints only under an invite grant) +### Google (OpenID Connect, link-only) -`google` is an identity provider that does not mint an account by itself. It is -a second door into a person who already has one, and a first door only for a -person an app has invited (see the invite grant below). +`google` is an identity provider that never mints an account. It is a second +door into a person who already has one. - Callback redirect URI (register exactly this in the Google Cloud OAuth client): `{GC_ACCESS_BASE_URL}/v1/oauth/google/callback`, which is @@ -257,23 +256,10 @@ person an app has invited (see the invite grant below). - `mode: "link"` needs `Authorization: Bearer ` for the same app; the identity attaches to that token's account and to no other. `mode: "sign_in"` signs in an account the `sub` is already linked to. -- A `sub` no account holds, arriving with `sign_in` and no invite grant, is - refused and mints nothing. A `sub` linked to another account is refused and - never moved. Both audit as `oauth_callback_failed` with error class - `LinkRefusal` and the code `identity_not_linked` or `link_initiator_mismatch`. -- Invite grant. An app whose profile sets `mayGrantFirstLogin` (only `bifrost`) - may start `mode: "sign_in"` with `firstLoginGrant: "invite"`, saying it has - invited this person. The start must carry that app's own secret: any other - caller, including a public start, is `401 app_auth_required`. An app whose - profile may not grant, any other mode, or any other value is - `400 first_login_grant_refused`. The grant rides only in the signed state - (`first_login_grant`), so nothing a browser sends can set it, and the state - stays single-use. At the callback a `sub` no account holds, under a grant, - mints one account with that identity linked, and audits - `account_minted_by_grant` with `{ provider, appSlug }`. A `sub` an account - already holds signs in to that account exactly as without a grant; the grant - never attaches an identity to an existing account and never moves one. - `mode: "link"` takes no grant and is unchanged. +- A `sub` no account holds, arriving with `sign_in`, is refused and mints + nothing. A `sub` linked to another account is refused and never moved. + Both audit as `oauth_callback_failed` with error class `LinkRefusal` + and the code `identity_not_linked` or `link_initiator_mismatch`. - Link is two-phase. The callback verifies the identity and records a pending link (TTL `completionTtlSeconds`), answering `status: "link_pending"` with a `pendingLinkId` and no session; it writes no linked identity. The app calls @@ -562,256 +548,6 @@ Important behavior: - the endpoint is not a provider OAuth start path and should not produce a provider authorization URL -### `GET /v1/me/identities` - -The identities the signed-in account holds, for a member's own view. - -Authentication: a live Heimdall access token for any app as -`Authorization: Bearer` (the same check as `/v1/me/grants`). `401 -sign_in_required` otherwise. The answer is `Cache-Control: no-store`. - -```json -{ - "accountId": "uuid", - "identities": [ - { - "id": "uuid", - "provider": "twitch", - "providerUserId": "12345", - "username": "name", - "displayName": "Name", - "linkedAt": "2026-11-13T12:00:00.000Z", - "scopes": ["user:read:email"] - } - ] -} -``` - -`username` and `displayName` are present when the provider gave them. The -answer never carries a token column, the stored provider profile or the -account's email. - -### `POST /v1/me/identities/{identityId}/unlink` - -Takes one identity off the signed-in account. It is the only way a linked -identity is deleted, and it never takes the account's last one. - -Authentication: a live Heimdall access token for any app, and fresh proof. The -body is empty or `null`. - -- `401 sign_in_required`: no live bearer. -- `403 step_up_required`: the access token carries no `step_up_at` claim, or it - is in the future, or it is older than 600 seconds - (`STEP_UP_PROOF_TTL_SECONDS`, `src/claims.ts`). The remedy is a `sign_in` - start with `stepUp: true` (see step-up above) through an identity on the - account whose provider has re-authentication parameters, today twitch, - youtube and google, then the access token that sign-in returns. -- `404 identity_not_found`: no such identity, or one that belongs to another - account. The two are not distinguishable. -- `409 last_identity`: the account holds no other identity. -- `200`: `{"unlinked": {"id", "provider", "providerUserId"}, "identities": [...]}` - with the remaining list in the shape above. - -`step_up_at` (epoch seconds) is set on the access claim only when the callback's -signed state has `step_up` true and mode `sign_in`, or by an app's `POST -/v1/apps/{appSlug}/step-up` assertion (below). A refresh never carries it: -tokens a refresh issues cannot unlink, so proof is renewed only by a new step-up -sign-in. The unlink writes the audit event `identity_unlinked` (provider and -identity id only). When the account then holds no identity of that provider, the -revocation receipts for its live grants of that provider are written, as the -grants revoke route writes them. - -A Twitch step-up proof is weaker than YouTube's or Google's: `force_verify` does -not force credential re-entry (see the step-up note under the OAuth start -section, "The strengths differ"). - -Limits that stay: - -- Access tokens issued before the unlink keep the unlinked identity in their - `identities` claim and its facts until they expire (`sessionTtlSeconds`). -- Discord and Patreon identities cannot give proof (no re-authentication - parameter); an account holding only those cannot unlink. -- A stolen access token minted by a step-up sign-in can unlink more than one - identity during its 600 second window. -- A sign-in through a provider whose identity is no longer linked mints a new - account. - -A link no longer moves an identity: `upsertLinkedIdentity` refuses an identity -another account holds (`links/confirm` answers `409 identity_linked_elsewhere`, -the callback `link_initiator_mismatch`). An unlinked identity belongs to no -account and can be linked by any account through the normal link flow. - -### `POST /v1/apps/{appSlug}/step-up` - -An app asserts that a member just passed a factor the app itself checked (for -Bifrost: a passkey assertion or an emailed code), and receives an access token -that carries that proof. The unlink route's step-up check then passes unchanged. - -Authentication: both, always. - -- the app's secret in `x-heimdall-app-secret`, as for every app route; and -- the member's live Heimdall access token for the same app as - `Authorization: Bearer`. - -Body (`additionalProperties` are dropped as on the sibling routes): - -```json -{ "method": "bifrost-passkey", "nonce": "16 to 128 characters, fresh per assertion" } -``` - -Nonce: 16 to 128 characters of the base64url alphabet (`A-Za-z0-9_-`), so a -random token fits and spaces, controls and lone surrogates are a 400 schema -refusal. `method` is 1 to 64 characters and then must be in the profile's set. - -Schema validation (body shape, `method` length, the nonce pattern and length, -the app slug) runs before the secret is checked and answers `400` with -Fastify's fixed schema error, the same for every caller whatever the secret and -never audited. Then the order of refusals, each a closed `error` code: - -- `401 app_auth_required`: missing, wrong or another app's secret. The first - check of the handler; nothing is written. -- `403 step_up_assertion_not_permitted`: the app's profile has no - `stepUpAssertion` grant. Only `bifrost` has one; every other app is refused - with its own secret. This branch has its own small budget (5 per 60 s per - app); past it the answer is 429. -- `429 step_up_rate_limited` (`retryAfterSeconds`): the per-app budget (120 per - 60 s, spent by every attempt that passed the secret and the grant, including - ones whose bearer then fails) is spent. In-process fixed windows: they reset - when the process restarts and are not shared between instances. -- `401 sign_in_required`: the bearer is missing, malformed, expired, signed by - another key, a refresh token, or rests on a session that is not live (no row, - wrong account, revoked or expired, revision moved). One answer for all of - them; it does not say whether an account exists. -- `403 bearer_app_mismatch`: a live bearer issued to another app. An app cannot - assert for a token issued to another app. It tells only a holder of the - secret and a valid bearer that the bearer is live and for another app, which - that holder already knows. -- `429 step_up_rate_limited`: the per-account budget (10 per 600 s) is spent. - It is checked after the bearer and its audience, before method and nonce. -- `400 unknown_step_up_method`: `method` is not in the profile's closed set - (`methods` in the answer lists it). Bifrost: `bifrost-passkey`, - `bifrost-email-code`. Provider labels (`provider:*`) cannot be asserted. -- `409 step_up_nonce_replayed`: that nonce was already spent for this session. - The claim is the store's `oauth_state_uses` single-use primitive with phase - `step_up_assert` and the key a SHA-256 of session id and nonce, so it holds - across restarts and instances. **Retention is the session's expiry as of the - claim plus 10.5 minutes (the 10 minute prune margin and 30 s clock skew), and - pruning is lazy: each successful claim deletes at most 50 expired rows.** A refresh slides the session's expiry - without bound, so a nonce can be pruned while its session is still live and - then be accepted again. Replaying it still needs the secret and a live - bearer, which is the power to assert with a fresh nonce; the nonce guards a - captured request, not a compromised app. A refused method or a rate-limited - attempt does not spend the nonce. -- `201`: `{"accessToken", "claimSet", "stepUp": {"at", "method", "validForSeconds"}}`, - `Cache-Control: no-store`. - -What the minted token is: a copy of the bearer's claims with a new `jti`, -`iat` and `nbf`, `step_up_at` = now and `step_up_method` = the asserted method. -It keeps the bearer's `exp`, same `sid` and account. Facts, capabilities and -identities are the bearer's and are not recomputed, so the route adds proof and -no capability. It mints no refresh token and writes no session row: it cannot -extend a lifetime or a session. A later refresh carries neither claim. The proof -is good for the usual 600 seconds (`STEP_UP_PROOF_TTL_SECONDS`) and only until -the token's own `exp`. - -Receipts: each assertion writes the audit event `step_up_asserted`, and each -refusal after the secret verified writes `step_up_assertion_refused`, except -that two kinds are not recorded row by row: a rate-limited refusal is recorded -once per window per budget (its first; the row's `budget` names `app`, -`account` or `notPermitted`), and an app without the grant once per window. -Every other refusal under budget still writes a row each, up to about 121 a -minute for a holder of the secret, and `audit_events` has no retention: that is -an open follow-up. Rows carry the -app, the account and session when the bearer resolved, `method` (null when it -was not in the allowlist), `outcome`, `code`, `budget` (rate-limit rows) and `nonceDigest`. Never the -secret, the bearer, the minted token or the nonce. A request without the secret, -or failing schema validation, writes nothing. - -Precondition: the route is usable only once the app holds the member's Heimdall -bearer. Bifrost deliberately does not hold it today. Putting the bearer in a -cookie ticket would turn cookie theft into bearer theft and, with -`bifrost-passkey` or `bifrost-email-code`, into unlink power; whether and how -Bifrost keeps the bearer is its own decision and is not made here. - -Unlink accepts any method today. A `bifrost-email-code` proof unlinks an -identity a Google re-authentication would have guarded. Identity moves -(below) are the first route to require a method for whole-account coverage; -unlink is unchanged. - -What this does not prove: Heimdall cannot see the passkey or the code. It trusts -the calling app's word, exactly as it trusts `stepUpRequested` (asked, not -verified). The word is bounded by the app secret, a live member bearer for that -app, the profile's method allowlist, a single-use nonce, the proof window and -the rate limits. A compromised Bifrost can assert proofs only for members whose -live bearer it holds. `identity_unlinked` records the proof's `stepUpMethod` -(`provider:`, an app label, or null), and unlink does not yet require any -particular method. - -### `POST /v1/apps/{appSlug}/identity-moves` - -The one sanctioned way a login changes account (`moveIdentities` is the only -writer of `linked_identities.account_id`). Bifrost owns the merge: survivor -choice, preview, grace and undo timing. Heimdall receives the choice as which -proofs fill which side, renders no preview and picks nothing. Only a profile with -`identityMoves` may call it (today bifrost). - -Credential: the app's secret. Body (closed; unknown properties are ignored, and -no account is ever named by the body): - -- `moveId` (`^[A-Za-z0-9_-]{16,64}$`): the caller's idempotency key. -- `fromProofs`: 1 to 8 live Heimdall access tokens for this app, all of the - source account. -- Forward move: `toProof` (a live token of the destination) and optionally - `identityIds` (1 to 32; default every login the source holds). -- Reversal: `reversesMoveId` instead of `toProof`/`identityIds`. It moves back - exactly the logins the forward move carried, once; `fromProofs` must be of the - forward move's destination. A reversal is not itself reversible. - -Each proof must be fresh: a step-up inside 600 s (`strong`) or a sign-in inside -300 s (`weak`), by `proofTier`, the same freshness rule the unlink route reads. -A token with neither claim (a refresh, a link) is stale. - -Coverage: a proof through login X (`auth_identity_id`) moves X and nothing else -from that account. Only a strong proof asserted with a method in the profile's -`identityMoves.accountProofMethods` (`bifrost-passkey`; not `bifrost-email-code`, -which proves an inbox) speaks for the whole account. Moving several logins takes -one proof per login, or the passkey. - -Order of refusals, each a fixed code: `401 app_auth_required`; `403 -not_allowed_for_app`; a replayed `moveId` is answered next (below); `409 -not_reversible` (reversal names a missing, foreign or reversal move); `403 -proof_invalid` `{proof: "from"|"to"}` (not a live bearer of this app, or -`fromProofs` naming two accounts); `409 same_account`; `403 proof_stale` -`{proof}`; `403 identity_not_proved`; then the store: `403 proof_invalid` (a -proof session lapsed under the lock), `409 already_moved` (either side is an -alias), `409 provider_conflict` `{provider}`, `409 not_reversible`, `409 -move_id_conflict`, `404 identity_not_found`, `403 identity_not_proved`. A refusal -body is `{error, detail?, proof?, provider?}` and never names an account id, an -identity the caller did not send, an email or a name. - -On success, in one transaction: the logins move to the destination with their -stored credentials stripped; every live session of the source is revoked and its -pending links and unredeemed completions expire; one append-only `identity_moves` -row is written. Afterwards, for each moved provider the source no longer holds, -its live grants get revocation receipts under the source, and `identity_moved` -is audited. Answer `200`, `Cache-Control: no-store`: -`{moveId, accountId: , movedIdentityIds, proof: {from, to}, reversesMoveId?}`, -with `proof.from` `strong` if any from-proof was strong and `to` null on a -reversal. - -Idempotency: the same `moveId` with the same app, accounts and `reversesMoveId` -answers the stored receipt byte for byte, even though the first success revoked -the source's sessions: the proofs are then checked for a valid Heimdall -signature, issuer, type and audience, and account, not for liveness. The replay -re-runs the revocation receipts, so a crash between commit and receipts heals on -the caller's retry. Anything else under a used `moveId` is `409 move_id_conflict`. - -What a move leaves: an account holding no login with an unreversed move from it -is an alias: derived at move time, never stored, and no route resolves it. A -move into or out of an alias is `already_moved`. Bearers of -the destination keep their old identity list until they refresh. A sign-in -through a moved login lands on the destination because the row moved. - ### `POST /v1/apps/{appSlug}/managed-credentials/resolve` Purpose: @@ -947,10 +683,6 @@ Current claim payload fields: - `typ` - `account_id` - `access_revision` -- `step_up_at` optional: epoch seconds of the proof; set only by a `sign_in` step-up callback or `POST /v1/apps/{appSlug}/step-up`, never by a refresh -- `step_up_method` optional: present exactly when `step_up_at` is; `provider:` for a provider step-up sign-in, otherwise the method label the app asserted -- `auth_at` optional: epoch seconds of the sign-in this token was minted by; set only by a `sign_in` callback (never link, connect or refresh), always with `auth_identity_id` -- `auth_identity_id` optional: the `linked_identities.id` that sign-in came through; the only record of which login proved the session. An asserted step-up spreads the bearer's claims, so these pass through unchanged - `display_name` optional - `app.slug` - `app.profile_version` diff --git a/src/app-profiles.ts b/src/app-profiles.ts index b388ce2..c25dbb2 100644 --- a/src/app-profiles.ts +++ b/src/app-profiles.ts @@ -56,30 +56,6 @@ export interface AppProfile { * state. Absent for apps whose browser starts are public by design. */ startRequiresAppCaller?: boolean; - /** - * The app decides who is invited. Its authenticated sign_in start may carry - * `firstLoginGrant: "invite"`, which lets a provider that otherwise requires a - * link (Google) mint the account for an identity no account holds. The grant - * never attaches an identity to an existing account. Absent for every app that - * may not grant. - */ - mayGrantFirstLogin?: true; - /** - * The app may assert, with its secret and a member's live bearer, that the - * member just passed a factor the app itself checked (POST - * /v1/apps/{app}/step-up). Heimdall cannot see that factor and trusts the - * app, so the grant is explicit per app and closed per method: only these - * labels may be asserted, and they end up in the claim's step_up_method. - * Absent for every app that may not assert. - */ - stepUpAssertion?: { methods: readonly string[] }; - /** - * The app may move linked identities between two accounts it holds proofs - * for (POST /v1/apps/{app}/identity-moves). `accountProofMethods` are the - * asserted step_up_method labels that prove a whole account rather than one - * login; each must be one of stepUpAssertion.methods. Absent: the app may not move. - */ - identityMoves?: { accountProofMethods: readonly string[] }; } /** The membership signal shared by every app that gates on GameCult membership. */ @@ -178,10 +154,6 @@ const bifrostProfile: AppProfile = { managedConnectionProviders: [], allowedReturnOrigins: ["https://bifrost.gamecult.org"], startRequiresAppCaller: true, - mayGrantFirstLogin: true, - stepUpAssertion: { methods: ["bifrost-passkey", "bifrost-email-code"] }, - // A passkey proves the account; an email code proves an inbox, which is one login's worth at most. - identityMoves: { accountProofMethods: ["bifrost-passkey"] }, capabilities: [ { key: "member_access", diff --git a/src/app.ts b/src/app.ts index 5e327cf..2977f08 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,4 +1,4 @@ -import { createHash, createHmac, randomUUID } from "node:crypto"; +import { createHmac, randomUUID } from "node:crypto"; import { deflateRawSync, inflateRawSync } from "node:zlib"; import cookie from "@fastify/cookie"; import cors from "@fastify/cors"; @@ -24,8 +24,7 @@ import { type OAuthStartRequest, type Provider, } from "./contracts.js"; -import { issueAccessClaim, proofCovers, proofTier, signAssertedStepUpClaim, STEP_UP_PROOF_TTL_SECONDS, type IssueAccessClaimInput } from "./claims.js"; -import { FixedWindowBudget, type FixedWindowLimit } from "./fixed-window.js"; +import { issueAccessClaim, type IssueAccessClaimInput } from "./claims.js"; import { builtInAppProfiles, getAppProfile, isAllowedReturnOrigin, serializeAppProfile, admitsProviderForMode, callbackMint, isUsableConnectionTarget } from "./app-profiles.js"; import { renderBrowserHandoffPage } from "./browser-handoff.js"; import { consentText, digestOfText, grantViews, GRANTS_PATH, renderConsentPage, renderGrantsPage, type ConsentAsk } from "./consent.js"; @@ -42,12 +41,11 @@ import { import { ManagedCredentialRefreshFailed, refreshManagedCredential } from "./managed-credential.js"; import { authorizationScopes, buildAuthorizationUrl, providerCatalog, providerExpectedEnv } from "./providers.js"; import { createRuntimeKeyMaterial, signJwt, verifyJwt } from "./signing.js"; -import { createStore, IdentityHeldElsewhereError, type HeimdallStore } from "./store/index.js"; +import { createStore, type HeimdallStore } from "./store/index.js"; import { OAUTH_STATE_SKEW_MS, type CreateAccountInput, type StoredCapabilityGrant, - type StoredIdentityMove, type StoredLinkedIdentity, type UpsertLinkedIdentityInput, } from "./store/types.js"; @@ -103,7 +101,6 @@ function buildOAuthStateToken(options: { entitlementPolicy: OAuthEntitlementPolicy | undefined; requestedScopes: string[] | undefined; stepUp: boolean | undefined; - firstLoginGrant: "invite" | undefined; keys: ReturnType; }): { token: string; jti: string; expiresAt: string } { const issuedAt = nowEpochSeconds(); @@ -127,7 +124,6 @@ function buildOAuthStateToken(options: { entitlement_policy: options.entitlementPolicy ?? null, requested_scopes: options.requestedScopes ?? null, step_up: options.stepUp ? true : null, - first_login_grant: options.firstLoginGrant ?? null, }; const token = signJwt(payload as unknown as Record, options.keys); @@ -192,8 +188,7 @@ function parseOAuthStatePayload(payload: Record): OAuthStatePay !entitlementPolicyIsValid || !(payload.initiator_account_id === undefined || payload.initiator_account_id === null || typeof payload.initiator_account_id === "string") || !requestedScopesAreValid || - !(payload.step_up === undefined || payload.step_up === null || payload.step_up === true) || - !(payload.first_login_grant === undefined || payload.first_login_grant === null || (payload.first_login_grant === "invite" && payload.mode === "sign_in")) + !(payload.step_up === undefined || payload.step_up === null || payload.step_up === true) ) { return null; } @@ -214,9 +209,6 @@ function parseOAuthStatePayload(payload: Record): OAuthStatePay if (!normalizedPayload.step_up) { normalizedPayload.step_up = null; } - if (!normalizedPayload.first_login_grant) { - normalizedPayload.first_login_grant = null; - } return normalizedPayload; } @@ -829,21 +821,10 @@ export async function startOAuthFlow( if (options?.trustedBrowserAttemptId && handoff.kind === "browser_completion") { handoff = { kind: "browser_completion", attemptId: options.trustedBrowserAttemptId }; } - if ((entitlementPolicy || profile.startRequiresAppCaller || input.firstLoginGrant !== undefined || (input.mode === "connect" && input.connection !== undefined)) && (!isAppCaller(caller) || caller.appSlug !== profile.slug)) { + if ((entitlementPolicy || profile.startRequiresAppCaller || (input.mode === "connect" && input.connection !== undefined)) && (!isAppCaller(caller) || caller.appSlug !== profile.slug)) { return { statusCode: 401, body: { error: "app_auth_required" } }; } - // A grant is the app's word that it invited this person: the app-caller gate above has already admitted only the profile's own app, - // and a caller without the secret learns nothing about what a grant needs. Here: only a profile that may grant, only on sign_in. - if (input.firstLoginGrant !== undefined) { - if (!(input.firstLoginGrant === "invite" && input.mode === "sign_in" && profile.mayGrantFirstLogin === true)) { - return { - statusCode: 400, - body: { error: "first_login_grant_refused", detail: "firstLoginGrant needs the app's own sign_in start, from an app that may grant." }, - }; - } - } - // After the app-secret gate, so a caller without the secret learns nothing about what a target must look like. if (input.connection !== undefined && !isUsableConnectionTarget(input.connection.targetId)) { return { @@ -882,7 +863,6 @@ export async function startOAuthFlow( entitlementPolicy, requestedScopes: input.requestedScopes, stepUp: input.stepUp, - firstLoginGrant: input.firstLoginGrant, keys, }); return { @@ -899,38 +879,28 @@ export async function startOAuthFlow( }; } -/** What a live bearer proves: the account its session belongs to, and the claims it was signed with. */ -interface ResolvedBearer { - accountId: string; - claims: Record; - /** When the session row the bearer rests on expires (the refresh horizon, not the access token's `exp`). */ - sessionExpiresAt: string; -} - /** - * The one verifier of a Heimdall access token. The token must verify under - * Heimdall's own key, be an access token for `appSlug` (or, when none is - * named, for any app), be inside its validity window, and belong to a session + * The account a link start binds to: the one a live Heimdall access token for + * this app names. The token must verify under Heimdall's own key, be an access + * token for `appSlug`, be inside its validity window, and belong to a session * the store still holds for that account at that revision. A bearer that fails - * any of these proves nothing. + * any of these binds nothing: a link is explicit or it does not happen. */ -async function resolveBearer( +async function resolveLinkAccount( ctx: Pick, - authorization: string | undefined, - appSlug?: AppSlug -): Promise { + appSlug: AppSlug, + authorization: string | undefined +): Promise { const token = /^Bearer\s+(\S+)$/i.exec(authorization ?? "")?.[1]; if (!token) return null; const verification = verifyJwt(token, ctx.keys.publicKey); if (!verification.valid) return null; const claims = verification.payload; - const audience = appSlug ?? claims.aud; - if (!isAppSlug(audience)) return null; const now = nowEpochSeconds(); if ( claims.typ !== "heimdall_access" || claims.iss !== ctx.config.issuer || - claims.aud !== audience || + claims.aud !== appSlug || typeof claims.account_id !== "string" || typeof claims.sid !== "string" || typeof claims.access_revision !== "number" || @@ -940,7 +910,7 @@ async function resolveBearer( ) { return null; } - const session = await ctx.store.findSession(audience, claims.sid); + const session = await ctx.store.findSession(appSlug, claims.sid); if ( !session || session.accountId !== claims.account_id || @@ -949,16 +919,7 @@ async function resolveBearer( ) { return null; } - return { accountId: claims.account_id, claims, sessionExpiresAt: session.expiresAt }; -} - -/** The account a link start binds to: the one a live Heimdall access token for this app names. A link is explicit or it does not happen. */ -async function resolveLinkAccount( - ctx: Pick, - appSlug: AppSlug, - authorization: string | undefined -): Promise { - return (await resolveBearer(ctx, authorization, appSlug))?.accountId ?? null; + return claims.account_id; } /** The account a Heimdall access token for any app names, when the token and its session are live. */ @@ -966,299 +927,12 @@ async function resolveAccessAccount( ctx: Pick, authorization: string | undefined ): Promise { - return (await resolveBearer(ctx, authorization))?.accountId ?? null; -} - -/** What an app may spend asserting step-up proofs: per member account, and per calling app. */ -export const STEP_UP_ASSERT_LIMITS: { account: FixedWindowLimit; app: FixedWindowLimit; notPermitted: FixedWindowLimit } = { - account: { max: 10, windowMs: 600_000 }, - app: { max: 120, windowMs: 60_000 }, - // An app whose profile has no grant, holding its own secret: a handful of refusals per window, no more. - notPermitted: { max: 5, windowMs: 60_000 }, -}; - -export interface StepUpAssertBudgets { - account: FixedWindowBudget; - app: FixedWindowBudget; - notPermitted: FixedWindowBudget; -} - -export function createStepUpAssertBudgets(now: () => number = () => Date.now()): StepUpAssertBudgets { - return { - account: new FixedWindowBudget(STEP_UP_ASSERT_LIMITS.account, now), - app: new FixedWindowBudget(STEP_UP_ASSERT_LIMITS.app, now), - notPermitted: new FixedWindowBudget(STEP_UP_ASSERT_LIMITS.notPermitted, now), - }; -} - -/** - * POST /v1/apps/{app}/step-up. The app says its member just passed a factor - * the app checked; Heimdall cannot see the factor, so the word is bounded by - * what the route demands: the app's secret AND the member's live bearer for - * that same app, the profile's explicit grant and method allowlist, a nonce - * spent once per session, and a rate per account and per app. Every - * refusal after the secret verified is recorded, except that a flood is not: - * a rate-limited refusal is recorded once per window per budget (its first), - * and an app without the grant is recorded once per window; a request without - * the secret writes nothing, since anyone can send one. The audit rows carry a digest of - * the nonce, never the nonce, the bearer or the secret. - */ -export async function assertStepUp( - ctx: Pick, - budgets: StepUpAssertBudgets, - appSlug: AppSlug, - headers: Record, - input: { method: string; nonce: string } -): Promise { - const { config, keys, store } = ctx; - if (!resolveAppCaller(config, appSlug, headers)) { - return { statusCode: 401, body: { error: "app_auth_required" } }; - } - const permitted = getAppProfile(appSlug)?.stepUpAssertion; - let known: { accountId: string; sessionId: string } | undefined; - let nonceDigest: string | undefined; - let tripped: string | undefined; - const refuse = async (statusCode: number, error: string, extra: Record = {}, record = true): Promise => { - if (!record) return { statusCode, body: { error, ...extra } }; - await store.createAuditEvent({ - ...(known ? { accountId: known.accountId, sessionId: known.sessionId } : {}), - appSlug, - eventType: "step_up_assertion_refused", - eventPayloadJson: { outcome: "refused", code: error, budget: tripped ?? null, method: permitted?.methods.includes(input.method) ? input.method : null, nonceDigest: nonceDigest ?? null }, - createdAt: new Date().toISOString(), - }); - return { statusCode, body: { error, ...extra } }; - }; - // Audit only the first denial of a window: the rows record that a budget tripped, not every request behind it. - const limited = (budget: string, spent: { n: number; retryAfterSeconds: number }, max: number) => { - tripped = budget; - return refuse(429, "step_up_rate_limited", { retryAfterSeconds: spent.retryAfterSeconds }, spent.n === max + 1); - }; - - if (!permitted) { - const spent = budgets.notPermitted.spend(appSlug); - if (spent.retryAfterSeconds) return limited("notPermitted", spent, STEP_UP_ASSERT_LIMITS.notPermitted.max); - return refuse(403, "step_up_assertion_not_permitted", { detail: `${appSlug} may not assert step-up proofs.` }, spent.n === 1); - } - const appSpent = budgets.app.spend(appSlug); - if (appSpent.retryAfterSeconds) return limited("app", appSpent, STEP_UP_ASSERT_LIMITS.app.max); - - const bearer = await resolveBearer(ctx, headers.authorization as string | undefined); - if (!bearer) { - return refuse(401, "sign_in_required", { detail: "Send the member's live Heimdall access token as a Bearer token." }); - } - const sessionId = bearer.claims.sid as string; - known = { accountId: bearer.accountId, sessionId }; - if (bearer.claims.aud !== appSlug) { - return refuse(403, "bearer_app_mismatch", { detail: `The access token was not issued to ${appSlug}.` }); - } - const accountSpent = budgets.account.spend(bearer.accountId); - if (accountSpent.retryAfterSeconds) return limited("account", accountSpent, STEP_UP_ASSERT_LIMITS.account.max); - - nonceDigest = createHash("sha256").update(`heimdall-step-up-nonce\0${sessionId}\0${input.nonce}`).digest("hex"); - if (!permitted.methods.includes(input.method)) { - return refuse(400, "unknown_step_up_method", { methods: permitted.methods }); - } - const at = new Date().toISOString(); - if (!(await store.claimOAuthStateUse({ jti: nonceDigest, phase: "step_up_assert", appSlug, usedAt: at, expiresAt: bearer.sessionExpiresAt }))) { - return refuse(409, "step_up_nonce_replayed", { detail: "A nonce is good once per session; send a fresh one." }); - } - - const minted = signAssertedStepUpClaim({ keys, bearerClaims: bearer.claims, method: input.method }); - await store.createAuditEvent({ - accountId: bearer.accountId, - sessionId, - appSlug, - eventType: "step_up_asserted", - eventPayloadJson: { outcome: "asserted", code: null, method: input.method, nonceDigest, stepUpAt: minted.stepUpAt }, - createdAt: at, - }); - return { - statusCode: 201, - body: { - accessToken: minted.accessToken, - claimSet: minted.claimSet, - stepUp: { at: minted.stepUpAt, method: input.method, validForSeconds: STEP_UP_PROOF_TTL_SECONDS }, - }, - }; -} - -export const MOVE_ID_PATTERN = "^[A-Za-z0-9_-]{16,64}$"; - -export interface MoveIdentitiesBody { - moveId: string; - fromProofs: string[]; - toProof?: string; - identityIds?: string[]; - reversesMoveId?: string; -} - -/** The answer a move gives, derived from its stored row so a replay is byte-identical to the first answer. */ -function moveReceipt(move: StoredIdentityMove) { - const tier = (proofs: { tier: "strong" | "weak" }[]) => (proofs.some((proof) => proof.tier === "strong") ? "strong" : "weak"); - return { - moveId: move.id, - accountId: move.toAccountId, - movedIdentityIds: move.moved.map((moved) => moved.id), - proof: { from: tier(move.proof.from), to: move.proof.to ? move.proof.to.tier : null }, - ...(move.reversesMoveId !== undefined ? { reversesMoveId: move.reversesMoveId } : {}), - }; -} - -/** - * POST /v1/apps/{app}/identity-moves: the one sanctioned way a login changes - * account. The caller's secret and its profile's identityMoves grant open the - * route; the accounts come only from the proofs (live bearers of this app, - * fresh by proofTier), never from the body, an email or a name. A proof - * through login X moves X; only an asserted account proof (the profile's - * accountProofMethods) speaks for the whole account. The store decides and - * commits; this route verifies, maps refusals to fixed codes, then writes the - * revocation receipts the move owes (revokeLiveGrants stays their one writer) - * and the audit row. A replayed moveId is answered before the proofs are - * verified, because the first success revoked the source's sessions. - */ -export async function moveIdentitiesRoute( - ctx: Pick, - revokeLiveGrants: (accountId: string, provider: Provider, receipts: Parameters[0], at: string) => Promise, - appSlug: AppSlug, - headers: Record, - body: MoveIdentitiesBody -): Promise { - const { config, keys, store } = ctx; - const refuse = (statusCode: number, error: string, extra: Record = {}): HandlerResult => ({ statusCode, body: { error, ...extra } }); - if (!resolveAppCaller(config, appSlug, headers)) return refuse(401, "app_auth_required"); - const grant = getAppProfile(appSlug)?.identityMoves; - if (!grant) return refuse(403, "not_allowed_for_app"); - - // The providers a move carried away from its source that the source no longer holds: their grants are taken back under the source. - const settleGrants = async (move: StoredIdentityMove) => { - const held = new Set((await store.listStoredLinkedIdentitiesForAccount(move.fromAccountId)).map((identity) => identity.provider)); - const at = new Date().toISOString(); - for (const provider of new Set(move.moved.map((moved) => moved.provider))) { - if (!held.has(provider)) await revokeLiveGrants(move.fromAccountId, provider, await store.listConsentReceipts(move.fromAccountId), at); - } - }; - - const existing = await store.findIdentityMove(body.moveId); - if (existing) { - const signedFor = (token: string | undefined, accountId: string) => { - const verification = token ? verifyJwt(token, keys.publicKey) : null; - return ( - verification?.valid === true && - verification.payload.typ === "heimdall_access" && - verification.payload.iss === config.issuer && - verification.payload.aud === appSlug && - verification.payload.account_id === accountId - ); - }; - const same = - existing.appSlug === appSlug && - existing.reversesMoveId === body.reversesMoveId && - body.fromProofs.every((token) => signedFor(token, existing.fromAccountId)) && - (existing.reversesMoveId !== undefined ? body.toProof === undefined : signedFor(body.toProof, existing.toAccountId)); - if (!same) return refuse(409, "move_id_conflict"); - await settleGrants(existing); - return { statusCode: 200, body: moveReceipt(existing) }; - } - - let forward: StoredIdentityMove | null = null; - if (body.reversesMoveId !== undefined) { - forward = await store.findIdentityMove(body.reversesMoveId); - if (!forward || forward.appSlug !== appSlug || forward.reversesMoveId !== undefined) return refuse(409, "not_reversible"); - } - - const nowS = nowEpochSeconds(); - const resolve = (token: string) => resolveBearer(ctx, `Bearer ${token}`, appSlug); - const fromBearers = []; - for (const token of body.fromProofs) { - const bearer = await resolve(token); - if (!bearer) return refuse(403, "proof_invalid", { proof: "from" }); - fromBearers.push(bearer); - } - const fromAccountId = fromBearers[0]!.accountId; - if (fromBearers.some((bearer) => bearer.accountId !== fromAccountId)) return refuse(403, "proof_invalid", { proof: "from" }); - let toBearer: ResolvedBearer | null = null; - if (forward === null) { - toBearer = await resolve(body.toProof!); - if (!toBearer) return refuse(403, "proof_invalid", { proof: "to" }); - } else if (fromAccountId !== forward.toAccountId) { - return refuse(409, "not_reversible"); - } - const toAccountId = toBearer?.accountId ?? forward!.fromAccountId; - if (fromAccountId === toAccountId) return refuse(409, "same_account"); - - const proofOf = (bearer: ResolvedBearer, tier: "strong" | "weak") => ({ - tier, - method: tier === "strong" && typeof bearer.claims.step_up_method === "string" ? bearer.claims.step_up_method : null, - identityId: typeof bearer.claims.auth_identity_id === "string" ? bearer.claims.auth_identity_id : null, - }); - const fromProof = []; - for (const bearer of fromBearers) { - const tier = proofTier(bearer.claims, nowS); - if (!tier) return refuse(403, "proof_stale", { proof: "from" }); - fromProof.push(proofOf(bearer, tier)); - } - const toTier = toBearer ? proofTier(toBearer.claims, nowS) : null; - if (toBearer && !toTier) return refuse(403, "proof_stale", { proof: "to" }); - - const coverage = fromBearers.map((bearer) => proofCovers(bearer.claims, grant.accountProofMethods, nowS)); - if (coverage.every((covered) => covered === null)) return refuse(403, "identity_not_proved"); - const covers = coverage.includes("account") ? "account" : coverage.filter((covered): covered is string => covered !== null); - - const at = new Date().toISOString(); - const result = await store.moveIdentities({ - moveId: body.moveId, - appSlug, - fromAccountId, - toAccountId, - identityIds: forward ? forward.moved.map((moved) => moved.id) : (body.identityIds ?? "all"), - covers, - proofSessions: [...fromBearers, ...(toBearer ? [toBearer] : [])].map((bearer) => ({ - appSlug, - sessionId: bearer.claims.sid as string, - accountId: bearer.accountId, - accessRevision: bearer.claims.access_revision as number, - })), - ...(body.reversesMoveId !== undefined ? { reversesMoveId: body.reversesMoveId } : {}), - proof: { from: fromProof, to: toBearer && toTier ? proofOf(toBearer, toTier) : null }, - at, - }); - switch (result.kind) { - case "proof_lapsed": - return refuse(403, "proof_invalid"); - case "already_moved": - case "not_reversible": - case "move_id_conflict": - return refuse(409, result.kind); - case "provider_conflict": - return refuse(409, "provider_conflict", { provider: result.provider }); - case "identity_not_found": - return refuse(404, "identity_not_found"); - case "identity_not_proved": - return refuse(403, "identity_not_proved"); - case "replayed": - await settleGrants(result.move); - return { statusCode: 200, body: moveReceipt(result.move) }; - case "moved": { - const { move } = result; - await settleGrants(move); - await store.createAuditEvent({ - accountId: move.fromAccountId, - appSlug, - eventType: "identity_moved", - eventPayloadJson: { - moveId: move.id, - toAccountId: move.toAccountId, - movedIdentityIds: move.moved.map((moved) => moved.id), - providers: move.moved.map((moved) => moved.provider), - tiers: { from: moveReceipt(move).proof.from, to: moveReceipt(move).proof.to }, - reversesMoveId: move.reversesMoveId ?? null, - }, - createdAt: at, - }); - return { statusCode: 200, body: moveReceipt(move) }; - } - } + const token = /^Bearer\s+(\S+)$/i.exec(authorization ?? "")?.[1]; + if (!token) return null; + const verification = verifyJwt(token, ctx.keys.publicKey); + if (!verification.valid) return null; + const audience = verification.payload.aud; + return isAppSlug(audience) ? resolveLinkAccount(ctx, audience, authorization) : null; } const grantsPageTokenType = "heimdall_grants_page"; @@ -1527,7 +1201,6 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { @@ -2166,15 +1834,6 @@ export async function buildApp(options: BuildAppOptions = {}): Promise( - "/v1/apps/:appSlug/step-up", - { - schema: { - params: { - type: "object", - required: ["appSlug"], - additionalProperties: false, - properties: { appSlug: { type: "string", enum: [...appSlugs] } }, - }, - body: { - type: "object", - required: ["method", "nonce"], - additionalProperties: false, - properties: { - method: { type: "string", minLength: 1, maxLength: 64 }, - // base64url alphabet: what a random token looks like, and no spaces, controls or lone surrogates. - nonce: { type: "string", pattern: "^[A-Za-z0-9_-]{16,128}$" }, - }, - }, - }, - }, - async (request, reply) => { - const result = await assertStepUp({ config, keys, store }, stepUpBudgets, request.params.appSlug, request.headers, request.body); - reply.code(result.statusCode).header("cache-control", "no-store"); - return result.body; - } - ); - app.post<{ Params: { appSlug: AppSlug }; Body: { @@ -3061,146 +2669,6 @@ export async function buildApp(options: BuildAppOptions = {}): Promise[0], at: string): Promise => { - const revoked: string[] = []; - for (const live of grantViews(receipts).filter((view) => view.provider === provider && view.status === "active")) { - const { created } = await store.createConsentReceipt({ - kind: "revocation", - accountId, - appSlug: live.appSlug, - provider: live.provider, - createdAt: at, - revokesReceiptId: live.id, - }); - // A concurrent revoke may have written it first; only the writer reports it. - if (created) revoked.push(live.id); - } - if (revoked.length) { - await store.createAuditEvent({ accountId, eventType: "consent_revoked", eventPayloadJson: { provider, grantIds: revoked }, createdAt: at }); - } - return revoked; - }; - - const identityViews = async (accountId: string) => - (await store.listStoredLinkedIdentitiesForAccount(accountId)).map((identity) => ({ - id: identity.id, - provider: identity.provider, - providerUserId: identity.providerUserId, - ...(identity.username !== undefined ? { username: identity.username } : {}), - ...(identity.displayName !== undefined ? { displayName: identity.displayName } : {}), - linkedAt: identity.createdAt, - scopes: identity.scopes, - })); - - // The identities an account holds: ids and public profile facts, never a - // credential, a stored profile or an email. - app.get("/v1/me/identities", async (request, reply) => { - const bearer = await resolveBearer({ config, keys, store }, request.headers.authorization); - if (!bearer) return signInRequired(reply); - grantsReply(reply); - return { accountId: bearer.accountId, identities: await identityViews(bearer.accountId) }; - }); - - // Taking an identity off the account. The bearer alone is not enough: the - // access token must come from a step-up sign-in inside the proof window, and - // a refresh never carries that proof forward. - app.post<{ Params: { identityId: string }; Body?: null }>( - "/v1/me/identities/:identityId/unlink", - { - schema: { - params: { type: "object", required: ["identityId"], additionalProperties: false, properties: { identityId: { type: "string", minLength: 1 } } }, - body: { type: ["object", "null"], additionalProperties: false, properties: {} }, - }, - }, - async (request, reply) => { - const bearer = await resolveBearer({ config, keys, store }, request.headers.authorization); - if (!bearer) return signInRequired(reply); - grantsReply(reply); - const { accountId, claims } = bearer; - const nowS = nowEpochSeconds(); - if (proofTier(claims, nowS) !== "strong") { - reply.code(403); - return { - error: "step_up_required", - detail: `Unlinking needs a sign-in with stepUp completed within the last ${STEP_UP_PROOF_TTL_SECONDS} seconds: POST /v1/oauth/{provider}/start with mode sign_in and stepUp true through an identity on this account whose provider has re-authentication parameters (today twitch, youtube and google; discord and patreon cannot prove), then use the access token that sign-in returns.`, - }; - } - const result = await store.unlinkLinkedIdentity(accountId, request.params.identityId); - if (result.kind === "not_found") { - reply.code(404); - return { error: "identity_not_found" }; - } - if (result.kind === "last_identity") { - reply.code(409); - return { error: "last_identity", detail: "This is the account's only identity; unlinking it would leave the account unreachable." }; - } - const { identity } = result; - const at = new Date().toISOString(); - await store.createAuditEvent({ - accountId, - eventType: "identity_unlinked", - eventPayloadJson: { provider: identity.provider, identityId: identity.id, stepUpMethod: typeof claims.step_up_method === "string" ? claims.step_up_method : null }, - createdAt: at, - }); - // The credential went with the row. When no identity of that provider - // is left, the grants that rested on it are taken back in the record too. - const remaining = await store.listStoredLinkedIdentitiesForAccount(accountId); - if (!remaining.some((other) => other.provider === identity.provider)) { - await revokeLiveGrants(accountId, identity.provider, await store.listConsentReceipts(accountId), at); - } - return { - unlinked: { id: identity.id, provider: identity.provider, providerUserId: identity.providerUserId }, - identities: await identityViews(accountId), - }; - } - ); - - // The sanctioned mover of logins between accounts: see moveIdentitiesRoute. Registered here because it - // needs revokeLiveGrants, which belongs to this scope. - app.post<{ Params: { appSlug: AppSlug }; Body: MoveIdentitiesBody }>( - "/v1/apps/:appSlug/identity-moves", - { - schema: { - params: { - type: "object", - required: ["appSlug"], - additionalProperties: false, - properties: { appSlug: { type: "string", enum: [...appSlugs] } }, - }, - body: { - type: "object", - required: ["moveId", "fromProofs"], - additionalProperties: false, - properties: { - moveId: { type: "string", pattern: MOVE_ID_PATTERN }, - fromProofs: { type: "array", minItems: 1, maxItems: 8, items: { type: "string", minLength: 1, maxLength: 8192 } }, - toProof: { type: "string", minLength: 1, maxLength: 8192 }, - identityIds: { type: "array", minItems: 1, maxItems: 32, uniqueItems: true, items: { type: "string", minLength: 1 } }, - reversesMoveId: { type: "string", pattern: MOVE_ID_PATTERN }, - }, - // A forward move names its destination proof; a reversal names the move and nothing else about who or what. - oneOf: [ - { required: ["toProof"], not: { anyOf: [{ required: ["reversesMoveId"] }] } }, - { required: ["reversesMoveId"], not: { anyOf: [{ required: ["toProof"] }, { required: ["identityIds"] }] } }, - ], - }, - }, - }, - async (request, reply) => { - const result = await moveIdentitiesRoute({ config, keys, store }, revokeLiveGrants, request.params.appSlug, request.headers, request.body); - reply.code(result.statusCode).header("cache-control", "no-store"); - return result.body; - } - ); - // The signed-in surface for consent: every grant and receipt the account // holds, and the one-click way to take each back. app.get<{ Querystring: { t?: string } }>( @@ -3262,7 +2730,26 @@ export async function buildApp(options: BuildAppOptions = {}): Promise ({ kind: "revoke", updatedAt: at })); } - revoked.push(...(await revokeLiveGrants(accountId, grant.provider, receipts, at))); + for (const live of grantViews(receipts).filter((view) => view.provider === grant.provider && view.status === "active")) { + const { created } = await store.createConsentReceipt({ + kind: "revocation", + accountId, + appSlug: live.appSlug, + provider: live.provider, + createdAt: at, + revokesReceiptId: live.id, + }); + // A concurrent revoke may have written it first; only the writer reports it. + if (created) revoked.push(live.id); + } + if (revoked.length) { + await store.createAuditEvent({ + accountId, + eventType: "consent_revoked", + eventPayloadJson: { provider: grant.provider, grantIds: revoked }, + createdAt: at, + }); + } } if (prefersHtml(request.headers.accept) || request.headers["content-type"]?.startsWith("application/x-www-form-urlencoded")) { reply.type("text/html; charset=utf-8"); diff --git a/src/claims.ts b/src/claims.ts index 8ddd423..4440ed3 100644 --- a/src/claims.ts +++ b/src/claims.ts @@ -11,12 +11,6 @@ import { identityFacts } from "./facts.js"; import { signJwt, type RuntimeKeyMaterial } from "./signing.js"; import { type CreateSessionInput, type HeimdallStore } from "./store/types.js"; -/** How long a step-up sign-in's proof stays good for an action that demands it (identity unlink). */ -export const STEP_UP_PROOF_TTL_SECONDS = 600; - -/** How long a plain sign-in's proof stays good for an action that accepts a weak proof (an identity move). */ -export const AUTH_PROOF_TTL_SECONDS = 300; - function nowEpochSeconds(): number { return Math.floor(Date.now() / 1000); } @@ -54,14 +48,6 @@ export interface IssueAccessClaimInput { sessionId?: string; accessRevision?: number; ttlSeconds?: number; - /** Epoch seconds of a step-up sign-in completing; only that callback sets it, a refresh never does. */ - stepUpAt?: number; - /** Required with stepUpAt (`provider:`); the claim never carries one without the other. */ - stepUpMethod?: string; - /** Epoch seconds of the sign-in that minted this token, with authIdentityId (both or neither). Only a sign_in callback sets them; a refresh, link or connect never does. */ - authAt?: number; - /** The linked_identities.id the sign-in came through. */ - authIdentityId?: string; } export interface IssuedAccessClaimResult { @@ -144,18 +130,6 @@ export async function issueAccessClaim(options: { identities: options.input.linkedIdentities, }; - if (options.input.stepUpAt !== undefined) { - claimSet.step_up_at = options.input.stepUpAt; - if (options.input.stepUpMethod !== undefined) { - claimSet.step_up_method = options.input.stepUpMethod; - } - } - - if (options.input.authAt !== undefined && options.input.authIdentityId !== undefined) { - claimSet.auth_at = options.input.authAt; - claimSet.auth_identity_id = options.input.authIdentityId; - } - if (options.input.displayName) { claimSet.display_name = options.input.displayName; } @@ -217,62 +191,3 @@ export async function issueAccessClaim(options: { : profile.capabilities.filter((capability) => capability.mode === "hybrid"), }; } - -/** - * A new access token for the session the bearer already holds, carrying proof - * the calling app asserted. Everything the bearer claimed is copied and - * nothing is recomputed, so the route can add proof and no capability; `exp` - * stays the bearer's, so it cannot extend a lifetime; no refresh token is - * minted and no session row is written, so it cannot extend the session. - */ -export function signAssertedStepUpClaim(options: { - keys: RuntimeKeyMaterial; - bearerClaims: Record; - method: string; -}): { accessToken: string; claimSet: Record; stepUpAt: number } { - const stepUpAt = nowEpochSeconds(); - const claimSet = { - ...options.bearerClaims, - jti: randomUUID(), - iat: stepUpAt, - nbf: stepUpAt, - step_up_at: stepUpAt, - step_up_method: options.method, - }; - return { accessToken: signJwt(claimSet, options.keys), claimSet, stepUpAt }; -} - -/** - * How fresh a bearer's proof of the member is, from its claims alone: - * `strong` when a step-up (Heimdall's or the app's asserted one) happened in - * the last STEP_UP_PROOF_TTL_SECONDS, else `weak` when the sign-in did in the - * last AUTH_PROOF_TTL_SECONDS, else null. The one freshness rule: identity - * unlink and identity moves both read it. - */ -export function proofTier(claims: Record, nowS: number): "strong" | "weak" | null { - const within = (at: unknown, window: number) => typeof at === "number" && at <= nowS && nowS - at <= window; - if (within(claims.step_up_at, STEP_UP_PROOF_TTL_SECONDS)) return "strong"; - if (within(claims.auth_at, AUTH_PROOF_TTL_SECONDS)) return "weak"; - return null; -} - -/** - * What a fresh proof covers of its account: `account` (every login) only for a - * strong proof whose step_up_method the app's profile lists as an account - * proof; otherwise the one login the sign-in came through (its id); otherwise - * nothing. A proof through login X never speaks for the account's other logins. - */ -export function proofCovers( - claims: Record, - accountProofMethods: readonly string[], - nowS: number -): "account" | string | null { - if ( - proofTier(claims, nowS) === "strong" && - typeof claims.step_up_method === "string" && - accountProofMethods.includes(claims.step_up_method) - ) { - return "account"; - } - return typeof claims.auth_identity_id === "string" ? claims.auth_identity_id : null; -} diff --git a/src/contracts.ts b/src/contracts.ts index 9fa28f8..78b3534 100644 --- a/src/contracts.ts +++ b/src/contracts.ts @@ -80,12 +80,6 @@ export interface OAuthStartRequest { entitlementPolicy?: OAuthEntitlementPolicy; /** Sign_in only, app-authenticated: ask the provider for a real re-authentication. Off when absent. */ stepUp?: boolean; - /** - * Sign_in only, from an app whose profile may grant (`mayGrantFirstLogin`): the app has - * invited this person, so a provider that otherwise requires a link may mint the - * first account. Carried in the signed state; never read from a browser. - */ - firstLoginGrant?: "invite"; } export interface OAuthStatePayload { @@ -109,8 +103,6 @@ export interface OAuthStatePayload { requested_scopes: string[] | null; /** The start's step-up request. Signed, so the launch hop reads it here and nowhere else; null when not asked. */ step_up: true | null; - /** The start's first-login grant. Signed, so only the app's own start can set it; null when not granted. */ - first_login_grant: "invite" | null; } export interface LinkedIdentityInput { @@ -161,19 +153,6 @@ export interface AccessClaimPayload { typ: "heimdall_access"; account_id: string; access_revision: number; - /** Epoch seconds of the step-up sign-in this access token was minted by; absent on every other token, and never carried by a refresh. */ - step_up_at?: number; - /** - * How the proof in step_up_at was made: `provider:` for a step-up - * sign-in Heimdall ran, or one of the calling app's allowlisted method - * labels when the app asserted it (POST /v1/apps/{app}/step-up). Present - * exactly when step_up_at is; never carried by a refresh. - */ - step_up_method?: string; - /** Epoch seconds of the sign-in this access token was minted by, with auth_identity_id; absent unless a sign_in callback minted it, and never carried by a refresh. */ - auth_at?: number; - /** The linked_identities.id the sign-in came through; present exactly when auth_at is. It is the only record of which login proved the session, and it describes the sign-in, not an asserted factor. */ - auth_identity_id?: string; display_name?: string; app: { slug: AppSlug; diff --git a/src/fixed-window.ts b/src/fixed-window.ts deleted file mode 100644 index cfb7f00..0000000 --- a/src/fixed-window.ts +++ /dev/null @@ -1,49 +0,0 @@ -// A fixed-window attempt budget per key, held in memory by the process that -// serves the route. It bounds a credentialed caller's rate; it is not a -// security boundary on its own and resets on restart. The clock is injected -// so tests can move it. - -export interface FixedWindowLimit { - max: number; - windowMs: number; -} - -export class FixedWindowBudget { - private readonly windows = new Map(); - - constructor( - private readonly limit: FixedWindowLimit, - private readonly now: () => number = Date.now, - private readonly maxKeys = 4096, - ) {} - - /** - * Spend one attempt for `key`. `n` counts attempts in the window, denied ones - * included, so a caller can act on the first denial (`n === max + 1`) and not - * on the flood behind it. `retryAfterSeconds` is 0 when allowed. - */ - spend(key: string): { n: number; retryAfterSeconds: number } { - const at = this.now(); - let current = this.windows.get(key); - if (!current || at - current.startedAt >= this.limit.windowMs) { - this.sweep(at); - current = { startedAt: at, used: 0 }; - this.windows.set(key, current); - } - current.used += 1; - if (current.used <= this.limit.max) return { n: current.used, retryAfterSeconds: 0 }; - return { n: current.used, retryAfterSeconds: Math.max(1, Math.ceil((current.startedAt + this.limit.windowMs - at) / 1000)) }; - } - - /** Drop turned-over windows once the table is full; if it is still full, the oldest key goes. */ - private sweep(at: number): void { - if (this.windows.size < this.maxKeys) return; - for (const [key, window] of this.windows) { - if (at - window.startedAt >= this.limit.windowMs) this.windows.delete(key); - } - if (this.windows.size >= this.maxKeys) { - const oldest = this.windows.keys().next().value; - if (oldest !== undefined) this.windows.delete(oldest); - } - } -} diff --git a/src/store/identity-move.ts b/src/store/identity-move.ts deleted file mode 100644 index 7b80d43..0000000 --- a/src/store/identity-move.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { type Provider } from "../contracts.js"; -import { type MoveIdentitiesInput, type StoredIdentityMove, type StoredLinkedIdentity } from "./types.js"; - -/** Everything a store read under its locks that the move rules decide on. */ -export interface MoveFacts { - /** The identity_moves row already holding input.moveId. */ - existing: StoredIdentityMove | null; - /** The move input.reversesMoveId names, and whether a reversal of it already exists. */ - forward: { move: StoredIdentityMove; reversed: boolean } | null; - /** Every proof session still carries its sid, app, account and access revision and has not expired. */ - proofSessionsLive: boolean; - sourceIdentities: readonly StoredLinkedIdentity[]; - destinationProviders: ReadonlySet; - /** An account with no identity and an unreversed move from it. */ - sourceIsAlias: boolean; - destinationIsAlias: boolean; -} - -export type MoveDecision = - | { kind: "replayed"; move: StoredIdentityMove } - | { kind: "refused"; result: { kind: "move_id_conflict" | "proof_lapsed" | "already_moved" | "identity_not_found" | "identity_not_proved" | "not_reversible" } | { kind: "provider_conflict"; provider: Provider } } - | { kind: "move"; identities: StoredLinkedIdentity[] }; - -/** - * The one statement of the move rules, in the order they are decided. Both - * stores gather MoveFacts under their locks and apply the answer, so memory - * and Postgres cannot disagree about what a move refuses. - */ -export function decideMove(input: MoveIdentitiesInput, facts: MoveFacts): MoveDecision { - const refuse = (kind: "move_id_conflict" | "proof_lapsed" | "already_moved" | "identity_not_found" | "identity_not_proved" | "not_reversible"): MoveDecision => ({ kind: "refused", result: { kind } }); - - const { existing } = facts; - if (existing) { - return existing.appSlug === input.appSlug && - existing.fromAccountId === input.fromAccountId && - existing.toAccountId === input.toAccountId && - existing.reversesMoveId === input.reversesMoveId - ? { kind: "replayed", move: existing } - : refuse("move_id_conflict"); - } - if (!facts.proofSessionsLive) return refuse("proof_lapsed"); - - const held = new Set(facts.sourceIdentities.map((identity) => identity.id)); - if (input.reversesMoveId !== undefined) { - const forward = facts.forward; - if ( - !forward || - forward.reversed || - forward.move.appSlug !== input.appSlug || - forward.move.reversesMoveId !== undefined || - forward.move.toAccountId !== input.fromAccountId || - forward.move.fromAccountId !== input.toAccountId || - !forward.move.moved.every((moved) => held.has(moved.id)) - ) { - return refuse("not_reversible"); - } - } else if (facts.sourceIsAlias || facts.destinationIsAlias) { - return refuse("already_moved"); - } - - let chosen: StoredLinkedIdentity[]; - if (input.identityIds === "all") { - chosen = [...facts.sourceIdentities]; - } else { - if (!input.identityIds.every((id) => held.has(id))) return refuse("identity_not_found"); - const wanted = new Set(input.identityIds); - chosen = facts.sourceIdentities.filter((identity) => wanted.has(identity.id)); - } - if (chosen.length === 0) return refuse("identity_not_found"); - - if (input.covers !== "account") { - const covered = new Set(input.covers); - if (!chosen.every((identity) => covered.has(identity.id))) return refuse("identity_not_proved"); - } - const clash = chosen.find((identity) => facts.destinationProviders.has(identity.provider)); - if (clash) return { kind: "refused", result: { kind: "provider_conflict", provider: clash.provider } }; - return { kind: "move", identities: chosen }; -} - -/** The history a move writes about what it carried. */ -export function movedRecord(identities: readonly StoredLinkedIdentity[]): StoredIdentityMove["moved"] { - return identities.map((identity) => ({ - id: identity.id, - provider: identity.provider, - providerUserId: identity.providerUserId, - credentialStripped: identity.accessTokenEncrypted !== undefined || identity.refreshTokenEncrypted !== undefined, - })); -} diff --git a/src/store/in-memory.ts b/src/store/in-memory.ts index f12661d..5df37ea 100644 --- a/src/store/in-memory.ts +++ b/src/store/in-memory.ts @@ -18,7 +18,6 @@ import { type CreateSessionInput, type CreatePrivateCommandReceiptInput, type HeimdallStore, - IdentityHeldElsewhereError, type StoredAccount, type StoredAuthAttempt, type StoredAuthCompletion, @@ -26,13 +25,8 @@ import { type StoredLinkedIdentity, type StoredSession, type StoredPrivateCommandReceipt, - type MoveIdentitiesInput, - type MoveResult, - type StoredIdentityMove, - type UnlinkResult, type UpsertLinkedIdentityInput, } from "./types.js"; -import { decideMove, movedRecord } from "./identity-move.js"; function clone(value: T): T { return JSON.parse(JSON.stringify(value)) as T; @@ -67,7 +61,6 @@ export class InMemoryStore implements HeimdallStore { private readonly entitlementSnapshots = new Map(); private readonly auditEvents = new Map(); private readonly consentReceipts: StoredConsentReceipt[] = []; - private readonly identityMoves = new Map(); async ensureSchema(): Promise { return; @@ -155,9 +148,6 @@ export class InMemoryStore implements HeimdallStore { const existing = [...this.linkedIdentities.values()].find( (identity) => identity.provider === input.provider && identity.providerUserId === input.providerUserId ); - if (existing && existing.accountId !== input.accountId) { - throw new IdentityHeldElsewhereError(); - } const id = existing?.id ?? input.id ?? randomUUID(); const linkedIdentity: StoredLinkedIdentity = { id, @@ -198,87 +188,6 @@ export class InMemoryStore implements HeimdallStore { return clone(linkedIdentity); } - async unlinkLinkedIdentity(accountId: string, identityId: string): Promise { - const target = this.linkedIdentities.get(identityId); - if (!target || target.accountId !== accountId) return { kind: "not_found" }; - const held = [...this.linkedIdentities.values()].filter((identity) => identity.accountId === accountId).length; - if (held <= 1) return { kind: "last_identity" }; - this.linkedIdentities.delete(identityId); - return { kind: "unlinked", identity: clone(target) }; - } - - /** No await between the reads and the writes: the event loop is the lock. */ - async moveIdentities(input: MoveIdentitiesInput): Promise { - const at = Date.parse(input.at); - const forwardMove = input.reversesMoveId !== undefined ? this.identityMoves.get(input.reversesMoveId) : undefined; - const sourceIdentities = [...this.linkedIdentities.values()].filter((identity) => identity.accountId === input.fromAccountId); - const destinationIdentities = [...this.linkedIdentities.values()].filter((identity) => identity.accountId === input.toAccountId); - const decision = decideMove(input, { - existing: this.identityMoves.get(input.moveId) ?? null, - forward: forwardMove ? { move: forwardMove, reversed: this.isReversed(forwardMove.id) } : null, - proofSessionsLive: input.proofSessions.every((proof) => { - const session = this.sessions.get(proof.sessionId); - return ( - session !== undefined && - session.appSlug === proof.appSlug && - session.accountId === proof.accountId && - session.accessRevision === proof.accessRevision && - Date.parse(session.expiresAt) > at - ); - }), - sourceIdentities: clone(sourceIdentities), - destinationProviders: new Set(destinationIdentities.map((identity) => identity.provider)), - sourceIsAlias: sourceIdentities.length === 0 && this.hasUnreversedMoveFrom(input.fromAccountId), - destinationIsAlias: destinationIdentities.length === 0 && this.hasUnreversedMoveFrom(input.toAccountId), - }); - if (decision.kind === "replayed") return { kind: "replayed", move: clone(decision.move) }; - if (decision.kind === "refused") return decision.result; - - for (const identity of decision.identities) { - const row = this.linkedIdentities.get(identity.id)!; - row.accountId = input.toAccountId; - row.updatedAt = input.at; - delete row.accessTokenEncrypted; - delete row.refreshTokenEncrypted; - delete row.tokenExpiresAt; - delete row.refreshFailedAt; - } - for (const session of this.sessions.values()) { - if (session.accountId === input.fromAccountId && Date.parse(session.expiresAt) > at) { - session.expiresAt = input.at; - session.lastSeenAt = input.at; - session.accessRevision += 1; - } - } - for (const row of [...this.pendingLinks.values(), ...this.authCompletions.values()]) { - if (row.accountId === input.fromAccountId && !row.consumedAt && Date.parse(row.expiresAt) > at) row.expiresAt = input.at; - } - const move: StoredIdentityMove = { - id: input.moveId, - appSlug: input.appSlug, - fromAccountId: input.fromAccountId, - toAccountId: input.toAccountId, - ...(input.reversesMoveId !== undefined ? { reversesMoveId: input.reversesMoveId } : {}), - moved: movedRecord(decision.identities), - proof: clone(input.proof), - createdAt: input.at, - }; - this.identityMoves.set(move.id, clone(move)); - return { kind: "moved", move }; - } - - async findIdentityMove(moveId: string): Promise { - return clone(this.identityMoves.get(moveId) ?? null); - } - - private isReversed(moveId: string): boolean { - return [...this.identityMoves.values()].some((move) => move.reversesMoveId === moveId); - } - - private hasUnreversedMoveFrom(accountId: string): boolean { - return [...this.identityMoves.values()].some((move) => move.fromAccountId === accountId && !this.isReversed(move.id)); - } - async updateLinkedIdentityCredential( id: string, decide: (locked: StoredLinkedIdentity) => Promise, diff --git a/src/store/postgres.ts b/src/store/postgres.ts index f0da059..247260c 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -1,7 +1,6 @@ import { randomUUID } from "node:crypto"; import { Pool, type PoolClient, type QueryResultRow } from "pg"; import { type AppSlug, type HeimdallAuthAttemptStatus, type LinkedIdentityInput, type Provider } from "../contracts.js"; -import { decideMove, movedRecord, type MoveFacts } from "./identity-move.js"; import { CREATE_SCHEMA_SQL, REQUIRED_COLUMNS, REQUIRED_KEYS, REQUIRED_TABLES } from "./schema.js"; import { type CreateAccountInput, @@ -19,10 +18,6 @@ import { type CreateSessionInput, type CreatePrivateCommandReceiptInput, type HeimdallStore, - IdentityHeldElsewhereError, - type MoveIdentitiesInput, - type MoveResult, - type StoredIdentityMove, OAUTH_STATE_PRUNE_BATCH, oauthStatePruneCutoffMs, type StoredAccount, @@ -32,7 +27,6 @@ import { type StoredLinkedIdentity, type StoredSession, type StoredPrivateCommandReceipt, - type UnlinkResult, type UpsertLinkedIdentityInput, } from "./types.js"; @@ -179,42 +173,6 @@ function mapAccountRow(row: AccountRow): StoredAccount { return account; } -interface IdentityMoveRow extends QueryResultRow { - id: string; - app_slug: AppSlug; - from_account_id: string; - to_account_id: string; - reverses_move_id: string | null; - moved_json: StoredIdentityMove["moved"]; - proof_json: StoredIdentityMove["proof"]; - created_at: string; -} - -async function selectIdentityMove(db: Pick, moveId: string): Promise { - const result = await db.query("SELECT * FROM identity_moves WHERE id = $1", [moveId]); - const row = result.rows[0]; - if (!row) return null; - return { - id: row.id, - appSlug: row.app_slug, - fromAccountId: row.from_account_id, - toAccountId: row.to_account_id, - ...(row.reverses_move_id ? { reversesMoveId: row.reverses_move_id } : {}), - moved: row.moved_json, - proof: row.proof_json, - createdAt: new Date(row.created_at).toISOString(), - }; -} - -/** A move from this account that no reversal names: the account's identities went elsewhere. */ -async function hasUnreversedMoveFrom(db: Pick, accountId: string): Promise { - const result = await db.query( - "SELECT 1 FROM identity_moves m WHERE m.from_account_id = $1 AND NOT EXISTS (SELECT 1 FROM identity_moves r WHERE r.reverses_move_id = m.id) LIMIT 1", - [accountId] - ); - return (result.rowCount ?? 0) > 0; -} - function mapLinkedIdentityRow(row: LinkedIdentityRow): StoredLinkedIdentity { const identity: StoredLinkedIdentity = { id: row.id, @@ -493,18 +451,13 @@ export function samePredicate(declared: string, actual: string, keyColumns: stri /** * What the store's statements do to each table, and so the privileges its * database role needs: it reads what it returns or looks up, inserts what it - * creates, updates what it changes or upserts, and deletes two things: - * expired oauth_state_uses rows (which needs SELECT for its WHERE), and the one - * linked_identities row an unlink names (unlinkLinkedIdentity, the only - * delete there; it needs SELECT for its WHERE and for the account's count). - * identity_moves is append-only. moveIdentities is the statement that updates - * linked_identities.account_id (its one writer), sessions, pending_links and - * auth_completions, all of which already hold UPDATE. + * creates, updates what it changes or upserts, and deletes only expired + * oauth_state_uses rows (which needs SELECT for its WHERE). * audit_events is written and never read back. */ export const STORE_TABLE_PRIVILEGES: Readonly> = { accounts: ["SELECT", "INSERT", "UPDATE"], - linked_identities: ["SELECT", "INSERT", "UPDATE", "DELETE"], + linked_identities: ["SELECT", "INSERT", "UPDATE"], sessions: ["SELECT", "INSERT", "UPDATE"], auth_attempts: ["SELECT", "INSERT", "UPDATE"], private_command_receipts: ["SELECT", "INSERT"], @@ -514,7 +467,6 @@ export const STORE_TABLE_PRIVILEGES: Readonly { - const client = await this.pool.connect(); - try { - await client.query("BEGIN"); - try { - // The account row serialises its unlinks: two clients racing for the last two identities queue here. - await client.query("SELECT id FROM accounts WHERE id = $1 FOR UPDATE", [accountId]); - const held = await client.query<{ n: string | number }>( - "SELECT count(*) AS n FROM linked_identities WHERE account_id = $1", - [accountId] - ); - let result: UnlinkResult; - if (Number(held.rows[0]?.n ?? 0) <= 1) { - const mine = await client.query("SELECT 1 FROM linked_identities WHERE id = $1 AND account_id = $2", [identityId, accountId]); - result = mine.rowCount ? { kind: "last_identity" } : { kind: "not_found" }; - } else { - const deleted = await client.query( - "DELETE FROM linked_identities WHERE id = $2 AND account_id = $1 RETURNING *", - [accountId, identityId] - ); - result = deleted.rows[0] ? { kind: "unlinked", identity: mapLinkedIdentityRow(deleted.rows[0]) } : { kind: "not_found" }; - } - await client.query("COMMIT"); - return result; - } catch (error) { - await client.query("ROLLBACK"); - throw error; - } - } finally { - client.release(); - } - } - - async moveIdentities(input: MoveIdentitiesInput): Promise { - const client = await this.pool.connect(); - try { - await client.query("BEGIN"); - try { - // Both accounts, one statement each in id order, before anything is read: opposite moves queue here - // instead of deadlocking. The order is the code's own, not whatever order a plan locks a set in. - for (const id of [input.fromAccountId, input.toAccountId].sort()) { - await client.query("SELECT id FROM accounts WHERE id = $1 FOR UPDATE", [id]); - } - const existing = await selectIdentityMove(client, input.moveId); - let forward: MoveFacts["forward"] = null; - if (input.reversesMoveId !== undefined) { - const forwardMove = await selectIdentityMove(client, input.reversesMoveId); - const reversal = forwardMove ? await client.query("SELECT 1 FROM identity_moves WHERE reverses_move_id = $1", [forwardMove.id]) : null; - forward = forwardMove ? { move: forwardMove, reversed: (reversal?.rowCount ?? 0) > 0 } : null; - } - let proofSessionsLive = true; - for (const proof of input.proofSessions) { - const live = await client.query( - "SELECT 1 FROM sessions WHERE id = $1 AND app_slug = $2 AND account_id = $3 AND access_revision = $4 AND expires_at > $5", - [proof.sessionId, proof.appSlug, proof.accountId, proof.accessRevision, input.at] - ); - if (!live.rowCount) proofSessionsLive = false; - } - const source = await client.query( - "SELECT * FROM linked_identities WHERE account_id = $1 ORDER BY created_at ASC, id ASC FOR UPDATE", - [input.fromAccountId] - ); - const destination = await client.query<{ provider: Provider }>("SELECT provider FROM linked_identities WHERE account_id = $1", [input.toAccountId]); - const sourceIdentities = source.rows.map(mapLinkedIdentityRow); - const decision = decideMove(input, { - existing, - forward, - proofSessionsLive, - sourceIdentities, - destinationProviders: new Set(destination.rows.map((row) => row.provider)), - sourceIsAlias: sourceIdentities.length === 0 && (await hasUnreversedMoveFrom(client, input.fromAccountId)), - destinationIsAlias: destination.rowCount === 0 && (await hasUnreversedMoveFrom(client, input.toAccountId)), - }); - if (decision.kind !== "move") { - await client.query("ROLLBACK"); - return decision.kind === "replayed" ? { kind: "replayed", move: decision.move } : decision.result; - } - const ids = decision.identities.map((identity) => identity.id); - await client.query( - `UPDATE linked_identities - SET account_id = $2, access_token_encrypted = NULL, refresh_token_encrypted = NULL, - token_expires_at = NULL, refresh_failed_at = NULL, updated_at = $3 - WHERE id = ANY($1) AND account_id = $4`, - [ids, input.toAccountId, input.at, input.fromAccountId] - ); - await client.query( - "UPDATE sessions SET expires_at = $2, last_seen_at = $2, access_revision = access_revision + 1 WHERE account_id = $1 AND expires_at > $2", - [input.fromAccountId, input.at] - ); - for (const table of ["pending_links", "auth_completions"]) { - await client.query( - `UPDATE ${table} SET expires_at = $2 WHERE account_id = $1 AND consumed_at IS NULL AND expires_at > $2`, - [input.fromAccountId, input.at] - ); - } - const move: StoredIdentityMove = { - id: input.moveId, - appSlug: input.appSlug, - fromAccountId: input.fromAccountId, - toAccountId: input.toAccountId, - ...(input.reversesMoveId !== undefined ? { reversesMoveId: input.reversesMoveId } : {}), - moved: movedRecord(decision.identities), - proof: input.proof, - createdAt: input.at, - }; - try { - await client.query( - `INSERT INTO identity_moves (id, app_slug, from_account_id, to_account_id, reverses_move_id, moved_json, proof_json, created_at) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, - [move.id, move.appSlug, move.fromAccountId, move.toAccountId, nullable(move.reversesMoveId), JSON.stringify(move.moved), JSON.stringify(move.proof), move.createdAt] - ); - } catch (error) { - // The row is the arbiter of a race the locks did not serialise (a reversal of the same move through another pool). - if ((error as { code?: string }).code !== "23505") throw error; - await client.query("ROLLBACK"); - const winner = await this.findIdentityMove(input.moveId); - if (!winner) return { kind: "not_reversible" }; - const again = decideMove(input, { existing: winner, forward: null, proofSessionsLive: true, sourceIdentities: [], destinationProviders: new Set(), sourceIsAlias: false, destinationIsAlias: false }); - return again.kind === "replayed" ? { kind: "replayed", move: again.move } : { kind: "move_id_conflict" }; - } - await client.query("COMMIT"); - return { kind: "moved", move }; - } catch (error) { - await client.query("ROLLBACK").catch(() => undefined); - throw error; - } - } finally { - client.release(); - } - } - - async findIdentityMove(moveId: string): Promise { - return selectIdentityMove(this.pool, moveId); + return mapLinkedIdentityRow(expectRow(result.rows[0], "upsertLinkedIdentity")); } async updateLinkedIdentityCredential( diff --git a/src/store/schema.ts b/src/store/schema.ts index ff1fcf2..3678122 100644 --- a/src/store/schema.ts +++ b/src/store/schema.ts @@ -216,29 +216,6 @@ CREATE UNIQUE INDEX IF NOT EXISTS consent_receipts_revokes_unique_idx CREATE INDEX IF NOT EXISTS consent_receipts_account_idx ON consent_receipts(account_id, created_at); --- One row per identity move, append-only: no UPDATE and no DELETE, and no --- ON DELETE CASCADE, so the record outlives nothing it names. moved_json is --- [{id, provider, providerUserId, credentialStripped}]; proof_json is --- {from: [{tier, method, identityId}], to: {...} | null}. Never a token, sid, --- email or name. A move is reversed once: the second row naming it conflicts. -CREATE TABLE IF NOT EXISTS identity_moves ( - id TEXT PRIMARY KEY, - app_slug TEXT NOT NULL, - from_account_id TEXT NOT NULL REFERENCES accounts(id), - to_account_id TEXT NOT NULL REFERENCES accounts(id), - reverses_move_id TEXT REFERENCES identity_moves(id), - moved_json JSONB NOT NULL, - proof_json JSONB NOT NULL, - created_at TIMESTAMPTZ NOT NULL -); - -CREATE UNIQUE INDEX IF NOT EXISTS identity_moves_reverses_unique_idx - ON identity_moves(reverses_move_id) - WHERE reverses_move_id IS NOT NULL; - -CREATE INDEX IF NOT EXISTS identity_moves_from_idx - ON identity_moves(from_account_id); - CREATE TABLE IF NOT EXISTS audit_events ( id TEXT PRIMARY KEY, account_id TEXT, diff --git a/src/store/types.ts b/src/store/types.ts index 78d12a4..a2a792d 100644 --- a/src/store/types.ts +++ b/src/store/types.ts @@ -41,78 +41,6 @@ export interface StoredLinkedIdentity { updatedAt: string; } -/** - * An upsert named an identity another account holds. A provider identity - * belongs to the account that holds it until that account unlinks it; no - * write moves it. - */ -export class IdentityHeldElsewhereError extends Error { - constructor() { - super("This provider identity is held by another account."); - this.name = "IdentityHeldElsewhereError"; - } -} - -/** What unlinkLinkedIdentity decided; `identity` is the row as it was deleted. */ -export type UnlinkResult = - | { kind: "unlinked"; identity: StoredLinkedIdentity } - | { kind: "last_identity" } - | { kind: "not_found" }; - -/** One login a move carried; `credentialStripped` is history written at the move (the row held a token the move dropped). */ -export interface MovedIdentity { - id: string; - provider: Provider; - providerUserId: string; - credentialStripped: boolean; -} - -/** What each side's proofs were, as tiers and methods only: never a token, sid, email or name. */ -export interface IdentityMoveProof { - from: { tier: "strong" | "weak"; method: string | null; identityId: string | null }[]; - to: { tier: "strong" | "weak"; method: string | null; identityId: string | null } | null; -} - -/** The append-only record of one move. */ -export interface StoredIdentityMove { - id: string; - appSlug: AppSlug; - fromAccountId: string; - toAccountId: string; - reversesMoveId?: string; - moved: MovedIdentity[]; - proof: IdentityMoveProof; - createdAt: string; -} - -export interface MoveIdentitiesInput { - moveId: string; - appSlug: AppSlug; - fromAccountId: string; - toAccountId: string; - /** The logins to carry, or every login the source holds. */ - identityIds: readonly string[] | "all"; - /** What the caller's from-proofs cover: the whole account, or exactly these logins. */ - covers: "account" | readonly string[]; - /** Sessions the proofs rested on; each must still be live when the transaction commits. */ - proofSessions: readonly { appSlug: AppSlug; sessionId: string; accountId: string; accessRevision: number }[]; - reversesMoveId?: string; - proof: IdentityMoveProof; - at: string; -} - -/** What moveIdentities decided. Refusals write nothing. */ -export type MoveResult = - | { kind: "moved"; move: StoredIdentityMove } - | { kind: "replayed"; move: StoredIdentityMove } - | { kind: "move_id_conflict" } - | { kind: "proof_lapsed" } - | { kind: "already_moved" } - | { kind: "identity_not_found" } - | { kind: "identity_not_proved" } - | { kind: "provider_conflict"; provider: Provider } - | { kind: "not_reversible" }; - export interface UpsertLinkedIdentityInput { id?: string; accountId: string; @@ -263,8 +191,7 @@ export function oauthStatePruneCutoffMs(nowMs: number): number { export interface ClaimOAuthStateUseInput { jti: string; - /** `step_up_assert` is the app-asserted step-up route's one-use nonce claim: jti is a digest of session and nonce. */ - phase: "launch" | "callback" | "step_up_assert"; + phase: "launch" | "callback"; appSlug: AppSlug; usedAt: string; expiresAt: string; @@ -384,26 +311,7 @@ export interface HeimdallStore { findStoredLinkedIdentity(provider: Provider, providerUserId: string): Promise; findStoredLinkedIdentityForAccount(accountId: string, provider: Provider): Promise; listStoredLinkedIdentitiesForAccount(accountId: string): Promise; - /** Writes the holder's own row; throws IdentityHeldElsewhereError rather than move another account's identity. */ upsertLinkedIdentity(input: UpsertLinkedIdentityInput): Promise; - /** - * The only delete of a linked identity. One transaction locks the account, - * refuses to take its last identity, and deletes the row only if the - * account holds it (an id that is missing or another account's is the same - * `not_found`). - */ - unlinkLinkedIdentity(accountId: string, identityId: string): Promise; - /** - * The only writer that sets a linked identity's account to another account, - * in one transaction: lock both accounts (in id order), answer a repeated - * moveId from its row, re-check the proof sessions, refuse what the rules - * refuse, move the rows with their credentials stripped, revoke the source's - * sessions and expire its pending links and unredeemed completions, and - * append the identity_moves row. A reversal (`reversesMoveId`) moves back - * exactly what the forward move carried. The destination never loses an identity. - */ - moveIdentities(input: MoveIdentitiesInput): Promise; - findIdentityMove(moveId: string): Promise; /** * Serialise decisions about one row's credential. `decide` receives the row * as read under the lock (never a caller's snapshot) and the decision is diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 279b21e..f7fa724 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -38,6 +38,3 @@ {"ts": "2026-10-19T15:56:24+00:00", "type": "design", "status": "accepted", "note": "Refresh is now one locked primitive for every provider (replaces unserialized refreshLinkedIdentityCredentialIfNeeded); Joystick is managed-only (Heimdall-held credential, no viewer sign-in until joystick:follow_up:joystick-viewer-signin-public-bot). Merged in PR #1, live at d51fa6b; campaign joystick:campaign:self.", "branch": "eureka/joystick-h1"} {"ts": "2026-10-19T16:03:16+00:00", "type": "verification", "status": "accepted", "note": "Live d51fa6b (H1) verified by a real human sign-in: the operator's StreamPixels Twitch sign-in through Heimdall start/callback, 2026-10-19 ('Twitch auth worked fine'); a streampixels session was created 16:02:33Z, after the 15:51Z switch. Joystick consent round trip still open: joystick:follow_up:h1-joystick-consent-round-trip."} {"ts": "2026-11-12T23:10:15+00:00", "type": "design", "status": "accepted", "note": "Changelog 2026-11-12: sign_in start accepts stepUp (app-authenticated, sign_in only, off by default); signed state carries step_up; launch adds Twitch force_verify=true, YouTube prompt='login consent', Google prompt=login; any other provider is 400 step_up_not_supported; completion reports stepUpRequested. Not deployed. For joystick:follow_up:chat-s7055-7056 (StreamPixels link hardening, second factor via fresh sign-in)."} -{"ts": "2026-11-13T19:10:00+00:00", "type": "design", "status": "accepted", "note": "Changelog 2026-11-13: GET /v1/me/identities lists an account's identities (no credentials, profile or email); POST /v1/me/identities/:id/unlink deletes one with a step-up proof (access claim step_up_at, 600 s, never carried by refresh), refuses the last identity (409), writes revocation receipts when the provider's last identity goes. upsertLinkedIdentity no longer moves an identity between accounts (IdentityHeldElsewhereError; links/confirm 409 identity_linked_elsewhere, callback link_initiator_mismatch). The store role needs DELETE on linked_identities (startup refuses without it): owner-role GRANT at deploy."} -{"ts": "2026-11-13T20:01:42+00:00", "type": "design", "status": "accepted", "note": "Changelog 2026-11-13: POST /v1/apps/{app}/step-up (profile grant stepUpAssertion, bifrost only; methods bifrost-passkey, bifrost-email-code). App secret plus the member's live bearer for that app; mints a same-session access token with step_up_at now and new claim step_up_method (exp kept, no refresh, no session write); nonce single-use via oauth_state_uses phase step_up_assert (no schema change), retained to the session expiry as of the claim (a refresh may slide the session past it); in-process rate limits 10 per 600 s per account, 120 per 60 s per app; audit step_up_asserted and step_up_assertion_refused with a nonce digest (429s and not-permitted refusals audited once per window; not-permitted has a 5 per 60 s per-app budget); nonce is base64url 16-128. Provider step-up sign-ins now carry step_up_method provider:; identity_unlinked records stepUpMethod. Heimdall cannot verify the factor: it trusts the calling app. Not deployed; no env, secret or migration. For heimdall-body:follow_up:chat-s7419-7419.", "branch": "heimdall/app-asserted-step-up"} -{"ts": "2026-11-14T01:10:00+00:00", "type": "design", "status": "accepted", "note": "Changelog 2026-11-14: POST /v1/apps/{app}/identity-moves (profile grant identityMoves, bifrost only; accountProofMethods bifrost-passkey) and the identity_moves table, the only writer of linked_identities.account_id (moveIdentities, one transaction, accounts locked in id order, shared decideMove on both stores). Access claims gain auth_at and auth_identity_id (sign_in callback only). proofTier is the one freshness rule (unlink reads it; strong 600 s step_up_at, weak 300 s auth_at); proofCovers: only an asserted account-proof method covers a whole account, otherwise the login in auth_identity_id (ruling move-proof-strict-passkey). Moves strip credentials, revoke the source's sessions, expire its pending links and unredeemed completions, write revocation receipts under the source, audit identity_moved; moveId is idempotent (replay answers the stored receipt without proof liveness); a move is reversible once. Not deployed: the owner must apply the identity_moves DDL and GRANT SELECT, INSERT ON identity_moves to the store role before the new build starts (startup refuses SCHEMA_MISSING / SCHEMA_PRIVILEGES otherwise).", "branch": "heimdall/identity-moves"} diff --git a/tests/google-link.test.ts b/tests/google-link.test.ts index 630d4a1..a33f27c 100644 --- a/tests/google-link.test.ts +++ b/tests/google-link.test.ts @@ -5,7 +5,7 @@ import { buildApp } from "../src/app.js"; import { loadConfig, type HeimdallConfig } from "../src/config.js"; import { resetGoogleJwksCache } from "../src/google-oidc.js"; import { type OAuthProviderRuntime } from "../src/oauth.js"; -import { IdentityHeldElsewhereError, InMemoryStore } from "../src/store/index.js"; +import { InMemoryStore } from "../src/store/index.js"; import { launchFlow, launchWithRedirect, stateOf, type LaunchedFlow } from "./oauth-flow.js"; const CLIENT_ID = "google-client"; @@ -25,7 +25,7 @@ function config(): HeimdallConfig { storage: { backend: "memory", applySchemaOnStartup: true }, tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"), bootstrapSigningPrivateKeyOnMissing: true, - appSharedSecrets: { ...base.appSharedSecrets, bifrost: "bifrost-secret", repixelizer: "repixelizer-secret" }, + appSharedSecrets: { ...base.appSharedSecrets, bifrost: "bifrost-secret" }, providers: { ...base.providers, google: { clientId: CLIENT_ID, clientSecret: "google-secret" }, @@ -188,18 +188,6 @@ afterEach(async () => { while (apps.length) await apps.pop()?.close(); }); -describe("a link write that loses the race to another account", () => { - it("links/confirm answers 409 identity_linked_elsewhere when the store refuses the move after the check passed", async () => { - const { app, store } = await build(); - const { accessToken } = await signInWithDiscord(app); - const done = await linkGoogleCallback(app, accessToken); - expect(done.statusCode).toBe(201); - vi.spyOn(store, "upsertLinkedIdentity").mockRejectedValueOnce(new IdentityHeldElsewhereError()); - const confirmed = await confirmLink(app, accessToken, done.json().pendingLinkId); - expect([confirmed.statusCode, confirmed.json().error]).toEqual([409, "identity_linked_elsewhere"]); - }); -}); - describe("Google as a Heimdall OIDC provider", () => { it("builds the authorization request: openid email profile, the exact callback, state, nonce and an S256 challenge", async () => { const { app } = await build(); @@ -535,141 +523,3 @@ describe("Google as a Heimdall OIDC provider", () => { expect(accountCount(store)).toBe(1); }); }); - -describe("an invite grant lets Bifrost's sign-in start mint the first Google account", () => { - const RETURN = "https://bifrost.gamecult.org/auth/heimdall/complete"; - - function startGrant(app: FastifyInstance, extra: Record = {}, headers: Record = BIFROST_APP) { - return app.inject({ - method: "POST", - url: "/v1/oauth/google/start", - headers, - payload: { appSlug: "bifrost", mode: "sign_in", returnTo: RETURN, firstLoginGrant: "invite", ...extra }, - }); - } - - async function googleCallback(app: FastifyInstance, start: { json(): never }, claims?: Record) { - const flow = await launchWithRedirect(app, start.json()); - fakeGoogle({ nonceFrom: () => flow.url.searchParams.get("nonce") ?? undefined, ...(claims ? { claims } : {}) }); - return { flow, done: await callbackGoogle(app, flow) }; - } - - const auditEvents = (store: InMemoryStore) => - [...(store as unknown as { auditEvents: Map }).auditEvents.values()]; - - it("google_first_login_without_grant_refused: no grant, identity_not_linked, nothing minted", async () => { - const { app, store } = await build(); - const start = await startGoogle(app, undefined, "sign_in"); - const { done } = await googleCallback(app, start); - expect([done.statusCode, done.json().error]).toEqual([403, "identity_not_linked"]); - expect(accountCount(store)).toBe(0); - }); - - it("google_first_login_with_bifrost_grant_mints: one account, the identity linked to it, audited", async () => { - const { app, store } = await build(); - const start = await startGrant(app); - expect(start.statusCode).toBe(201); - const { done } = await googleCallback(app, start); - expect(done.statusCode).toBe(201); - expect(accountCount(store)).toBe(1); - expect((await store.findStoredLinkedIdentity("google", "g-sub-1"))?.accountId).toBe(done.json().account.id); - const minted = auditEvents(store).filter((e) => e.eventType === "account_minted_by_grant"); - expect(minted.map((e) => e.eventPayloadJson)).toEqual([{ provider: "google", appSlug: "bifrost" }]); - }); - - it("a granted state is single-use: replaying the callback mints nothing more", async () => { - const { app, store } = await build(); - const start = await startGrant(app); - const { flow } = await googleCallback(app, start); - const again = await callbackGoogle(app, flow); - expect(again.statusCode).toBeGreaterThanOrEqual(400); - expect(accountCount(store)).toBe(1); - }); - - it("grant_from_other_app_refused: an app whose profile may not grant gets first_login_grant_refused", async () => { - const { app, store } = await build(); - const res = await app.inject({ - method: "POST", - url: "/v1/oauth/discord/start", - headers: { "x-heimdall-app-secret": "repixelizer-secret" }, - payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/", firstLoginGrant: "invite" }, - }); - expect([res.statusCode, res.json().error]).toEqual([400, "first_login_grant_refused"]); - // Another app's secret on Bifrost's start is no Bifrost caller. - const other = await startGrant(app, {}, { "x-heimdall-app-secret": "repixelizer-secret" }); - expect(other.statusCode).toBe(401); - expect(accountCount(store)).toBe(0); - }); - - it("grant_without_app_caller_refused: a public start with firstLoginGrant is refused", async () => { - const { app, store } = await build(); - for (const headers of [{}, { "x-heimdall-app-secret": "wrong" }]) { - const res = await startGrant(app, {}, headers); - expect(res.statusCode, JSON.stringify(headers)).toBeGreaterThanOrEqual(400); - expect(res.json().authorizationUrl).toBeUndefined(); - } - // An app that does not require a caller is still refused: a grant is a start only the app itself may make. - const open = await app.inject({ - method: "POST", - url: "/v1/oauth/discord/start", - payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/", firstLoginGrant: "invite" }, - }); - expect([open.statusCode, open.json().error]).toEqual([401, "app_auth_required"]); - expect(accountCount(store)).toBe(0); - }); - - it("refuses a grant on link mode and a grant value other than invite", async () => { - const { app } = await build(); - const { accessToken } = await signInWithDiscord(app); - const link = await app.inject({ - method: "POST", - url: "/v1/oauth/google/start", - headers: { ...BIFROST_APP, authorization: `Bearer ${accessToken}` }, - payload: { appSlug: "bifrost", mode: "link", returnTo: RETURN, firstLoginGrant: "invite" }, - }); - expect([link.statusCode, link.json().error]).toEqual([400, "first_login_grant_refused"]); - expect((await startGrant(app, { firstLoginGrant: "admin" })).statusCode).toBe(400); - }); - - it("grant_ignored_for_existing_account: a Google identity already held signs in to its account, no second account", async () => { - const { app, store } = await build(); - const { accessToken, accountId } = await signInWithDiscord(app); - await linkGoogle(app, accessToken); - const start = await startGrant(app); - const { done } = await googleCallback(app, start); - expect(done.statusCode).toBe(201); - expect(done.json().account.id).toBe(accountId); - expect(accountCount(store)).toBe(1); - expect(auditEvents(store).some((e) => e.eventType === "account_minted_by_grant")).toBe(false); - }); - - it("a grant never attaches an identity to an existing account: a new sub mints its own account and an held sub is never moved", async () => { - const store = new InMemoryStore(); - const first = await build(store, "discord-1"); - const a = await signInWithDiscord(first.app, "discord-1"); - await linkGoogle(first.app, a.accessToken); - const second = await build(store, "discord-2"); - const b = await signInWithDiscord(second.app, "discord-2"); - const start = await startGrant(second.app); - const { done } = await googleCallback(second.app, start, { sub: "g-sub-new" }); - expect(done.statusCode).toBe(201); - expect(done.json().account.id).not.toBe(a.accountId); - expect(done.json().account.id).not.toBe(b.accountId); - expect((await store.findStoredLinkedIdentity("google", "g-sub-1"))?.accountId).toBe(a.accountId); - expect((await store.findStoredLinkedIdentity("google", "g-sub-new"))?.accountId).toBe(done.json().account.id); - }); - - it("grant_tampered_state_refused: a first_login_grant added to a signed state fails verification", async () => { - const { app, store } = await build(); - const plain = await startGoogle(app, undefined, "sign_in"); - const [head, body, sig] = stateOf(plain.json()).split("."); - const payload = JSON.parse(Buffer.from(body!, "base64url").toString()); - const forged = [head, Buffer.from(JSON.stringify({ ...payload, first_login_grant: "invite" })).toString("base64url"), sig].join("."); - const launched = await app.inject({ method: "GET", url: `/v1/oauth/google/launch?state=${encodeURIComponent(forged)}` }); - expect(launched.statusCode).toBe(400); - expect(launched.headers.location).toBeUndefined(); - const cb = await app.inject({ method: "GET", url: `/v1/oauth/google/callback?code=g-code&state=${encodeURIComponent(forged)}` }); - expect(cb.statusCode).toBeGreaterThanOrEqual(400); - expect(accountCount(store)).toBe(0); - }); -}); diff --git a/tests/identity-moves.test.ts b/tests/identity-moves.test.ts deleted file mode 100644 index bc41597..0000000 --- a/tests/identity-moves.test.ts +++ /dev/null @@ -1,632 +0,0 @@ -import { mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { afterAll, afterEach, describe, expect, it, vi } from "vitest"; -import { buildApp } from "../src/app.js"; -import { builtInAppProfiles } from "../src/app-profiles.js"; -import { AUTH_PROOF_TTL_SECONDS, issueAccessClaim, proofTier } from "../src/claims.js"; -import { type AppSlug, type Provider } from "../src/contracts.js"; -import { type OAuthProviderRuntime } from "../src/oauth.js"; -import { createRuntimeKeyMaterial } from "../src/signing.js"; -import { InMemoryStore } from "../src/store/index.js"; -import { type CreateAuditEventInput } from "../src/store/types.js"; -import { createTestConfig, launchFlow } from "./oauth-flow.js"; - -// POST /v1/apps/{app}/identity-moves, driven over HTTP the way Bifrost would -// call it: the proofs are real access tokens whose claims say how and through -// which login the member signed in; the answers are what a caller can see. - -const now = "2026-11-14T12:00:00.000Z"; -const appAuth = { "x-heimdall-app-secret": "bifrost-secret" }; -const moveId = (tag: string) => `move-${tag}`.padEnd(20, "x"); -const nowS = () => Math.floor(Date.now() / 1000); - -const dir = mkdtempSync(join(tmpdir(), "heimdall-identity-moves-")); -const config = { ...createTestConfig(), signingPrivateKeyPath: join(dir, "signing.pem"), bootstrapSigningPrivateKeyOnMissing: true }; -afterAll(() => rmSync(dir, { recursive: true, force: true })); - -const apps: Awaited>[] = []; -afterEach(async () => { - vi.useRealTimers(); - vi.restoreAllMocks(); - await Promise.all(apps.splice(0).map((app) => app.close())); -}); - -function twitchRuntime(providerUserId: string): OAuthProviderRuntime { - return { - async exchangeAuthorizationCode() { - return { accessToken: "at", refreshToken: "rt", tokenType: "Bearer", scope: ["user:read:email"], raw: {} }; - }, - async resolveIdentity() { - return { provider: "twitch", providerUserId, username: providerUserId, profile: { id: providerUserId } }; - }, - async evaluateEntitlements() { - return { facts: [], snapshots: [] }; - }, - }; -} - -function discordRuntime(providerUserId: string): OAuthProviderRuntime { - return { ...twitchRuntime(providerUserId), async resolveIdentity() { return { provider: "discord", providerUserId, username: providerUserId, profile: { id: providerUserId } }; } }; -} - -async function rig(twitchUser = "t-signin") { - const store = new InMemoryStore(); - const audit: CreateAuditEventInput[] = []; - const realAudit = store.createAuditEvent.bind(store); - store.createAuditEvent = async (input) => { - audit.push(structuredClone(input)); - return realAudit(input); - }; - const app = await buildApp({ config, store, oauthRuntimes: { twitch: twitchRuntime(twitchUser), discord: discordRuntime("d-linked") } }); - apps.push(app); - const keys = createRuntimeKeyMaterial({ ...config, bootstrapSigningPrivateKeyOnMissing: false }); - return { app, store, keys, audit }; -} -type Rig = Awaited>; - -let seq = 0; -/** An account holding the given logins, each with a credential, and one live-session proof factory. */ -async function acct(r: Rig, held: Array<[Provider, string?]>) { - seq += 1; - const account = await r.store.createAccount({ createdAt: now, lastSeenAt: now, displayName: "DISPLAY-CANARY", primaryEmail: "canary@example.test" }); - const rows = []; - for (const [provider, user] of held) { - rows.push( - await r.store.upsertLinkedIdentity({ - accountId: account.id, - provider, - providerUserId: user ?? `${provider}-${seq}`, - scopes: ["identify"], - accessTokenEncrypted: "ACCESS-CIPHERTEXT", - refreshTokenEncrypted: "REFRESH-CIPHERTEXT", - profileJson: {}, - createdAt: now, - updatedAt: now, - }) - ); - } - return { account, rows }; -} -type Acct = Awaited>; - -interface ProofOptions { - app?: AppSlug; - /** Seconds since the sign-in; null mints a token with no sign-in claim (a refresh or link would). */ - signedInAgo?: number | null; - via?: number; - stepUp?: { agoS?: number; method: string }; -} -/** A live session for the account and the access token it would hold. */ -async function proof(r: Rig, a: Acct, o: ProofOptions = {}) { - const ago = o.signedInAgo === undefined ? 0 : o.signedInAgo; - const issued = await issueAccessClaim({ - config, - keys: r.keys, - store: r.store, - input: { - appSlug: o.app ?? "bifrost", - accountId: a.account.id, - linkedIdentities: a.rows.map((row) => ({ provider: row.provider, providerUserId: row.providerUserId })), - facts: [], - ...(ago === null ? {} : { authAt: nowS() - ago, authIdentityId: a.rows[o.via ?? 0]!.id }), - ...(o.stepUp ? { stepUpAt: nowS() - (o.stepUp.agoS ?? 0), stepUpMethod: o.stepUp.method } : {}), - }, - }); - return { token: issued.accessToken, sid: issued.session.sessionId }; -} -const passkey = { method: "bifrost-passkey" }; - -const move = (r: Rig, body: object, headers: Record = appAuth, app = "bifrost") => - r.app.inject({ method: "POST", url: `/v1/apps/${app}/identity-moves`, headers, payload: body }); -const held = async (r: Rig, a: Acct) => (await r.store.listStoredLinkedIdentitiesForAccount(a.account.id)).map((i) => i.id).sort(); -const err = (res: { statusCode: number; json(): { error?: string } }) => [res.statusCode, res.json().error]; - -/** Source with discord+google, destination with patreon: a passkey on the source and any fresh proof on the destination. */ -async function scene(r: Rig) { - const from = await acct(r, [["discord"], ["google"]]); - const to = await acct(r, [["patreon"]]); - return { - from, - to, - fromProof: await proof(r, from, { stepUp: passkey }), - toProof: await proof(r, to), - }; -} - -describe("a sanctioned move", () => { - it("two fresh proofs move every login of the source and answer the receipt, with no token, email or name", async () => { - const r = await rig(); - const s = await scene(r); - const sourceIds = await held(r, s.from); - const res = await move(r, { moveId: moveId("a"), fromProofs: [s.fromProof.token], toProof: s.toProof.token }); - expect(res.statusCode).toBe(200); - expect(res.headers["cache-control"]).toBe("no-store"); - expect(res.json()).toEqual({ - moveId: moveId("a"), - accountId: s.to.account.id, - movedIdentityIds: expect.arrayContaining(sourceIds), - proof: { from: "strong", to: "weak" }, - }); - expect(res.json().movedIdentityIds).toHaveLength(2); - expect(res.body).not.toMatch(/CIPHERTEXT|canary|DISPLAY|ey[A-Za-z0-9_-]{20,}\./); - expect(await held(r, s.from)).toEqual([]); - expect(await held(r, s.to)).toEqual(expect.arrayContaining(sourceIds)); - expect(await held(r, s.to)).toHaveLength(3); - expect(r.audit.find((e) => e.eventType === "identity_moved")).toMatchObject({ - accountId: s.from.account.id, - eventPayloadJson: { moveId: moveId("a"), toAccountId: s.to.account.id, providers: ["discord", "google"], reversesMoveId: null }, - }); - }); - - it("answers the identical body for the same moveId after the source's sessions are revoked, and changes nothing twice", async () => { - const r = await rig(); - const s = await scene(r); - const body = { moveId: moveId("b"), fromProofs: [s.fromProof.token], toProof: s.toProof.token }; - const first = await move(r, body); - expect(first.statusCode).toBe(200); - const session = await r.store.findSession("bifrost", s.fromProof.sid); - expect(Date.parse(session!.expiresAt), "the source's session is already dead").toBeLessThanOrEqual(Date.now()); - const again = await move(r, body); - expect([again.statusCode, again.body]).toEqual([200, first.body]); - expect(r.audit.filter((e) => e.eventType === "identity_moved")).toHaveLength(1); - }); - - it("a moveId reused for another account pair, another proof owner or another reversesMoveId is 409 move_id_conflict and changes nothing", async () => { - const r = await rig(); - const s = await scene(r); - const other = await acct(r, [["twitch"]]); - await move(r, { moveId: moveId("c"), fromProofs: [s.fromProof.token], toProof: s.toProof.token }); - const otherProof = await proof(r, other); - const toStranger = await move(r, { moveId: moveId("c"), fromProofs: [s.fromProof.token], toProof: otherProof.token }); - expect(err(toStranger)).toEqual([409, "move_id_conflict"]); - const fromStranger = await move(r, { moveId: moveId("c"), fromProofs: [otherProof.token], toProof: s.toProof.token }); - expect(err(fromStranger)).toEqual([409, "move_id_conflict"]); - const asReversal = await move(r, { moveId: moveId("c"), fromProofs: [s.toProof.token], reversesMoveId: moveId("zz") }); - expect(err(asReversal)).toEqual([409, "move_id_conflict"]); - expect(await held(r, other)).toHaveLength(1); - expect(await held(r, s.to)).toHaveLength(3); - }); - - it("a replay whose proofs are another app's tokens, or another account's, is 409 move_id_conflict, not the stored receipt", async () => { - const r = await rig(); - const s = await scene(r); - const body = { moveId: moveId("rp"), fromProofs: [s.fromProof.token], toProof: s.toProof.token }; - expect((await move(r, body)).statusCode).toBe(200); - const foreign = await proof(r, s.from, { app: "streampixels", stepUp: passkey }); - expect(err(await move(r, { ...body, fromProofs: [foreign.token] }))).toEqual([409, "move_id_conflict"]); - const foreignTo = await proof(r, s.to, { app: "streampixels" }); - expect(err(await move(r, { ...body, toProof: foreignTo.token }))).toEqual([409, "move_id_conflict"]); - expect((await move(r, body)).statusCode, "the genuine proofs still replay").toBe(200); - }); - - it("an app without the secret is 401; streampixels with its own secret is 403 not_allowed_for_app", async () => { - const r = await rig(); - const s = await scene(r); - const body = { moveId: moveId("d"), fromProofs: [s.fromProof.token], toProof: s.toProof.token }; - expect(err(await move(r, body, {}))).toEqual([401, "app_auth_required"]); - expect(err(await move(r, body, { "x-heimdall-app-secret": "nope" }))).toEqual([401, "app_auth_required"]); - expect(err(await move(r, body, { "x-heimdall-app-secret": "streampixels-secret" }, "streampixels"))).toEqual([403, "not_allowed_for_app"]); - expect(await held(r, s.from)).toHaveLength(2); - }); - - it("only bifrost is granted moves, and its account proofs are methods it may assert", () => { - const granted = Object.values(builtInAppProfiles).filter((p) => p.identityMoves !== undefined); - expect(granted.map((p) => p.slug)).toEqual(["bifrost"]); - const bifrost = granted[0]!; - expect(bifrost.identityMoves!.accountProofMethods.every((m) => bifrost.stepUpAssertion!.methods.includes(m))).toBe(true); - expect(bifrost.identityMoves!.accountProofMethods).not.toContain("bifrost-email-code"); - }); -}); - -describe("what a proof must be", () => { - it("another app's token, a revoked session and a forged signature are 403 proof_invalid and nothing moves", async () => { - const r = await rig(); - const s = await scene(r); - const foreign = await proof(r, s.from, { app: "streampixels", stepUp: passkey }); - const revoked = await proof(r, s.from, { stepUp: passkey }); - await r.store.revokeSession("bifrost", revoked.sid, s.from.account.id, 1, new Date().toISOString()); - const forged = s.fromProof.token.slice(0, -6) + "AAAAAA"; - for (const [fromProofs, toProof, who] of [ - [[foreign.token], s.toProof.token, "from"], - [[revoked.token], s.toProof.token, "from"], - [[forged], s.toProof.token, "from"], - [[s.fromProof.token], forged, "to"], - ] as const) { - const res = await move(r, { moveId: moveId("e"), fromProofs, toProof }); - expect([res.statusCode, res.json()]).toEqual([403, { error: "proof_invalid", proof: who }]); - } - expect(await held(r, s.from)).toHaveLength(2); - }); - - it("a sign-in 300 s old passes and 301 s is proof_stale; a token with no sign-in claim (refresh, link) is proof_stale; a step-up inside 600 s reports strong", async () => { - const r = await rig(); - vi.useFakeTimers({ toFake: ["Date"] }); - vi.setSystemTime(new Date(now)); - const to = await acct(r, [["patreon"]]); - const toProof = await proof(r, to); - const providers: Provider[] = ["discord", "google", "twitch", "github", "spotify", "youtube"]; - const attempt = async (tag: string, o: ProofOptions) => { - const from = await acct(r, [[providers.shift()!]]); - const p = await proof(r, from, o); - return move(r, { moveId: moveId(tag), fromProofs: [p.token], toProof: toProof.token }); - }; - const edge = await attempt("edge", { signedInAgo: AUTH_PROOF_TTL_SECONDS }); - expect([edge.statusCode, edge.json().proof]).toEqual([200, { from: "weak", to: "weak" }]); - const late = await attempt("late", { signedInAgo: AUTH_PROOF_TTL_SECONDS + 1 }); - expect([late.statusCode, late.json()]).toEqual([403, { error: "proof_stale", proof: "from" }]); - const none = await attempt("none", { signedInAgo: null }); - expect(err(none)).toEqual([403, "proof_stale"]); - const strong = await attempt("strong", { signedInAgo: 5_000, stepUp: { agoS: 600, method: "provider:twitch" } }); - expect([strong.statusCode, strong.json().proof.from]).toEqual([200, "strong"]); - const stale = await attempt("stale", { signedInAgo: 5_000, stepUp: { agoS: 601, method: "bifrost-passkey" } }); - expect(err(stale)).toEqual([403, "proof_stale"]); - // The destination's proof is held to the same rule. - const from = await acct(r, [["google"]]); - const fresh = await proof(r, from); - const staleTo = await proof(r, to, { signedInAgo: AUTH_PROOF_TTL_SECONDS + 1 }); - const res = await move(r, { moveId: moveId("sto"), fromProofs: [fresh.token], toProof: staleTo.token }); - expect([res.statusCode, res.json()]).toEqual([403, { error: "proof_stale", proof: "to" }]); - }); - - it("fromProofs naming two accounts is 403 proof_invalid; one account on both sides is 409 same_account", async () => { - const r = await rig(); - const s = await scene(r); - const split = await move(r, { moveId: moveId("f"), fromProofs: [s.fromProof.token, s.toProof.token], toProof: s.toProof.token }); - expect([split.statusCode, split.json()]).toEqual([403, { error: "proof_invalid", proof: "from" }]); - const twice = await proof(r, s.from, { stepUp: passkey }); - const same = await move(r, { moveId: moveId("g"), fromProofs: [s.fromProof.token], toProof: twice.token }); - expect(err(same)).toEqual([409, "same_account"]); - expect(await held(r, s.from)).toHaveLength(2); - }); - - it("the body is closed: a forward move needs toProof, a reversal takes no toProof or identityIds, ids are patterned", async () => { - const r = await rig(); - const s = await scene(r); - const t = s.fromProof.token; - for (const body of [ - { moveId: moveId("h"), fromProofs: [t] }, - { moveId: "short", fromProofs: [t], toProof: t }, - { moveId: moveId("h"), fromProofs: [], toProof: t }, - { moveId: moveId("h"), fromProofs: [t], toProof: t, reversesMoveId: moveId("i") }, - { moveId: moveId("h"), fromProofs: [t], reversesMoveId: moveId("i"), identityIds: ["x"] }, - ]) { - expect((await move(r, body)).statusCode, JSON.stringify(Object.keys(body))).toBe(400); - } - }); -}); - -describe("accounts come only from proofs", () => { - it("a stray accountId in the body steers nothing", async () => { - const r = await rig(); - const s = await scene(r); - const stranger = await acct(r, [["twitch"]]); - const res = await move(r, { moveId: moveId("y"), fromProofs: [s.fromProof.token], toProof: s.toProof.token, accountId: stranger.account.id, toAccountId: stranger.account.id }); - expect([res.statusCode, res.json().accountId]).toEqual([200, s.to.account.id]); - expect(await held(r, stranger)).toHaveLength(1); - }); -}); - -describe("which logins a proof moves", () => { - async function multi(r: Rig) { - const from = await acct(r, [["discord"], ["google"], ["twitch"]]); - const to = await acct(r, [["patreon"]]); - return { from, to, toProof: await proof(r, to) }; - } - - it("a sign-in through login X moves X and cannot move the source's other logins", async () => { - const r = await rig(); - const s = await multi(r); - const [discord, google] = s.from.rows; - const viaDiscord = await proof(r, s.from, { via: 0 }); - const all = await move(r, { moveId: moveId("j"), fromProofs: [viaDiscord.token], toProof: s.toProof.token }); - expect(err(all)).toEqual([403, "identity_not_proved"]); - const other = await move(r, { moveId: moveId("j"), fromProofs: [viaDiscord.token], toProof: s.toProof.token, identityIds: [google!.id] }); - expect(err(other)).toEqual([403, "identity_not_proved"]); - expect(await held(r, s.from)).toHaveLength(3); - const only = await move(r, { moveId: moveId("j"), fromProofs: [viaDiscord.token], toProof: s.toProof.token, identityIds: [discord!.id] }); - expect([only.statusCode, only.json().movedIdentityIds]).toEqual([200, [discord!.id]]); - expect((await held(r, s.from)).sort()).toEqual([google!.id, s.from.rows[2]!.id].sort()); - }); - - it("one proof per login moves them all; an asserted passkey covers the whole account; an email code covers only its own login", async () => { - const r = await rig(); - let s = await multi(r); - const perLogin = await Promise.all(s.from.rows.map((_, via) => proof(r, s.from, { via }))); - const res = await move(r, { moveId: moveId("k"), fromProofs: perLogin.map((p) => p.token), toProof: s.toProof.token }); - expect([res.statusCode, res.json().movedIdentityIds]).toHaveLength(2); - expect(res.json().proof.from).toBe("weak"); - expect(await held(r, s.from)).toEqual([]); - - s = await multi(r); - const byPasskey = await proof(r, s.from, { stepUp: passkey }); - expect((await move(r, { moveId: moveId("l"), fromProofs: [byPasskey.token], toProof: s.toProof.token })).statusCode).toBe(200); - - s = await multi(r); - const byEmail = await proof(r, s.from, { stepUp: { method: "bifrost-email-code" } }); - const refused = await move(r, { moveId: moveId("m"), fromProofs: [byEmail.token], toProof: s.toProof.token }); - expect(err(refused)).toEqual([403, "identity_not_proved"]); - expect(await held(r, s.from)).toHaveLength(3); - }); - - it("a provider held on both sides is 409 provider_conflict naming only the provider, and nothing moves", async () => { - const r = await rig(); - const from = await acct(r, [["discord"], ["google"]]); - const to = await acct(r, [["discord"]]); - const res = await move(r, { moveId: moveId("n"), fromProofs: [(await proof(r, from, { stepUp: passkey })).token], toProof: (await proof(r, to)).token }); - expect([res.statusCode, res.json()]).toEqual([409, { error: "provider_conflict", provider: "discord" }]); - expect(res.body).not.toContain(from.account.id); - expect(await held(r, from)).toHaveLength(2); - expect(await held(r, to)).toHaveLength(1); - }); - - it("naming an identity the source does not hold is 404 identity_not_found", async () => { - const r = await rig(); - const s = await scene(r); - const res = await move(r, { moveId: moveId("o"), fromProofs: [s.fromProof.token], toProof: s.toProof.token, identityIds: [s.to.rows[0]!.id] }); - expect(err(res)).toEqual([404, "identity_not_found"]); - }); -}); - -describe("what a move leaves behind", () => { - it("strips the moved credentials, expires the source's sessions, pending links and unredeemed completions, and leaves the destination live", async () => { - const r = await rig(); - const s = await scene(r); - const linkInput = { appSlug: "bifrost" as const, provider: "discord" as const, providerUserId: "d-x", identity: { accountId: "x", provider: "discord" as const, providerUserId: "d-x", scopes: [], profileJson: {}, createdAt: now, updatedAt: now }, returnTo: "https://bifrost.gamecult.org/x", createdAt: now, expiresAt: "2099-01-01T00:00:00.000Z" }; - const srcLink = await r.store.createPendingLink({ ...linkInput, accountId: s.from.account.id }); - const dstLink = await r.store.createPendingLink({ ...linkInput, accountId: s.to.account.id }); - const completion = (accountId: string) => - r.store.createAuthCompletion({ appSlug: "bifrost", provider: "discord", mode: "sign_in", accountId, sessionId: "sess", returnTo: "https://bifrost.gamecult.org/x", createdAt: now, expiresAt: "2099-01-01T00:00:00.000Z", payloadJson: {} }); - const srcCompletion = await completion(s.from.account.id); - const dstCompletion = await completion(s.to.account.id); - const res = await move(r, { moveId: moveId("p"), fromProofs: [s.fromProof.token], toProof: s.toProof.token }); - expect(res.statusCode).toBe(200); - const movedIds = new Set(s.from.rows.map((row) => row.id)); - for (const row of (await r.store.listStoredLinkedIdentitiesForAccount(s.to.account.id)).filter((row) => movedIds.has(row.id))) { - expect(row.accessTokenEncrypted).toBeUndefined(); - expect(row.refreshTokenEncrypted).toBeUndefined(); - } - const record = await r.store.findIdentityMove(moveId("p")); - expect(record?.moved.map((m) => m.credentialStripped)).toEqual([true, true]); - expect((await r.store.findSession("bifrost", s.fromProof.sid))!.accessRevision).toBe(2); - expect((await r.store.findSession("bifrost", s.toProof.sid))!.accessRevision).toBe(1); - expect(Date.parse((await r.store.findSession("bifrost", s.toProof.sid))!.expiresAt)).toBeGreaterThan(Date.now()); - expect(await r.store.consumePendingLink("bifrost", srcLink.id, s.from.account.id, new Date().toISOString())).toBeNull(); - expect(await r.store.consumePendingLink("bifrost", dstLink.id, s.to.account.id, new Date().toISOString())).not.toBeNull(); - expect(await r.store.consumeAuthCompletion("bifrost", srcCompletion.code, new Date().toISOString())).toBeNull(); - expect(await r.store.consumeAuthCompletion("bifrost", dstCompletion.code, new Date().toISOString())).not.toBeNull(); - }); - - it("revokes the source's live grants for the providers it no longer holds, leaves the destination's receipts, and a replay heals a crash after commit", async () => { - const r = await rig(); - const s = await scene(r); - const grant = (accountId: string, provider: Provider) => - r.store.createConsentReceipt({ kind: "grant", accountId, appSlug: "bifrost", provider, createdAt: now, scopesAsked: ["identify"], scopesGranted: ["identify"], consentPageDigest: "d", consentText: "t" }); - await grant(s.from.account.id, "discord"); - await grant(s.to.account.id, "patreon"); - const receiptsOf = async (a: Acct) => (await r.store.listConsentReceipts(a.account.id)).map((x) => `${x.kind}:${x.provider}`); - const body = { moveId: moveId("q"), fromProofs: [s.fromProof.token], toProof: s.toProof.token }; - vi.spyOn(r.store, "createConsentReceipt").mockRejectedValueOnce(new Error("crash after commit")); - expect((await move(r, body)).statusCode).toBe(500); - expect(await held(r, s.from), "the move itself committed").toEqual([]); - expect(await receiptsOf(s.from)).toEqual(["grant:discord"]); - const healed = await move(r, body); - expect(healed.statusCode).toBe(200); - expect(await receiptsOf(s.from)).toEqual(["grant:discord", "revocation:discord"]); - expect(await receiptsOf(s.to)).toEqual(["grant:patreon"]); - expect((await move(r, body)).body, "and it is idempotent").toBe(healed.body); - expect(await receiptsOf(s.from)).toHaveLength(2); - }); - - it("the destination never loses an identity, whatever is refused", async () => { - const r = await rig(); - const s = await scene(r); - const before = (await held(r, s.to)).length; - const refusals = [ - { moveId: moveId("r1"), fromProofs: [s.fromProof.token], toProof: s.toProof.token, identityIds: ["nope"] }, - { moveId: moveId("r2"), fromProofs: [s.fromProof.token], toProof: s.fromProof.token }, - { moveId: moveId("r3"), fromProofs: [s.toProof.token], toProof: s.toProof.token }, - ]; - for (const body of refusals) { - await move(r, body); - expect((await held(r, s.to)).length).toBeGreaterThanOrEqual(before); - } - expect((await move(r, { moveId: moveId("r4"), fromProofs: [s.fromProof.token], toProof: s.toProof.token })).statusCode).toBe(200); - expect((await held(r, s.to)).length).toBeGreaterThanOrEqual(before); - }); - - it("a sign-in through a moved login lands on the destination, with no alias lookup", async () => { - const r = await rig("t-moved"); - const from = await acct(r, [["twitch", "t-moved"]]); - const to = await acct(r, [["patreon"]]); - const mv = await move(r, { moveId: moveId("s"), fromProofs: [(await proof(r, from, { stepUp: passkey })).token], toProof: (await proof(r, to)).token }); - expect(mv.statusCode).toBe(200); - const started = await r.app.inject({ method: "POST", url: "/v1/oauth/twitch/start", payload: { appSlug: "streampixels", mode: "sign_in", returnTo: "https://streampixels.gamecult.org/signin/return" } }); - const flow = await launchFlow(r.app, started.json()); - const called = await r.app.inject({ method: "GET", url: `/v1/oauth/twitch/callback?code=c&state=${encodeURIComponent(flow.state)}`, headers: { cookie: flow.cookie, accept: "application/json" } }); - expect(called.statusCode).toBe(201); - expect(called.json().account.id).toBe(to.account.id); - }); -}); - -describe("aliases and reversal", () => { - it("an emptied source is an alias; moving into or out of it is 409 already_moved", async () => { - const r = await rig(); - const s = await scene(r); - expect((await move(r, { moveId: moveId("t"), fromProofs: [s.fromProof.token], toProof: s.toProof.token })).statusCode).toBe(200); - // A session can outlive its logins only by being minted for an account that holds none, which is how a stale caller would look. - const aliasProof = await proof(r, { account: s.from.account, rows: [s.to.rows[0]!] }, { stepUp: passkey }); - const third = await acct(r, [["github"]]); - const out = await move(r, { moveId: moveId("u"), fromProofs: [aliasProof.token], toProof: (await proof(r, third)).token }); - expect(err(out)).toEqual([409, "already_moved"]); - const aliasTo = await proof(r, { account: s.from.account, rows: [s.to.rows[0]!] }); - const into = await move(r, { moveId: moveId("u2"), fromProofs: [(await proof(r, third, { stepUp: passkey })).token], toProof: aliasTo.token }); - expect(err(into)).toEqual([409, "already_moved"]); - expect(await held(r, third)).toHaveLength(1); - }); - - it("a reversal through a moved login moves exactly those logins back; a second reversal is not_reversible; credentials stay stripped", async () => { - const r = await rig(); - const s = await scene(r); - const sourceIds = await held(r, s.from); - await move(r, { moveId: moveId("v"), fromProofs: [s.fromProof.token], toProof: s.toProof.token }); - const [discord, google] = s.from.rows; - // The destination now holds the moved logins: a sign-in through one of them is a proof of the destination. - const viaMoved = await proof(r, { account: s.to.account, rows: [discord!, google!] }, { via: 0 }); - const own = await proof(r, s.to, { via: 0 }); - const denied = await move(r, { moveId: moveId("w"), fromProofs: [own.token], reversesMoveId: moveId("v") }); - expect(err(denied), "the destination's own login does not speak for the moved ones").toEqual([403, "identity_not_proved"]); - const viaBoth = [viaMoved, await proof(r, { account: s.to.account, rows: [discord!, google!] }, { via: 1 })]; - const back = await move(r, { moveId: moveId("w"), fromProofs: viaBoth.map((p) => p.token), reversesMoveId: moveId("v") }); - expect(back.statusCode, back.body).toBe(200); - expect(back.json()).toEqual({ moveId: moveId("w"), accountId: s.from.account.id, movedIdentityIds: expect.arrayContaining(sourceIds), proof: { from: "weak", to: null }, reversesMoveId: moveId("v") }); - expect(await held(r, s.from)).toEqual(sourceIds); - expect(await held(r, s.to)).toHaveLength(1); - expect((await r.store.listStoredLinkedIdentitiesForAccount(s.from.account.id)).every((i) => i.accessTokenEncrypted === undefined)).toBe(true); - const own2 = await proof(r, s.to, { via: 0 }); - const again = await move(r, { moveId: moveId("w2"), fromProofs: [own2.token], reversesMoveId: moveId("v") }); - expect(err(again)).toEqual([409, "not_reversible"]); - const reverseTheReversal = await move(r, { moveId: moveId("w3"), fromProofs: [(await proof(r, s.from)).token], reversesMoveId: moveId("w") }); - expect(err(reverseTheReversal)).toEqual([409, "not_reversible"]); - const unknown = await move(r, { moveId: moveId("w4"), fromProofs: [(await proof(r, s.from)).token], reversesMoveId: moveId("nothere") }); - expect(err(unknown)).toEqual([409, "not_reversible"]); - }); -}); - -describe("proofTier", () => { - it("a proof dated in the future proves nothing, whichever claim carries it", () => { - const n = nowS(); - expect(proofTier({ auth_at: n + 5 }, n)).toBeNull(); - expect(proofTier({ step_up_at: n + 5 }, n)).toBeNull(); - expect(proofTier({ step_up_at: n + 5, auth_at: n }, n), "a future step-up does not hide a valid sign-in").toBe("weak"); - expect(proofTier({ step_up_at: n, auth_at: n - 9_999 }, n)).toBe("strong"); - }); -}); - -describe("the reversal's source must be the forward move's destination", () => { - it("is refused as not_reversible before the proofs are judged, even for a stale proof", async () => { - const r = await rig(); - const s = await scene(r); - expect((await move(r, { moveId: moveId("fw"), fromProofs: [s.fromProof.token], toProof: s.toProof.token })).statusCode).toBe(200); - const third = await acct(r, [["github"]]); - const onward = await proof(r, s.to, { stepUp: passkey }); - expect((await move(r, { moveId: moveId("on"), fromProofs: [onward.token], toProof: (await proof(r, third)).token })).statusCode).toBe(200); - const stale = await proof(r, third, { signedInAgo: 9_999 }); - const res = await move(r, { moveId: moveId("rv"), fromProofs: [stale.token], reversesMoveId: moveId("fw") }); - expect(err(res)).toEqual([409, "not_reversible"]); - }); -}); - -describe("idempotency is by moveId", () => { - it("a replayed reversal under another reversesMoveId is 409 move_id_conflict, not the stored receipt", async () => { - const r = await rig(); - const s = await scene(r); - await move(r, { moveId: moveId("fw2"), fromProofs: [s.fromProof.token], toProof: s.toProof.token }); - const [discord, google] = s.from.rows; - const viaMoved = async (via: number) => (await proof(r, { account: s.to.account, rows: [discord!, google!] }, { via })).token; - const body = { moveId: moveId("rv2"), fromProofs: [await viaMoved(0), await viaMoved(1)], reversesMoveId: moveId("fw2") }; - const back = await move(r, body); - expect(back.statusCode, back.body).toBe(200); - expect((await move(r, body)).body, "the same body replays").toBe(back.body); - expect(err(await move(r, { ...body, reversesMoveId: moveId("other") }))).toEqual([409, "move_id_conflict"]); - expect(await held(r, s.from)).toHaveLength(2); - }); - - it("a replay with the same moveId and different identityIds returns the first receipt (steward ruling: the key is the moveId, a retry carries the same body)", async () => { - const r = await rig(); - const from = await acct(r, [["discord"], ["google"]]); - const to = await acct(r, [["patreon"]]); - const fromProof = await proof(r, from, { stepUp: passkey }); - const toProof = await proof(r, to); - const first = await move(r, { moveId: moveId("ids"), fromProofs: [fromProof.token], toProof: toProof.token, identityIds: [from.rows[0]!.id] }); - expect(first.json().movedIdentityIds).toEqual([from.rows[0]!.id]); - const again = await move(r, { moveId: moveId("ids"), fromProofs: [fromProof.token], toProof: toProof.token, identityIds: [from.rows[1]!.id] }); - expect([again.statusCode, again.body]).toEqual([200, first.body]); - expect(await held(r, from), "and the second selection did not move").toEqual([from.rows[1]!.id]); - }); -}); - -describe("what a refusal says", () => { - it("no refusal body names an account id, an email, a name or an identity the caller did not send", async () => { - const r = await rig(); - const s = await scene(r); - const stranger = await acct(r, [["discord", "d-stranger"]]); - const bodies = [ - await move(r, { moveId: moveId("x1"), fromProofs: [s.fromProof.token], toProof: "garbage" }), - await move(r, { moveId: moveId("x2"), fromProofs: [(await proof(r, s.from, { via: 0 })).token], toProof: s.toProof.token }), - await move(r, { moveId: moveId("x3"), fromProofs: [s.fromProof.token], toProof: s.toProof.token, identityIds: [stranger.rows[0]!.id] }), - await move(r, { moveId: moveId("x4"), fromProofs: [s.toProof.token], toProof: s.toProof.token }), - await move(r, { moveId: moveId("x5"), fromProofs: [s.fromProof.token], reversesMoveId: moveId("nothere") }), - await move(r, { moveId: moveId("x6"), fromProofs: [(await proof(r, s.from, { signedInAgo: 9_999 })).token], toProof: s.toProof.token }), - ]; - const ids = [s.from, s.to, stranger].flatMap((a) => [a.account.id, ...a.rows.map((row) => row.id), ...a.rows.map((row) => row.providerUserId)]); - for (const res of bodies) { - expect(res.statusCode).toBeGreaterThanOrEqual(400); - for (const id of ids) expect(res.body).not.toContain(id); - expect(res.body).not.toMatch(/canary|DISPLAY/); - expect(Object.keys(res.json()).every((k) => ["error", "detail", "proof", "provider"].includes(k))).toBe(true); - } - }); -}); - -describe("claims: which sign-in a token came from", () => { - const returnTo = "https://streampixels.gamecult.org/signin/return"; - async function twitchSignIn(r: Rig) { - const started = await r.app.inject({ method: "POST", url: "/v1/oauth/twitch/start", payload: { appSlug: "streampixels", mode: "sign_in", returnTo } }); - const flow = await launchFlow(r.app, started.json()); - const called = await r.app.inject({ method: "GET", url: `/v1/oauth/twitch/callback?code=c&state=${encodeURIComponent(flow.state)}`, headers: { cookie: flow.cookie, accept: "application/json" } }); - expect(called.statusCode).toBe(201); - const redeemed = await r.app.inject({ method: "POST", url: "/v1/apps/streampixels/auth-completions/redeem", payload: { completionCode: called.json().completion.code } }); - expect(redeemed.statusCode).toBe(201); - return redeemed.json() as { refreshToken: string; claimSet: Record }; - } - - it("a sign_in stamps auth_at and the login it came through; a refresh does not renew them", async () => { - const r = await rig("t-claims"); - const before = nowS(); - const signed = await twitchSignIn(r); - const row = await r.store.findStoredLinkedIdentity("twitch", "t-claims"); - expect(signed.claimSet.auth_identity_id).toBe(row!.id); - expect(signed.claimSet.auth_at).toBeGreaterThanOrEqual(before); - expect(signed.claimSet.auth_at).toBeLessThanOrEqual(nowS()); - expect(signed.claimSet.step_up_at).toBeUndefined(); - const refreshed = await r.app.inject({ method: "POST", url: "/v1/apps/streampixels/sessions/refresh", payload: { refreshToken: signed.refreshToken } }); - expect(refreshed.statusCode).toBe(201); - expect(refreshed.json().claimSet.auth_at).toBeUndefined(); - expect(refreshed.json().claimSet.auth_identity_id).toBeUndefined(); - }); - - it("a link callback mints no sign-in proof: no auth_at, no auth_identity_id", async () => { - const r = await rig(); - const holder = await acct(r, [["twitch"]]); - const started = await r.app.inject({ method: "POST", url: "/v1/oauth/discord/start", headers: appAuth, payload: { appSlug: "bifrost", mode: "link", initiatingAccountId: holder.account.id, returnTo: "https://bifrost.gamecult.org/x" } }); - expect(started.statusCode).toBe(201); - const flow = await launchFlow(r.app, started.json()); - const called = await r.app.inject({ method: "GET", url: `/v1/oauth/discord/callback?code=c&state=${encodeURIComponent(flow.state)}`, headers: { cookie: flow.cookie, accept: "application/json" } }); - expect(called.statusCode).toBe(201); - expect(called.json().claimSet.identities).toHaveLength(2); - expect(called.json().claimSet.auth_at).toBeUndefined(); - expect(called.json().claimSet.auth_identity_id).toBeUndefined(); - expect(called.body).not.toMatch(/auth_at|auth_identity_id/); - }); - - it("a connect callback mints no sign-in proof either", async () => { - const r = await rig("t-connect"); - const started = await r.app.inject({ method: "POST", url: "/v1/oauth/twitch/start", headers: { "x-heimdall-app-secret": "streampixels-secret" }, payload: { appSlug: "streampixels", mode: "connect", returnTo: "https://streampixels.gamecult.org/signin/return", connection: { kind: "creator", targetId: "creator-1" } } }); - expect(started.statusCode, started.body).toBe(201); - const flow = await launchFlow(r.app, started.json()); - const called = await r.app.inject({ method: "GET", url: `/v1/oauth/twitch/callback?code=c&state=${encodeURIComponent(flow.state)}`, headers: { cookie: flow.cookie, accept: "application/json" } }); - expect(called.statusCode, called.body).toBe(201); - expect(called.body).toContain("claimSet"); - expect(called.body).not.toMatch(/auth_at|auth_identity_id/); - }); - - it("an asserted step-up carries the bearer's auth claims through unchanged", async () => { - const r = await rig(); - const a = await acct(r, [["discord"], ["google"]]); - const p = await proof(r, a, { via: 1, signedInAgo: 30 }); - const res = await r.app.inject({ method: "POST", url: "/v1/apps/bifrost/step-up", headers: { ...appAuth, authorization: `Bearer ${p.token}` }, payload: { method: "bifrost-passkey", nonce: "n".repeat(32) } }); - expect(res.statusCode).toBe(201); - expect(res.json().claimSet).toMatchObject({ auth_identity_id: a.rows[1]!.id, auth_at: nowS() - 30, step_up_method: "bifrost-passkey" }); - }); -}); diff --git a/tests/identity-unlink.test.ts b/tests/identity-unlink.test.ts deleted file mode 100644 index e12e418..0000000 --- a/tests/identity-unlink.test.ts +++ /dev/null @@ -1,334 +0,0 @@ -import { mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { afterAll, afterEach, describe, expect, it, vi } from "vitest"; -import { buildApp } from "../src/app.js"; -import { issueAccessClaim } from "../src/claims.js"; -import { type Provider } from "../src/contracts.js"; -import { type OAuthProviderRuntime } from "../src/oauth.js"; -import { createRuntimeKeyMaterial, decodeJwt, signJwt, verifyJwt } from "../src/signing.js"; -import { IdentityHeldElsewhereError, InMemoryStore } from "../src/store/index.js"; -import { createTestConfig, launchFlow, launchState, stateOf } from "./oauth-flow.js"; - -// The member's identity surface: list what an account holds, and take one -// identity off it. Taking one off is the account's own decision made with -// fresh proof (a step-up sign-in inside the proof window), never the -// bearer's alone. These tests drive both routes over HTTP as an app would. - -const returnTo = "https://streampixels.gamecult.org/signin/return"; -const spAuth = { "x-heimdall-app-secret": "streampixels-secret" }; -const now = "2026-11-13T12:00:00.000Z"; - -function runtime(provider: "twitch" | "youtube", providerUserId: string): OAuthProviderRuntime { - return { - async exchangeAuthorizationCode() { - return { accessToken: "at", refreshToken: "rt", tokenType: "Bearer", scope: ["user:read:email"], raw: {} }; - }, - async resolveIdentity() { - return { provider, providerUserId, username: providerUserId, profile: { id: providerUserId } }; - }, - async evaluateEntitlements() { - return { facts: [], snapshots: [] }; - }, - }; -} - -const dir = mkdtempSync(join(tmpdir(), "heimdall-unlink-")); -const config = { ...createTestConfig(), signingPrivateKeyPath: join(dir, "signing.pem"), bootstrapSigningPrivateKeyOnMissing: true }; -afterAll(() => rmSync(dir, { recursive: true, force: true })); - -const apps: Awaited>[] = []; -afterEach(async () => { - vi.useRealTimers(); - await Promise.all(apps.splice(0).map((app) => app.close())); -}); - -async function rig() { - const store = new InMemoryStore(); - const app = await buildApp({ - config, - store, - oauthRuntimes: { twitch: runtime("twitch", "t-1"), youtube: runtime("youtube", "y-1") }, - }); - apps.push(app); - const keys = createRuntimeKeyMaterial({ ...config, bootstrapSigningPrivateKeyOnMissing: false }); - return { app, store, keys }; -} -type Rig = Awaited>; - -async function seedAccount(r: Rig, held: Array<[Provider, string]>) { - const account = await r.store.createAccount({ createdAt: now, lastSeenAt: now }); - const rows = []; - for (const [provider, providerUserId] of held) { - rows.push( - await r.store.upsertLinkedIdentity({ - accountId: account.id, - provider, - providerUserId, - username: `${provider}-name`, - displayName: `${provider} display`, - primaryEmail: "secret@example.test", - accessTokenEncrypted: "ACCESS-CIPHERTEXT", - refreshTokenEncrypted: "REFRESH-CIPHERTEXT", - scopes: ["identify"], - profileJson: { raw: "PROFILE-CANARY" }, - createdAt: now, - updatedAt: now, - }) - ); - } - return { account, rows }; -} - -/** A real sign_in through twitch, as StreamPixels runs it, redeemed for the tokens. */ -async function signIn(r: Rig, stepUp: boolean) { - const started = await r.app.inject({ - method: "POST", - url: "/v1/oauth/twitch/start", - headers: stepUp ? spAuth : {}, - payload: { appSlug: "streampixels", mode: "sign_in", returnTo, ...(stepUp ? { stepUp: true } : {}) }, - }); - expect(started.statusCode).toBe(201); - const flow = await launchFlow(r.app, started.json()); - const called = await r.app.inject({ - method: "GET", - url: `/v1/oauth/twitch/callback?code=c&state=${encodeURIComponent(flow.state)}`, - headers: { cookie: flow.cookie, accept: "application/json" }, - }); - expect(called.statusCode).toBe(201); - const redeemed = await r.app.inject({ - method: "POST", - url: "/v1/apps/streampixels/auth-completions/redeem", - payload: { completionCode: called.json().completion.code }, - }); - expect(redeemed.statusCode).toBe(201); - return redeemed.json() as { accessToken: string; refreshToken: string; claimSet: Record }; -} - -const bearer = (token: string) => ({ authorization: `Bearer ${token}` }); -const list = (r: Rig, token?: string) => r.app.inject({ method: "GET", url: "/v1/me/identities", headers: token ? bearer(token) : {} }); -const unlink = (r: Rig, id: string, token?: string, payload?: unknown) => - r.app.inject({ method: "POST", url: `/v1/me/identities/${encodeURIComponent(id)}/unlink`, headers: token ? bearer(token) : {}, ...(payload !== undefined ? { payload: payload as object } : {}) }); - -describe("step_up_at on the access claim", () => { - it("a step-up sign-in's claim carries it; an ordinary sign-in and a refresh do not", async () => { - const r = await rig(); - await seedAccount(r, [["twitch", "t-1"], ["youtube", "y-1"]]); - const before = Math.floor(Date.now() / 1000); - const stepped = await signIn(r, true); - expect(stepped.claimSet.step_up_at).toBeGreaterThanOrEqual(before); - expect(stepped.claimSet.step_up_at).toBeLessThanOrEqual(Math.floor(Date.now() / 1000)); - expect(stepped.claimSet.step_up_method).toBe("provider:twitch"); - const plain = (await signIn(r, false)).claimSet; - expect(plain.step_up_at).toBeUndefined(); - expect(plain.step_up_method).toBeUndefined(); - - const refreshed = await r.app.inject({ method: "POST", url: "/v1/apps/streampixels/sessions/refresh", payload: { refreshToken: stepped.refreshToken } }); - expect(refreshed.statusCode).toBe(201); - expect(refreshed.json().claimSet.step_up_at, "a refresh never renews proof").toBeUndefined(); - expect(refreshed.json().claimSet.step_up_method).toBeUndefined(); - }); -}); - -describe("GET /v1/me/identities", () => { - it("is 401 sign_in_required without a live bearer", async () => { - const r = await rig(); - for (const token of [undefined, "not-a-token"]) { - const res = await list(r, token); - expect([res.statusCode, res.json().error]).toEqual([401, "sign_in_required"]); - } - }); - - it("lists the caller's identities and nothing that is a credential, a profile or an email", async () => { - const r = await rig(); - const { account, rows } = await seedAccount(r, [["twitch", "t-1"], ["discord", "d-9"]]); - await seedAccount(r, [["youtube", "y-other"]]); - const { accessToken } = await signIn(r, false); - const res = await list(r, accessToken); - expect(res.statusCode).toBe(200); - expect(res.headers["cache-control"]).toBe("no-store"); - const body = res.json(); - expect(body.accountId).toBe(account.id); - expect(body.identities).toEqual([ - // The sign-in above refreshed the twitch row from what the provider returned. - { id: rows[0]!.id, provider: "twitch", providerUserId: "t-1", username: "t-1", linkedAt: now, scopes: ["user:read:email"] }, - { id: rows[1]!.id, provider: "discord", providerUserId: "d-9", username: "discord-name", displayName: "discord display", linkedAt: now, scopes: ["identify"] }, - ]); - expect(res.body).not.toMatch(/CIPHERTEXT|PROFILE-CANARY|secret@example|primary_email|primaryEmail/); - }); -}); - -describe("POST /v1/me/identities/:identityId/unlink", () => { - it("is 401 without a live bearer", async () => { - const r = await rig(); - const { rows } = await seedAccount(r, [["twitch", "t-1"], ["youtube", "y-1"]]); - expect((await unlink(r, rows[1]!.id)).statusCode).toBe(401); - expect((await unlink(r, rows[1]!.id, "garbage")).statusCode).toBe(401); - }); - - it("is 403 step_up_required for a bearer with no proof, and for a refresh-issued one, and removes nothing", async () => { - const r = await rig(); - const { account, rows } = await seedAccount(r, [["twitch", "t-1"], ["youtube", "y-1"]]); - const plain = await signIn(r, false); - const denied = await unlink(r, rows[1]!.id, plain.accessToken); - expect([denied.statusCode, denied.json().error]).toEqual([403, "step_up_required"]); - expect(denied.json().detail).toMatch(/twitch, youtube and google/); - - const stepped = await signIn(r, true); - const refreshed = await r.app.inject({ method: "POST", url: "/v1/apps/streampixels/sessions/refresh", payload: { refreshToken: stepped.refreshToken } }); - const viaRefresh = await unlink(r, rows[1]!.id, refreshed.json().accessToken); - expect([viaRefresh.statusCode, viaRefresh.json().error]).toEqual([403, "step_up_required"]); - expect(await r.store.listStoredLinkedIdentitiesForAccount(account.id)).toHaveLength(2); - }); - - it("is 403 for proof older than the window and for proof dated in the future; 599 s old still passes", async () => { - const r = await rig(); - const { account, rows } = await seedAccount(r, [["twitch", "t-1"], ["youtube", "y-1"], ["discord", "d-1"]]); - const issueWith = async (stepUpAt: number) => - (await issueAccessClaim({ - config, - keys: r.keys, - store: r.store, - input: { appSlug: "streampixels", accountId: account.id, linkedIdentities: [], facts: [], stepUpAt }, - })).accessToken; - const nowS = Math.floor(Date.now() / 1000); - for (const at of [nowS - 601, nowS + 120]) { - const res = await unlink(r, rows[1]!.id, await issueWith(at)); - expect([res.statusCode, res.json().error], String(at - nowS)).toEqual([403, "step_up_required"]); - } - expect(await r.store.listStoredLinkedIdentitiesForAccount(account.id)).toHaveLength(3); - const edge = await unlink(r, rows[1]!.id, await issueWith(nowS - 599)); - expect(edge.statusCode).toBe(200); - }); - - it("a step-up sign-in's bearer unlinks: 200 with the remaining list, an audit event without credentials", async () => { - const r = await rig(); - const { account, rows } = await seedAccount(r, [["twitch", "t-1"], ["discord", "d-9"]]); - const audit = vi.spyOn(r.store, "createAuditEvent"); - const { accessToken } = await signIn(r, true); - const res = await unlink(r, rows[1]!.id, accessToken, null); - expect(res.statusCode).toBe(200); - expect(res.headers["cache-control"]).toBe("no-store"); - expect(res.json().unlinked).toEqual({ id: rows[1]!.id, provider: "discord", providerUserId: "d-9" }); - expect(res.json().identities.map((i: { id: string }) => i.id)).toEqual([rows[0]!.id]); - expect(res.body).not.toMatch(/CIPHERTEXT|PROFILE-CANARY|secret@example/); - expect(await r.store.listStoredLinkedIdentitiesForAccount(account.id)).toHaveLength(1); - const event = audit.mock.calls.map(([e]) => e).find((e) => e.eventType === "identity_unlinked"); - expect(event?.accountId).toBe(account.id); - expect(event?.eventPayloadJson).toEqual({ provider: "discord", identityId: rows[1]!.id, stepUpMethod: "provider:twitch" }); - }); - - it("the account's only identity is 409 last_identity and the row stays", async () => { - const r = await rig(); - const { account, rows } = await seedAccount(r, [["twitch", "t-1"]]); - const { accessToken } = await signIn(r, true); - const res = await unlink(r, rows[0]!.id, accessToken); - expect([res.statusCode, res.json().error]).toEqual([409, "last_identity"]); - expect(await r.store.listStoredLinkedIdentitiesForAccount(account.id)).toHaveLength(1); - }); - - it("another account's identity and a nonexistent one are the same 404", async () => { - const r = await rig(); - await seedAccount(r, [["twitch", "t-1"], ["discord", "d-9"]]); - const other = await seedAccount(r, [["youtube", "y-other"], ["github", "g-other"]]); - const { accessToken } = await signIn(r, true); - const foreign = await unlink(r, other.rows[0]!.id, accessToken); - const missing = await unlink(r, "no-such-id", accessToken); - expect([foreign.statusCode, foreign.json().error]).toEqual([404, "identity_not_found"]); - expect([missing.statusCode, missing.body]).toEqual([404, foreign.body]); - expect(await r.store.listStoredLinkedIdentitiesForAccount(other.account.id)).toHaveLength(2); - }); - - it("an unlinked identity belongs to no one, and another account can then link it, but not before", async () => { - const r = await rig(); - const mine = await seedAccount(r, [["twitch", "t-1"], ["discord", "d-9"]]); - const theirs = await seedAccount(r, [["youtube", "y-other"]]); - const input = { accountId: theirs.account.id, provider: "discord" as const, providerUserId: "d-9", scopes: [], profileJson: {}, createdAt: now, updatedAt: now }; - await expect(r.store.upsertLinkedIdentity(input)).rejects.toBeInstanceOf(IdentityHeldElsewhereError); - const { accessToken } = await signIn(r, true); - expect((await unlink(r, mine.rows[1]!.id, accessToken)).statusCode).toBe(200); - await expect(r.store.upsertLinkedIdentity(input)).resolves.toMatchObject({ accountId: theirs.account.id }); - }); - - it("writes revocation receipts for the provider's live grants when its last identity goes, and not before", async () => { - const r = await rig(); - const { account, rows } = await seedAccount(r, [["twitch", "t-1"], ["youtube", "y-1"], ["youtube", "y-2"]]); - const grant = async (provider: Provider) => - (await r.store.createConsentReceipt({ kind: "grant", accountId: account.id, appSlug: "streampixels", provider, createdAt: now, scopesAsked: ["a"], scopesGranted: ["a"], consentPageDigest: "d", consentText: "t" })).receipt; - const ytGrant = await grant("youtube"); - const twGrant = await grant("twitch"); - const { accessToken } = await signIn(r, true); - - // A second youtube identity remains: the grant's provider still holds a credential. - expect((await unlink(r, rows[1]!.id, accessToken)).statusCode).toBe(200); - expect((await r.store.listConsentReceipts(account.id)).filter((x) => x.kind === "revocation")).toHaveLength(0); - - // The last youtube identity goes (twitch stays as the sign-in identity): youtube's grant is revoked, twitch's is not. - const audit = vi.spyOn(r.store, "createAuditEvent"); - expect((await unlink(r, rows[2]!.id, accessToken)).statusCode).toBe(200); - const revocations = (await r.store.listConsentReceipts(account.id)).filter((x) => x.kind === "revocation"); - expect(revocations.map((x) => x.kind === "revocation" && x.revokesReceiptId)).toEqual([ytGrant.id]); - expect(revocations.map((x) => x.provider)).toEqual(["youtube"]); - expect(twGrant.id).not.toBe(ytGrant.id); - expect(audit.mock.calls.map(([e]) => e.eventType)).toEqual(expect.arrayContaining(["identity_unlinked", "consent_revoked"])); - }); - - it("proof past the window refuses even a bearer that was fresh when issued", async () => { - const r = await rig(); - const { rows } = await seedAccount(r, [["twitch", "t-1"], ["discord", "d-9"]]); - vi.useFakeTimers({ toFake: ["Date"] }); - const { accessToken } = await signIn(r, true); - vi.setSystemTime(Date.now() + 601_000); - const res = await unlink(r, rows[1]!.id, accessToken); - expect([res.statusCode, res.json().error]).toEqual([403, "step_up_required"]); - }); - - it("the proof window's edge: exactly 600 s old still passes, 601 s does not (frozen clock)", async () => { - const r = await rig(); - const { account, rows } = await seedAccount(r, [["twitch", "t-1"], ["youtube", "y-1"], ["discord", "d-1"]]); - vi.useFakeTimers({ toFake: ["Date"] }); - vi.setSystemTime(new Date("2026-11-13T12:00:00.000Z")); - const nowS = Math.floor(Date.now() / 1000); - const issueWith = async (stepUpAt: number) => - (await issueAccessClaim({ config, keys: r.keys, store: r.store, input: { appSlug: "streampixels", accountId: account.id, linkedIdentities: [], facts: [], stepUpAt } })).accessToken; - const tooOld = await unlink(r, rows[1]!.id, await issueWith(nowS - 601)); - expect([tooOld.statusCode, tooOld.json().error]).toEqual([403, "step_up_required"]); - const edge = await unlink(r, rows[1]!.id, await issueWith(nowS - 600)); - expect(edge.statusCode).toBe(200); - }); - - it("a one-identity bearer naming another account's identity gets 404, not 409", async () => { - const r = await rig(); - await seedAccount(r, [["twitch", "t-1"]]); - const other = await seedAccount(r, [["youtube", "y-other"], ["github", "g-other"]]); - const { accessToken } = await signIn(r, true); - const res = await unlink(r, other.rows[0]!.id, accessToken); - expect([res.statusCode, res.json().error]).toEqual([404, "identity_not_found"]); - }); - - it("a step_up state in a non-sign_in mode (forged, signed) yields no step_up_at", async () => { - const r = await rig(); - const { account } = await seedAccount(r, [["twitch", "t-1"]]); - const started = await r.app.inject({ - method: "POST", - url: "/v1/oauth/twitch/start", - headers: spAuth, - payload: { appSlug: "streampixels", mode: "link", initiatingAccountId: account.id, returnTo }, - }); - expect(started.statusCode).toBe(201); - const verified = verifyJwt(stateOf(started.json()), r.keys.publicKey) as { valid: boolean; payload: Record }; - expect(verified.valid).toBe(true); - expect(verified.payload.mode).toBe("link"); - const flow = await launchState(r.app, signJwt({ ...verified.payload, step_up: true }, r.keys)); - const called = await r.app.inject({ - method: "GET", - url: `/v1/oauth/twitch/callback?code=c&state=${encodeURIComponent(flow.state)}`, - headers: { cookie: flow.cookie, accept: "application/json" }, - }); - expect(called.statusCode).toBe(201); - expect(called.json().stepUpRequested, "the forged flag was read").toBe(true); - const token = called.json().accessToken as string; - expect(token, "the link completion minted an access token to inspect").toBeTruthy(); - expect(decodeJwt(token).payload.step_up_at).toBeUndefined(); - }); -}); diff --git a/tests/link-binding.test.ts b/tests/link-binding.test.ts index 4454d4d..7982229 100644 --- a/tests/link-binding.test.ts +++ b/tests/link-binding.test.ts @@ -6,7 +6,7 @@ import { buildApp } from "../src/app.js"; import { type HeimdallConfig } from "../src/config.js"; import { type OAuthProviderRuntime } from "../src/oauth.js"; import { createRuntimeKeyMaterial, signJwt, verifyJwt } from "../src/signing.js"; -import { IdentityHeldElsewhereError, InMemoryStore } from "../src/store/index.js"; +import { InMemoryStore } from "../src/store/index.js"; import { launchFlow } from "./oauth-flow.js"; function createTestConfig(): HeimdallConfig { @@ -166,15 +166,6 @@ describe("link callback holds the provider identity to the initiator", () => { expect((await r.store.findAccountByLinkedIdentity("discord", "d-held"))?.id).toBe(other.id); }); - it("maps a store refusal of the move (a race past the check) to link_initiator_mismatch", async () => { - const r = await rig("d-race"); - vi.spyOn(r.store, "upsertLinkedIdentity").mockRejectedValueOnce(new IdentityHeldElsewhereError()); - const started = await start(r, { mode: "link", initiatingAccountId: r.initiator.id }); - const done = await callback(r, started.json()); - expect([done.statusCode, done.json().error]).toEqual([403, "link_initiator_mismatch"]); - expect(done.json().completion).toBeUndefined(); - }); - it("refuses a link state that carries no initiator (forged or stripped), before attaching anything", async () => { const dir = mkdtempSync(join(tmpdir(), "heimdall-link-")); try { diff --git a/tests/recipe-secrets.test.ts b/tests/recipe-secrets.test.ts index b6be578..ea144c5 100644 --- a/tests/recipe-secrets.test.ts +++ b/tests/recipe-secrets.test.ts @@ -225,27 +225,4 @@ describe("Idunn recipe secret declarations", () => { expect(serviceNames).toContain(`${name}_FILE`); } }); - - it("declares every other name loadConfig reads, or says why a binding never sets it", () => { - // Idunn refuses a binding that sets an undeclared name, so an undeclared - // name is a setting no Idunn-admitted generation can ever change. - const neverBound = new Set([ - // The listen socket is the candidate bind under Idunn, and the command port follows it. - "HOST", - "PORT", - // The state root is the --state-root argument; the paths below it are Heimdall's own layout. - "GC_ACCESS_DATA_ROOT", - "GC_ACCESS_CULTCACHE_PATH", - "GC_ACCESS_PROVIDER_HEALTH_IDENTITY_PATH", - // The daemon id is the host's name for this process, fixed by the code's default. - "GC_ACCESS_IDUNN_DAEMON", - ]); - const declared = new Set(everyDeclaredName); - const unreachable = [...explored.names] - .filter((name) => !secretNames.includes(name) && !name.endsWith("_FILE")) - .filter((name) => !declared.has(name) && !neverBound.has(name)); - expect(unreachable).toEqual([]); - // An exemption for a name nothing reads would hide the next real gap. - expect([...neverBound].filter((name) => !explored.names.has(name))).toEqual([]); - }); }); diff --git a/tests/step-up-assertion.test.ts b/tests/step-up-assertion.test.ts deleted file mode 100644 index f064e00..0000000 --- a/tests/step-up-assertion.test.ts +++ /dev/null @@ -1,435 +0,0 @@ -import { mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { afterAll, afterEach, describe, expect, it, vi } from "vitest"; -import { buildApp, STEP_UP_ASSERT_LIMITS } from "../src/app.js"; -import { builtInAppProfiles } from "../src/app-profiles.js"; -import { issueAccessClaim } from "../src/claims.js"; -import { type Provider } from "../src/contracts.js"; -import { createRuntimeKeyMaterial, signJwt, verifyJwt } from "../src/signing.js"; -import { InMemoryStore } from "../src/store/index.js"; -import { type CreateAuditEventInput } from "../src/store/types.js"; -import { createTestConfig } from "./oauth-flow.js"; - -// An app asserting a step-up proof for its member: POST /v1/apps/{app}/step-up. -// Driven over HTTP through the real Fastify app, the way Bifrost would call it, -// with the unlink route as the consumer of the proof it mints. - -const now = "2026-11-13T12:00:00.000Z"; -const secret = "bifrost-secret"; -const appAuth = { "x-heimdall-app-secret": secret }; -const nonce = (tag: string) => `nonce-${tag.replace(/[^A-Za-z0-9_-]/g, "_")}-`.padEnd(32, "x"); - -const dir = mkdtempSync(join(tmpdir(), "heimdall-stepup-assert-")); -const config = { ...createTestConfig(), signingPrivateKeyPath: join(dir, "signing.pem"), bootstrapSigningPrivateKeyOnMissing: true }; -afterAll(() => rmSync(dir, { recursive: true, force: true })); - -const apps: Awaited>[] = []; -afterEach(async () => { - vi.useRealTimers(); - vi.restoreAllMocks(); - await Promise.all(apps.splice(0).map((app) => app.close())); -}); - -async function rig() { - const store = new InMemoryStore(); - const audit: CreateAuditEventInput[] = []; - const realAudit = store.createAuditEvent.bind(store); - store.createAuditEvent = async (input) => { - audit.push(structuredClone(input)); - return realAudit(input); - }; - const app = await buildApp({ config, store }); - apps.push(app); - const keys = createRuntimeKeyMaterial({ ...config, bootstrapSigningPrivateKeyOnMissing: false }); - return { app, store, keys, audit }; -} -type Rig = Awaited>; - -/** A member with the given identities and a live Heimdall session for `appSlug`, as a sign-in would have left them. */ -let seq = 0; -async function member(r: Rig, appSlug = "bifrost", held?: Array<[Provider, string]>, accountId?: string) { - seq += 1; - held ??= [["discord", `d-${seq}`], ["google", `g-${seq}`]]; - const account = accountId ? { id: accountId } : await r.store.createAccount({ createdAt: now, lastSeenAt: now }); - const rows = []; - if (!accountId) { - for (const [provider, providerUserId] of held) { - rows.push(await r.store.upsertLinkedIdentity({ accountId: account.id, provider, providerUserId, scopes: [], profileJson: {}, createdAt: now, updatedAt: now })); - } - } - const issued = await issueAccessClaim({ - config, - keys: r.keys, - store: r.store, - input: { appSlug, accountId: account.id, linkedIdentities: held.map(([provider, providerUserId]) => ({ provider, providerUserId })), facts: [] }, - }); - return { account, rows, issued, token: issued.accessToken, sid: issued.session.sessionId }; -} - -const bearer = (token?: string) => (token ? { authorization: `Bearer ${token}` } : {}); -const assertStepUp = (r: Rig, o: { app?: string; headers?: Record; token?: string | undefined; method?: string; nonce?: string; payload?: object } = {}) => - r.app.inject({ - method: "POST", - url: `/v1/apps/${o.app ?? "bifrost"}/step-up`, - headers: { ...(o.headers ?? appAuth), ...bearer(o.token) }, - payload: o.payload ?? { method: o.method ?? "bifrost-passkey", nonce: o.nonce ?? nonce("a") }, - }); -const unlink = (r: Rig, id: string, token: string) => - r.app.inject({ method: "POST", url: `/v1/me/identities/${encodeURIComponent(id)}/unlink`, headers: bearer(token) }); -const refused = (res: { statusCode: number; json(): { error?: string } }) => [res.statusCode, res.json().error]; -const claimsOf = (token: string, r: Rig) => { - const v = verifyJwt(token, r.keys.publicKey); - expect(v.valid).toBe(true); - return v.valid ? v.payload : {}; -}; -const nowS = () => Math.floor(Date.now() / 1000); -const auditOf = (r: Rig, type: string) => r.audit.filter((e) => e.eventType === type); - -describe("the proof it mints", () => { - it("returns a new access token for the same session and account, with step_up_at now and the method, and no refresh token", async () => { - const r = await rig(); - const m = await member(r); - const before = nowS(); - const res = await assertStepUp(r, { token: m.token }); - expect(res.statusCode).toBe(201); - expect(res.headers["cache-control"]).toBe("no-store"); - const body = res.json(); - expect(Object.keys(body).sort()).toEqual(["accessToken", "claimSet", "stepUp"]); - expect(res.body).not.toContain(m.issued.refreshToken); - const original = claimsOf(m.token, r); - const minted = claimsOf(body.accessToken, r); - expect(minted.step_up_method).toBe("bifrost-passkey"); - expect(minted.step_up_at).toBeGreaterThanOrEqual(before); - expect(minted.step_up_at).toBeLessThanOrEqual(nowS()); - expect(body.claimSet).toEqual(minted); - expect(body.stepUp).toEqual({ at: minted.step_up_at, method: "bifrost-passkey", validForSeconds: 600 }); - expect(minted.jti).not.toBe(original.jti); - // Everything else is the bearer's own: it adds proof, not capability, and does not move the session. - const { jti, iat, nbf, step_up_at, step_up_method, ...rest } = minted; - const { jti: _j, iat: _i, nbf: _n, ...originalRest } = original; - expect(rest).toEqual(originalRest); - expect([jti, iat, nbf, step_up_at, step_up_method].every((v) => v !== undefined)).toBe(true); - expect(minted.sid).toBe(m.sid); - expect(minted.account_id).toBe(m.account.id); - expect(minted.aud).toBe("bifrost"); - }); - - it("the unlink check passes with the returned bearer and fails 403 step_up_required with the original", async () => { - const r = await rig(); - const m = await member(r); - expect(refused(await unlink(r, m.rows[1]!.id, m.token))).toEqual([403, "step_up_required"]); - const minted = (await assertStepUp(r, { token: m.token })).json().accessToken; - expect((await unlink(r, m.rows[1]!.id, m.token)).statusCode, "the original bearer gains nothing").toBe(403); - const done = await unlink(r, m.rows[1]!.id, minted); - expect(done.statusCode).toBe(200); - expect(done.json().unlinked.id).toBe(m.rows[1]!.id); - const unlinkEvent = auditOf(r, "identity_unlinked")[0]!; - expect(unlinkEvent.eventPayloadJson).toMatchObject({ provider: "google", stepUpMethod: "bifrost-passkey" }); - }); - - it("does not extend the lifetime: exp stays the bearer's, the session row is untouched, no refresh is minted", async () => { - const r = await rig(); - const m = await member(r); - const sessionBefore = await r.store.findSession("bifrost", m.sid); - vi.useFakeTimers({ toFake: ["Date"] }); - vi.setSystemTime(Date.now() + 1_500_000); - const res = await assertStepUp(r, { token: m.token }); - expect(res.statusCode).toBe(201); - const original = claimsOf(m.token, r); - const minted = claimsOf(res.json().accessToken, r); - expect(minted.exp).toBe(original.exp); - expect(minted.iat).toBeGreaterThan(original.iat as number); - expect(await r.store.findSession("bifrost", m.sid)).toEqual(sessionBefore); - }); - - it("a refresh after an assertion carries neither step_up_at nor step_up_method", async () => { - const r = await rig(); - const m = await member(r); - expect((await assertStepUp(r, { token: m.token })).statusCode).toBe(201); - const refreshed = await r.app.inject({ method: "POST", url: "/v1/apps/bifrost/sessions/refresh", payload: { refreshToken: m.issued.refreshToken } }); - expect(refreshed.statusCode).toBe(201); - const claims = claimsOf(refreshed.json().accessToken, r); - expect(claims).not.toHaveProperty("step_up_at"); - expect(claims).not.toHaveProperty("step_up_method"); - expect(refreshed.json().claimSet).not.toHaveProperty("step_up_at"); - expect(refreshed.json().claimSet).not.toHaveProperty("step_up_method"); - }); - - it("the proof is good for 599 s and not for 601 s, as for any step-up", async () => { - const r = await rig(); - const m = await member(r, "bifrost", [["discord", "d-w"], ["google", "g-w"], ["patreon", "p-w"]]); - vi.useFakeTimers({ toFake: ["Date"] }); - const minted = (await assertStepUp(r, { token: m.token })).json().accessToken; - vi.setSystemTime(Date.now() + 601_000); - expect(refused(await unlink(r, m.rows[1]!.id, minted))).toEqual([403, "step_up_required"]); - vi.setSystemTime(Date.now() - 2_000); - expect((await unlink(r, m.rows[1]!.id, minted)).statusCode).toBe(200); - }); - - it("the provider step-up callback labels its proof provider:", async () => { - // The sign_in path itself is proved in identity-unlink.test.ts; here the claim input is the contract. - const r = await rig(); - const m = await member(r); - const issued = await issueAccessClaim({ - config, keys: r.keys, store: r.store, - input: { appSlug: "bifrost", accountId: m.account.id, linkedIdentities: [], facts: [], stepUpAt: nowS(), stepUpMethod: "provider:google" }, - }); - expect(issued.claimSet.step_up_method).toBe("provider:google"); - }); -}); - -describe("it is never issuable without both credentials", () => { - it("401 app_auth_required for a missing, wrong, or another app's secret, even with a good bearer; nothing is written", async () => { - const r = await rig(); - const m = await member(r); - for (const headers of [{}, { "x-heimdall-app-secret": "wrong" }, { "x-heimdall-app-secret": "streampixels-secret" }, { "x-heimdall-app-secret": "" }]) { - const res = await assertStepUp(r, { headers, token: m.token }); - expect(res.statusCode).toBe(401); - expect(res.json()).toEqual({ error: "app_auth_required" }); - } - expect(r.audit.filter((e) => e.eventType.startsWith("step_up"))).toEqual([]); - }); - - it("401 sign_in_required for a missing, garbage, expired, foreign-signed, revoked-session or unknown-session bearer; the same answer for each", async () => { - const r = await rig(); - const m = await member(r); - const claims = claimsOf(m.token, r); - const past = nowS() - 10; - const other = createRuntimeKeyMaterial({ ...config, signingPrivateKeyPath: join(dir, "other.pem"), bootstrapSigningPrivateKeyOnMissing: true }); - const bad: Array<[string, string | undefined]> = [ - ["missing", undefined], - ["garbage", "not-a-token"], - ["expired", signJwt({ ...claims, iat: past - 100, nbf: past - 100, exp: past }, r.keys)], - ["foreign key", signJwt(claims, other)], - ["unknown session", signJwt({ ...claims, sid: "no-such-session" }, r.keys)], - ["wrong account for the session", signJwt({ ...claims, account_id: "someone-else" }, r.keys)], - ["refresh token as bearer", m.issued.refreshToken], - ]; - for (const [label, token] of bad) { - const res = await assertStepUp(r, { token, nonce: nonce(label) }); - expect([label, ...refused(res)]).toEqual([label, 401, "sign_in_required"]); - expect(res.body).not.toContain("account"); - } - // A revoked session: the row is closed and its revision moved on. - expect(await r.store.revokeSession("bifrost", m.sid, m.account.id, 1, now)).not.toBeNull(); - const revoked = await assertStepUp(r, { token: m.token, nonce: nonce("revoked") }); - expect(refused(revoked)).toEqual([401, "sign_in_required"]); - expect(r.audit.some((e) => e.eventType === "step_up_asserted")).toBe(false); - }); - - it("a bearer issued to another app is 403 bearer_app_mismatch, never a proof, and says nothing about the account", async () => { - const r = await rig(); - const sp = await member(r, "streampixels"); - const res = await assertStepUp(r, { token: sp.token }); - expect(refused(res)).toEqual([403, "bearer_app_mismatch"]); - expect(res.body).not.toContain(sp.account.id); - // A token for a session that does not exist is indistinguishable from garbage, whatever app it names. - const ghost = signJwt({ ...claimsOf(sp.token, r), sid: "ghost" }, r.keys); - expect(refused(await assertStepUp(r, { token: ghost }))).toEqual([401, "sign_in_required"]); - }); - - it("only a profile that grants it may assert: every other app is 403 with its own secret and a live bearer", async () => { - expect(Object.values(builtInAppProfiles).filter((p) => p.stepUpAssertion).map((p) => p.slug)).toEqual(["bifrost"]); - const r = await rig(); - for (const [slug, appSecret] of [["streampixels", "streampixels-secret"], ["repixelizer", "repixelizer-secret"]] as const) { - const m = await member(r, slug); - const res = await assertStepUp(r, { app: slug, headers: { "x-heimdall-app-secret": appSecret }, token: m.token }); - expect([slug, ...refused(res)]).toEqual([slug, 403, "step_up_assertion_not_permitted"]); - expect(res.json()).not.toHaveProperty("accessToken"); - } - // Another app's secret on bifrost's route is still app_auth_required, not the flag. - const b = await member(r); - expect(refused(await assertStepUp(r, { headers: { "x-heimdall-app-secret": "streampixels-secret" }, token: b.token }))).toEqual([401, "app_auth_required"]); - }); -}); - -describe("the method and the nonce", () => { - it("rejects a method outside the profile's closed set with 400, names the set, and does not spend the nonce", async () => { - const r = await rig(); - const m = await member(r); - for (const method of ["passkey", "provider:google", "streampixels-passkey", "BIFROST-PASSKEY", "bifrost-passkey "]) { - const res = await assertStepUp(r, { token: m.token, method, nonce: nonce("m") }); - expect([method, ...refused(res)]).toEqual([method, 400, "unknown_step_up_method"]); - expect(res.json().methods).toEqual(["bifrost-passkey", "bifrost-email-code"]); - } - expect((await assertStepUp(r, { token: m.token, method: "bifrost-email-code", nonce: nonce("m") })).statusCode).toBe(201); - }); - - it("malformed bodies are 400 before anything is minted", async () => { - const r = await rig(); - const m = await member(r); - for (const payload of [{}, { method: "bifrost-passkey" }, { nonce: nonce("a") }, { method: "bifrost-passkey", nonce: "short" }, { method: "bifrost-passkey", nonce: "has a space in it, 16+ chars" }, { method: "bifrost-passkey", nonce: `${"a".repeat(20)}\ud800` }, { method: "bifrost-passkey", nonce: "a".repeat(129) }, { method: "bifrost-passkey", nonce: "ok-looking-nonce-é-ünï" }, { method: 7, nonce: nonce("a") }]) { - expect((await assertStepUp(r, { token: m.token, payload })).statusCode, JSON.stringify(payload)).toBe(400); - } - expect(auditOf(r, "step_up_asserted")).toEqual([]); - }); - - it("a nonce is single-use per session: the second try is 409, another session may use the same value", async () => { - const r = await rig(); - const m = await member(r); - const second = await member(r, "bifrost", [], m.account.id); - expect((await assertStepUp(r, { token: m.token })).statusCode).toBe(201); - const replay = await assertStepUp(r, { token: m.token }); - expect(refused(replay)).toEqual([409, "step_up_nonce_replayed"]); - expect(replay.json()).not.toHaveProperty("accessToken"); - // The replay does not depend on which method rides with it. - expect(refused(await assertStepUp(r, { token: m.token, method: "bifrost-email-code" }))).toEqual([409, "step_up_nonce_replayed"]); - expect((await assertStepUp(r, { token: second.token })).statusCode).toBe(201); - }); - - it("a nonce is retained to the session's expiry as of the claim plus the 10.5 min prune horizon; a refresh slides the session past that and the nonce can be reused (documented limit)", async () => { - const r = await rig(); - const m = await member(r); - vi.useFakeTimers({ toFake: ["Date"] }); - const t0 = Date.now(); - const R = config.refreshTtlSeconds * 1000; - expect((await assertStepUp(r, { token: m.token, nonce: nonce("N") })).statusCode).toBe(201); - vi.setSystemTime(t0 + R - 60_000); - const refreshed = await r.app.inject({ method: "POST", url: "/v1/apps/bifrost/sessions/refresh", payload: { refreshToken: m.issued.refreshToken } }); - expect(refreshed.statusCode).toBe(201); - const token = refreshed.json().accessToken as string; - expect(refused(await assertStepUp(r, { token, nonce: nonce("N") })).join()).toBe("409,step_up_nonce_replayed"); - // 10 min past the old expiry: a claim runs the prune, and N is still inside the 10.5 min horizon (10 min margin + 30 s skew). - vi.setSystemTime(t0 + R + 10 * 60_000); - expect((await assertStepUp(r, { token, nonce: nonce("M") })).statusCode).toBe(201); - expect(refused(await assertStepUp(r, { token, nonce: nonce("N") }))).toEqual([409, "step_up_nonce_replayed"]); - // Past the horizon the next claim prunes N (lazily, with the claim) while the session lives on. - vi.setSystemTime(t0 + R + 10 * 60_000 + 31_000 + 2_000); - expect((await assertStepUp(r, { token, nonce: nonce("K") })).statusCode).toBe(201); - expect((await assertStepUp(r, { token, nonce: nonce("N") })).statusCode).toBe(201); - }); - - it("a nonce stays spent for the session's life, past the access token's own expiry, and across a restart of the process", async () => { - const r = await rig(); - const m = await member(r); - expect((await assertStepUp(r, { token: m.token })).statusCode).toBe(201); - // A second app instance over the same store has no memory of the first: the store carries the claim. - const again = await buildApp({ config, store: r.store }); - apps.push(again); - const res = await again.inject({ method: "POST", url: "/v1/apps/bifrost/step-up", headers: { ...appAuth, ...bearer(m.token) }, payload: { method: "bifrost-passkey", nonce: nonce("a") } }); - expect(refused(res)).toEqual([409, "step_up_nonce_replayed"]); - }); -}); - -describe("rate limits", () => { - it("trips per account, leaves other accounts alone, and turns over with the window", async () => { - const r = await rig(); - const m = await member(r); - const other = await member(r); - vi.useFakeTimers({ toFake: ["Date"] }); - for (let i = 0; i < STEP_UP_ASSERT_LIMITS.account.max; i += 1) { - expect((await assertStepUp(r, { token: m.token, nonce: nonce(`r${i}`) })).statusCode, `attempt ${i}`).toBe(201); - } - const tripped = await assertStepUp(r, { token: m.token, nonce: nonce("over") }); - expect(refused(tripped)).toEqual([429, "step_up_rate_limited"]); - expect(tripped.json().retryAfterSeconds).toBeGreaterThan(0); - expect(tripped.json()).not.toHaveProperty("accessToken"); - expect((await assertStepUp(r, { token: other.token })).statusCode).toBe(201); - vi.setSystemTime(Date.now() + STEP_UP_ASSERT_LIMITS.account.windowMs + 1000); - expect((await assertStepUp(r, { token: m.token, nonce: nonce("after") })).statusCode).toBe(201); - // The tripped attempt did not spend its nonce. - expect((await assertStepUp(r, { token: m.token, nonce: nonce("over") })).statusCode).toBe(201); - }); - - it("trips per app across accounts, counting attempts that failed their bearer", async () => { - const r = await rig(); - const m = await member(r); - vi.useFakeTimers({ toFake: ["Date"] }); - for (let i = 0; i < STEP_UP_ASSERT_LIMITS.app.max; i += 1) { - expect((await assertStepUp(r, { token: "garbage", nonce: nonce(`g${i}`) })).statusCode).toBe(401); - } - expect(refused(await assertStepUp(r, { token: m.token }))).toEqual([429, "step_up_rate_limited"]); - vi.setSystemTime(Date.now() + STEP_UP_ASSERT_LIMITS.app.windowMs + 1000); - expect((await assertStepUp(r, { token: m.token })).statusCode).toBe(201); - }); -}); - -describe("flood handling", () => { - it("the not-permitted budget is per app: one app's flood neither blocks bifrost's own call nor another ungranted app's first refusal", async () => { - const r = await rig(); - const sp = await member(r, "streampixels"); - const rp = await member(r, "repixelizer"); - const b = await member(r); - const as = (app: string, appSecret: string, token: string, i: number) => assertStepUp(r, { app, headers: { "x-heimdall-app-secret": appSecret }, token, nonce: nonce(`i${i}`) }); - for (let i = 0; i < 50; i += 1) await as("streampixels", "streampixels-secret", sp.token, i); - expect((await as("streampixels", "streampixels-secret", sp.token, 99)).statusCode).toBe(429); - expect(refused(await as("repixelizer", "repixelizer-secret", rp.token, 1))).toEqual([403, "step_up_assertion_not_permitted"]); - expect((await assertStepUp(r, { token: b.token })).statusCode).toBe(201); - }); - - it("a flood is not an audit flood: an app without the grant is audited once per window, a tripped budget once per window", async () => { - const r = await rig(); - const sp = await member(r, "streampixels"); - vi.useFakeTimers({ toFake: ["Date"] }); - const codes: Record = {}; - for (let i = 0; i < 500; i += 1) { - const res = await assertStepUp(r, { app: "streampixels", headers: { "x-heimdall-app-secret": "streampixels-secret" }, token: sp.token, nonce: nonce(`f${i}`) }); - codes[res.statusCode] = (codes[res.statusCode] ?? 0) + 1; - } - expect(codes).toEqual({ 403: STEP_UP_ASSERT_LIMITS.notPermitted.max, 429: 500 - STEP_UP_ASSERT_LIMITS.notPermitted.max }); - const rows = (code: string) => auditOf(r, "step_up_assertion_refused").filter((e) => e.eventPayloadJson.code === code); - expect(rows("step_up_assertion_not_permitted")).toHaveLength(1); - expect(rows("step_up_rate_limited")).toHaveLength(1); - expect(rows("step_up_rate_limited")[0]!.eventPayloadJson.budget).toBe("notPermitted"); - vi.setSystemTime(Date.now() + STEP_UP_ASSERT_LIMITS.notPermitted.windowMs + 1000); - await assertStepUp(r, { app: "streampixels", headers: { "x-heimdall-app-secret": "streampixels-secret" }, token: sp.token }); - expect(rows("step_up_assertion_not_permitted")).toHaveLength(2); - - // The same for the granted app's per-app and per-account budgets. - const m = await member(r); - const before = r.audit.length; - for (let i = 0; i < 300; i += 1) await assertStepUp(r, { token: "garbage", nonce: nonce(`g${i}`) }); - expect(r.audit.length - before, "garbage-bearer refusals up to the budget, then one row for the trip").toBe(STEP_UP_ASSERT_LIMITS.app.max + 1); - vi.setSystemTime(Date.now() + STEP_UP_ASSERT_LIMITS.app.windowMs + 1000); - const mark = r.audit.length; - for (let i = 0; i < 30; i += 1) await assertStepUp(r, { token: m.token, nonce: nonce(`a${i}`) }); - const accountRows = r.audit.slice(mark); - expect(accountRows.filter((e) => e.eventType === "step_up_asserted")).toHaveLength(STEP_UP_ASSERT_LIMITS.account.max); - const trips = accountRows.filter((e) => e.eventPayloadJson.code === "step_up_rate_limited"); - expect(trips.map((e) => e.eventPayloadJson.budget)).toEqual(["account"]); - }); -}); - -describe("receipts", () => { - it("records every assertion and every post-secret refusal with account, app, session, method, outcome and time, and nothing secret", async () => { - const r = await rig(); - const m = await member(r); - const sp = await member(r, "streampixels"); - const printed: string[] = []; - for (const channel of ["log", "info", "warn", "error", "debug"] as const) vi.spyOn(console, channel).mockImplementation((...a) => void printed.push(a.join(" "))); - vi.spyOn(process.stdout, "write").mockImplementation((chunk: unknown) => (printed.push(String(chunk)), true)); - vi.spyOn(process.stderr, "write").mockImplementation((chunk: unknown) => (printed.push(String(chunk)), true)); - - const nonceOk = nonce("ok-CANARY"); - const nonceBadMethod = nonce("bad-CANARY"); - const responses = [ - await assertStepUp(r, { token: m.token, nonce: nonceOk }), - await assertStepUp(r, { token: m.token, nonce: nonceOk }), - await assertStepUp(r, { token: m.token, method: "evil-CANARY-method", nonce: nonceBadMethod }), - await assertStepUp(r, { token: sp.token, nonce: nonce("mismatch-CANARY") }), - await assertStepUp(r, { token: "garbage-CANARY", nonce: nonce("anon-CANARY") }), - ]; - expect(responses.map((x) => x.statusCode)).toEqual([201, 409, 400, 403, 401]); - - const ok = auditOf(r, "step_up_asserted"); - expect(ok).toHaveLength(1); - expect(ok[0]).toMatchObject({ accountId: m.account.id, sessionId: m.sid, appSlug: "bifrost", eventPayloadJson: { outcome: "asserted", method: "bifrost-passkey" } }); - expect(Date.parse(ok[0]!.createdAt)).not.toBeNaN(); - const refusals = auditOf(r, "step_up_assertion_refused"); - expect(refusals.map((e) => e.eventPayloadJson.code)).toEqual(["step_up_nonce_replayed", "unknown_step_up_method", "bearer_app_mismatch", "sign_in_required"]); - expect(refusals.map((e) => e.accountId)).toEqual([m.account.id, m.account.id, sp.account.id, undefined]); - expect(refusals[1]!.eventPayloadJson.method).toBeNull(); - expect(refusals.every((e) => e.appSlug === "bifrost" && e.eventPayloadJson.outcome === "refused")).toBe(true); - for (const e of [...ok, ...refusals.slice(0, 2)]) expect(e.eventPayloadJson.nonceDigest).toMatch(/^[0-9a-f]{64}$/); - - const everything = JSON.stringify([r.audit, printed, responses.map((x) => x.body.replace(/"accessToken":"[^"]+"/, ""))]); - const minted = responses[0]!.json().accessToken as string; - const secrets = [secret, m.token, sp.token, m.issued.refreshToken, "CANARY"]; - for (const needle of secrets) expect(everything, needle).not.toContain(needle); - expect(JSON.stringify(r.audit)).not.toContain(minted); - expect(printed.join("")).not.toContain(minted); - // A stored session row holds nothing the minted token adds. - expect(JSON.stringify(await r.store.findSession("bifrost", m.sid))).not.toContain("step_up"); - }); -}); diff --git a/tests/step-up.test.ts b/tests/step-up.test.ts index 6716623..99531e3 100644 --- a/tests/step-up.test.ts +++ b/tests/step-up.test.ts @@ -150,8 +150,6 @@ describe("the flag is the signed state's, not the redeem side's", () => { const redeemed = await app.inject({ method: "POST", url: "/v1/apps/streampixels/auth-completions/redeem", payload: { completionCode: code, stepUp: true } }); expect(redeemed.statusCode).toBe(201); expect(redeemed.json().stepUpRequested).toBe(asked ? true : undefined); - // The proof is the signed state's too: the claim carries step_up_at exactly when the start asked. - expect(typeof redeemed.json().claimSet.step_up_at).toBe(asked ? "number" : "undefined"); } }); }); diff --git a/tests/store.test.ts b/tests/store.test.ts index 03b869a..dc0fbe2 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -3,7 +3,7 @@ import { Pool } from "pg"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { newDb } from "pg-mem"; import { type HeimdallConfig } from "../src/config.js"; -import { createStore, IdentityHeldElsewhereError, InMemoryStore, type HeimdallStore } from "../src/store/index.js"; +import { createStore, InMemoryStore } from "../src/store/index.js"; import { createPostgresStore, PostgresStore, @@ -203,88 +203,6 @@ describe("PostgresStore", () => { }); }); -// linked_identities has one writer that can move a row between accounts: none. -// upsert refreshes the holder's own row and refuses another account's; unlink is -// the only delete, and it never takes an account's last identity. -const unlinkStores: Array<[string, () => Promise]> = [ - ["InMemoryStore", async () => new InMemoryStore()], - [ - "PostgresStore on pg-mem", - async () => { - const store = new PostgresStore(new (newDb().adapters.createPg().Pool)()); - await store.ensureSchema(); - return store; - }, - ], -]; -describe.each(unlinkStores)("linked_identities writes, %s", (_name, make) => { - const at = "2026-11-13T12:00:00.000Z"; - const input = (accountId: string, providerUserId: string, extra: Record = {}) => ({ - accountId, - provider: "discord" as const, - providerUserId, - scopes: ["identify"], - profileJson: {}, - createdAt: at, - updatedAt: at, - ...extra, - }); - async function twoAccounts() { - const store = await make(); - const a = await store.createAccount({ createdAt: at, lastSeenAt: at }); - const b = await store.createAccount({ createdAt: at, lastSeenAt: at }); - return { store, a, b }; - } - - // pg-mem has neither ON CONFLICT ... WHERE nor row locks: these two run on real Postgres below. - const realPostgresOnly = _name !== "InMemoryStore"; - - it.skipIf(realPostgresOnly)("upsert on an identity another account holds throws IdentityHeldElsewhereError and leaves the row untouched", async () => { - const { store, a, b } = await twoAccounts(); - const held = await store.upsertLinkedIdentity(input(a.id, "u1", { username: "original", accessTokenEncrypted: "keep" })); - await expect( - store.upsertLinkedIdentity(input(b.id, "u1", { username: "thief", accessTokenEncrypted: "stolen", updatedAt: "2027-01-01T00:00:00.000Z" })) - ).rejects.toBeInstanceOf(IdentityHeldElsewhereError); - expect(await store.findStoredLinkedIdentity("discord", "u1")).toEqual(held); - expect(await store.listStoredLinkedIdentitiesForAccount(b.id)).toEqual([]); - }); - - it.skipIf(realPostgresOnly)("moveIdentities keeps one contract: moved, replayed, conflict, lapsed proof, coverage, reversal", async () => { - await exerciseMoveContract(await make()); - }); - - it("upsert by the holder still refreshes its own row, keeping its id", async () => { - const { store, a } = await twoAccounts(); - const first = await store.upsertLinkedIdentity(input(a.id, "u1", { username: "one" })); - const again = await store.upsertLinkedIdentity(input(a.id, "u1", { username: "two", updatedAt: "2026-11-14T00:00:00.000Z" })); - expect([again.id, again.accountId, again.username]).toEqual([first.id, a.id, "two"]); - }); - - it("unlink: deletes one of two, refuses the last, reports another account's or a missing id as not_found", async () => { - const { store, a, b } = await twoAccounts(); - const one = await store.upsertLinkedIdentity(input(a.id, "u1")); - const two = await store.upsertLinkedIdentity(input(a.id, "u2")); - const theirs = await store.upsertLinkedIdentity(input(b.id, "u3")); - expect(await store.unlinkLinkedIdentity(a.id, theirs.id)).toEqual({ kind: "not_found" }); - expect(await store.unlinkLinkedIdentity(a.id, "no-such")).toEqual({ kind: "not_found" }); - expect(await store.unlinkLinkedIdentity(b.id, theirs.id)).toEqual({ kind: "last_identity" }); - const done = await store.unlinkLinkedIdentity(a.id, one.id); - expect(done).toMatchObject({ kind: "unlinked", identity: { id: one.id, provider: "discord", providerUserId: "u1" } }); - expect(await store.unlinkLinkedIdentity(a.id, two.id)).toEqual({ kind: "last_identity" }); - expect((await store.listStoredLinkedIdentitiesForAccount(a.id)).map((i) => i.id)).toEqual([two.id]); - expect(await store.findStoredLinkedIdentity("discord", "u3")).toMatchObject({ id: theirs.id, accountId: b.id }); - }); - - it.skipIf(realPostgresOnly)("two concurrent unlinks of an account's last two identities leave exactly one", async () => { - const { store, a } = await twoAccounts(); - const one = await store.upsertLinkedIdentity(input(a.id, "u1")); - const two = await store.upsertLinkedIdentity(input(a.id, "u2")); - const results = await Promise.all([store.unlinkLinkedIdentity(a.id, one.id), store.unlinkLinkedIdentity(a.id, two.id)]); - expect(results.map((r) => r.kind).sort()).toEqual(["last_identity", "unlinked"]); - expect(await store.listStoredLinkedIdentitiesForAccount(a.id)).toHaveLength(1); - }); -}); - describe("consent_receipts foreign key", () => { it("a revocation names a receipt of its own account: the schema says so and the memory store enforces it", async () => { expect(CREATE_SCHEMA_SQL).toContain("FOREIGN KEY (revokes_receipt_id, account_id) REFERENCES consent_receipts(id, account_id)"); @@ -481,10 +399,9 @@ describe("PostgresStore.checkSchema", () => { "capability_grants", "entitlement_snapshots", "consent_receipts", - "identity_moves", "audit_events", ]); - expect(REQUIRED_COLUMNS).toHaveLength(121); + expect(REQUIRED_COLUMNS).toHaveLength(113); expect(REQUIRED_COLUMNS).toEqual( expect.arrayContaining([ { table: "auth_completions", column: "code", type: "TEXT", nullable: false }, @@ -495,7 +412,7 @@ describe("PostgresStore.checkSchema", () => { { table: "auth_completions", column: "attempt_id", type: "TEXT", nullable: true }, ]) ); - expect(REQUIRED_KEYS).toHaveLength(19); + expect(REQUIRED_KEYS).toHaveLength(17); expect(REQUIRED_KEYS).toEqual( expect.arrayContaining([ { table: "linked_identities", columns: "provider,provider_user_id", predicate: "" }, @@ -503,7 +420,6 @@ describe("PostgresStore.checkSchema", () => { { table: "oauth_state_uses", columns: "jti,phase", predicate: "" }, { table: "consent_receipts", columns: "revokes_receipt_id", predicate: "revokes_receipt_id IS NOT NULL" }, { table: "consent_receipts", columns: "account_id,id", predicate: "" }, - { table: "identity_moves", columns: "reverses_move_id", predicate: "reverses_move_id IS NOT NULL" }, { table: "entitlement_snapshots", columns: "account_id,provider,scope", predicate: "" }, { table: "auth_completions", columns: "app_slug,attempt_id", predicate: "attempt_id IS NOT NULL AND consumed_at IS NULL" }, ]) @@ -580,8 +496,6 @@ async function exerciseStore(store: PostgresStore): Promise> { const linked = await s.upsertLinkedIdentity(identity); await s.updateLinkedIdentityCredential(linked.id, async () => ({ kind: "keep" })); await s.upsertLinkedIdentity({ ...identity, username: "again" }); - const spare = await s.upsertLinkedIdentity({ ...identity, providerUserId: "u-spare" }); - expect((await s.unlinkLinkedIdentity(account.id, spare.id)).kind).toBe("unlinked"); await s.findAccountByLinkedIdentity("discord", "u1"); await s.findStoredLinkedIdentity("discord", "u1"); await s.findStoredLinkedIdentityForAccount(account.id, "discord"); @@ -654,178 +568,9 @@ async function exerciseStore(store: PostgresStore): Promise> { expect(second.receipt.id).toBe(first.receipt.id); expect((await s.listConsentReceipts(account.id)).map((r) => r.kind)).toEqual(["grant", "revocation"]); await s.createAuditEvent({ eventType: "probe", eventPayloadJson: {}, createdAt: now }); - const target = await s.createAccount({ createdAt: now, lastSeenAt: now }); - await s.upsertLinkedIdentity({ ...identity, accountId: target.id, provider: "patreon", providerUserId: "u-target" }); - const moveId = `move-${randomUUID()}`; - expect((await s.moveIdentities({ moveId, appSlug: "bifrost", fromAccountId: account.id, toAccountId: target.id, identityIds: "all", covers: "account", proofSessions: [], proof: { from: [], to: null }, at: now })).kind).toBe("moved"); - expect((await s.findIdentityMove(moveId))?.id).toBe(moveId); return called; } -/** - * The move contract both stores keep, once. Each case builds its own accounts, - * so the order of cases proves nothing and a store holding earlier moves is fine. - */ -async function exerciseMoveContract(store: HeimdallStore): Promise { - const at = "2026-11-14T12:00:00.000Z"; - const later = "2999-01-01T00:00:00.000Z"; - const proofTiers = { from: [{ tier: "strong" as const, method: "bifrost-passkey", identityId: null }], to: { tier: "weak" as const, method: null, identityId: null } }; - const side = async (providers: Array<"discord" | "google" | "patreon">) => { - const account = await store.createAccount({ createdAt: at, lastSeenAt: at }); - const rows = []; - for (const provider of providers) { - rows.push(await store.upsertLinkedIdentity({ accountId: account.id, provider, providerUserId: `${provider}-${randomUUID()}`, accessTokenEncrypted: "A", refreshTokenEncrypted: "R", scopes: [], profileJson: {}, createdAt: at, updatedAt: at })); - } - const sessionId = randomUUID(); - await store.createSession({ id: sessionId, accountId: account.id, appSlug: "bifrost", createdAt: at, lastSeenAt: at, expiresAt: later, accessRevision: 1, claimsJson: {} }); - return { account, rows, proofSession: { appSlug: "bifrost" as const, sessionId, accountId: account.id, accessRevision: 1 } }; - }; - const input = (from: Awaited>, to: Awaited>, extra: Record = {}) => ({ - moveId: `move-${randomUUID()}`, - appSlug: "bifrost" as const, - fromAccountId: from.account.id, - toAccountId: to.account.id, - identityIds: "all" as const, - covers: "account" as const, - proofSessions: [from.proofSession, to.proofSession], - proof: proofTiers, - at, - ...extra, - }); - const held = async (a: { account: { id: string } }) => (await store.listStoredLinkedIdentitiesForAccount(a.account.id)).map((i) => i.id).sort(); - - // Moved: rows, credentials, sessions and the record. - const a = await side(["discord", "google"]); - const b = await side(["patreon"]); - const first = input(a, b); - const moved = await store.moveIdentities(first); - expect(moved.kind).toBe("moved"); - expect(await held(a)).toEqual([]); - expect(await held(b)).toEqual([...a.rows.map((r) => r.id), ...b.rows.map((r) => r.id)].sort()); - for (const row of await store.listStoredLinkedIdentitiesForAccount(b.account.id)) { - if (a.rows.some((r) => r.id === row.id)) expect([row.accessTokenEncrypted, row.refreshTokenEncrypted]).toEqual([undefined, undefined]); - else expect(row.accessTokenEncrypted, "the destination's own credential is untouched").toBe("A"); - } - const record = await store.findIdentityMove(first.moveId); - expect(record).toMatchObject({ id: first.moveId, fromAccountId: a.account.id, toAccountId: b.account.id, proof: proofTiers, createdAt: at }); - expect(record!.moved.map((m) => m.credentialStripped)).toEqual([true, true]); - expect((await store.findSession("bifrost", a.proofSession.sessionId))!.accessRevision).toBe(2); - expect((await store.findSession("bifrost", b.proofSession.sessionId))!.accessRevision).toBe(1); - - // Replay answers from the row, even though the proof session is gone; a different pair is a conflict. - expect(await store.moveIdentities(first)).toEqual({ kind: "replayed", move: record }); - const c = await side(["discord"]); - expect(await store.moveIdentities({ ...first, toAccountId: c.account.id })).toEqual({ kind: "move_id_conflict" }); - expect(await store.moveIdentities({ ...first, reversesMoveId: "x" })).toEqual({ kind: "move_id_conflict" }); - - // Into or out of an alias. - expect((await store.moveIdentities(input(a, c, { proofSessions: [c.proofSession] }))).kind).toBe("already_moved"); - expect((await store.moveIdentities(input(c, a, { proofSessions: [c.proofSession] }))).kind).toBe("already_moved"); - - // A proof session that was revoked, or has moved on a revision, has lapsed. - const d = await side(["google"]); - const e = await side(["patreon"]); - await store.revokeSession("bifrost", e.proofSession.sessionId, e.account.id, 1, at); - expect((await store.moveIdentities(input(d, e))).kind).toBe("proof_lapsed"); - expect(await held(d)).toHaveLength(1); - - // Coverage and conflict. - const f = await side(["discord", "google"]); - const g = await side(["patreon"]); - expect((await store.moveIdentities(input(f, g, { covers: [f.rows[0]!.id] }))).kind).toBe("identity_not_proved"); - expect((await store.moveIdentities(input(f, g, { identityIds: ["nope"] }))).kind).toBe("identity_not_found"); - const h = await side(["discord"]); - expect(await store.moveIdentities(input(f, h))).toEqual({ kind: "provider_conflict", provider: "discord" }); - expect(await held(f)).toHaveLength(2); - const onlyDiscord = await store.moveIdentities(input(f, g, { identityIds: [f.rows[0]!.id], covers: [f.rows[0]!.id] })); - expect(onlyDiscord.kind).toBe("moved"); - expect(await held(f)).toEqual([f.rows[1]!.id]); - - // Reversal: moves exactly what the forward carried, once, and a reversal is not itself reversible. - const forward = (moved as { move: { id: string } }).move; - const back = input(b, a, { reversesMoveId: forward.id, proofSessions: [], identityIds: a.rows.map((r) => r.id), covers: a.rows.map((r) => r.id) }); - const reversed = await store.moveIdentities(back); - expect(reversed.kind).toBe("moved"); - expect(await held(a)).toEqual(a.rows.map((r) => r.id).sort()); - expect(await held(b)).toEqual(b.rows.map((r) => r.id)); - expect((await store.moveIdentities({ ...back, moveId: `move-${randomUUID()}` })).kind).toBe("not_reversible"); - expect((await store.moveIdentities(input(a, b, { reversesMoveId: back.moveId, proofSessions: [], identityIds: "all" }))).kind).toBe("not_reversible"); - - // A moveId answers only the move that used it: each of app, source, destination and reversal must match. - const k = await side(["discord"]); - const l = await side(["patreon"]); - const m = await side(["google"]); - const once = input(k, l); - expect((await store.moveIdentities(once)).kind).toBe("moved"); - expect((await store.moveIdentities({ ...once, fromAccountId: m.account.id })).kind).toBe("move_id_conflict"); - expect((await store.moveIdentities({ ...once, toAccountId: m.account.id })).kind).toBe("move_id_conflict"); - expect((await store.moveIdentities({ ...once, appSlug: "streampixels" })).kind).toBe("move_id_conflict"); - expect((await store.moveIdentities(once)).kind).toBe("replayed"); - - // Every step of a move is on Postgres too: expiry of the source's pending links and unredeemed completions, and the stripped credential's expiry and failure mark. - const n = await side(["discord", "google"]); - const o = await side(["patreon"]); - await store.upsertLinkedIdentity({ accountId: n.account.id, provider: "discord", providerUserId: (await store.listStoredLinkedIdentitiesForAccount(n.account.id))[0]!.providerUserId, tokenExpiresAt: "2999-01-01T00:00:00.000Z", scopes: [], profileJson: {}, createdAt: at, updatedAt: at }); - await store.updateLinkedIdentityCredential(n.rows[1]!.id, async () => ({ kind: "failed", failedAt: at })); - const linkOf = (accountId: string) => store.createPendingLink({ appSlug: "bifrost", accountId, provider: "discord", providerUserId: "p", identity: { accountId, provider: "discord", providerUserId: "p", scopes: [], profileJson: {}, createdAt: at, updatedAt: at }, returnTo: "https://x.test/", createdAt: at, expiresAt: later }); - const completionOf = (accountId: string) => store.createAuthCompletion({ appSlug: "bifrost", provider: "discord", mode: "sign_in", accountId, sessionId: n.proofSession.sessionId, returnTo: "https://x.test/", createdAt: at, expiresAt: later, payloadJson: {} }); - const sourceLink = await linkOf(n.account.id); - const destLink = await linkOf(o.account.id); - const sourceCompletion = await completionOf(n.account.id); - const destCompletion = await completionOf(o.account.id); - expect((await store.moveIdentities(input(n, o))).kind).toBe("moved"); - const after = "2026-11-14T12:00:01.000Z"; - expect(await store.consumePendingLink("bifrost", sourceLink.id, n.account.id, after)).toBeNull(); - expect(await store.consumeAuthCompletion("bifrost", sourceCompletion.code, after)).toBeNull(); - expect((await store.consumePendingLink("bifrost", destLink.id, o.account.id, after))?.id).toBe(destLink.id); - expect((await store.consumeAuthCompletion("bifrost", destCompletion.code, after))?.code).toBe(destCompletion.code); - for (const row of (await store.listStoredLinkedIdentitiesForAccount(o.account.id)).filter((r) => n.rows.some((x) => x.id === r.id))) { - expect([row.accessTokenEncrypted, row.refreshTokenEncrypted, row.tokenExpiresAt, row.refreshFailedAt], row.provider).toEqual([undefined, undefined, undefined, undefined]); - } - - // Each reversal guard on its own: the refusal is not_reversible, never another code, and nothing moves. - const fresh = async () => ({ p: await side(["discord", "google"]), q: await side(["patreon"]), t: await side(["patreon"]) }); - const reverse = (forwardId: string, from: { account: { id: string } }, to: { account: { id: string } }, ids: readonly string[]) => ({ - moveId: `move-${randomUUID()}`, appSlug: "bifrost" as const, fromAccountId: from.account.id, toAccountId: to.account.id, - identityIds: ids, covers: ids, proofSessions: [], reversesMoveId: forwardId, proof: { from: [], to: null }, at, - }); - // (a) already reversed, even though the logins are back on the destination by a later forward move - { - const { p, q } = await fresh(); - const ids = p.rows.map((r) => r.id); - const m1 = input(p, q); - expect((await store.moveIdentities(m1)).kind).toBe("moved"); - expect((await store.moveIdentities(reverse(m1.moveId, q, p, ids))).kind).toBe("moved"); - expect((await store.moveIdentities(input(p, q, { proofSessions: [] }))).kind).toBe("moved"); - expect((await store.moveIdentities(reverse(m1.moveId, q, p, ids))).kind, "reversed once").toBe("not_reversible"); - expect(await held(p)).toEqual([]); - } - // (d) the logins are still on the forward's destination but the reversal targets another account - { - const { p, q } = await fresh(); - const ids = p.rows.map((r) => r.id); - const m1 = input(p, q); - expect((await store.moveIdentities(m1)).kind).toBe("moved"); - const elsewhere = await side(["patreon"]); - expect((await store.moveIdentities(reverse(m1.moveId, q, elsewhere, ids))).kind, "to is not the forward's source").toBe("not_reversible"); - expect(await held(elsewhere)).toHaveLength(1); - } - // (b) the logins moved on from the destination: not held, so not_reversible (not identity_not_found) - // (c) the reversal's source is not the forward's destination, or its target is not the forward's source - { - const { p, q, t } = await fresh(); - const ids = p.rows.map((r) => r.id); - const m1 = input(p, q); - expect((await store.moveIdentities(m1)).kind).toBe("moved"); - expect((await store.moveIdentities(input(q, t, { identityIds: ids, covers: ids, proofSessions: [] }))).kind).toBe("moved"); - expect((await store.moveIdentities(reverse(m1.moveId, q, p, ids))).kind, "ids no longer held").toBe("not_reversible"); - expect((await store.moveIdentities(reverse(m1.moveId, t, p, ids))).kind, "from is not the forward's destination").toBe("not_reversible"); - const u = await side(["google"]); - expect((await store.moveIdentities(reverse(m1.moveId, t, u, ids))).kind, "to is not the forward's source").toBe("not_reversible"); - expect(await held(t)).toEqual([...ids, ...t.rows.map((r) => r.id)].sort()); - } -} - // Against a real Postgres, through the startup path itself: createStore, with // and without applying the schema. HEIMDALL_TEST_PG_ADMIN_URL names a role // that may create databases and roles. Each case clones a template database @@ -971,138 +716,6 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD } }); - it("startup refuses a role that lacks DELETE on linked_identities", async () => { - expect(STORE_TABLE_PRIVILEGES.linked_identities).toContain("DELETE"); - const { name, owner } = await appliedDatabase(); - await grant(owner, { ...STORE_TABLE_PRIVILEGES, linked_identities: ["SELECT", "INSERT", "UPDATE"] }); - expect(await start(urlFor(name, role, rolePassword), false)).toBe(refusal("SCHEMA_PRIVILEGES")); - }); - - it("startup refuses a role that lacks INSERT or SELECT on identity_moves", async () => { - expect(STORE_TABLE_PRIVILEGES.identity_moves).toEqual(["SELECT", "INSERT"]); - for (const [kept, dropped] of [[["SELECT"], "INSERT"], [["INSERT"], "SELECT"]] as const) { - const { name, owner } = await appliedDatabase(); - await grant(owner, { ...STORE_TABLE_PRIVILEGES, identity_moves: kept }); - expect(await start(urlFor(name, role, rolePassword), false), `without ${dropped}`).toBe(refusal("SCHEMA_PRIVILEGES")); - } - }); - - it("on real Postgres: the move contract holds", async () => { - const { owner } = await appliedDatabase(); - await exerciseMoveContract(new PostgresStore(owner)); - }); - - describe("concurrent moves", () => { - const at = "2026-11-14T12:00:00.000Z"; - async function pair(store: PostgresStore) { - const make = async (provider: "discord" | "patreon") => { - const account = await store.createAccount({ createdAt: at, lastSeenAt: at }); - await store.upsertLinkedIdentity({ accountId: account.id, provider, providerUserId: `${provider}-${randomUUID()}`, scopes: [], profileJson: {}, createdAt: at, updatedAt: at }); - const sessionId = randomUUID(); - await store.createSession({ id: sessionId, accountId: account.id, appSlug: "bifrost", createdAt: at, lastSeenAt: at, expiresAt: "2999-01-01T00:00:00.000Z", accessRevision: 1, claimsJson: {} }); - return { id: account.id, proof: { appSlug: "bifrost" as const, sessionId, accountId: account.id, accessRevision: 1 } }; - }; - return { x: await make("discord"), y: await make("patreon") }; - } - const request = (from: { id: string; proof: object }, to: { id: string; proof: object }, moveId: string) => ({ - moveId, - appSlug: "bifrost" as const, - fromAccountId: from.id, - toAccountId: to.id, - identityIds: "all" as const, - covers: "account" as const, - proofSessions: [from.proof, to.proof] as never, - proof: { from: [], to: null }, - at, - }); - - it("opposite moves A->B and B->A over two pools leave one applied and never deadlock, ten rounds", async () => { - const { name, owner } = await appliedDatabase(); - const storeA = new PostgresStore(owner); - const other = fixturePool(urlFor(name)); - cleanup.push(async () => { - await other.end(); - }); - const storeB = new PostgresStore(other); - for (let round = 0; round < 10; round += 1) { - const { x, y } = await pair(storeA); - const results = await Promise.all([ - storeA.moveIdentities(request(x, y, `move-${randomUUID()}`)), - storeB.moveIdentities(request(y, x, `move-${randomUUID()}`)), - ]); - const kinds = results.map((r) => r.kind).sort(); - expect(kinds[0], `round ${round}: ${kinds}`).toBe("moved"); - expect(["already_moved", "proof_lapsed"], `round ${round}: ${kinds}`).toContain(kinds[1]); - const held = (await storeA.listStoredLinkedIdentitiesForAccount(x.id)).length + (await storeA.listStoredLinkedIdentitiesForAccount(y.id)).length; - expect(held, "no identity is lost or duplicated").toBe(2); - } - }); - - it("one moveId over two different pairs at once: one moved, the other move_id_conflict, never a receipt for a move it did not make", async () => { - const { name, owner } = await appliedDatabase(); - const storeA = new PostgresStore(owner); - const other = fixturePool(urlFor(name)); - cleanup.push(async () => { - await other.end(); - }); - const storeB = new PostgresStore(other); - for (let round = 0; round < 6; round += 1) { - const one = await pair(storeA); - const two = await pair(storeA); - const id = `move-${randomUUID()}`; - const results = await Promise.all([storeA.moveIdentities(request(one.x, one.y, id)), storeB.moveIdentities(request(two.x, two.y, id))]); - expect(results.map((r) => r.kind).sort(), `round ${round}`).toEqual(["move_id_conflict", "moved"]); - const winner = (await storeA.findIdentityMove(id))!; - const moved = results.find((r) => r.kind === "moved") as { move: { fromAccountId: string } }; - expect(winner.fromAccountId).toBe(moved.move.fromAccountId); - } - }); - - it("two concurrent identical moveIds: one moved, one replayed", async () => { - const { name, owner } = await appliedDatabase(); - const storeA = new PostgresStore(owner); - const other = fixturePool(urlFor(name)); - cleanup.push(async () => { - await other.end(); - }); - const storeB = new PostgresStore(other); - for (let round = 0; round < 5; round += 1) { - const { x, y } = await pair(storeA); - const body = request(x, y, `move-${randomUUID()}`); - const results = await Promise.all([storeA.moveIdentities(body), storeB.moveIdentities(body)]); - expect(results.map((r) => r.kind).sort(), `round ${round}`).toEqual(["moved", "replayed"]); - } - }); - }); - - it("on real Postgres: an upsert never moves an identity, and concurrent unlinks of the last two leave one", async () => { - const { name, owner } = await appliedDatabase(); - const clientA = new PostgresStore(owner); - const at = "2026-11-13T12:00:00.000Z"; - const a = await clientA.createAccount({ createdAt: at, lastSeenAt: at }); - const b = await clientA.createAccount({ createdAt: at, lastSeenAt: at }); - const base = { provider: "discord" as const, scopes: [], profileJson: {}, createdAt: at, updatedAt: at }; - const held = await clientA.upsertLinkedIdentity({ ...base, accountId: a.id, providerUserId: "u1", username: "original" }); - await expect(clientA.upsertLinkedIdentity({ ...base, accountId: b.id, providerUserId: "u1", username: "thief" })).rejects.toBeInstanceOf(IdentityHeldElsewhereError); - expect(await clientA.findStoredLinkedIdentity("discord", "u1")).toEqual(held); - - await clientA.upsertLinkedIdentity({ ...base, accountId: a.id, providerUserId: "u2" }); - // Two separate pools, as two Heimdall processes would be, race for the last two. - const other = fixturePool(urlFor(name)); - cleanup.push(async () => { - await other.end(); - }); - const storeB = new PostgresStore(other); - for (let round = 0; round < 10; round += 1) { - const [first, second] = await clientA.listStoredLinkedIdentitiesForAccount(a.id); - expect(first && second, `round ${round} starts with two`).toBeTruthy(); - const results = await Promise.all([clientA.unlinkLinkedIdentity(a.id, first!.id), storeB.unlinkLinkedIdentity(a.id, second!.id)]); - expect(results.map((r) => r.kind).sort(), `round ${round}`).toEqual(["last_identity", "unlinked"]); - expect(await clientA.listStoredLinkedIdentitiesForAccount(a.id)).toHaveLength(1); - await clientA.upsertLinkedIdentity({ ...base, accountId: a.id, providerUserId: `u-next-${round}` }); - } - }); - describe("oauth_state_uses retention", () => { const expMs = Date.parse("2026-04-26T12:10:00.000Z"); const boundary = expMs + OAUTH_STATE_SKEW_MS + OAUTH_STATE_PRUNE_MARGIN_MS; @@ -1151,20 +764,6 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD expect(found.rowCount).toBe(1); }); - it("the step_up_assert nonce claim is single-use under the store's own role, and independent of the other phases", async () => { - const { name, owner } = await appliedDatabase(); - await grant(owner, STORE_TABLE_PRIVILEGES); - const pool = fixturePool(urlFor(name, role, rolePassword)); - cleanup.push(async () => { - await pool.end(); - }); - const store = new PostgresStore(pool); - const claim = { ...use("digest", boundary, boundary + 600_000), phase: "step_up_assert" as const, appSlug: "bifrost" }; - expect(await store.claimOAuthStateUse(claim)).toBe(true); - expect(await store.claimOAuthStateUse(claim)).toBe(false); - expect(await store.claimOAuthStateUse({ ...claim, phase: "callback" })).toBe(true); - }); - it("a role without DELETE still claims, and leaves the old records", async () => { const { name, owner } = await appliedDatabase(); await grant(owner, { ...STORE_TABLE_PRIVILEGES, oauth_state_uses: ["SELECT", "INSERT"] }); @@ -1192,7 +791,6 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD const appliedByIndex = { auth_completions_attempt_unconsumed_unique_idx: "auth_completions", consent_receipts_revokes_unique_idx: "consent_receipts", - identity_moves_reverses_unique_idx: "identity_moves", }; const partialKeys = REQUIRED_KEYS.flatMap((key, index) => (key.predicate === "" ? [] : [{ key, index }])); expect(partialKeys.map(({ key }) => key.table).sort()).toEqual(Object.values(appliedByIndex).sort());