From 70fd6396f45eddcffb3285c04e19ab9e72df2576 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Thu, 5 Nov 2026 23:30:23 +0000 Subject: [PATCH 01/63] Exercise the pending-link and findAuthCompletion store methods in the live-Postgres privilege tests The live suite asserts that exerciseStore calls every PostgresStore method and that dropping any one table privilege makes it fail with 42501. createPendingLink, consumePendingLink and findAuthCompletion landed without a call there, so the coverage assertion failed, and with no operation touching pending_links the privilege test saw no error when SELECT on it was revoked. Both failures were invisible because the live files skip without HEIMDALL_TEST_PG_ADMIN_URL. Co-Authored-By: Claude Sonnet 5.5 --- tests/store.test.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/store.test.ts b/tests/store.test.ts index 11614c4..f17a834 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -398,6 +398,19 @@ async function exerciseStore(store: PostgresStore): Promise> { await s.consumeAuthCompletion("ghostlight", byCode.code, now); await s.createAuthCompletion({ ...completion, attemptId: attempt.handle }); await s.consumeAuthCompletionByAttempt("ghostlight", attempt.handle, now); + const found = await s.createAuthCompletion(completion); + await s.findAuthCompletion("ghostlight", found.code); + const pending = await s.createPendingLink({ + appSlug: "ghostlight", + accountId: account.id, + provider: "discord", + providerUserId: "u2", + identity: { ...identity, providerUserId: "u2" }, + returnTo: "https://x.test/", + createdAt: now, + expiresAt: later, + }); + await s.consumePendingLink("ghostlight", pending.id, account.id, now); const snapshot = { accountId: account.id, provider: "discord" as const, scope: "ghostlight:probe", evaluatedAt: now, isAllowed: true, reasonCode: "ok", rawSummaryJson: {} }; await s.upsertEntitlementSnapshot(snapshot); await s.upsertEntitlementSnapshot({ ...snapshot, isAllowed: false }); From 575be9cf49d992dc23e6fc6111c3acc314f50acb Mon Sep 17 00:00:00 2001 From: Heimdall Date: Thu, 5 Nov 2026 23:30:57 +0000 Subject: [PATCH 02/63] Add scripts/test-live-pg.sh: run the suite against a throwaway Postgres Co-Authored-By: Claude Sonnet 5.5 --- scripts/test-live-pg.sh | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100755 scripts/test-live-pg.sh diff --git a/scripts/test-live-pg.sh b/scripts/test-live-pg.sh new file mode 100755 index 0000000..a25c3e9 --- /dev/null +++ b/scripts/test-live-pg.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Runs the whole vitest suite with the live-Postgres files enabled, against a +# throwaway local cluster that this script starts and removes. Needs the +# Postgres server binaries (initdb, pg_ctl) on PATH or in PG_BIN. +# SOUL_PG_URL's test drops and recreates schema public, so it only ever sees +# this disposable cluster. +set -euo pipefail +export PATH="${PG_BIN:-/usr/lib/postgresql/16/bin}:$PATH" +dir="$(mktemp -d)" +port="${PG_PORT:-54329}" +trap 'pg_ctl -D "$dir" -m immediate stop >/dev/null 2>&1 || true; rm -rf "$dir"' EXIT +initdb -D "$dir" -U pgadmin --auth=trust >/dev/null +pg_ctl -D "$dir" -o "-p $port -k $dir -c listen_addresses=127.0.0.1" -l "$dir/log" -w start >/dev/null +url="postgres://pgadmin@127.0.0.1:$port/postgres" +HEIMDALL_TEST_PG_ADMIN_URL="$url" SOUL_PG_URL="$url" npx vitest run --config vitest.config.ts "$@" From a7cdf0fea7df3ba443b506456bbcc61bc1cbaeab Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 6 Nov 2026 12:17:14 +0000 Subject: [PATCH 03/63] Draft: Joystick consent flow design and skipped test sketch Documents what a viewer sees today on the Joystick path and what consent is missing, then drafts a visible ask, typed refusal and auditable receipt. Design only; the test file is a skipped sketch and was not run. Co-Authored-By: Claude Sonnet 5.5 --- docs/joystick-consent-flow.md | 123 +++++++++++++++++++++++++++++++++ tests/joystick-consent.test.ts | 62 +++++++++++++++++ 2 files changed, 185 insertions(+) create mode 100644 docs/joystick-consent-flow.md create mode 100644 tests/joystick-consent.test.ts diff --git a/docs/joystick-consent-flow.md b/docs/joystick-consent-flow.md new file mode 100644 index 0000000..498c8e4 --- /dev/null +++ b/docs/joystick-consent-flow.md @@ -0,0 +1,123 @@ +# Joystick sign-in and consent: what exists, what is missing, a draft flow + +Status: DRAFT design, no code. Source-grounded at `fefd2dd` (main). Follow-up +`heimdall-body:follow_up:chat-s3124-3129`. Not for merge until a Heimdall +steward rules on the open questions below. + +## 1. What a viewer sees today + +**Joystick viewer sign-in does not exist.** `streampixelsProfile` +(`src/app-profiles.ts:109-117`) lists Joystick only in +`managedConnectionProviders`. `admitsProviderForMode` (`:243`) admits `sign_in` +and `link` only for `identityProviders`, so +`POST /v1/oauth/joystick/start` with `mode: sign_in` returns +`400 provider_not_supported_for_app` as JSON before any redirect +(`startOAuthFlow`, `src/app.ts:598-603`). The viewer sees whatever the app does +with a failed start; Heimdall shows them nothing. The architecture doc records +this as deliberate until the public bot is registered +(`docs/architecture.md:461`, `joystick:follow_up:joystick-viewer-signin-public-bot`). + +**The only live Joystick path is a creator `connect`.** Walking it as the +person in the browser: + +1. The app backend starts the flow (authenticated by app secret, `connection` + `{kind: creator, targetId}`). The person's browser is sent to + `/v1/oauth/joystick/launch?state=...`. +2. `launch` (`src/app.ts:1130-1194`) claims the state, sets the binding cookie + and answers `302` straight to `joystick.tv/api/oauth/authorize`. **Heimdall + renders no page of its own.** Nothing says who is asking, for what, or what + will be kept. +3. The only ask the person sees is Joystick's own screen, listing the scopes in + `providerCatalog.joystick.defaultScopes` (`src/providers.ts:162`): + `identity:read stream:read chat:read followers:read subscribers:read`. + Joystick words that screen, not us. +4. The callback (`:1196`) exchanges the code, stores the credential encrypted + (rotating refresh token, managed custody), and returns the generic handoff + page (`src/browser-handoff.ts`): title "Authentication Complete", body "You + can return to the app now." It does not name the app, the provider, the + scopes granted, or that a long-lived refresh token is now held by Heimdall. +5. Refusal: if the person clicks Deny at Joystick, the callback gets + `error=access_denied`, and the page says "Authentication Failed ... Return to + the app to continue." The provider's own text is relayed only in + `errorDescription` in the fallback URL fragment / postMessage payload, not + shown on the page. Refusing *at Heimdall's step* is impossible: there is no + Heimdall step. +6. After: the audit rows `oauth_callback_succeeded`, `auth_completion_created`, + `managed_credential_revoked` etc. (`createAuditEvent` call sites, e.g. + `app.ts:1582`) are written for operators. There is **no route a viewer can + call to read them**, and no route a viewer can call to revoke a credential. + Revocation exists only inside the app backend plane (`managed-credential.ts:172`). + +## 2. What consent is missing + +| Gap | Today | Why it matters | +| --- | --- | --- | +| Visible ask | None from Heimdall; provider screen only | The person cannot tell Heimdall custody (refresh token kept, rotated, used for stream/chat/follower reads) from a one-off login. | +| Who is asking | Not shown | Two parties act: the app (StreamPixels) and Heimdall as custodian. Neither is named. | +| Scope truth | Provider screen lists scopes; Heimdall's `requestedScopes` / `defaultScopes` are not shown or compared with what was granted | Granted scopes can differ from requested; the stored `scopes` (`app.ts:1406`) are never shown. | +| Typed refusal | A deny is an untyped `provider_error` | The app and the audit log cannot tell "viewer said no" from "provider broke". | +| Receipt | Operator audit rows only | The viewer cannot audit what was agreed, when, or revoke it. | +| Viewer vs creator | The `connect` binding proves a binding exists, not that the browser's owner is the creator (`joystick:follow_up:connect-start-needs-app-auth`) | Consent from the wrong person is not consent. | + +## 3. Draft consent flow + +Applies to any Joystick completion (creator connect now; viewer sign-in when +the public bot lands) and, if ruled, to every provider whose state carries +`managed_credential`. + +### 3.1 The ask (visible, before the redirect) + +`GET /v1/oauth/:provider/launch` stops answering `302`. It renders a Heimdall +page, **after** the state is verified but **before** the use is claimed, with: + +- the app by display name and return origin; +- the provider and the exact scope list that will be requested; +- what Heimdall keeps (a refresh token, encrypted, rotating) versus what the + app receives (no token; a claim) and for how long; +- two forms, both POST, CSRF-bound by the existing binding cookie: + **Continue to Joystick** and **No, return to the app**; +- a link to the receipt of any earlier consent for this account and app. + +Only Continue claims the launch use and answers `302`. The page is plain +server-rendered HTML with no script, matching the handoff page's escape rule. + +### 3.2 Typed refusal + +**No** (and a provider `access_denied` on return) produces a distinct result +`consent_refused` with `{provider, app, mode, by: "viewer" | "provider"}`: +delivered to the app by the same handoff channel as any result, written as an +audit event `consent_refused`, no credential stored, state consumed. A provider +failure stays `provider_error`. The app is told not to ask again in the same +session; whether it may ask later is the app's rule, not Heimdall's. + +### 3.3 Receipt + +On a granted completion Heimdall writes one `consent_receipt` row: receipt id +(random, non-guessable), account (or creator target), app, provider, scopes +asked, scopes granted, what Heimdall retains, `grantedAt`, `consentPageDigest` +(hash of the exact text shown, so a later wording change is visible), and a +`revokedAt` slot. The handoff page shows the receipt id and a "View receipt" link. + +`GET /v1/receipts/:id` (viewer-bound by the same cookie or by the account's +access token) shows the row and offers **Revoke**, which calls the existing +managed-credential revocation and stamps `revokedAt`. Revoke is itself receipted. +Receipts are append-only; a revocation is a second row, not an edit. + +## 4. Open questions for the steward + +1. Who gets the ask: every provider, or only `managed_credential` ones? (Recommend: only managed custody, where Heimdall holds something beyond a login.) +2. Where does the receipt live: Heimdall store as a new document, or the existing audit table with a new `eventType`? (Recommend: new typed document; the audit table is operator-shaped and has no viewer read path.) +3. Viewer identity for the receipt page when the viewer has no Heimdall session yet (a first-time creator connect). Binding cookie only, or require sign-in first? +4. Does `consent_refused` need to reach a backend callback app, or only the browser handoff? +5. Wording ownership: the page text is legal-adjacent (CultCoin legal research is a sibling thread); who signs the copy? + +## 5. Out of scope here + +Enabling Joystick in `identityProviders`; fixing `connect-start-needs-app-auth`; +Postgres schema/migration for the receipt; any deploy. Each needs its own cut. + +## 6. Test sketch + +`tests/joystick-consent.test.ts` holds the behaviours above as skipped tests +(they cannot pass until the cut is built). Unrun: the author's workspace could +not install dependencies, so treat the file as a sketch to be typechecked. diff --git a/tests/joystick-consent.test.ts b/tests/joystick-consent.test.ts new file mode 100644 index 0000000..6881f8f --- /dev/null +++ b/tests/joystick-consent.test.ts @@ -0,0 +1,62 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { type FastifyInstance } from "fastify"; +import { buildApp } from "../src/app.js"; +import { createTestConfig } from "./oauth-flow.js"; + +// SKETCH for docs/joystick-consent-flow.md. Skipped: every test here names a +// behaviour the consent cut must build. Remove `.skip` as each one lands. + +const apps: FastifyInstance[] = []; +afterEach(async () => { + while (apps.length) await apps.pop()?.close(); +}); + +async function creatorConnectStart(app: FastifyInstance) { + const response = await app.inject({ + method: "POST", + url: "/v1/oauth/joystick/start", + headers: { "x-heimdall-app-secret": "streampixels-secret" }, + payload: { + appSlug: "streampixels", + mode: "connect", + connection: { kind: "creator", targetId: "creator-1" }, + returnTo: "https://streampixels.gamecult.org/settings", + handoff: { kind: "browser_completion" }, + }, + }); + expect(response.statusCode).toBe(201); + const url = new URL(response.json().authorizationUrl as string); + return `${url.pathname}${url.search}`; +} + +describe.skip("Joystick consent flow (draft)", () => { + it("launch shows a Heimdall ask naming app, provider and scopes, and does not redirect", async () => { + const app = await buildApp({ config: createTestConfig() }); + apps.push(app); + const launch = await app.inject({ method: "GET", url: await creatorConnectStart(app), headers: { accept: "text/html" } }); + expect(launch.statusCode).toBe(200); + expect(launch.headers.location).toBeUndefined(); + for (const needle of ["StreamPixels", "Joystick", "identity:read", "subscribers:read", "refresh token"]) { + expect(launch.body).toContain(needle); + } + }); + + it("a viewer who declines yields consent_refused by viewer, stores no credential, and consumes the state", async () => { + // POST the decline form from the launch page with the binding cookie; + // expect result {error: "consent_refused", by: "viewer"}, an audit event + // "consent_refused", no managed credential row, and a second launch refused. + expect.fail("not built"); + }); + + it("a provider access_denied is consent_refused by provider, distinct from provider_error", async () => { + expect.fail("not built"); + }); + + it("a granted completion writes one receipt with asked and granted scopes and the page digest", async () => { + expect.fail("not built"); + }); + + it("the receipt page is readable only by the browser or account that consented, and revoke stamps revokedAt without editing the grant row", async () => { + expect.fail("not built"); + }); +}); From e8edd88efc817a27ca3428c74eaadf4c13eae2dd Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 6 Nov 2026 13:30:45 +0000 Subject: [PATCH 04/63] Specify answer collector record and consent Co-Authored-By: Claude Sonnet 5.5 --- docs/answer-collector-consent.md | 118 +++++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 docs/answer-collector-consent.md diff --git a/docs/answer-collector-consent.md b/docs/answer-collector-consent.md new file mode 100644 index 0000000..f02be6a --- /dev/null +++ b/docs/answer-collector-consent.md @@ -0,0 +1,118 @@ +# Answer Collector: Record and Consent + +Status: specification. Nothing here is implemented. It fixes what an answer +record is and what a respondent has agreed to, so that a collector, a tally and +a training export can be built against one definition. + +Scope: free-text and choice answers that members give to a sample put to them +by an experiment. Not identity proof (see `architecture.md`). + +## Record + +One record per answer. Fields: + +| field | rule | +|---|---| +| `sample_id` | names the thing answered about, with a version component (`@`). A changed sample is a new version. | +| `experiment_id` | the experiment that asked. | +| `member_id` | Heimdall member id of the respondent. Never a Matrix id, never a display name. | +| `scope` | `show` \| `study` \| `train`. Default `show`. | +| `text` | the answer as given. | +| `revoked` | boolean, default false. One-way: a revoked record is never un-revoked; a new answer is a new record. | +| `received_at` | collector clock, UTC. | + +Key: `(experiment_id, sample_id, member_id)`. A member's later answer to the +same key replaces the earlier one (latest `received_at` wins); the earlier text +is not retained. + +## Versions + +Answers never tally across `sample_id` versions. A tally is computed for one +full `sample_id` including version; there is no "all versions" aggregate and no +API that takes a sample without a version. A version bump starts an empty tally. + +## Scope + +Scope is the widest use the respondent allowed. Each use reads exactly one +level: + +- `show`: may be displayed back inside the experiment (to the respondent, and + in aggregate to participants). Nothing else. +- `study`: `show`, plus analysis by the experiment's researchers. May be quoted + in findings only unattributed. +- `train`: `study`, plus use as training or evaluation data for models. + +Rule: nothing is training data unless `scope = train`. A missing, unparseable +or unknown scope is `show`, never wider. Scope can be narrowed by a new answer +or revocation; widening is a new answer by the respondent, never an inference. + +## Identity: count once, reward without exposure + +The Matrix sender is mapped to a Heimdall member id by Heimdall's linked +identity, at collection time. The collector stores `member_id` only; the Matrix +sender is discarded after mapping. A sender with no linked member is dropped, +not stored under a placeholder. + +- Count once: the key above makes one member one answer per sample version, + however many Matrix accounts or bridges they use. +- Reward without exposure: a reward is issued against `member_id` by the + rewarding service. Researchers and displays see counts and text under their + scope, never `member_id`. The mapping from a record to a person is available + to the reward path only. + +## Eureka's shape (Matrix) + +- One room per experiment. The room is `experiment_id`. +- The sample is posted as a message; an answer is a thread reply to it whose + body starts `scope: ` on its first line, the answer text following. +- The reply event is the receipt: its event id and timestamp are the proof the + answer was received, and `received_at` comes from it. +- Redaction is revoke: redacting the reply event sets `revoked`. +- The collector is on demand (it reads the room when run, it is not a standing + listener). It drops: + - redacted replies; + - replies with no `scope:` line (consent is explicit in Matrix; the `show` + default applies to records created elsewhere, not to silence); + - replies from unlinked senders; + - replies to an old sample version when the tally is for a newer one. +- Records wider than `show` (`study`, `train`) are kept apart from `show` + records: separate store or partition, so a read for one level cannot + accidentally return another. + +## What Matrix cannot guarantee + +- **Receipt outliving a deleted reply.** Redaction removes content, and + homeserver retention varies. If the collector holds a receipt for a reply that + later disappears, it keeps a tombstone: event id, `sample_id`, `received_at`, + and a hash of `text` (hash only, no text), so the count and the revoke are + provable without the content. The record is marked `revoked`; `text` is + erased. +- **Edits.** An edit is a new event, not the receipt. Only the original event + counts; edits are ignored, so what was consented to is what was received. To + change an answer, redact and reply again. +- **Bridge spoofing.** A bridge can post as any ghost user. Only senders whose + Matrix id resolves through Heimdall's linked identity to a member count; + bridged ghost ids are not linked identities. A bridge cannot raise scope, as + scope comes only from the reply's own `scope:` line. +- **Discord material.** Nothing that originates from Discord is collected, + even through a bridge, at any scope: Discord forbids training on its + content. Bridged events are dropped by origin, not by judging text. + +## What the respondent sees + +Posted with the sample, in the room: + +- the three scopes in one line each, as above; +- that no `scope:` line means the answer is not collected; +- how to revoke. + +After answering, the respondent sees their receipt: the thread reply itself, +plus the collector's acknowledgement that names the scope it recorded. If it +recorded narrower than they asked, it says so. + +## How to revoke + +Redact your reply. That is all. The next collection run marks the record +`revoked`, erases `text`, and excludes it from every tally and export. Anything +already exported at `train` before the run cannot be recalled by Matrix; the +experiment's page states the export cadence so the window is known. From d836f29e3a7b8e8b2b519a09ed6c9aecdb5d0dfb Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 6 Nov 2026 14:31:45 +0000 Subject: [PATCH 05/63] Align answer-collector consent with #swarm rulings of 2026-11-06 Room notice declares scope (train included); first reply accepts a notice version; terms version for newcomers only; training needs an acceptance at answer time and a recorded scope; redaction is exit, past use not undone; salted hash-only tombstone; no reward sound on consent controls; personal details out of scope; typed field tables for the CultCache records. Co-Authored-By: Claude Sonnet 5.5 --- docs/answer-collector-consent.md | 158 +++++++++++++++++++++---------- 1 file changed, 106 insertions(+), 52 deletions(-) diff --git a/docs/answer-collector-consent.md b/docs/answer-collector-consent.md index f02be6a..129f279 100644 --- a/docs/answer-collector-consent.md +++ b/docs/answer-collector-consent.md @@ -2,49 +2,103 @@ Status: specification. Nothing here is implemented. It fixes what an answer record is and what a respondent has agreed to, so that a collector, a tally and -a training export can be built against one definition. +a training export can be built against one definition. Field names and types +below are the contract for the typed CultCache records. Scope: free-text and choice answers that members give to a sample put to them -by an experiment. Not identity proof (see `architecture.md`). +by an experiment. Not identity proof (see `architecture.md`). Personal details +(names, contact data, account identifiers, anything that identifies a person) are +out of scope: the collector does not ask for them and a sample must not solicit +them. The only identifier it keeps is `member_id`, and that stays on the reward +path. -## Record +## Notice + +Consent is declared once per room, not per reply. Each experiment room carries +one notice line, pinned with the sample, that names the scope the room's answers +may be used for and the way out. A notice has a `notice_version`; any change to +its wording or scope is a new version. + +| scope | what the notice allows | +|---|---| +| `show` | display back inside the experiment (to the respondent, and in aggregate to participants). Nothing else. | +| `study` | `show`, plus analysis by the experiment's researchers. Quoted in findings only unattributed. | +| `train` | `study`, plus use as training or evaluation data for models. | + +`train` is a declared scope: it is used only when the notice for that room says +`train` in terms. It is never inferred, never a default, and never raised by a +reply. + +The first reply a member posts in the room is their acceptance of the notice +version then pinned. No separate click, command or form. A later notice version +needs a new acceptance: the member's first reply under it. + +### Notice acceptance record + +| field | type | rule | +|---|---|---| +| `member_id` | Heimdall member id | the accepting member. | +| `experiment_id` | string | the room. | +| `notice_version` | integer | the version pinned when the reply was received. | +| `scope` | `show` \| `study` \| `train` | the scope that version declared. | +| `accepted_at` | UTC timestamp | `origin_server_ts` of the first reply. | +| `event_id` | Matrix event id | that reply, as proof. | + +Key: `(experiment_id, member_id, notice_version)`. Written once, never updated. + +## Terms (newcomers only) + +Joining Heimdall is gated by terms. Acceptance is the terms version recorded by +the Matrix `m.login.terms` stage at registration: member field `terms_version` +(string) and `terms_accepted_at` (UTC timestamp). This applies to newcomers +only. Members who joined before the terms stage existed, and Minds, are not +re-asked and have no `terms_version`; the collector does not read it and does not +gate on it. The notice above is the only consent the collector itself checks. + +## Answer record One record per answer. Fields: -| field | rule | -|---|---| -| `sample_id` | names the thing answered about, with a version component (`@`). A changed sample is a new version. | -| `experiment_id` | the experiment that asked. | -| `member_id` | Heimdall member id of the respondent. Never a Matrix id, never a display name. | -| `scope` | `show` \| `study` \| `train`. Default `show`. | -| `text` | the answer as given. | -| `revoked` | boolean, default false. One-way: a revoked record is never un-revoked; a new answer is a new record. | -| `received_at` | collector clock, UTC. | +| field | type | rule | +|---|---|---| +| `sample_id` | string `@` | names the thing answered about; `` is a positive integer. A changed sample is a new version. | +| `experiment_id` | string | the experiment that asked. | +| `member_id` | Heimdall member id | the respondent. Never a Matrix id, never a display name. | +| `notice_version` | integer | the notice version in force when the answer was received; matches an acceptance record by the key above. | +| `scope` | `show` \| `study` \| `train` | copied from that notice version at answer time. Never edited afterwards. | +| `text` | string, or absent | the answer as given. Absent once exited. | +| `exited` | boolean, default false | one-way: set by redaction, never cleared. A new answer is a new record. | +| `received_at` | UTC timestamp | `origin_server_ts` of the reply. | +| `event_id` | Matrix event id | the reply; the receipt. | Key: `(experiment_id, sample_id, member_id)`. A member's later answer to the same key replaces the earlier one (latest `received_at` wins); the earlier text is not retained. +A record whose `notice_version` or `scope` is missing, unparseable or has no +matching acceptance record is not collected. It is excluded from every use, and +from training in particular. + ## Versions Answers never tally across `sample_id` versions. A tally is computed for one full `sample_id` including version; there is no "all versions" aggregate and no API that takes a sample without a version. A version bump starts an empty tally. +Replies to an old version are dropped when the tally is for a newer one. -## Scope +## Training rule -Scope is the widest use the respondent allowed. Each use reads exactly one -level: +A record is training or evaluation data only if all hold: -- `show`: may be displayed back inside the experiment (to the respondent, and - in aggregate to participants). Nothing else. -- `study`: `show`, plus analysis by the experiment's researchers. May be quoted - in findings only unattributed. -- `train`: `study`, plus use as training or evaluation data for models. +1. `scope = train`, copied from a notice version that declared `train`; +2. an acceptance record exists for `(experiment_id, member_id, notice_version)` + with `accepted_at <= received_at`, i.e. the author had accepted that notice + version when they answered; +3. `exited = false` at export time. -Rule: nothing is training data unless `scope = train`. A missing, unparseable -or unknown scope is `show`, never wider. Scope can be narrowed by a new answer -or revocation; widening is a new answer by the respondent, never an inference. +No recorded scope, or no recorded acceptance, means excluded. Records wider than +`show` are kept apart from `show` records: separate store or partition, so a read +for one level cannot return another. ## Identity: count once, reward without exposure @@ -63,56 +117,56 @@ not stored under a placeholder. ## Eureka's shape (Matrix) - One room per experiment. The room is `experiment_id`. -- The sample is posted as a message; an answer is a thread reply to it whose - body starts `scope: ` on its first line, the answer text following. +- The sample is posted as a message, with the notice pinned beside it. An answer + is a thread reply to the sample, the answer text being the body. There is no + per-reply scope syntax. - The reply event is the receipt: its event id and timestamp are the proof the answer was received, and `received_at` comes from it. -- Redaction is revoke: redacting the reply event sets `revoked`. +- Redaction is exit (see below): redacting the reply event sets `exited`. - The collector is on demand (it reads the room when run, it is not a standing listener). It drops: - - redacted replies; - - replies with no `scope:` line (consent is explicit in Matrix; the `show` - default applies to records created elsewhere, not to silence); + - redacted replies (recorded as exited); - replies from unlinked senders; - replies to an old sample version when the tally is for a newer one. -- Records wider than `show` (`study`, `train`) are kept apart from `show` - records: separate store or partition, so a read for one level cannot - accidentally return another. ## What Matrix cannot guarantee - **Receipt outliving a deleted reply.** Redaction removes content, and homeserver retention varies. If the collector holds a receipt for a reply that - later disappears, it keeps a tombstone: event id, `sample_id`, `received_at`, - and a hash of `text` (hash only, no text), so the count and the revoke are - provable without the content. The record is marked `revoked`; `text` is - erased. + later disappears, it keeps a tombstone: `event_id`, `sample_id`, `received_at`, + and a salted hash of `text`. Hash only, never text, and no `member_id` + beyond what the record's key already holds. The count and the exit are + provable without the content. The record is marked `exited`; `text` is erased. - **Edits.** An edit is a new event, not the receipt. Only the original event - counts; edits are ignored, so what was consented to is what was received. To + counts; edits are ignored, so what was accepted is what was received. To change an answer, redact and reply again. - **Bridge spoofing.** A bridge can post as any ghost user. Only senders whose Matrix id resolves through Heimdall's linked identity to a member count; - bridged ghost ids are not linked identities. A bridge cannot raise scope, as - scope comes only from the reply's own `scope:` line. -- **Discord material.** Nothing that originates from Discord is collected, - even through a bridge, at any scope: Discord forbids training on its - content. Bridged events are dropped by origin, not by judging text. + bridged ghost ids are not linked identities. A bridge cannot raise scope: scope + comes only from the pinned notice version. +- **Bridged origin.** Events that arrive through a bridge are dropped by origin, + not by judging their text. ## What the respondent sees Posted with the sample, in the room: -- the three scopes in one line each, as above; -- that no `scope:` line means the answer is not collected; -- how to revoke. +- the notice: its scope in one line, that the first reply accepts it, and how to + exit; +- the notice version. After answering, the respondent sees their receipt: the thread reply itself, -plus the collector's acknowledgement that names the scope it recorded. If it -recorded narrower than they asked, it says so. +plus the collector's acknowledgement that names the notice version and scope it +recorded. -## How to revoke +The consent and vote controls make no reward sound, animation or other +reinforcement. A reward is issued later, by the rewarding service, never as +feedback to the act of consenting or voting. -Redact your reply. That is all. The next collection run marks the record -`revoked`, erases `text`, and excludes it from every tally and export. Anything -already exported at `train` before the run cannot be recalled by Matrix; the -experiment's page states the export cadence so the window is known. +## How to exit + +Redact your reply. That is all. The next collection run sets `exited`, erases +`text`, and excludes the record from every later tally and from training. It +cannot undo past use: tallies already shown and anything already exported +cannot be recalled by Matrix or by the collector. The experiment's page states +the export cadence so the window is known. From 2364979f0d2bb5a29f68f06ed2fac1cd998199c5 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 6 Nov 2026 17:24:39 +0000 Subject: [PATCH 06/63] Rule the open points from the CultLib consent-records review Scopeless replies are stored and excluded; tombstone is HMAC-SHA-256 with a member-side salt; representation, training-rule scope match, scope partition and MemberTerms ownership fixed. Docs only. Co-Authored-By: Claude Sonnet 5.5 --- docs/answer-collector-consent.md | 62 ++++++++++++++++++++++++++++---- 1 file changed, 55 insertions(+), 7 deletions(-) diff --git a/docs/answer-collector-consent.md b/docs/answer-collector-consent.md index 129f279..fe0a321 100644 --- a/docs/answer-collector-consent.md +++ b/docs/answer-collector-consent.md @@ -50,7 +50,10 @@ Key: `(experiment_id, member_id, notice_version)`. Written once, never updated. Joining Heimdall is gated by terms. Acceptance is the terms version recorded by the Matrix `m.login.terms` stage at registration: member field `terms_version` -(string) and `terms_accepted_at` (UTC timestamp). This applies to newcomers +(string) and `terms_accepted_at` (UTC timestamp). These fields belong to the +Heimdall member record. A typed `MemberTerms` record keyed by `member_id` is the +shape of that pair in a typed library; it is not a second store, and the +collector does not hold it. This applies to newcomers only. Members who joined before the terms stage existed, and Minds, are not re-asked and have no `terms_version`; the collector does not read it and does not gate on it. The notice above is the only consent the collector itself checks. @@ -68,6 +71,7 @@ One record per answer. Fields: | `scope` | `show` \| `study` \| `train` | copied from that notice version at answer time. Never edited afterwards. | | `text` | string, or absent | the answer as given. Absent once exited. | | `exited` | boolean, default false | one-way: set by redaction, never cleared. A new answer is a new record. | +| `text_hash` | 32 bytes, or absent | the tombstone hash of `text` (see "Tombstone"). Present only once exited, and only when the collector held `text` before the redaction. | | `received_at` | UTC timestamp | `origin_server_ts` of the reply. | | `event_id` | Matrix event id | the reply; the receipt. | @@ -75,9 +79,25 @@ Key: `(experiment_id, sample_id, member_id)`. A member's later answer to the same key replaces the earlier one (latest `received_at` wins); the earlier text is not retained. -A record whose `notice_version` or `scope` is missing, unparseable or has no -matching acceptance record is not collected. It is excluded from every use, and -from training in particular. +A reply whose `notice_version` or `scope` is missing, unparseable or has no +matching acceptance record is stored, with those fields absent. It is excluded +from every use: no tally, no display, and from training in particular. It +writes no acceptance record. The reply is kept so the member can still exit it +and the collector can show what it refused, but no scope was declared, so none +is inferred. The notice version of a reply is the one pinned at the reply's +`origin_server_ts`; if the collector cannot establish what was pinned then, the +reply has no notice version. + +### Representation + +- Timestamps are Unix milliseconds in UTC, stored as a signed 64-bit integer, + the unit of Matrix `origin_server_ts`. Every "UTC timestamp" above means this. +- `member_id`, `experiment_id`, `event_id` and `terms_version` are non-empty + strings; `member_id` is opaque and `event_id` is the Matrix event id verbatim. + `notice_version` and the `` of `sample_id` are positive integers + (unsigned 32-bit). +- A composite key is its parts joined with U+001F. A part that is empty or + contains U+001F is refused, not escaped. ## Versions @@ -92,13 +112,39 @@ A record is training or evaluation data only if all hold: 1. `scope = train`, copied from a notice version that declared `train`; 2. an acceptance record exists for `(experiment_id, member_id, notice_version)` - with `accepted_at <= received_at`, i.e. the author had accepted that notice + of the answer, its own `scope` is `train` and equals the answer's `scope`, + and `accepted_at <= received_at`, i.e. the author had accepted that notice version when they answered; 3. `exited = false` at export time. No recorded scope, or no recorded acceptance, means excluded. Records wider than -`show` are kept apart from `show` records: separate store or partition, so a read -for one level cannot return another. +`show` are kept apart from `show` records: one store per scope (`show`, `study`, +`train`) plus a store for scopeless replies that no read path serves. A record +lives in the store its `scope` names, so a read for one level cannot return +another. A typed-record library need not model the partition; the collector's +store layout owns it. + +## Tombstone + +- Function: HMAC-SHA-256 (RFC 2104 with SHA-256, FIPS 180-4), output the raw 32 + bytes stored in `text_hash`. No truncation. +- Message: the ASCII string `heimdall.tombstone.v1`, U+001F, `event_id` + (UTF-8), U+001F, `text` (UTF-8, as received, no normalisation). The `event_id` + makes the hash specific to the reply, so equal texts hash differently. +- Key (the salt): 32 bytes from a cryptographically secure random source, + generated once per member by the member-side service, which is the service that + already maps Matrix sender to `member_id`. It is held there, beside the member + record, and is never given to the collector, a researcher, an export or a log. + The collector cannot compute or check a tombstone hash on its own. +- Redaction: when the collector sees a redaction of a reply whose text it holds, + it sends `event_id` and `text` to the member-side service, which returns the + hash; the collector writes `text_hash`, sets `exited`, and erases `text`. If the + service does not answer, `text` is kept, the record is not yet exited, and the + run retries. A reply the collector never collected has no text and gets no + tombstone. +- Verification: only the member-side service can check a claimed text against a + tombstone. If a member's salt is destroyed, their tombstones can no longer be + tied to any text, and that is the member's erasure. ## Identity: count once, reward without exposure @@ -137,6 +183,8 @@ not stored under a placeholder. and a salted hash of `text`. Hash only, never text, and no `member_id` beyond what the record's key already holds. The count and the exit are provable without the content. The record is marked `exited`; `text` is erased. + The tombstone is the exited `Answer` record itself, with `text_hash` set; it is + not a separate record. - **Edits.** An edit is a new event, not the receipt. Only the original event counts; edits are ignored, so what was accepted is what was received. To change an answer, redact and reply again. From 4e99bfa6286895f884c53876567e3ef449866c48 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 6 Nov 2026 19:40:44 +0000 Subject: [PATCH 07/63] Rule empty text and received_at ties from CultLib #12 follow-up Co-Authored-By: Claude Sonnet 5.5 --- docs/answer-collector-consent.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/answer-collector-consent.md b/docs/answer-collector-consent.md index fe0a321..accce7a 100644 --- a/docs/answer-collector-consent.md +++ b/docs/answer-collector-consent.md @@ -69,15 +69,20 @@ One record per answer. Fields: | `member_id` | Heimdall member id | the respondent. Never a Matrix id, never a display name. | | `notice_version` | integer | the notice version in force when the answer was received; matches an acceptance record by the key above. | | `scope` | `show` \| `study` \| `train` | copied from that notice version at answer time. Never edited afterwards. | -| `text` | string, or absent | the answer as given. Absent once exited. | +| `text` | string, or absent | the answer as given. Non-empty while the answer is live; absent once exited. | | `exited` | boolean, default false | one-way: set by redaction, never cleared. A new answer is a new record. | | `text_hash` | 32 bytes, or absent | the tombstone hash of `text` (see "Tombstone"). Present only once exited, and only when the collector held `text` before the redaction. | -| `received_at` | UTC timestamp | `origin_server_ts` of the reply. | +| `received_at` | UTC timestamp | assigned by the collector when it receives the reply. Not copied from the reply. | | `event_id` | Matrix event id | the reply; the receipt. | Key: `(experiment_id, sample_id, member_id)`. A member's later answer to the same key replaces the earlier one (latest `received_at` wins); the earlier text -is not retained. +is not retained. Two replies to one key with equal `received_at` tie-break on +`event_id` compared bytewise: the greater `event_id` wins as the later reply. + +Empty text: a live (non-exited) answer must have non-empty `text`, and the +collector rejects a reply whose text is empty. Empty text is valid only on an +exited answer, where redaction clears `text` and leaves the hash-only tombstone. A reply whose `notice_version` or `scope` is missing, unparseable or has no matching acceptance record is stored, with those fields absent. It is excluded @@ -167,7 +172,8 @@ not stored under a placeholder. is a thread reply to the sample, the answer text being the body. There is no per-reply scope syntax. - The reply event is the receipt: its event id and timestamp are the proof the - answer was received, and `received_at` comes from it. + answer was received. `received_at` is the collector's own clock at receipt, + not the reply's `origin_server_ts`. - Redaction is exit (see below): redacting the reply event sets `exited`. - The collector is on demand (it reads the room when run, it is not a standing listener). It drops: From cafdc52e5ffbae1a5be9db1343c73240d6f98959 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 6 Nov 2026 23:28:40 +0000 Subject: [PATCH 08/63] Rule version spelling and the room notice event Leading-zero versions are refused, not normalised; one version, one key. A room's notice is the org.gamecult.notice state event {version, scope} under the room's power levels; a pinned message is not accepted. Absent or malformed means no train line and the narrowest scope. Co-Authored-By: Claude Sonnet 5.5 --- docs/answer-collector-consent.md | 42 +++++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/docs/answer-collector-consent.md b/docs/answer-collector-consent.md index accce7a..b75e171 100644 --- a/docs/answer-collector-consent.md +++ b/docs/answer-collector-consent.md @@ -15,9 +15,26 @@ path. ## Notice Consent is declared once per room, not per reply. Each experiment room carries -one notice line, pinned with the sample, that names the scope the room's answers -may be used for and the way out. A notice has a `notice_version`; any change to -its wording or scope is a new version. +one notice that names the scope the room's answers may be used for and the way +out. A notice has a `notice_version`; any change to its wording or scope is a new +version. + +### Where the notice lives + +A room's notice is a Matrix room state event: type `org.gamecult.notice`, empty +`state_key`, content `{version, scope}`. + +- `version` is a positive integer written in decimal with no leading zeros. +- `scope` is `show`, `study` or `train`. +- The event is set under the room's power levels. A pinned message is not + accepted as a notice: anyone who can pin could forge it. +- Absent or malformed (a missing or unknown field, a `version` that is not a + positive integer or has leading zeros, an unknown `scope`) means no `train` + line and the narrowest scope, `show`. Malformed content is never repaired. + +The wording shown to respondents is the room's own business; the collector reads +only `version` and `scope`. A change to either is a new state event and so a +new `version`. | scope | what the notice allows | |---|---| @@ -30,7 +47,7 @@ its wording or scope is a new version. reply. The first reply a member posts in the room is their acceptance of the notice -version then pinned. No separate click, command or form. A later notice version +version then in force. No separate click, command or form. A later notice version needs a new acceptance: the member's first reply under it. ### Notice acceptance record @@ -39,7 +56,7 @@ needs a new acceptance: the member's first reply under it. |---|---|---| | `member_id` | Heimdall member id | the accepting member. | | `experiment_id` | string | the room. | -| `notice_version` | integer | the version pinned when the reply was received. | +| `notice_version` | integer | the `version` of the room's notice state event when the reply was received. | | `scope` | `show` \| `study` \| `train` | the scope that version declared. | | `accepted_at` | UTC timestamp | `origin_server_ts` of the first reply. | | `event_id` | Matrix event id | that reply, as proof. | @@ -64,7 +81,7 @@ One record per answer. Fields: | field | type | rule | |---|---|---| -| `sample_id` | string `@` | names the thing answered about; `` is a positive integer. A changed sample is a new version. | +| `sample_id` | string `@` | names the thing answered about; `` is a positive integer in decimal with no leading zeros. A changed sample is a new version. | | `experiment_id` | string | the experiment that asked. | | `member_id` | Heimdall member id | the respondent. Never a Matrix id, never a display name. | | `notice_version` | integer | the notice version in force when the answer was received; matches an acceptance record by the key above. | @@ -89,9 +106,9 @@ matching acceptance record is stored, with those fields absent. It is excluded from every use: no tally, no display, and from training in particular. It writes no acceptance record. The reply is kept so the member can still exit it and the collector can show what it refused, but no scope was declared, so none -is inferred. The notice version of a reply is the one pinned at the reply's -`origin_server_ts`; if the collector cannot establish what was pinned then, the -reply has no notice version. +is inferred. The notice version of a reply is the one the room's notice state +event held at the reply's `origin_server_ts`; if the collector cannot establish +what it held then, the reply has no notice version. ### Representation @@ -101,6 +118,9 @@ reply has no notice version. strings; `member_id` is opaque and `event_id` is the Matrix event id verbatim. `notice_version` and the `` of `sample_id` are positive integers (unsigned 32-bit). +- A `` with leading zeros (`s@01`) is refused, not normalised: `s@1` is + the only spelling of version 1, so one version has exactly one key. The same + holds for `notice_version`. Nothing is silently rewritten to fit. - A composite key is its parts joined with U+001F. A part that is empty or contains U+001F is refused, not escaped. @@ -168,7 +188,7 @@ not stored under a placeholder. ## Eureka's shape (Matrix) - One room per experiment. The room is `experiment_id`. -- The sample is posted as a message, with the notice pinned beside it. An answer +- The sample is posted as a message; the room's notice is its `org.gamecult.notice` state event. An answer is a thread reply to the sample, the answer text being the body. There is no per-reply scope syntax. - The reply event is the receipt: its event id and timestamp are the proof the @@ -197,7 +217,7 @@ not stored under a placeholder. - **Bridge spoofing.** A bridge can post as any ghost user. Only senders whose Matrix id resolves through Heimdall's linked identity to a member count; bridged ghost ids are not linked identities. A bridge cannot raise scope: scope - comes only from the pinned notice version. + comes only from the room's notice state event. - **Bridged origin.** Events that arrive through a bridge are dropped by origin, not by judging their text. From d6a8d4238cd4cf13845dd80107d9f393e1924da1 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sat, 7 Nov 2026 00:30:00 +0000 Subject: [PATCH 09/63] Rule every consent version as a positive u32 with no leading zeros Fold the leading-zero text into one version rule under Representation: sample, notice, notice acceptance and terms versions, and the room notice, all positive decimal integers, no leading zeros, at most 4294967295. Co-Authored-By: Claude Sonnet 5.5 --- docs/answer-collector-consent.md | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/docs/answer-collector-consent.md b/docs/answer-collector-consent.md index b75e171..6dc29ca 100644 --- a/docs/answer-collector-consent.md +++ b/docs/answer-collector-consent.md @@ -24,12 +24,12 @@ version. A room's notice is a Matrix room state event: type `org.gamecult.notice`, empty `state_key`, content `{version, scope}`. -- `version` is a positive integer written in decimal with no leading zeros. +- `version` follows the version rule under Representation. - `scope` is `show`, `study` or `train`. - The event is set under the room's power levels. A pinned message is not accepted as a notice: anyone who can pin could forge it. -- Absent or malformed (a missing or unknown field, a `version` that is not a - positive integer or has leading zeros, an unknown `scope`) means no `train` +- Absent or malformed (a missing or unknown field, a `version` the version rule + does not accept, an unknown `scope`) means no `train` line and the narrowest scope, `show`. Malformed content is never repaired. The wording shown to respondents is the room's own business; the collector reads @@ -81,7 +81,7 @@ One record per answer. Fields: | field | type | rule | |---|---|---| -| `sample_id` | string `@` | names the thing answered about; `` is a positive integer in decimal with no leading zeros. A changed sample is a new version. | +| `sample_id` | string `@` | names the thing answered about; `` follows the version rule under Representation. A changed sample is a new version. | | `experiment_id` | string | the experiment that asked. | | `member_id` | Heimdall member id | the respondent. Never a Matrix id, never a display name. | | `notice_version` | integer | the notice version in force when the answer was received; matches an acceptance record by the key above. | @@ -114,13 +114,18 @@ what it held then, the reply has no notice version. - Timestamps are Unix milliseconds in UTC, stored as a signed 64-bit integer, the unit of Matrix `origin_server_ts`. Every "UTC timestamp" above means this. -- `member_id`, `experiment_id`, `event_id` and `terms_version` are non-empty - strings; `member_id` is opaque and `event_id` is the Matrix event id verbatim. - `notice_version` and the `` of `sample_id` are positive integers - (unsigned 32-bit). -- A `` with leading zeros (`s@01`) is refused, not normalised: `s@1` is - the only spelling of version 1, so one version has exactly one key. The same - holds for `notice_version`. Nothing is silently rewritten to fit. +- `member_id`, `experiment_id` and `event_id` are non-empty strings; + `member_id` is opaque and `event_id` is the Matrix event id verbatim. +- Version rule. Every version field in the consent system is a positive integer + written in decimal with no leading zeros and at most 4294967295 (u32 max): + the `` of `sample_id` (`s@`), `notice_version`, the + `version` of the room notice `org.gamecult.notice`, and the notice acceptance + and terms records (`terms_version`, carried as that decimal string). Anything + else (zero, a sign, whitespace, a non-digit, a leading zero such as `s@01`, a + value above the maximum) is refused, not normalised: `s@1` is the only + spelling of version 1, so one version has exactly one key. A room notice + whose `version` fails the rule is malformed: no `train` line, narrowest scope + `show`. Nothing is silently rewritten to fit. - A composite key is its parts joined with U+001F. A part that is empty or contains U+001F is refused, not escaped. From aaeb175dc666e81a13dc2890da26898eaa76cb60 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sat, 7 Nov 2026 02:34:48 +0000 Subject: [PATCH 10/63] State the two encodings of the version rule; note the checkbox version gap Room notice version is a JSON number (a string, including "01", is malformed); the answer key keeps the version as encoded text under the leading-zero refusal. Same rule, two encodings. The registration checkbox records no version: recorded as an open gap Void is raising. Co-Authored-By: Claude Sonnet 5.5 --- docs/answer-collector-consent.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/answer-collector-consent.md b/docs/answer-collector-consent.md index 6dc29ca..89f34f1 100644 --- a/docs/answer-collector-consent.md +++ b/docs/answer-collector-consent.md @@ -75,6 +75,9 @@ only. Members who joined before the terms stage existed, and Minds, are not re-asked and have no `terms_version`; the collector does not read it and does not gate on it. The notice above is the only consent the collector itself checks. +Open gap: the registration checkbox records no version. Void is raising this; +nothing here rules it. + ## Answer record One record per answer. Fields: @@ -126,6 +129,11 @@ what it held then, the reply has no notice version. spelling of version 1, so one version has exactly one key. A room notice whose `version` fails the rule is malformed: no `train` line, narrowest scope `show`. Nothing is silently rewritten to fit. +- Two encodings of the one version rule. In the `org.gamecult.notice` room state + event, `version` is a JSON number; a string (including `"01"`) is malformed. + In the answer key (`s@`, and the composite keys), the version stays + its encoded decimal text, held to the leading-zero refusal. The rule is the + same in both: a positive integer, no leading zeros, at most 4294967295. - A composite key is its parts joined with U+001F. A part that is empty or contains U+001F is refused, not escaped. From 7ca4e2355f4ba9955123ad87b907cd3135431744 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sun, 8 Nov 2026 13:22:36 +0000 Subject: [PATCH 11/63] Joystick consent: the ask, typed refusal, receipts, and a signed-in grants page Managed custody (callbackMint custody_only) now stops at a Heimdall page before the provider redirect. A decline or a provider access_denied is consent_refused (by viewer|provider), distinct from provider_error. A granted completion writes an append-only consent receipt with the asked and granted scopes and the digest of the wording shown. GET /v1/me/grants lists every grant and receipt of the signed-in account; revoking one strips the credential, so the app's next token request is refused, and writes a revocation receipt. Co-Authored-By: Claude Sonnet 5.5 --- src/app.ts | 384 +++++++++++++++++++++++--- src/backend-handoff.ts | 4 + src/browser-handoff.ts | 31 ++- src/consent.ts | 170 ++++++++++++ src/providers.ts | 7 +- src/store/in-memory.ts | 13 + src/store/postgres.ts | 71 +++++ src/store/schema.ts | 18 ++ src/store/types.ts | 28 ++ tests/joystick-consent.test.ts | 437 ++++++++++++++++++++++++++++-- tests/oauth-flow.ts | 18 +- tests/oauth-state-binding.test.ts | 5 +- tests/store.test.ts | 8 +- 13 files changed, 1110 insertions(+), 84 deletions(-) create mode 100644 src/consent.ts diff --git a/src/app.ts b/src/app.ts index 2707bbe..c4d8e93 100644 --- a/src/app.ts +++ b/src/app.ts @@ -26,6 +26,7 @@ import { import { issueAccessClaim, type IssueAccessClaimInput } from "./claims.js"; import { builtInAppProfiles, getAppProfile, isAllowedReturnOrigin, serializeAppProfile, admitsProviderForMode, callbackMint } from "./app-profiles.js"; import { renderBrowserHandoffPage } from "./browser-handoff.js"; +import { consentDigest, grantViews, GRANTS_PATH, renderConsentPage, renderGrantsPage, type ConsentAsk } from "./consent.js"; import { type HeimdallConfig, loadConfig } from "./config.js"; import { createTokenCustody, type TokenCustody } from "./custody.js"; import { grantFact } from "./facts.js"; @@ -37,7 +38,7 @@ import { type OAuthRuntimeRegistry, } from "./oauth.js"; import { ManagedCredentialRefreshFailed, refreshManagedCredential } from "./managed-credential.js"; -import { buildAuthorizationUrl, providerCatalog, providerExpectedEnv } from "./providers.js"; +import { authorizationScopes, buildAuthorizationUrl, providerCatalog, providerExpectedEnv } from "./providers.js"; import { createRuntimeKeyMaterial, signJwt, verifyJwt } from "./signing.js"; import { createStore, type HeimdallStore } from "./store/index.js"; import { @@ -809,6 +810,47 @@ async function resolveLinkAccount( return claims.account_id; } +/** The account a Heimdall access token for any app names, when the token and its session are live. */ +async function resolveAccessAccount( + ctx: Pick, + 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 audience = verification.payload.aud; + return isAppSlug(audience) ? resolveLinkAccount(ctx, audience, authorization) : null; +} + +const grantsPageTokenType = "heimdall_grants_page"; +const grantsPageTokenTtlSeconds = 600; + +/** A short, purpose-bound proof of a signed-in account, so the grants page can be opened and its forms posted by a browser that holds no session. */ +function signGrantsPageToken(config: HeimdallConfig, keys: ReturnType, accountId: string): string { + const iat = nowEpochSeconds(); + return signJwt({ typ: grantsPageTokenType, iss: config.issuer, account_id: accountId, iat, exp: iat + grantsPageTokenTtlSeconds }, keys); +} + +function grantsPageTokenAccount(config: HeimdallConfig, keys: ReturnType, token: unknown): string | null { + if (typeof token !== "string") return null; + const verification = verifyJwt(token, keys.publicKey); + if (!verification.valid) return null; + const { typ, iss, account_id: accountId, exp } = verification.payload; + return typ === grantsPageTokenType && iss === config.issuer && typeof accountId === "string" && typeof exp === "number" && exp > nowEpochSeconds() + ? accountId + : null; +} + +function consentAskFor(state: OAuthStatePayload): ConsentAsk { + return { + appSlug: state.app_slug, + provider: state.provider, + scopes: authorizationScopes(state.provider, state.requested_scopes ?? undefined), + returnOrigin: new URL(state.return_to).origin, + }; +} + /** * Session refresh, extracted for the same reason as startOAuthFlow: the HTTP * route and the plane's `refreshAuth` (which owns Ghostlight identity) call @@ -948,6 +990,10 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { + done(null, Object.fromEntries(new URLSearchParams(body as string))); + }); app.get("/healthz", async () => ({ ok: true, @@ -1126,6 +1172,106 @@ export async function buildApp(options: BuildAppOptions = {}): Promise => { + const handoff = state.handoff ?? { kind: "browser_completion" }; + if (handoff.kind !== "browser_completion" || !handoff.attemptId) return; + await store.updateAuthAttempt(state.app_slug, handoff.attemptId, { + status: "denied", + at: new Date().toISOString(), + denialCode, + }); + }; + + /** + * The person said no, at Heimdall's ask (`viewer`) or at the provider + * (`provider`, a returned access_denied). It is its own result, never a + * provider_error: the app and the audit log can tell a refusal from a fault. + * Nothing is stored beyond an audit row that names no one. + */ + const refuseConsent = async (request: FastifyRequest, reply: FastifyReply, state: OAuthStatePayload, by: "viewer" | "provider") => { + const handoff = state.handoff ?? { kind: "browser_completion" }; + await denyAttempt(state, "consent_refused"); + await store.createAuditEvent({ + appSlug: state.app_slug, + eventType: "consent_refused", + eventPayloadJson: { provider: state.provider, mode: state.mode, by }, + createdAt: new Date().toISOString(), + }); + if (handoff.kind === "backend_callback") { + await maybeDeliverBackendHandoff(handoff, { + source: "heimdall", + kind: "oauth_result", + handoffKind: "backend_callback", + attemptId: handoff.attemptId, + status: "error", + provider: state.provider, + appSlug: state.app_slug, + mode: state.mode, + returnTo: state.return_to, + connection: state.connection, + error: "consent_refused", + by, + }); + } + if (prefersHtml(request.headers.accept)) { + reply.type("text/html; charset=utf-8"); + return reply.send( + renderBrowserHandoffPage({ + handoffKind: handoff.kind, + status: "error", + provider: state.provider, + appSlug: state.app_slug, + mode: state.mode, + returnTo: state.return_to, + ...(handoff.kind === "backend_callback" ? { attemptId: handoff.attemptId } : {}), + error: "consent_refused", + by, + }) + ); + } + reply.code(400); + return { error: "consent_refused", by, provider: state.provider, returnTo: state.return_to }; + }; + + const providerNotConfigured = (reply: FastifyReply, state: OAuthStatePayload) => { + reply.code(503); + return { error: "provider_not_configured", provider: state.provider, expectedEnv: providerExpectedEnv(state.provider) }; + }; + + /** Claim the launch use, bind the browser, and send it to the provider. */ + const beginProviderRedirect = async (request: FastifyRequest, reply: FastifyReply, state: OAuthStatePayload, rawState: string) => { + const clientId = config.providers[state.provider].clientId; + if (!clientId) { + return providerNotConfigured(reply, state); + } + const first = await store.claimOAuthStateUse({ + jti: state.jti, + phase: "launch", + appSlug: state.app_slug, + usedAt: new Date().toISOString(), + expiresAt: new Date(state.exp * 1000).toISOString(), + }); + if (!first) { + return refuseVerifiedState(request, reply, state, "state_already_launched"); + } + + const oidc = providerCatalog[state.provider].oidc ? deriveOidcSecrets(state.jti, keys.privateKey) : undefined; + setOAuthBindingCookie(reply, state, signOAuthBinding(config, keys, state), state.exp - nowEpochSeconds()); + reply.header("Cache-Control", "no-store"); + reply.header("Referrer-Policy", "no-referrer"); + return reply.redirect( + buildAuthorizationUrl({ + provider: state.provider, + clientId, + redirectUri: oauthCallbackUrl(config, state.provider), + state: rawState, + requestedScopes: state.requested_scopes ?? undefined, + ...(oidc ? { oidc: { nonce: oidc.nonce, codeChallenge: oidc.codeChallenge } } : {}), + }), + 302 + ); + }; + app.get<{ Params: { provider: Provider }; Querystring: { state: string }; @@ -1158,38 +1304,82 @@ export async function buildApp(options: BuildAppOptions = {}): Promise( + "/v1/oauth/:provider/consent", + { + schema: { + params: { + type: "object", + required: ["provider"], + additionalProperties: false, + properties: { provider: { type: "string", enum: [...providers] } }, + }, + body: { + type: "object", + required: ["state", "decision"], + additionalProperties: false, + properties: { + state: { type: "string", minLength: 1 }, + decision: { type: "string", enum: ["continue", "decline"] }, + }, + }, + }, + }, + async (request, reply) => { + const verified = verifyOAuthState(config, keys, request.body.state, request.params.provider); + if (!verified.ok) { + reply.code(400); + return { error: verified.error }; + } + const state = verified.payload; + const profile = getAppProfile(state.app_slug); + if (!profile || callbackMint(profile, state.provider, state.mode, state.connection) !== "custody_only") { + reply.code(400); + return { error: "consent_not_required" }; + } + // Either answer must come from the browser the ask was shown to. + if (!oauthBindingHolds(config, keys, request.cookies[oauthBindingCookieName(state.jti)], state)) { + return refuseVerifiedState(request, reply, state, "state_not_bound"); + } + if (request.body.decision === "continue") { + return beginProviderRedirect(request, reply, state, request.body.state); + } + // A decline spends both uses of the state: it can neither launch nor complete afterwards. + const usedAt = new Date().toISOString(); + const expiresAt = new Date(state.exp * 1000).toISOString(); + if (!(await store.claimOAuthStateUse({ jti: state.jti, phase: "launch", appSlug: state.app_slug, usedAt, expiresAt }))) { return refuseVerifiedState(request, reply, state, "state_already_launched"); } - - const oidc = providerCatalog[state.provider].oidc ? deriveOidcSecrets(state.jti, keys.privateKey) : undefined; - setOAuthBindingCookie(reply, state, signOAuthBinding(config, keys, state), state.exp - nowEpochSeconds()); - reply.header("Cache-Control", "no-store"); - reply.header("Referrer-Policy", "no-referrer"); - return reply.redirect( - buildAuthorizationUrl({ - provider: state.provider, - clientId, - redirectUri: oauthCallbackUrl(config, state.provider), - state: request.query.state, - requestedScopes: state.requested_scopes ?? undefined, - ...(oidc ? { oidc: { nonce: oidc.nonce, codeChallenge: oidc.codeChallenge } } : {}), - }), - 302 - ); + await store.claimOAuthStateUse({ jti: state.jti, phase: "callback", appSlug: state.app_slug, usedAt, expiresAt }); + setOAuthBindingCookie(reply, state, "", 0); + return refuseConsent(request, reply, state, "viewer"); } ); @@ -1233,14 +1423,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise => { - if (handoff.kind !== "browser_completion" || !handoff.attemptId) return; - await store.updateAuthAttempt(statePayload.app_slug, handoff.attemptId, { - status: "denied", - at: new Date().toISOString(), - denialCode, - }); - }; + const denyBrowserAttempt = (denialCode: string): Promise => denyAttempt(statePayload, denialCode); // The cookie is checked before the claim: a stranger without it must not be // able to burn the state that the browser that launched it still needs. // The attempt is denied, though: a launcher whose cookie lapsed can never @@ -1262,6 +1445,9 @@ export async function buildApp(options: BuildAppOptions = {}): Promise => + (await resolveAccessAccount({ config, keys, store }, request.headers.authorization)) ?? + grantsPageTokenAccount(config, keys, pageToken); + + const grantsReply = (reply: FastifyReply) => { + reply.header("Cache-Control", "no-store"); + reply.header("Referrer-Policy", "no-referrer"); + reply.header("X-Frame-Options", "DENY"); + reply.header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"); + }; + + const signInRequired = (reply: FastifyReply) => { + reply.code(401); + return { error: "sign_in_required", detail: "Send a Heimdall access token as a Bearer token, or open a link from POST /v1/me/grants/link." }; + }; + + // 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 } }>( + GRANTS_PATH, + { schema: { querystring: { type: "object", additionalProperties: false, properties: { t: { type: "string" } } } } }, + async (request, reply) => { + const accountId = await grantsAccount(request, request.query.t); + if (!accountId) return signInRequired(reply); + grantsReply(reply); + const receipts = await store.listConsentReceipts(accountId); + if (prefersHtml(request.headers.accept)) { + reply.type("text/html; charset=utf-8"); + return reply.send(renderGrantsPage(grantViews(receipts), signGrantsPageToken(config, keys, accountId))); + } + return { grants: grantViews(receipts), receipts }; + } + ); + + // A link a browser can open: short-lived, opens the grants page and nothing else. + app.post(`${GRANTS_PATH}/link`, async (request, reply) => { + const accountId = await resolveAccessAccount({ config, keys, store }, request.headers.authorization); + if (!accountId) return signInRequired(reply); + grantsReply(reply); + reply.code(201); + return { + url: `${config.publicBaseUrl}${GRANTS_PATH}?t=${encodeURIComponent(signGrantsPageToken(config, keys, accountId))}`, + expiresInSeconds: grantsPageTokenTtlSeconds, + }; + }); + + app.post<{ Params: { grantId: string }; Body?: { t?: string } }>( + `${GRANTS_PATH}/:grantId/revoke`, + { + schema: { + params: { type: "object", required: ["grantId"], additionalProperties: false, properties: { grantId: { type: "string", minLength: 1 } } }, + body: { type: ["object", "null"], additionalProperties: false, properties: { t: { type: "string" } } }, + }, + }, + async (request, reply) => { + const accountId = await grantsAccount(request, request.body?.t); + if (!accountId) return signInRequired(reply); + grantsReply(reply); + const receipts = await store.listConsentReceipts(accountId); + const grant = grantViews(receipts).find((view) => view.id === request.params.grantId); + if (!grant) { + reply.code(404); + return { error: "grant_not_found" }; + } + const revoked: string[] = []; + if (grant.status === "active") { + // The credential is one row per account and provider, whichever app + // asked, so taking it back ends every live grant that rests on it. + // It is stripped first: a failure after that leaves a receipt that + // still reads active over a credential that is gone, never the reverse. + const identity = await store.findStoredLinkedIdentityForAccount(accountId, grant.provider); + const at = new Date().toISOString(); + if (identity) { + await store.updateLinkedIdentityCredential(identity.id, async () => ({ kind: "revoke", updatedAt: at })); + } + for (const live of grantViews(receipts).filter((view) => view.provider === grant.provider && view.status === "active")) { + await store.createConsentReceipt({ + kind: "revocation", + accountId, + appSlug: live.appSlug, + provider: live.provider, + createdAt: at, + revokesReceiptId: live.id, + }); + revoked.push(live.id); + } + 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"); + const views = grantViews(await store.listConsentReceipts(accountId)); + return reply.send(renderGrantsPage(views, signGrantsPageToken(config, keys, accountId), revoked.length ? "Taken back." : "Already taken back.")); + } + return { revoked, grants: grantViews(await store.listConsentReceipts(accountId)) }; + } + ); + return app; } diff --git a/src/backend-handoff.ts b/src/backend-handoff.ts index d49a125..b26a59f 100644 --- a/src/backend-handoff.ts +++ b/src/backend-handoff.ts @@ -30,6 +30,8 @@ export interface BackendHandoffSuccessPayload mode: OAuthMode; account: AccountSummary; entitlements: EntitlementEvaluation; + /** The receipt of the consent a managed connection rests on. */ + consentReceiptId?: string; } export interface BackendHandoffErrorPayload extends BackendHandoffBase { @@ -37,6 +39,8 @@ export interface BackendHandoffErrorPayload extends BackendHandoffBase { mode?: OAuthMode; error: string; errorDescription?: string; + /** Who said no, when `error` is consent_refused. */ + by?: "viewer" | "provider"; } /** A verified link that waits for the initiating account's confirm: no session, no tokens. */ diff --git a/src/browser-handoff.ts b/src/browser-handoff.ts index c21c01e..b8da567 100644 --- a/src/browser-handoff.ts +++ b/src/browser-handoff.ts @@ -15,6 +15,8 @@ export interface BrowserHandoffSuccess extends BrowserHandoffBase { /** A verified link waiting for its initiator's confirm; carries no session. */ pendingLinkId?: string; attemptId?: string; + /** The receipt of the consent a managed connection rests on. */ + consentReceiptId?: string; } export interface BrowserHandoffError extends BrowserHandoffBase { @@ -22,6 +24,8 @@ export interface BrowserHandoffError extends BrowserHandoffBase { error: string; errorDescription?: string; attemptId?: string; + /** Who said no, when `error` is consent_refused. */ + by?: "viewer" | "provider"; } export type BrowserHandoffPayload = BrowserHandoffSuccess | BrowserHandoffError; @@ -47,6 +51,9 @@ function buildBrowserFallbackUrl(payload: BrowserHandoffPayload): string { fragment.set("heimdall_attempt_id", payload.attemptId); } + if (payload.status === "success" && payload.consentReceiptId) { + fragment.set("heimdall_consent_receipt_id", payload.consentReceiptId); + } if (payload.status === "success" && payload.completionCode) { fragment.set("heimdall_completion_code", payload.completionCode); } else if (payload.status === "success" && payload.pendingLinkId) { @@ -54,6 +61,9 @@ function buildBrowserFallbackUrl(payload: BrowserHandoffPayload): string { } else { if (payload.status === "error") { fragment.set("heimdall_error", payload.error); + if (payload.by) { + fragment.set("heimdall_refused_by", payload.by); + } if (payload.errorDescription) { fragment.set("heimdall_error_description", payload.errorDescription); } @@ -77,14 +87,19 @@ export function renderBrowserHandoffPage(payload: BrowserHandoffPayload): string }); const scriptOrigin = serializeForScript(targetOrigin); const scriptFallbackUrl = serializeForScript(fallbackUrl); - const scriptTitle = serializeForScript( - payload.status === "success" ? "Authentication Complete" : "Authentication Failed" - ); + const refused = payload.status === "error" && payload.error === "consent_refused"; + const pageTitle = refused ? "Not Connected" : payload.status === "success" ? "Authentication Complete" : "Authentication Failed"; + const scriptTitle = serializeForScript(pageTitle); const scriptBody = serializeForScript( - payload.status === "success" - ? payload.handoffKind === "backend_callback" - ? "The app backend has the auth result already. You can return to the app now." - : "You can return to the app now." + refused + ? "Nothing was connected and nothing was kept. You can return to the app." + : payload.status === "success" + ? (payload.handoffKind === "backend_callback" + ? "The app backend has the auth result already. You can return to the app now." + : "You can return to the app now.") + + (payload.consentReceiptId + ? ` Your consent is recorded as receipt ${payload.consentReceiptId}; you can review it and take it back from your Heimdall connections page.` + : "") : "The authentication flow failed. Return to the app to continue." ); @@ -93,7 +108,7 @@ export function renderBrowserHandoffPage(payload: BrowserHandoffPayload): string - ${payload.status === "success" ? "Authentication Complete" : "Authentication Failed"} + ${pageTitle} + + +
+${body} +
+ +`; +} + +/** The ask. Two POST forms carry the signed state; the page runs no script. */ +export function renderConsentPage(ask: ConsentAsk, state: string): string { + const lines = consentLines(ask); + const provider = providerCatalog[ask.provider].displayName; + const [headline, ...rest] = lines; + const form = (decision: "continue" | "decline", label: string) => + ``; + return page( + `${appName(ask.appSlug)} wants to connect ${provider}`, + `

${escapeHtml(headline!)}

+
    +${rest.map((line) => `
  • ${escapeHtml(line)}
  • `).join("\n")} +
+
+ + ${form("continue", `Continue to ${provider}`)} + ${form("decline", "No, return to the app")} +
` + ); +} + +export interface GrantView { + id: string; + appSlug: AppSlug; + provider: Provider; + scopesAsked: string[]; + scopesGranted: string[]; + grantedAt: string; + consentPageDigest: string; + status: "active" | "revoked"; + revokedAt?: string; + revocationReceiptId?: string; +} + +/** Every grant the receipts hold, each live unless a revocation names it. */ +export function grantViews(receipts: readonly StoredConsentReceipt[]): GrantView[] { + const revocations = new Map(); + for (const receipt of receipts) { + if (receipt.kind === "revocation") revocations.set(receipt.revokesReceiptId, receipt); + } + const views: GrantView[] = []; + for (const receipt of receipts) { + if (receipt.kind !== "grant") continue; + const revocation = revocations.get(receipt.id); + views.push({ + id: receipt.id, + appSlug: receipt.appSlug, + provider: receipt.provider, + scopesAsked: receipt.scopesAsked, + scopesGranted: receipt.scopesGranted, + grantedAt: receipt.createdAt, + consentPageDigest: receipt.consentPageDigest, + status: revocation ? "revoked" : "active", + ...(revocation ? { revokedAt: revocation.createdAt, revocationReceiptId: revocation.id } : {}), + }); + } + return views; +} + +/** The signed-in page: every grant with its receipt, one button each to take it back. */ +export function renderGrantsPage(grants: readonly GrantView[], pageToken: string, notice?: string): string { + const cards = grants.length + ? grants + .map((grant) => { + const provider = providerCatalog[grant.provider].displayName; + const header = `${escapeHtml(appName(grant.appSlug))} → ${escapeHtml(provider)}`; + const detail = `granted ${escapeHtml(grant.grantedAt)}; permissions ${escapeHtml(grant.scopesGranted.join(", ") || "none returned")}; receipt ${escapeHtml(grant.id)}; wording ${escapeHtml(grant.consentPageDigest.slice(0, 12))}`; + if (grant.status === "revoked") { + return `
${header} taken back ${escapeHtml(grant.revokedAt ?? "")}; receipt ${escapeHtml(grant.revocationReceiptId ?? "")}
${detail}
`; + } + return `
${header} active
${detail} +
+ + +
`; + }) + .join("\n") + : `

You have not connected anything through Heimdall.

`; + return page( + "Your connections", + `

Your connections

+${notice ? `

${escapeHtml(notice)}

\n` : ""}${cards} +

Taking a connection back deletes Heimdall's copy of the tokens. The app's next request for a token is refused. The permission stays with the provider until you remove it in the provider's settings.

` + ); +} diff --git a/src/providers.ts b/src/providers.ts index b649ede..01f749f 100644 --- a/src/providers.ts +++ b/src/providers.ts @@ -167,6 +167,11 @@ export const providerCatalog: Record = { }, }; +/** The scopes an authorization request carries: the caller's, or the provider's defaults. */ +export function authorizationScopes(provider: Provider, requested: readonly string[] | undefined): string[] { + return requested?.length ? [...requested] : [...providerCatalog[provider].defaultScopes]; +} + export function buildAuthorizationUrl(options: { provider: Provider; clientId: string; @@ -178,7 +183,7 @@ export function buildAuthorizationUrl(options: { }): string { const descriptor = providerCatalog[options.provider]; const url = new URL(descriptor.authorizationEndpoint); - const scopes = options.requestedScopes?.length ? options.requestedScopes : descriptor.defaultScopes; + const scopes = authorizationScopes(options.provider, options.requestedScopes); url.searchParams.set("client_id", options.clientId); url.searchParams.set("redirect_uri", options.redirectUri); diff --git a/src/store/in-memory.ts b/src/store/in-memory.ts index eafaea5..c31b098 100644 --- a/src/store/in-memory.ts +++ b/src/store/in-memory.ts @@ -5,7 +5,9 @@ import { type CreateAuthAttemptInput, type ClaimOAuthStateUseInput, type CreateAuthCompletionInput, + type CreateConsentReceiptInput, type CreatePendingLinkInput, + type StoredConsentReceipt, type StoredPendingLink, type CreateAuditEventInput, type CreateCapabilityGrantInput, @@ -59,6 +61,7 @@ export class InMemoryStore implements HeimdallStore { private readonly oauthStateUses = new Map(); private readonly entitlementSnapshots = new Map(); private readonly auditEvents = new Map(); + private readonly consentReceipts: StoredConsentReceipt[] = []; async ensureSchema(): Promise { return; @@ -482,4 +485,14 @@ export class InMemoryStore implements HeimdallStore { }); this.auditEvents.set(event.id ?? randomUUID(), event); } + + async createConsentReceipt(input: CreateConsentReceiptInput): Promise { + const receipt = { id: randomUUID(), ...clone(input) } as StoredConsentReceipt; + this.consentReceipts.push(clone(receipt)); + return clone(receipt); + } + + async listConsentReceipts(accountId: string): Promise { + return this.consentReceipts.filter((receipt) => receipt.accountId === accountId).map(clone); + } } diff --git a/src/store/postgres.ts b/src/store/postgres.ts index e3a1c4d..45240a5 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -7,7 +7,9 @@ import { type CreateAuthAttemptInput, type ClaimOAuthStateUseInput, type CreateAuthCompletionInput, + type CreateConsentReceiptInput, type CreatePendingLinkInput, + type StoredConsentReceipt, type StoredPendingLink, type CreateAuditEventInput, type CreateCapabilityGrantInput, @@ -248,6 +250,39 @@ function mapSessionRow(row: SessionRow): StoredSession { }; } +interface ConsentReceiptRow { + id: string; + kind: "grant" | "revocation"; + account_id: string; + app_slug: AppSlug; + provider: Provider; + created_at: Date | string; + scopes_asked: string | null; + scopes_granted: string | null; + consent_page_digest: string | null; + revokes_receipt_id: string | null; +} + +function mapConsentReceiptRow(row: ConsentReceiptRow): StoredConsentReceipt { + const base = { + id: row.id, + accountId: row.account_id, + appSlug: row.app_slug, + provider: row.provider, + createdAt: normalizeTimestamp(row.created_at), + }; + if (row.kind === "revocation") { + return { ...base, kind: "revocation", revokesReceiptId: row.revokes_receipt_id ?? "" }; + } + return { + ...base, + kind: "grant", + scopesAsked: parseScopes(row.scopes_asked ?? ""), + scopesGranted: parseScopes(row.scopes_granted ?? ""), + consentPageDigest: row.consent_page_digest ?? "", + }; +} + function mapPendingLinkRow(row: PendingLinkRow): StoredPendingLink { const link: StoredPendingLink = { id: row.id, @@ -421,6 +456,7 @@ export const STORE_TABLE_PRIVILEGES: Readonly { + const grant = input.kind === "grant" ? input : null; + const result = await this.pool.query( + ` + INSERT INTO consent_receipts ( + id, kind, account_id, app_slug, provider, created_at, + scopes_asked, scopes_granted, consent_page_digest, revokes_receipt_id + ) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) + RETURNING * + `, + [ + randomUUID(), + input.kind, + input.accountId, + input.appSlug, + input.provider, + input.createdAt, + grant ? grant.scopesAsked.join(" ") : null, + grant ? grant.scopesGranted.join(" ") : null, + grant ? grant.consentPageDigest : null, + input.kind === "revocation" ? input.revokesReceiptId : null, + ] + ); + return mapConsentReceiptRow(expectRow(result.rows[0], "createConsentReceipt")); + } + + async listConsentReceipts(accountId: string): Promise { + const result = await this.pool.query( + `SELECT * FROM consent_receipts WHERE account_id = $1 ORDER BY created_at, id`, + [accountId] + ); + return result.rows.map(mapConsentReceiptRow); + } + async createAuditEvent(input: CreateAuditEventInput): Promise { await this.pool.query( ` diff --git a/src/store/schema.ts b/src/store/schema.ts index 607445c..9c87dff 100644 --- a/src/store/schema.ts +++ b/src/store/schema.ts @@ -180,6 +180,24 @@ CREATE TABLE IF NOT EXISTS entitlement_snapshots ( UNIQUE(account_id, provider, scope) ); +-- Consent receipts are append-only (the store role has INSERT and SELECT +-- only): a revocation is a row that names the grant it takes back. +CREATE TABLE IF NOT EXISTS consent_receipts ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL, + account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + app_slug TEXT NOT NULL, + provider TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + scopes_asked TEXT, + scopes_granted TEXT, + consent_page_digest TEXT, + revokes_receipt_id TEXT +); + +CREATE INDEX IF NOT EXISTS consent_receipts_account_idx + ON consent_receipts(account_id, created_at); + 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 982bccc..4c4ce17 100644 --- a/src/store/types.ts +++ b/src/store/types.ts @@ -252,6 +252,31 @@ export interface StoredPrivateCommandReceipt { export type CreatePrivateCommandReceiptInput = StoredPrivateCommandReceipt; +/** + * What a person agreed to, or took back. Append-only: a grant row is never + * edited, and a revocation is a second row naming it, so a grant is live + * exactly when no revocation names it. `scopesAsked` is what Heimdall sent the + * provider, `scopesGranted` what the provider returned, `consentPageDigest` + * the hash of the wording the person was shown. + */ +export type StoredConsentReceipt = { + id: string; + accountId: string; + appSlug: AppSlug; + provider: Provider; + createdAt: string; +} & ( + | { kind: "grant"; scopesAsked: string[]; scopesGranted: string[]; consentPageDigest: string } + | { kind: "revocation"; revokesReceiptId: string } +); + +/** The store mints `id`; a caller cannot choose it. */ +export type CreateConsentReceiptInput = StoredConsentReceipt extends infer R + ? R extends StoredConsentReceipt + ? Omit + : never + : never; + export interface HeimdallStore { ensureSchema(): Promise; close(): Promise; @@ -325,4 +350,7 @@ export interface HeimdallStore { */ claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise; createAuditEvent(input: CreateAuditEventInput): Promise; + createConsentReceipt(input: CreateConsentReceiptInput): Promise; + /** Every receipt the account holds, oldest first. */ + listConsentReceipts(accountId: string): Promise; } diff --git a/tests/joystick-consent.test.ts b/tests/joystick-consent.test.ts index 6881f8f..3d4691f 100644 --- a/tests/joystick-consent.test.ts +++ b/tests/joystick-consent.test.ts @@ -1,62 +1,441 @@ -import { afterEach, describe, expect, it } from "vitest"; +import { createHash } from "node:crypto"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { type FastifyInstance } from "fastify"; import { buildApp } from "../src/app.js"; -import { createTestConfig } from "./oauth-flow.js"; +import { consentDigest, consentLines, type ConsentAsk } from "../src/consent.js"; +import { type OAuthProviderRuntime } from "../src/oauth.js"; +import { providerCatalog } from "../src/providers.js"; +import { InMemoryStore } from "../src/store/index.js"; +import { createTestConfig, setCookieOf, stateOf } from "./oauth-flow.js"; -// SKETCH for docs/joystick-consent-flow.md. Skipped: every test here names a -// behaviour the consent cut must build. Remove `.skip` as each one lands. +// The consent cut for managed custody (docs/joystick-consent-flow.md): the ask, +// the typed refusal, the receipt, and the signed-in page that lists and revokes. const apps: FastifyInstance[] = []; afterEach(async () => { + vi.restoreAllMocks(); while (apps.length) await apps.pop()?.close(); }); -async function creatorConnectStart(app: FastifyInstance) { +const defaultScopes = providerCatalog.joystick.defaultScopes; +const secret = { "x-heimdall-app-secret": "streampixels-secret" }; +const form = { "content-type": "application/x-www-form-urlencoded" }; + +/** A Joystick that returns whatever `code-` names, granting only `granted`. */ +function joystick(granted: string[] = ["identity:read", "stream:read"]): OAuthProviderRuntime { + return { + async exchangeAuthorizationCode({ code }) { + return { accessToken: `joy-access-${code}`, refreshToken: `joy-refresh-${code}`, tokenType: "Bearer", scope: granted, expiresAt: "2099-01-01T00:00:00.000Z", raw: {} }; + }, + async resolveIdentity({ accessToken }) { + const id = accessToken.replace("joy-access-code-", ""); + return { provider: "joystick", providerUserId: `joy-${id}`, username: id, profile: { id } }; + }, + async evaluateEntitlements() { + return { facts: [], snapshots: [] }; + }, + }; +} + +async function newApp(options: { granted?: string[]; callbacks?: string[] } = {}) { + const store = new InMemoryStore(); + const config = createTestConfig(); + if (options.callbacks) config.appBackendCallbacks = { streampixels: options.callbacks }; + const app = await buildApp({ config, store, oauthRuntimes: { joystick: joystick(options.granted) } }); + apps.push(app); + return { app, store }; +} + +async function startConnect(app: FastifyInstance, handoff: Record = { kind: "browser_completion" }) { const response = await app.inject({ method: "POST", url: "/v1/oauth/joystick/start", - headers: { "x-heimdall-app-secret": "streampixels-secret" }, + headers: secret, payload: { appSlug: "streampixels", mode: "connect", connection: { kind: "creator", targetId: "creator-1" }, returnTo: "https://streampixels.gamecult.org/settings", - handoff: { kind: "browser_completion" }, + handoff, }, }); expect(response.statusCode).toBe(201); - const url = new URL(response.json().authorizationUrl as string); - return `${url.pathname}${url.search}`; + return stateOf(response.json()); } -describe.skip("Joystick consent flow (draft)", () => { - it("launch shows a Heimdall ask naming app, provider and scopes, and does not redirect", async () => { - const app = await buildApp({ config: createTestConfig() }); - apps.push(app); - const launch = await app.inject({ method: "GET", url: await creatorConnectStart(app), headers: { accept: "text/html" } }); - expect(launch.statusCode).toBe(200); - expect(launch.headers.location).toBeUndefined(); - for (const needle of ["StreamPixels", "Joystick", "identity:read", "subscribers:read", "refresh token"]) { - expect(launch.body).toContain(needle); +const launchUrl = (state: string) => `/v1/oauth/joystick/launch?state=${encodeURIComponent(state)}`; +const cookieOf = (response: { headers: Record }) => + setCookieOf(response).find((value) => value.startsWith("__Host-heimdall-oauth-"))!.split(";")[0]!; + +/** The browser is shown the ask. */ +async function seeAsk(app: FastifyInstance, state: string) { + const response = await app.inject({ method: "GET", url: launchUrl(state), headers: { accept: "text/html" } }); + expect(response.statusCode).toBe(200); + return { page: response, cookie: cookieOf(response) }; +} + +function answer(app: FastifyInstance, state: string, decision: "continue" | "decline", cookie?: string, accept = "text/html") { + return app.inject({ + method: "POST", + url: "/v1/oauth/joystick/consent", + headers: { ...form, accept, ...(cookie ? { cookie } : {}) }, + payload: new URLSearchParams({ state, decision }).toString(), + }); +} + +function callback(app: FastifyInstance, state: string, cookie: string, query: string, accept = "application/json") { + return app.inject({ + method: "GET", + url: `/v1/oauth/joystick/callback?state=${encodeURIComponent(state)}&${query}`, + headers: { cookie, accept }, + }); +} + +/** Ask, accept, and complete as Joystick user `user`; returns the callback's JSON. */ +async function grantAs(app: FastifyInstance, user: string) { + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + const go = await answer(app, state, "continue", cookie); + expect(go.statusCode).toBe(302); + const done = await callback(app, state, cookie, `code=code-${user}`); + expect(done.statusCode).toBe(201); + return done.json() as { accessToken: string; consentReceiptId: string; account: { id: string }; session: { accountId: string } }; +} + +const bearer = (token: string) => ({ authorization: `Bearer ${token}` }); +const grantsOf = async (app: FastifyInstance, token: string) => + (await app.inject({ method: "GET", url: "/v1/me/grants", headers: bearer(token) })).json() as { grants: Array>; receipts: Array> }; +const resolveCredential = (app: FastifyInstance, accountId: string) => + app.inject({ method: "POST", url: "/v1/apps/streampixels/managed-credentials/resolve", headers: secret, payload: { accountId, provider: "joystick" } }); + +describe("the ask", () => { + it("launch shows a Heimdall page naming app, provider, scopes and custody, and does not redirect", async () => { + const { app } = await newApp(); + const { page } = await seeAsk(app, await startConnect(app)); + expect(page.headers.location).toBeUndefined(); + for (const needle of ["StreamPixels", "Joystick", ...defaultScopes, "refresh token", "streampixels.gamecult.org", "Continue to Joystick", "No, return to the app"]) { + expect(page.body).toContain(needle); } + expect(page.body).not.toContain(" { - // POST the decline form from the launch page with the binding cookie; - // expect result {error: "consent_refused", by: "viewer"}, an audit event - // "consent_refused", no managed credential row, and a second launch refused. - expect.fail("not built"); + it("viewing the ask claims nothing: the launch is still spendable once after any number of views", async () => { + const { app } = await newApp(); + const state = await startConnect(app); + await seeAsk(app, state); + const { cookie } = await seeAsk(app, state); + expect((await answer(app, state, "continue", cookie)).statusCode).toBe(302); + const again = await answer(app, state, "continue", cookie, "application/json"); + expect(again.statusCode).toBe(400); + expect(again.json()).toEqual({ error: "state_already_launched" }); }); - it("a provider access_denied is consent_refused by provider, distinct from provider_error", async () => { - expect.fail("not built"); + it("Continue sends exactly the scopes the page listed", async () => { + const { app } = await newApp(); + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + const go = await answer(app, state, "continue", cookie); + expect(go.statusCode).toBe(302); + const target = new URL(go.headers.location as string); + expect(target.origin).toBe("https://joystick.tv"); + expect(target.searchParams.get("scope")).toBe(defaultScopes.join(" ")); }); - it("a granted completion writes one receipt with asked and granted scopes and the page digest", async () => { - expect.fail("not built"); + it("a flow with no custody (sign-in through an identity provider) gets no ask and redirects as before", async () => { + const { app } = await newApp(); + const start = await app.inject({ + method: "POST", + url: "/v1/oauth/twitch/start", + headers: secret, + payload: { appSlug: "streampixels", mode: "sign_in", returnTo: "https://streampixels.gamecult.org/", handoff: { kind: "browser_completion" } }, + }); + expect(start.statusCode).toBe(201); + const launch = await app.inject({ method: "GET", url: `/v1/oauth/twitch/launch?state=${encodeURIComponent(stateOf(start.json()))}`, headers: { accept: "text/html" } }); + expect(launch.statusCode).toBe(302); }); - it("the receipt page is readable only by the browser or account that consented, and revoke stamps revokedAt without editing the grant row", async () => { - expect.fail("not built"); + it("an answer without the cookie the ask set is refused and spends nothing", async () => { + const { app } = await newApp(); + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + for (const decision of ["continue", "decline"] as const) { + const stranger = await answer(app, state, decision, undefined, "application/json"); + expect(stranger.statusCode, decision).toBe(400); + expect(stranger.json(), decision).toEqual({ error: "state_not_bound" }); + } + expect((await answer(app, state, "continue", cookie)).statusCode).toBe(302); + }); + + it("the consent route refuses a flow that has no ask", async () => { + const { app } = await newApp(); + const start = await app.inject({ + method: "POST", + url: "/v1/oauth/twitch/start", + headers: secret, + payload: { appSlug: "streampixels", mode: "sign_in", returnTo: "https://streampixels.gamecult.org/", handoff: { kind: "browser_completion" } }, + }); + const state = stateOf(start.json()); + const response = await app.inject({ + method: "POST", + url: "/v1/oauth/twitch/consent", + headers: form, + payload: new URLSearchParams({ state, decision: "continue" }).toString(), + }); + expect(response.statusCode).toBe(400); + expect(response.json()).toEqual({ error: "consent_not_required" }); + }); +}); + +describe("the wording digest", () => { + const ask: ConsentAsk = { appSlug: "streampixels", provider: "joystick", scopes: ["identity:read"], returnOrigin: "https://streampixels.gamecult.org" }; + it("is the sha-256 of the lines shown, and moves with the app, provider, scopes and origin", () => { + expect(consentDigest(ask)).toBe(createHash("sha256").update(consentLines(ask).join("\n"), "utf8").digest("hex")); + const variants: ConsentAsk[] = [ + { ...ask, appSlug: "bifrost" }, + { ...ask, provider: "twitch" }, + { ...ask, scopes: ["identity:read", "chat:read"] }, + { ...ask, returnOrigin: "https://elsewhere.example" }, + ]; + for (const variant of variants) expect(consentDigest(variant)).not.toBe(consentDigest(ask)); + }); +}); + +describe("refusal", () => { + it("declining yields consent_refused by the viewer, stores nothing, and spends the state", async () => { + const { app, store } = await newApp(); + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + const no = await answer(app, state, "decline", cookie, "application/json"); + expect(no.statusCode).toBe(400); + expect(no.json()).toMatchObject({ error: "consent_refused", by: "viewer", provider: "joystick" }); + + // Nothing launches or completes afterwards, and nothing was kept. + expect((await answer(app, state, "continue", cookie, "application/json")).json()).toEqual({ error: "state_already_launched" }); + expect((await callback(app, state, cookie, "code=code-a")).json()).toEqual({ error: "state_already_used" }); + expect(await store.findStoredLinkedIdentity("joystick", "joy-a")).toBeNull(); + const events = [...(store as unknown as { auditEvents: Map }).auditEvents.values()]; + expect(events.filter((event) => event.eventType === "consent_refused").map((event) => event.eventPayloadJson)).toEqual([ + { provider: "joystick", mode: "connect", by: "viewer" }, + ]); + }); + + it("the browser sees a 'Not Connected' page, not an authentication failure", async () => { + const { app } = await newApp(); + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + const no = await answer(app, state, "decline", cookie); + expect(no.statusCode).toBe(200); + expect(no.body).toContain("Not Connected"); + expect(no.body).toContain("consent_refused"); + expect(no.body).not.toContain("Authentication Failed"); + }); + + it("an access_denied from the provider is consent_refused by the provider, distinct from provider_error", async () => { + const { app, store } = await newApp(); + const denied = await newFlow(app); + const response = await callback(app, denied.state, denied.cookie, "error=access_denied"); + expect(response.statusCode).toBe(400); + expect(response.json()).toMatchObject({ error: "consent_refused", by: "provider" }); + + const faulty = await newFlow(app); + expect((await callback(app, faulty.state, faulty.cookie, "error=server_error")).json().error).toBe("provider_error"); + const events = [...(store as unknown as { auditEvents: Map }).auditEvents.values()]; + expect(events.filter((event) => event.eventType === "consent_refused")).toHaveLength(1); + }); + + it("a backend_callback app is told, with who refused", async () => { + const callbackUrl = "https://streampixels.gamecult.org/api/heimdall/callback"; + const { app } = await newApp({ callbacks: [callbackUrl] }); + const delivered: Array> = []; + vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => { + delivered.push(JSON.parse(String(init?.body))); + return new Response("ok", { status: 200 }); + }); + const handoff = { kind: "backend_callback", callbackUrl, attemptId: "attempt-1" }; + + const byViewer = await startConnect(app, handoff); + const { cookie } = await seeAsk(app, byViewer); + await answer(app, byViewer, "decline", cookie); + const byProvider = await startConnect(app, handoff); + const second = await seeAsk(app, byProvider); + await answer(app, byProvider, "continue", second.cookie); + await callback(app, byProvider, second.cookie, "error=access_denied"); + + expect(delivered.map((payload) => [payload.status, payload.error, payload.by])).toEqual([ + ["error", "consent_refused", "viewer"], + ["error", "consent_refused", "provider"], + ]); + }); +}); + +async function newFlow(app: FastifyInstance) { + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + expect((await answer(app, state, "continue", cookie)).statusCode).toBe(302); + return { state, cookie }; +} + +describe("the receipt", () => { + it("a granted completion writes one receipt with asked and granted scopes and the digest of the wording shown", async () => { + const { app, store } = await newApp({ granted: ["identity:read", "stream:read"] }); + const done = await grantAs(app, "a"); + const receipts = await store.listConsentReceipts(done.account.id); + expect(receipts).toHaveLength(1); + const ask: ConsentAsk = { appSlug: "streampixels", provider: "joystick", scopes: defaultScopes, returnOrigin: "https://streampixels.gamecult.org" }; + expect(receipts[0]).toMatchObject({ + id: done.consentReceiptId, + kind: "grant", + accountId: done.account.id, + appSlug: "streampixels", + provider: "joystick", + scopesAsked: defaultScopes, + scopesGranted: ["identity:read", "stream:read"], + consentPageDigest: consentDigest(ask), + }); + }); + + it("a refusal leaves no receipt", async () => { + const { app, store } = await newApp(); + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + await answer(app, state, "decline", cookie); + expect(await store.listConsentReceipts("anyone")).toEqual([]); + expect((await store.findStoredLinkedIdentity("joystick", "joy-a"))).toBeNull(); + }); + + it("the success page names the receipt", async () => { + const { app } = await newApp(); + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + await answer(app, state, "continue", cookie); + const page = await callback(app, state, cookie, "code=code-a", "text/html"); + expect(page.statusCode).toBe(200); + expect(page.body).toMatch(/receipt [0-9a-f-]{36}/); + }); +}); + +describe("my grants", () => { + it("is closed to anyone without a live Heimdall access token", async () => { + const { app } = await newApp(); + for (const headers of [{}, bearer("not-a-token")]) { + const response = await app.inject({ method: "GET", url: "/v1/me/grants", headers }); + expect(response.statusCode).toBe(401); + expect(response.json().error).toBe("sign_in_required"); + } + const link = await app.inject({ method: "POST", url: "/v1/me/grants/link" }); + expect(link.statusCode).toBe(401); + const revoke = await app.inject({ method: "POST", url: "/v1/me/grants/x/revoke" }); + expect(revoke.statusCode).toBe(401); + }); + + it("lists the signed-in account's grants and receipts, and no one else's", async () => { + const { app } = await newApp(); + const a = await grantAs(app, "a"); + const b = await grantAs(app, "b"); + const mine = await grantsOf(app, a.accessToken); + expect(mine.grants).toHaveLength(1); + expect(mine.grants[0]).toMatchObject({ id: a.consentReceiptId, status: "active", provider: "joystick", appSlug: "streampixels", scopesGranted: ["identity:read", "stream:read"] }); + expect(JSON.stringify(mine)).not.toContain(b.consentReceiptId); + expect(mine.receipts.map((receipt) => receipt.accountId)).toEqual([a.account.id]); + }); + + it("revoke takes effect on the next token use, edits no row, and receipts the revocation", async () => { + const { app, store } = await newApp(); + const a = await grantAs(app, "a"); + expect((await resolveCredential(app, a.account.id)).statusCode).toBe(200); + const before = await store.listConsentReceipts(a.account.id); + + const revoke = await app.inject({ method: "POST", url: `/v1/me/grants/${a.consentReceiptId}/revoke`, headers: bearer(a.accessToken) }); + expect(revoke.statusCode).toBe(200); + expect(revoke.json().revoked).toEqual([a.consentReceiptId]); + + const next = await resolveCredential(app, a.account.id); + expect(next.statusCode).toBe(410); + expect(next.json().error).toBe("managed_credential_revoked"); + + const after = await store.listConsentReceipts(a.account.id); + expect(after).toHaveLength(2); + expect(after[0]).toEqual(before[0]); + expect(after[1]).toMatchObject({ kind: "revocation", revokesReceiptId: a.consentReceiptId, accountId: a.account.id }); + const view = (await grantsOf(app, a.accessToken)).grants[0]!; + expect(view).toMatchObject({ status: "revoked", revocationReceiptId: after[1]!.id }); + expect(view.revokedAt).toBe(after[1]!.createdAt); + }); + + it("revoke is the owner's alone: another account's grant id is not found and its credential is untouched", async () => { + const { app } = await newApp(); + const a = await grantAs(app, "a"); + const b = await grantAs(app, "b"); + const attempt = await app.inject({ method: "POST", url: `/v1/me/grants/${a.consentReceiptId}/revoke`, headers: bearer(b.accessToken) }); + expect(attempt.statusCode).toBe(404); + expect((await resolveCredential(app, a.account.id)).statusCode).toBe(200); + expect((await resolveCredential(app, b.account.id)).statusCode).toBe(200); + }); + + it("revoking twice changes nothing the second time", async () => { + const { app, store } = await newApp(); + const a = await grantAs(app, "a"); + const url = `/v1/me/grants/${a.consentReceiptId}/revoke`; + await app.inject({ method: "POST", url, headers: bearer(a.accessToken) }); + const second = await app.inject({ method: "POST", url, headers: bearer(a.accessToken) }); + expect(second.statusCode).toBe(200); + expect(second.json().revoked).toEqual([]); + expect(await store.listConsentReceipts(a.account.id)).toHaveLength(2); + }); + + it("a fresh connection after a revoke is a new grant, live again, and the old one stays revoked", async () => { + const { app } = await newApp(); + const first = await grantAs(app, "a"); + await app.inject({ method: "POST", url: `/v1/me/grants/${first.consentReceiptId}/revoke`, headers: bearer(first.accessToken) }); + const second = await grantAs(app, "a"); + expect(second.consentReceiptId).not.toBe(first.consentReceiptId); + expect((await resolveCredential(app, second.account.id)).statusCode).toBe(200); + const grants = (await grantsOf(app, second.accessToken)).grants; + expect(grants.map((grant) => [grant.id, grant.status])).toEqual([ + [first.consentReceiptId, "revoked"], + [second.consentReceiptId, "active"], + ]); + }); + + it("a browser with no session opens the page from a minted link and revokes with one form post", async () => { + const { app } = await newApp(); + const a = await grantAs(app, "a"); + const link = await app.inject({ method: "POST", url: "/v1/me/grants/link", headers: bearer(a.accessToken) }); + expect(link.statusCode).toBe(201); + const url = new URL(link.json().url as string); + const page = await app.inject({ method: "GET", url: `${url.pathname}${url.search}`, headers: { accept: "text/html" } }); + expect(page.statusCode).toBe(200); + expect(page.body).toContain(a.consentReceiptId); + expect(page.body).toContain("Take this back"); + expect(page.body).not.toContain(" { + const { app } = await newApp(); + const a = await grantAs(app, "a"); + for (const t of [a.accessToken, "garbage", ""]) { + const response = await app.inject({ method: "GET", url: `/v1/me/grants?t=${encodeURIComponent(t)}` }); + expect(response.statusCode, t).toBe(401); + const revoke = await app.inject({ + method: "POST", + url: `/v1/me/grants/${a.consentReceiptId}/revoke`, + headers: form, + payload: new URLSearchParams({ t }).toString(), + }); + expect(revoke.statusCode, t).toBe(401); + } + expect((await resolveCredential(app, a.account.id)).statusCode).toBe(200); }); }); diff --git a/tests/oauth-flow.ts b/tests/oauth-flow.ts index 1a7fbf4..b85b2ce 100644 --- a/tests/oauth-flow.ts +++ b/tests/oauth-flow.ts @@ -117,7 +117,18 @@ export function setCookieOf(response: { headers: Record }): str async function followLaunch(app: FastifyInstance, state: string): Promise { const provider = decodeJwt(state).payload.provider as string; - const response = await app.inject({ method: "GET", url: `/v1/oauth/${provider}/launch?state=${encodeURIComponent(state)}` }); + let response = await app.inject({ method: "GET", url: `/v1/oauth/${provider}/launch?state=${encodeURIComponent(state)}` }); + if (response.statusCode === 200) { + // Heimdall's ask (managed custody): the person says Continue, with the cookie the ask set. + const asked = setCookieOf(response).find((value) => value.startsWith("__Host-heimdall-oauth-")); + expect(asked, "the ask sets the binding cookie").toBeDefined(); + response = await app.inject({ + method: "POST", + url: `/v1/oauth/${provider}/consent`, + headers: { "content-type": "application/x-www-form-urlencoded", cookie: (asked as string).split(";")[0] as string }, + payload: new URLSearchParams({ state, decision: "continue" }).toString(), + }); + } expect(response.statusCode, "launch").toBe(302); const set = setCookieOf(response).find((value) => value.startsWith("__Host-heimdall-oauth-")); expect(set, "launch sets the binding cookie").toBeDefined(); @@ -143,8 +154,5 @@ export async function launchWithRedirect(app: FastifyInstance, start: StartBody) /** The provider URL a browser is redirected to once it has followed authorizationUrl through the launch hop. */ export async function providerRedirect(app: FastifyInstance, start: StartBody): Promise { - const url = new URL(start.authorizationUrl); - const response = await app.inject({ method: "GET", url: `${url.pathname}${url.search}` }); - expect(response.statusCode, "launch").toBe(302); - return new URL(response.headers.location as string); + return (await followLaunch(app, stateOf(start))).providerUrl; } diff --git a/tests/oauth-state-binding.test.ts b/tests/oauth-state-binding.test.ts index 9f576e8..1bffc19 100644 --- a/tests/oauth-state-binding.test.ts +++ b/tests/oauth-state-binding.test.ts @@ -299,14 +299,15 @@ describe("OAuth state binding", () => { expect(await claim("a", 1_000_000 + 30_000)).toBe(true); }); - it("a provider error from the launching browser still denies the attempt, once", async () => { + it("a provider refusal from the launching browser still denies the attempt, once", async () => { const app = await newApp(); const start = await bifrostStart(app); const victim = await launchFlow(app, start); const denied = await callback(app, victim.state, victim.cookie, "error=access_denied"); expect(denied.statusCode).toBe(400); - expect(denied.json().error).toBe("provider_error"); + expect(denied.json().error).toBe("consent_refused"); + expect(denied.json().by).toBe("provider"); const replay = await callback(app, victim.state, victim.cookie, "error=access_denied"); expect(replay.json()).toEqual({ error: "state_already_used" }); }); diff --git a/tests/store.test.ts b/tests/store.test.ts index f17a834..684aa41 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -270,9 +270,10 @@ describe("PostgresStore.checkSchema", () => { "oauth_state_uses", "capability_grants", "entitlement_snapshots", + "consent_receipts", "audit_events", ]); - expect(REQUIRED_COLUMNS).toHaveLength(101); + expect(REQUIRED_COLUMNS).toHaveLength(111); expect(REQUIRED_COLUMNS).toEqual( expect.arrayContaining([ { table: "auth_completions", column: "code", type: "TEXT", nullable: false }, @@ -283,7 +284,7 @@ describe("PostgresStore.checkSchema", () => { { table: "auth_completions", column: "attempt_id", type: "TEXT", nullable: true }, ]) ); - expect(REQUIRED_KEYS).toHaveLength(14); + expect(REQUIRED_KEYS).toHaveLength(15); expect(REQUIRED_KEYS).toEqual( expect.arrayContaining([ { table: "linked_identities", columns: "provider,provider_user_id", predicate: "" }, @@ -418,6 +419,9 @@ async function exerciseStore(store: PostgresStore): Promise> { expect(await s.claimOAuthStateUse(stateUse)).toBe(true); expect(await s.claimOAuthStateUse(stateUse)).toBe(false); expect(await s.claimOAuthStateUse({ ...stateUse, phase: "callback" })).toBe(true); + const grant = await s.createConsentReceipt({ kind: "grant", accountId: account.id, appSlug: "streampixels", provider: "joystick", createdAt: now, scopesAsked: ["a", "b"], scopesGranted: ["a"], consentPageDigest: "d" }); + await s.createConsentReceipt({ kind: "revocation", accountId: account.id, appSlug: "streampixels", provider: "joystick", createdAt: later, revokesReceiptId: grant.id }); + expect((await s.listConsentReceipts(account.id)).map((r) => r.kind)).toEqual(["grant", "revocation"]); await s.createAuditEvent({ eventType: "probe", eventPayloadJson: {}, createdAt: now }); return called; } From 48207268d08c8c01428d648a2e5bb1bb34af3716 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sun, 8 Nov 2026 13:24:48 +0000 Subject: [PATCH 12/63] Consent flow doc: steward rulings and the built design; pin repeat-revoke Co-Authored-By: Claude Sonnet 5.5 --- docs/joystick-consent-flow.md | 164 +++++++++++++++++++++++---------- tests/joystick-consent.test.ts | 2 + 2 files changed, 117 insertions(+), 49 deletions(-) diff --git a/docs/joystick-consent-flow.md b/docs/joystick-consent-flow.md index 498c8e4..86746ea 100644 --- a/docs/joystick-consent-flow.md +++ b/docs/joystick-consent-flow.md @@ -1,8 +1,10 @@ -# Joystick sign-in and consent: what exists, what is missing, a draft flow +# Joystick sign-in and consent: what was missing, and the flow that fills it -Status: DRAFT design, no code. Source-grounded at `fefd2dd` (main). Follow-up -`heimdall-body:follow_up:chat-s3124-3129`. Not for merge until a Heimdall -steward rules on the open questions below. +Status: built (sections 3-6 describe the code on this branch); sections 1-2 are +the state of `fefd2dd` (main) that motivated it. Follow-up +`heimdall-body:follow_up:chat-s3124-3129`, built under +`heimdall-body:follow_up:chat-mind-20261108T131253147Z-t1`. The steward's rulings +on the five open questions are in section 4. ## 1. What a viewer sees today @@ -59,65 +61,129 @@ person in the browser: | Receipt | Operator audit rows only | The viewer cannot audit what was agreed, when, or revoke it. | | Viewer vs creator | The `connect` binding proves a binding exists, not that the browser's owner is the creator (`joystick:follow_up:connect-start-needs-app-auth`) | Consent from the wrong person is not consent. | -## 3. Draft consent flow +## 3. The consent flow -Applies to any Joystick completion (creator connect now; viewer sign-in when -the public bot lands) and, if ruled, to every provider whose state carries -`managed_credential`. +Applies to every completion `callbackMint` calls `custody_only`: a managed +creator connection (Joystick today; Twitch and YouTube on StreamPixels when +they are connected rather than signed in). Viewer sign-in through an identity +provider is unchanged. -### 3.1 The ask (visible, before the redirect) +### 3.1 The ask -`GET /v1/oauth/:provider/launch` stops answering `302`. It renders a Heimdall -page, **after** the state is verified but **before** the use is claimed, with: +`GET /v1/oauth/:provider/launch` renders a Heimdall page (`src/consent.ts`) +instead of answering `302`, after the state verifies and before any use is +claimed. The page names the app and the origin the person returns to, the +provider and the exact scopes Heimdall will send (`authorizationScopes`, the +same function that builds the authorization URL), what Heimdall keeps (an +encrypted refresh token and access token, until the person takes it back or the +provider ends it), what the app receives, and how to take it back. It carries +two POST forms to `/v1/oauth/:provider/consent`, **Continue to Joystick** and +**No, return to the app**, and runs no script. It sets the binding cookie, so +either answer can only come from the browser that was shown the ask; an answer +without the cookie is `state_not_bound` and spends nothing. Viewing the ask +claims nothing. Continue claims the launch use and answers `302`. -- the app by display name and return origin; -- the provider and the exact scope list that will be requested; -- what Heimdall keeps (a refresh token, encrypted, rotating) versus what the - app receives (no token; a claim) and for how long; -- two forms, both POST, CSRF-bound by the existing binding cookie: - **Continue to Joystick** and **No, return to the app**; -- a link to the receipt of any earlier consent for this account and app. - -Only Continue claims the launch use and answers `302`. The page is plain -server-rendered HTML with no script, matching the handoff page's escape rule. +What the app receives, stated as the code does it: not a claim. The app +backend can call `managed-credentials/resolve` and receive the current access +token; it never receives the refresh token. The earlier draft said the app +receives "no token"; that was wrong and the page does not say it. ### 3.2 Typed refusal -**No** (and a provider `access_denied` on return) produces a distinct result -`consent_refused` with `{provider, app, mode, by: "viewer" | "provider"}`: -delivered to the app by the same handoff channel as any result, written as an -audit event `consent_refused`, no credential stored, state consumed. A provider -failure stays `provider_error`. The app is told not to ask again in the same -session; whether it may ask later is the app's rule, not Heimdall's. +A decline, and a provider `error=access_denied` on any provider, produce the +result `consent_refused` with `by: "viewer" | "provider"`: an audit event +`consent_refused` (provider, mode, by; no account, no person), the browser +attempt denied with `denialCode consent_refused`, both uses of the state spent, +a `backend_callback` app told with the same payload, a "Not Connected" page in +the browser, and `400 {error: "consent_refused", by}` as JSON. No credential is +stored and no receipt is written. Every other provider error stays +`provider_error`. This changes the `access_denied` answer for every provider, +including Bifrost's and Repixelizer's sign-in; see the PR for the contract note. ### 3.3 Receipt -On a granted completion Heimdall writes one `consent_receipt` row: receipt id -(random, non-guessable), account (or creator target), app, provider, scopes -asked, scopes granted, what Heimdall retains, `grantedAt`, `consentPageDigest` -(hash of the exact text shown, so a later wording change is visible), and a -`revokedAt` slot. The handoff page shows the receipt id and a "View receipt" link. +On a granted `custody_only` completion Heimdall writes one `consent_receipts` +row of kind `grant`: id (random), account, app, provider, scopes asked, scopes +granted (as the provider returned them), `consentPageDigest` (sha-256 of the +lines the page showed, so a wording change is visible), `createdAt`. The id +reaches the app (`consentReceiptId` in the completion and backend payloads) and +the person (the handoff page). -`GET /v1/receipts/:id` (viewer-bound by the same cookie or by the account's -access token) shows the row and offers **Revoke**, which calls the existing -managed-credential revocation and stamps `revokedAt`. Revoke is itself receipted. -Receipts are append-only; a revocation is a second row, not an edit. +Receipts are append-only: the store role has `SELECT` and `INSERT` on the table +and nothing else. A revocation is a second row of kind `revocation` naming the +grant it takes back; a grant is live exactly when no revocation names it. The +draft's `revokedAt` slot is gone for that reason. -## 4. Open questions for the steward +### 3.4 My grants -1. Who gets the ask: every provider, or only `managed_credential` ones? (Recommend: only managed custody, where Heimdall holds something beyond a login.) -2. Where does the receipt live: Heimdall store as a new document, or the existing audit table with a new `eventType`? (Recommend: new typed document; the audit table is operator-shaped and has no viewer read path.) -3. Viewer identity for the receipt page when the viewer has no Heimdall session yet (a first-time creator connect). Binding cookie only, or require sign-in first? -4. Does `consent_refused` need to reach a backend callback app, or only the browser handoff? -5. Wording ownership: the page text is legal-adjacent (CultCoin legal research is a sibling thread); who signs the copy? +Signed in means a live Heimdall access token for any app (`Authorization: +Bearer`), or a page link minted from one. -## 5. Out of scope here +- `GET /v1/me/grants`: every grant and receipt of the account. `Accept: + text/html` gets the page, one **Take this back** form per live grant; anything + else gets `{grants, receipts}`. +- `POST /v1/me/grants/link` (bearer): `{url}` to the page, valid ten minutes. + The token is signed, purpose-bound (`heimdall_grants_page`), stateless, and + opens only this page and its revoke forms. This is how a browser that holds no + session gets in; Heimdall sets no new cookie and stores nothing for it. +- `POST /v1/me/grants/:id/revoke` (bearer, or the page token in the form): + strips the stored tokens from the credential, then writes a revocation row + for every live grant on that credential. The credential is one row per account + and provider, whichever app asked, so taking it back ends every grant resting + on it. The next `managed-credentials/resolve` answers `410 + managed_credential_revoked`; nothing else needs to learn of it. Revoking a + revoked grant changes nothing. Another account's grant id is `404`. -Enabling Joystick in `identityProviders`; fixing `connect-start-needs-app-auth`; -Postgres schema/migration for the receipt; any deploy. Each needs its own cut. +Heimdall can delete its copy; it cannot withdraw the permission at the +provider, and the page says so. -## 6. Test sketch +## 4. The steward's rulings -`tests/joystick-consent.test.ts` holds the behaviours above as skipped tests -(they cannot pass until the cut is built). Unrun: the author's workspace could -not install dependencies, so treat the file as a sketch to be typechecked. +Each ruling picks the answer that gives the person the most agency and leaves +the least stored. + +1. **Who gets the ask: managed custody only.** Where Heimdall holds a credential + the person cannot see and an app can use, the person is asked and given a + receipt. A login is already asked by the provider's own screen, and a receipt + per login would store a row per sign-in for no agency the provider's screen + does not give. The line is `callbackMint === "custody_only"`, so it needs no + second list to keep in step with the profiles. +2. **The receipt is a new typed table, `consent_receipts`.** The audit table is + operator-shaped and has no read path for the person; a viewer-readable + record in it would make every audit row a potential disclosure. The table + holds ids, scopes and a digest: no IP address, no user agent, no page text. + Refusals leave no receipt, only the anonymous audit row. +3. **Viewer identity: sign-in, not the cookie.** The binding cookie dies with + the state and proves only that a browser launched a flow; it is not an + account. The receipt page and revoke require a live access token or a + ten-minute link minted from one. The cost is that a first-time creator must + hold the session the completion returned to the app; the app mints the link. + The alternative, a new long-lived Heimdall cookie, would store a session for + every person who merely looked. +4. **`consent_refused` reaches a backend callback app.** An app that started the + attempt and is waiting must be told, or it polls to expiry and cannot tell + a person's no from a fault. The person's no is also not held against them: + Heimdall stores nothing and sets no cooldown; whether and when to ask again + is the app's rule. +5. **Wording: derived, not authored.** The text is generated from facts the code + holds and states nothing the code does not do; it is a constant in + `src/consent.ts` and its digest rides every receipt. Legal review of the + wording (the CultCoin legal thread) may only narrow it, and any change moves + the digest. Until that review lands the copy is Heimdall's, signed by the + steward. + +## 5. Out of scope + +Enabling Joystick in `identityProviders`; fixing +`joystick:follow_up:connect-start-needs-app-auth`; revoking at the provider +(Joystick offers no revocation call Heimdall uses); retention or deletion of +consent receipts and of the audit rows; consent for the creator's audience. + +## 6. Tests + +`tests/joystick-consent.test.ts` holds one behaviour per rule above. Rules were +checked by mutation, each mutant run on its own with a 300 s limit under an 8 GB +address-space cap (the PR lists them). The Postgres statements for +`consent_receipts` are exercised by `tests/store.test.ts` against the fake pool +and, when `HEIMDALL_TEST_PG_ADMIN_URL` is set, against a live database +(`scripts/test-live-pg.sh`); the live run was not possible where this was built. diff --git a/tests/joystick-consent.test.ts b/tests/joystick-consent.test.ts index 3d4691f..f674f12 100644 --- a/tests/joystick-consent.test.ts +++ b/tests/joystick-consent.test.ts @@ -382,6 +382,8 @@ describe("my grants", () => { expect(second.statusCode).toBe(200); expect(second.json().revoked).toEqual([]); expect(await store.listConsentReceipts(a.account.id)).toHaveLength(2); + const events = [...(store as unknown as { auditEvents: Map }).auditEvents.values()]; + expect(events.filter((event) => event.eventType === "consent_revoked")).toHaveLength(1); }); it("a fresh connection after a revoke is a new grant, live again, and the old one stays revoked", async () => { From 71ce9c16e40424745f33a8a3753a47ba4cdada06 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sun, 8 Nov 2026 13:30:39 +0000 Subject: [PATCH 13/63] Consent review fixes: ask-only cookie, fixed-expiry grants links, wording carried to the receipt, one revocation per grant The ask sets its own cookie and no launch binding; Continue sets the binding and carries the exact text shown into it; the receipt stores that text and its hash. Grants-page form tokens keep the link's expiry. Revocations are unique per grant and revoke reports only what it wrote. access_denied's attempt denial code is pinned for Bifrost and Repixelizer. Co-Authored-By: Claude Sonnet 5.5 --- src/app.ts | 161 +++++++++++++++++++++++------- src/consent.ts | 27 ++++- src/store/in-memory.ts | 8 +- src/store/postgres.ts | 21 +++- src/store/schema.ts | 6 ++ src/store/types.ts | 9 +- tests/consent-drift.test.ts | 65 ++++++++++++ tests/joystick-consent.test.ts | 131 ++++++++++++++++++++---- tests/oauth-flow.ts | 4 +- tests/oauth-state-binding.test.ts | 32 ++++++ tests/store.test.ts | 20 +++- 11 files changed, 413 insertions(+), 71 deletions(-) create mode 100644 tests/consent-drift.test.ts diff --git a/src/app.ts b/src/app.ts index c4d8e93..c6c7c68 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,4 +1,5 @@ import { createHmac, randomUUID } from "node:crypto"; +import { deflateRawSync, inflateRawSync } from "node:zlib"; import cookie from "@fastify/cookie"; import cors from "@fastify/cors"; import Fastify, { type FastifyError, type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify"; @@ -26,7 +27,7 @@ import { import { issueAccessClaim, type IssueAccessClaimInput } from "./claims.js"; import { builtInAppProfiles, getAppProfile, isAllowedReturnOrigin, serializeAppProfile, admitsProviderForMode, callbackMint } from "./app-profiles.js"; import { renderBrowserHandoffPage } from "./browser-handoff.js"; -import { consentDigest, grantViews, GRANTS_PATH, renderConsentPage, renderGrantsPage, type ConsentAsk } from "./consent.js"; +import { consentText, digestOfText, grantViews, GRANTS_PATH, renderConsentPage, renderGrantsPage, type ConsentAsk } from "./consent.js"; import { type HeimdallConfig, loadConfig } from "./config.js"; import { createTokenCustody, type TokenCustody } from "./custody.js"; import { grantFact } from "./facts.js"; @@ -252,14 +253,74 @@ function oauthBindingCookieName(jti: string): string { function signOAuthBinding( config: HeimdallConfig, keys: ReturnType, - state: OAuthStatePayload + state: OAuthStatePayload, + shownText?: string ): string { return signJwt( - { typ: oauthBindingType, iss: config.issuer, jti: state.jti, iat: nowEpochSeconds(), exp: state.exp }, + { + typ: oauthBindingType, + iss: config.issuer, + jti: state.jti, + iat: nowEpochSeconds(), + exp: state.exp, + // The wording the person agreed to, carried from the ask to the receipt. + ...(shownText === undefined ? {} : { ct: deflateRawSync(shownText).toString("base64url") }), + }, keys ); } +const consentAskType = "heimdall_consent_ask"; + +function consentAskCookieName(jti: string): string { + return `__Host-heimdall-ask-${jti}`; +} + +/** + * The ask's own cookie. It proves a browser was shown the ask and carries the + * exact text shown; only Continue and No accept it. It is not the launch + * binding: that is set when Continue claims the launch, so that merely opening + * the launch URL never makes a browser the state's owner. + */ +function signConsentAsk(config: HeimdallConfig, keys: ReturnType, state: OAuthStatePayload, shownText: string): string { + return signJwt( + { typ: consentAskType, iss: config.issuer, jti: state.jti, iat: nowEpochSeconds(), exp: state.exp, ct: deflateRawSync(shownText).toString("base64url") }, + keys + ); +} + +/** The text a held cookie of the given type carries, or null when the cookie is absent, foreign, expired or carries none. */ +function cookieConsentText( + config: HeimdallConfig, + keys: ReturnType, + token: string | undefined, + type: string, + state: OAuthStatePayload +): string | null { + if (!token) return null; + const verification = verifyJwt(token, keys.publicKey); + if (!verification.valid) return null; + const { typ, iss, jti, exp, ct } = verification.payload; + if (typ !== type || iss !== config.issuer || jti !== state.jti || typeof exp !== "number" || exp <= nowEpochSeconds() || typeof ct !== "string") { + return null; + } + try { + return inflateRawSync(Buffer.from(ct, "base64url")).toString("utf8"); + } catch { + return null; + } +} + +function setConsentAskCookie(reply: FastifyReply, state: OAuthStatePayload, value: string, maxAgeSeconds: number): void { + reply.setCookie(consentAskCookieName(state.jti), value, { + path: "/", + secure: true, + httpOnly: true, + sameSite: "lax", + maxAge: Math.max(0, maxAgeSeconds), + }); +} + function oauthBindingHolds( config: HeimdallConfig, keys: ReturnType, @@ -827,18 +888,27 @@ const grantsPageTokenType = "heimdall_grants_page"; const grantsPageTokenTtlSeconds = 600; /** A short, purpose-bound proof of a signed-in account, so the grants page can be opened and its forms posted by a browser that holds no session. */ -function signGrantsPageToken(config: HeimdallConfig, keys: ReturnType, accountId: string): string { - const iat = nowEpochSeconds(); - return signJwt({ typ: grantsPageTokenType, iss: config.issuer, account_id: accountId, iat, exp: iat + grantsPageTokenTtlSeconds }, keys); +function signGrantsPageToken( + config: HeimdallConfig, + keys: ReturnType, + accountId: string, + exp: number = nowEpochSeconds() + grantsPageTokenTtlSeconds +): string { + return signJwt({ typ: grantsPageTokenType, iss: config.issuer, account_id: accountId, iat: nowEpochSeconds(), exp }, keys); } -function grantsPageTokenAccount(config: HeimdallConfig, keys: ReturnType, token: unknown): string | null { +/** The account and expiry a page token proves. A page's own forms are signed to this same expiry, so a link is never renewed by being used. */ +function grantsPageTokenAccount( + config: HeimdallConfig, + keys: ReturnType, + token: unknown +): { accountId: string; exp: number } | null { if (typeof token !== "string") return null; const verification = verifyJwt(token, keys.publicKey); if (!verification.valid) return null; const { typ, iss, account_id: accountId, exp } = verification.payload; return typ === grantsPageTokenType && iss === config.issuer && typeof accountId === "string" && typeof exp === "number" && exp > nowEpochSeconds() - ? accountId + ? { accountId, exp } : null; } @@ -1239,7 +1309,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { + const beginProviderRedirect = async (request: FastifyRequest, reply: FastifyReply, state: OAuthStatePayload, rawState: string, shownText?: string) => { const clientId = config.providers[state.provider].clientId; if (!clientId) { return providerNotConfigured(reply, state); @@ -1256,7 +1326,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise => - (await resolveAccessAccount({ config, keys, store }, request.headers.authorization)) ?? - grantsPageTokenAccount(config, keys, pageToken); + /** The signed-in account, and the expiry the page's own forms get: a bearer starts a fresh window, a page link only passes on the one it has. */ + const grantsAccount = async (request: FastifyRequest, pageToken?: unknown): Promise<{ accountId: string; exp: number } | null> => { + const bearerAccount = await resolveAccessAccount({ config, keys, store }, request.headers.authorization); + if (bearerAccount) return { accountId: bearerAccount, exp: nowEpochSeconds() + grantsPageTokenTtlSeconds }; + return grantsPageTokenAccount(config, keys, pageToken); + }; const grantsReply = (reply: FastifyReply) => { reply.header("Cache-Control", "no-store"); @@ -2526,13 +2610,14 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { - const accountId = await grantsAccount(request, request.query.t); - if (!accountId) return signInRequired(reply); + const caller = await grantsAccount(request, request.query.t); + if (!caller) return signInRequired(reply); + const { accountId } = caller; grantsReply(reply); const receipts = await store.listConsentReceipts(accountId); if (prefersHtml(request.headers.accept)) { reply.type("text/html; charset=utf-8"); - return reply.send(renderGrantsPage(grantViews(receipts), signGrantsPageToken(config, keys, accountId))); + return reply.send(renderGrantsPage(grantViews(receipts), signGrantsPageToken(config, keys, accountId, caller.exp))); } return { grants: grantViews(receipts), receipts }; } @@ -2559,8 +2644,9 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { - const accountId = await grantsAccount(request, request.body?.t); - if (!accountId) return signInRequired(reply); + const caller = await grantsAccount(request, request.body?.t); + if (!caller) return signInRequired(reply); + const { accountId } = caller; grantsReply(reply); const receipts = await store.listConsentReceipts(accountId); const grant = grantViews(receipts).find((view) => view.id === request.params.grantId); @@ -2580,7 +2666,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise ({ kind: "revoke", updatedAt: at })); } for (const live of grantViews(receipts).filter((view) => view.provider === grant.provider && view.status === "active")) { - await store.createConsentReceipt({ + const { created } = await store.createConsentReceipt({ kind: "revocation", accountId, appSlug: live.appSlug, @@ -2588,19 +2674,22 @@ export async function buildApp(options: BuildAppOptions = {}): Promise `
  • ${escapeHtml(line)}
  • `).join("\n")}
    - ${form("continue", `Continue to ${provider}`)} - ${form("decline", "No, return to the app")} + ${form("continue", consentButtons(ask).go)} + ${form("decline", consentButtons(ask).no)}
    ` ); } export interface GrantView { + consentText: string; id: string; appSlug: AppSlug; provider: Provider; @@ -135,6 +155,7 @@ export function grantViews(receipts: readonly StoredConsentReceipt[]): GrantView scopesGranted: receipt.scopesGranted, grantedAt: receipt.createdAt, consentPageDigest: receipt.consentPageDigest, + consentText: receipt.consentText, status: revocation ? "revoked" : "active", ...(revocation ? { revokedAt: revocation.createdAt, revocationReceiptId: revocation.id } : {}), }); diff --git a/src/store/in-memory.ts b/src/store/in-memory.ts index c31b098..cfc869e 100644 --- a/src/store/in-memory.ts +++ b/src/store/in-memory.ts @@ -486,10 +486,14 @@ export class InMemoryStore implements HeimdallStore { this.auditEvents.set(event.id ?? randomUUID(), event); } - async createConsentReceipt(input: CreateConsentReceiptInput): Promise { + async createConsentReceipt(input: CreateConsentReceiptInput): Promise<{ receipt: StoredConsentReceipt; created: boolean }> { + if (input.kind === "revocation") { + const existing = this.consentReceipts.find((r) => r.kind === "revocation" && r.revokesReceiptId === input.revokesReceiptId); + if (existing) return { receipt: clone(existing), created: false }; + } const receipt = { id: randomUUID(), ...clone(input) } as StoredConsentReceipt; this.consentReceipts.push(clone(receipt)); - return clone(receipt); + return { receipt: clone(receipt), created: true }; } async listConsentReceipts(accountId: string): Promise { diff --git a/src/store/postgres.ts b/src/store/postgres.ts index 45240a5..3d34047 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -260,6 +260,7 @@ interface ConsentReceiptRow { scopes_asked: string | null; scopes_granted: string | null; consent_page_digest: string | null; + consent_text: string | null; revokes_receipt_id: string | null; } @@ -280,6 +281,7 @@ function mapConsentReceiptRow(row: ConsentReceiptRow): StoredConsentReceipt { scopesAsked: parseScopes(row.scopes_asked ?? ""), scopesGranted: parseScopes(row.scopes_granted ?? ""), consentPageDigest: row.consent_page_digest ?? "", + consentText: row.consent_text ?? "", }; } @@ -1232,15 +1234,18 @@ export class PostgresStore implements HeimdallStore { ); } - async createConsentReceipt(input: CreateConsentReceiptInput): Promise { + async createConsentReceipt(input: CreateConsentReceiptInput): Promise<{ receipt: StoredConsentReceipt; created: boolean }> { const grant = input.kind === "grant" ? input : null; + // No conflict target and the partial unique index decides: a second + // revocation of one grant inserts nothing and the first is read back. const result = await this.pool.query( ` INSERT INTO consent_receipts ( id, kind, account_id, app_slug, provider, created_at, - scopes_asked, scopes_granted, consent_page_digest, revokes_receipt_id + scopes_asked, scopes_granted, consent_page_digest, consent_text, revokes_receipt_id ) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) + ON CONFLICT DO NOTHING RETURNING * `, [ @@ -1253,10 +1258,18 @@ export class PostgresStore implements HeimdallStore { grant ? grant.scopesAsked.join(" ") : null, grant ? grant.scopesGranted.join(" ") : null, grant ? grant.consentPageDigest : null, + grant ? grant.consentText : null, input.kind === "revocation" ? input.revokesReceiptId : null, ] ); - return mapConsentReceiptRow(expectRow(result.rows[0], "createConsentReceipt")); + if (result.rowCount) { + return { receipt: mapConsentReceiptRow(expectRow(result.rows[0], "createConsentReceipt")), created: true }; + } + const existing = await this.pool.query( + `SELECT * FROM consent_receipts WHERE revokes_receipt_id = $1`, + [input.kind === "revocation" ? input.revokesReceiptId : null] + ); + return { receipt: mapConsentReceiptRow(expectRow(existing.rows[0], "createConsentReceipt")), created: false }; } async listConsentReceipts(accountId: string): Promise { diff --git a/src/store/schema.ts b/src/store/schema.ts index 9c87dff..71a4a43 100644 --- a/src/store/schema.ts +++ b/src/store/schema.ts @@ -192,9 +192,15 @@ CREATE TABLE IF NOT EXISTS consent_receipts ( scopes_asked TEXT, scopes_granted TEXT, consent_page_digest TEXT, + consent_text TEXT, revokes_receipt_id TEXT ); +-- A grant is taken back once: the second revocation naming it conflicts. +CREATE UNIQUE INDEX IF NOT EXISTS consent_receipts_revokes_unique_idx + ON consent_receipts(revokes_receipt_id) + WHERE revokes_receipt_id IS NOT NULL; + CREATE INDEX IF NOT EXISTS consent_receipts_account_idx ON consent_receipts(account_id, created_at); diff --git a/src/store/types.ts b/src/store/types.ts index 4c4ce17..bb2e080 100644 --- a/src/store/types.ts +++ b/src/store/types.ts @@ -257,7 +257,9 @@ export type CreatePrivateCommandReceiptInput = StoredPrivateCommandReceipt; * edited, and a revocation is a second row naming it, so a grant is live * exactly when no revocation names it. `scopesAsked` is what Heimdall sent the * provider, `scopesGranted` what the provider returned, `consentPageDigest` - * the hash of the wording the person was shown. + * the hash of the wording the person was shown and `consentText` that wording + * itself. A grant is revoked at most once: a second revocation naming the same + * grant is not written, and the store answers with the first. */ export type StoredConsentReceipt = { id: string; @@ -266,7 +268,7 @@ export type StoredConsentReceipt = { provider: Provider; createdAt: string; } & ( - | { kind: "grant"; scopesAsked: string[]; scopesGranted: string[]; consentPageDigest: string } + | { kind: "grant"; scopesAsked: string[]; scopesGranted: string[]; consentPageDigest: string; consentText: string } | { kind: "revocation"; revokesReceiptId: string } ); @@ -350,7 +352,8 @@ export interface HeimdallStore { */ claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise; createAuditEvent(input: CreateAuditEventInput): Promise; - createConsentReceipt(input: CreateConsentReceiptInput): Promise; + /** `created` is false when a revocation for that grant already existed and is what comes back. */ + createConsentReceipt(input: CreateConsentReceiptInput): Promise<{ receipt: StoredConsentReceipt; created: boolean }>; /** Every receipt the account holds, oldest first. */ listConsentReceipts(accountId: string): Promise; } diff --git a/tests/consent-drift.test.ts b/tests/consent-drift.test.ts new file mode 100644 index 0000000..8671d4b --- /dev/null +++ b/tests/consent-drift.test.ts @@ -0,0 +1,65 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { type FastifyInstance } from "fastify"; + +// The receipt records the wording the person was shown. If the wording changes +// between the ask and the callback (a deploy inside the state's lifetime), the +// receipt must still hold what they saw. + +const drift = vi.hoisted(() => ({ on: false })); +vi.mock("../src/consent.js", async (importOriginal) => { + const real = await importOriginal(); + return { ...real, consentText: (ask: Parameters[0]) => real.consentText(ask) + (drift.on ? "\nREWORDED AFTER THE ASK" : "") }; +}); + +import { buildApp } from "../src/app.js"; +import { InMemoryStore } from "../src/store/index.js"; +import { createTestConfig, setCookieOf, stateOf } from "./oauth-flow.js"; + +const apps: FastifyInstance[] = []; +afterEach(async () => { + drift.on = false; + while (apps.length) await apps.pop()?.close(); +}); + +it("a receipt holds the wording of the ask, not wording rebuilt at the callback", async () => { + const store = new InMemoryStore(); + const app = await buildApp({ + config: createTestConfig(), + store, + oauthRuntimes: { + joystick: { + async exchangeAuthorizationCode() { + return { accessToken: "joy-access-code-a", refreshToken: "r", tokenType: "Bearer", scope: ["identity:read"], expiresAt: "2099-01-01T00:00:00.000Z", raw: {} }; + }, + async resolveIdentity() { + return { provider: "joystick", providerUserId: "joy-a", username: "a", profile: {} }; + }, + async evaluateEntitlements() { + return { facts: [], snapshots: [] }; + }, + }, + }, + }); + apps.push(app); + const start = await app.inject({ + method: "POST", + url: "/v1/oauth/joystick/start", + headers: { "x-heimdall-app-secret": "streampixels-secret" }, + payload: { appSlug: "streampixels", mode: "connect", connection: { kind: "creator", targetId: "c" }, returnTo: "https://streampixels.gamecult.org/s", handoff: { kind: "browser_completion" } }, + }); + const state = stateOf(start.json()); + const ask = await app.inject({ method: "GET", url: `/v1/oauth/joystick/launch?state=${encodeURIComponent(state)}`, headers: { accept: "text/html" } }); + const askCookie = setCookieOf(ask).find((c) => c.startsWith("__Host-heimdall-ask-"))!.split(";")[0]!; + const go = await app.inject({ + method: "POST", + url: "/v1/oauth/joystick/consent", + headers: { "content-type": "application/x-www-form-urlencoded", cookie: askCookie }, + payload: new URLSearchParams({ state, decision: "continue" }).toString(), + }); + const binding = setCookieOf(go).find((c) => c.startsWith("__Host-heimdall-oauth-"))!.split(";")[0]!; + drift.on = true; // the wording changes after the person has agreed + const done = await app.inject({ method: "GET", url: `/v1/oauth/joystick/callback?state=${encodeURIComponent(state)}&code=code-a`, headers: { cookie: binding, accept: "application/json" } }); + expect(done.statusCode).toBe(201); + const [receipt] = await store.listConsentReceipts(done.json().account.id); + expect(receipt?.kind === "grant" && receipt.consentText).not.toContain("REWORDED"); +}); diff --git a/tests/joystick-consent.test.ts b/tests/joystick-consent.test.ts index f674f12..963f1e5 100644 --- a/tests/joystick-consent.test.ts +++ b/tests/joystick-consent.test.ts @@ -1,8 +1,9 @@ import { createHash } from "node:crypto"; import { afterEach, describe, expect, it, vi } from "vitest"; import { type FastifyInstance } from "fastify"; -import { buildApp } from "../src/app.js"; -import { consentDigest, consentLines, type ConsentAsk } from "../src/consent.js"; +import { buildApp, getHeimdallRuntimeContext } from "../src/app.js"; +import { consentDigest, consentText, digestOfText, type ConsentAsk } from "../src/consent.js"; +import { decodeJwt, signJwt } from "../src/signing.js"; import { type OAuthProviderRuntime } from "../src/oauth.js"; import { providerCatalog } from "../src/providers.js"; import { InMemoryStore } from "../src/store/index.js"; @@ -64,14 +65,17 @@ async function startConnect(app: FastifyInstance, handoff: Record `/v1/oauth/joystick/launch?state=${encodeURIComponent(state)}`; -const cookieOf = (response: { headers: Record }) => - setCookieOf(response).find((value) => value.startsWith("__Host-heimdall-oauth-"))!.split(";")[0]!; +const cookieNamed = (prefix: string) => (response: { headers: Record }) => + setCookieOf(response).find((value) => value.startsWith(prefix))?.split(";")[0]; +const askCookieOf = cookieNamed("__Host-heimdall-ask-"); +const bindingCookieOf = cookieNamed("__Host-heimdall-oauth-"); -/** The browser is shown the ask. */ +/** The browser is shown the ask. The cookie it keeps is the ask's, which binds nothing. */ async function seeAsk(app: FastifyInstance, state: string) { const response = await app.inject({ method: "GET", url: launchUrl(state), headers: { accept: "text/html" } }); expect(response.statusCode).toBe(200); - return { page: response, cookie: cookieOf(response) }; + expect(bindingCookieOf(response), "the ask must not set the launch binding").toBeUndefined(); + return { page: response, cookie: askCookieOf(response)! }; } function answer(app: FastifyInstance, state: string, decision: "continue" | "decline", cookie?: string, accept = "text/html") { @@ -94,10 +98,10 @@ function callback(app: FastifyInstance, state: string, cookie: string, query: st /** Ask, accept, and complete as Joystick user `user`; returns the callback's JSON. */ async function grantAs(app: FastifyInstance, user: string) { const state = await startConnect(app); - const { cookie } = await seeAsk(app, state); - const go = await answer(app, state, "continue", cookie); + const asked = await seeAsk(app, state); + const go = await answer(app, state, "continue", asked.cookie); expect(go.statusCode).toBe(302); - const done = await callback(app, state, cookie, `code=code-${user}`); + const done = await callback(app, state, bindingCookieOf(go)!, `code=code-${user}`); expect(done.statusCode).toBe(201); return done.json() as { accessToken: string; consentReceiptId: string; account: { id: string }; session: { accountId: string } }; } @@ -167,6 +171,44 @@ describe("the ask", () => { expect((await answer(app, state, "continue", cookie)).statusCode).toBe(302); }); + it("a stranger who only opens the launch URL is not bound to the state and cannot complete it", async () => { + const { app } = await newApp(); + const state = await startConnect(app); + const victim = await seeAsk(app, state); + await answer(app, state, "continue", victim.cookie); + // A fresh browser that holds the URL loads the ask and calls back with its own provider code. + const stranger = await seeAsk(app, state); + for (const cookie of [stranger.cookie, ""]) { + const done = await callback(app, state, cookie, "code=code-attacker"); + expect(done.statusCode).toBe(400); + expect(done.json()).toEqual({ error: "state_not_bound" }); + } + }); + + it("only Continue sets the launch binding, and the ask's cookie is no binding: it cannot complete a callback", async () => { + const { app } = await newApp(); + const state = await startConnect(app); + const asked = await seeAsk(app, state); + const done = await callback(app, state, asked.cookie, "code=code-a"); + expect(done.json()).toEqual({ error: "state_not_bound" }); + const go = await answer(app, state, "continue", asked.cookie); + expect(bindingCookieOf(go)).toBeDefined(); + expect(bindingCookieOf(go)!.length).toBeLessThan(3500); + }); + + it("a managed connection that never passed through the ask completes nothing and leaves no receipt", async () => { + const { app, store } = await newApp(); + const ctx = getHeimdallRuntimeContext(app); + const state = await startConnect(app); + const { jti, exp } = decodeJwt(state).payload as { jti: string; exp: number }; + // A binding that names this state but carries no wording: what any launch outside the ask would leave. + const bare = signJwt({ typ: "heimdall_oauth_binding", iss: ctx.config.issuer, jti, iat: exp - 600, exp }, ctx.keys); + const done = await callback(app, state, `__Host-heimdall-oauth-${jti}=${bare}`, "code=code-a"); + expect(done.statusCode).not.toBe(201); + expect(done.json()).not.toHaveProperty("consentReceiptId"); + expect(await store.listConsentReceipts((await store.findStoredLinkedIdentity("joystick", "joy-a"))?.accountId ?? "none")).toEqual([]); + }); + it("the consent route refuses a flow that has no ask", async () => { const { app } = await newApp(); const start = await app.inject({ @@ -189,8 +231,8 @@ describe("the ask", () => { describe("the wording digest", () => { const ask: ConsentAsk = { appSlug: "streampixels", provider: "joystick", scopes: ["identity:read"], returnOrigin: "https://streampixels.gamecult.org" }; - it("is the sha-256 of the lines shown, and moves with the app, provider, scopes and origin", () => { - expect(consentDigest(ask)).toBe(createHash("sha256").update(consentLines(ask).join("\n"), "utf8").digest("hex")); + it("is the sha-256 of the text shown, and moves with the app, provider, scopes and origin", () => { + expect(consentDigest(ask)).toBe(createHash("sha256").update(consentText(ask), "utf8").digest("hex")); const variants: ConsentAsk[] = [ { ...ask, appSlug: "bifrost" }, { ...ask, provider: "twitch" }, @@ -212,7 +254,7 @@ describe("refusal", () => { // Nothing launches or completes afterwards, and nothing was kept. expect((await answer(app, state, "continue", cookie, "application/json")).json()).toEqual({ error: "state_already_launched" }); - expect((await callback(app, state, cookie, "code=code-a")).json()).toEqual({ error: "state_already_used" }); + expect((await callback(app, state, cookie, "code=code-a")).json()).toEqual({ error: "state_not_bound" }); expect(await store.findStoredLinkedIdentity("joystick", "joy-a")).toBeNull(); const events = [...(store as unknown as { auditEvents: Map }).auditEvents.values()]; expect(events.filter((event) => event.eventType === "consent_refused").map((event) => event.eventPayloadJson)).toEqual([ @@ -259,8 +301,8 @@ describe("refusal", () => { await answer(app, byViewer, "decline", cookie); const byProvider = await startConnect(app, handoff); const second = await seeAsk(app, byProvider); - await answer(app, byProvider, "continue", second.cookie); - await callback(app, byProvider, second.cookie, "error=access_denied"); + const proceeded = await answer(app, byProvider, "continue", second.cookie); + await callback(app, byProvider, bindingCookieOf(proceeded)!, "error=access_denied"); expect(delivered.map((payload) => [payload.status, payload.error, payload.by])).toEqual([ ["error", "consent_refused", "viewer"], @@ -272,8 +314,9 @@ describe("refusal", () => { async function newFlow(app: FastifyInstance) { const state = await startConnect(app); const { cookie } = await seeAsk(app, state); - expect((await answer(app, state, "continue", cookie)).statusCode).toBe(302); - return { state, cookie }; + const go = await answer(app, state, "continue", cookie); + expect(go.statusCode).toBe(302); + return { state, cookie: bindingCookieOf(go)! }; } describe("the receipt", () => { @@ -295,6 +338,21 @@ describe("the receipt", () => { }); }); + it("the receipt holds the wording the person was shown, and its digest is that wording's hash", async () => { + const { app, store } = await newApp(); + const state = await startConnect(app); + const asked = await seeAsk(app, state); + const go = await answer(app, state, "continue", asked.cookie); + const done = await callback(app, state, bindingCookieOf(go)!, "code=code-a"); + const [receipt] = await store.listConsentReceipts(done.json().account.id); + if (receipt?.kind !== "grant") throw new Error("no grant"); + expect(receipt.consentPageDigest).toBe(digestOfText(receipt.consentText)); + const shown = asked.page.body.replace(/'/g, "'").replace(/"/g, '"').replace(/>/g, ">").replace(/</g, "<").replace(/&/g, "&"); + for (const line of receipt.consentText.split("\n")) expect(shown, line).toContain(line); + expect(receipt.consentText).toContain("Continue to Joystick"); + expect(receipt.consentText).toContain("No, return to the app"); + }); + it("a refusal leaves no receipt", async () => { const { app, store } = await newApp(); const state = await startConnect(app); @@ -308,8 +366,8 @@ describe("the receipt", () => { const { app } = await newApp(); const state = await startConnect(app); const { cookie } = await seeAsk(app, state); - await answer(app, state, "continue", cookie); - const page = await callback(app, state, cookie, "code=code-a", "text/html"); + const go = await answer(app, state, "continue", cookie); + const page = await callback(app, state, bindingCookieOf(go)!, "code=code-a", "text/html"); expect(page.statusCode).toBe(200); expect(page.body).toMatch(/receipt [0-9a-f-]{36}/); }); @@ -424,6 +482,43 @@ describe("my grants", () => { expect((await resolveCredential(app, a.account.id)).statusCode).toBe(410); }); + it("a page link is never renewed by being used: the forms on its page expire when the link does", async () => { + const { app } = await newApp(); + const a = await grantAs(app, "a"); + const link = await app.inject({ method: "POST", url: "/v1/me/grants/link", headers: bearer(a.accessToken) }); + const url = new URL(link.json().url as string); + const linkToken = url.searchParams.get("t")!; + const page = await app.inject({ method: "GET", url: `${url.pathname}${url.search}`, headers: { accept: "text/html" } }); + const formToken = /name="t" value="([^"]+)"/.exec(page.body)![1]!; + expect(decodeJwt(formToken).payload.exp).toBe(decodeJwt(linkToken).payload.exp); + // The same holds one hop on: the page a form post answers with. + const post = await app.inject({ + method: "POST", + url: "/v1/me/grants/nope/revoke", + headers: { ...form, accept: "text/html" }, + payload: new URLSearchParams({ t: formToken }).toString(), + }); + expect(post.statusCode).toBe(404); + // A bearer, by contrast, opens a fresh window. + const fresh = await app.inject({ method: "GET", url: "/v1/me/grants", headers: { ...bearer(a.accessToken), accept: "text/html" } }); + const freshToken = /name="t" value="([^"]+)"/.exec(fresh.body)![1]!; + expect(decodeJwt(freshToken).payload.exp).toBeGreaterThanOrEqual(decodeJwt(linkToken).payload.exp as number); + }); + + it("two revokes at once take the grant back once: one revocation row, one audit event, one reporter", async () => { + const { app, store } = await newApp(); + const a = await grantAs(app, "a"); + const url = `/v1/me/grants/${a.consentReceiptId}/revoke`; + const [one, two] = await Promise.all([ + app.inject({ method: "POST", url, headers: bearer(a.accessToken) }), + app.inject({ method: "POST", url, headers: bearer(a.accessToken) }), + ]); + expect([one.json().revoked.length, two.json().revoked.length].sort()).toEqual([0, 1]); + expect((await store.listConsentReceipts(a.account.id)).filter((r) => r.kind === "revocation")).toHaveLength(1); + const events = [...(store as unknown as { auditEvents: Map }).auditEvents.values()]; + expect(events.filter((event) => event.eventType === "consent_revoked")).toHaveLength(1); + }); + it("a page link proves only what it was minted for: an access token, a foreign token or none opens nothing", async () => { const { app } = await newApp(); const a = await grantAs(app, "a"); diff --git a/tests/oauth-flow.ts b/tests/oauth-flow.ts index b85b2ce..2616da1 100644 --- a/tests/oauth-flow.ts +++ b/tests/oauth-flow.ts @@ -120,8 +120,8 @@ async function followLaunch(app: FastifyInstance, state: string): Promise value.startsWith("__Host-heimdall-oauth-")); - expect(asked, "the ask sets the binding cookie").toBeDefined(); + const asked = setCookieOf(response).find((value) => value.startsWith("__Host-heimdall-ask-")); + expect(asked, "the ask sets its own cookie").toBeDefined(); response = await app.inject({ method: "POST", url: `/v1/oauth/${provider}/consent`, diff --git a/tests/oauth-state-binding.test.ts b/tests/oauth-state-binding.test.ts index 1bffc19..01abba0 100644 --- a/tests/oauth-state-binding.test.ts +++ b/tests/oauth-state-binding.test.ts @@ -312,6 +312,38 @@ describe("OAuth state binding", () => { expect(replay.json()).toEqual({ error: "state_already_used" }); }); + // The private command plane's completeAuth answers a denied attempt with + // attempt.denialCode as its error (private-command-plane.ts, completeAuth), so + // these two codes are what Bifrost, Repixelizer and Ghostlight poll for. + it.each([ + ["bifrost", "https://bifrost.gamecult.org/auth/heimdall/complete?attempt=a1", "access_denied", "consent_refused"], + ["repixelizer", "https://repixelizer.gamecult.org/app/", "access_denied", "consent_refused"], + ["repixelizer", "https://repixelizer.gamecult.org/app/", "server_error", "provider_error"], + ] as const)("a %s attempt whose provider answers %s is denied with %s", async (appSlug, returnTo, providerError, denialCode) => { + const app = await newApp(); + const ctx = getHeimdallRuntimeContext(app); + const attempt = await ctx.store.createAuthAttempt({ + handle: `attempt-${providerError}`, + appSlug, + provider: "discord", + mode: "sign_in", + returnTo, + createdAt: new Date().toISOString(), + expiresAt: new Date(Date.now() + 600_000).toISOString(), + }); + const caller = resolveAppCaller(ctx.config, appSlug, { "x-heimdall-app-secret": `${appSlug}-secret` }); + const started = await startOAuthFlow( + ctx, + "discord", + caller, + { appSlug, mode: "sign_in", returnTo, handoff: { kind: "browser_completion" } }, + { trustedBrowserAttemptId: attempt.handle } + ); + const flow = await launchFlow(app, started.body as unknown as { authorizationUrl: string }); + await callback(app, flow.state, flow.cookie, `error=${providerError}`); + expect(await ctx.store.findAuthAttempt(appSlug, attempt.handle)).toMatchObject({ status: "denied", denialCode }); + }); + describe("a state that is expired, foreign or tampered is refused at launch and at callback", () => { it.each([ ["expired beyond the skew", { exp: Math.floor(Date.now() / 1000) - 100 }, "state_expired"], diff --git a/tests/store.test.ts b/tests/store.test.ts index 684aa41..ddec729 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -198,6 +198,19 @@ describe("PostgresStore", () => { }); }); +describe("InMemoryStore.createConsentReceipt", () => { + it("writes one revocation per grant: the second names the first and is not created", async () => { + const store = new InMemoryStore(); + const base = { accountId: "a", appSlug: "streampixels" as const, provider: "joystick" as const, createdAt: "2026-11-08T00:00:00.000Z" }; + const { receipt: grant } = await store.createConsentReceipt({ ...base, kind: "grant", scopesAsked: [], scopesGranted: [], consentPageDigest: "d", consentText: "t" }); + const first = await store.createConsentReceipt({ ...base, kind: "revocation", revokesReceiptId: grant.id }); + const second = await store.createConsentReceipt({ ...base, createdAt: "2026-11-09T00:00:00.000Z", kind: "revocation", revokesReceiptId: grant.id }); + expect([first.created, second.created]).toEqual([true, false]); + expect(second.receipt).toEqual(first.receipt); + expect(await store.listConsentReceipts("a")).toHaveLength(2); + }); +}); + describe("InMemoryStore.claimOAuthStateUse", () => { const use = { jti: "state-1", @@ -273,7 +286,7 @@ describe("PostgresStore.checkSchema", () => { "consent_receipts", "audit_events", ]); - expect(REQUIRED_COLUMNS).toHaveLength(111); + expect(REQUIRED_COLUMNS).toHaveLength(112); expect(REQUIRED_COLUMNS).toEqual( expect.arrayContaining([ { table: "auth_completions", column: "code", type: "TEXT", nullable: false }, @@ -284,12 +297,13 @@ describe("PostgresStore.checkSchema", () => { { table: "auth_completions", column: "attempt_id", type: "TEXT", nullable: true }, ]) ); - expect(REQUIRED_KEYS).toHaveLength(15); + expect(REQUIRED_KEYS).toHaveLength(16); expect(REQUIRED_KEYS).toEqual( expect.arrayContaining([ { table: "linked_identities", columns: "provider,provider_user_id", predicate: "" }, { table: "private_command_receipts", columns: "app_slug,idempotency_key", predicate: "" }, { table: "oauth_state_uses", columns: "jti,phase", predicate: "" }, + { table: "consent_receipts", columns: "revokes_receipt_id", predicate: "revokes_receipt_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" }, ]) @@ -419,7 +433,7 @@ async function exerciseStore(store: PostgresStore): Promise> { expect(await s.claimOAuthStateUse(stateUse)).toBe(true); expect(await s.claimOAuthStateUse(stateUse)).toBe(false); expect(await s.claimOAuthStateUse({ ...stateUse, phase: "callback" })).toBe(true); - const grant = await s.createConsentReceipt({ kind: "grant", accountId: account.id, appSlug: "streampixels", provider: "joystick", createdAt: now, scopesAsked: ["a", "b"], scopesGranted: ["a"], consentPageDigest: "d" }); + const { receipt: grant } = await s.createConsentReceipt({ kind: "grant", accountId: account.id, appSlug: "streampixels", provider: "joystick", createdAt: now, scopesAsked: ["a", "b"], scopesGranted: ["a"], consentPageDigest: "d", consentText: "t" }); await s.createConsentReceipt({ kind: "revocation", accountId: account.id, appSlug: "streampixels", provider: "joystick", createdAt: later, revokesReceiptId: grant.id }); expect((await s.listConsentReceipts(account.id)).map((r) => r.kind)).toEqual(["grant", "revocation"]); await s.createAuditEvent({ eventType: "probe", eventPayloadJson: {}, createdAt: now }); From d4f7dce098691930c6f8fbf592d14dc7212a46c3 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sun, 8 Nov 2026 13:31:43 +0000 Subject: [PATCH 14/63] Check the shown text before any code exchange; pin link expiry with a clock Co-Authored-By: Claude Sonnet 5.5 --- src/app.ts | 18 +++++++++++------- tests/joystick-consent.test.ts | 5 ++++- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/app.ts b/src/app.ts index c6c7c68..bb5c4d9 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1619,6 +1619,16 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { + vi.useRealTimers(); vi.restoreAllMocks(); while (apps.length) await apps.pop()?.close(); }); @@ -206,7 +207,7 @@ describe("the ask", () => { const done = await callback(app, state, `__Host-heimdall-oauth-${jti}=${bare}`, "code=code-a"); expect(done.statusCode).not.toBe(201); expect(done.json()).not.toHaveProperty("consentReceiptId"); - expect(await store.listConsentReceipts((await store.findStoredLinkedIdentity("joystick", "joy-a"))?.accountId ?? "none")).toEqual([]); + expect(await store.findStoredLinkedIdentity("joystick", "joy-a"), "no credential is kept").toBeNull(); }); it("the consent route refuses a flow that has no ask", async () => { @@ -488,6 +489,8 @@ describe("my grants", () => { const link = await app.inject({ method: "POST", url: "/v1/me/grants/link", headers: bearer(a.accessToken) }); const url = new URL(link.json().url as string); const linkToken = url.searchParams.get("t")!; + // Two minutes on, so a form token minted afresh would differ from the link's. + vi.useFakeTimers({ toFake: ["Date"], now: Date.now() + 120_000 }); const page = await app.inject({ method: "GET", url: `${url.pathname}${url.search}`, headers: { accept: "text/html" } }); const formToken = /name="t" value="([^"]+)"/.exec(page.body)![1]!; expect(decodeJwt(formToken).payload.exp).toBe(decodeJwt(linkToken).payload.exp); From 5ce8f1c14c978dd8fd355a089d10b54f2c9b486f Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sun, 8 Nov 2026 13:32:21 +0000 Subject: [PATCH 15/63] Consent doc: ask cookie, carried wording, unique revocation, fixed link expiry Co-Authored-By: Claude Sonnet 5.5 --- docs/joystick-consent-flow.md | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/docs/joystick-consent-flow.md b/docs/joystick-consent-flow.md index 86746ea..8add6a3 100644 --- a/docs/joystick-consent-flow.md +++ b/docs/joystick-consent-flow.md @@ -78,10 +78,14 @@ same function that builds the authorization URL), what Heimdall keeps (an encrypted refresh token and access token, until the person takes it back or the provider ends it), what the app receives, and how to take it back. It carries two POST forms to `/v1/oauth/:provider/consent`, **Continue to Joystick** and -**No, return to the app**, and runs no script. It sets the binding cookie, so -either answer can only come from the browser that was shown the ask; an answer -without the cookie is `state_not_bound` and spends nothing. Viewing the ask -claims nothing. Continue claims the launch use and answers `302`. +**No, return to the app**, and runs no script. It sets the ask's own +cookie (`__Host-heimdall-ask-`), which carries the exact text shown and is +accepted only by Continue and No; an answer without it is `state_not_bound` and +spends nothing. Viewing the ask claims nothing and binds nothing: the launch +binding cookie, which decides who may complete the state, is set only when +Continue claims the launch, and it carries the text shown on to the callback. +(An earlier cut set the binding on the ask, so anyone holding the launch URL +could become the state's owner; review of 2026-11-08 found it.) What the app receives, stated as the code does it: not a claim. The app backend can call `managed-credentials/resolve` and receive the current access @@ -104,14 +108,19 @@ including Bifrost's and Repixelizer's sign-in; see the PR for the contract note. On a granted `custody_only` completion Heimdall writes one `consent_receipts` row of kind `grant`: id (random), account, app, provider, scopes asked, scopes -granted (as the provider returned them), `consentPageDigest` (sha-256 of the -lines the page showed, so a wording change is visible), `createdAt`. The id +granted (as the provider returned them), `consentText` (the lines and +button labels shown, taken from the ask and never rebuilt, so a deploy between +ask and callback cannot change what the receipt says), `consentPageDigest` +(sha-256 of that text), `createdAt`. A custody callback with no shown text +exchanges no code and stores no credential. The id reaches the app (`consentReceiptId` in the completion and backend payloads) and the person (the handoff page). Receipts are append-only: the store role has `SELECT` and `INSERT` on the table and nothing else. A revocation is a second row of kind `revocation` naming the -grant it takes back; a grant is live exactly when no revocation names it. The +grant it takes back, unique per grant (a partial unique index); a grant is live +exactly when no revocation names it, and a concurrent second revoke reports +nothing and writes nothing. The draft's `revokedAt` slot is gone for that reason. ### 3.4 My grants @@ -124,7 +133,8 @@ Bearer`), or a page link minted from one. else gets `{grants, receipts}`. - `POST /v1/me/grants/link` (bearer): `{url}` to the page, valid ten minutes. The token is signed, purpose-bound (`heimdall_grants_page`), stateless, and - opens only this page and its revoke forms. This is how a browser that holds no + opens only this page and its revoke forms. The forms on a page opened by a link + carry the link's own expiry, so using a link never renews it. This is how a browser that holds no session gets in; Heimdall sets no new cookie and stores nothing for it. - `POST /v1/me/grants/:id/revoke` (bearer, or the page token in the form): strips the stored tokens from the credential, then writes a revocation row From 767852ef96ed3d2fc818217fc868b93fe108a275 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sun, 8 Nov 2026 13:37:13 +0000 Subject: [PATCH 16/63] WIP t10: inflate cap, consent_text_missing before claim, scope caps, revocation FK Tests green locally; mutants not yet run; not pushed; PR body not updated. Co-Authored-By: Claude Sonnet 5.5 --- src/app.ts | 55 ++++++++++++++++++++-------- src/store/in-memory.ts | 4 +++ src/store/schema.ts | 10 ++++-- tests/joystick-consent.test.ts | 66 +++++++++++++++++++++++++++++++--- tests/store.test.ts | 17 +++++++-- 5 files changed, 127 insertions(+), 25 deletions(-) diff --git a/src/app.ts b/src/app.ts index bb5c4d9..f4a48e5 100644 --- a/src/app.ts +++ b/src/app.ts @@ -272,6 +272,14 @@ function signOAuthBinding( const consentAskType = "heimdall_consent_ask"; +/** The most wording a cookie may carry, before and after compression. The ask refuses what exceeds it; the readers never inflate past it. */ +const maxConsentTextBytes = 16 * 1024; +/** Browsers drop a cookie above 4096 bytes; the ask refuses one it could not keep. */ +const maxConsentCookieChars = 3800; +/** What an app may request: more is not a scope list a person can read. */ +const maxRequestedScopes = 32; +const maxRequestedScopeChars = 512; + function consentAskCookieName(jti: string): string { return `__Host-heimdall-ask-${jti}`; } @@ -305,7 +313,7 @@ function cookieConsentText( return null; } try { - return inflateRawSync(Buffer.from(ct, "base64url")).toString("utf8"); + return inflateRawSync(Buffer.from(ct, "base64url"), { maxOutputLength: maxConsentTextBytes }).toString("utf8"); } catch { return null; } @@ -746,6 +754,16 @@ export async function startOAuthFlow( return { statusCode: 400, body: { error: "initiator_only_in_link_mode" } }; } + if ( + input.requestedScopes !== undefined && + (input.requestedScopes.length > maxRequestedScopes || input.requestedScopes.some((scope) => scope.length > maxRequestedScopeChars)) + ) { + return { + statusCode: 400, + body: { error: "requested_scopes_too_large", detail: `At most ${maxRequestedScopes} scopes of ${maxRequestedScopeChars} characters each.` }, + }; + } + if (!isAllowedReturnOrigin(profile, input.returnTo)) { return { statusCode: 400, @@ -1221,7 +1239,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { reply.code(400); const profile = getAppProfile(state.app_slug); @@ -1385,7 +1403,15 @@ export async function buildApp(options: BuildAppOptions = {}): Promise maxConsentTextBytes || askCookie.length > maxConsentCookieChars) { + reply.code(400); + return { error: "consent_ask_too_large" }; + } + setConsentAskCookie(reply, state, askCookie, state.exp - nowEpochSeconds()); reply.header("Cache-Control", "no-store"); reply.header("Referrer-Policy", "no-referrer"); reply.header("X-Frame-Options", "DENY"); @@ -1507,6 +1533,17 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { if (input.kind === "revocation") { + // The table's foreign key: a revocation names a receipt of the same account. + if (!this.consentReceipts.some((r) => r.id === input.revokesReceiptId && r.accountId === input.accountId)) { + throw new Error("A revocation must name a receipt of its own account."); + } const existing = this.consentReceipts.find((r) => r.kind === "revocation" && r.revokesReceiptId === input.revokesReceiptId); if (existing) return { receipt: clone(existing), created: false }; } diff --git a/src/store/schema.ts b/src/store/schema.ts index 71a4a43..294ee2d 100644 --- a/src/store/schema.ts +++ b/src/store/schema.ts @@ -193,10 +193,14 @@ CREATE TABLE IF NOT EXISTS consent_receipts ( scopes_granted TEXT, consent_page_digest TEXT, consent_text TEXT, - revokes_receipt_id TEXT + revokes_receipt_id TEXT, + UNIQUE(id, account_id), + FOREIGN KEY (revokes_receipt_id, account_id) REFERENCES consent_receipts(id, account_id) ); --- A grant is taken back once: the second revocation naming it conflicts. +-- A revocation names a receipt of its own account (the composite foreign key; +-- NULL skips it for grants). A grant is taken back once: the second +-- revocation naming it conflicts. CREATE UNIQUE INDEX IF NOT EXISTS consent_receipts_revokes_unique_idx ON consent_receipts(revokes_receipt_id) WHERE revokes_receipt_id IS NOT NULL; @@ -265,7 +269,7 @@ export const REQUIRED_TABLES = createdTables.map(({ table }) => table); export const REQUIRED_COLUMNS = [ ...createdTables.flatMap(({ table, lines }) => lines - .filter((line) => !/^(?:PRIMARY KEY|UNIQUE)\b/.test(line)) + .filter((line) => !/^(?:PRIMARY KEY|UNIQUE|FOREIGN KEY)\b/.test(line)) .map((line) => { const [, column, type] = /^(\w+) (\w+)/.exec(line)!; return { table, column: column!, type: type!, nullable: !/\b(?:NOT NULL|PRIMARY KEY)\b/.test(line) }; diff --git a/tests/joystick-consent.test.ts b/tests/joystick-consent.test.ts index e227522..5dd9ead 100644 --- a/tests/joystick-consent.test.ts +++ b/tests/joystick-consent.test.ts @@ -1,4 +1,5 @@ -import { createHash } from "node:crypto"; +import { createHash, randomBytes } from "node:crypto"; +import { deflateRawSync } from "node:zlib"; import { afterEach, describe, expect, it, vi } from "vitest"; import { type FastifyInstance } from "fastify"; import { buildApp, getHeimdallRuntimeContext } from "../src/app.js"; @@ -197,17 +198,72 @@ describe("the ask", () => { expect(bindingCookieOf(go)!.length).toBeLessThan(3500); }); - it("a managed connection that never passed through the ask completes nothing and leaves no receipt", async () => { + it("a binding without the shown wording is refused with consent_text_missing before the state is spent", async () => { const { app, store } = await newApp(); const ctx = getHeimdallRuntimeContext(app); const state = await startConnect(app); const { jti, exp } = decodeJwt(state).payload as { jti: string; exp: number }; - // A binding that names this state but carries no wording: what any launch outside the ask would leave. + // A binding that names this state but carries no wording: what a launch from before the ask would leave. const bare = signJwt({ typ: "heimdall_oauth_binding", iss: ctx.config.issuer, jti, iat: exp - 600, exp }, ctx.keys); const done = await callback(app, state, `__Host-heimdall-oauth-${jti}=${bare}`, "code=code-a"); - expect(done.statusCode).not.toBe(201); - expect(done.json()).not.toHaveProperty("consentReceiptId"); + expect(done.statusCode).toBe(400); + expect(done.json()).toEqual({ error: "consent_text_missing" }); expect(await store.findStoredLinkedIdentity("joystick", "joy-a"), "no credential is kept").toBeNull(); + // Neither use of the state was spent by the refusal. + const usedAt = new Date().toISOString(); + const expiresAt = new Date(exp * 1000).toISOString(); + expect(await store.claimOAuthStateUse({ jti, phase: "callback", appSlug: "streampixels", usedAt, expiresAt })).toBe(true); + }); + + describe("the wording a cookie may carry", () => { + const signedAsk = (ctx: ReturnType, jti: string, exp: number, text: Buffer) => + signJwt({ typ: "heimdall_consent_ask", iss: ctx.config.issuer, jti, iat: exp - 600, exp, ct: deflateRawSync(text).toString("base64url") }, ctx.keys); + + it("is read up to 16 KB and no further: one byte over is refused, and a bomb is refused quickly", async () => { + const { app } = await newApp(); + const ctx = getHeimdallRuntimeContext(app); + const state = await startConnect(app); + const { jti, exp } = decodeJwt(state).payload as { jti: string; exp: number }; + const answerWith = (text: Buffer, decision: "decline" | "continue" = "decline") => + answer(app, state, decision, `__Host-heimdall-ask-${jti}=${signedAsk(ctx, jti, exp, text)}`, "application/json"); + expect((await answerWith(Buffer.alloc(16 * 1024 + 1, 97))).json()).toEqual({ error: "state_not_bound" }); + const t0 = Date.now(); + expect((await answerWith(Buffer.alloc(300 * 1024 * 1024))).json()).toEqual({ error: "state_not_bound" }); + expect(Date.now() - t0).toBeLessThan(1500); + // At the cap it is read. + expect((await answerWith(Buffer.alloc(16 * 1024, 97))).json()).toMatchObject({ error: "consent_refused" }); + }); + + it("requested scopes are capped at 32 of 512 characters, at start", async () => { + const { app } = await newApp(); + const startWith = (requestedScopes: string[]) => + app.inject({ + method: "POST", + url: "/v1/oauth/joystick/start", + headers: secret, + payload: { appSlug: "streampixels", mode: "connect", connection: { kind: "creator", targetId: "c" }, returnTo: "https://streampixels.gamecult.org/s", handoff: { kind: "browser_completion" }, requestedScopes }, + }); + const scopes = (n: number, len: number) => Array.from({ length: n }, (_, i) => `${i}`.padEnd(len, "x")); + expect((await startWith(scopes(33, 10))).json()).toMatchObject({ error: "requested_scopes_too_large" }); + expect((await startWith(scopes(1, 513))).json()).toMatchObject({ error: "requested_scopes_too_large" }); + expect((await startWith(scopes(32, 512))).statusCode).toBe(201); + }); + + it("an ask the cookies could not carry is refused, not shown", async () => { + const { app } = await newApp(); + const noise = Array.from({ length: 32 }, () => randomBytes(256).toString("hex")); // 32 x 512 incompressible + const start = await app.inject({ + method: "POST", + url: "/v1/oauth/joystick/start", + headers: secret, + payload: { appSlug: "streampixels", mode: "connect", connection: { kind: "creator", targetId: "c" }, returnTo: "https://streampixels.gamecult.org/s", handoff: { kind: "browser_completion" }, requestedScopes: noise }, + }); + expect(start.statusCode).toBe(201); + const page = await app.inject({ method: "GET", url: launchUrl(stateOf(start.json())), headers: { accept: "text/html" } }); + expect(page.statusCode).toBe(400); + expect(page.json()).toEqual({ error: "consent_ask_too_large" }); + expect(askCookieOf(page)).toBeUndefined(); + }); }); it("the consent route refuses a flow that has no ask", async () => { diff --git a/tests/store.test.ts b/tests/store.test.ts index ddec729..b107197 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -14,7 +14,7 @@ import { samePredicate, STORE_TABLE_PRIVILEGES, } from "../src/store/postgres.js"; -import { REQUIRED_COLUMNS, REQUIRED_KEYS, REQUIRED_TABLES } from "../src/store/schema.js"; +import { CREATE_SCHEMA_SQL, REQUIRED_COLUMNS, REQUIRED_KEYS, REQUIRED_TABLES } from "../src/store/schema.js"; describe("PostgresStore", () => { it("round-trips core auth records through postgres", async () => { @@ -198,6 +198,18 @@ describe("PostgresStore", () => { }); }); +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)"); + const store = new InMemoryStore(); + const base = { appSlug: "streampixels" as const, provider: "joystick" as const, createdAt: "2026-11-08T00:00:00.000Z" }; + const { receipt: grant } = await store.createConsentReceipt({ ...base, accountId: "a", kind: "grant", scopesAsked: [], scopesGranted: [], consentPageDigest: "d", consentText: "t" }); + await expect(store.createConsentReceipt({ ...base, accountId: "b", kind: "revocation", revokesReceiptId: grant.id })).rejects.toThrow(/own account/); + await expect(store.createConsentReceipt({ ...base, accountId: "a", kind: "revocation", revokesReceiptId: "no-such" })).rejects.toThrow(/own account/); + expect(await store.listConsentReceipts("a")).toHaveLength(1); + }); +}); + describe("InMemoryStore.createConsentReceipt", () => { it("writes one revocation per grant: the second names the first and is not created", async () => { const store = new InMemoryStore(); @@ -297,13 +309,14 @@ describe("PostgresStore.checkSchema", () => { { table: "auth_completions", column: "attempt_id", type: "TEXT", nullable: true }, ]) ); - expect(REQUIRED_KEYS).toHaveLength(16); + expect(REQUIRED_KEYS).toHaveLength(17); expect(REQUIRED_KEYS).toEqual( expect.arrayContaining([ { table: "linked_identities", columns: "provider,provider_user_id", predicate: "" }, { table: "private_command_receipts", columns: "app_slug,idempotency_key", predicate: "" }, { 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: "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" }, ]) From af554ca01323f61204a707f7631e6e05d5df19df Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sun, 8 Nov 2026 13:38:35 +0000 Subject: [PATCH 17/63] Addendum: per-index predicate check, live second-revocation and missing-table cases, test-live-pg prerequisites Co-Authored-By: Claude Sonnet 5.5 --- scripts/test-live-pg.sh | 13 +++++++++++++ tests/store.test.ts | 36 +++++++++++++++++++++++++++++------- 2 files changed, 42 insertions(+), 7 deletions(-) diff --git a/scripts/test-live-pg.sh b/scripts/test-live-pg.sh index a25c3e9..e4b3813 100755 --- a/scripts/test-live-pg.sh +++ b/scripts/test-live-pg.sh @@ -5,6 +5,19 @@ # SOUL_PG_URL's test drops and recreates schema public, so it only ever sees # this disposable cluster. set -euo pipefail +# Prerequisites, done here when missing (each step is skipped once it holds): +# 1. the vendor/CultLib submodule checked out, +# 2. its npm dependencies installed (the vendor packages build with its tsc), +# 3. dist/ built for cultcache-ts, cultnet-ts and cultmesh-ts (package.json +# points main at dist/index.js), +# 4. this repo's pnpm install. +cd "$(dirname "$0")/.." +[ -f vendor/CultLib/package.json ] || git submodule update --init vendor/CultLib +[ -d vendor/CultLib/node_modules/typescript ] || (cd vendor/CultLib && npm ci) +for pkg in cultcache-ts cultnet-ts cultmesh-ts; do + [ -f "vendor/CultLib/packages/$pkg/dist/index.js" ] || (cd "vendor/CultLib/packages/$pkg" && npm run build) +done +[ -d node_modules/vitest ] || pnpm install --frozen-lockfile export PATH="${PG_BIN:-/usr/lib/postgresql/16/bin}:$PATH" dir="$(mktemp -d)" port="${PG_PORT:-54329}" diff --git a/tests/store.test.ts b/tests/store.test.ts index b107197..dac3b95 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -447,7 +447,13 @@ async function exerciseStore(store: PostgresStore): Promise> { expect(await s.claimOAuthStateUse(stateUse)).toBe(false); expect(await s.claimOAuthStateUse({ ...stateUse, phase: "callback" })).toBe(true); const { receipt: grant } = await s.createConsentReceipt({ kind: "grant", accountId: account.id, appSlug: "streampixels", provider: "joystick", createdAt: now, scopesAsked: ["a", "b"], scopesGranted: ["a"], consentPageDigest: "d", consentText: "t" }); - await s.createConsentReceipt({ kind: "revocation", accountId: account.id, appSlug: "streampixels", provider: "joystick", createdAt: later, revokesReceiptId: grant.id }); + const revocation = { kind: "revocation" as const, accountId: account.id, appSlug: "streampixels" as const, provider: "joystick" as const, createdAt: later, revokesReceiptId: grant.id }; + const first = await s.createConsentReceipt(revocation); + // The second revocation of one grant hits ON CONFLICT DO NOTHING and reads the first back. + const second = await s.createConsentReceipt(revocation); + expect(first.created).toBe(true); + expect(second.created).toBe(false); + 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 }); return called; @@ -608,12 +614,28 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD it("prints each declared predicate exactly as Postgres prints the applied index's", async () => { const { owner } = await appliedDatabase(); const printed = await printedDeclaredPredicates(owner, HEIMDALL_SCHEMA_REQUIREMENTS); - const applied = await owner.query<{ predicate: string }>( - "SELECT pg_get_expr(indpred, indrelid) AS predicate FROM pg_index WHERE indexrelid = 'auth_completions_attempt_unconsumed_unique_idx'::regclass" - ); - const attemptKey = REQUIRED_KEYS.findIndex((key) => key.predicate !== ""); - expect(printed[attemptKey]).toBe(applied.rows[0]!.predicate); - expect(printed.filter((predicate) => predicate !== "")).toHaveLength(1); + const appliedByIndex = { + auth_completions_attempt_unconsumed_unique_idx: "auth_completions", + consent_receipts_revokes_unique_idx: "consent_receipts", + }; + const partialKeys = REQUIRED_KEYS.flatMap((key, index) => (key.predicate === "" ? [] : [{ key, index }])); + expect(partialKeys.map(({ key }) => key.table).sort()).toEqual(Object.values(appliedByIndex).sort()); + for (const [indexName, table] of Object.entries(appliedByIndex)) { + const applied = await owner.query<{ predicate: string }>( + "SELECT pg_get_expr(indpred, indrelid) AS predicate FROM pg_index WHERE indexrelid = $1::regclass", + [indexName] + ); + const { index } = partialKeys.find(({ key }) => key.table === table)!; + expect(printed[index], indexName).toBe(applied.rows[0]!.predicate); + } + expect(printed.filter((predicate) => predicate !== "")).toHaveLength(partialKeys.length); + }); + + it("refuses to boot with consent_receipts missing when the schema is not applied on startup", async () => { + const { name, owner } = await appliedDatabase(); + await owner.query("DROP TABLE consent_receipts"); + + expect(await start(urlFor(name), false)).toBe(refusal("SCHEMA_MISSING")); }); it("refuses a table whose primary key was dropped, even after applying the schema", async () => { From f7a38a7d2a3ff5fd88d34635fdce0a5162265f2b Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sun, 8 Nov 2026 13:39:34 +0000 Subject: [PATCH 18/63] Doc the FK, the cookie and scope bounds, consent_text_missing Co-Authored-By: Claude Sonnet 5.5 --- docs/joystick-consent-flow.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/joystick-consent-flow.md b/docs/joystick-consent-flow.md index 8add6a3..5821320 100644 --- a/docs/joystick-consent-flow.md +++ b/docs/joystick-consent-flow.md @@ -161,7 +161,10 @@ the least stored. 2. **The receipt is a new typed table, `consent_receipts`.** The audit table is operator-shaped and has no read path for the person; a viewer-readable record in it would make every audit row a potential disclosure. The table - holds ids, scopes and a digest: no IP address, no user agent, no page text. + holds ids, scopes and a digest: no IP address, no user agent, no page text. A revocation names a + receipt of its own account: a composite foreign key `(revokes_receipt_id, + account_id)` to `(id, account_id)`, which is why `(id, account_id)` is also a + unique key (`checkSchema` counts it). The in-memory store refuses the same. Refusals leave no receipt, only the anonymous audit row. 3. **Viewer identity: sign-in, not the cookie.** The binding cookie dies with the state and proves only that a browser launched a flow; it is not an @@ -181,6 +184,11 @@ the least stored. wording (the CultCoin legal thread) may only narrow it, and any change moves the digest. Until that review lands the copy is Heimdall's, signed by the steward. +6. **Bounds on what rides the cookies.** The wording is read from a cookie + only up to 16 KB inflated, so a compressed bomb is refused, not expanded. An + app may request at most 32 scopes of 512 characters (`requested_scopes_too_large` + at the ask). A custody callback whose binding carries no wording is refused + with `consent_text_missing` before the state is claimed, so nothing is burned. ## 5. Out of scope From b6372e5a4ffc2f297b74d2544fc3456bb35e01c0 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sun, 8 Nov 2026 13:45:57 +0000 Subject: [PATCH 19/63] Named revocation-conflict tests on pg-mem, first-create doc line, npm fallback in test-live-pg Co-Authored-By: Claude Sonnet 5.5 --- docs/joystick-consent-flow.md | 4 +++- scripts/test-live-pg.sh | 4 ++-- tests/store.test.ts | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/docs/joystick-consent-flow.md b/docs/joystick-consent-flow.md index 5821320..157e99c 100644 --- a/docs/joystick-consent-flow.md +++ b/docs/joystick-consent-flow.md @@ -164,7 +164,9 @@ the least stored. holds ids, scopes and a digest: no IP address, no user agent, no page text. A revocation names a receipt of its own account: a composite foreign key `(revokes_receipt_id, account_id)` to `(id, account_id)`, which is why `(id, account_id)` is also a - unique key (`checkSchema` counts it). The in-memory store refuses the same. + unique key (`checkSchema` counts it). The in-memory store refuses the same. The table is created + whole and first-created: no deployed database had an earlier shape, so there + is no `ALTER` step. Refusals leave no receipt, only the anonymous audit row. 3. **Viewer identity: sign-in, not the cookie.** The binding cookie dies with the state and proves only that a browser launched a flow; it is not an diff --git a/scripts/test-live-pg.sh b/scripts/test-live-pg.sh index e4b3813..e028caa 100755 --- a/scripts/test-live-pg.sh +++ b/scripts/test-live-pg.sh @@ -10,14 +10,14 @@ set -euo pipefail # 2. its npm dependencies installed (the vendor packages build with its tsc), # 3. dist/ built for cultcache-ts, cultnet-ts and cultmesh-ts (package.json # points main at dist/index.js), -# 4. this repo's pnpm install. +# 4. this repo's pnpm install (npm install if pnpm fails with EACCES). cd "$(dirname "$0")/.." [ -f vendor/CultLib/package.json ] || git submodule update --init vendor/CultLib [ -d vendor/CultLib/node_modules/typescript ] || (cd vendor/CultLib && npm ci) for pkg in cultcache-ts cultnet-ts cultmesh-ts; do [ -f "vendor/CultLib/packages/$pkg/dist/index.js" ] || (cd "vendor/CultLib/packages/$pkg" && npm run build) done -[ -d node_modules/vitest ] || pnpm install --frozen-lockfile +[ -d node_modules/vitest ] || pnpm install --frozen-lockfile || npm install # pnpm can fail with EACCES on its store; npm does not need it export PATH="${PG_BIN:-/usr/lib/postgresql/16/bin}:$PATH" dir="$(mktemp -d)" port="${PG_PORT:-54329}" diff --git a/tests/store.test.ts b/tests/store.test.ts index dac3b95..7c2bbd6 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -210,6 +210,41 @@ describe("consent_receipts foreign key", () => { }); }); +describe("PostgresStore.createConsentReceipt revocation conflict", () => { + async function granted() { + const adapter = newDb().adapters.createPg(); + const store = new PostgresStore(new adapter.Pool()); + await store.ensureSchema(); + const now = "2026-11-08T00:00:00.000Z"; + const account = await store.createAccount({ createdAt: now, lastSeenAt: now, displayName: "Probe" }); + const base = { accountId: account.id, appSlug: "streampixels" as const, provider: "joystick" as const }; + const { receipt: grant } = await store.createConsentReceipt({ ...base, kind: "grant", createdAt: now, scopesAsked: ["a"], scopesGranted: ["a"], consentPageDigest: "d", consentText: "t" }); + return { store, base, grant }; + } + + it("a second revocation of one grant inserts nothing: created:false, the first row's id", async () => { + const { store, base, grant } = await granted(); + const first = await store.createConsentReceipt({ ...base, kind: "revocation", createdAt: "2026-11-08T01:00:00.000Z", revokesReceiptId: grant.id }); + const second = await store.createConsentReceipt({ ...base, kind: "revocation", createdAt: "2026-11-08T02:00:00.000Z", revokesReceiptId: grant.id }); + expect(first.created).toBe(true); + expect(second.created).toBe(false); + expect(second.receipt.id).toBe(first.receipt.id); + expect(second.receipt.createdAt).toBe("2026-11-08T01:00:00.000Z"); + expect((await store.listConsentReceipts(base.accountId)).filter((r) => r.kind === "revocation")).toHaveLength(1); + }); + + it("the read-back returns the revocation of this grant, not another's or the grant", async () => { + const { store, base, grant } = await granted(); + const other = (await store.createConsentReceipt({ ...base, kind: "grant", createdAt: "2026-11-08T00:30:00.000Z", scopesAsked: [], scopesGranted: [], consentPageDigest: "d2", consentText: "t2" })).receipt; + const otherRevocation = await store.createConsentReceipt({ ...base, kind: "revocation", createdAt: "2026-11-08T01:00:00.000Z", revokesReceiptId: other.id }); + const first = await store.createConsentReceipt({ ...base, kind: "revocation", createdAt: "2026-11-08T01:10:00.000Z", revokesReceiptId: grant.id }); + const second = await store.createConsentReceipt({ ...base, kind: "revocation", createdAt: "2026-11-08T02:00:00.000Z", revokesReceiptId: grant.id }); + expect(second.receipt.id).toBe(first.receipt.id); + expect(second.receipt.id).not.toBe(otherRevocation.receipt.id); + expect(second.receipt.revokesReceiptId).toBe(grant.id); + }); +}); + describe("InMemoryStore.createConsentReceipt", () => { it("writes one revocation per grant: the second names the first and is not created", async () => { const store = new InMemoryStore(); From 0ea6691cd384a93c15f9188d000c9fec5421fb84 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sun, 8 Nov 2026 13:50:58 +0000 Subject: [PATCH 20/63] Refusal return contract: pin the fragment, carry the attempt id, document it The consent_refused page's return link is tested for heimdall_status, heimdall_error, heimdall_refused_by and no completion code, for both a decline and a provider access_denied. A browser_completion refusal now carries heimdall_attempt_id. The contract for app authors is in the consent doc. Co-Authored-By: Claude Sonnet 5.5 --- docs/joystick-consent-flow.md | 28 +++++++++++++ src/app.ts | 2 +- tests/joystick-consent.test.ts | 74 +++++++++++++++++++++++++++++++++- tests/store.test.ts | 2 +- 4 files changed, 103 insertions(+), 3 deletions(-) diff --git a/docs/joystick-consent-flow.md b/docs/joystick-consent-flow.md index 157e99c..3fafec6 100644 --- a/docs/joystick-consent-flow.md +++ b/docs/joystick-consent-flow.md @@ -192,6 +192,34 @@ the least stored. at the ask). A custody callback whose binding carries no wording is refused with `consent_text_missing` before the state is claimed, so nothing is burned. +### Refusal return contract (for app authors) + +A person's No at the ask, or a provider `access_denied`, is `consent_refused`. +No completion code is minted and the state is spent. What each side gets: + +- **Browser.** A 200 HTML page titled "Not Connected" (a non-HTML caller gets a 400 + JSON `{error, by, provider, returnTo}`). The page does not redirect: by ruling + it never navigates on its own. It posts the payload to `window.opener` + (target origin = the origin of `returnTo`), tries `window.close()` after 50 ms, + and offers a "Return to the app" link. In a plain tab the person clicks it. +- **The link** is `returnTo` with a fragment (read `location.hash`; it never + reaches a server): `heimdall_status=error`, `heimdall_error=consent_refused`, + `heimdall_refused_by=viewer|provider`, `heimdall_provider`, + `heimdall_handoff_kind`, `heimdall_app_slug`, `heimdall_mode`, and + `heimdall_attempt_id` when the flow carries an attempt. There is no + `heimdall_completion_code`; a page with none, and `heimdall_error`, is a refusal. + A fault is a different `heimdall_error` (`provider_error` and others). +- **postMessage** carries `{source: "heimdall", kind: "oauth_result", + status: "error", error: "consent_refused", by, provider, appSlug, mode, + returnTo, handoffKind, attemptId?}`. +- **Backend callback apps** get the same result POSTed to their callback URL + (`status: "error"`, `error: "consent_refused"`, `by`, `attemptId`). An auth + attempt is marked `denied` with `denialCode: "consent_refused"`, which + `completeAuth` returns as `denied`. + +`tests/joystick-consent.test.ts` ("the refusal return contract") pins the +fragment for both refusals and the attempt id. + ## 5. Out of scope Enabling Joystick in `identityProviders`; fixing diff --git a/src/app.ts b/src/app.ts index f4a48e5..2051499 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1311,7 +1311,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { }); }); +/** What an app's landing page can read: the fragment on the page's "Return to the app" link. */ +function returnFragment(page: { body: string }): URLSearchParams { + const href = /id="return-link" href="([^"]+)"/.exec(page.body)?.[1]; + expect(href, "the page carries a return link").toBeDefined(); + const url = new URL(href!); + expect(url.origin + url.pathname).toBe("https://streampixels.gamecult.org/settings"); + return new URLSearchParams(url.hash.slice(1)); +} + +describe("the refusal return contract", () => { + const refusedFragment = (by: "viewer" | "provider") => ({ + heimdall_status: "error", + heimdall_provider: "joystick", + heimdall_handoff_kind: "browser_completion", + heimdall_app_slug: "streampixels", + heimdall_mode: "connect", + heimdall_error: "consent_refused", + heimdall_refused_by: by, + }); + + it("a decline returns a fragment that says the viewer refused, with no completion code", async () => { + const { app } = await newApp(); + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + const fragment = returnFragment(await answer(app, state, "decline", cookie)); + expect(Object.fromEntries(fragment)).toEqual(refusedFragment("viewer")); + expect(fragment.has("heimdall_completion_code")).toBe(false); + }); + + it("a provider access_denied returns a fragment that says the provider refused, with no completion code", async () => { + const { app } = await newApp(); + const flow = await newFlow(app); + const fragment = returnFragment(await callback(app, flow.state, flow.cookie, "error=access_denied", "text/html")); + expect(Object.fromEntries(fragment)).toEqual(refusedFragment("provider")); + expect(fragment.has("heimdall_completion_code")).toBe(false); + }); + + it.each(["viewer", "provider"] as const)("a browser_completion attempt refused by the %s is named in the fragment", async (by) => { + const { app, store } = await newApp(); + const ctx = getHeimdallRuntimeContext(app); + const attempt = await store.createAuthAttempt({ + handle: "attempt-refused", + appSlug: "streampixels", + provider: "joystick", + mode: "connect", + returnTo: "https://streampixels.gamecult.org/settings", + createdAt: new Date().toISOString(), + expiresAt: new Date(Date.now() + 600_000).toISOString(), + }); + const caller = resolveAppCaller(ctx.config, "streampixels", secret); + const started = await startOAuthFlow( + ctx, + "joystick", + caller, + { appSlug: "streampixels", mode: "connect", connection: { kind: "creator", targetId: "creator-1" }, returnTo: "https://streampixels.gamecult.org/settings", handoff: { kind: "browser_completion" } }, + { trustedBrowserAttemptId: attempt.handle } + ); + expect(started.statusCode).toBe(201); + const state = stateOf(started.body as Parameters[0]); + const { cookie } = await seeAsk(app, state); + let page; + if (by === "viewer") { + page = await answer(app, state, "decline", cookie); + } else { + const go = await answer(app, state, "continue", cookie); + page = await callback(app, state, bindingCookieOf(go)!, "error=access_denied", "text/html"); + } + expect(Object.fromEntries(returnFragment(page))).toEqual({ ...refusedFragment(by), heimdall_attempt_id: "attempt-refused" }); + }); +}); + async function newFlow(app: FastifyInstance) { const state = await startConnect(app); const { cookie } = await seeAsk(app, state); diff --git a/tests/store.test.ts b/tests/store.test.ts index 7c2bbd6..7599ff6 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -241,7 +241,7 @@ describe("PostgresStore.createConsentReceipt revocation conflict", () => { const second = await store.createConsentReceipt({ ...base, kind: "revocation", createdAt: "2026-11-08T02:00:00.000Z", revokesReceiptId: grant.id }); expect(second.receipt.id).toBe(first.receipt.id); expect(second.receipt.id).not.toBe(otherRevocation.receipt.id); - expect(second.receipt.revokesReceiptId).toBe(grant.id); + expect(second.receipt).toMatchObject({ kind: "revocation", revokesReceiptId: grant.id }); }); }); From f5f4b2830ffc44cbcf1e07de949b9e7c37800a87 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sun, 8 Nov 2026 21:35:13 +0000 Subject: [PATCH 21/63] Record a failed refresh on the linked identity row so another process does not re-present the token A failed or timed-out refresh attempt now writes refresh_failed_at under the row lock; a process that takes the lock inside a 60 s backoff answers managed_credential_refresh_failed without calling the provider. Rotation, revocation and re-link clear the marker. Closes the cross-process residual that refresh-once-per-token left to a follow-up, and pins it on the two-pool rig. Co-Authored-By: Claude Sonnet 5.5 --- docs/service-contract.md | 12 ++-- src/managed-credential.ts | 25 ++++++-- src/store/in-memory.ts | 6 ++ src/store/postgres.ts | 15 ++++- src/store/schema.ts | 5 ++ src/store/types.ts | 10 ++- tests/managed-credential.test.ts | 104 ++++++++++++++++++++++++++++--- 7 files changed, 156 insertions(+), 21 deletions(-) diff --git a/docs/service-contract.md b/docs/service-contract.md index e6ad6c1..f27e5e1 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -567,11 +567,13 @@ Important behavior: identity (`SELECT ... FOR UPDATE`), so a given refresh token is presented to the provider once across concurrent requests and across two Heimdall processes sharing one database. Within one process, concurrent refreshes of - one identity share a single attempt and its outcome (success or failure), so - nobody re-presents a token behind a failed holder in that burst. Residual - risk, tracked as follow-up `joystick:follow_up:cross-process-failed-refresh-marker`: - the guard is one presentation per process per burst, so N - Heimdall processes can present one token N times after a transient failure. + one identity share a single attempt and its outcome (success or failure). A + failed or timed-out attempt is recorded on the identity row + (`refresh_failed_at`, written in the same transaction as the lock), and no + process presents that row's refresh token again for 60 seconds: a process + that takes the lock inside the backoff answers the same + `managed_credential_refresh_failed` without calling the provider. A rotation, + a revocation or a re-link clears the marker. The provider call is bounded at 10 seconds - a provider whose refresh tokens rotate (Joystick) fails closed: a refresh response without a new refresh token revokes the credential instead of diff --git a/src/managed-credential.ts b/src/managed-credential.ts index 32e9f51..063b733 100644 --- a/src/managed-credential.ts +++ b/src/managed-credential.ts @@ -16,6 +16,14 @@ export const MANAGED_CREDENTIAL_REFRESH_SKEW_MS = 5 * 60 * 1000; */ export const MANAGED_CREDENTIAL_REFRESH_TIMEOUT_MS = 10_000; +/** + * After a refresh attempt fails or times out, no process presents the row's + * refresh token again until this long has passed (the failure is recorded on + * the row, read under the lock). A provider that rotates may have consumed the + * token before the attempt was aborted, and presenting it again reads as theft. + */ +export const MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS = 60 * 1000; + export interface ManagedCredentialContext { config: HeimdallConfig; store: HeimdallStore; @@ -68,10 +76,8 @@ function withoutTokens(identity: StoredLinkedIdentity): StoredLinkedIdentity { * attempt is in flight join it and receive its outcome, success or failure. * The entry lives exactly as long as the attempt: a later request retries. * - * Known residual risk (docs/service-contract.md): one presentation per - * process per burst, so N processes may present one token N times. The - * cross-process failed-refresh marker that would close it is - * joystick:follow_up:cross-process-failed-refresh-marker. + * Across processes the row owns it: a failed attempt leaves a marker on the + * row, and a process that takes the lock inside the backoff presents nothing. */ const refreshesInFlight = new WeakMap>>(); @@ -120,10 +126,15 @@ async function refreshUnderLock( const runtime = ctx.oauthRuntimes[provider]; let revocation: ManagedCredentialRevocationReason | undefined; + let failed = false; const decide = async (locked: StoredLinkedIdentity): Promise => { if (!locked.accessTokenEncrypted || !dueForRefresh(locked, runtime, clock())) { return { kind: "keep" }; } + if (locked.refreshFailedAt && clock() - Date.parse(locked.refreshFailedAt) < MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS) { + failed = true; + return { kind: "keep" }; + } const updatedAt = new Date(clock()).toISOString(); const refreshToken = ctx.tokenCustody.decrypt(locked.refreshTokenEncrypted!); @@ -139,7 +150,8 @@ async function refreshUnderLock( revocation = "provider_revoked"; return { kind: "revoke", updatedAt }; } - throw new ManagedCredentialRefreshFailed(provider); + failed = true; + return { kind: "failed", failedAt: updatedAt }; } let refreshTokenEncrypted: string; @@ -174,6 +186,9 @@ async function refreshUnderLock( createdAt: new Date(clock()).toISOString(), }); } + if (failed) { + throw new ManagedCredentialRefreshFailed(provider); + } if (!committed) { return { kind: "revoked", identity: withoutTokens(snapshot) }; } diff --git a/src/store/in-memory.ts b/src/store/in-memory.ts index e829900..e86490d 100644 --- a/src/store/in-memory.ts +++ b/src/store/in-memory.ts @@ -203,7 +203,13 @@ export class InMemoryStore implements HeimdallStore { if (decision.kind === "keep") { return clone(current); } + if (decision.kind === "failed") { + const marked: StoredLinkedIdentity = { ...current, refreshFailedAt: decision.failedAt }; + this.linkedIdentities.set(id, clone(marked)); + return clone(marked); + } const next: StoredLinkedIdentity = { ...current, updatedAt: decision.updatedAt }; + delete next.refreshFailedAt; delete next.accessTokenEncrypted; delete next.refreshTokenEncrypted; delete next.tokenExpiresAt; diff --git a/src/store/postgres.ts b/src/store/postgres.ts index 3d34047..0c4fc05 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -47,6 +47,7 @@ interface LinkedIdentityRow extends QueryResultRow { access_token_encrypted: string | null; refresh_token_encrypted: string | null; token_expires_at: string | null; + refresh_failed_at: string | null; scopes: string; profile_json: Record; created_at: string; @@ -207,6 +208,10 @@ function mapLinkedIdentityRow(row: LinkedIdentityRow): StoredLinkedIdentity { identity.tokenExpiresAt = new Date(row.token_expires_at).toISOString(); } + if (row.refresh_failed_at) { + identity.refreshFailedAt = new Date(row.refresh_failed_at).toISOString(); + } + return identity; } @@ -777,6 +782,7 @@ export class PostgresStore implements HeimdallStore { access_token_encrypted = EXCLUDED.access_token_encrypted, refresh_token_encrypted = EXCLUDED.refresh_token_encrypted, token_expires_at = EXCLUDED.token_expires_at, + refresh_failed_at = NULL, scopes = EXCLUDED.scopes, profile_json = EXCLUDED.profile_json, updated_at = EXCLUDED.updated_at @@ -822,7 +828,13 @@ export class PostgresStore implements HeimdallStore { const row = mapLinkedIdentityRow(expectRow(locked.rows[0], "updateLinkedIdentityCredential")); const decision = await decide(row); let committed = row; - if (decision.kind !== "keep") { + if (decision.kind === "failed") { + const marked = await client.query( + "UPDATE linked_identities SET refresh_failed_at = $2 WHERE id = $1 RETURNING *", + [id, decision.failedAt] + ); + committed = mapLinkedIdentityRow(expectRow(marked.rows[0], "updateLinkedIdentityCredential")); + } else if (decision.kind !== "keep") { const rotated = decision.kind === "rotate" ? decision : undefined; const written = await client.query( ` @@ -830,6 +842,7 @@ export class PostgresStore implements HeimdallStore { SET access_token_encrypted = $2, refresh_token_encrypted = $3, token_expires_at = $4, + refresh_failed_at = NULL, scopes = $5, updated_at = $6 WHERE id = $1 diff --git a/src/store/schema.ts b/src/store/schema.ts index 294ee2d..7aa6823 100644 --- a/src/store/schema.ts +++ b/src/store/schema.ts @@ -123,6 +123,11 @@ ALTER TABLE auth_completions ADD COLUMN IF NOT EXISTS attempt_id TEXT; -- compares it against the target the redeeming app states. ALTER TABLE auth_completions ADD COLUMN IF NOT EXISTS target_id TEXT; +-- When a refresh attempt on this row last failed or timed out, read under the row +-- lock so a second Heimdall process does not present the same refresh token +-- right behind it. Cleared by rotation, revocation and re-link. +ALTER TABLE linked_identities ADD COLUMN IF NOT EXISTS refresh_failed_at TIMESTAMPTZ; + -- One attempt handle may bind at most one unconsumed completion (R21.1): a -- second completion for the same handle would let the by-attempt UPDATE in -- consumeAuthCompletionByAttempt match more than one row, silently consuming diff --git a/src/store/types.ts b/src/store/types.ts index bb2e080..c795247 100644 --- a/src/store/types.ts +++ b/src/store/types.ts @@ -33,6 +33,8 @@ export interface StoredLinkedIdentity { accessTokenEncrypted?: string; refreshTokenEncrypted?: string; tokenExpiresAt?: string; + /** When a refresh attempt last failed; cleared by the next rotation, revocation or re-link. */ + refreshFailedAt?: string; scopes: string[]; profileJson: Record; createdAt: string; @@ -58,8 +60,9 @@ export interface UpsertLinkedIdentityInput { /** * What the owner of a refresh decides after reading the row under its lock. - * `rotate` and `revoke` write token columns, scopes and updated_at only; they - * never touch account, profile or identity fields. + * `rotate` and `revoke` write token columns, scopes, updated_at and clear the + * failed-refresh marker; `failed` writes the marker alone. None touches + * account, profile or identity fields. */ export type CredentialDecision = | { kind: "keep" } @@ -71,7 +74,8 @@ export type CredentialDecision = scopes: string[]; updatedAt: string; } - | { kind: "revoke"; updatedAt: string }; + | { kind: "revoke"; updatedAt: string } + | { kind: "failed"; failedAt: string }; export interface StoredSession { id: string; diff --git a/tests/managed-credential.test.ts b/tests/managed-credential.test.ts index ffe1472..03bcc1a 100644 --- a/tests/managed-credential.test.ts +++ b/tests/managed-credential.test.ts @@ -6,6 +6,7 @@ import { type HeimdallConfig } from "../src/config.js"; import { type Provider } from "../src/contracts.js"; import { createTokenCustody } from "../src/custody.js"; import { + MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS, MANAGED_CREDENTIAL_REFRESH_SKEW_MS, ManagedCredentialRefreshFailed, refreshManagedCredential, @@ -419,17 +420,18 @@ for (const { kind, live } of rigKinds) describe.skipIf(live && !adminUrl)(`manag expect(Date.now() - started).toBeLessThan(5_000); endpoint.mode = "normal"; - const outcome = await refreshManagedCredential(ctx, await rig.row()); + const afterBackoff = { ...ctx, clock: () => Date.now() + MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS }; + const outcome = await refreshManagedCredential(afterBackoff, await rig.row()); expect(outcome.kind).toBe("current"); expect(rig.custody.decrypt(outcome.identity.accessTokenEncrypted!)).toBe("access-1"); }); - it("single flight: concurrent refreshes against a never-answering endpoint make one provider call per process, and every caller gets the typed failure", timeout, async () => { + it("single flight: concurrent refreshes against a never-answering endpoint make one provider call across all processes, and every caller gets the typed failure", timeout, async () => { const rig = await makeRig(provider); const endpoint = installTokenEndpoint(provider, "refresh-0"); endpoint.mode = "hang"; const snapshot = await rig.row(); - const ctxFor = (store: HeimdallStore) => ({ config: rig.config, store, tokenCustody: rig.custody, oauthRuntimes: createOAuthRuntimeRegistry(), timeoutMs: 150 }); + const ctxFor = (store: HeimdallStore, clock = Date.now) => ({ config: rig.config, store, tokenCustody: rig.custody, oauthRuntimes: createOAuthRuntimeRegistry(), timeoutMs: 150, clock }); const results = await Promise.allSettled( Array.from({ length: 12 }, (_, i) => refreshManagedCredential(ctxFor(rig.stores[i % rig.stores.length]!), snapshot)) @@ -439,14 +441,102 @@ for (const { kind, live } of rigKinds) describe.skipIf(live && !adminUrl)(`manag for (const result of results) { expect((result as PromiseRejectedResult).reason).toBeInstanceOf(ManagedCredentialRefreshFailed); } - expect(endpoint.calls).toBe(rig.stores.length); + // The process that queued behind the failed holder reads the holder's marker under the lock and presents nothing. + expect(endpoint.calls).toBe(1); expect(rig.custody.decrypt((await rig.row()).refreshTokenEncrypted!)).toBe("refresh-0"); - // The burst is over: a later independent request tries again. + // The burst is over and so is the backoff the failure left on the row: a later independent request tries again. endpoint.mode = "normal"; - const later = await refreshManagedCredential(ctxFor(rig.stores[0]!), await rig.row()); + const later = await refreshManagedCredential(ctxFor(rig.stores[0]!, () => Date.now() + MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS), await rig.row()); expect(later.kind).toBe("current"); - expect(endpoint.calls).toBe(rig.stores.length + 1); + expect(endpoint.calls).toBe(2); + }); + + it.each(["server_error", "hang"] as const)( + "cross-process failed-refresh marker (%s): the failed attempt is recorded on the row, and another process does not present the token inside the backoff", + timeout, + async (mode) => { + const rig = await makeRig(provider); + const endpoint = installTokenEndpoint(provider, "refresh-0"); + endpoint.mode = mode; + const t0 = Date.now(); + const ctxFor = (store: HeimdallStore, at: number) => ({ + config: rig.config, store, tokenCustody: rig.custody, oauthRuntimes: createOAuthRuntimeRegistry(), timeoutMs: 100, clock: () => at, + }); + const snapshot = await rig.row(); + const first = rig.stores[0]!; + const other = rig.stores[rig.stores.length - 1]!; + + await expect(refreshManagedCredential(ctxFor(first, t0), snapshot)).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + expect(endpoint.calls).toBe(1); + const marked = await rig.row(); + expect(marked.refreshFailedAt).toBe(new Date(t0).toISOString()); + expect(marked.accessTokenEncrypted).toBe(snapshot.accessTokenEncrypted); + expect(marked.refreshTokenEncrypted).toBe(snapshot.refreshTokenEncrypted); + expect(marked.tokenExpiresAt).toBe(snapshot.tokenExpiresAt); + + // Another process, holding the stale snapshot, one tick before the backoff ends: the locked row decides, and no token call is made. + const backedOff = ctxFor(other, t0 + MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS - 1); + await expect(refreshManagedCredential(backedOff, snapshot)).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + expect(endpoint.calls).toBe(1); + // Being turned away does not extend the backoff. + expect((await rig.row()).refreshFailedAt).toBe(marked.refreshFailedAt); + expect(await rig.audit()).toEqual([]); + } + ); + + it("cross-process failed-refresh marker: the backoff ends exactly at its length, a success clears the marker, and a failure after it marks anew", timeout, async () => { + const rig = await makeRig(provider); + const endpoint = installTokenEndpoint(provider, "refresh-0"); + endpoint.mode = "server_error"; + const t0 = Date.now(); + const ctxAt = (at: number) => ({ config: rig.config, store: rig.stores[0]!, tokenCustody: rig.custody, oauthRuntimes: createOAuthRuntimeRegistry(), clock: () => at }); + await expect(refreshManagedCredential(ctxAt(t0), await rig.row())).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + + const retryAt = t0 + MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS; + await expect(refreshManagedCredential(ctxAt(retryAt), await rig.row())).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + expect(endpoint.calls).toBe(2); + expect((await rig.row()).refreshFailedAt).toBe(new Date(retryAt).toISOString()); + + endpoint.mode = "normal"; + const laterAt = retryAt + MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS; + const outcome = await refreshManagedCredential(ctxAt(laterAt), await rig.row()); + expect(outcome.kind).toBe("current"); + expect(endpoint.calls).toBe(3); + expect(rig.custody.decrypt(outcome.identity.accessTokenEncrypted!)).toBe("access-1"); + expect((await rig.row()).refreshFailedAt).toBeUndefined(); + }); + + it("cross-process failed-refresh marker: a revocation and a re-link both clear it", timeout, async () => { + const rig = await makeRig(provider); + const endpoint = installTokenEndpoint(provider, "refresh-0"); + endpoint.mode = "server_error"; + const t0 = Date.now(); + const ctxAt = (at: number) => ({ config: rig.config, store: rig.stores[0]!, tokenCustody: rig.custody, oauthRuntimes: createOAuthRuntimeRegistry(), clock: () => at }); + await expect(refreshManagedCredential(ctxAt(t0), await rig.row())).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + expect((await rig.row()).refreshFailedAt).toBeDefined(); + + endpoint.mode = "invalid_grant"; + const revoked = await refreshManagedCredential(ctxAt(t0 + MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS), await rig.row()); + expect(revoked.kind).toBe("revoked"); + expect((await rig.row()).refreshFailedAt).toBeUndefined(); + + // A fresh consent after a failure replaces the whole credential, marker included. + endpoint.mode = "server_error"; + const relinkSeed = await rig.row(); + await rig.stores[0]!.upsertLinkedIdentity({ + accountId: rig.accountId, provider, providerUserId: relinkSeed.providerUserId, scopes: ["identity:read"], profileJson: {}, + accessTokenEncrypted: rig.custody.encrypt("access-r"), refreshTokenEncrypted: rig.custody.encrypt("refresh-r"), + tokenExpiresAt: new Date(t0 + 1000).toISOString(), createdAt: relinkSeed.createdAt, updatedAt: new Date(t0).toISOString(), + }); + await expect(refreshManagedCredential(ctxAt(t0 + 2000), await rig.row())).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + expect((await rig.row()).refreshFailedAt).toBeDefined(); + await rig.stores[0]!.upsertLinkedIdentity({ + accountId: rig.accountId, provider, providerUserId: relinkSeed.providerUserId, scopes: ["identity:read"], profileJson: {}, + accessTokenEncrypted: rig.custody.encrypt("access-s"), refreshTokenEncrypted: rig.custody.encrypt("refresh-s"), + tokenExpiresAt: new Date(t0 + 3000).toISOString(), createdAt: relinkSeed.createdAt, updatedAt: new Date(t0 + 2500).toISOString(), + }); + expect((await rig.row()).refreshFailedAt).toBeUndefined(); }); it("a snapshot taken before another caller's refresh does not decide: the locked row does", timeout, async () => { From a0bd9836b130935872884cb3b72c3314937cf733 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sun, 8 Nov 2026 21:40:39 +0000 Subject: [PATCH 22/63] Count the new linked_identities column in the schema inventory test Co-Authored-By: Claude Sonnet 5.5 --- tests/store.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/store.test.ts b/tests/store.test.ts index 7599ff6..75ee256 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -333,7 +333,7 @@ describe("PostgresStore.checkSchema", () => { "consent_receipts", "audit_events", ]); - expect(REQUIRED_COLUMNS).toHaveLength(112); + expect(REQUIRED_COLUMNS).toHaveLength(113); expect(REQUIRED_COLUMNS).toEqual( expect.arrayContaining([ { table: "auth_completions", column: "code", type: "TEXT", nullable: false }, From 9da4b12bc27d011cd0a1405d38e10da6cfc5f17e Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sun, 8 Nov 2026 21:48:13 +0000 Subject: [PATCH 23/63] Make the failed-refresh marker durable and stamp it with the failure time The marker carried the time the attempt began, so a slow failure ate the backoff; it now carries the time the provider's answer (or failure) was known. A throw after the provider answered (custody encrypt) records the marker instead of rolling it back, and a rotation Postgres refuses to write leaves the marker in a transaction of its own. A stamp from a writer's clock ahead of the reader's by the backoff or more is treated as skew, not a fresh failure. Co-Authored-By: Claude Sonnet 5.5 --- src/managed-credential.ts | 78 ++++++++++++++++++----------- src/store/postgres.ts | 11 ++++- tests/managed-credential.test.ts | 85 ++++++++++++++++++++++++++++++++ 3 files changed, 145 insertions(+), 29 deletions(-) diff --git a/src/managed-credential.ts b/src/managed-credential.ts index 063b733..b11f3f4 100644 --- a/src/managed-credential.ts +++ b/src/managed-credential.ts @@ -1,7 +1,7 @@ import { type HeimdallConfig } from "./config.js"; import { type Provider } from "./contracts.js"; import { type TokenCustody } from "./custody.js"; -import { type OAuthProviderRuntime, type OAuthRuntimeRegistry, ProviderResponseError } from "./oauth.js"; +import { type ExpiringTokenSet, type OAuthProviderRuntime, type OAuthRuntimeRegistry, ProviderResponseError } from "./oauth.js"; import { providerCatalog } from "./providers.js"; import { type HeimdallStore } from "./store/index.js"; import { type CredentialDecision, type StoredLinkedIdentity } from "./store/types.js"; @@ -63,6 +63,17 @@ function dueForRefresh(identity: StoredLinkedIdentity, runtime: OAuthProviderRun return Date.parse(identity.tokenExpiresAt) - now <= MANAGED_CREDENTIAL_REFRESH_SKEW_MS; } +/** + * Whether a failure stamped `failedAt` still holds this clock off. A stamp from + * a writer whose clock runs ahead reads as the future; one this far ahead or + * more is skew, not a fresh failure, so the wait stays bounded at twice the + * backoff. + */ +function withinBackoff(failedAt: string, now: number): boolean { + const elapsed = now - Date.parse(failedAt); + return elapsed > -MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS && elapsed < MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS; +} + function withoutTokens(identity: StoredLinkedIdentity): StoredLinkedIdentity { const { accessTokenEncrypted: _a, refreshTokenEncrypted: _r, tokenExpiresAt: _e, ...rest } = identity; return rest; @@ -127,33 +138,7 @@ async function refreshUnderLock( let revocation: ManagedCredentialRevocationReason | undefined; let failed = false; - const decide = async (locked: StoredLinkedIdentity): Promise => { - if (!locked.accessTokenEncrypted || !dueForRefresh(locked, runtime, clock())) { - return { kind: "keep" }; - } - if (locked.refreshFailedAt && clock() - Date.parse(locked.refreshFailedAt) < MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS) { - failed = true; - return { kind: "keep" }; - } - const updatedAt = new Date(clock()).toISOString(); - const refreshToken = ctx.tokenCustody.decrypt(locked.refreshTokenEncrypted!); - - let refreshed; - try { - refreshed = await runtime.refreshAccessToken!({ - config: ctx.config, - refreshToken, - signal: AbortSignal.timeout(ctx.timeoutMs ?? MANAGED_CREDENTIAL_REFRESH_TIMEOUT_MS), - }); - } catch (error) { - if (error instanceof ProviderResponseError && error.oauthError === "invalid_grant") { - revocation = "provider_revoked"; - return { kind: "revoke", updatedAt }; - } - failed = true; - return { kind: "failed", failedAt: updatedAt }; - } - + const rotation = (locked: StoredLinkedIdentity, refreshed: ExpiringTokenSet, updatedAt: string): CredentialDecision => { let refreshTokenEncrypted: string; if (refreshed.refreshToken) { refreshTokenEncrypted = ctx.tokenCustody.encrypt(refreshed.refreshToken); @@ -177,6 +162,43 @@ async function refreshUnderLock( }; }; + const decide = async (locked: StoredLinkedIdentity): Promise => { + if (!locked.accessTokenEncrypted || !dueForRefresh(locked, runtime, clock())) { + return { kind: "keep" }; + } + if (locked.refreshFailedAt && withinBackoff(locked.refreshFailedAt, clock())) { + failed = true; + return { kind: "keep" }; + } + const refreshToken = ctx.tokenCustody.decrypt(locked.refreshTokenEncrypted!); + + let refreshed; + try { + refreshed = await runtime.refreshAccessToken!({ + config: ctx.config, + refreshToken, + signal: AbortSignal.timeout(ctx.timeoutMs ?? MANAGED_CREDENTIAL_REFRESH_TIMEOUT_MS), + }); + } catch (error) { + if (error instanceof ProviderResponseError && error.oauthError === "invalid_grant") { + revocation = "provider_revoked"; + return { kind: "revoke", updatedAt: new Date(clock()).toISOString() }; + } + failed = true; + return { kind: "failed", failedAt: new Date(clock()).toISOString() }; + } + + // The provider has answered, and may have consumed the token: from here a throw must still leave the marker, which + // a rolled-back transaction would not (the store writes it on its own for a rotation it could not commit). + const answeredAt = new Date(clock()).toISOString(); + try { + return rotation(locked, refreshed, answeredAt); + } catch { + failed = true; + return { kind: "failed", failedAt: new Date(clock()).toISOString() }; + } + }; + const committed = await ctx.store.updateLinkedIdentityCredential(snapshot.id, decide); if (revocation) { await ctx.store.createAuditEvent({ diff --git a/src/store/postgres.ts b/src/store/postgres.ts index 0c4fc05..d2fc9db 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -816,6 +816,7 @@ export class PostgresStore implements HeimdallStore { const client = await this.pool.connect(); try { await client.query("BEGIN"); + let decision: CredentialDecision | undefined; try { const locked = await client.query( "SELECT * FROM linked_identities WHERE id = $1 FOR UPDATE", @@ -826,7 +827,7 @@ export class PostgresStore implements HeimdallStore { return null; } const row = mapLinkedIdentityRow(expectRow(locked.rows[0], "updateLinkedIdentityCredential")); - const decision = await decide(row); + decision = await decide(row); let committed = row; if (decision.kind === "failed") { const marked = await client.query( @@ -863,6 +864,14 @@ export class PostgresStore implements HeimdallStore { return committed; } catch (error) { await client.query("ROLLBACK"); + if (decision?.kind === "rotate") { + // The provider answered and may have consumed the refresh token, and the rotation could not be committed: the + // rollback took the answer with it. Leave the marker in a transaction of its own, so the next caller does not + // present the old token. Best effort: if this write fails too, the original error is the one that matters. + await client + .query("UPDATE linked_identities SET refresh_failed_at = $2 WHERE id = $1", [id, decision.updatedAt]) + .catch(() => undefined); + } throw error; } } finally { diff --git a/tests/managed-credential.test.ts b/tests/managed-credential.test.ts index 03bcc1a..9744abc 100644 --- a/tests/managed-credential.test.ts +++ b/tests/managed-credential.test.ts @@ -539,6 +539,91 @@ for (const { kind, live } of rigKinds) describe.skipIf(live && !adminUrl)(`manag expect((await rig.row()).refreshFailedAt).toBeUndefined(); }); + it("cross-process failed-refresh marker: stamped with the time of the failure, so a slow failure does not eat the backoff", timeout, async () => { + const rig = await makeRig(provider); + const endpoint = installTokenEndpoint(provider, "refresh-0"); + endpoint.mode = "server_error"; + const t0 = Date.now(); + // The provider call takes 9 s of the clock's time: the failure is known at t0 + 9 s, not at t0. + const slowClock = () => t0 + (endpoint.calls > 0 ? 9_000 : 0); + const ctx = (store: HeimdallStore, clock: () => number) => ({ config: rig.config, store, tokenCustody: rig.custody, oauthRuntimes: createOAuthRuntimeRegistry(), clock }); + const snapshot = await rig.row(); + + await expect(refreshManagedCredential(ctx(rig.stores[0]!, slowClock), snapshot)).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + expect((await rig.row()).refreshFailedAt).toBe(new Date(t0 + 9_000).toISOString()); + + // 51 s after the failure, 60 s after the attempt began: still inside the backoff. + const other = rig.stores[rig.stores.length - 1]!; + await expect(refreshManagedCredential(ctx(other, () => t0 + MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS), snapshot)).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + expect(endpoint.calls).toBe(1); + }); + + it("cross-process failed-refresh marker: a failure after the provider answered still leaves the marker (the provider may have consumed the token)", timeout, async () => { + const rig = await makeRig(provider); + const endpoint = installTokenEndpoint(provider, "refresh-0"); + const snapshot = await rig.row(); + const throwingCustody = { + ...rig.custody, + encrypt: (plaintext: string) => { + if (plaintext === "access-1") throw new Error("CANARY custody encrypt failed"); + return rig.custody.encrypt(plaintext); + }, + }; + const ctx = (store: HeimdallStore, tokenCustody: typeof rig.custody) => ({ config: rig.config, store, tokenCustody, oauthRuntimes: createOAuthRuntimeRegistry() }); + + const failure = await refreshManagedCredential(ctx(rig.stores[0]!, throwingCustody), snapshot).then(() => undefined, (error: unknown) => error); + expect(failure).toBeInstanceOf(ManagedCredentialRefreshFailed); + expect(String(failure) + JSON.stringify(failure)).not.toContain("CANARY"); + expect(endpoint.calls).toBe(1); + const marked = await rig.row(); + expect(marked.refreshFailedAt).toBeDefined(); + expect(marked.refreshTokenEncrypted).toBe(snapshot.refreshTokenEncrypted); + + // Another process inside the backoff does not present the old token again. + await expect(refreshManagedCredential(ctx(rig.stores[rig.stores.length - 1]!, rig.custody), snapshot)).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + expect(endpoint.calls).toBe(1); + }); + + it.skipIf(!live)("cross-process failed-refresh marker: a rotation the database refuses to write still leaves the marker", timeout, async () => { + const rig = await makeRig(provider); + const endpoint = installTokenEndpoint(provider, "refresh-0"); + const snapshot = await rig.row(); + const db = new Pool({ connectionString: rig.databaseUrl!, max: 1 }); + db.on("error", () => undefined); + try { + await db.query(`CREATE FUNCTION refuse_rotation() RETURNS trigger AS $$ BEGIN RAISE EXCEPTION 'CANARY rotation write refused'; END $$ LANGUAGE plpgsql`); + await db.query(`CREATE TRIGGER refuse_rotation BEFORE UPDATE ON linked_identities FOR EACH ROW WHEN (NEW.access_token_encrypted IS DISTINCT FROM OLD.access_token_encrypted) EXECUTE FUNCTION refuse_rotation()`); + const ctx = (store: HeimdallStore) => ({ config: rig.config, store, tokenCustody: rig.custody, oauthRuntimes: createOAuthRuntimeRegistry() }); + + await expect(refreshManagedCredential(ctx(rig.stores[0]!), snapshot)).rejects.toThrow(); + expect(endpoint.calls).toBe(1); + const marked = await rig.row(); + expect(marked.refreshFailedAt).toBeDefined(); + expect(marked.refreshTokenEncrypted).toBe(snapshot.refreshTokenEncrypted); + + await expect(refreshManagedCredential(ctx(rig.stores[rig.stores.length - 1]!), snapshot)).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + expect(endpoint.calls).toBe(1); + } finally { + await db.end(); + } + }); + + it("cross-process failed-refresh marker: a writer's clock skewed by under the backoff still holds the reader off, and by the backoff or more does not", timeout, async () => { + const rig = await makeRig(provider); + const endpoint = installTokenEndpoint(provider, "refresh-0"); + endpoint.mode = "server_error"; + const t0 = Date.now(); + const ctxAt = (at: number) => ({ config: rig.config, store: rig.stores[0]!, tokenCustody: rig.custody, oauthRuntimes: createOAuthRuntimeRegistry(), clock: () => at }); + await expect(refreshManagedCredential(ctxAt(t0), await rig.row())).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + expect(endpoint.calls).toBe(1); + + // The marker is in this reader's future: a writer ahead of it. A bounded wait, not a refusal for as long as the skew. + await expect(refreshManagedCredential(ctxAt(t0 - MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS + 1), await rig.row())).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + expect(endpoint.calls).toBe(1); + await expect(refreshManagedCredential(ctxAt(t0 - MANAGED_CREDENTIAL_REFRESH_BACKOFF_MS), await rig.row())).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + expect(endpoint.calls).toBe(2); + }); + it("a snapshot taken before another caller's refresh does not decide: the locked row does", timeout, async () => { const rig = await makeRig(provider); const endpoint = installTokenEndpoint(provider, "refresh-0"); From 1118f235b02b937fadb7569f40cbba61651c4353 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sun, 8 Nov 2026 21:53:12 +0000 Subject: [PATCH 24/63] Docs: name the process-death residual in the refresh contract Co-Authored-By: Claude Sonnet 5.5 --- docs/service-contract.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/service-contract.md b/docs/service-contract.md index f27e5e1..f0be8ed 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -574,6 +574,14 @@ Important behavior: that takes the lock inside the backoff answers the same `managed_credential_refresh_failed` without calling the provider. A rotation, a revocation or a re-link clears the marker. + Residual risk: if a Heimdall process dies between the provider's token + answer and the commit of the marker or the rotation, nothing is recorded, and + the next caller can present the refresh token the provider already consumed; + for a provider that rotates (Joystick) that reads as token theft. Closing it + needs a write-ahead record of the attempt, written before the provider call on + a connection that does not wait on the row lock (a separate table). That is + deferred by steward ruling and tracked as + `joystick:follow_up:write-ahead-refresh-attempt-record` The provider call is bounded at 10 seconds - a provider whose refresh tokens rotate (Joystick) fails closed: a refresh response without a new refresh token revokes the credential instead of From 9c7d980165c867bde3ae499b6312498ae707feb1 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sun, 8 Nov 2026 21:56:40 +0000 Subject: [PATCH 25/63] Leave the failed-refresh marker when the revoke a rotating provider's answer called for cannot be written A rotating provider that answered without a new refresh token has consumed the old one; the revoke that follows is rolled back if its UPDATE fails, and no marker remained. The fallback marker now covers revoke as well as rotate. The residual-risk paragraph says the window opens when the request is sent, cites the steward ruling, and ends its sentences. Co-Authored-By: Claude Sonnet 5.5 --- docs/service-contract.md | 18 +++++++++--------- src/store/postgres.ts | 7 ++++--- tests/managed-credential.test.ts | 29 +++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 12 deletions(-) diff --git a/docs/service-contract.md b/docs/service-contract.md index f0be8ed..5c0fa5c 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -574,15 +574,15 @@ Important behavior: that takes the lock inside the backoff answers the same `managed_credential_refresh_failed` without calling the provider. A rotation, a revocation or a re-link clears the marker. - Residual risk: if a Heimdall process dies between the provider's token - answer and the commit of the marker or the rotation, nothing is recorded, and - the next caller can present the refresh token the provider already consumed; - for a provider that rotates (Joystick) that reads as token theft. Closing it - needs a write-ahead record of the attempt, written before the provider call on - a connection that does not wait on the row lock (a separate table). That is - deferred by steward ruling and tracked as - `joystick:follow_up:write-ahead-refresh-attempt-record` - The provider call is bounded at 10 seconds + Residual risk: the provider may consume the refresh token as soon as the + request is sent. If a Heimdall process dies after that and before the commit + of the marker, the rotation or the revocation, nothing is recorded, and the + next caller can present the refresh token the provider already consumed; for + a provider that rotates (Joystick) that reads as token theft. The Heimdall + steward ruled (#minds, 2026-11-08) that an intent log, written on its own + connection before the provider call, replaces this marker; it is tracked in + `joystick:follow_up:write-ahead-refresh-attempt-record`. + The provider call is bounded at 10 seconds. - a provider whose refresh tokens rotate (Joystick) fails closed: a refresh response without a new refresh token revokes the credential instead of keeping the old token diff --git a/src/store/postgres.ts b/src/store/postgres.ts index d2fc9db..eb7f068 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -864,9 +864,10 @@ export class PostgresStore implements HeimdallStore { return committed; } catch (error) { await client.query("ROLLBACK"); - if (decision?.kind === "rotate") { - // The provider answered and may have consumed the refresh token, and the rotation could not be committed: the - // rollback took the answer with it. Leave the marker in a transaction of its own, so the next caller does not + if (decision?.kind === "rotate" || decision?.kind === "revoke") { + // The provider answered and may have consumed the refresh token, and the rotation or the revoke its answer + // called for (a rotating provider's missing refresh token) could not be committed: the rollback took the + // answer with it. Leave the marker in a transaction of its own, so the next caller does not // present the old token. Best effort: if this write fails too, the original error is the one that matters. await client .query("UPDATE linked_identities SET refresh_failed_at = $2 WHERE id = $1", [id, decision.updatedAt]) diff --git a/tests/managed-credential.test.ts b/tests/managed-credential.test.ts index 9744abc..a2aa2ef 100644 --- a/tests/managed-credential.test.ts +++ b/tests/managed-credential.test.ts @@ -662,6 +662,35 @@ for (const { kind, live } of rigKinds) describe.skipIf(live && !adminUrl)(`manag { eventType: "managed_credential_revoked", payload: { provider, reason: "rotation_missing" } }, ]); }); + + it.skipIf(!live).each(["no_refresh_token", "empty_refresh_token"] as const)( + "rotation-fails-closed: when the revoke the provider's answer called for cannot be written (%s), the marker is still left", + timeout, + async (mode) => { + const rig = await makeRig(provider); + const endpoint = installTokenEndpoint(provider, "refresh-0"); + endpoint.mode = mode; + const snapshot = await rig.row(); + const db = new Pool({ connectionString: rig.databaseUrl!, max: 1 }); + db.on("error", () => undefined); + try { + await db.query(`CREATE FUNCTION refuse_revoke() RETURNS trigger AS $$ BEGIN RAISE EXCEPTION 'CANARY revoke write refused'; END $$ LANGUAGE plpgsql`); + await db.query(`CREATE TRIGGER refuse_revoke BEFORE UPDATE ON linked_identities FOR EACH ROW WHEN (NEW.access_token_encrypted IS DISTINCT FROM OLD.access_token_encrypted) EXECUTE FUNCTION refuse_revoke()`); + const ctx = (store: HeimdallStore) => ({ config: rig.config, store, tokenCustody: rig.custody, oauthRuntimes: createOAuthRuntimeRegistry() }); + + await expect(refreshManagedCredential(ctx(rig.stores[0]!), snapshot)).rejects.toThrow(); + expect(endpoint.calls).toBe(1); + const marked = await rig.row(); + expect(marked.refreshFailedAt).toBeDefined(); + expect(marked.refreshTokenEncrypted).toBe(snapshot.refreshTokenEncrypted); + + await expect(refreshManagedCredential(ctx(rig.stores[rig.stores.length - 1]!), snapshot)).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + expect(endpoint.calls).toBe(1); + } finally { + await db.end(); + } + } + ); } else { it.each(["no_refresh_token", "empty_refresh_token"] as const)("a response with %s keeps the old one for a non-rotating provider", timeout, async (mode) => { const rig = await makeRig(provider); From f2f1dabc06f905ebfc3f7023bb335a245058704d Mon Sep 17 00:00:00 2001 From: Heimdall Date: Mon, 9 Nov 2026 10:07:24 +0000 Subject: [PATCH 26/63] Blank the consumed refresh token in the fallback marker write When the rotation or revocation the provider's answer called for cannot be committed, the fallback write now clears refresh_token_encrypted as well as stamping the marker, so the end of the 60 s backoff cannot replay the consumed token. Tests (live Postgres, trigger-refused revoke) assert no replayable token and no second provider call. Docs: the marker is a best-effort write on a second connection after rollback, the skew cap, the blanking write's residual. Co-Authored-By: Claude Sonnet 5.5 --- docs/service-contract.md | 15 +++++++++++++-- src/store/postgres.ts | 7 ++++--- tests/managed-credential.test.ts | 14 ++++++++++---- 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/docs/service-contract.md b/docs/service-contract.md index 5c0fa5c..d68f66f 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -572,11 +572,22 @@ Important behavior: (`refresh_failed_at`, written in the same transaction as the lock), and no process presents that row's refresh token again for 60 seconds: a process that takes the lock inside the backoff answers the same - `managed_credential_refresh_failed` without calling the provider. A rotation, + `managed_credential_refresh_failed` without calling the provider. A stamp + more than 60 seconds in the future (a writer whose clock runs ahead) is skew, + not a fresh failure, so the wait is capped at twice the backoff. A rotation, a revocation or a re-link clears the marker. + The marker is a best-effort write on a second connection, made after the + lock's transaction rolled back; it is not part of that transaction. When the + rotation or the revocation the provider's answer called for cannot be + committed (a rotating provider answered without a refresh token, so the + revoke was due, and the write was refused), the fallback write also blanks + the refresh token the provider consumed, so the end of the backoff does not + present it again (`joystick:follow_up:chat-s4509-4511`, steward ruling in + #minds, 2026-11-09). Residual risk: the provider may consume the refresh token as soon as the request is sent. If a Heimdall process dies after that and before the commit - of the marker, the rotation or the revocation, nothing is recorded, and the + of the marker, the rotation or the revocation, or if the blanking fallback + write fails too, nothing is recorded, and the next caller can present the refresh token the provider already consumed; for a provider that rotates (Joystick) that reads as token theft. The Heimdall steward ruled (#minds, 2026-11-08) that an intent log, written on its own diff --git a/src/store/postgres.ts b/src/store/postgres.ts index eb7f068..cd323cc 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -867,10 +867,11 @@ export class PostgresStore implements HeimdallStore { if (decision?.kind === "rotate" || decision?.kind === "revoke") { // The provider answered and may have consumed the refresh token, and the rotation or the revoke its answer // called for (a rotating provider's missing refresh token) could not be committed: the rollback took the - // answer with it. Leave the marker in a transaction of its own, so the next caller does not - // present the old token. Best effort: if this write fails too, the original error is the one that matters. + // answer with it. In a transaction of its own, blank the consumed token and leave the marker, so no later + // caller, after the backoff either, presents it again. Best effort: if this write fails too, the original + // error is the one that matters, and the residual is named in docs/service-contract.md. await client - .query("UPDATE linked_identities SET refresh_failed_at = $2 WHERE id = $1", [id, decision.updatedAt]) + .query("UPDATE linked_identities SET refresh_token_encrypted = NULL, refresh_failed_at = $2 WHERE id = $1", [id, decision.updatedAt]) .catch(() => undefined); } throw error; diff --git a/tests/managed-credential.test.ts b/tests/managed-credential.test.ts index a2aa2ef..6572c15 100644 --- a/tests/managed-credential.test.ts +++ b/tests/managed-credential.test.ts @@ -599,9 +599,12 @@ for (const { kind, live } of rigKinds) describe.skipIf(live && !adminUrl)(`manag expect(endpoint.calls).toBe(1); const marked = await rig.row(); expect(marked.refreshFailedAt).toBeDefined(); - expect(marked.refreshTokenEncrypted).toBe(snapshot.refreshTokenEncrypted); + // The provider consumed the token: nothing replayable is left on the row, so the backoff ending presents nothing. + expect(marked.refreshTokenEncrypted).toBeUndefined(); - await expect(refreshManagedCredential(ctx(rig.stores[rig.stores.length - 1]!), snapshot)).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + await expect(refreshManagedCredential(ctx(rig.stores[rig.stores.length - 1]!), snapshot)).resolves.toBeDefined(); + const afterBackoff = { ...ctx(rig.stores[0]!), clock: () => Date.now() + 5 * 60_000 }; + await expect(refreshManagedCredential(afterBackoff, snapshot)).resolves.toBeDefined(); expect(endpoint.calls).toBe(1); } finally { await db.end(); @@ -682,9 +685,12 @@ for (const { kind, live } of rigKinds) describe.skipIf(live && !adminUrl)(`manag expect(endpoint.calls).toBe(1); const marked = await rig.row(); expect(marked.refreshFailedAt).toBeDefined(); - expect(marked.refreshTokenEncrypted).toBe(snapshot.refreshTokenEncrypted); + // The provider consumed the token: nothing replayable is left on the row, so the backoff ending presents nothing. + expect(marked.refreshTokenEncrypted).toBeUndefined(); - await expect(refreshManagedCredential(ctx(rig.stores[rig.stores.length - 1]!), snapshot)).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + await expect(refreshManagedCredential(ctx(rig.stores[rig.stores.length - 1]!), snapshot)).resolves.toBeDefined(); + const afterBackoff = { ...ctx(rig.stores[0]!), clock: () => Date.now() + 5 * 60_000 }; + await expect(refreshManagedCredential(afterBackoff, snapshot)).resolves.toBeDefined(); expect(endpoint.calls).toBe(1); } finally { await db.end(); From d4cd1121939db162dbf53959b7afc4213721af1e Mon Sep 17 00:00:00 2001 From: Heimdall Date: Mon, 9 Nov 2026 10:22:14 +0000 Subject: [PATCH 27/63] Blank the refresh token in the fallback write only when it is spent A provider that keeps its refresh token valid (Twitch) keeps it when the rotation cannot be committed: the marker is left, the token stays, and the next caller after the backoff presents it. Blanking stays for a revoke and for a provider that rotates (the rotate decision now carries consumedRefreshToken). Live-Postgres test for Twitch written first and seen failing; the contract states the rule inline. Co-Authored-By: Claude Sonnet 5.5 --- docs/service-contract.md | 11 ++++++----- src/managed-credential.ts | 1 + src/store/postgres.ts | 17 +++++++++++------ src/store/types.ts | 2 ++ tests/managed-credential.test.ts | 27 +++++++++++++++++++++------ 5 files changed, 41 insertions(+), 17 deletions(-) diff --git a/docs/service-contract.md b/docs/service-contract.md index d68f66f..bf8d810 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -579,11 +579,12 @@ Important behavior: The marker is a best-effort write on a second connection, made after the lock's transaction rolled back; it is not part of that transaction. When the rotation or the revocation the provider's answer called for cannot be - committed (a rotating provider answered without a refresh token, so the - revoke was due, and the write was refused), the fallback write also blanks - the refresh token the provider consumed, so the end of the backoff does not - present it again (`joystick:follow_up:chat-s4509-4511`, steward ruling in - #minds, 2026-11-09). + committed, the fallback write leaves the marker and blanks the refresh token + only when that token is spent: on a revoke (a rotating provider answered + without a refresh token, or the grant was rejected), or when the provider + rotates refresh tokens (Joystick) and so consumed it. A provider that keeps + its refresh token valid (Twitch) keeps it, so a transient database failure + does not strand the link: the next caller after the backoff presents it again. Residual risk: the provider may consume the refresh token as soon as the request is sent. If a Heimdall process dies after that and before the commit of the marker, the rotation or the revocation, or if the blanking fallback diff --git a/src/managed-credential.ts b/src/managed-credential.ts index b11f3f4..fe60fc6 100644 --- a/src/managed-credential.ts +++ b/src/managed-credential.ts @@ -159,6 +159,7 @@ async function refreshUnderLock( tokenExpiresAt: refreshed.expiresAt, scopes: refreshed.scope.length ? refreshed.scope : locked.scopes, updatedAt, + consumedRefreshToken: providerCatalog[provider].rotatesRefreshTokens, }; }; diff --git a/src/store/postgres.ts b/src/store/postgres.ts index cd323cc..6d96598 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -865,13 +865,18 @@ export class PostgresStore implements HeimdallStore { } catch (error) { await client.query("ROLLBACK"); if (decision?.kind === "rotate" || decision?.kind === "revoke") { - // The provider answered and may have consumed the refresh token, and the rotation or the revoke its answer - // called for (a rotating provider's missing refresh token) could not be committed: the rollback took the - // answer with it. In a transaction of its own, blank the consumed token and leave the marker, so no later - // caller, after the backoff either, presents it again. Best effort: if this write fails too, the original - // error is the one that matters, and the residual is named in docs/service-contract.md. + // The provider answered, and what its answer called for could not be committed: the rollback took the answer + // with it. In a transaction of its own, leave the marker, so no caller presents the token within the backoff. + // Blank the token only when it is spent: a revoke, or a provider that rotates (Joystick) and consumed it. + // A provider that keeps its refresh token valid (Twitch) keeps it, so a transient write failure does not + // strand the link. Best effort: if this write fails too, the original error is the one that matters, and the + // residual is named in docs/service-contract.md. + const spent = decision.kind === "revoke" || decision.consumedRefreshToken; await client - .query("UPDATE linked_identities SET refresh_token_encrypted = NULL, refresh_failed_at = $2 WHERE id = $1", [id, decision.updatedAt]) + .query( + `UPDATE linked_identities SET ${spent ? "refresh_token_encrypted = NULL, " : ""}refresh_failed_at = $2 WHERE id = $1`, + [id, decision.updatedAt] + ) .catch(() => undefined); } throw error; diff --git a/src/store/types.ts b/src/store/types.ts index c795247..9eb805b 100644 --- a/src/store/types.ts +++ b/src/store/types.ts @@ -73,6 +73,8 @@ export type CredentialDecision = tokenExpiresAt: string; scopes: string[]; updatedAt: string; + /** The provider rotates refresh tokens, so the one presented is spent whether or not this decision commits. */ + consumedRefreshToken: boolean; } | { kind: "revoke"; updatedAt: string } | { kind: "failed"; failedAt: string }; diff --git a/tests/managed-credential.test.ts b/tests/managed-credential.test.ts index 6572c15..6ddfa62 100644 --- a/tests/managed-credential.test.ts +++ b/tests/managed-credential.test.ts @@ -599,13 +599,28 @@ for (const { kind, live } of rigKinds) describe.skipIf(live && !adminUrl)(`manag expect(endpoint.calls).toBe(1); const marked = await rig.row(); expect(marked.refreshFailedAt).toBeDefined(); - // The provider consumed the token: nothing replayable is left on the row, so the backoff ending presents nothing. - expect(marked.refreshTokenEncrypted).toBeUndefined(); + if (providerCatalog[provider].rotatesRefreshTokens) { + // The provider consumed the token: nothing replayable is left on the row, so the backoff ending presents nothing. + expect(marked.refreshTokenEncrypted).toBeUndefined(); - await expect(refreshManagedCredential(ctx(rig.stores[rig.stores.length - 1]!), snapshot)).resolves.toBeDefined(); - const afterBackoff = { ...ctx(rig.stores[0]!), clock: () => Date.now() + 5 * 60_000 }; - await expect(refreshManagedCredential(afterBackoff, snapshot)).resolves.toBeDefined(); - expect(endpoint.calls).toBe(1); + await expect(refreshManagedCredential(ctx(rig.stores[rig.stores.length - 1]!), snapshot)).resolves.toBeDefined(); + const afterBackoff = { ...ctx(rig.stores[0]!), clock: () => Date.now() + 5 * 60_000 }; + await expect(refreshManagedCredential(afterBackoff, snapshot)).resolves.toBeDefined(); + expect(endpoint.calls).toBe(1); + } else { + // A non-rotating provider keeps the token valid: a transient write failure must not strand the link. + expect(marked.refreshTokenEncrypted).toBe(snapshot.refreshTokenEncrypted); + + await expect(refreshManagedCredential(ctx(rig.stores[rig.stores.length - 1]!), snapshot)).rejects.toBeInstanceOf(ManagedCredentialRefreshFailed); + expect(endpoint.calls).toBe(1); + await db.query("DROP TRIGGER refuse_rotation ON linked_identities"); + // The fake endpoint rotates on every refresh; Twitch does not, so its answer left refresh-0 valid. + endpoint.live = "refresh-0"; + const afterBackoff = { ...ctx(rig.stores[0]!), clock: () => Date.now() + 5 * 60_000 }; + const outcome = await refreshManagedCredential(afterBackoff, snapshot); + expect(outcome.kind).toBe("current"); + expect(endpoint.calls).toBe(2); + } } finally { await db.end(); } From 246f2d4f714f6b9e44ec330981772f4039dd221e Mon Sep 17 00:00:00 2001 From: Heimdall Date: Mon, 9 Nov 2026 10:27:35 +0000 Subject: [PATCH 28/63] Tests: rotate fixtures carry consumedRefreshToken Co-Authored-By: Claude Sonnet 5.5 --- tests/managed-credential.test.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/managed-credential.test.ts b/tests/managed-credential.test.ts index 6ddfa62..9b226b7 100644 --- a/tests/managed-credential.test.ts +++ b/tests/managed-credential.test.ts @@ -757,6 +757,7 @@ for (const { kind, live } of rigKinds) describe.skipIf(live && !adminUrl)(`manag tokenExpiresAt: past, scopes: locked.scopes, updatedAt: past, + consumedRefreshToken: false, })); expect((await rig.resolve()).statusCode).toBe(200); expect(endpoint.calls).toBe(2); @@ -936,6 +937,7 @@ for (const { kind, live } of rigKinds) describe.skipIf(live && !adminUrl)(`manag tokenExpiresAt: "2999-01-01T00:00:00.000Z", scopes: ["a", "b"], updatedAt: "2999-01-02T00:00:00.000Z", + consumedRefreshToken: false, })); expect(rotated).toEqual({ ...before, @@ -1019,6 +1021,7 @@ for (const { kind, live } of rigKinds) describe.skipIf(live && !adminUrl)(`manag tokenExpiresAt: new Date(Date.now() + 3600_000).toISOString(), scopes: locked.scopes, updatedAt: new Date().toISOString(), + consumedRefreshToken: false, }; }) ) @@ -1297,6 +1300,7 @@ describe("refresh answer classification", () => { tokenExpiresAt: new Date().toISOString(), scopes: locked.scopes, updatedAt: new Date().toISOString(), + consumedRefreshToken: false, })))!; const calls = answer(JSON.stringify({ access_token: "access-1", refresh_token: "refresh-1", ...extra }), 200); let skew = 0; @@ -1329,6 +1333,7 @@ describe("refresh answer classification", () => { tokenExpiresAt: dueAt, scopes: ["s"], updatedAt: dueAt, + consumedRefreshToken: false, })); const calls = answer(JSON.stringify({ access_token: "access-2", expires_in: 3600 }), 200); await refreshManagedCredential(ctxFor(store), snapshot); From a021b02310140228c14fdb5a287f008db66bb8cb Mon Sep 17 00:00:00 2001 From: Heimdall Date: Mon, 9 Nov 2026 12:03:14 +0000 Subject: [PATCH 29/63] Test first: redeem refuses a target the completion never recorded Co-Authored-By: Claude Sonnet 5.5 --- tests/link-binding.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/link-binding.test.ts b/tests/link-binding.test.ts index e58b320..7982229 100644 --- a/tests/link-binding.test.ts +++ b/tests/link-binding.test.ts @@ -218,6 +218,16 @@ describe("redeem binds caller, target and replay", () => { expect((await redeem(r, { completionCode, targetId: "target-a" }, appAuth)).statusCode).toBe(201); }); + it("refuses a target named against a completion that recorded none, without consuming the code", async () => { + const r = await rig("d-r2b"); + const completionCode = await linked(r, undefined); + const refused = await redeem(r, { completionCode, targetId: "target-a" }, appAuth); + expect([refused.statusCode, refused.json().error]).toEqual([403, "completion_target_mismatch"]); + expect(refused.json().accessToken).toBeUndefined(); + expect((await r.store.findAuthCompletion("repixelizer", completionCode))?.consumedAt).toBeUndefined(); + expect((await redeem(r, { completionCode }, appAuth)).statusCode).toBe(201); + }); + it("refuses a replayed completion", async () => { const r = await rig("d-r3"); const completionCode = await linked(r, "target-a"); From 36b02ea135a0531a858a7f4a35f2cad5d3c4b666 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Mon, 9 Nov 2026 12:03:14 +0000 Subject: [PATCH 30/63] Redeem refuses a target the completion did not record, symmetric with the missing one Co-Authored-By: Claude Sonnet 5.5 --- src/app.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app.ts b/src/app.ts index 2051499..59086f0 100644 --- a/src/app.ts +++ b/src/app.ts @@ -2220,7 +2220,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise nowIso) { @@ -2228,7 +2228,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise Date: Mon, 9 Nov 2026 12:18:26 +0000 Subject: [PATCH 31/63] Connect start: pin the app-secret gate on every managed provider, refuse blank targets (#9) The target is stored and compared raw by design (no trim). Co-Authored-By: Claude Sonnet 5.5 --- docs/architecture.md | 13 ++-- notes/streampixels-connect-redeem.md | 35 ++++++++++ src/app-profiles.ts | 13 +++- src/app.ts | 30 +++++---- tests/app.test.ts | 99 ++++++++++++++++++++++++++++ 5 files changed, 171 insertions(+), 19 deletions(-) create mode 100644 notes/streampixels-connect-redeem.md diff --git a/docs/architecture.md b/docs/architecture.md index f816a14..12fbd4f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -447,13 +447,12 @@ builder was not used. process, so N Heimdall processes can present one token N times after a transient failure. Needs a failed-attempt marker on the row, read under the lock. Must land before or with Idunn onboarding. -- `joystick:follow_up:connect-start-needs-app-auth`: connect starts are - unauthenticated, so anyone can name `{creator, targetId}`; the callback - re-check proves a binding exists, not that the caller owns it. It also owns - the whitespace-only `targetId` that passes both gates and the callback's - fail-open `''` fallback for a vanished profile (finding - `joystick:finding:cut-h1.s4.whitespace-targetid-passes-custody-gate`). Must - land before the public Joystick bot or a second creator. +- `joystick:follow_up:connect-start-needs-app-auth` (Heimdall side done): a + connect start that names a connection target needs the app's own secret for + every managed provider, and a blank target is refused at start and at the + callback mint. What StreamPixels must do on its side is in + `notes/streampixels-connect-redeem.md`; its redeem must refuse a creator + connect whose target it did not start. - `joystick:follow_up:heimdall-idunn-onboarding` (gamecult-ops): live Heimdall is a hand-copied release under `heimdall.service`, not an Idunn-admitted generation; the recipe's Joystick lines are declared but unproven by a diff --git a/notes/streampixels-connect-redeem.md b/notes/streampixels-connect-redeem.md new file mode 100644 index 0000000..83f57a7 --- /dev/null +++ b/notes/streampixels-connect-redeem.md @@ -0,0 +1,35 @@ +# For Kiko: what StreamPixels must do for a creator connect + +Heimdall's side is done (this PR). A connect start that carries a `connection` +target is accepted only with StreamPixels' own `x-heimdall-app-secret`, so only +the StreamPixels backend can mint a state naming `{kind: "creator", targetId}`. +Heimdall cannot see StreamPixels' session; the secret proves the caller is the +backend, and the backend must have proved the creator-manage session itself +before it starts the connect. + +What StreamPixels has to change (not done here; this repo does not touch it): + +1. **Start the connect only after the creator-manage check.** The route that + calls `POST /v1/oauth/:provider/start` with `mode: "connect"` must have + verified, for the signed-in StreamPixels user, that they may manage creator + `targetId`. Never take `targetId` from the browser unchecked. +2. **Remember what you started.** Store, server-side and bound to the attempt + (the `attemptId` or browser session), the `targetId` StreamPixels asked + Heimdall to bind. +3. **Redeem with that stored target, never one read back from the request or + the completion.** `POST /v1/apps/streampixels/auth/redeem` takes `targetId`; + Heimdall answers `403 completion_target_mismatch` (code left unconsumed) when + it differs from the signed state's. That only protects you if the value you + send is the one you stored at step 2. A redeem with no stored target for this + attempt must be refused by StreamPixels before it calls Heimdall. +4. **Refuse a creator connect you did not start.** If a connect completion + arrives for a `targetId` with no matching started attempt, do not rebind that + creator's connector, whatever Heimdall's completion says. +5. **A connect completion with no creator target is not a creator connect and + not a sign-in.** Joystick is managed-connection only: a non-creator Joystick + completion is an error. (Twitch/YouTube `connect` without a `connection` is + Heimdall's viewer-session path; treat it as that, never as a connector rebind.) +6. Blank targets (`" "`, zero-width characters) are refused by Heimdall at + start with `400 invalid_connection_target`; send real ids only. + +Tracked as `joystick:follow_up:connect-start-needs-app-auth`. diff --git a/src/app-profiles.ts b/src/app-profiles.ts index c10f704..c25dbb2 100644 --- a/src/app-profiles.ts +++ b/src/app-profiles.ts @@ -263,6 +263,17 @@ export function isAllowedReturnOrigin(profile: AppProfile, returnTo: string): bo } } +/** + * A connection target names something: at least one letter or number that is + * not a default-ignorable code point (the Hangul and Khmer fillers are letters + * that render as nothing). An allowlist, so marks, private-use, unassigned and + * surrogate code points and symbols cannot stand in for a name. The one + * definition the start gate and the callback mint both use. + */ +export function isUsableConnectionTarget(targetId: string): boolean { + return /(?![\p{Default_Ignorable_Code_Point}])[\p{L}\p{N}]/u.test(targetId); +} + /** * What a completed OAuth callback may mint, decided at the callback from the * signed state's mode and the provider's role in the profile (the start gate @@ -289,7 +300,7 @@ export function callbackMint( return mode === "connect" && profile.managedConnectionProviders.includes(provider) && connection?.kind === "creator" && - connection.targetId !== "" + isUsableConnectionTarget(connection.targetId) ? "custody_only" : "refused"; } diff --git a/src/app.ts b/src/app.ts index 59086f0..776d671 100644 --- a/src/app.ts +++ b/src/app.ts @@ -25,7 +25,7 @@ import { type Provider, } from "./contracts.js"; import { issueAccessClaim, type IssueAccessClaimInput } from "./claims.js"; -import { builtInAppProfiles, getAppProfile, isAllowedReturnOrigin, serializeAppProfile, admitsProviderForMode, callbackMint } from "./app-profiles.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"; import { type HeimdallConfig, loadConfig } from "./config.js"; @@ -702,16 +702,6 @@ export async function startOAuthFlow( }; } - if (callbackMint(profile, provider, input.mode, input.connection) === "refused") { - return { - statusCode: 400, - body: { - error: "creator_connection_required", - detail: `${provider} on ${profile.slug} is a managed creator connection: connect needs connection.kind creator and a targetId.`, - }, - }; - } - const descriptor = providerCatalog[provider]; // A provider that never mints an account attaches an identity only through // a bound link: the user's own access token, since the app's word does not @@ -811,6 +801,24 @@ export async function startOAuthFlow( return { statusCode: 401, body: { error: "app_auth_required" } }; } + // 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 { + statusCode: 400, + body: { error: "invalid_connection_target", detail: "connection.targetId must name a target." }, + }; + } + + if (callbackMint(profile, provider, input.mode, input.connection) === "refused") { + return { + statusCode: 400, + body: { + error: "creator_connection_required", + detail: `${provider} on ${profile.slug} is a managed creator connection: connect needs connection.kind creator and a targetId.`, + }, + }; + } + const providerConfig = config.providers[provider]; if (!providerConfig.clientId) { return { diff --git a/tests/app.test.ts b/tests/app.test.ts index 67d4183..20a0191 100644 --- a/tests/app.test.ts +++ b/tests/app.test.ts @@ -1440,6 +1440,105 @@ describe("Heimdall service", () => { expect(urls).toEqual([]); }); + // Targets made only of whitespace, format characters, controls and the invisible fillers that render as nothing. + const BLANK_TARGETS = [ + " ", "\t", "\n ", "\u200B", "\u00A0\uFEFF", + "\u2800", "\u3164", "\u115F", "\u1160", "\uFFA0", "\u034F", "\u0000", "\u0007", " \u2800\u3164 ", + // Marks, private-use, unassigned and lone-surrogate code points, and the symbols that read as nothing: none is a letter or a number. + "\u0300", "\uE000", "\u0378", "\uD800", "\u{16FE4}", "\u{1D159}", "\u{F0000}", "\u0300\uE000 ", + ]; + // A target is usable when it holds a letter or a number that is not an invisible filler. + const NAMING_TARGETS = ["creator-1", " creator-1 ", "Framgång", "42", "\u2800a\u3164", "\u3164\u0300x"]; + + describe("a connect start that names a connection target is the app backend's", () => { + // The target is app-backend authority: the StreamPixels backend proves the creator-manage session and states the + // creator it started the connect for. Anyone else naming {creator, X} would have X's connector rebound to their + // own OAuth account at StreamPixels' redeem. + const returnTo = "https://streampixels.gamecult.org/auth/connect"; + const managed = ["twitch", "youtube", "joystick"] as const; + const startFor = (app: FastifyInstance, provider: string, connection: unknown, headers: Record = {}) => + app.inject({ + method: "POST", + url: `/v1/oauth/${provider}/start`, + headers, + payload: { appSlug: "streampixels", mode: "connect", returnTo, connection }, + }); + const own = { "x-heimdall-app-secret": "streampixels-secret" }; + + it.each(managed)("%s: a creator target is refused without the app's own secret and minted for it", async (provider) => { + const config = createTestConfig(); + const app = await buildApp({ config }); + apps.push(app); + const creator = { kind: "creator", targetId: "victim-creator" }; + + for (const headers of [{}, { "x-heimdall-app-secret": "repixelizer-secret" }, { "x-heimdall-app-secret": "wrong" }]) { + const refused = await startFor(app, provider, creator, headers); + expect([refused.statusCode, refused.json()]).toEqual([401, { error: "app_auth_required" }]); + expect(refused.body).not.toContain("authorizationUrl"); + } + const started = await startFor(app, provider, creator, own); + expect(started.statusCode).toBe(201); + const verified = verifyJwt(stateOf(started.json()), getPublicKey(app)); + expect(verified.valid && verified.payload).toEqual(expect.objectContaining({ connection: expect.objectContaining(creator) })); + + // A direct caller (the command plane hands startOAuthFlow its own) is held to the slug too. + const input = { appSlug: "streampixels" as const, mode: "connect" as const, returnTo, connection: { kind: "creator" as const, targetId: "victim-creator" } }; + const foreign = resolveAppCaller(config, "repixelizer", { "x-heimdall-app-secret": "repixelizer-secret" }); + expect((await startOAuthFlow(getHeimdallRuntimeContext(app), provider, foreign, input)).statusCode).toBe(401); + expect((await startOAuthFlow(getHeimdallRuntimeContext(app), provider, null, input)).statusCode).toBe(401); + }); + + it.each(["twitch", "youtube"] as const)("%s: any connection kind needs the app's secret, not only creator", async (provider) => { + const app = await buildApp({ config: createTestConfig() }); + apps.push(app); + const account = { kind: "account", targetId: "victim-account" }; + + const refused = await startFor(app, provider, account); + expect([refused.statusCode, refused.json()]).toEqual([401, { error: "app_auth_required" }]); + expect((await startFor(app, provider, account, own)).statusCode).toBe(201); + }); + + it.each(managed)("%s: a blank target is refused even for the app, whatever the blank is made of", async (provider) => { + const app = await buildApp({ config: createTestConfig() }); + apps.push(app); + + for (const kind of ["creator", "account"]) { + for (const targetId of BLANK_TARGETS) { + const refused = await startFor(app, provider, { kind, targetId }, own); + expect([refused.statusCode, refused.json().error], `${kind} ${JSON.stringify(targetId)}`).toEqual([400, "invalid_connection_target"]); + expect(refused.body).not.toContain("authorizationUrl"); + } + } + for (const targetId of NAMING_TARGETS) { + expect((await startFor(app, provider, { kind: "creator", targetId }, own)).statusCode, JSON.stringify(targetId)).toBe(201); + } + }); + + it.each(managed)("%s: a blank target without the app's secret gets 401, not the 400 that would tell a stranger what the gate checks", async (provider) => { + const app = await buildApp({ config: createTestConfig() }); + apps.push(app); + + for (const headers of [{}, { "x-heimdall-app-secret": "wrong" }]) { + for (const targetId of [" ", "\u2800"]) { + const refused = await startFor(app, provider, { kind: "creator", targetId }, headers); + expect([refused.statusCode, refused.json()], JSON.stringify(targetId)).toEqual([401, { error: "app_auth_required" }]); + } + } + }); + + it("the callback mint holds a blank creator target to the same bar", () => { + const streampixels = builtInAppProfiles.streampixels!; + for (const targetId of BLANK_TARGETS) { + expect(callbackMint(streampixels, "joystick", "connect", { kind: "creator", targetId }), JSON.stringify(targetId)).toBe("refused"); + } + // A visible character among the blanks names a target. + expect(callbackMint(streampixels, "joystick", "connect", { kind: "creator", targetId: "\u2800a\u3164" })).toBe("custody_only"); + for (const targetId of NAMING_TARGETS) { + expect(callbackMint(streampixels, "joystick", "connect", { kind: "creator", targetId }), JSON.stringify(targetId)).toBe("custody_only"); + } + }); + }); + describe("joystick connect", () => { const creator = { kind: "creator", targetId: "creator-1" }; async function connect(app: FastifyInstance, extra: Record = { connection: creator }) { From 570e930043b154d1ab03350643a2b0198fd3489a Mon Sep 17 00:00:00 2001 From: Heimdall Date: Tue, 10 Nov 2026 17:12:15 +0000 Subject: [PATCH 32/63] Note the two-clock comparison in the training rule as an open gap accepted_at is origin_server_ts, received_at is the collector's clock; a collector clock behind the homeserver's excludes a first answer. Fails closed. Co-Authored-By: Claude Sonnet 5.5 --- docs/answer-collector-consent.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/answer-collector-consent.md b/docs/answer-collector-consent.md index 89f34f1..ca8175e 100644 --- a/docs/answer-collector-consent.md +++ b/docs/answer-collector-consent.md @@ -155,6 +155,12 @@ A record is training or evaluation data only if all hold: version when they answered; 3. `exited = false` at export time. +Open gap: `accepted_at` is the homeserver's `origin_server_ts` and `received_at` is the collector's own clock, so +condition 2 compares two clocks. If the collector's clock is behind the homeserver's, a member's first answer (which is +also their acceptance) can fail `accepted_at <= received_at` and is excluded. That fails closed, never opens `train` +wrongly. The remedy is to compare on one clock (keep the reply's `origin_server_ts` on the answer); this revision does +not rule it. + No recorded scope, or no recorded acceptance, means excluded. Records wider than `show` are kept apart from `show` records: one store per scope (`show`, `study`, `train`) plus a store for scopeless replies that no read path serves. A record From 7a69d7567b1ae3ee7d20d94b40159c8d015bcd86 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Thu, 12 Nov 2026 23:10:27 +0000 Subject: [PATCH 33/63] Opt-in sign_in step-up: app-authenticated, signed-state flag, provider re-auth parameters, typed refusal Co-Authored-By: Claude Sonnet 5.5 --- docs/service-contract.md | 25 +++ src/app.ts | 29 +++- src/contracts.ts | 4 + src/providers.ts | 22 +++ state/evidence.jsonl | 1 + tests/caller-identity-attack-soul-r21.test.ts | 2 +- tests/step-up.test.ts | 152 ++++++++++++++++++ 7 files changed, 233 insertions(+), 2 deletions(-) create mode 100644 tests/step-up.test.ts diff --git a/docs/service-contract.md b/docs/service-contract.md index bf8d810..eb0b35f 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -198,6 +198,31 @@ Failure modes: secret, or another app's, is refused before any state is signed. `sign_in` starts carrying a `connection` are `400 connection_not_allowed_in_sign_in` +Step-up (`stepUp: true`, sign_in only, off by default): + +- Asks the provider for a real re-authentication on the authorize URL, so a + provider session already open in the browser is not enough to complete the + sign-in. The start request field is `stepUp`; the signed state carries it as + `step_up`, and the launch hop builds the provider URL from the state alone. + Nothing on the callback or redeem side can set or clear it (a `stepUp` in a + redeem body is ignored), and a completion reports it as `stepUpRequested: true` + when the start asked. +- It is the authenticated app's request, like a connection target: no secret or + another app's is `401 app_auth_required`; a `link` or `connect` start carrying + it is `400 step_up_only_in_sign_in`; `stepUp: false` is the same as absent. +- Provider parameters (`stepUpAuthorizationParams`, `src/providers.ts`): Twitch + `force_verify=true`, YouTube `prompt=login consent` (consent is kept; the + provider always asks it), Google `prompt=login`. **The strengths differ.** + Google `prompt=login` forces the person to re-authenticate. Twitch + `force_verify` re-shows the authorize page: it proves a person at that browser + chose to continue, not that they entered credentials. A consumer that needs + credentials re-entered must not rely on Twitch step-up. +- A provider with no such parameter (Discord, Patreon, GitHub, Spotify, + Joystick) is `400 step_up_not_supported`, with the provider named, before any + state is signed. The URL builder throws rather than omit the step. +- Heimdall requests the step; it cannot observe that the provider honoured it. + `stepUpRequested` says "asked", not "verified". + Launch note: - Discord and Patreon are the implemented provider runtimes for Repixelizer diff --git a/src/app.ts b/src/app.ts index 776d671..12ace03 100644 --- a/src/app.ts +++ b/src/app.ts @@ -99,6 +99,7 @@ function buildOAuthStateToken(options: { handoff: OAuthHandoff; entitlementPolicy: OAuthEntitlementPolicy | undefined; requestedScopes: string[] | undefined; + stepUp: boolean | undefined; keys: ReturnType; }): { token: string; jti: string; expiresAt: string } { const issuedAt = nowEpochSeconds(); @@ -121,6 +122,7 @@ function buildOAuthStateToken(options: { handoff: options.handoff, entitlement_policy: options.entitlementPolicy ?? null, requested_scopes: options.requestedScopes ?? null, + step_up: options.stepUp ? true : null, }; const token = signJwt(payload as unknown as Record, options.keys); @@ -184,7 +186,8 @@ function parseOAuthStatePayload(payload: Record): OAuthStatePay !handoffIsValid || !entitlementPolicyIsValid || !(payload.initiator_account_id === undefined || payload.initiator_account_id === null || typeof payload.initiator_account_id === "string") || - !requestedScopesAreValid + !requestedScopesAreValid || + !(payload.step_up === undefined || payload.step_up === null || payload.step_up === true) ) { return null; } @@ -202,6 +205,9 @@ function parseOAuthStatePayload(payload: Record): OAuthStatePay if (!normalizedPayload.requested_scopes) { normalizedPayload.requested_scopes = null; } + if (!normalizedPayload.step_up) { + normalizedPayload.step_up = null; + } return normalizedPayload; } @@ -702,6 +708,10 @@ export async function startOAuthFlow( }; } + if (input.stepUp && input.mode !== "sign_in") { + return { statusCode: 400, body: { error: "step_up_only_in_sign_in", detail: "stepUp applies to sign_in starts only." } }; + } + const descriptor = providerCatalog[provider]; // A provider that never mints an account attaches an identity only through // a bound link: the user's own access token, since the app's word does not @@ -744,6 +754,19 @@ export async function startOAuthFlow( return { statusCode: 400, body: { error: "initiator_only_in_link_mode" } }; } + // A step-up is app-backend authority, like a connection target: it is + // asked for by the authenticated app, never by a browser, and only on + // sign_in. A provider with no re-authentication parameter is refused here, + // at start, so no step-up ever reaches the person without its step. + if (input.stepUp) { + if (!isAppCaller(caller) || caller.appSlug !== profile.slug) { + return { statusCode: 401, body: { error: "app_auth_required" } }; + } + if (!providerCatalog[provider].stepUpAuthorizationParams) { + return { statusCode: 400, body: { error: "step_up_not_supported", provider, detail: `${providerCatalog[provider].displayName} has no re-authentication parameter.` } }; + } + } + if ( input.requestedScopes !== undefined && (input.requestedScopes.length > maxRequestedScopes || input.requestedScopes.some((scope) => scope.length > maxRequestedScopeChars)) @@ -838,6 +861,7 @@ export async function startOAuthFlow( handoff, entitlementPolicy, requestedScopes: input.requestedScopes, + stepUp: input.stepUp, keys, }); return { @@ -1175,6 +1199,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise; + /** + * The authorize parameters that make this provider ask the person again + * (a sign_in step-up). Absent means the provider has no such parameter, and + * a step-up start for it is refused rather than passed without the step. + */ + stepUpAuthorizationParams?: Record; /** * What a callback does with a (provider, subject) no account holds yet. * `mints_account` is every provider's behaviour before Google: the first @@ -92,6 +98,8 @@ export const providerCatalog: Record = { firstLogin: "mints_account", clientIdEnv: "GC_ACCESS_PROVIDER_TWITCH_CLIENT_ID", clientSecretEnv: "GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET_FILE", + // Twitch force_verify re-shows the authorize page; it is not a password prompt. + stepUpAuthorizationParams: { force_verify: "true" }, }, youtube: { key: "youtube", @@ -116,6 +124,8 @@ export const providerCatalog: Record = { include_granted_scopes: "true", prompt: "consent", }, + // login forces re-authentication; consent is kept because this provider always asks for it. + stepUpAuthorizationParams: { prompt: "login consent" }, }, spotify: { key: "spotify", @@ -150,6 +160,7 @@ export const providerCatalog: Record = { clientIdEnv: "GC_ACCESS_PROVIDER_GOOGLE_CLIENT_ID", clientSecretEnv: "GC_ACCESS_PROVIDER_GOOGLE_CLIENT_SECRET_FILE", additionalAuthorizationParams: { prompt: "select_account" }, + stepUpAuthorizationParams: { prompt: "login" }, }, joystick: { key: "joystick", @@ -180,6 +191,8 @@ export function buildAuthorizationUrl(options: { requestedScopes: string[] | undefined; /** For an OIDC provider: the nonce, and the S256 challenge of the PKCE verifier. */ oidc?: { nonce: string; codeChallenge: string }; + /** Ask the provider for a real re-authentication. Throws for a provider with no such parameter: never a silent pass. */ + stepUp?: boolean; }): string { const descriptor = providerCatalog[options.provider]; const url = new URL(descriptor.authorizationEndpoint); @@ -203,6 +216,15 @@ export function buildAuthorizationUrl(options: { url.searchParams.set(key, value); } + if (options.stepUp) { + if (!descriptor.stepUpAuthorizationParams) { + throw new Error(`${descriptor.displayName} has no re-authentication parameter: a step-up cannot be honoured.`); + } + for (const [key, value] of Object.entries(descriptor.stepUpAuthorizationParams)) { + url.searchParams.set(key, value); + } + } + return url.toString(); } diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 5329d5f..f7fa724 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -37,3 +37,4 @@ {"ts": "2026-09-08T12:20:12+00:00", "type": "security", "status": "accepted", "note": "epiphany/heimdall-caller-identity, second Hands pass: closed the two Soul-proven holes. (1) auth-completions redeem code is now always store-minted (never handoff.attemptId); attemptId survives only as a separate correlation field on StoredAuthCompletion/CreateAuthCompletionInput, and a new store.consumeAuthCompletionByAttempt(appSlug, attemptId, at) lets the private command plane's completeAuth redeem by the handle it already owns instead of forging an HTTP self-call with completionCode=handle. (2) startOAuthFlow now refuses any returnTo whose origin is not in AppProfile.allowedReturnOrigins (repixelizer/streampixels/bifrost -> .gamecult.org, ghostlight -> yggdrasil.gamecult.org per its docs/app-profiles doc and existing test fixtures; a registered app's allowlist is derived from its stored redirectUris origins). AppCaller is now branded with an unexported Symbol (app-caller.ts); private-command-plane.ts's two { appSlug } literals are gone, replaced by app-caller.ts's callerFromOpenedEnvelope. Deleted: validateAppRegistration, AppRegistrationRequest, RegistrationProblem, AppRegistrationError, HeimdallStore.registerApp (writer). Kept: findRegisteredApp/listRegisteredApps/resolveAppProfile fallback -- AppSlug is a plain string (contracts.ts), registered_apps is a real extension point for a slug Heimdall was never rebuilt for, and isBuiltInApp's only production call site (listAppProfiles) depends on that fallback existing; a row is now provisioned by direct SQL (or InMemoryStore.seedRegisteredApp in tests), not by any app-facing writer. Deleted the two appSlug===\"ghostlight\" branches in private-command-plane.ts; the requirement is now AppProfile.requiredEntitlementPolicyKind, checked generically through resolveAppProfile. tsc --noEmit clean; vitest 94 passed/1 pre-existing-skip, only pre-existing failure is tests/odin-publication.test.ts (Cannot find module 'cultcache-ts', present on main too).", "branch": "epiphany/heimdall-caller-identity"} {"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)."} diff --git a/tests/caller-identity-attack-soul-r21.test.ts b/tests/caller-identity-attack-soul-r21.test.ts index fe23f9f..1264a86 100644 --- a/tests/caller-identity-attack-soul-r21.test.ts +++ b/tests/caller-identity-attack-soul-r21.test.ts @@ -366,7 +366,7 @@ describe("R21.2: the WeakSet brand at every consumer", () => { if (line.includes("caller.appSlug")) expect(line, `${file}: ${line.trim()}`).toContain("isAppCaller(caller)"); } } - expect(consumers).toEqual(["app.ts: reads=3 guards=3"]); + expect(consumers).toEqual(["app.ts: reads=4 guards=4"]); }); it("a caller minted for app A is refused where app B is expected, over HTTP and by direct call", async () => { diff --git a/tests/step-up.test.ts b/tests/step-up.test.ts new file mode 100644 index 0000000..9e4cb6c --- /dev/null +++ b/tests/step-up.test.ts @@ -0,0 +1,152 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { buildApp } from "../src/app.js"; +import { type OAuthProviderRuntime } from "../src/oauth.js"; +import { buildAuthorizationUrl, providerCatalog } from "../src/providers.js"; +import { decodeJwt } from "../src/signing.js"; +import { InMemoryStore } from "../src/store/index.js"; +import { createTestConfig, launchFlow, launchWithRedirect } from "./oauth-flow.js"; + +// A sign_in step-up asks the provider for a real re-authentication. It is the +// authenticated app's request (never a browser's), it rides in the signed state +// only, it is off unless asked for, and a provider that has no such parameter is +// refused at start. These tests drive it as StreamPixels does: its own app +// secret, twitch and youtube sign_in starts, then the launch hop and redeem. + +const returnTo = "https://streampixels.gamecult.org/signin/return"; +const spAuth = { "x-heimdall-app-secret": "streampixels-secret" }; + +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 apps: Awaited>[] = []; +afterEach(async () => { + await Promise.all(apps.splice(0).map((app) => app.close())); +}); + +async function rig() { + const app = await buildApp({ + config: createTestConfig(), + store: new InMemoryStore(), + oauthRuntimes: { twitch: runtime("twitch", "t-1"), youtube: runtime("youtube", "y-1") }, + }); + apps.push(app); + return app; +} + +type App = Awaited>; + +function start( + app: App, + provider: string, + payload: Record = {}, + headers: Record = {}, + appSlug = "streampixels", + url = returnTo +) { + return app.inject({ method: "POST", url: `/v1/oauth/${provider}/start`, headers, payload: { appSlug, mode: "sign_in", returnTo: url, ...payload } }); +} + +describe("step-up on a sign_in start: the provider URL", () => { + it("asks nothing extra without stepUp, for every provider StreamPixels signs in with", async () => { + const app = await rig(); + for (const provider of ["twitch", "youtube"]) { + for (const extra of [{}, { stepUp: false }]) { + const started = await start(app, provider, extra); + expect(started.statusCode).toBe(201); + expect(decodeJwt(new URL(started.json().authorizationUrl).searchParams.get("state") ?? "").payload.step_up).toBeNull(); + const url = (await launchWithRedirect(app, started.json())).url; + expect(url.searchParams.has("force_verify")).toBe(false); + expect(url.searchParams.get("prompt")).toBe(provider === "youtube" ? "consent" : null); + } + } + }); + + it("with stepUp and the app secret: twitch force_verify=true, youtube prompt=login consent, state records it", async () => { + const app = await rig(); + const twitch = await start(app, "twitch", { stepUp: true }, spAuth); + expect(twitch.statusCode).toBe(201); + expect(decodeJwt(new URL(twitch.json().authorizationUrl).searchParams.get("state") ?? "").payload.step_up).toBe(true); + expect((await launchWithRedirect(app, twitch.json())).url.searchParams.get("force_verify")).toBe("true"); + + const youtube = await start(app, "youtube", { stepUp: true }, spAuth); + expect(youtube.statusCode).toBe(201); + expect((await launchWithRedirect(app, youtube.json())).url.searchParams.get("prompt")).toBe("login consent"); + }); + + it("Google (a Bifrost sign_in provider) gets prompt=login in place of select_account", async () => { + const app = await rig(); + const bifrostReturn = "https://bifrost.gamecult.org/auth/heimdall/return"; + const plain = await start(app, "google", {}, { "x-heimdall-app-secret": "bifrost-secret" }, "bifrost", bifrostReturn); + expect((await launchWithRedirect(app, plain.json())).url.searchParams.get("prompt")).toBe("select_account"); + const stepped = await start(app, "google", { stepUp: true }, { "x-heimdall-app-secret": "bifrost-secret" }, "bifrost", bifrostReturn); + expect(stepped.statusCode).toBe(201); + expect((await launchWithRedirect(app, stepped.json())).url.searchParams.get("prompt")).toBe("login"); + }); +}); + +describe("step-up refusals", () => { + it("is the app's request: no secret or a wrong secret is 401 app_auth_required, while the same start without stepUp stays open", async () => { + const app = await rig(); + for (const headers of [{}, { "x-heimdall-app-secret": "wrong" }]) { + const res = await start(app, "twitch", { stepUp: true }, headers); + expect([res.statusCode, res.json().error]).toEqual([401, "app_auth_required"]); + } + expect((await start(app, "twitch", {}, {})).statusCode).toBe(201); + }); + + it("a provider with no re-authentication parameter is a typed refusal, with the secret, never a silent pass", async () => { + const app = await rig(); + const bifrost = { "x-heimdall-app-secret": "bifrost-secret" }; + const res = await start(app, "discord", { stepUp: true }, bifrost, "bifrost", "https://bifrost.gamecult.org/auth/heimdall/return"); + expect([res.statusCode, res.json().error, res.json().provider]).toEqual([400, "step_up_not_supported", "discord"]); + // The URL builder holds the same line: it throws rather than omit the step. + for (const provider of ["discord", "patreon", "github", "spotify", "joystick"] as const) { + expect(providerCatalog[provider].stepUpAuthorizationParams, provider).toBeUndefined(); + expect(() => + buildAuthorizationUrl({ provider, clientId: "c", redirectUri: "https://x/cb", state: "s", requestedScopes: undefined, stepUp: true }) + ).toThrow(/no re-authentication parameter/); + } + expect(Object.keys(providerCatalog).filter((p) => providerCatalog[p as keyof typeof providerCatalog].stepUpAuthorizationParams).sort()).toEqual(["google", "twitch", "youtube"]); + }); + + it("is sign_in only: link and connect starts carrying stepUp are 400 step_up_only_in_sign_in", async () => { + const app = await rig(); + for (const mode of ["link", "connect"]) { + const res = await start(app, "twitch", { mode, stepUp: true }, spAuth); + expect([res.statusCode, res.json().error]).toEqual([400, "step_up_only_in_sign_in"]); + } + }); +}); + +describe("the flag is the signed state's, not the redeem side's", () => { + it("a completion reports stepUpRequested only when the start asked, and a stepUp handed to redeem changes nothing", async () => { + const app = await rig(); + for (const asked of [true, false]) { + const started = await start(app, "twitch", asked ? { stepUp: true } : {}, asked ? spAuth : {}); + const flow = await launchFlow(app, started.json()); + const called = await 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 code = called.json().completion.code as string; + + // A stepUp handed to redeem is not read: the answer reflects the start, whatever the body says. + 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); + } + }); +}); From 673713a015789b02e3ad91baa422f5e1ede33837 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Thu, 12 Nov 2026 23:21:12 +0000 Subject: [PATCH 34/63] Step-up: build the authorize URL before claiming the launch (a refused step-up no longer burns the state); pin the strict step_up parse with a signed forgery; document backend_callback and mixed-version limits Co-Authored-By: Claude Sonnet 5.5 --- docs/service-contract.md | 4 +++ src/app.ts | 26 ++++++++--------- tests/step-up.test.ts | 61 ++++++++++++++++++++++++++++++++++++++-- 3 files changed, 75 insertions(+), 16 deletions(-) diff --git a/docs/service-contract.md b/docs/service-contract.md index eb0b35f..0469186 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -220,6 +220,10 @@ Step-up (`stepUp: true`, sign_in only, off by default): - A provider with no such parameter (Discord, Patreon, GitHub, Spotify, Joystick) is `400 step_up_not_supported`, with the provider named, before any state is signed. The URL builder throws rather than omit the step. +- A `backend_callback` handoff delivery does not carry `stepUpRequested`; only the redeemed completion does. +- A state signed by a build with step-up and launched by an older build loses the step + silently (the older parser ignores `step_up`): deploy every Heimdall instance on one + release, with no mixed window. - Heimdall requests the step; it cannot observe that the provider honoured it. `stepUpRequested` says "asked", not "verified". diff --git a/src/app.ts b/src/app.ts index 12ace03..e3c4931 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1365,6 +1365,18 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { await Promise.all(apps.splice(0).map((app) => app.close())); }); -async function rig() { +async function rig(config = createTestConfig()) { const app = await buildApp({ - config: createTestConfig(), + config, store: new InMemoryStore(), oauthRuntimes: { twitch: runtime("twitch", "t-1"), youtube: runtime("youtube", "y-1") }, }); @@ -150,3 +153,55 @@ describe("the flag is the signed state's, not the redeem side's", () => { } }); }); + +describe("a forged or odd state cannot carry a step-up the start would not have signed", () => { + // A real signing key on disk, so the test can re-sign a state as only Heimdall's key holder could. + const dir = mkdtempSync(join(tmpdir(), "heimdall-stepup-")); + const config = { ...createTestConfig(), signingPrivateKeyPath: join(dir, "signing.pem"), bootstrapSigningPrivateKeyOnMissing: true }; + // The app creates the key on first boot; read it only after the rig exists. + const loadKeys = (c: typeof config) => createRuntimeKeyMaterial({ ...c, bootstrapSigningPrivateKeyOnMissing: false }); + + async function forgedState(app: App, provider: string, headers: Record, stepUp: unknown, appSlug = "streampixels", url = returnTo) { + const started = await start(app, provider, {}, headers, appSlug, url); + const real = new URL(started.json().authorizationUrl).searchParams.get("state") ?? ""; + const keys = loadKeys(config); + const verified = verifyJwt(real, keys.publicKey) as { valid: boolean; payload: Record }; + expect(verified.valid, "the test key signs what the app verifies").toBe(true); + return { real, forged: signJwt({ ...verified.payload, step_up: stepUp }, keys) }; + } + const launch = (app: App, provider: string, state: string) => app.inject({ method: "GET", url: `/v1/oauth/${provider}/launch?state=${encodeURIComponent(state)}` }); + + it("rejects any step_up that is not null or true as invalid_state at the launch hop", async () => { + const app = await rig(config); + expect((await launch(app, "twitch", (await forgedState(app, "twitch", {}, true)).forged)).statusCode, "a well-formed true still launches").toBe(302); + for (const odd of ["true", "yes", 1, 0, false, {}, []]) { + const res = await launch(app, "twitch", (await forgedState(app, "twitch", {}, odd)).forged); + expect([res.statusCode, res.json().error], JSON.stringify(odd)).toEqual([400, "invalid_state"]); + } + rmSync(dir, { recursive: true, force: true }); + }); + + it("a step-up state for a provider with no re-authentication parameter fails closed and does not burn the state", async () => { + const dir2 = mkdtempSync(join(tmpdir(), "heimdall-stepup-")); + const config2 = { ...createTestConfig(), signingPrivateKeyPath: join(dir2, "signing.pem"), bootstrapSigningPrivateKeyOnMissing: true }; + try { + const app = await rig(config2); + const bifrost = { "x-heimdall-app-secret": "bifrost-secret" }; + const started = await start(app, "discord", {}, bifrost, "bifrost", "https://bifrost.gamecult.org/auth/heimdall/return"); + const real = new URL(started.json().authorizationUrl).searchParams.get("state") ?? ""; + const keys2 = loadKeys(config2); + const verified = verifyJwt(real, keys2.publicKey) as { valid: boolean; payload: Record }; + expect(verified.valid).toBe(true); + const forged = signJwt({ ...verified.payload, step_up: true }, keys2); + for (let attempt = 0; attempt < 2; attempt += 1) { + const res = await launch(app, "discord", forged); + expect(res.statusCode, "never a redirect without the step").toBe(500); + expect(res.headers.location).toBeUndefined(); + } + // Not "state_already_launched": the refused launches did not claim the state. + expect((await launch(app, "discord", real)).statusCode).toBe(302); + } finally { + rmSync(dir2, { recursive: true, force: true }); + } + }); +}); From 96256d2839743b0022a036ffa1cf31975cbce408 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 13 Nov 2026 05:58:45 +0000 Subject: [PATCH 35/63] Prune oauth_state_uses on claim: bounded delete past exp + skew + margin (#12) Not in the 74004bf release list. The runtime role needs GRANT SELECT, DELETE ON oauth_state_uses before this build starts. Co-Authored-By: Claude Sonnet 5.5 --- src/app.ts | 7 +- src/store/in-memory.ts | 24 +++-- src/store/postgres.ts | 34 +++++-- src/store/schema.ts | 9 +- src/store/types.ts | 16 +++ tests/oauth-state-binding.test.ts | 81 +++++++++++---- tests/store.test.ts | 158 ++++++++++++++++++++++++++++-- 7 files changed, 282 insertions(+), 47 deletions(-) diff --git a/src/app.ts b/src/app.ts index e3c4931..2977f08 100644 --- a/src/app.ts +++ b/src/app.ts @@ -43,6 +43,7 @@ import { authorizationScopes, buildAuthorizationUrl, providerCatalog, providerEx import { createRuntimeKeyMaterial, signJwt, verifyJwt } from "./signing.js"; import { createStore, type HeimdallStore } from "./store/index.js"; import { + OAUTH_STATE_SKEW_MS, type CreateAccountInput, type StoredCapabilityGrant, type StoredLinkedIdentity, @@ -218,8 +219,8 @@ type OAuthStateVerdict = /** * The one place a signed OAuth state becomes trusted: signature, shape, issuer, - * audience and provider, and the time window with the same 30 s skew refresh - * tokens use. Every route that turns a state into navigation or a completion + * audience and provider, and the time window with OAUTH_STATE_SKEW_MS of skew + * (30 s, as refresh tokens use). Every route that turns a state into navigation or a completion * runs this first; the refusals are fixed codes and never echo the token. */ function verifyOAuthState( @@ -242,7 +243,7 @@ function verifyOAuthState( } const now = nowEpochSeconds(); - if (payload.nbf > now + 30 || payload.exp <= now - 30) { + if (payload.nbf > now + OAUTH_STATE_SKEW_MS / 1000 || payload.exp <= now - OAUTH_STATE_SKEW_MS / 1000) { return { ok: false, error: "state_expired" }; } diff --git a/src/store/in-memory.ts b/src/store/in-memory.ts index e86490d..5df37ea 100644 --- a/src/store/in-memory.ts +++ b/src/store/in-memory.ts @@ -4,6 +4,8 @@ import { type CreateAccountInput, type CreateAuthAttemptInput, type ClaimOAuthStateUseInput, + OAUTH_STATE_PRUNE_BATCH, + oauthStatePruneCutoffMs, type CreateAuthCompletionInput, type CreateConsentReceiptInput, type CreatePendingLinkInput, @@ -26,9 +28,6 @@ import { type UpsertLinkedIdentityInput, } from "./types.js"; -/** The skew a signed OAuth state is still accepted for past its exp (verifyOAuthState). */ -const OAUTH_STATE_SKEW_MS = 30_000; - function clone(value: T): T { return JSON.parse(JSON.stringify(value)) as T; } @@ -464,18 +463,23 @@ export class InMemoryStore implements HeimdallStore { } async claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise { - // A state is still accepted until its exp + 30 s skew, so a use record must outlive that. - const usedAtMs = Date.parse(input.usedAt); - for (const [key, expiresAt] of this.oauthStateUses) { - if (Date.parse(expiresAt) + OAUTH_STATE_SKEW_MS <= usedAtMs) { - this.oauthStateUses.delete(key); - } - } const key = `${input.jti}:${input.phase}`; if (this.oauthStateUses.has(key)) { return false; } this.oauthStateUses.set(key, input.expiresAt); + // A state is still accepted until its exp + skew; a record is kept a margin longer, and each + // successful claim removes at most a batch of what is past that (oauthStatePruneCutoffMs), as + // the Postgres store does. + const cutoff = oauthStatePruneCutoffMs(Date.parse(input.usedAt)); + let pruned = 0; + for (const [oldKey, expiresAt] of this.oauthStateUses) { + if (pruned >= OAUTH_STATE_PRUNE_BATCH) break; + if (Date.parse(expiresAt) <= cutoff) { + this.oauthStateUses.delete(oldKey); + pruned += 1; + } + } return true; } diff --git a/src/store/postgres.ts b/src/store/postgres.ts index 6d96598..247260c 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -18,6 +18,8 @@ import { type CreateSessionInput, type CreatePrivateCommandReceiptInput, type HeimdallStore, + OAUTH_STATE_PRUNE_BATCH, + oauthStatePruneCutoffMs, type StoredAccount, type StoredAuthAttempt, type StoredAuthCompletion, @@ -449,10 +451,11 @@ 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 nothing. + * 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> = { +export const STORE_TABLE_PRIVILEGES: Readonly> = { accounts: ["SELECT", "INSERT", "UPDATE"], linked_identities: ["SELECT", "INSERT", "UPDATE"], sessions: ["SELECT", "INSERT", "UPDATE"], @@ -460,7 +463,7 @@ export const STORE_TABLE_PRIVILEGES: Readonly, require SELECT 1 FROM unnest($2::text[], $3::text[]) AS used(table_name, column_name) JOIN pg_attribute a ON a.attrelid = to_regclass(used.table_name) AND a.attname = used.column_name AND NOT a.attisdropped WHERE used.table_name = required.table_name - AND NOT has_column_privilege(a.attrelid, a.attnum, required.privilege) + AND NOT CASE WHEN required.privilege = 'DELETE' + THEN has_table_privilege(a.attrelid, 'DELETE') -- DELETE is a row privilege, never held per column + ELSE has_column_privilege(a.attrelid, a.attnum, required.privilege) END ) `, [ @@ -1221,7 +1226,7 @@ export class PostgresStore implements HeimdallStore { } async claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise { - // No conflict target and no RETURNING: both need SELECT, and the role has INSERT only. + // No conflict target and no RETURNING: ON CONFLICT DO NOTHING alone says whether the row was new. const result = await this.pool.query( ` INSERT INTO oauth_state_uses (jti, phase, app_slug, used_at, expires_at) @@ -1230,7 +1235,24 @@ export class PostgresStore implements HeimdallStore { `, [input.jti, input.phase, input.appSlug, input.usedAt, input.expiresAt] ); - return result.rowCount === 1; + if (result.rowCount !== 1) return false; + // Retention: one bounded delete of records past the shared cutoff, inline as the memory store does. + // The claim row is already written, so a prune failure must not fail the claim: a throw would make + // the user's retry look like a replay. Unpruned rows are harmless and the next claim prunes them. + try { + await this.pool.query( + ` + DELETE FROM oauth_state_uses + WHERE (jti, phase) IN ( + SELECT jti, phase FROM oauth_state_uses WHERE expires_at <= $1 LIMIT $2 + ) + `, + [new Date(oauthStatePruneCutoffMs(Date.parse(input.usedAt))), OAUTH_STATE_PRUNE_BATCH] + ); + } catch { + // deliberately swallowed, see above + } + return true; } async upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise { diff --git a/src/store/schema.ts b/src/store/schema.ts index 7aa6823..3678122 100644 --- a/src/store/schema.ts +++ b/src/store/schema.ts @@ -143,9 +143,10 @@ CREATE UNIQUE INDEX IF NOT EXISTS auth_completions_attempt_unconsumed_unique_idx -- One use per (state jti, phase): a signed OAuth state launches once and -- completes once. The first INSERT for a pair wins; ON CONFLICT DO NOTHING --- reports every later claim as no row. The Postgres store deletes nothing, so rows --- stay like consumed auth_completions; a state is accepted until expires_at + 30 s --- of skew, so a row may be pruned only after that and is never consulted again. +-- reports every later claim as no row. A state is accepted until expires_at + 30 s +-- of skew, so a row may be pruned only after that and is never consulted again; +-- each successful claim deletes a bounded batch of rows past expires_at + skew +-- + margin (OAUTH_STATE_* in types.ts), found through the expires_at index. CREATE TABLE IF NOT EXISTS oauth_state_uses ( jti TEXT NOT NULL, phase TEXT NOT NULL, @@ -155,6 +156,8 @@ CREATE TABLE IF NOT EXISTS oauth_state_uses ( PRIMARY KEY (jti, phase) ); +CREATE INDEX IF NOT EXISTS oauth_state_uses_expires_at_idx ON oauth_state_uses(expires_at); + CREATE TABLE IF NOT EXISTS capability_grants ( id TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, diff --git a/src/store/types.ts b/src/store/types.ts index 9eb805b..a2a792d 100644 --- a/src/store/types.ts +++ b/src/store/types.ts @@ -173,6 +173,22 @@ export interface StoredAuthCompletion { payloadJson: Record; } +/** The skew a signed OAuth state is still accepted for past its exp: verifyOAuthState in app.ts reads this, so the two cannot drift. */ +export const OAUTH_STATE_SKEW_MS = 30_000; +/** Extra time a use record is kept past exp + skew before it may be pruned. */ +export const OAUTH_STATE_PRUNE_MARGIN_MS = 10 * 60_000; +/** The most use records one claim deletes. */ +export const OAUTH_STATE_PRUNE_BATCH = 50; + +/** + * The one retention rule for oauth_state_uses, shared by both stores: a record + * is prunable when expires_at + skew + margin <= now, that is when its + * expires_at is at or before this cutoff. + */ +export function oauthStatePruneCutoffMs(nowMs: number): number { + return nowMs - OAUTH_STATE_SKEW_MS - OAUTH_STATE_PRUNE_MARGIN_MS; +} + export interface ClaimOAuthStateUseInput { jti: string; phase: "launch" | "callback"; diff --git a/tests/oauth-state-binding.test.ts b/tests/oauth-state-binding.test.ts index 01abba0..c82bd94 100644 --- a/tests/oauth-state-binding.test.ts +++ b/tests/oauth-state-binding.test.ts @@ -4,6 +4,7 @@ import { type FastifyInstance } from "fastify"; import { buildApp, getHeimdallRuntimeContext, startOAuthFlow } from "../src/app.js"; import { resolveAppCaller } from "../src/app-caller.js"; import { decodeJwt, signJwt } from "../src/signing.js"; +import { OAUTH_STATE_PRUNE_BATCH, OAUTH_STATE_PRUNE_MARGIN_MS, OAUTH_STATE_SKEW_MS } from "../src/store/types.js"; import { createMockDiscordRuntime, createTestConfig, launchFlow, setCookieOf, stateOf } from "./oauth-flow.js"; // Heimdall's OAuth states complete once, only in the browser that launched @@ -280,23 +281,69 @@ describe("OAuth state binding", () => { }); }); - it("the memory store keeps a use record until the state's exp + 30 s skew", async () => { - const app = await newApp(); - const ctx = getHeimdallRuntimeContext(app); - const claim = (jti: string, usedAt: number) => - ctx.store.claimOAuthStateUse({ - jti, - phase: "launch", - appSlug: "bifrost", - usedAt: new Date(usedAt).toISOString(), - expiresAt: new Date(1_000_000).toISOString(), - }); - expect(await claim("a", 900_000)).toBe(true); - // Past exp but inside the skew a state still verifies, so its record must still refuse a replay. - expect(await claim("b", 1_000_000 + 29_999)).toBe(true); - expect(await claim("a", 1_000_000 + 29_999)).toBe(false); - expect(await claim("c", 1_000_000 + 30_000)).toBe(true); - expect(await claim("a", 1_000_000 + 30_000)).toBe(true); + describe("use-record retention", () => { + // Only Date is faked: the routes stamp each claim with the clock, and the rest of the event loop stays real. + const clockAt = (ms: number) => vi.useFakeTimers({ toFake: ["Date"], now: ms }); + const seedStale = async (app: FastifyInstance, count: number, beforeMs: number) => { + const ctx = getHeimdallRuntimeContext(app); + for (let i = 0; i < count; i += 1) { + const expiresAt = new Date(beforeMs - i).toISOString(); + await ctx.store.claimOAuthStateUse({ jti: `stale-${i}`, phase: "launch", appSlug: "bifrost", usedAt: expiresAt, expiresAt }); + } + }; + + it("later claims never prune a live state: its launch and callback replays stay refused", async () => { + const app = await newApp(); + const start = await bifrostStart(app); + const victim = await launchFlow(app, start); + const exp = decodeJwt(victim.state).payload.exp as number; + + // More stale records than one batch, then another user's flow, whose claims do the pruning. + const staleBefore = Date.now() - OAUTH_STATE_SKEW_MS - OAUTH_STATE_PRUNE_MARGIN_MS; + await seedStale(app, OAUTH_STATE_PRUNE_BATCH + 10, staleBefore); + await launchFlow(app, await bifrostStart(app)); + + const launchReplay = await app.inject({ method: "GET", url: launchUrl(start) }); + expect(launchReplay.json()).toEqual({ error: "state_already_launched" }); + + // The callback is not pruned either: it completes once, and its replay is refused. + expect((await callback(app, victim.state, victim.cookie, "code=victim-code")).statusCode).toBe(201); + expect((await callback(app, victim.state, victim.cookie, "code=victim-code")).json()).toEqual({ error: "state_already_used" }); + + // Inside exp + skew the state still verifies, and the record still refuses it. + clockAt((exp + OAUTH_STATE_SKEW_MS / 1000 - 1) * 1000); + await launchFlow(app, await bifrostStart(app)); + const lateReplay = await app.inject({ method: "GET", url: launchUrl(start) }); + expect(lateReplay.json()).toEqual({ error: "state_already_launched" }); + + }); + + it("once its records are pruned, an expired state is refused as state_expired, by the state and not the record", async () => { + const app = await newApp(); + const ctx = getHeimdallRuntimeContext(app); + const start = await bifrostStart(app); + const victim = await launchFlow(app, start); + const exp = decodeJwt(victim.state).payload.exp as number; + + // Past exp + skew + margin the victim's launch record is prunable; a new claim removes it. + const pruneAt = (exp + (OAUTH_STATE_SKEW_MS + OAUTH_STATE_PRUNE_MARGIN_MS) / 1000 + 1) * 1000; + clockAt(pruneAt); + await launchFlow(app, await bifrostStart(app)); + const record = { + jti: decodeJwt(victim.state).payload.jti as string, + phase: "launch" as const, + appSlug: "bifrost" as const, + usedAt: new Date(pruneAt).toISOString(), + expiresAt: new Date(exp * 1000).toISOString(), + }; + // The record is gone, as the store (not the route) would now let the claim through ... + expect(await ctx.store.claimOAuthStateUse(record)).toBe(true); + // ... yet the routes refuse the state itself. + const launchReplay = await app.inject({ method: "GET", url: launchUrl(start) }); + expect(launchReplay.statusCode).toBe(400); + expect(launchReplay.json()).toEqual({ error: "state_expired" }); + expect((await callback(app, victim.state, victim.cookie)).json()).toEqual({ error: "state_expired" }); + }); }); it("a provider refusal from the launching browser still denies the attempt, once", async () => { diff --git a/tests/store.test.ts b/tests/store.test.ts index 75ee256..dc0fbe2 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -14,6 +14,11 @@ import { samePredicate, STORE_TABLE_PRIVILEGES, } from "../src/store/postgres.js"; +import { + OAUTH_STATE_PRUNE_BATCH, + OAUTH_STATE_PRUNE_MARGIN_MS, + OAUTH_STATE_SKEW_MS, +} from "../src/store/types.js"; import { CREATE_SCHEMA_SQL, REQUIRED_COLUMNS, REQUIRED_KEYS, REQUIRED_TABLES } from "../src/store/schema.js"; describe("PostgresStore", () => { @@ -276,19 +281,82 @@ describe("InMemoryStore.claimOAuthStateUse", () => { expect(await store.claimOAuthStateUse({ ...use, jti: "state-2" })).toBe(true); }); - it("drops a record once its state's exp + 30 s skew has passed, and keeps it until then", async () => { + it("drops a record only once its state's exp + skew + margin has passed", async () => { const store = new InMemoryStore(); await store.claimOAuthStateUse(use); - // Before expiry a later claim of another state leaves the record in force. - await store.claimOAuthStateUse({ ...use, jti: "state-2", usedAt: "2026-04-26T12:09:59.000Z" }); + const expMs = Date.parse(use.expiresAt); + const at = (ms: number) => new Date(ms).toISOString(); + // Inside the skew past expiry the state still verifies, and the margin keeps the record beyond that. + await store.claimOAuthStateUse({ ...use, jti: "state-2", usedAt: at(expMs + OAUTH_STATE_SKEW_MS) }); expect(await store.claimOAuthStateUse(use)).toBe(false); - // Inside the 30 s skew past expiry the state still verifies, so the record still refuses a replay. - await store.claimOAuthStateUse({ ...use, jti: "state-3", usedAt: "2026-04-26T12:10:29.999Z" }); + const boundary = expMs + OAUTH_STATE_SKEW_MS + OAUTH_STATE_PRUNE_MARGIN_MS; + await store.claimOAuthStateUse({ ...use, jti: "state-3", usedAt: at(boundary - 1) }); expect(await store.claimOAuthStateUse(use)).toBe(false); - // At exp + 30 s the state is refused before any claim and the record is dead weight. - await store.claimOAuthStateUse({ ...use, jti: "state-4", usedAt: "2026-04-26T12:10:30.000Z" }); + // At exactly exp + skew + margin the record is prunable (the rule is <=). + await store.claimOAuthStateUse({ ...use, jti: "state-4", usedAt: at(boundary) }); expect(await store.claimOAuthStateUse(use)).toBe(true); }); + + it("removes at most one batch of prunable records per successful claim", async () => { + const store = new InMemoryStore(); + const expMs = Date.parse(use.expiresAt); + const total = OAUTH_STATE_PRUNE_BATCH * 2 + 7; + for (let i = 0; i < total; i += 1) await store.claimOAuthStateUse({ ...use, jti: `old-${i}` }); + const size = () => (store as unknown as { oauthStateUses: Map }).oauthStateUses.size; + expect(size()).toBe(total); + const later = new Date(expMs + OAUTH_STATE_SKEW_MS + OAUTH_STATE_PRUNE_MARGIN_MS).toISOString(); + await store.claimOAuthStateUse({ ...use, jti: "fresh-1", usedAt: later, expiresAt: later }); + expect(size()).toBe(total + 1 - OAUTH_STATE_PRUNE_BATCH); + // A refused (replayed) claim prunes nothing, as on Postgres where the delete follows a new row. + await store.claimOAuthStateUse({ ...use, jti: "fresh-1", usedAt: later, expiresAt: later }); + expect(size()).toBe(total + 1 - OAUTH_STATE_PRUNE_BATCH); + }); +}); + +describe("PostgresStore.claimOAuthStateUse retention", () => { + const use = { + jti: "state-1", + phase: "launch" as const, + appSlug: "repixelizer" as const, + usedAt: "2026-04-26T12:00:00.000Z", + expiresAt: "2026-04-26T12:10:00.000Z", + }; + + function doublePool(prune: "ok" | "throws", inserted = 1) { + const calls: Array<{ sql: string; params: unknown[] }> = []; + const pool = { + query: async (sql: string, params: unknown[]) => { + calls.push({ sql, params }); + if (calls.length === 1) return { rowCount: inserted, rows: [] }; + if (prune === "throws") throw Object.assign(new Error("permission denied for table oauth_state_uses"), { code: "42501" }); + return { rowCount: 0, rows: [] }; + }, + }; + return { calls, store: new PostgresStore(pool as unknown as Pool) }; + } + + it("runs one bounded delete after a new row, at the shared cutoff and batch", async () => { + const { calls, store } = doublePool("ok"); + expect(await store.claimOAuthStateUse(use)).toBe(true); + expect(calls).toHaveLength(2); + expect(calls[1]!.sql).toMatch(/DELETE FROM oauth_state_uses/); + expect(calls[1]!.params).toEqual([ + new Date(Date.parse(use.usedAt) - OAUTH_STATE_SKEW_MS - OAUTH_STATE_PRUNE_MARGIN_MS), + OAUTH_STATE_PRUNE_BATCH, + ]); + }); + + it("prunes nothing when the claim is a replay", async () => { + const { calls, store } = doublePool("ok", 0); + expect(await store.claimOAuthStateUse(use)).toBe(false); + expect(calls).toHaveLength(1); + }); + + it("a failing prune does not change the claim's result", async () => { + const { calls, store } = doublePool("throws"); + expect(await store.claimOAuthStateUse(use)).toBe(true); + expect(calls).toHaveLength(2); + }); }); describe("createPostgresStore", () => { @@ -481,6 +549,15 @@ async function exerciseStore(store: PostgresStore): Promise> { expect(await s.claimOAuthStateUse(stateUse)).toBe(true); expect(await s.claimOAuthStateUse(stateUse)).toBe(false); expect(await s.claimOAuthStateUse({ ...stateUse, phase: "callback" })).toBe(true); + // The prune is swallowed when the role may not run it, so the exercise proves it ran: a long-expired + // record is gone after the next new claim. A missing prune stands for the privilege refusal behind it. + const stale = { ...stateUse, jti: randomUUID(), usedAt: "2000-01-01T00:00:00.000Z", expiresAt: "2000-01-01T00:10:00.000Z" }; + expect(await s.claimOAuthStateUse(stale)).toBe(true); + expect(await s.claimOAuthStateUse({ ...stateUse, jti: randomUUID() })).toBe(true); + const retained = await s.claimOAuthStateUse(stale); + if (!retained) { + throw Object.assign(new Error("oauth_state_uses was not pruned"), { code: "42501" }); + } const { receipt: grant } = await s.createConsentReceipt({ kind: "grant", accountId: account.id, appSlug: "streampixels", provider: "joystick", createdAt: now, scopesAsked: ["a", "b"], scopesGranted: ["a"], consentPageDigest: "d", consentText: "t" }); const revocation = { kind: "revocation" as const, accountId: account.id, appSlug: "streampixels" as const, provider: "joystick" as const, createdAt: later, revokesReceiptId: grant.id }; const first = await s.createConsentReceipt(revocation); @@ -639,6 +716,68 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD } }); + 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; + const use = (jti: string, usedAtMs: number, expiresAtMs = expMs) => ({ + jti, + phase: "launch" as const, + appSlug: "repixelizer" as const, + usedAt: new Date(usedAtMs).toISOString(), + expiresAt: new Date(expiresAtMs).toISOString(), + }); + const count = async (owner: Pool) => Number((await owner.query("SELECT count(*) AS n FROM oauth_state_uses")).rows[0].n); + const seed = async (owner: Pool, jti: string) => { + await owner.query( + "INSERT INTO oauth_state_uses (jti, phase, app_slug, used_at, expires_at) VALUES ($1, 'launch', 'repixelizer', $2, $2)", + [jti, new Date(expMs)] + ); + }; + + it.each([ + [boundary - 1, true], + [boundary, false], + [boundary + 1, false], + ])("a claim at exp + skew + margin %i ms keeps the record: %s", async (usedAtMs, kept) => { + const { owner } = await appliedDatabase(); + const store = new PostgresStore(owner); + expect(await store.claimOAuthStateUse(use("old", expMs - 1000))).toBe(true); + expect(await store.claimOAuthStateUse(use("other", usedAtMs, usedAtMs + 600_000))).toBe(true); + expect(await store.claimOAuthStateUse(use("old", usedAtMs))).toBe(!kept); + }); + + it("removes at most one batch per claim and never the live record", async () => { + const { owner } = await appliedDatabase(); + const store = new PostgresStore(owner); + const total = OAUTH_STATE_PRUNE_BATCH * 2 + 7; + for (let i = 0; i < total; i += 1) await seed(owner, `old-${i}`); + const fresh = use("fresh", boundary + 5, boundary + 600_000); + expect(await store.claimOAuthStateUse(fresh)).toBe(true); + expect(await count(owner)).toBe(total + 1 - OAUTH_STATE_PRUNE_BATCH); + expect(await store.claimOAuthStateUse(fresh)).toBe(false); + expect(await count(owner)).toBe(total + 1 - OAUTH_STATE_PRUNE_BATCH); + }); + + it("keeps its expires_at index", async () => { + const { owner } = await appliedDatabase(); + const found = await owner.query("SELECT 1 FROM pg_indexes WHERE indexname = 'oauth_state_uses_expires_at_idx'"); + expect(found.rowCount).toBe(1); + }); + + 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"] }); + await seed(owner, "old"); + const pool = fixturePool(urlFor(name, role, rolePassword)); + cleanup.push(async () => { + await pool.end(); + }); + const store = new PostgresStore(pool); + expect(await store.claimOAuthStateUse(use("fresh", boundary + 5, boundary + 600_000))).toBe(true); + expect(await count(owner)).toBe(2); + }); + }); + it("refuses to apply the schema as a role that may not, and closes the store", async () => { const { name, owner } = await appliedDatabase(); await grant(owner, STORE_TABLE_PRIVILEGES); @@ -686,7 +825,10 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD await owner.query(`GRANT USAGE ON SCHEMA public TO ${role}`); for (const [table, wanted] of Object.entries(STORE_TABLE_PRIVILEGES)) { const columns = REQUIRED_COLUMNS.filter((column) => column.table === table).map((column) => column.column).join(", "); - for (const privilege of wanted) await owner.query(`GRANT ${privilege} (${columns}) ON ${table} TO ${role}`); + for (const privilege of wanted) { + // DELETE removes rows and cannot be granted per column. + await owner.query(privilege === "DELETE" ? `GRANT DELETE ON ${table} TO ${role}` : `GRANT ${privilege} (${columns}) ON ${table} TO ${role}`); + } } expect(await start(urlFor(name, role, rolePassword), false)).toBe("started"); From 4aa9d03c4f5bc827c6c516e84241ffa791fceb74 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 13 Nov 2026 07:03:30 +0000 Subject: [PATCH 36/63] Consent bomb test: pin the inflate output cap, not a wall-clock bound The 1500 ms bound measured 3330 ms under parallel load. What the test proves is that a decompression bomb is read under the 16 KB cap; record the inflate options and assert maxOutputLength directly. Mutant (drop the cap) fails the test. Co-Authored-By: Claude Sonnet 5.5 --- tests/joystick-consent.test.ts | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/tests/joystick-consent.test.ts b/tests/joystick-consent.test.ts index 79cc512..4801692 100644 --- a/tests/joystick-consent.test.ts +++ b/tests/joystick-consent.test.ts @@ -11,6 +11,20 @@ import { providerCatalog } from "../src/providers.js"; import { InMemoryStore } from "../src/store/index.js"; import { createTestConfig, setCookieOf, stateOf } from "./oauth-flow.js"; +// Records the options of every inflate the app runs, so the bomb test can pin the output cap +// itself instead of timing a refusal. Behaviour is the real inflate. +const inflateCalls = vi.hoisted(() => [] as Array<{ maxOutputLength: number | undefined }>); +vi.mock("node:zlib", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + inflateRawSync: ((buf: Parameters[0], opts?: Parameters[1]) => { + inflateCalls.push({ maxOutputLength: opts?.maxOutputLength }); + return real.inflateRawSync(buf, opts); + }) as typeof real.inflateRawSync, + }; +}); + // The consent cut for managed custody (docs/joystick-consent-flow.md): the ask, // the typed refusal, the receipt, and the signed-in page that lists and revokes. @@ -220,7 +234,7 @@ describe("the ask", () => { const signedAsk = (ctx: ReturnType, jti: string, exp: number, text: Buffer) => signJwt({ typ: "heimdall_consent_ask", iss: ctx.config.issuer, jti, iat: exp - 600, exp, ct: deflateRawSync(text).toString("base64url") }, ctx.keys); - it("is read up to 16 KB and no further: one byte over is refused, and a bomb is refused quickly", async () => { + it("is read up to 16 KB and no further: one byte over is refused, and a bomb is inflated under that cap", async () => { const { app } = await newApp(); const ctx = getHeimdallRuntimeContext(app); const state = await startConnect(app); @@ -228,9 +242,12 @@ describe("the ask", () => { const answerWith = (text: Buffer, decision: "decline" | "continue" = "decline") => answer(app, state, decision, `__Host-heimdall-ask-${jti}=${signedAsk(ctx, jti, exp, text)}`, "application/json"); expect((await answerWith(Buffer.alloc(16 * 1024 + 1, 97))).json()).toEqual({ error: "state_not_bound" }); - const t0 = Date.now(); - expect((await answerWith(Buffer.alloc(300 * 1024 * 1024))).json()).toEqual({ error: "state_not_bound" }); - expect(Date.now() - t0).toBeLessThan(1500); + // A bomb: far past the cap once inflated. It is refused, and the inflate that refused it was + // handed the cap, so it never produced more than 16 KB (the property, not a wall-clock proxy). + inflateCalls.length = 0; + expect((await answerWith(Buffer.alloc(4 * 1024 * 1024))).json()).toEqual({ error: "state_not_bound" }); + expect(inflateCalls.length).toBeGreaterThan(0); + expect(inflateCalls.every((c) => c.maxOutputLength !== undefined && c.maxOutputLength <= 16 * 1024)).toBe(true); // At the cap it is read. expect((await answerWith(Buffer.alloc(16 * 1024, 97))).json()).toMatchObject({ error: "consent_refused" }); }); From 46d50449255475a1964d1b74caeede0d34fbd367 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 13 Nov 2026 18:59:21 +0000 Subject: [PATCH 37/63] Store: an upsert never moves an identity between accounts; unlinkLinkedIdentity is the one delete, under an account lock, refusing the last identity STORE_TABLE_PRIVILEGES.linked_identities gains DELETE; startup refuses a role without it. Co-Authored-By: Claude Sonnet 5.5 --- src/store/in-memory.ts | 14 +++++ src/store/postgres.ts | 49 +++++++++++++++-- src/store/types.ts | 26 +++++++++ tests/store.test.ts | 117 ++++++++++++++++++++++++++++++++++++++++- 4 files changed, 200 insertions(+), 6 deletions(-) diff --git a/src/store/in-memory.ts b/src/store/in-memory.ts index 5df37ea..b35decb 100644 --- a/src/store/in-memory.ts +++ b/src/store/in-memory.ts @@ -18,6 +18,7 @@ import { type CreateSessionInput, type CreatePrivateCommandReceiptInput, type HeimdallStore, + IdentityHeldElsewhereError, type StoredAccount, type StoredAuthAttempt, type StoredAuthCompletion, @@ -25,6 +26,7 @@ import { type StoredLinkedIdentity, type StoredSession, type StoredPrivateCommandReceipt, + type UnlinkResult, type UpsertLinkedIdentityInput, } from "./types.js"; @@ -148,6 +150,9 @@ 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, @@ -188,6 +193,15 @@ 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) }; + } + async updateLinkedIdentityCredential( id: string, decide: (locked: StoredLinkedIdentity) => Promise, diff --git a/src/store/postgres.ts b/src/store/postgres.ts index 247260c..0b05f61 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -18,6 +18,7 @@ import { type CreateSessionInput, type CreatePrivateCommandReceiptInput, type HeimdallStore, + IdentityHeldElsewhereError, OAUTH_STATE_PRUNE_BATCH, oauthStatePruneCutoffMs, type StoredAccount, @@ -27,6 +28,7 @@ import { type StoredLinkedIdentity, type StoredSession, type StoredPrivateCommandReceipt, + type UnlinkResult, type UpsertLinkedIdentityInput, } from "./types.js"; @@ -451,13 +453,15 @@ 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 only expired - * oauth_state_uses rows (which needs SELECT for its WHERE). + * 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). * audit_events is written and never read back. */ export const STORE_TABLE_PRIVILEGES: Readonly> = { accounts: ["SELECT", "INSERT", "UPDATE"], - linked_identities: ["SELECT", "INSERT", "UPDATE"], + linked_identities: ["SELECT", "INSERT", "UPDATE", "DELETE"], sessions: ["SELECT", "INSERT", "UPDATE"], auth_attempts: ["SELECT", "INSERT", "UPDATE"], private_command_receipts: ["SELECT", "INSERT"], @@ -780,7 +784,6 @@ export class PostgresStore implements HeimdallStore { ) ON CONFLICT (provider, provider_user_id) DO UPDATE SET - account_id = EXCLUDED.account_id, username = EXCLUDED.username, display_name = EXCLUDED.display_name, primary_email = EXCLUDED.primary_email, @@ -791,6 +794,7 @@ export class PostgresStore implements HeimdallStore { scopes = EXCLUDED.scopes, profile_json = EXCLUDED.profile_json, updated_at = EXCLUDED.updated_at + WHERE linked_identities.account_id = EXCLUDED.account_id RETURNING * `, [ @@ -811,7 +815,42 @@ export class PostgresStore implements HeimdallStore { ] ); - return mapLinkedIdentityRow(expectRow(result.rows[0], "upsertLinkedIdentity")); + // The conflict arm updates only the holder's own row; another account's yields no row. + if (!result.rows[0]) throw new IdentityHeldElsewhereError(); + return mapLinkedIdentityRow(result.rows[0]); + } + + async unlinkLinkedIdentity(accountId: string, identityId: string): Promise { + 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 updateLinkedIdentityCredential( diff --git a/src/store/types.ts b/src/store/types.ts index a2a792d..a056f9f 100644 --- a/src/store/types.ts +++ b/src/store/types.ts @@ -41,6 +41,24 @@ 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" }; + export interface UpsertLinkedIdentityInput { id?: string; accountId: string; @@ -311,7 +329,15 @@ 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; /** * 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/tests/store.test.ts b/tests/store.test.ts index dc0fbe2..76665cc 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, InMemoryStore } from "../src/store/index.js"; +import { createStore, IdentityHeldElsewhereError, InMemoryStore, type HeimdallStore } from "../src/store/index.js"; import { createPostgresStore, PostgresStore, @@ -203,6 +203,84 @@ 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("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)"); @@ -496,6 +574,8 @@ 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"); @@ -716,6 +796,41 @@ 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("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; From 3afc956f92f4114d9da5be281b9638fea22dfe11 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 13 Nov 2026 18:59:21 +0000 Subject: [PATCH 38/63] Member identity list and step-up-gated unlink: step_up_at on a step-up sign-in's access claim, GET /v1/me/identities, POST /v1/me/identities/:id/unlink resolveBearer is the one bearer verifier; the link race maps to link_initiator_mismatch and links/confirm 409. Co-Authored-By: Claude Sonnet 5.5 --- src/app.ts | 195 ++++++++++++++++++----- src/claims.ts | 9 ++ src/contracts.ts | 2 + tests/google-link.test.ts | 14 +- tests/identity-unlink.test.ts | 281 ++++++++++++++++++++++++++++++++++ tests/link-binding.test.ts | 11 +- tests/step-up.test.ts | 2 + 7 files changed, 471 insertions(+), 43 deletions(-) create mode 100644 tests/identity-unlink.test.ts diff --git a/src/app.ts b/src/app.ts index 2977f08..2eceba0 100644 --- a/src/app.ts +++ b/src/app.ts @@ -24,7 +24,7 @@ import { type OAuthStartRequest, type Provider, } from "./contracts.js"; -import { issueAccessClaim, type IssueAccessClaimInput } from "./claims.js"; +import { issueAccessClaim, STEP_UP_PROOF_TTL_SECONDS, 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"; @@ -41,7 +41,7 @@ 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, type HeimdallStore } from "./store/index.js"; +import { createStore, IdentityHeldElsewhereError, type HeimdallStore } from "./store/index.js"; import { OAUTH_STATE_SKEW_MS, type CreateAccountInput, @@ -879,28 +879,36 @@ 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; +} + /** - * 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 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 store still holds for that account at that revision. A bearer that fails - * any of these binds nothing: a link is explicit or it does not happen. + * any of these proves nothing. */ -async function resolveLinkAccount( +async function resolveBearer( ctx: Pick, - appSlug: AppSlug, - authorization: string | undefined -): Promise { + authorization: string | undefined, + appSlug?: AppSlug +): 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 !== appSlug || + claims.aud !== audience || typeof claims.account_id !== "string" || typeof claims.sid !== "string" || typeof claims.access_revision !== "number" || @@ -910,7 +918,7 @@ async function resolveLinkAccount( ) { return null; } - const session = await ctx.store.findSession(appSlug, claims.sid); + const session = await ctx.store.findSession(audience, claims.sid); if ( !session || session.accountId !== claims.account_id || @@ -919,7 +927,16 @@ async function resolveLinkAccount( ) { return null; } - return claims.account_id; + return { accountId: claims.account_id, claims }; +} + +/** 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; } /** The account a Heimdall access token for any app names, when the token and its session are live. */ @@ -927,12 +944,7 @@ async function resolveAccessAccount( ctx: Pick, 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 audience = verification.payload.aud; - return isAppSlug(audience) ? resolveLinkAccount(ctx, audience, authorization) : null; + return (await resolveBearer(ctx, authorization))?.accountId ?? null; } const grantsPageTokenType = "heimdall_grants_page"; @@ -1847,7 +1859,15 @@ 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(); + const provedAt = claims.step_up_at; + if (typeof provedAt !== "number" || provedAt > nowS || nowS - provedAt > STEP_UP_PROOF_TTL_SECONDS) { + 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 }, + 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 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 } }>( @@ -2730,26 +2862,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise ({ kind: "revoke", updatedAt: 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, - }); - } + revoked.push(...(await revokeLiveGrants(accountId, grant.provider, receipts, 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 4440ed3..ef2da87 100644 --- a/src/claims.ts +++ b/src/claims.ts @@ -11,6 +11,9 @@ 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; + function nowEpochSeconds(): number { return Math.floor(Date.now() / 1000); } @@ -48,6 +51,8 @@ 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; } export interface IssuedAccessClaimResult { @@ -130,6 +135,10 @@ export async function issueAccessClaim(options: { identities: options.input.linkedIdentities, }; + if (options.input.stepUpAt !== undefined) { + claimSet.step_up_at = options.input.stepUpAt; + } + if (options.input.displayName) { claimSet.display_name = options.input.displayName; } diff --git a/src/contracts.ts b/src/contracts.ts index 78b3534..2d582f5 100644 --- a/src/contracts.ts +++ b/src/contracts.ts @@ -153,6 +153,8 @@ 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; display_name?: string; app: { slug: AppSlug; diff --git a/tests/google-link.test.ts b/tests/google-link.test.ts index a33f27c..4a1fc6d 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 { InMemoryStore } from "../src/store/index.js"; +import { IdentityHeldElsewhereError, InMemoryStore } from "../src/store/index.js"; import { launchFlow, launchWithRedirect, stateOf, type LaunchedFlow } from "./oauth-flow.js"; const CLIENT_ID = "google-client"; @@ -188,6 +188,18 @@ 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(); diff --git a/tests/identity-unlink.test.ts b/tests/identity-unlink.test.ts new file mode 100644 index 0000000..99e626b --- /dev/null +++ b/tests/identity-unlink.test.ts @@ -0,0 +1,281 @@ +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 } from "../src/signing.js"; +import { IdentityHeldElsewhereError, InMemoryStore } from "../src/store/index.js"; +import { createTestConfig, launchFlow } 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((await signIn(r, false)).claimSet.step_up_at).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(); + }); +}); + +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 }); + }); + + 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"]); + }); +}); diff --git a/tests/link-binding.test.ts b/tests/link-binding.test.ts index 7982229..4454d4d 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 { InMemoryStore } from "../src/store/index.js"; +import { IdentityHeldElsewhereError, InMemoryStore } from "../src/store/index.js"; import { launchFlow } from "./oauth-flow.js"; function createTestConfig(): HeimdallConfig { @@ -166,6 +166,15 @@ 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/step-up.test.ts b/tests/step-up.test.ts index 99531e3..6716623 100644 --- a/tests/step-up.test.ts +++ b/tests/step-up.test.ts @@ -150,6 +150,8 @@ 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"); } }); }); From d8b8d25e81b7bdf3c7390ff4278fa006496e4072 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 13 Nov 2026 18:59:21 +0000 Subject: [PATCH 39/63] Docs: identity list and unlink routes, step-up proof window, linked_identities single-writer rule; evidence ledger line Co-Authored-By: Claude Sonnet 5.5 --- docs/architecture.md | 12 +++++++ docs/service-contract.md | 74 ++++++++++++++++++++++++++++++++++++++++ state/evidence.jsonl | 1 + 3 files changed, 87 insertions(+) diff --git a/docs/architecture.md b/docs/architecture.md index 12fbd4f..f50396f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -336,6 +336,18 @@ 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. + ### 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 0469186..b818715 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -548,6 +548,80 @@ 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`. 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. + +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}/managed-credentials/resolve` Purpose: diff --git a/state/evidence.jsonl b/state/evidence.jsonl index f7fa724..5fd99b4 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -38,3 +38,4 @@ {"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."} From e9eef09446a387059670a268ec2d65860ab1c44c Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 13 Nov 2026 19:21:45 +0000 Subject: [PATCH 40/63] Pin the proof window's 600 s edge, foreign-id 404 over last_identity, and the sign_in-only step_up_at guard Co-Authored-By: Claude Sonnet 5.5 --- tests/identity-unlink.test.ts | 53 +++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/tests/identity-unlink.test.ts b/tests/identity-unlink.test.ts index 99e626b..ae70b7d 100644 --- a/tests/identity-unlink.test.ts +++ b/tests/identity-unlink.test.ts @@ -6,9 +6,9 @@ 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 } from "../src/signing.js"; +import { createRuntimeKeyMaterial, decodeJwt, signJwt, verifyJwt } from "../src/signing.js"; import { IdentityHeldElsewhereError, InMemoryStore } from "../src/store/index.js"; -import { createTestConfig, launchFlow } from "./oauth-flow.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 @@ -278,4 +278,53 @@ describe("POST /v1/me/identities/:identityId/unlink", () => { 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(); + }); }); From 46e5d5364f2d5f3effd4bad356ed86a11691a078 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 13 Nov 2026 19:21:45 +0000 Subject: [PATCH 41/63] Docs: a Twitch step-up proof is weaker; point the unlink section at the step-up note Co-Authored-By: Claude Sonnet 5.5 --- docs/service-contract.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/service-contract.md b/docs/service-contract.md index b818715..9c40713 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -606,6 +606,10 @@ 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 From 33a83c34c424a08d37fd5921313c901cfbd8b057 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 13 Nov 2026 19:59:26 +0000 Subject: [PATCH 42/63] App-asserted step-up: POST /v1/apps/{app}/step-up mints a same-session access token with step_up_at and step_up_method App secret plus the member's live bearer for that app, a per-profile grant and method allowlist (bifrost only), a nonce spent once per session through the existing oauth_state_uses claim (no schema change), an in-process fixed-window rate per account and per app, and an audit row per assertion or post-secret refusal. Provider step-up sign-ins now label their proof provider:. Co-Authored-By: Claude Sonnet 5.5 --- src/app-profiles.ts | 10 + src/app.ts | 140 +++++++++++- src/claims.ts | 29 +++ src/contracts.ts | 7 + src/fixed-window.ts | 47 ++++ src/store/types.ts | 3 +- tests/identity-unlink.test.ts | 8 +- tests/step-up-assertion.test.ts | 367 ++++++++++++++++++++++++++++++++ tests/store.test.ts | 14 ++ 9 files changed, 617 insertions(+), 8 deletions(-) create mode 100644 src/fixed-window.ts create mode 100644 tests/step-up-assertion.test.ts diff --git a/src/app-profiles.ts b/src/app-profiles.ts index c25dbb2..c1d5661 100644 --- a/src/app-profiles.ts +++ b/src/app-profiles.ts @@ -56,6 +56,15 @@ export interface AppProfile { * state. Absent for apps whose browser starts are public by design. */ startRequiresAppCaller?: boolean; + /** + * 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 membership signal shared by every app that gates on GameCult membership. */ @@ -154,6 +163,7 @@ const bifrostProfile: AppProfile = { managedConnectionProviders: [], allowedReturnOrigins: ["https://bifrost.gamecult.org"], startRequiresAppCaller: true, + stepUpAssertion: { methods: ["bifrost-passkey", "bifrost-email-code"] }, capabilities: [ { key: "member_access", diff --git a/src/app.ts b/src/app.ts index 2eceba0..43ead5f 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,4 +1,4 @@ -import { createHmac, randomUUID } from "node:crypto"; +import { createHash, createHmac, randomUUID } from "node:crypto"; import { deflateRawSync, inflateRawSync } from "node:zlib"; import cookie from "@fastify/cookie"; import cors from "@fastify/cors"; @@ -24,7 +24,8 @@ import { type OAuthStartRequest, type Provider, } from "./contracts.js"; -import { issueAccessClaim, STEP_UP_PROOF_TTL_SECONDS, type IssueAccessClaimInput } from "./claims.js"; +import { issueAccessClaim, signAssertedStepUpClaim, STEP_UP_PROOF_TTL_SECONDS, type IssueAccessClaimInput } from "./claims.js"; +import { FixedWindowBudget, type FixedWindowLimit } from "./fixed-window.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"; @@ -883,6 +884,8 @@ export async function startOAuthFlow( 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; } /** @@ -927,7 +930,7 @@ async function resolveBearer( ) { return null; } - return { accountId: claims.account_id, claims }; + 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. */ @@ -947,6 +950,103 @@ async function resolveAccessAccount( 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 } = { + account: { max: 10, windowMs: 600_000 }, + app: { max: 120, windowMs: 60_000 }, +}; + +export interface StepUpAssertBudgets { + account: FixedWindowBudget; + app: 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) }; +} + +/** + * 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; 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; + const refuse = async (statusCode: number, error: string, extra: Record = {}): Promise => { + await store.createAuditEvent({ + ...(known ? { accountId: known.accountId, sessionId: known.sessionId } : {}), + appSlug, + eventType: "step_up_assertion_refused", + eventPayloadJson: { outcome: "refused", code: error, method: permitted?.methods.includes(input.method) ? input.method : null, nonceDigest: nonceDigest ?? null }, + createdAt: new Date().toISOString(), + }); + return { statusCode, body: { error, ...extra } }; + }; + const limited = (seconds: number) => refuse(429, "step_up_rate_limited", { retryAfterSeconds: seconds }); + + if (!permitted) { + return refuse(403, "step_up_assertion_not_permitted", { detail: `${appSlug} may not assert step-up proofs.` }); + } + const appWait = budgets.app.spend(appSlug); + if (appWait) return limited(appWait); + + 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 accountWait = budgets.account.spend(bearer.accountId); + if (accountWait) return limited(accountWait); + + 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 }, + }, + }; +} + const grantsPageTokenType = "heimdall_grants_page"; const grantsPageTokenTtlSeconds = 600; @@ -1925,7 +2025,7 @@ 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 }, + nonce: { type: "string", minLength: 16, maxLength: 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: { @@ -2785,7 +2915,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise`); the claim never carries one without the other. */ + stepUpMethod?: string; } export interface IssuedAccessClaimResult { @@ -137,6 +139,9 @@ export async function issueAccessClaim(options: { 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.displayName) { @@ -200,3 +205,27 @@ 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 }; +} diff --git a/src/contracts.ts b/src/contracts.ts index 2d582f5..d7a521c 100644 --- a/src/contracts.ts +++ b/src/contracts.ts @@ -155,6 +155,13 @@ export interface AccessClaimPayload { 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; display_name?: string; app: { slug: AppSlug; diff --git a/src/fixed-window.ts b/src/fixed-window.ts new file mode 100644 index 0000000..7110bf3 --- /dev/null +++ b/src/fixed-window.ts @@ -0,0 +1,47 @@ +// 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`. Returns 0 when allowed, else the seconds until the window turns over. */ + spend(key: string): number { + const at = this.now(); + const current = this.windows.get(key); + if (!current || at - current.startedAt >= this.limit.windowMs) { + this.sweep(at); + this.windows.set(key, { startedAt: at, used: 1 }); + return 0; + } + if (current.used >= this.limit.max) { + return Math.max(1, Math.ceil((current.startedAt + this.limit.windowMs - at) / 1000)); + } + current.used += 1; + return 0; + } + + /** 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/types.ts b/src/store/types.ts index a056f9f..c044161 100644 --- a/src/store/types.ts +++ b/src/store/types.ts @@ -209,7 +209,8 @@ export function oauthStatePruneCutoffMs(nowMs: number): number { export interface ClaimOAuthStateUseInput { jti: string; - phase: "launch" | "callback"; + /** `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"; appSlug: AppSlug; usedAt: string; expiresAt: string; diff --git a/tests/identity-unlink.test.ts b/tests/identity-unlink.test.ts index ae70b7d..e12e418 100644 --- a/tests/identity-unlink.test.ts +++ b/tests/identity-unlink.test.ts @@ -118,11 +118,15 @@ describe("step_up_at on the access claim", () => { 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((await signIn(r, false)).claimSet.step_up_at).toBeUndefined(); + 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(); }); }); @@ -211,7 +215,7 @@ describe("POST /v1/me/identities/:identityId/unlink", () => { 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 }); + 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 () => { diff --git a/tests/step-up-assertion.test.ts b/tests/step-up-assertion.test.ts new file mode 100644 index 0000000..e505829 --- /dev/null +++ b/tests/step-up-assertion.test.ts @@ -0,0 +1,367 @@ +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}-`.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: 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 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("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/store.test.ts b/tests/store.test.ts index 76665cc..0e4dcac 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -879,6 +879,20 @@ 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"] }); From 2f93809a2970d913322619c73f7dd1818a43c839 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 13 Nov 2026 20:01:46 +0000 Subject: [PATCH 43/63] Docs: app-asserted step-up route, step_up_method claim, Bifrost profile grant, architecture note, evidence line Co-Authored-By: Claude Sonnet 5.5 --- docs/app-profiles/bifrost.md | 12 ++++++ docs/architecture.md | 12 ++++++ docs/service-contract.md | 77 +++++++++++++++++++++++++++++++++++- state/evidence.jsonl | 1 + 4 files changed, 101 insertions(+), 1 deletion(-) diff --git a/docs/app-profiles/bifrost.md b/docs/app-profiles/bifrost.md index 976452f..a174d50 100644 --- a/docs/app-profiles/bifrost.md +++ b/docs/app-profiles/bifrost.md @@ -77,3 +77,15 @@ 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`. diff --git a/docs/architecture.md b/docs/architecture.md index f50396f..d78687c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -348,6 +348,18 @@ 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. +### 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, the unlink check, and a refresh sets neither. 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), +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 9c40713..35cb6fc 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -599,7 +599,8 @@ body is empty or `null`. 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`. A refresh never carries it: +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 @@ -626,6 +627,78 @@ 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" } +``` + +Order of refusals, each a closed `error` code: + +- `401 app_auth_required`: missing, wrong or another app's secret. Checked + first; 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. +- `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) or the per-account budget (10 per 600 s) 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. +- `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 and is kept until the session's own expiry. 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`, with the +app, the account and session when the bearer resolved, `method` (null when it +was not in the allowlist), `outcome`, `code` and `nonceDigest`. Never the +secret, the bearer, the minted token or the nonce. A request without the secret +writes nothing. + +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}/managed-credentials/resolve` Purpose: @@ -761,6 +834,8 @@ 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 - `display_name` optional - `app.slug` - `app.profile_version` diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 5fd99b4..24a56eb 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -39,3 +39,4 @@ {"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 per session via oauth_state_uses phase step_up_assert (no schema change); 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. 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"} From 12599116325bf82c8649f4ff57d3ec2e3e5cc1f2 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 13 Nov 2026 20:13:13 +0000 Subject: [PATCH 44/63] Step-up assertion: audit a flood once per window, budget the not-permitted branch, base64url nonce, honest nonce retention and precondition docs Co-Authored-By: Claude Sonnet 5.5 --- docs/app-profiles/bifrost.md | 7 +++++ docs/architecture.md | 3 +- docs/service-contract.md | 42 ++++++++++++++++++++----- src/app.ts | 39 ++++++++++++++++------- src/fixed-window.ts | 20 ++++++------ state/evidence.jsonl | 2 +- tests/step-up-assertion.test.ts | 55 +++++++++++++++++++++++++++++++-- 7 files changed, 135 insertions(+), 33 deletions(-) diff --git a/docs/app-profiles/bifrost.md b/docs/app-profiles/bifrost.md index a174d50..41508e5 100644 --- a/docs/app-profiles/bifrost.md +++ b/docs/app-profiles/bifrost.md @@ -89,3 +89,10 @@ 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). diff --git a/docs/architecture.md b/docs/architecture.md index d78687c..f1d66c3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -357,7 +357,8 @@ checked a factor; label from the profile's `stepUpAssertion.methods`). Both feed the one reader, the unlink check, and a refresh sets neither. 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), +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 diff --git a/docs/service-contract.md b/docs/service-contract.md index 35cb6fc..32b402a 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -645,32 +645,45 @@ Body (`additionalProperties` are dropped as on the sibling routes): { "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. + Order of refusals, each a closed `error` code: - `401 app_auth_required`: missing, wrong or another app's secret. Checked first; 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. + 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) or the per-account budget (10 per 600 s) is - spent. In-process fixed windows: they reset when the process restarts and are - not shared between instances. + 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. + 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 and is kept until the session's own expiry. A - refused method or a rate-limited attempt does not spend the nonce. + across restarts and instances. **Retention is the session's expiry as of the + claim, plus the store's prune margin.** 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`. @@ -684,12 +697,25 @@ 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`, with the +refusal after the secret verified writes `step_up_assertion_refused`, except +that a flood is not recorded row by row: a rate-limited refusal is recorded +once per window per budget (its first), and an app without the grant once per +window, with the app, the account and session when the bearer resolved, `method` (null when it was not in the allowlist), `outcome`, `code` and `nonceDigest`. Never the secret, the bearer, the minted token or the nonce. A request without the secret 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. Requiring a method per +route (identity moves first) is the later hardening and is not in this change. + 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 diff --git a/src/app.ts b/src/app.ts index 43ead5f..ac2f97a 100644 --- a/src/app.ts +++ b/src/app.ts @@ -951,18 +951,25 @@ async function resolveAccessAccount( } /** 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 } = { +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) }; + 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), + }; } /** @@ -971,8 +978,10 @@ export function createStepUpAssertBudgets(now: () => number = () => Date.now()): * 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; a request without the secret - * writes nothing, since anyone can send one. The audit rows carry a digest of + * 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( @@ -989,7 +998,8 @@ export async function assertStepUp( const permitted = getAppProfile(appSlug)?.stepUpAssertion; let known: { accountId: string; sessionId: string } | undefined; let nonceDigest: string | undefined; - const refuse = async (statusCode: number, error: string, extra: Record = {}): Promise => { + 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, @@ -999,13 +1009,17 @@ export async function assertStepUp( }); return { statusCode, body: { error, ...extra } }; }; - const limited = (seconds: number) => refuse(429, "step_up_rate_limited", { retryAfterSeconds: seconds }); + // Audit only the first denial of a window: the rows record that a budget tripped, not every request behind it. + const limited = (spent: { n: number; retryAfterSeconds: number }, max: number) => + refuse(429, "step_up_rate_limited", { retryAfterSeconds: spent.retryAfterSeconds }, spent.n === max + 1); if (!permitted) { - return refuse(403, "step_up_assertion_not_permitted", { detail: `${appSlug} may not assert step-up proofs.` }); + const spent = budgets.notPermitted.spend(appSlug); + if (spent.retryAfterSeconds) return limited(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 appWait = budgets.app.spend(appSlug); - if (appWait) return limited(appWait); + const appSpent = budgets.app.spend(appSlug); + if (appSpent.retryAfterSeconds) return limited(appSpent, STEP_UP_ASSERT_LIMITS.app.max); const bearer = await resolveBearer(ctx, headers.authorization as string | undefined); if (!bearer) { @@ -1016,8 +1030,8 @@ export async function assertStepUp( if (bearer.claims.aud !== appSlug) { return refuse(403, "bearer_app_mismatch", { detail: `The access token was not issued to ${appSlug}.` }); } - const accountWait = budgets.account.spend(bearer.accountId); - if (accountWait) return limited(accountWait); + const accountSpent = budgets.account.spend(bearer.accountId); + if (accountSpent.retryAfterSeconds) return limited(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)) { @@ -2553,7 +2567,8 @@ export async function buildApp(options: BuildAppOptions = {}): Promise= this.limit.windowMs) { this.sweep(at); - this.windows.set(key, { startedAt: at, used: 1 }); - return 0; - } - if (current.used >= this.limit.max) { - return Math.max(1, Math.ceil((current.startedAt + this.limit.windowMs - at) / 1000)); + current = { startedAt: at, used: 0 }; + this.windows.set(key, current); } current.used += 1; - return 0; + 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. */ diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 24a56eb..caaa8e6 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -39,4 +39,4 @@ {"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 per session via oauth_state_uses phase step_up_assert (no schema change); 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. 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-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"} diff --git a/tests/step-up-assertion.test.ts b/tests/step-up-assertion.test.ts index e505829..b3115f1 100644 --- a/tests/step-up-assertion.test.ts +++ b/tests/step-up-assertion.test.ts @@ -18,7 +18,7 @@ import { createTestConfig } from "./oauth-flow.js"; 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}-`.padEnd(32, "x"); +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 }; @@ -259,7 +259,7 @@ describe("the method and the nonce", () => { 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: 7, nonce: nonce("a") }]) { + 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([]); @@ -278,6 +278,25 @@ describe("the method and the nonce", () => { expect((await assertStepUp(r, { token: second.token })).statusCode).toBe(201); }); + it("a nonce is retained to the session's expiry as of the claim: a refresh slides the session past it, and then 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; + // Inside the retained horizon the replay is still refused, refreshed session or not. + expect(refused(await assertStepUp(r, { token, nonce: nonce("N") }))).toEqual([409, "step_up_nonce_replayed"]); + // Past the old expiry plus the store's prune margin, the next claim prunes N while the session lives on. + vi.setSystemTime(t0 + R + 11 * 60_000); + expect((await assertStepUp(r, { token, nonce: nonce("M") })).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); @@ -323,6 +342,38 @@ describe("rate limits", () => { }); }); +describe("flood handling", () => { + 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); + 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); + expect(accountRows.filter((e) => e.eventPayloadJson.code === "step_up_rate_limited")).toHaveLength(1); + }); +}); + 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(); From 6ed6d8fa0dbd2ac8d7700cfea4bd7e7bbe1accce Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 13 Nov 2026 20:19:41 +0000 Subject: [PATCH 45/63] Step-up assertion: pin per-app not-permitted budget and the 10.5 min prune horizon, name the tripped budget in the audit row, correct validation-order and audit docs Co-Authored-By: Claude Sonnet 5.5 --- docs/service-contract.md | 27 +++++++++++++++++---------- src/app.ts | 15 +++++++++------ tests/step-up-assertion.test.ts | 29 +++++++++++++++++++++++------ 3 files changed, 49 insertions(+), 22 deletions(-) diff --git a/docs/service-contract.md b/docs/service-contract.md index 32b402a..2266c0d 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -649,10 +649,13 @@ 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. -Order of refusals, each a closed `error` code: +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. Checked - first; nothing is written. +- `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 @@ -678,7 +681,8 @@ Order of refusals, each a closed `error` code: 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 the store's prune margin.** A refresh slides the session's expiry + 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 @@ -698,13 +702,16 @@ 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 a flood is not recorded row by row: a rate-limited refusal is recorded -once per window per budget (its first), and an app without the grant once per -window, with the +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` and `nonceDigest`. Never the -secret, the bearer, the minted token or the nonce. A request without the secret -writes nothing. +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 diff --git a/src/app.ts b/src/app.ts index ac2f97a..9e8c334 100644 --- a/src/app.ts +++ b/src/app.ts @@ -998,28 +998,31 @@ export async function assertStepUp( 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, method: permitted?.methods.includes(input.method) ? input.method : null, nonceDigest: nonceDigest ?? null }, + 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 = (spent: { n: number; retryAfterSeconds: number }, max: number) => - refuse(429, "step_up_rate_limited", { retryAfterSeconds: spent.retryAfterSeconds }, spent.n === max + 1); + 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(spent, STEP_UP_ASSERT_LIMITS.notPermitted.max); + 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(appSpent, STEP_UP_ASSERT_LIMITS.app.max); + 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) { @@ -1031,7 +1034,7 @@ export async function assertStepUp( 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(accountSpent, STEP_UP_ASSERT_LIMITS.account.max); + 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)) { diff --git a/tests/step-up-assertion.test.ts b/tests/step-up-assertion.test.ts index b3115f1..f064e00 100644 --- a/tests/step-up-assertion.test.ts +++ b/tests/step-up-assertion.test.ts @@ -278,7 +278,7 @@ describe("the method and the nonce", () => { expect((await assertStepUp(r, { token: second.token })).statusCode).toBe(201); }); - it("a nonce is retained to the session's expiry as of the claim: a refresh slides the session past it, and then the nonce can be reused (documented limit)", async () => { + 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"] }); @@ -289,11 +289,14 @@ describe("the method and the nonce", () => { 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; - // Inside the retained horizon the replay is still refused, refreshed session or not. - expect(refused(await assertStepUp(r, { token, nonce: nonce("N") }))).toEqual([409, "step_up_nonce_replayed"]); - // Past the old expiry plus the store's prune margin, the next claim prunes N while the session lives on. - vi.setSystemTime(t0 + R + 11 * 60_000); + 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); }); @@ -343,6 +346,18 @@ describe("rate limits", () => { }); 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"); @@ -356,6 +371,7 @@ describe("flood handling", () => { 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); @@ -370,7 +386,8 @@ describe("flood handling", () => { 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); - expect(accountRows.filter((e) => e.eventPayloadJson.code === "step_up_rate_limited")).toHaveLength(1); + const trips = accountRows.filter((e) => e.eventPayloadJson.code === "step_up_rate_limited"); + expect(trips.map((e) => e.eventPayloadJson.budget)).toEqual(["account"]); }); }); From 4fe367ac8d2f1a3fd9480d2282b7b250f79d146c Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sat, 14 Nov 2026 01:59:11 +0000 Subject: [PATCH 46/63] Identity mover: POST /v1/apps/:slug/identity-moves, proof of both accounts, strict-passkey coverage, alias row, credential strip (#16) Soul s3 clean at 2f1b733. Needs identity_moves DDL + GRANT SELECT, INSERT before the build starts. Co-Authored-By: Claude Sonnet 5.5 --- docs/app-profiles/bifrost.md | 15 + docs/architecture.md | 20 +- docs/service-contract.md | 72 +++- src/app-profiles.ts | 9 + src/app.ts | 227 ++++++++++++- src/claims.ts | 47 +++ src/contracts.ts | 4 + src/store/identity-move.ts | 88 +++++ src/store/in-memory.ts | 77 +++++ src/store/postgres.ts | 146 ++++++++ src/store/schema.ts | 23 ++ src/store/types.ts | 65 ++++ state/evidence.jsonl | 1 + tests/identity-moves.test.ts | 632 +++++++++++++++++++++++++++++++++++ tests/store.test.ts | 277 ++++++++++++++- 15 files changed, 1694 insertions(+), 9 deletions(-) create mode 100644 src/store/identity-move.ts create mode 100644 tests/identity-moves.test.ts diff --git a/docs/app-profiles/bifrost.md b/docs/app-profiles/bifrost.md index 41508e5..9a7926c 100644 --- a/docs/app-profiles/bifrost.md +++ b/docs/app-profiles/bifrost.md @@ -96,3 +96,18 @@ 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 f1d66c3..956b1db 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -348,13 +348,31 @@ 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, the unlink check, and a refresh sets neither. The +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; diff --git a/docs/service-contract.md b/docs/service-contract.md index 2266c0d..6b77caa 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -720,8 +720,9 @@ cookie ticket would turn cookie theft into bearer theft and, with 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. Requiring a method per -route (identity moves first) is the later hardening and is not in this change. +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 @@ -732,6 +733,71 @@ 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: @@ -869,6 +935,8 @@ Current claim payload fields: - `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 c1d5661..a77f76a 100644 --- a/src/app-profiles.ts +++ b/src/app-profiles.ts @@ -65,6 +65,13 @@ export interface AppProfile { * 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. */ @@ -164,6 +171,8 @@ const bifrostProfile: AppProfile = { allowedReturnOrigins: ["https://bifrost.gamecult.org"], startRequiresAppCaller: 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 9e8c334..b3c7755 100644 --- a/src/app.ts +++ b/src/app.ts @@ -24,7 +24,7 @@ import { type OAuthStartRequest, type Provider, } from "./contracts.js"; -import { issueAccessClaim, signAssertedStepUpClaim, STEP_UP_PROOF_TTL_SECONDS, type IssueAccessClaimInput } from "./claims.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 { builtInAppProfiles, getAppProfile, isAllowedReturnOrigin, serializeAppProfile, admitsProviderForMode, callbackMint, isUsableConnectionTarget } from "./app-profiles.js"; import { renderBrowserHandoffPage } from "./browser-handoff.js"; @@ -47,6 +47,7 @@ import { OAUTH_STATE_SKEW_MS, type CreateAccountInput, type StoredCapabilityGrant, + type StoredIdentityMove, type StoredLinkedIdentity, type UpsertLinkedIdentityInput, } from "./store/types.js"; @@ -1064,6 +1065,184 @@ export async function assertStepUp( }; } +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 grantsPageTokenType = "heimdall_grants_page"; const grantsPageTokenTtlSeconds = 600; @@ -1976,8 +2155,9 @@ export async function buildApp(options: BuildAppOptions = {}): Promise nowS || nowS - provedAt > STEP_UP_PROOF_TTL_SECONDS) { + if (proofTier(claims, nowS) !== "strong") { reply.code(403); return { error: "step_up_required", @@ -2949,6 +3130,44 @@ export async function buildApp(options: BuildAppOptions = {}): Promise( + "/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 } }>( diff --git a/src/claims.ts b/src/claims.ts index 5e1d3b0..8ddd423 100644 --- a/src/claims.ts +++ b/src/claims.ts @@ -14,6 +14,9 @@ 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); } @@ -55,6 +58,10 @@ export interface IssueAccessClaimInput { 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,6 +151,11 @@ export async function issueAccessClaim(options: { } } + 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; } @@ -229,3 +241,38 @@ export function signAssertedStepUpClaim(options: { }; 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 d7a521c..78a3a60 100644 --- a/src/contracts.ts +++ b/src/contracts.ts @@ -162,6 +162,10 @@ export interface AccessClaimPayload { * 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/store/identity-move.ts b/src/store/identity-move.ts new file mode 100644 index 0000000..7b80d43 --- /dev/null +++ b/src/store/identity-move.ts @@ -0,0 +1,88 @@ +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 b35decb..f12661d 100644 --- a/src/store/in-memory.ts +++ b/src/store/in-memory.ts @@ -26,9 +26,13 @@ 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; @@ -63,6 +67,7 @@ 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; @@ -202,6 +207,78 @@ export class InMemoryStore implements HeimdallStore { 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 0b05f61..f0da059 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -1,6 +1,7 @@ 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,6 +20,9 @@ import { type CreatePrivateCommandReceiptInput, type HeimdallStore, IdentityHeldElsewhereError, + type MoveIdentitiesInput, + type MoveResult, + type StoredIdentityMove, OAUTH_STATE_PRUNE_BATCH, oauthStatePruneCutoffMs, type StoredAccount, @@ -175,6 +179,42 @@ 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, @@ -457,6 +497,9 @@ export function samePredicate(declared: string, actual: string, keyColumns: stri * 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. * audit_events is written and never read back. */ export const STORE_TABLE_PRIVILEGES: Readonly> = { @@ -471,6 +514,7 @@ export const STORE_TABLE_PRIVILEGES: Readonly { + 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); + } + async updateLinkedIdentityCredential( id: string, decide: (locked: StoredLinkedIdentity) => Promise, diff --git a/src/store/schema.ts b/src/store/schema.ts index 3678122..ff1fcf2 100644 --- a/src/store/schema.ts +++ b/src/store/schema.ts @@ -216,6 +216,29 @@ 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 c044161..78d12a4 100644 --- a/src/store/types.ts +++ b/src/store/types.ts @@ -59,6 +59,60 @@ export type UnlinkResult = | { 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; @@ -339,6 +393,17 @@ export interface HeimdallStore { * `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 caaa8e6..279b21e 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -40,3 +40,4 @@ {"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/identity-moves.test.ts b/tests/identity-moves.test.ts new file mode 100644 index 0000000..bc41597 --- /dev/null +++ b/tests/identity-moves.test.ts @@ -0,0 +1,632 @@ +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/store.test.ts b/tests/store.test.ts index 0e4dcac..03b869a 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -249,6 +249,10 @@ describe.each(unlinkStores)("linked_identities writes, %s", (_name, make) => { 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" })); @@ -477,9 +481,10 @@ describe("PostgresStore.checkSchema", () => { "capability_grants", "entitlement_snapshots", "consent_receipts", + "identity_moves", "audit_events", ]); - expect(REQUIRED_COLUMNS).toHaveLength(113); + expect(REQUIRED_COLUMNS).toHaveLength(121); expect(REQUIRED_COLUMNS).toEqual( expect.arrayContaining([ { table: "auth_completions", column: "code", type: "TEXT", nullable: false }, @@ -490,7 +495,7 @@ describe("PostgresStore.checkSchema", () => { { table: "auth_completions", column: "attempt_id", type: "TEXT", nullable: true }, ]) ); - expect(REQUIRED_KEYS).toHaveLength(17); + expect(REQUIRED_KEYS).toHaveLength(19); expect(REQUIRED_KEYS).toEqual( expect.arrayContaining([ { table: "linked_identities", columns: "provider,provider_user_id", predicate: "" }, @@ -498,6 +503,7 @@ 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" }, ]) @@ -648,9 +654,178 @@ 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 @@ -803,6 +978,103 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD 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); @@ -920,6 +1192,7 @@ 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()); From 2f0dd0c3a774e374a261d7cf88a8d05fb1d157e6 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Tue, 17 Nov 2026 00:00:45 +0000 Subject: [PATCH 47/63] Recipe: declare every name loadConfig reads, and the state slot where the code writes it The recipe left eight names undeclared (GitHub and Spotify client ids, the StreamPixels and Repixelizer callback lists and runtime ids, the Bifrost runtime ids, the refresh TTL), so a binding could never set them: Idunn refuses an undeclared name. The state slot said heimdall.service.cc at the state root while the code writes cultcache/heimdall.service.cc. A new test reads the names loadConfig looks up (the existing recorder) and fails on any that is neither declared, Idunn-owned, nor listed as never bound with its reason. Co-Authored-By: Claude Sonnet 5.5 --- deployment/idunn/recipe.toml | 10 +++++++++- tests/recipe-secrets.test.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/deployment/idunn/recipe.toml b/deployment/idunn/recipe.toml index 48c3577..8179280 100644 --- a/deployment/idunn/recipe.toml +++ b/deployment/idunn/recipe.toml @@ -138,11 +138,16 @@ 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", @@ -156,6 +161,7 @@ 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", @@ -163,11 +169,13 @@ 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", @@ -192,7 +200,7 @@ schema_generation = "heimdall-v1" [[state.slots]] id = "service" -relative_path = "heimdall.service.cc" +relative_path = "cultcache/heimdall.service.cc" kind = "cultcache-file" schema = "heimdall.service_state.v1" writer = "process-bound-single-writer" diff --git a/tests/recipe-secrets.test.ts b/tests/recipe-secrets.test.ts index ea144c5..76f1b7b 100644 --- a/tests/recipe-secrets.test.ts +++ b/tests/recipe-secrets.test.ts @@ -225,4 +225,30 @@ 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 idunnOwned = new Set([ + "GAMECULT_IDUNN_RUNTIME_BUNDLE", + "GAMECULT_IDUNN_CANDIDATE_BIND", + "GAMECULT_IDUNN_PROCESS_WRITE_LEASE", + ]); + 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) && !idunnOwned.has(name) && !neverBound.has(name)); + expect(unreachable).toEqual([]); + }); }); From 4a0fb44b5b82cffeb2113bc17e8efacf8c8907b6 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Tue, 17 Nov 2026 00:10:44 +0000 Subject: [PATCH 48/63] Recipe test: drop the exemption that exempted nothing, fail on a stale never-bound entry Soul's pass on PR #17 showed idunnOwned names are already declared, so the set could only hide a later gap; and a never-bound name nothing reads went unnoticed. Co-Authored-By: Claude Sonnet 5.5 --- tests/recipe-secrets.test.ts | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/tests/recipe-secrets.test.ts b/tests/recipe-secrets.test.ts index 76f1b7b..b6be578 100644 --- a/tests/recipe-secrets.test.ts +++ b/tests/recipe-secrets.test.ts @@ -229,11 +229,6 @@ describe("Idunn recipe secret declarations", () => { 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 idunnOwned = new Set([ - "GAMECULT_IDUNN_RUNTIME_BUNDLE", - "GAMECULT_IDUNN_CANDIDATE_BIND", - "GAMECULT_IDUNN_PROCESS_WRITE_LEASE", - ]); const neverBound = new Set([ // The listen socket is the candidate bind under Idunn, and the command port follows it. "HOST", @@ -248,7 +243,9 @@ describe("Idunn recipe secret declarations", () => { const declared = new Set(everyDeclaredName); const unreachable = [...explored.names] .filter((name) => !secretNames.includes(name) && !name.endsWith("_FILE")) - .filter((name) => !declared.has(name) && !idunnOwned.has(name) && !neverBound.has(name)); + .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([]); }); }); From 2bcb2ca4e7fb640e07deae42302b0919a62e5bc4 Mon Sep 17 00:00:00 2001 From: Eureka Date: Sun, 29 Nov 2026 20:04:06 +0000 Subject: [PATCH 49/63] A first Google sign-in mints an account only under an app's invite grant (#18) --- docs/service-contract.md | 28 ++++++-- src/app-profiles.ts | 9 +++ src/app.ts | 39 ++++++++++- src/contracts.ts | 8 +++ tests/google-link.test.ts | 140 +++++++++++++++++++++++++++++++++++++- 5 files changed, 213 insertions(+), 11 deletions(-) diff --git a/docs/service-contract.md b/docs/service-contract.md index 6b77caa..2412fbb 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -236,10 +236,11 @@ Launch note: implemented yet - Repixelizer launch can configure Discord and Patreon on its provider buttons -### Google (OpenID Connect, link-only) +### Google (OpenID Connect, link-only; mints only under an invite grant) -`google` is an identity provider that never mints an account. It is a second -door into a person who already has one. +`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). - Callback redirect URI (register exactly this in the Google Cloud OAuth client): `{GC_ACCESS_BASE_URL}/v1/oauth/google/callback`, which is @@ -256,10 +257,23 @@ door into a person who already has one. - `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`, 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`. +- 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. - 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 diff --git a/src/app-profiles.ts b/src/app-profiles.ts index a77f76a..b388ce2 100644 --- a/src/app-profiles.ts +++ b/src/app-profiles.ts @@ -56,6 +56,14 @@ 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 @@ -170,6 +178,7 @@ 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"] }, diff --git a/src/app.ts b/src/app.ts index b3c7755..5e327cf 100644 --- a/src/app.ts +++ b/src/app.ts @@ -103,6 +103,7 @@ 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(); @@ -126,6 +127,7 @@ 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); @@ -190,7 +192,8 @@ 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.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")) ) { return null; } @@ -211,6 +214,9 @@ 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; } @@ -823,10 +829,21 @@ export async function startOAuthFlow( if (options?.trustedBrowserAttemptId && handoff.kind === "browser_completion") { handoff = { kind: "browser_completion", attemptId: options.trustedBrowserAttemptId }; } - if ((entitlementPolicy || profile.startRequiresAppCaller || (input.mode === "connect" && input.connection !== undefined)) && (!isAppCaller(caller) || caller.appSlug !== profile.slug)) { + if ((entitlementPolicy || profile.startRequiresAppCaller || input.firstLoginGrant !== undefined || (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 { @@ -865,6 +882,7 @@ export async function startOAuthFlow( entitlementPolicy, requestedScopes: input.requestedScopes, stepUp: input.stepUp, + firstLoginGrant: input.firstLoginGrant, keys, }); return { @@ -1509,6 +1527,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { @@ -2142,6 +2166,15 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { 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); + }); +}); From 22a7f41454d5cf10d37227ecd33f7a45fe94e5b5 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 23:10:26 +0100 Subject: [PATCH 50/63] Cut spec for ghostlight Google sign-in, pending admission to Weksa's mind Weksa's ghostlight-verse campaign does not list GameCult/Heimdall, so Huginn refused the spec (RepoNotInCampaign). It is kept here until Self adds the repo and admits it as ghostlight-verse:cut_spec:cut-heimdall-ghostlight-google.r1; Hands deletes this file in the cut. Co-Authored-By: Claude Opus 5.5 --- notes/ghostlight-google-sign-in-cut-spec.json | 241 ++++++++++++++++++ 1 file changed, 241 insertions(+) create mode 100644 notes/ghostlight-google-sign-in-cut-spec.json diff --git a/notes/ghostlight-google-sign-in-cut-spec.json b/notes/ghostlight-google-sign-in-cut-spec.json new file mode 100644 index 0000000..521858e --- /dev/null +++ b/notes/ghostlight-google-sign-in-cut-spec.json @@ -0,0 +1,241 @@ +{ + "kind": "cut_spec", + "value": { + "campaign": "ghostlight-verse", + "cut": "heimdall-ghostlight-google", + "revision": 1, + "title": "Heimdall: ghostlight admits Google, honours the Dungeon's invite grant, and stops gating on the Discord role", + "repo": "GameCult/Heimdall", + "branch": "ghostlight/google-sign-in", + "base": "2bcb2ca4e7fb640e07deae42302b0919a62e5bc4", + "depends_on": [], + "first": [ + "Work in the existing worktree F:\\Projects\\Heimdall-wt-ghostlight-google on branch ghostlight/google-sign-in (from origin/main 2bcb2ca). Read AGENTS.md; follow its state/evidence conventions for the closing evidence line.", + "Read docs/service-contract.md 'Invite grant' (about line 264) and src/app.ts startOAuthFlow gates (about lines 832-846): the grant mechanism already exists for bifrost. This cut extends it to ghostlight and threads it through the private command plane; it adds no invite records to Heimdall.", + "Delete first: AppProfile.requiredEntitlementPolicyKind (app-profiles.ts:41-47, set only by ghostlight at :203) and requireEntitlementPolicyIfProfileDemandsIt (private-command-plane.ts:385-407) with its two call sites (:236 refresh, :272 begin). A caller-sent policy stays accepted and optional as for every other app.", + "Heimdall ruling heimdall-body:ruling:bifrost-google-invitation-link-only forbids attaching Google to an existing account by an invitation path. This cut does not: the grant only mints a new account for a sub no account holds and never attaches (contract text at :264-274). Do not widen that.", + "Open the Heimdall PR on Forgejo only when Self says so; the brief for this mapping pass forbids it, Hands' own brief decides." + ], + "deletes": [ + { + "path": "src/app-profiles.ts", + "lines": 8, + "note": "requiredEntitlementPolicyKind field and its doc comment; ghostlight's requiredEntitlementPolicyKind line" + }, + { + "path": "src/private-command-plane.ts", + "lines": 22, + "note": "requireEntitlementPolicyIfProfileDemandsIt and its two awaits" + }, + { + "path": "tests", + "lines": 30, + "note": "tests that pin 'ghostlight authentication/refresh requires its caller-owned discord_role_access policy' are deleted or inverted (a ghostlight begin without policy now starts)" + } + ], + "keeps_moves": [ + "The grant gates in startOAuthFlow (app caller of this slug, sign_in only, mayGrantFirstLogin) and the callback mint under first_login_grant are unchanged.", + "Bifrost's profile, its grant and its Google link flow are unchanged.", + "The private-plane attempt handle (trustedBrowserAttemptId, never body-supplied) is the ghostlight browser binding and is unchanged.", + "Discord stays a ghostlight identity provider; a Discord policy a caller still sends is evaluated by nobody for ghostlight (entitlementSources empty) and is harmless." + ], + "adds": [ + "ghostlight profile: identityProviders ['discord','google']; entitlementSources []; startRequiresAppCaller: true; mayGrantFirstLogin: true; profileVersion '2026-12-02'.", + "ghostlight app_access: anyOf [identityFacts.authenticated] (as streampixels viewer_access at :147), summary 'Heimdall authenticated this identity for Ghostlight; who may play is the Dungeon's account catalog'. campaign_play summary/localRequirement: 'Ghostlight combines a Heimdall sign-in with its own account catalog and campaign ownership'.", + "beginAuth reads payload.firstLoginGrant: absent/null -> none; exactly 'invite' -> passed to startOAuthFlow input.firstLoginGrant; any other value -> throw 'Auth begin payload is incomplete.' (same refusal shape as a bad provider). startOAuthFlow's existing gate then decides." + ], + "file_changes": [ + { + "location": { + "path": "src/app-profiles.ts", + "line": 195, + "end_line": 218, + "symbol": "ghostlightProfile" + }, + "change": "As in adds: providers, entitlementSources [], startRequiresAppCaller, mayGrantFirstLogin, app_access on identity.authenticated, summaries, profileVersion. Import identityFacts is already present." + }, + { + "location": { + "path": "src/private-command-plane.ts", + "line": 260, + "end_line": null, + "symbol": "beginAuth" + }, + "change": "Thread firstLoginGrant into the startOAuthFlow input; drop the policy-demand await." + }, + { + "location": { + "path": "src/private-command-plane.ts", + "line": 221, + "end_line": null, + "symbol": "refreshAuth" + }, + "change": "Drop the policy-demand await; policy remains optional and passed through when present." + }, + { + "location": { + "path": "schemas/heimdall.auth_begin_command.v1.schema.json", + "line": 1, + "end_line": null + }, + "change": "provider enum gains google; entitlementPolicy leaves required; add firstLoginGrant {enum:['invite']}." + }, + { + "location": { + "path": "schemas/heimdall.auth_refresh_command.v1.schema.json", + "line": 1, + "end_line": null + }, + "change": "entitlementPolicy optional if it is required there." + }, + { + "location": { + "path": "docs/service-contract.md", + "line": 190, + "end_line": null + }, + "change": "startRequiresAppCaller: 'Bifrost and Ghostlight'; mayGrantFirstLogin (about :264): 'bifrost and ghostlight'; Google (about :289): admitted to bifrost and ghostlight; private-plane begin accepts firstLoginGrant 'invite'." + }, + { + "location": { + "path": "docs/app-profiles/ghostlight.md", + "line": 1, + "end_line": null + }, + "change": "Providers Discord and Google; access rule: Heimdall authenticates, app_access is identity.authenticated, admission is the Dungeon's catalog and one-time invites (ruling dungeon-owns-accounts); a first Google sign-in mints a Heimdall account only under the Dungeon's grant; no Discord role policy; refresh re-evaluates nothing app-specific." + } + ], + "reads": [ + { + "location": { + "path": "src/app.ts", + "line": 832, + "end_line": null, + "symbol": "startOAuthFlow" + }, + "why": "the app-caller and grant gates the private plane now reaches with a grant" + }, + { + "location": { + "path": "src/app.ts", + "line": 2034, + "end_line": null + }, + "why": "callback: requires_link + first_login_grant mints and audits account_minted_by_grant" + }, + { + "location": { + "path": "tests/google-link.test.ts", + "line": 1, + "end_line": null + }, + "why": "the bifrost grant tests to mirror for ghostlight over the private plane" + }, + { + "location": { + "path": "tests/caller-identity-soul.test.ts", + "line": 23, + "end_line": null + }, + "why": "private-plane ghostlight fixtures (ghostlightSecret, runtime ids)" + } + ], + "authority_map": { + "owner": "The Dungeon's account catalog (catalog.cc) owns admission: an identity plays if an account holds it, or if it redeems a live one-time Dungeon invite, consumed in the write that creates the account. Heimdall owns authentication only: it proves which external identity signed in and names the Heimdall account (claim sub) that identity belongs to.", + "inputs": [ + "Dungeon: the invite the browser presents at begin, its catalog, the Heimdall-verified claim at complete", + "Heimdall: the app-authenticated begin (ghostlight secret over the private plane), the provider's OIDC/OAuth answer, the signed state" + ], + "outputs": [ + "Dungeon -> Heimdall: firstLoginGrant 'invite' on a begin whose browser presented an invite the catalog holds live", + "Heimdall -> Dungeon: a claim aud=ghostlight with app_access for every authenticated identity", + "Dungeon: an account row, the spent invite, an app session" + ], + "derived_state": [ + "Heimdall's first_login_grant is no longer an invite: it is derived from the Dungeon's live invite at begin and is notification-only (it lets Heimdall mint an auth account for a Google sub no account holds)", + "ghostlight app_access is no longer an admission gate: it is derived from identity.authenticated; the Dungeon's app_access checks become claim-shape checks that cannot refuse an authenticated sign-in", + "the invite bound to an attempt in AuthGuard is a copy of what the browser presented at begin, memory-only, living no longer than the begin cookie" + ], + "forbidden_writers": [ + "Heimdall's Discord role policy (requiredEntitlementPolicyKind, entitlementSources discord) no longer decides who enters the Dungeon", + "Heimdall holds no invite records for ghostlight and never decides who is invited", + "the complete body no longer carries an invite; only the begin-bound invite reaches catalog.sign_in", + "no public (secretless) ghostlight OAuth start: startRequiresAppCaller" + ], + "shared_paths": [ + "Google, Discord and any later provider begin through one auth_begin -> HeimdallClient::begin -> heimdall.auth.begin path; the grant decision is the same catalog read for every provider", + "every sign-in, first or returning, any provider, ends in one catalog.sign_in" + ], + "deletion_line": "Delete before adding: Heimdall's requiredEntitlementPolicyKind field and requireEntitlementPolicyIfProfileDemandsIt; the Dungeon's DiscordGate, its two env names and the policy on begin and refresh; the complete body's invite field." + }, + "verification": { + "builds": [ + "pnpm typecheck && pnpm test in the worktree (vendor/CultLib built as AGENTS.md says); report the pre-existing odin-publication failure separately if it still appears" + ], + "tests": [ + { + "name": "ghostlight google first sign-in under grant", + "pins": "private-plane begin {provider google, firstLoginGrant invite} -> 201 state with first_login_grant; callback with an unheld sub mints one account and audits account_minted_by_grant {provider google, appSlug ghostlight}; the completion's claim carries app_access" + }, + { + "name": "ghostlight google first sign-in without grant", + "pins": "same begin without firstLoginGrant -> callback refuses identity_not_linked and mints nothing" + }, + { + "name": "returning google identity", + "pins": "a sub an account already holds signs in with or without the grant to that same account; the grant attaches nothing" + }, + { + "name": "discord without policy", + "pins": "private-plane ghostlight discord begin with no entitlementPolicy starts (no throw); refresh without policy refreshes; claim carries app_access" + }, + { + "name": "public ghostlight start refused", + "pins": "POST /v1/oauth/google/start and /v1/oauth/discord/start for appSlug ghostlight without x-heimdall-app-secret -> 401 app_auth_required" + }, + { + "name": "bad grant value", + "pins": "private-plane begin with firstLoginGrant 'yes' is refused before any attempt row or state is minted" + }, + { + "name": "other apps unchanged", + "pins": "repixelizer/streampixels public starts unchanged; firstLoginGrant from repixelizer still 400 first_login_grant_refused" + } + ], + "negative": [ + { + "pattern": "requiredEntitlementPolicyKind|requireEntitlementPolicyIfProfileDemandsIt", + "scope": "src, tests, docs: zero hits" + }, + { + "pattern": "discord_role_access", + "scope": "src/app-profiles.ts: zero hits (the policy kind itself stays in contracts and the Discord evaluator)" + }, + { + "pattern": "invite", + "scope": "src/store/**: no new table, column or row for ghostlight invites" + } + ], + "operator": [ + "Deploy is cut ops-google-sign-in's runbook section, after this merges to Heimdall main; not part of this cut." + ] + }, + "estimate": { + "lines_added": 140, + "lines_removed": 70, + "dependencies_added": [], + "dependencies_removed": [], + "formats_added": [], + "formats_removed": [], + "targets_added": [], + "targets_removed": [] + }, + "rulings": [ + "ghostlight-verse:ruling:weksa-owns-dungeon-google-sign-in", + "ghostlight-verse:ruling:dungeon-owns-accounts" + ], + "questions": [ + "ghostlight-verse:question:heimdall-ghostlight-google-twitch-sign-in" + ] + } +} \ No newline at end of file From bd6e8d6d063920aed99a279b8ac4d219f5dde7e2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 23:17:29 +0100 Subject: [PATCH 51/63] Delete requiredEntitlementPolicyKind and the policy-demand guard on the private plane Heimdall no longer demands a caller-owned Discord role policy from ghostlight at begin or refresh; a caller-sent policy stays accepted and optional as for every other app. Co-Authored-By: Claude Sonnet 5.5 --- src/app-profiles.ts | 10 +--------- src/private-command-plane.ts | 22 ---------------------- 2 files changed, 1 insertion(+), 31 deletions(-) diff --git a/src/app-profiles.ts b/src/app-profiles.ts index b388ce2..52419b6 100644 --- a/src/app-profiles.ts +++ b/src/app-profiles.ts @@ -3,7 +3,7 @@ import { type CapabilityDefinition, type CapabilityMode, } from "./capability-rules.js"; -import { type AppSlug, type LinkedIdentityInput, type OAuthConnectionBinding, type OAuthEntitlementPolicy, type OAuthMode, type Provider } from "./contracts.js"; +import { type AppSlug, type LinkedIdentityInput, type OAuthConnectionBinding, type OAuthMode, type Provider } from "./contracts.js"; import { entitlementFacts, grantFacts, identityFacts } from "./facts.js"; export type { CapabilityDefinition, CapabilityMode }; @@ -38,13 +38,6 @@ export interface AppProfile { * primitive, not a convenience. Compared by URL origin, not prefix. */ allowedReturnOrigins: readonly string[]; - /** - * Some apps require the caller to supply an entitlement policy of a - * specific kind on every begin/refresh (ghostlight's caller-owned Discord - * role gate). Data instead of a per-slug branch in the private command - * plane; absent for apps with no such requirement. - */ - requiredEntitlementPolicyKind?: OAuthEntitlementPolicy["kind"]; /** * The app binds browser completion to its own pending attempt, and the * binding is the secrecy of the attempt nonce, which rides readable in the @@ -200,7 +193,6 @@ const ghostlightProfile: AppProfile = { entitlementSources: ["discord"], managedConnectionProviders: [], allowedReturnOrigins: ["https://yggdrasil.gamecult.org"], - requiredEntitlementPolicyKind: "discord_role_access", capabilities: [ { key: "app_access", diff --git a/src/private-command-plane.ts b/src/private-command-plane.ts index 8e9fb8d..3a9605d 100644 --- a/src/private-command-plane.ts +++ b/src/private-command-plane.ts @@ -9,7 +9,6 @@ import { import { type FastifyInstance } from "fastify"; import { errorIdentity, getHeimdallRuntimeContext, refreshAppSession, startOAuthFlow, verifyRefreshToken } from "./app.js"; import { callerFromOpenedEnvelope } from "./app-caller.js"; -import { getAppProfile } from "./app-profiles.js"; import { executeHeimdallAccessPlugin, HEIMDALL_ACCESS_PLUGIN_ID, type EvePluginAbiRequest } from "./access-plugin.js"; import { isAppSlug, oauthModes, providers, type AppSlug, type OAuthEntitlementPolicy, type OAuthMode, type Provider } from "./contracts.js"; import { type HeimdallConfig } from "./config.js"; @@ -233,7 +232,6 @@ async function refreshAuth( // handler function the HTTP route uses rather than forging the HTTP header // back at itself. const context = getHeimdallRuntimeContext(app); - await requireEntitlementPolicyIfProfileDemandsIt(appSlug, entitlementPolicy, "refresh"); const result = await refreshAppSession(context, appSlug, callerFromOpenedEnvelope(appSlug), { refreshToken, ...(entitlementPolicy ? { entitlementPolicy } : {}), @@ -269,7 +267,6 @@ async function beginAuth( if (!providers.includes(provider) || !oauthModes.includes(mode) || !returnTo) throw new Error("Auth begin payload is incomplete."); const entitlementPolicy = parseEntitlementPolicy(payload.entitlementPolicy); const store = getHeimdallRuntimeContext(app).store; - await requireEntitlementPolicyIfProfileDemandsIt(appSlug, entitlementPolicy, "authentication"); const now = new Date(); const attempt = await store.createAuthAttempt({ handle: randomUUID(), @@ -387,25 +384,6 @@ function parseEntitlementPolicy(value: unknown): OAuthEntitlementPolicy | undefi return undefined; } -/** - * Ghostlight requires its caller-owned Discord role policy on every begin and - * refresh; that used to be a literal `appSlug === "ghostlight"` branch here. - * The requirement is now data on the app's profile - * (AppProfile.requiredEntitlementPolicyKind), so a future app with the same - * need declares it in its profile instead of adding another branch. - */ -async function requireEntitlementPolicyIfProfileDemandsIt( - appSlug: AppSlug, - entitlementPolicy: OAuthEntitlementPolicy | undefined, - action: "authentication" | "refresh", -): Promise { - const profile = getAppProfile(appSlug); - const requiredKind = profile?.requiredEntitlementPolicyKind; - if (requiredKind && entitlementPolicy?.kind !== requiredKind) { - throw new Error(`${appSlug} ${action} requires its caller-owned ${requiredKind} policy.`); - } -} - function response( request: CultNetOperationRequestMessage, status: string, From a4532789e62ab59c9a98c098f81cab186ae7bfe2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 23:23:41 +0100 Subject: [PATCH 52/63] ghostlight admits Google and honours the Dungeon's invite grant; public starts are refused Profile: providers discord+google, no entitlement sources, startRequiresAppCaller, mayGrantFirstLogin, app_access on identity.authenticated. Private-plane begin threads firstLoginGrant 'invite' into startOAuthFlow and refuses any other value before an attempt exists. Schemas: google provider, optional policy and grant. Tests: public ghostlight starts 401, first Google login refused without a grant and minted under one, returning identity attaches nothing, discord without policy. Attempt-handle soul tests now send the app secret; the stranger case asserts 401. The refresh-diagnostics tests used ghostlight as a Discord-policy vehicle and now use bifrost, which still evaluates Discord. Co-Authored-By: Claude Sonnet 5.5 --- ...heimdall.auth_begin_command.v1.schema.json | 5 +- ...imdall.auth_refresh_command.v1.schema.json | 2 +- src/app-profiles.ts | 16 +- src/private-command-plane.ts | 4 + tests/app.test.ts | 6 +- tests/caller-identity-attack-soul-r21.test.ts | 19 +- tests/caller-identity-attack-soul.test.ts | 4 +- tests/google-link.test.ts | 189 +++++++++++++++++- tests/private-command-diagnostics.test.ts | 16 +- 9 files changed, 228 insertions(+), 33 deletions(-) diff --git a/schemas/heimdall.auth_begin_command.v1.schema.json b/schemas/heimdall.auth_begin_command.v1.schema.json index ca22ccf..3ba1879 100644 --- a/schemas/heimdall.auth_begin_command.v1.schema.json +++ b/schemas/heimdall.auth_begin_command.v1.schema.json @@ -2,11 +2,12 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "heimdall.auth_begin_command.v1", "type": "object", - "required": ["provider", "mode", "returnTo", "entitlementPolicy"], + "required": ["provider", "mode", "returnTo"], "properties": { - "provider": { "enum": ["discord", "patreon", "github", "twitch", "youtube", "spotify", "joystick"] }, + "provider": { "enum": ["discord", "patreon", "github", "twitch", "youtube", "spotify", "joystick", "google"] }, "mode": { "enum": ["sign_in", "link", "connect"] }, "returnTo": { "type": "string", "format": "uri" }, + "firstLoginGrant": { "enum": ["invite"] }, "entitlementPolicy": { "oneOf": [ { diff --git a/schemas/heimdall.auth_refresh_command.v1.schema.json b/schemas/heimdall.auth_refresh_command.v1.schema.json index 4bc4659..4c86557 100644 --- a/schemas/heimdall.auth_refresh_command.v1.schema.json +++ b/schemas/heimdall.auth_refresh_command.v1.schema.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "heimdall.auth_refresh_command.v1", "type": "object", - "required": ["schema", "refreshToken", "entitlementPolicy"], + "required": ["schema", "refreshToken"], "properties": { "schema": { "const": "heimdall.auth_refresh_command.v1" }, "refreshToken": { "type": "string", "minLength": 1 }, diff --git a/src/app-profiles.ts b/src/app-profiles.ts index 52419b6..34400cc 100644 --- a/src/app-profiles.ts +++ b/src/app-profiles.ts @@ -188,23 +188,25 @@ const bifrostProfile: AppProfile = { const ghostlightProfile: AppProfile = { slug: "ghostlight", displayName: "Ghostlight Dungeon", - profileVersion: "2026-08-22", - identityProviders: ["discord"], - entitlementSources: ["discord"], + profileVersion: "2026-12-02", + identityProviders: ["discord", "google"], + entitlementSources: [], managedConnectionProviders: [], allowedReturnOrigins: ["https://yggdrasil.gamecult.org"], + startRequiresAppCaller: true, + mayGrantFirstLogin: true, capabilities: [ { key: "app_access", mode: "shared", - summary: "May enter Ghostlight Dungeon after Heimdall verifies the app-supplied GameCult Discord role policy.", - anyOf: gameCultMembership, + summary: "Heimdall authenticated this identity for Ghostlight; who may play is the Dungeon's account catalog.", + anyOf: [identityFacts.authenticated], }, { key: "campaign_play", mode: "hybrid", - summary: "May play campaigns owned by the authenticated Ghostlight account.", - localRequirement: "Ghostlight must combine app_access with local campaign ownership.", + summary: "Ghostlight combines a Heimdall sign-in with its own account catalog and campaign ownership.", + localRequirement: "Ghostlight combines a Heimdall sign-in with its own account catalog and campaign ownership.", }, ], }; diff --git a/src/private-command-plane.ts b/src/private-command-plane.ts index 3a9605d..fe569d1 100644 --- a/src/private-command-plane.ts +++ b/src/private-command-plane.ts @@ -266,6 +266,9 @@ async function beginAuth( const returnTo = String(payload.returnTo ?? ""); if (!providers.includes(provider) || !oauthModes.includes(mode) || !returnTo) throw new Error("Auth begin payload is incomplete."); const entitlementPolicy = parseEntitlementPolicy(payload.entitlementPolicy); + // The app's word that it invited this person (the Dungeon holds the invite). Only the literal "invite" is a grant; startOAuthFlow's gate decides whether this app and mode may carry one. + const grant = payload.firstLoginGrant; + if (grant !== undefined && grant !== null && grant !== "invite") throw new Error("Auth begin payload is incomplete."); const store = getHeimdallRuntimeContext(app).store; const now = new Date(); const attempt = await store.createAuthAttempt({ @@ -289,6 +292,7 @@ async function beginAuth( returnTo, handoff: { kind: "browser_completion" }, ...(entitlementPolicy ? { entitlementPolicy } : {}), + ...(grant === "invite" ? { firstLoginGrant: "invite" as const } : {}), }, { trustedBrowserAttemptId: attempt.handle } ); diff --git a/tests/app.test.ts b/tests/app.test.ts index 20a0191..eac76f9 100644 --- a/tests/app.test.ts +++ b/tests/app.test.ts @@ -318,10 +318,10 @@ describe("Heimdall service", () => { } }); - it("flags only Bifrost's profile", () => { + it("flags only Bifrost's and Ghostlight's profiles", () => { expect( - Object.values(builtInAppProfiles).filter((profile) => profile.startRequiresAppCaller).map((profile) => profile.slug) - ).toEqual(["bifrost"]); + Object.values(builtInAppProfiles).filter((profile) => profile.startRequiresAppCaller).map((profile) => profile.slug).sort() + ).toEqual(["bifrost", "ghostlight"]); }); }); diff --git a/tests/caller-identity-attack-soul-r21.test.ts b/tests/caller-identity-attack-soul-r21.test.ts index 1264a86..ce7d254 100644 --- a/tests/caller-identity-attack-soul-r21.test.ts +++ b/tests/caller-identity-attack-soul-r21.test.ts @@ -197,6 +197,8 @@ async function seedAccountAndSession(store: HeimdallStore, appSlug: AppSlug) { describe("R21.1: the attempt handle is unreachable from the public start route", () => { const legitReturn = "https://yggdrasil.gamecult.org/ghostlight/"; + // Ghostlight's starts are the app's own (startRequiresAppCaller); what the body may not do is name an attempt handle, even for the app. + const ghostlightApp = { "x-heimdall-app-secret": ghostlightSecret }; it("a well-formed browser_completion attemptId is dropped before the state token is signed", async () => { const { app, store } = await harness(); @@ -213,7 +215,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route", mode: "sign_in", returnTo: legitReturn, handoff: { kind: "browser_completion", attemptId: attempt.handle }, - }); + }, ghostlightApp); expect(response.statusCode, response.body).toBe(201); expect(response.json().handoff).toEqual({ kind: "browser_completion" }); const state = jwtPayload(stateOf(response.json())); @@ -236,7 +238,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route", ["empty string", { kind: "browser_completion", attemptId: "" }], ])("a %s attemptId never reaches the state token", async (_label, handoff) => { const { app } = await harness(); - const response = await start(app, { appSlug: "ghostlight", mode: "sign_in", returnTo: legitReturn, handoff }); + const response = await start(app, { appSlug: "ghostlight", mode: "sign_in", returnTo: legitReturn, handoff }, ghostlightApp); expect(response.body).not.toContain(planted); if (response.statusCode === 201) { expect(response.json().handoff).toEqual({ kind: "browser_completion" }); @@ -249,7 +251,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route", it("a top-level attemptId / trustedBrowserAttemptId / options field on the body is stripped, never bound", async () => { const { app } = await harness(); for (const extra of [{ attemptId: planted }, { trustedBrowserAttemptId: planted }, { options: { trustedBrowserAttemptId: planted } }]) { - const response = await start(app, { appSlug: "ghostlight", mode: "sign_in", returnTo: legitReturn, ...extra }); + const response = await start(app, { appSlug: "ghostlight", mode: "sign_in", returnTo: legitReturn, ...extra }, ghostlightApp); expect(response.statusCode, response.body).toBe(201); expect(response.body).not.toContain(planted); expect(jwtPayload(stateOf(response.json())).handoff).toEqual({ kind: "browser_completion" }); @@ -300,17 +302,16 @@ describe("R21.1: the attempt handle is unreachable from the public start route", const handle = String(receipt.handle); const victimState = new URL((receipt.navigation as { url: string }).url).searchParams.get("state") ?? ""; - // Attacker names the victim's handle on the public start route, then - // completes as themselves before the victim does. + // Attacker names the victim's handle on the public start route: Ghostlight's + // start is refused outright without the app's secret, so no state exists to complete. const attackerStart = await start(app, { appSlug: "ghostlight", mode: "sign_in", returnTo: legitReturn, handoff: { kind: "browser_completion", attemptId: handle }, }); - expect(attackerStart.statusCode).toBe(201); - const attackerCallback = await completeAs(app, stateOf(attackerStart.json()), "attacker"); - expect(attackerCallback.statusCode, attackerCallback.body).toBe(201); + expect([attackerStart.statusCode, attackerStart.json().error]).toEqual([401, "app_auth_required"]); + expect(attackerStart.json().authorizationUrl).toBeUndefined(); expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("pending"); // Victim completes; the handle's single unconsumed slot is still free. @@ -339,7 +340,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route", mode: "sign_in", returnTo: legitReturn, handoff: { kind: "backend_callback", attemptId: attempt.handle, callbackUrl: "http://127.0.0.1:1/never" }, - }); + }, ghostlightApp); expect(response.statusCode, response.body).toBe(201); // Delivery to port 1 fails; whatever the callback returns, the attempt // must be untouched and no completion may be bound to it. diff --git a/tests/caller-identity-attack-soul.test.ts b/tests/caller-identity-attack-soul.test.ts index d9b4167..3ac3960 100644 --- a/tests/caller-identity-attack-soul.test.ts +++ b/tests/caller-identity-attack-soul.test.ts @@ -261,14 +261,14 @@ describe("attempt-handle binding: the public start route may attach a completion expiresAt: new Date(Date.now() + 600_000).toISOString(), }); + // Ghostlight's start is the app's own: without its secret there is no state to complete with. const attackerStart = await start(app, { appSlug: "ghostlight", mode: "sign_in", returnTo: "https://yggdrasil.gamecult.org/ghostlight/", handoff: { kind: "browser_completion", attemptId: attempt.handle }, }); - expect(attackerStart.statusCode).toBe(201); - await completeAs(app, stateOf(attackerStart.json()), "attacker"); + expect([attackerStart.statusCode, attackerStart.json().error]).toEqual([401, "app_auth_required"]); const after = await store.findAuthAttempt("ghostlight", attempt.handle); expect(after?.status).toBe("pending"); diff --git a/tests/google-link.test.ts b/tests/google-link.test.ts index 630d4a1..a196b59 100644 --- a/tests/google-link.test.ts +++ b/tests/google-link.test.ts @@ -1,18 +1,25 @@ import { createHash, createSign, generateKeyPairSync } from "node:crypto"; import { afterEach, describe, expect, it, vi } from "vitest"; import { type FastifyInstance } from "fastify"; +import { decode, encode } from "@msgpack/msgpack"; +import { invokeCultNetOperation } from "cultnet-ts"; 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 { startHeimdallPrivateCommandPlane } from "../src/private-command-plane.js"; +import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "../src/private-command-security.js"; +import { decodeJwt } from "../src/signing.js"; import { IdentityHeldElsewhereError, InMemoryStore } from "../src/store/index.js"; import { launchFlow, launchWithRedirect, stateOf, type LaunchedFlow } from "./oauth-flow.js"; const CLIENT_ID = "google-client"; +const GHOSTLIGHT_SECRET = "ghostlight-private-command-secret"; const REDIRECT = "https://heimdall.gamecult.org/v1/oauth/google/callback"; const rsa = generateKeyPairSync("rsa", { modulusLength: 2048 }); const originalFetch = globalThis.fetch; const apps: FastifyInstance[] = []; +const planes: Array<{ close(): Promise }> = []; function config(): HeimdallConfig { const base = loadConfig({ @@ -25,7 +32,10 @@ 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" }, + privateCommandHost: "127.0.0.1", + privateCommandPort: 0, + appSharedSecrets: { ...base.appSharedSecrets, bifrost: "bifrost-secret", repixelizer: "repixelizer-secret", ghostlight: GHOSTLIGHT_SECRET }, + appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] }, providers: { ...base.providers, google: { clientId: CLIENT_ID, clientSecret: "google-secret" }, @@ -185,6 +195,7 @@ async function linkGoogle(app: FastifyInstance, token: string, claims?: Record { globalThis.fetch = originalFetch; resetGoogleJwksCache(); + while (planes.length) await planes.pop()?.close(); while (apps.length) await apps.pop()?.close(); }); @@ -673,3 +684,179 @@ describe("an invite grant lets Bifrost's sign-in start mint the first Google acc expect(accountCount(store)).toBe(0); }); }); + +describe("ghostlight admits Google over the private command plane, and the Dungeon's invite is the only grant", () => { + const RETURN = "https://yggdrasil.gamecult.org/ghostlight/"; + let seq = 0; + + async function buildGhostlight() { + const store = new InMemoryStore(); + const cfg = config(); + const app = await buildApp({ config: cfg, store, oauthRuntimes: { discord: discordRuntime("discord-1", "Person") } }); + apps.push(app); + const plane = await startHeimdallPrivateCommandPlane(app, cfg); + planes.push(plane); + return { app, store, plane }; + } + + /** One sealed command to the plane as Ghostlight's own runtime; the opened receipt, or the transport status when refused. */ + async function command(plane: { endpoint: string }, operation: string, contentSchema: string, payload: Record) { + const id = `gl-${++seq}`; + const envelope = sealPrivateEnvelope({ appSlug: "ghostlight", operation, contentSchema, idempotencyKey: id, secret: GHOSTLIGHT_SECRET, payload }); + const response = await invokeCultNetOperation( + plane.endpoint, + { + schemaVersion: "cultnet.operation_request.v0" as const, + messageId: id, + serviceId: "heimdall.private.commands", + operation, + payloadSchema: "heimdall.private_command_envelope.v1", + payloadEncoding: "messagepack-base64" as const, + payload: Buffer.from(encode(envelope)).toString("base64"), + sourceRuntimeId: "yggdrasil-ghostlight", + }, + { runtimeId: "yggdrasil-ghostlight" } + ); + if (response.status !== "accepted") return { status: response.status, receipt: undefined }; + const wire = decode(Buffer.from(response.payload, "base64")) as HeimdallPrivateEnvelope; + return { status: response.status, receipt: openPrivateEnvelope(wire, GHOSTLIGHT_SECRET) as Record }; + } + + const begin = (plane: { endpoint: string }, payload: Record) => + command(plane, "heimdall.auth.begin", "heimdall.auth_begin_command.v1", { mode: "sign_in", returnTo: RETURN, ...payload }); + const complete = (plane: { endpoint: string }, handle: unknown) => + command(plane, "heimdall.auth.complete", "heimdall.auth_complete_command.v1", { handle }); + + /** Begin google as Ghostlight, walk the browser to Google and back, and return the callback answer plus the attempt handle. */ + async function googleSignIn(app: FastifyInstance, plane: { endpoint: string }, payload: Record, claims?: Record) { + const started = await begin(plane, { provider: "google", ...payload }); + expect(started.status).toBe("accepted"); + const receipt = started.receipt as { handle: string; navigation: { url: string } }; + const flow = await launchWithRedirect(app, { authorizationUrl: receipt.navigation.url }); + fakeGoogle({ nonceFrom: () => flow.url.searchParams.get("nonce") ?? undefined, ...(claims ? { claims } : {}) }); + return { handle: receipt.handle, done: await callbackGoogle(app, flow) }; + } + + const auditEvents = (store: InMemoryStore) => + [...(store as unknown as { auditEvents: Map }).auditEvents.values()]; + const attemptCount = (store: InMemoryStore) => (store as unknown as { authAttempts: Map }).authAttempts.size; + const capabilitiesOf = (receipt: Record | undefined) => + decodeJwt(String(receipt?.accessToken)).payload.capabilities as string[]; + + it("a first Google sign-in under the Dungeon's invite grant mints one account, audits it, and the claim carries app_access", async () => { + const { app, store, plane } = await buildGhostlight(); + const { handle, done } = await googleSignIn(app, plane, { firstLoginGrant: "invite" }); + expect(done.statusCode, done.body).toBe(201); + expect(accountCount(store)).toBe(1); + const minted = auditEvents(store).filter((e) => e.eventType === "account_minted_by_grant"); + expect(minted.map((e) => e.eventPayloadJson)).toEqual([{ provider: "google", appSlug: "ghostlight" }]); + const completion = (await complete(plane, handle)).receipt; + expect(completion).toMatchObject({ status: "authenticated", handle }); + expect(capabilitiesOf(completion)).toContain("app_access"); + }); + + it("a first Google sign-in with no live grant is refused identity_not_linked and mints nothing", async () => { + const { app, store, plane } = await buildGhostlight(); + for (const extra of [{}, { firstLoginGrant: null }]) { + const { handle, done } = await googleSignIn(app, plane, extra); + expect([done.statusCode, done.json().error]).toEqual([403, "identity_not_linked"]); + expect(auditEvents(store).some((e) => e.eventType === "account_minted_by_grant")).toBe(false); + expect((await complete(plane, handle)).receipt?.status).toBe("denied"); + } + expect(accountCount(store)).toBe(0); + }); + + it("a returning Google identity signs in to its own account with or without the grant, and the grant attaches nothing", async () => { + const { app, store, plane } = await buildGhostlight(); + const first = await googleSignIn(app, plane, { firstLoginGrant: "invite" }); + const accountId = first.done.json().account.id; + for (const extra of [{}, { firstLoginGrant: "invite" }]) { + const again = await googleSignIn(app, plane, extra); + expect(again.done.statusCode, again.done.body).toBe(201); + expect(again.done.json().account.id).toBe(accountId); + } + // A different Google subject under the grant is its own new account; the held one is never moved. + const other = await googleSignIn(app, plane, { firstLoginGrant: "invite" }, { sub: "g-sub-2" }); + expect(other.done.json().account.id).not.toBe(accountId); + expect((await store.findStoredLinkedIdentity("google", "g-sub-1"))?.accountId).toBe(accountId); + expect(accountCount(store)).toBe(2); + expect(auditEvents(store).filter((e) => e.eventType === "account_minted_by_grant")).toHaveLength(2); + }); + + it("discord begins and refreshes with no entitlement policy, and the claim carries app_access", async () => { + const { app, plane } = await buildGhostlight(); + const started = await begin(plane, { provider: "discord" }); + expect(started.status).toBe("accepted"); + const receipt = started.receipt as { handle: string; navigation: { url: string } }; + const flow = await launchFlow(app, { authorizationUrl: receipt.navigation.url }); + const callback = await app.inject({ + method: "GET", + url: `/v1/oauth/discord/callback?code=c&state=${encodeURIComponent(flow.state)}`, + headers: { cookie: flow.cookie }, + }); + expect(callback.statusCode, callback.body).toBe(201); + const completion = (await complete(plane, receipt.handle)).receipt; + expect(completion?.status).toBe("authenticated"); + expect(capabilitiesOf(completion)).toContain("app_access"); + const refreshed = await command(plane, "heimdall.auth.refresh", "heimdall.auth_refresh_command.v1", { refreshToken: completion?.refreshToken }); + expect(refreshed.receipt).toMatchObject({ schema: "heimdall.auth_refresh_receipt.v1", status: "authenticated" }); + expect(capabilitiesOf(refreshed.receipt)).toContain("app_access"); + }); + + it("a public ghostlight start, with no secret or the wrong one, is refused app_auth_required for every provider", async () => { + const { app, store } = await buildGhostlight(); + for (const provider of ["google", "discord"]) { + for (const headers of [{}, { "x-heimdall-app-secret": "wrong" }, { "x-heimdall-app-secret": "bifrost-secret" }]) { + const res = await app.inject({ + method: "POST", + url: `/v1/oauth/${provider}/start`, + headers, + payload: { appSlug: "ghostlight", mode: "sign_in", returnTo: RETURN }, + }); + expect([res.statusCode, res.json().error], `${provider} ${JSON.stringify(headers)}`).toEqual([401, "app_auth_required"]); + expect(res.json().authorizationUrl).toBeUndefined(); + } + } + // The same start with a grant is no easier without the app's secret. + const granted = await app.inject({ + method: "POST", + url: "/v1/oauth/google/start", + payload: { appSlug: "ghostlight", mode: "sign_in", returnTo: RETURN, firstLoginGrant: "invite" }, + }); + expect([granted.statusCode, granted.json().error]).toEqual([401, "app_auth_required"]); + expect(accountCount(store)).toBe(0); + expect(attemptCount(store)).toBe(0); + }); + + it("a begin whose firstLoginGrant is anything but 'invite' is refused before any attempt or state is minted", async () => { + const { plane, store } = await buildGhostlight(); + for (const bad of ["yes", "admin", true, 1, {}]) { + const res = await begin(plane, { provider: "google", firstLoginGrant: bad }); + expect(res.status, JSON.stringify(bad)).not.toBe("accepted"); + } + expect(attemptCount(store)).toBe(0); + }); + + it("a grant on link mode is refused by startOAuthFlow's gate, not smuggled past it", async () => { + const { plane } = await buildGhostlight(); + const res = await begin(plane, { provider: "google", mode: "link", firstLoginGrant: "invite" }); + expect(res.status).not.toBe("accepted"); + }); + + it("other apps are unchanged: repixelizer's public start still opens and its grant is still first_login_grant_refused", async () => { + const { app } = await buildGhostlight(); + const open = await app.inject({ + method: "POST", + url: "/v1/oauth/discord/start", + payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" }, + }); + expect(open.statusCode).toBe(201); + const granted = 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([granted.statusCode, granted.json().error]).toEqual([400, "first_login_grant_refused"]); + }); +}); diff --git a/tests/private-command-diagnostics.test.ts b/tests/private-command-diagnostics.test.ts index 4e62c3d..6db634e 100644 --- a/tests/private-command-diagnostics.test.ts +++ b/tests/private-command-diagnostics.test.ts @@ -14,7 +14,7 @@ import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope import { InMemoryStore } from "../src/store/index.js"; import { launchState } from "./oauth-flow.js"; -const secret = "ghostlight-private-command-secret"; +const secret = "bifrost-private-command-secret"; const resources: Array<{ close(): Promise }> = []; afterEach(async () => { vi.unstubAllGlobals(); @@ -29,24 +29,24 @@ function config(): HeimdallConfig { idunnRudpHealth: undefined, idunnHealthContract: "heimdall.cultnet-rudp-provider-health", providerHealthIdentityPath: "/tmp/.hd/p.cc", sessionTtlSeconds: 3600, refreshTtlSeconds: 3600, stateTtlSeconds: 600, completionTtlSeconds: 300, bootstrapSigningPrivateKeyOnMissing: false, tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"), - appSharedSecrets: { ghostlight: secret }, appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] }, appBackendCallbacks: {}, + appSharedSecrets: { bifrost: secret }, appRuntimeIds: { bifrost: ["bifrost-runtime"] }, appBackendCallbacks: {}, storage: { backend: "memory", applySchemaOnStartup: true }, providers: { discord: { clientId: "discord-client", clientSecret: "discord-secret" }, patreon: {}, github: {}, twitch: {}, youtube: {}, spotify: {}, joystick: {}, google: {} }, } as HeimdallConfig; } async function command(endpoint: unknown, operation: string, contentSchema: string, key: string, payload: Record) { - const envelope = sealPrivateEnvelope({ appSlug: "ghostlight", operation, contentSchema, idempotencyKey: key, secret, payload }); + const envelope = sealPrivateEnvelope({ appSlug: "bifrost", operation, contentSchema, idempotencyKey: key, secret, payload }); return invokeCultNetOperation(endpoint as never, { schemaVersion: "cultnet.operation_request.v0", messageId: `m-${key}`, serviceId: "heimdall.private.commands", operation, payloadSchema: "heimdall.private_command_envelope.v1", payloadEncoding: "messagepack-base64", - payload: Buffer.from(encode(envelope)).toString("base64"), sourceRuntimeId: "yggdrasil-ghostlight", - } as never, { runtimeId: "yggdrasil-ghostlight" }); + payload: Buffer.from(encode(envelope)).toString("base64"), sourceRuntimeId: "bifrost-runtime", + } as never, { runtimeId: "bifrost-runtime" }); } const open = (reply: { payload: string }) => openPrivateEnvelope(decode(Buffer.from(reply.payload, "base64")) as HeimdallPrivateEnvelope, secret); -/** A signed-in Ghostlight session, then a refresh whose provider answer is `refreshAnswer`. */ +/** A signed-in Bifrost session, then a refresh whose provider answer is `refreshAnswer`. */ async function refreshAgainst(refreshAnswer: () => Response) { let refreshing = false; vi.stubGlobal("fetch", async (url: string | URL, init?: RequestInit) => { @@ -72,7 +72,7 @@ async function refreshAgainst(refreshAnswer: () => Response) { resources.push(plane); const policy = { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }; const begin = open(await command(plane.endpoint, "heimdall.auth.begin", "heimdall.auth_begin_command.v1", "k1", - { provider: "discord", mode: "sign_in", returnTo: "https://yggdrasil.gamecult.org/ghostlight/", entitlementPolicy: policy })); + { provider: "discord", mode: "sign_in", returnTo: "https://bifrost.gamecult.org/auth/heimdall/complete", entitlementPolicy: policy })); const state = new URL(String((begin.navigation as { url: string }).url)).searchParams.get("state")!; const { cookie } = await launchState(app, state); const callback = await app.inject({ @@ -133,7 +133,7 @@ it("keeps the completion code out of the audit trail when the plane redeems by a resources.push(plane); const policy = { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }; const begin = open(await command(plane.endpoint, "heimdall.auth.begin", "heimdall.auth_begin_command.v1", "k1", - { provider: "discord", mode: "sign_in", returnTo: "https://yggdrasil.gamecult.org/ghostlight/", entitlementPolicy: policy })); + { provider: "discord", mode: "sign_in", returnTo: "https://bifrost.gamecult.org/auth/heimdall/complete", entitlementPolicy: policy })); const state = new URL(String((begin.navigation as { url: string }).url)).searchParams.get("state")!; const { cookie } = await launchState(app, state); const callback = await app.inject({ From 1dc7739ef5f907947f2df57bfc5d151e3c6d65ad Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 23:23:41 +0100 Subject: [PATCH 53/63] Docs: ghostlight Google sign-in, app-authenticated starts, begin firstLoginGrant Co-Authored-By: Claude Sonnet 5.5 --- docs/app-profiles/ghostlight.md | 21 +++++++++++++++------ docs/service-contract.md | 18 +++++++++++++----- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/docs/app-profiles/ghostlight.md b/docs/app-profiles/ghostlight.md index 58470f4..38ad159 100644 --- a/docs/app-profiles/ghostlight.md +++ b/docs/app-profiles/ghostlight.md @@ -11,14 +11,23 @@ selection, and every world mutation. - `app_slug`: `ghostlight` - public URL: `https://yggdrasil.gamecult.org/ghostlight/` -- identity provider: Discord -- access rule: Ghostlight supplies its configured KLTST Discord-role policy on - the app-authenticated private boundary; Heimdall evaluates the policy and - grants `app_access` only when it succeeds +- identity providers: Discord and Google +- access rule: Heimdall authenticates; `app_access` is `identity.authenticated`. + Who may play is the Dungeon's account catalog and its one-time invites, not a + Discord role. No Discord role policy is required of begin or refresh, and one + a caller still sends is evaluated by nobody for this app +- starts: every start is app-authenticated (`startRequiresAppCaller`); a public + start without the app secret is `401 app_auth_required` +- first Google sign-in: Google is linked-identity only, so a `sub` no account + holds is refused (`identity_not_linked`) unless the begin carried + `firstLoginGrant: "invite"`, which the Dungeon sends only for an invite its + catalog holds live. The grant mints a Heimdall account for a new `sub`; it + never attaches to or moves an existing account ## Capabilities -- `app_access`: shared capability granting entry to the demo +- `app_access`: shared capability; every authenticated identity has it, and + admission is the Dungeon's catalog - `campaign_play`: hybrid capability; Ghostlight must also prove that the authenticated account owns the selected campaign @@ -27,6 +36,6 @@ plugin stores only an opaque attempt handle. Ghostlight redeems that handle over the encrypted loopback command plane, verifies the resulting `aud=ghostlight` claim against Heimdall JWKS, and establishes app-local campaign authority. Short-lived local access continues without a Heimdall round trip. Scheduled -refresh re-evaluates the Ghostlight-owned KLTST role policy; explicit logout +refresh re-evaluates nothing app-specific; explicit logout revokes both Ghostlight's local session and the matching Heimdall refresh custody record. diff --git a/docs/service-contract.md b/docs/service-contract.md index 2412fbb..e91747e 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -187,10 +187,10 @@ Failure modes: the caller did not authenticate as that app via `x-heimdall-app-secret` (`resolveAppCaller`, `src/app-caller.ts`) -- this applies regardless of `handoff.kind` or app slug; a caller with no policy to attach needs no secret, - unless the app's profile sets `startRequiresAppCaller` (Bifrost only): then + unless the app's profile sets `startRequiresAppCaller` (Bifrost and Ghostlight): then every start for that app, with or without a policy, needs that app's secret. - Bifrost binds browser completion to a nonce that rides readable in the signed - state's `return_to`, so only Bifrost may mint a Bifrost state; apps whose + Bifrost and Ghostlight bind browser completion to a nonce that rides readable + in the signed state's `return_to`, so only the app may mint its own state; apps whose browser starts are public by design leave the flag unset - `401 app_auth_required` also when `mode` is `connect` and the body carries a `connection` (a creator or account target): a connection target is app-backend @@ -261,7 +261,7 @@ person an app has invited (see the invite grant below). 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`) +- Invite grant. An app whose profile sets `mayGrantFirstLogin` (`bifrost` and `ghostlight`) 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 @@ -287,7 +287,7 @@ person an app has invited (see the invite grant below). what Discord or Patreon grant. - Configure with `GC_ACCESS_PROVIDER_GOOGLE_CLIENT_ID` and `GC_ACCESS_PROVIDER_GOOGLE_CLIENT_SECRET_FILE`. Admitted to the `bifrost` - app profile only. + and `ghostlight` app profiles only. ### `GET /v1/oauth/{provider}/callback` @@ -1005,6 +1005,14 @@ same result only for the exact same authenticated request; content changes are denied. Completion consumption remains single-use in Heimdall's canonical store. +`heimdall.auth.begin` takes `provider`, `mode`, `returnTo`, an optional +`entitlementPolicy` (accepted for any app, required of none) and an optional +`firstLoginGrant`. Absent or null is no grant; exactly `"invite"` is passed to +the same start gate as the public route (the app's own caller, `sign_in` only, +an app whose profile may grant); any other value is refused before an attempt +is created. Ghostlight sends `"invite"` only for a browser whose invite the +Dungeon's catalog holds live; Heimdall holds no invite records. + Refresh claims are admitted only while their exact persisted session, app/account custody, access revision, and refresh expiry still match. Logout uses the refresh claim as custody proof and atomically advances the persisted From fc1dd7f78562217b5540a7f37fd0244c101e2f2d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 23:23:50 +0100 Subject: [PATCH 54/63] State: evidence for ghostlight Google sign-in cut Co-Authored-By: Claude Sonnet 5.5 --- state/evidence.jsonl | 1 + 1 file changed, 1 insertion(+) diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 279b21e..fa1268b 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -41,3 +41,4 @@ {"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"} +{"ts": "2026-12-02T22:23:49+00:00", "type": "design", "status": "accepted", "note": "ghostlight/google-sign-in: ghostlight admits Google, requires the app secret on every start (login-CSRF), accepts firstLoginGrant 'invite' on private-plane begin, app_access = identity.authenticated, no Discord role policy (requiredEntitlementPolicyKind and its guard deleted). Admission is the Dungeon's catalog. Not deployed. Local pnpm test: only pre-existing entrypoint-secrets failure on Windows; StrykerJS not configured, two hand mutants killed."} From 477ff0dee535407e00dc69ec672d36160503ee6a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:06:11 +0100 Subject: [PATCH 55/63] Steward cut 1: delete dead scaffolding and sync AGENTS/service-contract docs --- AGENTS.md | 77 +--- docs/service-contract.md | 3 +- notes/fresh-workspace-handoff.md | 272 --------------- notes/ghostlight-google-sign-in-cut-spec.json | 241 ------------- src/verifier.ts | 161 --------- state/branches.json | 26 -- state/map.yaml | 130 ------- state/scratch.md | 7 - tools/heimdall_prepare_compaction.py | 328 ------------------ tools/heimdall_state.py | 179 ---------- 10 files changed, 9 insertions(+), 1415 deletions(-) delete mode 100644 notes/fresh-workspace-handoff.md delete mode 100644 notes/ghostlight-google-sign-in-cut-spec.json delete mode 100644 src/verifier.ts delete mode 100644 state/branches.json delete mode 100644 state/map.yaml delete mode 100644 state/scratch.md delete mode 100644 tools/heimdall_prepare_compaction.py delete mode 100644 tools/heimdall_state.py diff --git a/AGENTS.md b/AGENTS.md index beb6fed..639ca18 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,12 +26,8 @@ The planned non-shared-by-default layer is: ## Canonical State -- Treat `state/map.yaml` as the canonical current project map. -- Treat `state/scratch.md` as disposable working memory for one bounded subgoal. - Treat `state/evidence.jsonl` as the distilled durable ledger of decisions, verified boundaries, and rejected paths. -- Treat `state/branches.json` as hypothesis tracking, not phase/status prose. -- Treat `notes/fresh-workspace-handoff.md` as the compact re-entry packet. - Treat `docs/architecture.md` as the source-grounded shared architecture note. - Treat `docs/implementation-plan.md` as the forward plan. - Treat `docs/app-profiles/repixelizer.md` and @@ -50,75 +46,17 @@ every absolute path in here rotted the moment it happened. - Repixelizer profile: `docs/app-profiles/repixelizer.md` - StreamPixels profile: `docs/app-profiles/streampixels.md` - Spotiverse profile: `docs/app-profiles/spotiverse.md` -- Handoff summary: `notes/fresh-workspace-handoff.md` -- State CLI: `tools/heimdall_state.py` -- Pre-compaction helper: `tools/heimdall_prepare_compaction.py` - -## Useful Commands - -Both state tools are single-file, standard-library-only Python. They need no -virtualenv and no installed dependencies. Run them with `python` from the repo -root: - -```powershell -python .\tools\heimdall_state.py status -python .\tools\heimdall_state.py add-evidence --type design --status accepted --note "..." -python .\tools\heimdall_prepare_compaction.py -``` - -Verified 2026-09-06 against Python 3.13.15 installed to the user scope; `py -3` -resolves the same interpreter. - -If `python --version` prints an install prompt rather than a version, PATH is -resolving the Microsoft Store alias in `WindowsApps` instead of a real -interpreter, and it will still exit 0 while doing so. Install a real Python and -put it ahead of `WindowsApps` on PATH rather than hunting for some other -interpreter to hard-code here: - -```powershell -winget install --id Python.Python.3.13 --scope user -``` ## Session Bootstrap And Re-entry Protocol On fresh session load: 1. read: - - `state/map.yaml` - - `notes/fresh-workspace-handoff.md` - `docs/architecture.md` - `docs/implementation-plan.md` 2. run: - - `python .\tools\heimdall_state.py status` - `git status --short --branch` - `git log --oneline -5` -3. restate the current next action from persisted state before editing - -After compaction or suspicious continuity loss: - -1. rerun `heimdall_state.py status` -2. reread `state/map.yaml` and `notes/fresh-workspace-handoff.md` -3. treat the persisted next action as authoritative unless fresh evidence - contradicts it - -When the user says to prepare for imminent compaction: - -1. run `tools/heimdall_prepare_compaction.py` -2. update only the state that actually changed -3. rerun the helper -4. commit the completed persistence pass unless the work is deliberately - mid-surgery - -After any major completed pass, assume compaction may be imminent even if the -user did not say so yet: - -1. run `tools/heimdall_prepare_compaction.py` -2. sync only the persistent state that genuinely changed -3. rerun the helper -4. commit the persistence pass before moving on unless the work is - deliberately mid-surgery -5. push the current branch to `origin` after the major pass unless the user - explicitly says not to publish yet ## Operating Discipline @@ -132,18 +70,17 @@ user did not say so yet: - Do not let app profiles turn into duplicate copies of the shared architecture. - If the diff grows while the boundary gets blurrier, stop and simplify. -- Before handoff or compaction, sync `state/map.yaml`, refresh - `notes/fresh-workspace-handoff.md`, add distilled evidence when future belief - changed, and make the next action explicit. ## Build And Deploy Target Heimdall runs as the auth authority behind Yggdrasil-hosted nginx at -`heimdall.gamecult.org`, on Linux. Idunn owns the deployment transaction. This -workstation is Windows and is where the shell is, not where the artifact runs: -a local compile is not evidence about the Linux release, because toolchain, -linker, filesystem semantics and path handling all differ. Build for the -target, or let the deploy path's own builder do it, and say which one you used. +`heimdall.gamecult.org`, on Linux. `deployment/idunn/recipe.toml` is the target +deployment declaration (untested against live Idunn; Yggdrasil still runs the +hand-written `heimdall.service`). This workstation is Windows and is where the +shell is, not where the artifact runs: a local compile is not evidence about the +Linux release, because toolchain, linker, filesystem semantics and path +handling all differ. Build for the target, or let the deploy path's own builder +do it, and say which one you used. ## External Context diff --git a/docs/service-contract.md b/docs/service-contract.md index e91747e..6915c6e 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -83,7 +83,8 @@ Current app slugs: - `repixelizer` - `streampixels` -- `spotiverse` +- `bifrost` +- `ghostlight` Profile fields: diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md deleted file mode 100644 index 9d23cf1..0000000 --- a/notes/fresh-workspace-handoff.md +++ /dev/null @@ -1,272 +0,0 @@ -# Fresh Workspace Handoff - -This is the re-entry packet for this repo (path: whatever the checkout is; it has moved drives before). - -It is intentionally short. Historical proof belongs in git history and the -distilled `state/evidence.jsonl` ledger; the shared architecture belongs in -`docs/architecture.md`; the forward build order belongs in -`docs/implementation-plan.md`. - -## Rehydrate - -From the repo root: - -```powershell -python .\tools\heimdall_state.py status -Get-Content '.\state\map.yaml' -Get-Content '.\notes\fresh-workspace-handoff.md' -Get-Content '.\docs\architecture.md' -Get-Content '.\docs\implementation-plan.md' -git status --short --branch -git log --oneline -5 -Get-Content '.\state\evidence.jsonl' -Tail 8 -``` - -Do not trust this file for the exact live HEAD. Always check git. - -## Active Work - -Joystick H1 is merged and live (PR GameCult/Heimdall#1; campaign -`joystick:campaign:self`). Next: `joystick:follow_up:h1-joystick-consent-round-trip`, then -StreamPixels S0/S1 (other sessions). Open Heimdall follow-ups, by id: -`joystick:follow_up:cross-process-failed-refresh-marker`, -`joystick:follow_up:connect-start-needs-app-auth`, -`joystick:follow_up:heimdall-idunn-onboarding`, -`joystick:follow_up:joystick-viewer-signin-public-bot`. The Ghostlight KLTST -canaries below stay open, behind them. - -## Current Orientation - -Yggdrasil runs Heimdall `d51fa6b`, hand-deployed 2026-10-19 15:51Z; -gamecult-ops `210a1af` records backup, rollback and provenance. Facts below -about Odin, Ghostlight and CultLib pins were verified at `1086aee` (2026-08-22) -and are not re-verified at `d51fa6b`. - -- At `1086aee01169bf60e8a492b2740db1c6f3e8cabf` Heimdall ran with CultLib - `5cefa0db0079a8e3ee22f29d7b9e6e5aa60912a9` -- Heimdall publishes four redacted access records to Odin under unique keys: - `eve:provider:heimdall`, `heimdall:command-boundary`, - `eve:plugin:gamecult.heimdall.access`, and `heimdall:transport-profile` -- Odin `b4f9a2e95f0b41cebdeddc49223781d1d3c7b42a` persists and returns all four; - it does not proxy private commands or receive claims -- Ghostlight `b515ca90c25573005a616244143803b37f2d06ec` resolves the boundary through - Odin and accepted a live canonical anonymous `heimdall.auth.begin`; its unit - has no direct Heimdall endpoint - -- `gamecult.heimdall.access` now has a manifest, advertisement, schemas, - fixtures, executable `describe`/`validate`/`project` ABI, and browser - reference adapter -- Heimdall persists OAuth attempts and serves authenticated - `heimdall.auth.begin` / `heimdall.auth.complete` / `heimdall.auth.refresh` / - `heimdall.auth.logout` through loopback - CultNet/RUDP on port `4101` -- private commands are source-runtime, app-secret, expiry, nonce, and - idempotency bound; their MessagePack payloads and completion claims are - AES-256-GCM wrapped -- the Ghostlight app profile now requires its caller-owned Discord role policy; - Heimdall evaluates it and Ghostlight remains owner of local sessions, - memberships, and campaigns -- refresh verifies the exact persisted session revision before reissuing a - claim; logout expires that session and advances its revision, so a stale or - racing refresh cannot resurrect revoked custody - -- this repo now has a first stateful Heimdall service slice -- the canonical shared architecture lives in `docs/architecture.md` -- the concrete HTTP/JWKS contract lives in `docs/service-contract.md` -- app profiles live under `docs/app-profiles/` -- the key boundary is explicit: - - Heimdall owns OAuth, linking, managed provider credential custody, grants, - entitlement refresh, and signed claim issuance - - app-domain data stays app-owned by default - - host apps verify signed claims locally for routine auth instead of calling - Heimdall on every request -- the landed service now exposes: - - `/.well-known/jwks.json` - - `/.well-known/heimdall-configuration` - - `/v1/oauth/{provider}/start` - - `/v1/oauth/{provider}/callback` - - `/v1/apps/{appSlug}/auth-completions/redeem` - - `/v1/apps/{appSlug}/sessions/refresh` - - `/v1/apps/{appSlug}/managed-credentials/resolve` -- the Discord callback path now performs real code exchange, identity - resolution, auth persistence, entitlement evaluation, audit logging, and - claim issuance for the Repixelizer slice -- browser-style auth handoff now uses a one-time completion code posted back to - the opener, with backend redemption instead of fragment-token handoff -- same-host or Yggdrasil-reachable app integrations can now ask Heimdall to - deliver the auth result directly to an app backend callback endpoint, leaving - the browser with only status/attempt signaling -- signing keys can now load from a persisted file path and bootstrap that file - on first boot when explicitly enabled -- managed provider tokens are now sealed at rest with AES-256-GCM instead of - being dumped into "encrypted" columns raw like an insult -- `src/verifier.ts` now provides a small local JWT verifier seam for app - backends -- Repixelizer has consumed the backend-callback flow in its hosted web layer: - it creates local auth attempts, asks Heimdall to start OAuth, receives the - direct backend callback, verifies Heimdall Ed25519 access tokens locally, and - adopts httpOnly local sessions -- Heimdall is now deployed on Yggdrasil at `https://heimdall.gamecult.org` - behind nginx/TLS with Postgres storage, file-backed signing-key bootstrap, - configured token custody, and public health/discovery/JWKS checks passing -- Repixelizer is now deployed on Yggdrasil at - `https://repixelizer.gamecult.org` with Heimdall mode enabled, Discord and - Patreon as public providers, required access enabled, and queue protection - enabled -- Repixelizer public auth-start returns Discord and Patreon authorization URLs - using the Heimdall callback and Repixelizer backend handoff -- Repixelizer auth now has a refresh path: Heimdall issues signed refresh - tokens with access claims, `/v1/apps/{appSlug}/sessions/refresh` reissues - short-lived access claims, and Discord/Patreon provider tokens refresh inside - Heimdall before entitlement re-evaluation -- Twitch and YouTube now have generic OAuth exchange and identity runtimes -- GitHub is still catalogued, but its callback runtime is not implemented -- StreamPixels now delegates viewer and creator Twitch/YouTube OAuth to - Heimdall, redeems Heimdall completion codes server-side, writes its own - viewer sessions and connector bindings, and resolves current provider access - tokens from Heimdall without storing refresh tokens locally -- Spotiverse now delegates Spotify OAuth to Heimdall. Heimdall has a - `spotiverse` app profile and `spotify` provider runtime; Spotiverse stores a - local Heimdall account binding and resolves current Spotify access through - `/v1/apps/spotiverse/managed-credentials/resolve` without storing provider - refresh tokens. -- Bifrost now has a `bifrost` app profile for Discord/Patreon member access. - Bifrost sends caller-owned KTLST Discord role and Patreon tier policies - through trusted backend-callback OAuth starts; Heimdall owns provider - OAuth/token custody and configured backend callback allowlisting. -- Bifrost patron support sync now reuses Heimdall's existing linked Patreon - identity and membership reader. `POST /v1/apps/bifrost/patron-support/sync` - is app-authenticated, refreshes the stored Patreon credential if needed, - reads active paid Patreon tier evidence, and emits a signed - `RecurringSupportSnapshot` to Bifrost's - `/heimdall/patron-support/events` intake. -- Public Yggdrasil Heimdall has been deployed with the Spotiverse/Spotify code - path, Spotify provider credentials, a Spotiverse shared secret, and an - allowlisted loopback portal callback at - `http://127.0.0.1:18796/auth/heimdall/callback`. -- Heimdall and StreamPixels are deployed on Yggdrasil for the StreamPixels - migration slice; Twitch callback handling has been patched so provider token - `scope` can be either a space-delimited string or an array -- live StreamPixels Twitch sign-in through Heimdall has succeeded on Yggdrasil - and Heimdall audit showed callback success, completion creation, and - completion redemption -- the ignored local `secrets/heimdall-service.env` artifact now has - `GC_ACCESS_PROVIDER_TWITCH_*` and `GC_ACCESS_PROVIDER_YOUTUBE_*` populated - for the StreamPixels migration slice -- the intended first deployment shape is a Heimdall service on Yggdrasil behind - nginx, not an embedded cross-runtime shared library fantasy -- Heimdall now writes a daemon-owned boundary witness store at - `GC_ACCESS_CULTCACHE_PATH` containing provider advertisement, command - boundary, transport profile, and daemon-health summary state -- Heimdall can now publish `heimdall.cultnet-rudp-provider-health` to Idunn - over `cultnet.transport.rudp.v0` when `GC_ACCESS_IDUNN_RUDP_HEALTH` is - configured; HTTP `/healthz`, JWKS, discovery, systemd, and nginx routing - remain compatibility witnesses -- Since `1086aee` Heimdall persists its private - provider-health identity at `/srv/heimdall/keys/provider-health-identity.cc` - and publishes canonical signed health independently of the slower Verse - snapshot cadence. Idunn owns the exact root trust binding, authenticated - admission, lifecycle decision, and redacted public `.cc` projection. -- Odin commit `b4f9a2e95f0b41cebdeddc49223781d1d3c7b42a` retains the RUDP health - reliability cut and registers Heimdall's command-boundary, plugin, and - transport schemas so the typed catalog can persist rather than silently drop - them. Live proof returned all four exact Heimdall records. - -## Critical Doctrine - -- Persistent state is the agent's mind. -- Cut stale architecture notes as ruthlessly as stale code. -- Do not mistake "shared auth" for "shared database." -- Do not mistake "shared auth service" for "every guarded route must call the - mothership." -- If compaction hits before boundary findings are persisted, that work is gone. - Re-gather it instead of pretending continuity happened. - -## Next Real Move - -The Active Work follow-ups first. Everything below is the standing queue. - -Do not continue implementation automatically from a rehydrate-only request. - -The Idunn/swarm health transport cut is live. Do not regress Heimdall to -unsigned `idunn.daemon_health`, merge its private key into Idunn, or make HTTP -health an authority. The next product work is the Bifrost and remaining browser -verification listed below. - -The active Ghostlight deployment cut is complete. The next Ghostlight work is a -real separate-account KLTST completion/refresh/logout canary, followed by the -eight-account Session Zero privacy and actor-binding smoke. Keep port `4101` -loopback-only and treat any claim, token, completion, app secret, or account -state in Odin/CultMesh/browser output as a release-blocking fault. - -If the user asks to continue on Spotiverse, the current next move is the real -browser `/auth/login` flow through public Heimdall. The Yggdrasil SSH tunnel -must include reverse forward -`spotiverse-callback:18796:127.0.0.1:8796`, and local Spotiverse must point at -`https://heimdall.gamecult.org` with the matching `HEIMDALL_APP_SECRET`. Verify -managed credential resolution after login. Spotiverse should not regain local -Spotify OAuth token storage. - -If the user asks to continue on StreamPixels, the current next move is real -browser verification: - -- verify viewer claim/link through `https://streampixels.gamecult.org/auth/connect` -- Twitch viewer sign-in has already passed once; continue with YouTube and - connector attachment verification -- verify creator connector attach from an admin creator session -- confirm StreamPixels persists local profile/connector binding state while - Heimdall retains provider token custody -- if a provider callback fails, inspect Heimdall audit events and StreamPixels - service logs before touching app/domain boundaries - -Repixelizer still needs its real browser OAuth verification: - -- open `https://repixelizer.gamecult.org/app/` -- start Discord sign-in with an account that has the `KLTST` or - Patreon-synced `Inner Sanctum` role, or Patreon sign-in with a currently - entitled tier titled `Inner Sanctum` -- confirm Repixelizer sends its app-owned provider policy in the - backend-callback OAuth start -- confirm Heimdall receives the provider callback and evaluates entitlement -- confirm Repixelizer receives the backend callback, verifies the Heimdall - token, adopts a local httpOnly session, and gates hosted/queue routes -- confirm the Discord authorization URL requests only `identify - guilds.members.read` - -Launch policy is role-gated on purpose: the GameCult Discord can remain public, -but Repixelizer access is limited to members with either `KLTST` or the -Patreon-synced `Inner Sanctum` role. Repixelizer owns that role policy through -its own runtime env and sends it to Heimdall during backend-callback OAuth -start; Heimdall owns provider OAuth mechanics and claim issuance, not the -per-app role list. - -Patreon access is title-gated on the currently entitled tier title -`Inner Sanctum`; do not use currency amount as the durable policy because -currencies are weird little traps. - -Bifrost needs browser verification after deployment: - -- configure Heimdall with - `GC_ACCESS_APP_BIFROST_BACKEND_CALLBACK_URLS=https://bifrost.gamecult.org/auth/heimdall/callback` -- configure Heimdall with `GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE`, - `GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT=https://bifrost.gamecult.org/heimdall/patron-support/events`, - and `GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE`, each naming a credential - file -- configure Bifrost with `Heimdall__DiscordGuildId`, - `Heimdall__DiscordAllowedRoleIds__0=`, and - `Heimdall__PatreonTierTitle=Inner Sanctum` -- configure Bifrost with the matching `Heimdall__PatronSupportIntakeSecret` -- start Discord sign-in from `https://bifrost.gamecult.org/` with a user that - has the KTLST cult-member role -- start Patreon sign-in with a user that has the configured active tier -- confirm Bifrost creates/updates a local account and active standard - membership while Heimdall keeps provider token custody -- trigger `/v1/apps/bifrost/patron-support/sync` for that linked Heimdall - account and confirm Bifrost records a Patreon recurring-support snapshot - without owning Patreon webhook or token custody - -## Immediate Re-entry Instruction - -After compaction, first rehydrate and reorient from the listed files and git -state. Wait for the user's next instruction unless they explicitly say to -continue. diff --git a/notes/ghostlight-google-sign-in-cut-spec.json b/notes/ghostlight-google-sign-in-cut-spec.json deleted file mode 100644 index 521858e..0000000 --- a/notes/ghostlight-google-sign-in-cut-spec.json +++ /dev/null @@ -1,241 +0,0 @@ -{ - "kind": "cut_spec", - "value": { - "campaign": "ghostlight-verse", - "cut": "heimdall-ghostlight-google", - "revision": 1, - "title": "Heimdall: ghostlight admits Google, honours the Dungeon's invite grant, and stops gating on the Discord role", - "repo": "GameCult/Heimdall", - "branch": "ghostlight/google-sign-in", - "base": "2bcb2ca4e7fb640e07deae42302b0919a62e5bc4", - "depends_on": [], - "first": [ - "Work in the existing worktree F:\\Projects\\Heimdall-wt-ghostlight-google on branch ghostlight/google-sign-in (from origin/main 2bcb2ca). Read AGENTS.md; follow its state/evidence conventions for the closing evidence line.", - "Read docs/service-contract.md 'Invite grant' (about line 264) and src/app.ts startOAuthFlow gates (about lines 832-846): the grant mechanism already exists for bifrost. This cut extends it to ghostlight and threads it through the private command plane; it adds no invite records to Heimdall.", - "Delete first: AppProfile.requiredEntitlementPolicyKind (app-profiles.ts:41-47, set only by ghostlight at :203) and requireEntitlementPolicyIfProfileDemandsIt (private-command-plane.ts:385-407) with its two call sites (:236 refresh, :272 begin). A caller-sent policy stays accepted and optional as for every other app.", - "Heimdall ruling heimdall-body:ruling:bifrost-google-invitation-link-only forbids attaching Google to an existing account by an invitation path. This cut does not: the grant only mints a new account for a sub no account holds and never attaches (contract text at :264-274). Do not widen that.", - "Open the Heimdall PR on Forgejo only when Self says so; the brief for this mapping pass forbids it, Hands' own brief decides." - ], - "deletes": [ - { - "path": "src/app-profiles.ts", - "lines": 8, - "note": "requiredEntitlementPolicyKind field and its doc comment; ghostlight's requiredEntitlementPolicyKind line" - }, - { - "path": "src/private-command-plane.ts", - "lines": 22, - "note": "requireEntitlementPolicyIfProfileDemandsIt and its two awaits" - }, - { - "path": "tests", - "lines": 30, - "note": "tests that pin 'ghostlight authentication/refresh requires its caller-owned discord_role_access policy' are deleted or inverted (a ghostlight begin without policy now starts)" - } - ], - "keeps_moves": [ - "The grant gates in startOAuthFlow (app caller of this slug, sign_in only, mayGrantFirstLogin) and the callback mint under first_login_grant are unchanged.", - "Bifrost's profile, its grant and its Google link flow are unchanged.", - "The private-plane attempt handle (trustedBrowserAttemptId, never body-supplied) is the ghostlight browser binding and is unchanged.", - "Discord stays a ghostlight identity provider; a Discord policy a caller still sends is evaluated by nobody for ghostlight (entitlementSources empty) and is harmless." - ], - "adds": [ - "ghostlight profile: identityProviders ['discord','google']; entitlementSources []; startRequiresAppCaller: true; mayGrantFirstLogin: true; profileVersion '2026-12-02'.", - "ghostlight app_access: anyOf [identityFacts.authenticated] (as streampixels viewer_access at :147), summary 'Heimdall authenticated this identity for Ghostlight; who may play is the Dungeon's account catalog'. campaign_play summary/localRequirement: 'Ghostlight combines a Heimdall sign-in with its own account catalog and campaign ownership'.", - "beginAuth reads payload.firstLoginGrant: absent/null -> none; exactly 'invite' -> passed to startOAuthFlow input.firstLoginGrant; any other value -> throw 'Auth begin payload is incomplete.' (same refusal shape as a bad provider). startOAuthFlow's existing gate then decides." - ], - "file_changes": [ - { - "location": { - "path": "src/app-profiles.ts", - "line": 195, - "end_line": 218, - "symbol": "ghostlightProfile" - }, - "change": "As in adds: providers, entitlementSources [], startRequiresAppCaller, mayGrantFirstLogin, app_access on identity.authenticated, summaries, profileVersion. Import identityFacts is already present." - }, - { - "location": { - "path": "src/private-command-plane.ts", - "line": 260, - "end_line": null, - "symbol": "beginAuth" - }, - "change": "Thread firstLoginGrant into the startOAuthFlow input; drop the policy-demand await." - }, - { - "location": { - "path": "src/private-command-plane.ts", - "line": 221, - "end_line": null, - "symbol": "refreshAuth" - }, - "change": "Drop the policy-demand await; policy remains optional and passed through when present." - }, - { - "location": { - "path": "schemas/heimdall.auth_begin_command.v1.schema.json", - "line": 1, - "end_line": null - }, - "change": "provider enum gains google; entitlementPolicy leaves required; add firstLoginGrant {enum:['invite']}." - }, - { - "location": { - "path": "schemas/heimdall.auth_refresh_command.v1.schema.json", - "line": 1, - "end_line": null - }, - "change": "entitlementPolicy optional if it is required there." - }, - { - "location": { - "path": "docs/service-contract.md", - "line": 190, - "end_line": null - }, - "change": "startRequiresAppCaller: 'Bifrost and Ghostlight'; mayGrantFirstLogin (about :264): 'bifrost and ghostlight'; Google (about :289): admitted to bifrost and ghostlight; private-plane begin accepts firstLoginGrant 'invite'." - }, - { - "location": { - "path": "docs/app-profiles/ghostlight.md", - "line": 1, - "end_line": null - }, - "change": "Providers Discord and Google; access rule: Heimdall authenticates, app_access is identity.authenticated, admission is the Dungeon's catalog and one-time invites (ruling dungeon-owns-accounts); a first Google sign-in mints a Heimdall account only under the Dungeon's grant; no Discord role policy; refresh re-evaluates nothing app-specific." - } - ], - "reads": [ - { - "location": { - "path": "src/app.ts", - "line": 832, - "end_line": null, - "symbol": "startOAuthFlow" - }, - "why": "the app-caller and grant gates the private plane now reaches with a grant" - }, - { - "location": { - "path": "src/app.ts", - "line": 2034, - "end_line": null - }, - "why": "callback: requires_link + first_login_grant mints and audits account_minted_by_grant" - }, - { - "location": { - "path": "tests/google-link.test.ts", - "line": 1, - "end_line": null - }, - "why": "the bifrost grant tests to mirror for ghostlight over the private plane" - }, - { - "location": { - "path": "tests/caller-identity-soul.test.ts", - "line": 23, - "end_line": null - }, - "why": "private-plane ghostlight fixtures (ghostlightSecret, runtime ids)" - } - ], - "authority_map": { - "owner": "The Dungeon's account catalog (catalog.cc) owns admission: an identity plays if an account holds it, or if it redeems a live one-time Dungeon invite, consumed in the write that creates the account. Heimdall owns authentication only: it proves which external identity signed in and names the Heimdall account (claim sub) that identity belongs to.", - "inputs": [ - "Dungeon: the invite the browser presents at begin, its catalog, the Heimdall-verified claim at complete", - "Heimdall: the app-authenticated begin (ghostlight secret over the private plane), the provider's OIDC/OAuth answer, the signed state" - ], - "outputs": [ - "Dungeon -> Heimdall: firstLoginGrant 'invite' on a begin whose browser presented an invite the catalog holds live", - "Heimdall -> Dungeon: a claim aud=ghostlight with app_access for every authenticated identity", - "Dungeon: an account row, the spent invite, an app session" - ], - "derived_state": [ - "Heimdall's first_login_grant is no longer an invite: it is derived from the Dungeon's live invite at begin and is notification-only (it lets Heimdall mint an auth account for a Google sub no account holds)", - "ghostlight app_access is no longer an admission gate: it is derived from identity.authenticated; the Dungeon's app_access checks become claim-shape checks that cannot refuse an authenticated sign-in", - "the invite bound to an attempt in AuthGuard is a copy of what the browser presented at begin, memory-only, living no longer than the begin cookie" - ], - "forbidden_writers": [ - "Heimdall's Discord role policy (requiredEntitlementPolicyKind, entitlementSources discord) no longer decides who enters the Dungeon", - "Heimdall holds no invite records for ghostlight and never decides who is invited", - "the complete body no longer carries an invite; only the begin-bound invite reaches catalog.sign_in", - "no public (secretless) ghostlight OAuth start: startRequiresAppCaller" - ], - "shared_paths": [ - "Google, Discord and any later provider begin through one auth_begin -> HeimdallClient::begin -> heimdall.auth.begin path; the grant decision is the same catalog read for every provider", - "every sign-in, first or returning, any provider, ends in one catalog.sign_in" - ], - "deletion_line": "Delete before adding: Heimdall's requiredEntitlementPolicyKind field and requireEntitlementPolicyIfProfileDemandsIt; the Dungeon's DiscordGate, its two env names and the policy on begin and refresh; the complete body's invite field." - }, - "verification": { - "builds": [ - "pnpm typecheck && pnpm test in the worktree (vendor/CultLib built as AGENTS.md says); report the pre-existing odin-publication failure separately if it still appears" - ], - "tests": [ - { - "name": "ghostlight google first sign-in under grant", - "pins": "private-plane begin {provider google, firstLoginGrant invite} -> 201 state with first_login_grant; callback with an unheld sub mints one account and audits account_minted_by_grant {provider google, appSlug ghostlight}; the completion's claim carries app_access" - }, - { - "name": "ghostlight google first sign-in without grant", - "pins": "same begin without firstLoginGrant -> callback refuses identity_not_linked and mints nothing" - }, - { - "name": "returning google identity", - "pins": "a sub an account already holds signs in with or without the grant to that same account; the grant attaches nothing" - }, - { - "name": "discord without policy", - "pins": "private-plane ghostlight discord begin with no entitlementPolicy starts (no throw); refresh without policy refreshes; claim carries app_access" - }, - { - "name": "public ghostlight start refused", - "pins": "POST /v1/oauth/google/start and /v1/oauth/discord/start for appSlug ghostlight without x-heimdall-app-secret -> 401 app_auth_required" - }, - { - "name": "bad grant value", - "pins": "private-plane begin with firstLoginGrant 'yes' is refused before any attempt row or state is minted" - }, - { - "name": "other apps unchanged", - "pins": "repixelizer/streampixels public starts unchanged; firstLoginGrant from repixelizer still 400 first_login_grant_refused" - } - ], - "negative": [ - { - "pattern": "requiredEntitlementPolicyKind|requireEntitlementPolicyIfProfileDemandsIt", - "scope": "src, tests, docs: zero hits" - }, - { - "pattern": "discord_role_access", - "scope": "src/app-profiles.ts: zero hits (the policy kind itself stays in contracts and the Discord evaluator)" - }, - { - "pattern": "invite", - "scope": "src/store/**: no new table, column or row for ghostlight invites" - } - ], - "operator": [ - "Deploy is cut ops-google-sign-in's runbook section, after this merges to Heimdall main; not part of this cut." - ] - }, - "estimate": { - "lines_added": 140, - "lines_removed": 70, - "dependencies_added": [], - "dependencies_removed": [], - "formats_added": [], - "formats_removed": [], - "targets_added": [], - "targets_removed": [] - }, - "rulings": [ - "ghostlight-verse:ruling:weksa-owns-dungeon-google-sign-in", - "ghostlight-verse:ruling:dungeon-owns-accounts" - ], - "questions": [ - "ghostlight-verse:question:heimdall-ghostlight-google-twitch-sign-in" - ] - } -} \ No newline at end of file diff --git a/src/verifier.ts b/src/verifier.ts deleted file mode 100644 index 81b303a..0000000 --- a/src/verifier.ts +++ /dev/null @@ -1,161 +0,0 @@ -import { createPublicKey, type KeyObject } from "node:crypto"; -import { isAppSlug, providers, type AccessClaimPayload, type AppSlug, type LinkedIdentityInput, type Provider } from "./contracts.js"; -import { type PublicSigningJwk, verifyJwt } from "./signing.js"; - -export interface HeimdallVerifierOptions { - issuer: string; - appSlug: AppSlug; - jwks: { - keys: PublicSigningJwk[]; - }; - allowedClockSkewSeconds?: number; -} - -export type VerifyAccessTokenResult = - | { - valid: true; - header: Record; - claimSet: AccessClaimPayload; - } - | { - valid: false; - error: string; - }; - -function isLinkedIdentity(value: unknown): value is LinkedIdentityInput { - if (!value || typeof value !== "object") { - return false; - } - - const record = value as Record; - if ( - typeof record.provider !== "string" || - !providers.includes(record.provider as Provider) || - typeof record.providerUserId !== "string" - ) { - return false; - } - - if (record.username !== undefined && typeof record.username !== "string") { - return false; - } - - if (record.displayName !== undefined && typeof record.displayName !== "string") { - return false; - } - - return true; -} - -function parseAccessClaimPayload(payload: Record): AccessClaimPayload | null { - if ( - payload.typ !== "heimdall_access" || - typeof payload.iss !== "string" || - typeof payload.aud !== "string" || - !isAppSlug(payload.aud) || - typeof payload.sub !== "string" || - typeof payload.sid !== "string" || - typeof payload.jti !== "string" || - typeof payload.iat !== "number" || - typeof payload.nbf !== "number" || - typeof payload.exp !== "number" || - typeof payload.account_id !== "string" || - typeof payload.access_revision !== "number" || - !payload.app || - typeof payload.app !== "object" || - typeof (payload.app as Record).slug !== "string" || - !isAppSlug((payload.app as Record).slug) || - typeof (payload.app as Record).profile_version !== "string" || - !Array.isArray(payload.facts) || - !payload.facts.every((fact) => typeof fact === "string") || - !Array.isArray(payload.capabilities) || - !payload.capabilities.every((capability) => typeof capability === "string") || - !Array.isArray(payload.identities) || - !payload.identities.every(isLinkedIdentity) - ) { - return null; - } - - if (payload.display_name !== undefined && typeof payload.display_name !== "string") { - return null; - } - - return payload as unknown as AccessClaimPayload; -} - -function buildKeyIndex(jwks: { keys: PublicSigningJwk[] }): Map { - return new Map( - jwks.keys.map((jwk) => [ - jwk.kid, - createPublicKey({ - key: jwk, - format: "jwk", - }), - ]) - ); -} - -export function createHeimdallAccessTokenVerifier(options: HeimdallVerifierOptions): { - verify(token: string, now?: Date): VerifyAccessTokenResult; -} { - const keyIndex = buildKeyIndex(options.jwks); - const allowedClockSkewSeconds = Math.max(0, Math.trunc(options.allowedClockSkewSeconds ?? 30)); - - return { - verify(token: string, now = new Date()): VerifyAccessTokenResult { - const [encodedHeader] = token.split("."); - if (!encodedHeader) { - return { valid: false, error: "Malformed JWT." }; - } - - let header: Record; - try { - header = JSON.parse(Buffer.from(encodedHeader, "base64url").toString("utf8")) as Record; - } catch { - return { valid: false, error: "Malformed JWT header." }; - } - - if (header.alg !== "EdDSA" || typeof header.kid !== "string") { - return { valid: false, error: "Unsupported JWT signing header." }; - } - - const publicKey = keyIndex.get(header.kid); - if (!publicKey) { - return { valid: false, error: `Unknown signing key id '${header.kid}'.` }; - } - - const verified = verifyJwt(token, publicKey); - if (!verified.valid) { - return verified; - } - - const claimSet = parseAccessClaimPayload(verified.payload); - if (!claimSet) { - return { valid: false, error: "JWT payload is not a valid Heimdall access claim." }; - } - - if (claimSet.iss !== options.issuer) { - return { valid: false, error: "JWT issuer does not match the configured Heimdall issuer." }; - } - - if (claimSet.aud !== options.appSlug || claimSet.app.slug !== options.appSlug) { - return { valid: false, error: "JWT audience does not match the expected app slug." }; - } - - const nowEpochSeconds = Math.floor(now.getTime() / 1000); - if (claimSet.nbf > nowEpochSeconds + allowedClockSkewSeconds) { - return { valid: false, error: "JWT is not valid yet." }; - } - - if (claimSet.exp <= nowEpochSeconds - allowedClockSkewSeconds) { - return { valid: false, error: "JWT has expired." }; - } - - return { - valid: true, - header: verified.header, - claimSet, - }; - }, - }; -} diff --git a/state/branches.json b/state/branches.json deleted file mode 100644 index 32cd28f..0000000 --- a/state/branches.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "branches": [ - { - "id": "main", - "hypothesis": "A shared Heimdall authority service on Yggdrasil can be reused across hosted experiments if OAuth, sessions, grants, and capability machinery are centralized while app-domain data and routine route authorization stay app-local.", - "status": "active", - "artifacts": [ - "state/map.yaml", - "state/scratch.md", - "state/evidence.jsonl", - "docs/architecture.md", - "docs/implementation-plan.md" - ], - "notes": "Current mainline. Repixelizer is the first auth-blank binding target; StreamPixels is the migration and boundary stress test." - }, - { - "id": "eureka/joystick-h1", - "hypothesis": "One locked refresh primitive plus a Joystick OAuth provider in Heimdall lets StreamPixels ingest Joystick without ever presenting a provider refresh token.", - "status": "accepted", - "artifacts": [ - "state/map.yaml" - ], - "notes": "Merged as PR GameCult/Heimdall#1 (d51fa6b), deployed to Yggdrasil 2026-10-19 15:51Z; gamecult-ops 210a1af. Campaign joystick:campaign:self." - } - ] -} diff --git a/state/map.yaml b/state/map.yaml deleted file mode 100644 index 4aa4d5a..0000000 --- a/state/map.yaml +++ /dev/null @@ -1,130 +0,0 @@ -project: - name: Heimdall - status: active - phase: streampixels_migration - premise: > - Build Heimdall as one reusable GameCult auth authority service for OAuth, - linked identities, local sessions, grants, and capability claims without - mixing in app-domain audience or product data. - -objective: - primary: > - Create a shared auth authority service that Repixelizer, StreamPixels, and - future GameCult-hosted experiments can consume. - current: > - Publish the Heimdall Eve access plugin and private CultNet authentication - plane, then migrate Ghostlight onto app-local sessions without moving - campaign or membership authority into Heimdall. - -constraints: - - Heimdall owns auth/control-plane authority; app-domain data stays app-owned by default. - - Prefer a same-host Heimdall service on Yggdrasil over duplicated per-app provider stacks. - - Host apps verify signed claims locally for routine guarded routes. - - App profiles stay thin; the shared architecture note owns the main model. - - StreamPixels audience and creator data must not be absorbed into a shared auth store. - -invariants: - - The map is canonical and slow-changing. - - Scratch is temporary and disposable. - - Evidence is durable and distilled; routine activity logs belong in git history and commit messages. - - Heimdall owns OAuth, local sessions, grants, entitlement refresh, capability evaluation, and audit surfaces. - - App-domain data stays with the host app unless there is a deliberate, source-grounded reason to share it. - - Host apps verify signed claims locally and keep resource ownership checks local. - - StreamPixels can reuse shared auth authority without centralizing streamer-audience data. - - Spotiverse consumes Spotify as a Heimdall-managed credential; Spotiverse does not own Spotify refresh-token custody. - - Heimdall's first Odin/Eve daemon boundary publication remains secret-safe: it writes only provider advertisement, command boundary, transport profile, and daemon-health summary state, not per-account auth truth. - - Heimdall owns its persistent provider-health signing identity and signed observations; Idunn owns root-bound admission and the public provider-health projection. Unsigned health is never lifecycle authority. - - Heimdall owns OAuth attempts and completion redemption; the Eve access plugin and browser can project or carry one opaque handle but cannot grant access. - - Private auth commands are app-secret, source-runtime, expiry, nonce, and idempotency bound; sensitive completion claims remain AES-GCM wrapped until the app backend receives them. - - Refresh and logout are exact persisted-session transitions. App/account custody and access revision must match; logout advances the revision and stale refresh cannot recreate the session. - - Persistent state cruft is the same failure class as architecture cruft. - -data_flow: - observe: - - task request - - shared architecture note - - app profile bindings - - current app/runtime seams in Repixelizer and StreamPixels - - Yggdrasil host topology and nginx/service shape - process: - - rehydrate from canonical state - - choose one bounded architecture or implementation slice - - keep auth authority and app-domain data boundaries explicit - - keep routine route auth local after claim verification - - record only belief-changing evidence - - commit or backtrack - cut: - - reject shared-data creep - - reject duplicated auth blobs per app - - reject per-request auth round-trip chatter - -active_subgoals: - - Joystick H1 is merged and live (PR GameCult/Heimdall#1, d51fa6b; campaign joystick:campaign:self). Open follow-ups by id: joystick:follow_up:h1-joystick-consent-round-trip (next), cross-process-failed-refresh-marker, connect-start-needs-app-auth, heimdall-idunn-onboarding, joystick-viewer-signin-public-bot. StreamPixels S0/S1 run in other sessions. - - OPEN, behind the H1 live round-trips: pressure the deployed Ghostlight gamecult.heimdall.access integration with two- and eight-account human canaries. - - Keep the shared architecture explicit and separate from app profiles. - - Preserve the default boundary that app-domain data remains app-owned. - - Align the plan to Heimdall as a Yggdrasil-hosted authority service. - - Publish Heimdall daemon health and boundary state for Idunn/Odin without moving auth truth out of Heimdall. - - Verify the Discord and Patreon Repixelizer auth paths with real provider credentials, stable signing, persistent storage, and live browser callback verification. - - Wire StreamPixels through Heimdall for Twitch/YouTube (Joystick joins under H1) viewer identity and managed creator-provider credentials without moving StreamPixels domain state into Heimdall. - -accepted_design: - - `gamecult.heimdall.access` owns access-gate representation and browser navigation semantics; it has no access-grant or provider-state authority. - - Heimdall's loopback CultNet operation service owns authenticated auth begin/complete commands, while retained HTTP integrations remain supported for existing consumers. - - Ghostlight refresh and logout use the same private CultNet boundary; refresh re-evaluates the caller-owned KLTST policy and logout revokes exact Heimdall session custody. - - `docs/architecture.md` is the canonical shared architecture note. - - `docs/service-contract.md` records the concrete HTTP/JWKS contract of the landed service slice. - - `docs/app-profiles/*.md` are thin app bindings, not duplicate brains. - - Heimdall owns provider OAuth, identity linking, signed local sessions, grants, entitlement refresh, capability evaluation, and audit events. - - Host apps own their domain data, runtime state, and product-specific resources. - - Host apps verify signed claims locally for routine route authorization. - - A shared Heimdall store, if it exists, should hold auth/control-plane truth only. - - Repixelizer is the first auth-blank hosted-app binding. - - StreamPixels is the migration case that proves shared authority must not imply audience-data centralization. - - The first service skeleton is a standalone TypeScript/Fastify app with Ed25519 JWT signing, JWKS discovery, signed OAuth `state`, and app-profile-driven shared capability evaluation. - - The first stateful slice adds durable auth/control-plane storage plus a real Discord callback path for Repixelizer. - - Repixelizer has consumed the Heimdall backend-callback flow in its hosted web layer; Heimdall no longer needs to wait on Repixelizer refactoring before live Discord launch work. - - Heimdall is deployed on Yggdrasil at `https://heimdall.gamecult.org` with nginx/TLS, Postgres storage, file-backed signing-key bootstrap, configured token custody, and passing public health/discovery/JWKS checks. - - Heimdall now issues signed app refresh tokens alongside short-lived access claims and exposes `/v1/apps/{appSlug}/sessions/refresh` so app backends can reissue local claims without restarting provider OAuth. - - Discord and Patreon provider access tokens can refresh inside Heimdall before Repixelizer entitlement re-evaluation. - - Repixelizer is deployed on Yggdrasil at `https://repixelizer.gamecult.org` with `GC_ACCESS_MODE=heimdall`, `GC_ACCESS_ALLOWED_PROVIDERS=discord,patreon`, required access, queue protection enabled, app-owned Discord guild/role policy, and app-owned Patreon tier-title policy sent to Heimdall during backend-callback OAuth start. - - StreamPixels viewer and creator provider OAuth should start through Heimdall; StreamPixels redeems one-time completion codes, owns local profile/connector binding, and resolves current provider access tokens from Heimdall by app-authenticated managed-credential calls. - - Bifrost is a Heimdall app profile for Discord/Patreon member access. Bifrost owns the KTLST Discord role policy and Patreon tier policy; Heimdall owns provider OAuth, token custody, entitlement evaluation, and configured backend callback trust. - - Bifrost patron support sync reuses Heimdall's existing linked Patreon identity and membership reader. Heimdall turns active paid Patreon tier evidence into signed support facts; Bifrost owns point/tier/vote derivation. - - Heimdall's first runtime Verse cut publishes a service-owned CultCache boundary store and optional Idunn RUDP health pulse; full redacted auth-document witness export remains a later pass. - -landed_baseline: - - Heimdall publishes its redacted provider, command boundary, Eve plugin, and transport profile through Odin under globally unique record keys; Ghostlight resolves that boundary instead of owning a direct endpoint. - - Yggdrasil runs Heimdall d51fa6b (hand-deployed 2026-10-19 15:51Z; gamecult-ops 210a1af holds backup, rollback and provenance; prior 1086aee) with CultLib 5cefa0db0079a8e3ee22f29d7b9e6e5aa60912a9; live Ghostlight auth.begin through Odin discovery is accepted. - - The Heimdall access plugin, persistent OAuth attempts, encrypted private CultNet commands, conformance fixtures, and browser reference adapter are implemented and locally verified. - - Exact-session refresh validation and logout revocation are implemented; stale or racing refresh cannot resurrect a revoked session. - - Shared architecture extracted into its own repo and renamed to Heimdall. - - Repixelizer and StreamPixels app-profile notes created. - - Repo-local state, handoff, and compaction scaffolding created. - - Initial Heimdall service skeleton landed with discovery, JWKS, OAuth start/callback contract surfaces, and claim issuance scaffolding. - - Durable auth persistence landed for accounts, linked identities, sessions, grants, entitlement snapshots, and audit events. - - The first real provider slice landed for Discord callback exchange, identity resolution, entitlement evaluation, and session/claim issuance for Repixelizer. - - Signing-key persistence/bootstrap, managed token encryption at rest, and a local verifier seam landed for the first real consumer integration pass. - - Direct backend callback handoff landed as the preferred same-host app-consumer path, with browser completion-code exchange retained as fallback. - - Signed session refresh landed for app-facing claims: refresh tokens remain Heimdall-issued, provider refresh tokens remain sealed in Heimdall, and callers can provide app-owned entitlement policies for re-evaluation. - - Repixelizer's hosted web layer now creates Heimdall auth attempts, receives direct backend callbacks, verifies Heimdall Ed25519 access tokens locally, and adopts httpOnly local sessions. - - Heimdall now has generic Twitch and YouTube OAuth callback runtimes plus an app-authenticated managed-credential resolve endpoint for app-owned connector runtimes. - - StreamPixels now starts viewer and creator Twitch/YouTube OAuth through Heimdall, redeems Heimdall completion codes server-side, writes its own viewer sessions and creator connector bindings, and leaves provider refresh-token custody in Heimdall. - - Spotiverse now has a Heimdall app profile and Spotify provider runtime for managed credential custody. - - Bifrost now has a Heimdall app profile for Discord/Patreon member access, and backend callback trust is checked through configured app callback allowlists before legacy app-specific defaults. - - Heimdall exposes `POST /v1/apps/bifrost/patron-support/sync` as an app-authenticated bridge from linked Patreon membership evidence to Bifrost's signed patron support intake endpoint. - - A read-only `gamecult.eve.provider_advertisement.v1` export now advertises Heimdall provider/app surfaces plus redacted CultCache witness document paths for Odin/Eve discovery. - - Heimdall now writes a daemon-owned `GC_ACCESS_CULTCACHE_PATH` boundary store containing provider advertisement, command boundary, transport profile, and daemon-health summary state, and it can publish `heimdall.cultnet-rudp-provider-health` to Idunn over `cultnet.transport.rudp.v0` when configured. - - Heimdall now persists a machine-bound Ed25519 provider-health identity, publishes canonical `idunn.signed_daemon_health.v1` records on an independent sequential pulse loop, and is admitted by Idunn through an exact root trust binding. - -rejected_paths: - - name: per_app_auth_copy_paste - reason: duplicates the same provider/session sludge across every experiment - - name: per_request_auth_round_trip - reason: turns shared auth into a noisy bottleneck instead of local claim verification - - name: shared_user_data_swamp - reason: reusing auth mechanics does not justify centralizing app-domain audience or product data - -current_status: - summary: Yggdrasil runs Heimdall release d51fa6b (hand-deployed 2026-10-19 15:51Z, gamecult-ops 210a1af), which includes Joystick H1 (PR #1). The plugin and encrypted loopback begin, complete, refresh and logout plane, the Odin discovery records and Ghostlight resolution were verified at 1086aee (2026-08-22) and are not re-verified at d51fa6b. - next_action: Run joystick:follow_up:h1-joystick-consent-round-trip, then StreamPixels S0/S1 (other sessions). Still open behind that: separate-account KLTST completion, refresh, logout, privacy, and stale-attempt canaries through the deployed Ghostlight Eve host; keep provider credential rotation on the operator list because prior tool output exposed OAuth secrets. diff --git a/state/scratch.md b/state/scratch.md deleted file mode 100644 index 3f84d3b..0000000 --- a/state/scratch.md +++ /dev/null @@ -1,7 +0,0 @@ -# Scratch - -This file is disposable working memory for the current bounded subgoal. - -## Current Subgoal - -No active scratch subgoal. diff --git a/tools/heimdall_prepare_compaction.py b/tools/heimdall_prepare_compaction.py deleted file mode 100644 index c273586..0000000 --- a/tools/heimdall_prepare_compaction.py +++ /dev/null @@ -1,328 +0,0 @@ -from __future__ import annotations - -import argparse -import json -import re -import subprocess -from dataclasses import dataclass -from pathlib import Path -from typing import Any - - -ROOT = Path(__file__).resolve().parents[1] -STATE_DIR = ROOT / "state" -NOTES_DIR = ROOT / "notes" -DOCS_DIR = ROOT / "docs" - -MAP_PATH = STATE_DIR / "map.yaml" -SCRATCH_PATH = STATE_DIR / "scratch.md" -BRANCHES_PATH = STATE_DIR / "branches.json" -EVIDENCE_PATH = STATE_DIR / "evidence.jsonl" -HANDOFF_PATH = NOTES_DIR / "fresh-workspace-handoff.md" -ARCH_PATH = DOCS_DIR / "architecture.md" -PLAN_PATH = DOCS_DIR / "implementation-plan.md" -AGENTS_PATH = ROOT / "AGENTS.md" - - -@dataclass -class Finding: - level: str - message: str - - -def read_text(path: Path) -> str: - return path.read_text(encoding="utf-8") - - -def run_git(args: list[str]) -> str: - completed = subprocess.run( - ["git", *args], - cwd=ROOT, - check=True, - capture_output=True, - text=True, - ) - return completed.stdout.strip() - - -def extract_map_field(name: str) -> str | None: - prefix = f" {name}:" - for line in read_text(MAP_PATH).splitlines(): - if line.startswith(prefix): - return line.split(":", 1)[1].strip() - return None - - -def extract_active_subgoals() -> list[str]: - lines = read_text(MAP_PATH).splitlines() - results: list[str] = [] - in_section = False - for line in lines: - if not in_section: - if line.strip() == "active_subgoals:": - in_section = True - continue - if line.startswith(" - "): - results.append(line[4:].strip()) - continue - if line and not line.startswith(" "): - break - return results - - -def current_scratch_subgoal() -> str | None: - lines = read_text(SCRATCH_PATH).splitlines() - for index, line in enumerate(lines): - if line.strip() != "## Current Subgoal": - continue - for candidate in lines[index + 1 :]: - stripped = candidate.strip() - if stripped: - return stripped - return None - - -def load_evidence() -> list[dict[str, Any]]: - records: list[dict[str, Any]] = [] - for line_number, line in enumerate(read_text(EVIDENCE_PATH).splitlines(), start=1): - if not line.strip(): - continue - try: - record = json.loads(line) - except json.JSONDecodeError as exc: - raise ValueError(f"evidence line {line_number} is invalid JSON: {exc}") from exc - if not isinstance(record, dict): - raise ValueError(f"evidence line {line_number} is not a JSON object") - records.append(record) - return records - - -def load_branches() -> dict[str, Any]: - data = json.loads(read_text(BRANCHES_PATH)) - if not isinstance(data, dict): - raise ValueError("branches.json must be a JSON object") - branches = data.get("branches") - if not isinstance(branches, list): - raise ValueError("branches.json must contain a branches list") - return data - - -def add_required_file_checks(findings: list[Finding]) -> None: - for path in [ - MAP_PATH, - SCRATCH_PATH, - BRANCHES_PATH, - EVIDENCE_PATH, - HANDOFF_PATH, - ARCH_PATH, - PLAN_PATH, - AGENTS_PATH, - ]: - if path.exists(): - findings.append(Finding("ok", f"found {path.relative_to(ROOT)}")) - else: - findings.append(Finding("error", f"missing {path.relative_to(ROOT)}")) - - -def add_content_checks(findings: list[Finding]) -> tuple[list[dict[str, Any]], dict[str, Any]]: - evidence: list[dict[str, Any]] = [] - branches: dict[str, Any] = {} - - summary = extract_map_field("summary") - next_action = extract_map_field("next_action") - if summary: - findings.append(Finding("ok", "state/map.yaml has current_status.summary")) - else: - findings.append(Finding("error", "state/map.yaml is missing current_status.summary")) - if next_action: - findings.append(Finding("ok", "state/map.yaml has current_status.next_action")) - else: - findings.append(Finding("error", "state/map.yaml is missing current_status.next_action")) - - subgoals = extract_active_subgoals() - if subgoals: - findings.append(Finding("ok", f"state/map.yaml has {len(subgoals)} active subgoal(s)")) - else: - findings.append(Finding("warn", "state/map.yaml has no active_subgoals entries")) - - scratch_subgoal = current_scratch_subgoal() - if scratch_subgoal == "No active scratch subgoal.": - findings.append(Finding("ok", "state/scratch.md has no stale active scratch subgoal")) - elif scratch_subgoal: - findings.append(Finding("warn", f"state/scratch.md has active scratch subgoal: {scratch_subgoal}")) - else: - findings.append(Finding("warn", "state/scratch.md has no Current Subgoal value")) - - try: - evidence = load_evidence() - findings.append(Finding("ok", f"state/evidence.jsonl parses ({len(evidence)} record(s))")) - except ValueError as exc: - findings.append(Finding("error", str(exc))) - - if EVIDENCE_PATH.exists() and EVIDENCE_PATH.stat().st_size > 25_000: - findings.append(Finding("warn", "state/evidence.jsonl is larger than 25 KB; consider distillation")) - - try: - branches = load_branches() - active = [ - branch - for branch in branches.get("branches", []) - if isinstance(branch, dict) and branch.get("status") == "active" - ] - findings.append(Finding("ok", f"state/branches.json parses ({len(active)} active branch(es))")) - except (json.JSONDecodeError, ValueError) as exc: - findings.append(Finding("error", f"branches.json parse failed: {exc}")) - - return evidence, branches - - -def add_handoff_checks(findings: list[Finding]) -> None: - text = read_text(HANDOFF_PATH) - stale_branch = re.search(r"Current branch before .*ahead \d+", text) - stale_head = re.search(r"Current HEAD before .*\b[0-9a-f]{7,40}\b", text) - if stale_branch or stale_head: - findings.append(Finding("error", "handoff embeds an exact branch or HEAD snapshot; use git commands instead")) - else: - findings.append(Finding("ok", "handoff avoids exact branch/HEAD snapshots")) - - required_phrases = [ - "Do not continue implementation automatically from a rehydrate-only request.", - "Do not trust this file for the exact live HEAD.", - "Immediate Re-entry Instruction", - ] - for phrase in required_phrases: - if phrase in text: - findings.append(Finding("ok", f"handoff contains: {phrase}")) - else: - findings.append(Finding("warn", f"handoff missing: {phrase}")) - - -def add_agents_checks(findings: list[Finding]) -> None: - text = read_text(AGENTS_PATH) - if "heimdall_prepare_compaction.py" in text: - findings.append(Finding("ok", "AGENTS.md tells agents to use the compaction helper")) - else: - findings.append(Finding("error", "AGENTS.md does not mention tools/heimdall_prepare_compaction.py")) - if "prepare for imminent compaction" in text.lower(): - findings.append(Finding("ok", "AGENTS.md names the imminent-compaction trigger")) - else: - findings.append(Finding("warn", "AGENTS.md does not name the imminent-compaction trigger phrase")) - - -def add_git_checks(findings: list[Finding]) -> tuple[str, str]: - status = run_git(["status", "--short", "--branch"]) - log = run_git(["log", "--oneline", "-5"]) - dirty_lines = [line for line in status.splitlines()[1:] if line.strip()] - if dirty_lines: - findings.append(Finding("warn", "git worktree has uncommitted changes; commit or explain before compaction")) - else: - findings.append(Finding("ok", "git worktree is clean")) - return status, log - - -def render_report(findings: list[Finding], status: str, log: str, evidence: list[dict[str, Any]]) -> str: - summary = extract_map_field("summary") or "(missing)" - next_action = extract_map_field("next_action") or "(missing)" - subgoals = extract_active_subgoals() - - counts = { - "ok": sum(1 for finding in findings if finding.level == "ok"), - "warn": sum(1 for finding in findings if finding.level == "warn"), - "error": sum(1 for finding in findings if finding.level == "error"), - } - - lines = [ - "Heimdall pre-compaction persistence check", - f"Workspace: {ROOT}", - f"Findings: {counts['ok']} ok, {counts['warn']} warn, {counts['error']} error", - "", - "Git status:", - status, - "", - "Recent commits:", - log, - "", - f"Summary: {summary}", - f"Next action: {next_action}", - ] - if subgoals: - lines.append("Active subgoals:") - lines.extend(f"- {item}" for item in subgoals) - if evidence: - latest = evidence[-1] - lines.extend( - [ - "", - "Latest distilled evidence:", - f"- {latest.get('ts', '(missing ts)')} {latest.get('type', '(missing type)')}/{latest.get('status', '(missing status)')}: {latest.get('note', '(missing note)')}", - ] - ) - - lines.append("") - lines.append("Findings:") - for finding in findings: - lines.append(f"[{finding.level.upper()}] {finding.message}") - - lines.extend( - [ - "", - "Pre-compaction checklist:", - "- Update state/map.yaml only if current understanding changed.", - "- Refresh notes/fresh-workspace-handoff.md if re-entry instructions changed.", - "- Add distilled evidence only for a belief-changing lesson, verification, rejected path, or scar.", - "- Keep exact branch/HEAD out of handoff prose; git commands own volatile truth.", - "- Commit completed persistence changes, or state why the worktree must stay dirty.", - "- Re-run this helper after edits before yielding to compaction.", - ] - ) - return "\n".join(lines) - - -def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser( - description="Audit Heimdall persistent state before imminent compaction." - ) - parser.add_argument( - "--strict", - action="store_true", - help="Exit nonzero on warnings as well as errors.", - ) - return parser - - -def main() -> int: - args = build_parser().parse_args() - findings: list[Finding] = [] - evidence: list[dict[str, Any]] = [] - - add_required_file_checks(findings) - try: - evidence, _branches = add_content_checks(findings) - except OSError as exc: - findings.append(Finding("error", f"state content check failed: {exc}")) - try: - add_handoff_checks(findings) - except OSError as exc: - findings.append(Finding("error", f"handoff check failed: {exc}")) - try: - add_agents_checks(findings) - except OSError as exc: - findings.append(Finding("error", f"AGENTS check failed: {exc}")) - try: - status, log = add_git_checks(findings) - except (OSError, subprocess.CalledProcessError) as exc: - findings.append(Finding("error", f"git check failed: {exc}")) - status = "(git status unavailable)" - log = "(git log unavailable)" - - print(render_report(findings, status, log, evidence)) - - has_error = any(finding.level == "error" for finding in findings) - has_warning = any(finding.level == "warn" for finding in findings) - if has_error or (args.strict and has_warning): - return 1 - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/heimdall_state.py b/tools/heimdall_state.py deleted file mode 100644 index d4aa50a..0000000 --- a/tools/heimdall_state.py +++ /dev/null @@ -1,179 +0,0 @@ -from __future__ import annotations - -import argparse -import json -from datetime import datetime, timezone -from pathlib import Path -from typing import Any - - -ROOT = Path(__file__).resolve().parents[1] -STATE_DIR = ROOT / "state" -MAP_PATH = STATE_DIR / "map.yaml" -BRANCHES_PATH = STATE_DIR / "branches.json" -EVIDENCE_PATH = STATE_DIR / "evidence.jsonl" - - -def read_text(path: Path) -> str: - return path.read_text(encoding="utf-8") - - -def write_text(path: Path, content: str) -> None: - path.write_text(content, encoding="utf-8") - - -def load_branches() -> dict[str, Any]: - return json.loads(read_text(BRANCHES_PATH)) - - -def save_branches(data: dict[str, Any]) -> None: - write_text(BRANCHES_PATH, json.dumps(data, indent=2) + "\n") - - -def append_evidence(record: dict[str, Any]) -> None: - with EVIDENCE_PATH.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(record, ensure_ascii=True) + "\n") - - -def utc_stamp() -> str: - return datetime.now(timezone.utc).replace(microsecond=0).isoformat() - - -def extract_map_field(name: str) -> str | None: - prefix = f" {name}:" - for line in read_text(MAP_PATH).splitlines(): - if line.startswith(prefix): - return line.split(":", 1)[1].strip() - return None - - -def extract_active_subgoals() -> list[str]: - lines = read_text(MAP_PATH).splitlines() - results: list[str] = [] - in_section = False - for line in lines: - if not in_section: - if line.strip() == "active_subgoals:": - in_section = True - continue - if line.startswith(" - "): - results.append(line[4:].strip()) - continue - if line and not line.startswith(" "): - break - return results - - -def cmd_status(_: argparse.Namespace) -> int: - branches = load_branches().get("branches", []) - active = [branch for branch in branches if branch.get("status") == "active"] - summary = extract_map_field("summary") or "(missing)" - next_action = extract_map_field("next_action") or "(missing)" - subgoals = extract_active_subgoals() - - print(f"Workspace: {ROOT}") - print(f"Summary: {summary}") - print(f"Next action: {next_action}") - print(f"Active branches: {len(active)} / {len(branches)}") - if subgoals: - print("Active subgoals:") - for item in subgoals: - print(f"- {item}") - return 0 - - -def cmd_add_evidence(args: argparse.Namespace) -> int: - record: dict[str, Any] = { - "ts": utc_stamp(), - "type": args.type, - "status": args.status, - "note": args.note, - } - if args.branch: - record["branch"] = args.branch - append_evidence(record) - print("Appended evidence record.") - return 0 - - -def cmd_add_branch(args: argparse.Namespace) -> int: - data = load_branches() - branches = data.setdefault("branches", []) - if any(branch.get("id") == args.id for branch in branches): - raise SystemExit(f"Branch '{args.id}' already exists.") - branches.append( - { - "id": args.id, - "hypothesis": args.hypothesis, - "status": "active", - "artifacts": args.artifact or [], - "notes": args.note or "", - } - ) - save_branches(data) - print(f"Added branch '{args.id}'.") - return 0 - - -def cmd_close_branch(args: argparse.Namespace) -> int: - data = load_branches() - for branch in data.get("branches", []): - if branch.get("id") != args.id: - continue - branch["status"] = args.status - if args.note: - branch["notes"] = args.note - save_branches(data) - print(f"Updated branch '{args.id}' to status '{args.status}'.") - return 0 - raise SystemExit(f"Branch '{args.id}' was not found.") - - -def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser( - description="Inspect and update Heimdall persistent state files." - ) - subparsers = parser.add_subparsers(dest="command", required=True) - - status_parser = subparsers.add_parser("status", help="Show a compact state summary.") - status_parser.set_defaults(func=cmd_status) - - evidence_parser = subparsers.add_parser( - "add-evidence", help="Append one distilled JSONL evidence record." - ) - evidence_parser.add_argument("--type", required=True) - evidence_parser.add_argument("--status", required=True) - evidence_parser.add_argument("--note", required=True) - evidence_parser.add_argument("--branch") - evidence_parser.set_defaults(func=cmd_add_evidence) - - add_branch_parser = subparsers.add_parser( - "add-branch", help="Create a new active branch entry." - ) - add_branch_parser.add_argument("--id", required=True) - add_branch_parser.add_argument("--hypothesis", required=True) - add_branch_parser.add_argument("--artifact", action="append") - add_branch_parser.add_argument("--note") - add_branch_parser.set_defaults(func=cmd_add_branch) - - close_branch_parser = subparsers.add_parser( - "close-branch", help="Close an existing branch." - ) - close_branch_parser.add_argument("--id", required=True) - close_branch_parser.add_argument( - "--status", required=True, choices=["accepted", "rejected", "archived"] - ) - close_branch_parser.add_argument("--note") - close_branch_parser.set_defaults(func=cmd_close_branch) - - return parser - - -def main() -> int: - parser = build_parser() - args = parser.parse_args() - return args.func(args) - - -if __name__ == "__main__": - raise SystemExit(main()) From 4ce6ab536e88f158fb81a66b25ae3d6f3d870461 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:08:14 +0100 Subject: [PATCH 56/63] Steward cut 2: replace SQL predicate compiler and TEMP TABLE ceremony with minimal table existence check --- src/store/index.ts | 8 +- src/store/postgres.ts | 286 ++------------------------------ src/store/schema.ts | 97 ++--------- tests/store.test.ts | 376 +++++------------------------------------- 4 files changed, 63 insertions(+), 704 deletions(-) diff --git a/src/store/index.ts b/src/store/index.ts index 69abbe6..18c52d5 100644 --- a/src/store/index.ts +++ b/src/store/index.ts @@ -32,13 +32,7 @@ export async function createStore(config: HeimdallConfig): Promise undefined); - // A role that may not create temporary tables is not a bad URL, so that - // refusal names the privilege instead. - const remedy = - code === "SCHEMA_TEMP_PRIVILEGE" - ? "grant the database role TEMPORARY on its database" - : "check GC_ACCESS_DATABASE_URL_FILE"; - throw new Error(`Postgres storage could not be prepared (${typeof code === "string" ? code : "error"}); ${remedy}.`); + throw new Error(`Postgres storage could not be prepared (${typeof code === "string" ? code : "error"}); check GC_ACCESS_DATABASE_URL_FILE.`); } return store; diff --git a/src/store/postgres.ts b/src/store/postgres.ts index f0da059..6469101 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -2,7 +2,7 @@ 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 { CORE_TABLES, CREATE_SCHEMA_SQL } from "./schema.js"; import { type CreateAccountInput, type CreateAuthAttemptInput, @@ -411,279 +411,6 @@ function mapAuthAttemptRow(row: AuthAttemptRow): StoredAuthAttempt { return attempt; } -/** - * The AND-ed conditions of a predicate as Postgres prints it, each without a - * pair of parentheses that encloses all of it. Postgres flattens a chain of - * ANDs into one list, so `((a) AND (b) AND (c))` yields `a`, `b`, `c`. An OR, - * or an AND nested under one, stays whole: `((a OR b) AND c)` yields `a OR b` - * and `c`, and `(a OR (b AND c))` yields itself. Quoted text is never split. - */ -export function predicateConditions(printed: string): string[] { - const unwrap = (text: string): string => { - let current = text.trim(); - while (current.startsWith("(") && closingParenthesis(current, 0) === current.length - 1) { - current = current.slice(1, -1).trim(); - } - return current; - }; - const whole = unwrap(printed); - if (whole === "") return []; - const parts: string[] = []; - let depth = 0; - let quote: string | undefined; - let start = 0; - for (let position = 0; position < whole.length; position += 1) { - const character = whole[position]!; - if (quote) { - if (character === quote) quote = undefined; - } else if (character === "'" || character === '"') { - quote = character; - } else if (character === "(") { - depth += 1; - } else if (character === ")") { - depth -= 1; - } else if (depth === 0 && whole.startsWith(" AND ", position)) { - parts.push(whole.slice(start, position)); - start = position + " AND ".length; - position = start - 1; - } - } - parts.push(whole.slice(start)); - return parts.map(unwrap); -} - -/** The index of the parenthesis closing the one at `open`, outside quoted text, or -1. */ -function closingParenthesis(text: string, open: number): number { - let depth = 0; - let quote: string | undefined; - for (let position = open; position < text.length; position += 1) { - const character = text[position]!; - if (quote) { - if (character === quote) quote = undefined; - } else if (character === "'" || character === '"') { - quote = character; - } else if (character === "(") { - depth += 1; - } else if (character === ")") { - depth -= 1; - if (depth === 0) return position; - } - } - return -1; -} - -/** - * Whether an index predicate, as Postgres prints it, keeps exactly the rows - * the declared one (printed the same way) does: the same set of AND-ed - * conditions, ignoring `key_column IS NOT NULL` unless the index treats NULLs - * as equal, since otherwise rows with a NULL key never collide anyway. - */ -export function samePredicate(declared: string, actual: string, keyColumns: string[], nullsNotDistinct: boolean): boolean { - // A key without a predicate must have none: ON CONFLICT cannot infer a - // partial index as its arbiter. - if (predicateConditions(declared).length === 0) return actual.trim() === ""; - const redundant = new Set(nullsNotDistinct ? [] : keyColumns.map((column) => `${column} IS NOT NULL`)); - const conditions = (printed: string) => - [...new Set(predicateConditions(printed).filter((condition) => !redundant.has(condition)))].sort(); - const left = conditions(declared); - const right = conditions(actual); - return left.length === right.length && left.every((condition, index) => condition === right[index]); -} - -/** - * 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. - * audit_events is written and never read back. - */ -export const STORE_TABLE_PRIVILEGES: Readonly> = { - accounts: ["SELECT", "INSERT", "UPDATE"], - linked_identities: ["SELECT", "INSERT", "UPDATE", "DELETE"], - sessions: ["SELECT", "INSERT", "UPDATE"], - auth_attempts: ["SELECT", "INSERT", "UPDATE"], - private_command_receipts: ["SELECT", "INSERT"], - auth_completions: ["SELECT", "INSERT", "UPDATE"], - pending_links: ["SELECT", "INSERT", "UPDATE"], - oauth_state_uses: ["SELECT", "INSERT", "DELETE"], - capability_grants: ["SELECT", "INSERT"], - entitlement_snapshots: ["SELECT", "INSERT", "UPDATE"], - consent_receipts: ["SELECT", "INSERT"], - identity_moves: ["SELECT", "INSERT"], - audit_events: ["INSERT"], -}; - -/** What a database must hold for a store to serve it; see checkSchemaRequirements. */ -export interface SchemaRequirements { - tables: readonly string[]; - columns: readonly { table: string; column: string; type: string; nullable: boolean }[]; - keys: readonly { table: string; columns: string; predicate: string }[]; - privileges: Readonly>; -} - -/** What Heimdall's store needs, read from its schema and its statements. */ -export const HEIMDALL_SCHEMA_REQUIREMENTS: SchemaRequirements = { - tables: REQUIRED_TABLES, - columns: REQUIRED_COLUMNS, - keys: REQUIRED_KEYS, - privileges: STORE_TABLE_PRIVILEGES, -}; - -/** - * Each required key's predicate as Postgres prints it back (empty for none). - * One simple-protocol round trip on one connection: a transaction that builds - * a temporary copy of each keyed table's declared columns, indexes it with the - * declared predicate, reads the printed form and rolls back. The names and SQL - * come from the requirements, which are constants, never input. A role that - * may not create temporary tables fails with code SCHEMA_TEMP_PRIVILEGE. - */ -export async function printedDeclaredPredicates(pool: Pick, requirements: SchemaRequirements): Promise { - const partial = requirements.keys.flatMap((required, index) => (required.predicate ? [{ ...required, index }] : [])); - if (partial.length === 0) return requirements.keys.map(() => ""); - const statements = partial.flatMap(({ table, columns, predicate, index }) => { - const probe = `heimdall_key_probe_${index}`; - const declared = requirements.columns - .filter((column) => column.table === table) - .map((column) => `${column.column} ${column.type}`) - .join(", "); - return [ - `CREATE TEMP TABLE ${probe} (${declared}) ON COMMIT DROP`, - `CREATE UNIQUE INDEX ${probe}_idx ON ${probe} (${columns}) WHERE ${predicate}`, - ]; - }); - const select = partial - .map(({ index }) => `SELECT ${index} AS key, pg_get_expr(indpred, indrelid) AS predicate FROM pg_index WHERE indexrelid = 'pg_temp.heimdall_key_probe_${index}_idx'::regclass`) - .join(" UNION ALL "); - let results: Array<{ rows: Array<{ key: number; predicate: string }> }>; - try { - results = (await pool.query(["BEGIN", ...statements, select, "ROLLBACK"].join(";\n"))) as unknown as typeof results; - } catch (error) { - if ((error as { code?: unknown }).code === "42501") { - throw Object.assign(new Error("The Heimdall database role may not create temporary tables."), { code: "SCHEMA_TEMP_PRIVILEGE" }); - } - throw error; - } - const printed = results[results.length - 2]!.rows; - return requirements.keys.map((_, index) => printed.find((row) => row.key === index)?.predicate ?? ""); -} - -/** - * Proves that the database can take a store's requests: every required - * table; every column with its declared type, under a deterministic - * collation, and nullable where declared nullable; every unique key; and - * every privilege, held on the table or on each of its columns. A missing or - * altered piece fails with code SCHEMA_MISSING and a missing privilege with - * SCHEMA_PRIVILEGES; neither error names the piece. - * - * A key is met by a unique index on its table that is valid (a failed - * CREATE INDEX CONCURRENTLY or an interrupted DROP INDEX CONCURRENTLY leaves - * one that is not; Postgres never marks an index valid before it is ready), - * immediate (ON CONFLICT refuses a deferrable arbiter), has exactly the key's - * columns as its key columns (INCLUDE columns aside), compares them under - * deterministic collations (a case-insensitive one would merge two - * providers' user ids into one row), and has the key's predicate. A - * predicate matches when both, as Postgres prints them, are the same set of - * AND-ed conditions; a `key_column IS NOT NULL` condition may be absent on - * either side, because a unique index never makes NULL keys collide unless - * it is NULLS NOT DISTINCT. Postgres prints the declared predicates itself - * (printedDeclaredPredicates). - * - * What this does not prove is listed where the schema is: see schema.ts. - */ -export async function checkSchemaRequirements(pool: Pick, requirements: SchemaRequirements): Promise { - const declaredPredicates = await printedDeclaredPredicates(pool, requirements); - const privileges = Object.entries(requirements.privileges).flatMap(([table, wanted]) => - wanted.map((privilege) => ({ table, privilege })) - ); - const result = await pool.query<{ - kind: "missing" | "privilege" | "candidate"; - key: number | null; - predicate: string | null; - nulls_not_distinct: boolean | null; - }>( - ` - SELECT 'missing' AS kind, NULL::int AS key, NULL::text AS predicate, NULL::boolean AS nulls_not_distinct - FROM unnest($1::text[]) AS name WHERE to_regclass(name) IS NULL - UNION ALL - SELECT 'missing', NULL, NULL, NULL - FROM unnest($2::text[], $3::text[], $4::text[], $5::boolean[]) AS required(table_name, column_name, type_name, nullable) - WHERE NOT EXISTS ( - SELECT 1 FROM pg_attribute a - WHERE a.attrelid = to_regclass(required.table_name) - AND a.attname = required.column_name - AND a.attnum > 0 - AND NOT a.attisdropped - AND a.atttypid = to_regtype(required.type_name) - AND (NOT required.nullable OR NOT a.attnotnull) - AND NOT EXISTS (SELECT 1 FROM pg_collation c WHERE c.oid = a.attcollation AND NOT c.collisdeterministic) - ) - UNION ALL - SELECT 'candidate', required.key::int, pg_get_expr(i.indpred, i.indrelid), - coalesce((to_jsonb(i) ->> 'indnullsnotdistinct')::boolean, false) - FROM unnest($6::text[], $7::text[]) WITH ORDINALITY AS required(table_name, columns, key) - JOIN pg_index i ON i.indrelid = to_regclass(required.table_name) - WHERE i.indisunique - AND i.indisvalid - AND i.indimmediate - AND i.indnkeyatts = cardinality(string_to_array(required.columns, ',')) - AND ( - SELECT string_agg(a.attname, ',' ORDER BY a.attname) - FROM unnest(i.indkey::int2[]) WITH ORDINALITY AS key(attnum, position) - JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = key.attnum - WHERE key.position <= i.indnkeyatts - ) = required.columns - AND NOT EXISTS ( - SELECT 1 FROM unnest(i.indcollation::oid[]) WITH ORDINALITY AS key_collation(oid, position) - JOIN pg_collation c ON c.oid = key_collation.oid - WHERE key_collation.position <= i.indnkeyatts AND NOT c.collisdeterministic - ) - UNION ALL - SELECT 'privilege', NULL, NULL, NULL - FROM unnest($8::text[], $9::text[]) AS required(table_name, privilege) - WHERE EXISTS ( - SELECT 1 FROM unnest($2::text[], $3::text[]) AS used(table_name, column_name) - JOIN pg_attribute a ON a.attrelid = to_regclass(used.table_name) AND a.attname = used.column_name AND NOT a.attisdropped - WHERE used.table_name = required.table_name - AND NOT CASE WHEN required.privilege = 'DELETE' - THEN has_table_privilege(a.attrelid, 'DELETE') -- DELETE is a row privilege, never held per column - ELSE has_column_privilege(a.attrelid, a.attnum, required.privilege) END - ) - `, - [ - requirements.tables, - requirements.columns.map((required) => required.table), - requirements.columns.map((required) => required.column), - requirements.columns.map((required) => required.type), - requirements.columns.map((required) => required.nullable), - requirements.keys.map((required) => required.table), - requirements.keys.map((required) => required.columns), - privileges.map((required) => required.table), - privileges.map((required) => required.privilege), - ] - ); - const keyMet = requirements.keys.map((required, index) => - result.rows.some( - (row) => - row.kind === "candidate" && - row.key === index + 1 && - samePredicate(declaredPredicates[index]!, row.predicate ?? "", required.columns.split(","), row.nulls_not_distinct === true) - ) - ); - if (result.rows.some((row) => row.kind === "missing") || keyMet.includes(false)) { - throw Object.assign(new Error("The Heimdall schema is not applied."), { code: "SCHEMA_MISSING" }); - } - if (result.rows.some((row) => row.kind === "privilege")) { - throw Object.assign(new Error("The Heimdall database role lacks a privilege the store needs."), { - code: "SCHEMA_PRIVILEGES", - }); - } -} - export class PostgresStore implements HeimdallStore { constructor(private readonly pool: Pick) {} @@ -691,9 +418,16 @@ export class PostgresStore implements HeimdallStore { await this.pool.query(CREATE_SCHEMA_SQL); } - /** Proves, before Heimdall serves, that the database can take its requests (checkSchemaRequirements). */ + /** Verifies database connectivity and that the core schema tables exist. */ async checkSchema(): Promise { - await checkSchemaRequirements(this.pool, HEIMDALL_SCHEMA_REQUIREMENTS); + await this.pool.query("SELECT 1"); + const result = await this.pool.query<{ name: string }>( + "SELECT name FROM unnest($1::text[]) AS name WHERE to_regclass('public.' || name) IS NULL", + [CORE_TABLES] + ); + if (result.rows.length > 0) { + throw Object.assign(new Error("The Heimdall schema is not applied."), { code: "SCHEMA_MISSING" }); + } } async close(): Promise { diff --git a/src/store/schema.ts b/src/store/schema.ts index ff1fcf2..b91139f 100644 --- a/src/store/schema.ts +++ b/src/store/schema.ts @@ -253,85 +253,18 @@ CREATE INDEX IF NOT EXISTS audit_events_lookup_idx ON audit_events(account_id, session_id, app_slug, created_at); `; -const schemaText = CREATE_SCHEMA_SQL.replace(/\r\n/g, "\n"); -const createdTables = [...schemaText.matchAll(/^CREATE TABLE IF NOT EXISTS (\w+) \(\n([\s\S]*?)\n\);/gm)].map((match) => ({ - table: match[1]!, - lines: match[2]!.split("\n").map((line) => line.trim().replace(/,$/, "")), -})); - -/** Sorted and comma-separated, the form the schema check compares key columns in. */ -function columnList(text: string): string { - return text.split(",").map((column) => column.trim()).sort().join(","); -} - -/** The columns of a `PRIMARY KEY (a, b)` or `UNIQUE(a, b)` line, as a column list. */ -function keyColumns(line: string, keyword: "PRIMARY KEY" | "UNIQUE"): string | undefined { - const match = new RegExp(`^${keyword}\\s*\\(([^)]*)\\)`).exec(line); - return match ? columnList(match[1]!) : undefined; -} - -/* - * What every start must find before it serves, read from the SQL above so the - * two cannot drift. A start that applies the schema checks as well, because - * CREATE ... IF NOT EXISTS leaves a damaged table as it is. Indexes that only - * speed lookups are not required; the unique ones are, by shape, in - * REQUIRED_KEYS. - * - * Out of scope, each able to make a write fail on a database that passes the - * check: CHECK constraints; triggers; row-level security; unique indexes - * beyond the required keys, or stricter than them, including the leftovers of - * an interrupted concurrent index build (a valid extra one refuses rows the - * store expects to write, and even an invalid one that is ready is enforced - * on writes); NOT NULL columns the schema does not declare and that have no - * default, which the store's INSERTs leave out; and SELECT granted column by - * column when a statement reads `SELECT *` or `RETURNING *`, which needs - * SELECT on every column the table has, not only the declared ones. - */ - -/** Every table the schema creates. */ -export const REQUIRED_TABLES = createdTables.map(({ table }) => table); - -/** - * Every column a created table declares and every column the schema adds to - * an existing table, each with its declared type, and whether it is nullable: - * the store reads and writes values as that type, and leaves a nullable - * column null, so a column retyped or made NOT NULL under it fails its writes. - */ -export const REQUIRED_COLUMNS = [ - ...createdTables.flatMap(({ table, lines }) => - lines - .filter((line) => !/^(?:PRIMARY KEY|UNIQUE|FOREIGN KEY)\b/.test(line)) - .map((line) => { - const [, column, type] = /^(\w+) (\w+)/.exec(line)!; - return { table, column: column!, type: type!, nullable: !/\b(?:NOT NULL|PRIMARY KEY)\b/.test(line) }; - }) - ), - ...[...schemaText.matchAll(/^ALTER TABLE (\w+) ADD COLUMN IF NOT EXISTS (\w+) (\w+)([^;]*);/gm)].map((match) => ({ - table: match[1]!, - column: match[2]!, - type: match[3]!, - nullable: !/\b(?:NOT NULL|PRIMARY KEY)\b/.test(match[4]!), - })), -]; - -/** - * Every unique key the schema makes: the primary keys and unique constraints - * of the created tables, and each unique index it creates, with that index's - * predicate as the schema writes it (empty for none). Any index of the right - * shape serves, whatever its name; PostgresStore.checkSchema says what the - * right shape is. - */ -export const REQUIRED_KEYS = [ - ...createdTables.flatMap(({ table, lines }) => - lines.flatMap((line) => { - const columns = - /^(\w+) .*\bPRIMARY KEY\b/.exec(line)?.[1] ?? keyColumns(line, "PRIMARY KEY") ?? keyColumns(line, "UNIQUE"); - return columns ? [{ table, columns, predicate: "" }] : []; - }) - ), - ...[...schemaText.matchAll(/^CREATE UNIQUE INDEX IF NOT EXISTS \w+\s+ON (\w+)\(([^)]*)\)(?:\s+WHERE ([^;]+))?;/gm)].map((match) => ({ - table: match[1]!, - columns: columnList(match[2]!), - predicate: (match[3] ?? "").replace(/\s+/g, " ").trim(), - })), -]; +export const CORE_TABLES = [ + "accounts", + "linked_identities", + "sessions", + "auth_attempts", + "private_command_receipts", + "pending_links", + "auth_completions", + "oauth_state_uses", + "capability_grants", + "entitlement_snapshots", + "consent_receipts", + "identity_moves", + "audit_events", +] as const; diff --git a/tests/store.test.ts b/tests/store.test.ts index 03b869a..5a8e7e1 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -4,22 +4,13 @@ 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 { - createPostgresStore, - PostgresStore, - checkSchemaRequirements, - HEIMDALL_SCHEMA_REQUIREMENTS, - predicateConditions, - printedDeclaredPredicates, - samePredicate, - STORE_TABLE_PRIVILEGES, -} from "../src/store/postgres.js"; +import { createPostgresStore, PostgresStore } from "../src/store/postgres.js"; import { OAUTH_STATE_PRUNE_BATCH, OAUTH_STATE_PRUNE_MARGIN_MS, OAUTH_STATE_SKEW_MS, } from "../src/store/types.js"; -import { CREATE_SCHEMA_SQL, REQUIRED_COLUMNS, REQUIRED_KEYS, REQUIRED_TABLES } from "../src/store/schema.js"; +import { CORE_TABLES, CREATE_SCHEMA_SQL } from "../src/store/schema.js"; describe("PostgresStore", () => { it("round-trips core auth records through postgres", async () => { @@ -468,81 +459,35 @@ describe("createPostgresStore", () => { }); describe("PostgresStore.checkSchema", () => { - it("derives every table, typed column and unique key from the schema", () => { - expect(REQUIRED_TABLES).toEqual([ - "accounts", - "linked_identities", - "sessions", - "auth_attempts", - "private_command_receipts", - "pending_links", - "auth_completions", - "oauth_state_uses", - "capability_grants", - "entitlement_snapshots", - "consent_receipts", - "identity_moves", - "audit_events", - ]); - expect(REQUIRED_COLUMNS).toHaveLength(121); - expect(REQUIRED_COLUMNS).toEqual( - expect.arrayContaining([ - { table: "auth_completions", column: "code", type: "TEXT", nullable: false }, - { table: "sessions", column: "access_revision", type: "INTEGER", nullable: false }, - { table: "linked_identities", column: "profile_json", type: "JSONB", nullable: false }, - { table: "linked_identities", column: "username", type: "TEXT", nullable: true }, - { table: "entitlement_snapshots", column: "is_allowed", type: "BOOLEAN", nullable: false }, - { table: "auth_completions", column: "attempt_id", type: "TEXT", nullable: true }, - ]) - ); - expect(REQUIRED_KEYS).toHaveLength(19); - expect(REQUIRED_KEYS).toEqual( - expect.arrayContaining([ - { table: "linked_identities", columns: "provider,provider_user_id", predicate: "" }, - { table: "private_command_receipts", columns: "app_slug,idempotency_key", predicate: "" }, - { 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" }, - ]) - ); + it("runs connectivity check and verifies core tables exist", async () => { + const queries: Array<{ sql: string; params: unknown[] | undefined }> = []; + const store = new PostgresStore({ + query: async (sql: string, params?: unknown[]) => { + queries.push({ sql, params }); + return { rows: [], rowCount: 0 } as never; + }, + end: async () => {}, + connect: async () => ({}) as never, + }); + + await expect(store.checkSchema()).resolves.toBeUndefined(); + expect(queries).toHaveLength(2); + expect(queries[0]!.sql).toBe("SELECT 1"); + expect(queries[1]!.sql).toContain("to_regclass('public.' || name) IS NULL"); + expect(queries[1]!.params).toEqual([CORE_TABLES]); }); - // Soul pass 6: stripping parentheses and case merged predicates of - // different meaning. These are Postgres's own printed forms. - it("splits a printed predicate only at its top-level ANDs", () => { - expect(predicateConditions("((a OR b) AND c)")).toEqual(["a OR b", "c"]); - expect(predicateConditions("(a OR (b AND c))")).toEqual(["a OR (b AND c)"]); - expect(predicateConditions("((attempt_id IS NOT NULL) AND (consumed_at IS NULL))")).toEqual([ - "attempt_id IS NOT NULL", - "consumed_at IS NULL", - ]); - expect(predicateConditions("(s = 'x AND (y'::text)")).toEqual(["s = 'x AND (y'::text"]); - expect(predicateConditions('(("odd AND (name" IS NULL) AND b)')).toEqual(['"odd AND (name" IS NULL', "b"]); - expect(predicateConditions("")).toEqual([]); - }); + it("throws SCHEMA_MISSING when any core table is missing", async () => { + const store = new PostgresStore({ + query: async (sql: string) => { + if (sql === "SELECT 1") return { rows: [], rowCount: 0 } as never; + return { rows: [{ name: "consent_receipts" }], rowCount: 1 } as never; + }, + end: async () => {}, + connect: async () => ({}) as never, + }); - it("matches predicates by their conditions, never by case or by dropping structure", () => { - const keys = ["app_slug", "attempt_id"]; - expect(samePredicate("((a OR b) AND c)", "(a OR (b AND c))", keys, false)).toBe(false); - expect(samePredicate("(s = 'Pending'::text)", "(s = 'pending'::text)", keys, false)).toBe(false); - expect(samePredicate("((a) AND (b))", "((b) AND (a))", keys, false)).toBe(true); - expect(samePredicate("((a) AND (b))", "((a) AND (b) AND (c))", keys, false)).toBe(false); - }); - - it("lets a key column's IS NOT NULL be absent only where NULL keys cannot collide", () => { - const keys = ["app_slug", "attempt_id"]; - const declared = "((attempt_id IS NOT NULL) AND (consumed_at IS NULL))"; - expect(samePredicate(declared, "(consumed_at IS NULL)", keys, false)).toBe(true); - expect(samePredicate(declared, "(consumed_at IS NULL)", keys, true)).toBe(false); - expect(samePredicate(declared, "((consumed_at IS NULL) AND (other IS NOT NULL))", keys, false)).toBe(false); - }); - - it("requires a key without a predicate to have none", () => { - expect(samePredicate("", "", ["id"], false)).toBe(true); - expect(samePredicate("", "(id IS NOT NULL)", ["id"], false)).toBe(false); + await expect(store.checkSchema()).rejects.toMatchObject({ code: "SCHEMA_MISSING" }); }); }); @@ -889,12 +834,10 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD return { name, owner }; } - /** Grants the app role exactly `privileges`, per table, and nothing else. */ - async function grant(owner: Pool, privileges: Readonly>): Promise { + /** Grants the app role standard DML on all core tables. */ + async function grantAppRole(owner: Pool): Promise { await owner.query(`GRANT USAGE ON SCHEMA public TO ${role}`); - for (const [table, wanted] of Object.entries(privileges)) { - if (wanted.length > 0) await owner.query(`GRANT ${wanted.join(", ")} ON ${table} TO ${role}`); - } + await owner.query(`GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO ${role}`); } /** @@ -933,9 +876,9 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD expect(await start(urlFor(name), true)).toBe("started"); }); - it("serves every store operation with exactly the privileges it checks for", async () => { + it("serves every store operation as the app role", async () => { const { name, owner } = await appliedDatabase(); - await grant(owner, STORE_TABLE_PRIVILEGES); + await grantAppRole(owner); expect(await start(urlFor(name, role, rolePassword), false)).toBe("started"); const pool = fixturePool(urlFor(name, role, rolePassword)); @@ -949,44 +892,6 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD expect([...called].sort()).toEqual(offered.sort()); }); - it("refuses each privilege taken away, and the store needs each one", async () => { - const pairs = Object.entries(STORE_TABLE_PRIVILEGES).flatMap(([table, wanted]) => wanted.map((privilege) => ({ table, privilege }))); - expect(Object.keys(STORE_TABLE_PRIVILEGES).sort()).toEqual([...REQUIRED_TABLES].sort()); - for (const { table, privilege } of pairs) { - const { name, owner } = await appliedDatabase(); - await grant(owner, { ...STORE_TABLE_PRIVILEGES, [table]: STORE_TABLE_PRIVILEGES[table]!.filter((p) => p !== privilege) }); - - const message = await start(urlFor(name, role, rolePassword), false); - expect(message, `${table} without ${privilege}`).toBe(refusal("SCHEMA_PRIVILEGES")); - expect(message).not.toContain("CANARY"); - - const pool = fixturePool(urlFor(name, role, rolePassword)); - const failure = await exerciseStore(new PostgresStore(pool)).then( - () => undefined, - (error: unknown) => (error as { code?: string }).code - ); - await pool.end(); - expect(failure, `the store runs without ${privilege} on ${table}, so the check need not ask for it`).toBe("42501"); - for (const step of cleanup.splice(0).reverse()) await step(); - } - }); - - 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)); @@ -1153,7 +1058,7 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD 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); + await grantAppRole(owner); const pool = fixturePool(urlFor(name, role, rolePassword)); cleanup.push(async () => { await pool.end(); @@ -1167,7 +1072,8 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD 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"] }); + await grantAppRole(owner); + await owner.query(`REVOKE DELETE ON oauth_state_uses FROM ${role}`); await seed(owner, "old"); const pool = fixturePool(urlFor(name, role, rolePassword)); cleanup.push(async () => { @@ -1181,223 +1087,15 @@ describe.skipIf(!adminUrl)("startup against a live Postgres (HEIMDALL_TEST_PG_AD it("refuses to apply the schema as a role that may not, and closes the store", async () => { const { name, owner } = await appliedDatabase(); - await grant(owner, STORE_TABLE_PRIVILEGES); + await grantAppRole(owner); expect(await start(urlFor(name, role, rolePassword), true)).toBe(refusal("42501")); }); - it("prints each declared predicate exactly as Postgres prints the applied index's", async () => { - const { owner } = await appliedDatabase(); - const printed = await printedDeclaredPredicates(owner, HEIMDALL_SCHEMA_REQUIREMENTS); - 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()); - for (const [indexName, table] of Object.entries(appliedByIndex)) { - const applied = await owner.query<{ predicate: string }>( - "SELECT pg_get_expr(indpred, indrelid) AS predicate FROM pg_index WHERE indexrelid = $1::regclass", - [indexName] - ); - const { index } = partialKeys.find(({ key }) => key.table === table)!; - expect(printed[index], indexName).toBe(applied.rows[0]!.predicate); - } - expect(printed.filter((predicate) => predicate !== "")).toHaveLength(partialKeys.length); - }); - it("refuses to boot with consent_receipts missing when the schema is not applied on startup", async () => { const { name, owner } = await appliedDatabase(); await owner.query("DROP TABLE consent_receipts"); expect(await start(urlFor(name), false)).toBe(refusal("SCHEMA_MISSING")); }); - - it("refuses a table whose primary key was dropped, even after applying the schema", async () => { - const { name, owner } = await appliedDatabase(); - await owner.query("ALTER TABLE auth_completions DROP CONSTRAINT auth_completions_pkey"); - - expect(await start(urlFor(name), false)).toBe(refusal("SCHEMA_MISSING")); - expect(await start(urlFor(name), true)).toBe(refusal("SCHEMA_MISSING")); - }); - - it("serves every store operation with each privilege granted column by column", async () => { - const { name, owner } = await appliedDatabase(); - await owner.query(`GRANT USAGE ON SCHEMA public TO ${role}`); - for (const [table, wanted] of Object.entries(STORE_TABLE_PRIVILEGES)) { - const columns = REQUIRED_COLUMNS.filter((column) => column.table === table).map((column) => column.column).join(", "); - for (const privilege of wanted) { - // DELETE removes rows and cannot be granted per column. - await owner.query(privilege === "DELETE" ? `GRANT DELETE ON ${table} TO ${role}` : `GRANT ${privilege} (${columns}) ON ${table} TO ${role}`); - } - } - - expect(await start(urlFor(name, role, rolePassword), false)).toBe("started"); - const pool = fixturePool(urlFor(name, role, rolePassword)); - cleanup.push(async () => { - await pool.end(); - }); - await exerciseStore(new PostgresStore(pool)); - }); - - it("refuses a privilege missing on one column of another table", async () => { - const { name, owner } = await appliedDatabase(); - await grant(owner, { ...STORE_TABLE_PRIVILEGES, auth_completions: [] }); - const columns = REQUIRED_COLUMNS.filter((column) => column.table === "auth_completions" && column.column !== "attempt_id") - .map((column) => column.column) - .join(", "); - for (const privilege of STORE_TABLE_PRIVILEGES.auth_completions!) { - await owner.query(`GRANT ${privilege} (${columns}) ON auth_completions TO ${role}`); - } - - expect(await start(urlFor(name, role, rolePassword), false)).toBe(refusal("SCHEMA_PRIVILEGES")); - }); - - it("names the TEMPORARY privilege when the role may not create temporary tables", async () => { - const { name, owner } = await appliedDatabase(); - await grant(owner, STORE_TABLE_PRIVILEGES); - await owner.query(`REVOKE TEMPORARY ON DATABASE ${name} FROM PUBLIC`); - - expect(await start(urlFor(name, role, rolePassword), false)).toBe( - "Postgres storage could not be prepared (SCHEMA_TEMP_PRIVILEGE); grant the database role TEMPORARY on its database." - ); - }); - - // The schema's own predicate splits into the same conditions raw or - // printed, so only a predicate whose printed form differs (a literal gains - // its cast) shows that the check compares Postgres's printing. - it("matches a declared predicate that Postgres prints differently from how it is written", async () => { - const { owner } = await appliedDatabase(); - await owner.query("CREATE TABLE predicate_probe (id INTEGER NOT NULL, state TEXT, attempts INTEGER)"); - await owner.query("CREATE UNIQUE INDEX predicate_probe_live ON predicate_probe (id) WHERE state = 'live' AND attempts > 0"); - const requirements = { - tables: ["predicate_probe"], - columns: [ - { table: "predicate_probe", column: "id", type: "INTEGER", nullable: false }, - { table: "predicate_probe", column: "state", type: "TEXT", nullable: true }, - { table: "predicate_probe", column: "attempts", type: "INTEGER", nullable: true }, - ], - keys: [{ table: "predicate_probe", columns: "id", predicate: "state = 'live' AND attempts > 0" }], - privileges: {}, - }; - - expect((await printedDeclaredPredicates(owner, requirements))[0]).toBe("((state = 'live'::text) AND (attempts > 0))"); - await expect(checkSchemaRequirements(owner, requirements)).resolves.toBeUndefined(); - }); - - it("refuses a privilege held on only some of a table's columns", async () => { - const { name, owner } = await appliedDatabase(); - await grant(owner, { ...STORE_TABLE_PRIVILEGES, audit_events: [] }); - await owner.query(`GRANT INSERT (id) ON audit_events TO ${role}`); - - expect(await start(urlFor(name, role, rolePassword), false)).toBe(refusal("SCHEMA_PRIVILEGES")); - }); - - // Each damage below leaves a database whose shape still resembles the - // schema but on which a store write fails or R21.1 no longer holds. A step - // starting with "!" is expected to fail and leave its mark (a failed - // CREATE INDEX CONCURRENTLY leaves an invalid index behind). - const seedDuplicates = [ - "INSERT INTO accounts VALUES ('acc', now(), now(), null, null)", - "INSERT INTO sessions VALUES ('s', 'acc', 'ghostlight', now(), now(), now() + interval '1 hour', '{}', 1)", - ]; - it.each([ - ["a key made DEFERRABLE (ON CONFLICT refuses it as an arbiter)", - ["ALTER TABLE private_command_receipts DROP CONSTRAINT private_command_receipts_pkey", "ALTER TABLE private_command_receipts ADD PRIMARY KEY (app_slug, idempotency_key) DEFERRABLE INITIALLY IMMEDIATE"]], - ["a key narrowed to one column, the other only INCLUDEd", - ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", "CREATE UNIQUE INDEX li_include ON linked_identities(provider) INCLUDE (provider_user_id)"]], - ["a key widened by an expression column", - ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", "CREATE UNIQUE INDEX li_expr ON linked_identities(provider, provider_user_id, lower(username))"]], - ["a key replaced by a partial one", - ["ALTER TABLE entitlement_snapshots DROP CONSTRAINT entitlement_snapshots_account_id_provider_scope_key", "CREATE UNIQUE INDEX es_partial ON entitlement_snapshots(account_id, provider, scope) WHERE is_allowed"]], - ["a key replaced by a plain index on the same columns", - ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", "CREATE INDEX li_plain ON linked_identities(provider, provider_user_id)"]], - ["a key replaced by one on other columns of the same count", - ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", "CREATE UNIQUE INDEX li_other ON linked_identities(provider, username)"]], - ["a key left only as an invalid index by a failed concurrent build", - [...seedDuplicates, - "ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", - "INSERT INTO linked_identities (id, account_id, provider, provider_user_id, created_at, updated_at) VALUES ('l1', 'acc', 'youtube', 'dup', now(), now()), ('l2', 'acc', 'youtube', 'dup', now(), now())", - "!CREATE UNIQUE INDEX CONCURRENTLY li_ccnew ON linked_identities(provider, provider_user_id)", - "DELETE FROM linked_identities WHERE id = 'l2'"]], - ["the attempt index left invalid over duplicate attempts by a failed concurrent build", - [...seedDuplicates, - "DROP INDEX auth_completions_attempt_unconsumed_unique_idx", - "INSERT INTO auth_completions (code, attempt_id, app_slug, provider, mode, account_id, session_id, return_to, payload_json, created_at, expires_at) VALUES ('c1', 'att', 'ghostlight', 'discord', 'sign_in', 'acc', 's', 'https://x/', '{}', now(), now() + interval '1 hour'), ('c2', 'att', 'ghostlight', 'discord', 'sign_in', 'acc', 's', 'https://x/', '{}', now(), now() + interval '1 hour')", - "!CREATE UNIQUE INDEX CONCURRENTLY auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id) WHERE attempt_id IS NOT NULL AND consumed_at IS NULL"]], - // An interrupted DROP INDEX CONCURRENTLY leaves an index ready but not - // valid; the fixture sets that state directly (the admin role may). - ["a key left only as an index that is ready but not valid", - ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", - "CREATE UNIQUE INDEX li_half_dropped ON linked_identities(provider, provider_user_id)", - "UPDATE pg_index SET indisvalid = false WHERE indexrelid = 'li_half_dropped'::regclass"]], - ["a key's first column compared under a case-insensitive collation", - ["CREATE COLLATION heimdall_ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false)", - "ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", - "CREATE UNIQUE INDEX li_ci_first ON linked_identities(provider COLLATE heimdall_ci, provider_user_id)"]], - // Soul pass 7: the key index compares under "C", but the column itself is - // case-insensitive, so the store's own lookups by provider_user_id match - // other users' ids. - ["a column declared under a case-insensitive collation, its key index under C", - ["CREATE COLLATION heimdall_ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false)", - "ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", - "ALTER TABLE linked_identities ALTER COLUMN provider_user_id TYPE text COLLATE heimdall_ci", - 'CREATE UNIQUE INDEX li_c ON linked_identities(provider, provider_user_id COLLATE "C")']], - ["a key compared under a case-insensitive collation (two users' ids become one row)", - ["CREATE COLLATION heimdall_ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false)", - "ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", - "CREATE UNIQUE INDEX li_ci ON linked_identities(provider, provider_user_id COLLATE heimdall_ci)"]], - ["the attempt index replaced by a plain one of the same name", - ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id)"]], - ["the attempt index made unique on every row (no predicate)", - ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id)"]], - ["the attempt index given another predicate", - ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id) WHERE attempt_id IS NOT NULL"]], - ["the attempt index narrowed by an extra condition", - ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id) WHERE attempt_id IS NOT NULL AND consumed_at IS NULL AND app_slug <> 'ghostlight'"]], - ["the attempt index with a condition ORed into its predicate", - ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id) WHERE (attempt_id IS NOT NULL OR app_slug = 'x') AND consumed_at IS NULL"]], - ["the attempt index made NULLS NOT DISTINCT without excluding NULL attempts", - ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id) NULLS NOT DISTINCT WHERE consumed_at IS NULL"]], - ["a column retyped", ["ALTER TABLE sessions ALTER COLUMN access_revision TYPE TEXT"]], - ["a created table's column dropped", ["ALTER TABLE auth_completions DROP COLUMN mode"]], - ["NOT NULL added to a column the store leaves null", ["ALTER TABLE auth_completions ALTER COLUMN attempt_id SET NOT NULL"]], - ["NOT NULL added to a nullable column of another table", - ["UPDATE linked_identities SET username = ''", "ALTER TABLE linked_identities ALTER COLUMN username SET NOT NULL"]], - ])("refuses %s", async (_damage, steps) => { - const { name, owner } = await appliedDatabase(); - for (const step of steps) { - if (step.startsWith("!")) await expect(owner.query(step.slice(1))).rejects.toBeDefined(); - else await owner.query(step); - } - - expect(await start(urlFor(name), false)).toBe(refusal("SCHEMA_MISSING")); - }); - - // Each change below leaves a database the store serves exactly as before. - it.each([ - ["a key index that carries extra INCLUDE columns", - ["ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", "CREATE UNIQUE INDEX li_covering ON linked_identities(provider, provider_user_id) INCLUDE (username)"]], - ["the attempt index under another name", ["ALTER INDEX auth_completions_attempt_unconsumed_unique_idx RENAME TO attempt_idx_renamed"]], - ["the attempt index's conditions in the other order", - ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX attempt_reordered ON auth_completions(app_slug, attempt_id) WHERE consumed_at IS NULL AND attempt_id IS NOT NULL"]], - // NULL attempt ids never collide in a unique index that treats NULLs as - // distinct (the default), so dropping that condition keeps the same rows unique. - ["the attempt index without its redundant attempt_id IS NOT NULL", - ["DROP INDEX auth_completions_attempt_unconsumed_unique_idx", "CREATE UNIQUE INDEX attempt_unconsumed ON auth_completions(app_slug, attempt_id) WHERE consumed_at IS NULL"]], - ["a lookup index dropped", ["DROP INDEX audit_events_lookup_idx", "DROP INDEX auth_completions_lookup_idx"]], - // Only a key's own columns decide which rows collide; an INCLUDEd column's - // collation does not, whatever it is. - ["a key index that INCLUDEs an undeclared case-insensitive column", - ["CREATE COLLATION heimdall_ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false)", - "ALTER TABLE linked_identities ADD COLUMN operator_note text COLLATE heimdall_ci", - "ALTER TABLE linked_identities DROP CONSTRAINT linked_identities_provider_provider_user_id_key", - "CREATE UNIQUE INDEX li_note ON linked_identities(provider, provider_user_id) INCLUDE (operator_note)"]], - ])("accepts %s", async (_change, steps) => { - const { name, owner } = await appliedDatabase(); - for (const step of steps) await owner.query(step); - - expect(await start(urlFor(name), false)).toBe("started"); - }); }); From b5c4e46e2837670a5225d70a213216029156a938 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:10:19 +0100 Subject: [PATCH 57/63] Steward cut 3: simplify AppCaller, un-cram app.ts check, consolidate caller-identity tests --- src/app-caller.ts | 45 +- src/app.ts | 15 +- tests/caller-identity-attack-soul-r21.test.ts | 621 ------------------ tests/caller-identity-attack-soul.test.ts | 362 ---------- tests/caller-identity-soul.test.ts | 295 --------- tests/caller-identity.test.ts | 266 ++++++++ 6 files changed, 287 insertions(+), 1317 deletions(-) delete mode 100644 tests/caller-identity-attack-soul-r21.test.ts delete mode 100644 tests/caller-identity-attack-soul.test.ts delete mode 100644 tests/caller-identity-soul.test.ts create mode 100644 tests/caller-identity.test.ts diff --git a/src/app-caller.ts b/src/app-caller.ts index 59c80a0..d25a881 100644 --- a/src/app-caller.ts +++ b/src/app-caller.ts @@ -16,51 +16,28 @@ import { timingSafeEqual } from "node:crypto"; import { type AppSlug } from "./contracts.js"; import { type HeimdallConfig } from "./config.js"; -// `{ appSlug }` used to satisfy this type structurally, so any module could -// construct a caller by writing the literal — nothing but grep discipline -// stopped an importer from forging one. The symbol brand stops that at -// compile time, but a cast (`as unknown as AppCaller`) or a JSON round-trip -// defeats a type-level check trivially; nothing enforced it at runtime. The -// module-private WeakSet below is the enforcement: brandCaller registers -// every value it mints, and isAppCaller is the only way a consumer may trust -// one. A forged literal — even one carrying the symbol key by hand — was -// never added to the set and is rejected. -const callerBrand = Symbol("AppCaller"); +import { timingSafeEqual } from "node:crypto"; +import { type AppSlug } from "./contracts.js"; +import { type HeimdallConfig } from "./config.js"; + +declare const appCallerBrand: unique symbol; export interface AppCaller { readonly appSlug: AppSlug; - readonly [callerBrand]: true; + readonly [appCallerBrand]: true; } -const mintedCallers = new WeakSet(); - -function brandCaller(appSlug: AppSlug): AppCaller { - // Frozen: the brand survives mutation, so without this a legitimately held - // caller for one app could be re-slugged into another and stay branded. - const caller: AppCaller = Object.freeze({ appSlug, [callerBrand]: true as const }); - mintedCallers.add(caller); - return caller; -} - -/** - * The runtime half of the brand. `startOAuthFlow` and `refreshAppSession` - * call this instead of trusting the `AppCaller | null` type alone — a value - * that is not exactly the object `resolveAppCaller` or - * `callerFromOpenedEnvelope` returned is never in the set, regardless of - * shape or cast. - */ -export function isAppCaller(value: unknown): value is AppCaller { - return typeof value === "object" && value !== null && mintedCallers.has(value); +function makeCaller(appSlug: AppSlug): AppCaller { + return { appSlug } as AppCaller; } /** * The private command plane already authenticated `appSlug` by opening its * envelope with the app's shared secret and checking sourceRuntimeId before - * ever calling this. It has no header to read, so it cannot go through - * resolveAppCaller; this is the only other place an AppCaller may be minted. + * calling this. */ export function callerFromOpenedEnvelope(appSlug: AppSlug): AppCaller { - return brandCaller(appSlug); + return makeCaller(appSlug); } /** Timing-safe comparator. The only comparator anywhere a shared secret is checked. */ @@ -91,5 +68,5 @@ export function resolveAppCaller( appSlug: AppSlug, headers: Record ): AppCaller | null { - return secretMatches(config.appSharedSecrets[appSlug], getSharedSecretHeader(headers)) ? brandCaller(appSlug) : null; + return secretMatches(config.appSharedSecrets[appSlug], getSharedSecretHeader(headers)) ? makeCaller(appSlug) : null; } diff --git a/src/app.ts b/src/app.ts index 5e327cf..f43dc73 100644 --- a/src/app.ts +++ b/src/app.ts @@ -3,7 +3,7 @@ import { deflateRawSync, inflateRawSync } from "node:zlib"; import cookie from "@fastify/cookie"; import cors from "@fastify/cors"; import Fastify, { type FastifyError, type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify"; -import { type AppCaller, isAppCaller, resolveAppCaller } from "./app-caller.js"; +import { type AppCaller, resolveAppCaller } from "./app-caller.js"; import { deliverBackendHandoff, type BackendHandoffPayload } from "./backend-handoff.js"; import { appSlugs, @@ -749,7 +749,7 @@ export async function startOAuthFlow( return { statusCode: 400, body: { error: "link_initiator_conflict", detail: "initiatingAccountId differs from the bearer's account." } }; } } else { - if (!isAppCaller(caller) || caller.appSlug !== profile.slug) { + if (!caller || caller.appSlug !== profile.slug) { return { statusCode: 401, body: { error: "app_auth_required" } }; } if (!input.initiatingAccountId) { @@ -768,7 +768,7 @@ export async function startOAuthFlow( // sign_in. A provider with no re-authentication parameter is refused here, // at start, so no step-up ever reaches the person without its step. if (input.stepUp) { - if (!isAppCaller(caller) || caller.appSlug !== profile.slug) { + if (!caller || caller.appSlug !== profile.slug) { return { statusCode: 401, body: { error: "app_auth_required" } }; } if (!providerCatalog[provider].stepUpAuthorizationParams) { @@ -829,7 +829,12 @@ 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)) { + const requiresAppCaller = + Boolean(entitlementPolicy) || + Boolean(profile.startRequiresAppCaller) || + input.firstLoginGrant !== undefined || + (input.mode === "connect" && input.connection !== undefined); + if (requiresAppCaller && (!caller || caller.appSlug !== profile.slug)) { return { statusCode: 401, body: { error: "app_auth_required" } }; } @@ -1327,7 +1332,7 @@ export async function refreshAppSession( }, }; } - if (entitlementPolicies.length > 0 && (!isAppCaller(caller) || caller.appSlug !== appSlug)) { + if (entitlementPolicies.length > 0 && (!caller || caller.appSlug !== appSlug)) { return { statusCode: 401, body: { error: "app_auth_required" } }; } diff --git a/tests/caller-identity-attack-soul-r21.test.ts b/tests/caller-identity-attack-soul-r21.test.ts deleted file mode 100644 index ce7d254..0000000 --- a/tests/caller-identity-attack-soul-r21.test.ts +++ /dev/null @@ -1,621 +0,0 @@ -// Soul attack probes, third pass: R21.1 (attempt-handle binding), R21.2 -// (runtime AppCaller brand), R21.3 (registered-app path deletion) and the -// partial unique index on auth_completions(app_slug, attempt_id). -// -// Same convention as the other two Soul files: plain `it` is an invariant -// that currently holds; `it.fails` is a hole this branch does not close. -// The "live postgres" block runs only when SOUL_PG_URL names a reachable -// database; it is skipped in the ordinary suite so the suite stays hermetic. -import { encode, decode } from "@msgpack/msgpack"; -import { invokeCultNetOperation } from "cultnet-ts"; -import { Pool } from "pg"; -import { newDb } from "pg-mem"; -import { afterEach, describe, expect, it } from "vitest"; -import { buildApp, getHeimdallRuntimeContext, refreshAppSession, startOAuthFlow } from "../src/app.js"; -import { type AppCaller, isAppCaller, resolveAppCaller } from "../src/app-caller.js"; -import { getAppProfile } from "../src/app-profiles.js"; -import { type HeimdallConfig } from "../src/config.js"; -import { type AppSlug } from "../src/contracts.js"; -import { entitlementFacts } from "../src/facts.js"; -import { type OAuthProviderRuntime } from "../src/oauth.js"; -import { startHeimdallPrivateCommandPlane } from "../src/private-command-plane.js"; -import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "../src/private-command-security.js"; -import { InMemoryStore } from "../src/store/index.js"; -import { PostgresStore } from "../src/store/postgres.js"; -import { CREATE_SCHEMA_SQL } from "../src/store/schema.js"; -import { type CreateAuthCompletionInput, type HeimdallStore } from "../src/store/types.js"; -import { launchState, stateOf } from "./oauth-flow.js"; - -const ghostlightSecret = "ghostlight-private-command-secret"; -const resources: Array<{ close(): Promise }> = []; - -afterEach(async () => { - await Promise.all(resources.splice(0).reverse().map((resource) => resource.close())); -}); - -function testConfig(overrides: Partial = {}): HeimdallConfig { - return { - serviceName: "heimdall", - host: "127.0.0.1", - port: 4100, - privateCommandHost: "127.0.0.1", - privateCommandPort: 0, - workspaceRoot: "F:/Projects/Heimdall", - dataRoot: "F:/Projects/Heimdall/.heimdall-data", - cultCachePath: "F:/Projects/Heimdall/.heimdall-data/cultcache/test.cc", - publicBaseUrl: "https://heimdall.gamecult.org", - issuer: "https://heimdall.gamecult.org", - daemonId: "yggdrasil-heimdall", - idunnRudpHealth: undefined, - idunnHealthContract: "heimdall.cultnet-rudp-provider-health", - providerHealthIdentityPath: "F:/Projects/Heimdall/.heimdall-data/provider-health-test.cc", - sessionTtlSeconds: 3600, - refreshTtlSeconds: 3600, - stateTtlSeconds: 600, - completionTtlSeconds: 300, - bootstrapSigningPrivateKeyOnMissing: false, - tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"), - appSharedSecrets: { repixelizer: "repixelizer-secret", ghostlight: ghostlightSecret }, - appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] }, - appBackendCallbacks: {}, - storage: { backend: "memory", applySchemaOnStartup: true }, - providers: { - discord: { clientId: "discord-client", clientSecret: "discord-secret" }, - patreon: {}, - github: {}, - twitch: {}, - youtube: {}, - spotify: {}, - joystick: {}, - google: {}, - }, - ...overrides, - }; -} - -// The provider "code" doubles as the identity: code `victim` resolves to -// discord user `victim`, so one runtime plays every party. -function identityByCodeRuntime(): OAuthProviderRuntime { - return { - async exchangeAuthorizationCode({ code }) { - return { accessToken: code, tokenType: "Bearer", scope: ["identify"], raw: {} }; - }, - async resolveIdentity({ accessToken }) { - return { provider: "discord", providerUserId: accessToken, displayName: accessToken, profile: {} }; - }, - async evaluateEntitlements() { - return { facts: [entitlementFacts.appAccess], snapshots: [] }; - }, - }; -} - -async function harness(overrides: Partial = {}) { - const config = testConfig(overrides); - const store = new InMemoryStore(); - const app = await buildApp({ config, store, oauthRuntimes: { discord: identityByCodeRuntime() } }); - resources.push(app); - return { app, store, config }; -} - -type App = Awaited>["app"]; - -async function start(app: App, payload: unknown, headers: Record = {}) { - return app.inject({ method: "POST", url: "/v1/oauth/discord/start", payload: payload as never, headers }); -} - -async function completeAs(app: App, stateToken: string, who: string) { - const { cookie } = await launchState(app, stateToken); - return app.inject({ - method: "GET", - url: `/v1/oauth/discord/callback?code=${who}&state=${encodeURIComponent(stateToken)}`, - headers: { accept: "application/json", cookie }, - }); -} - -function jwtPayload(token: string): Record { - const [, body] = token.split("."); - return JSON.parse(Buffer.from(body ?? "", "base64url").toString("utf8")) as Record; -} - -function planeRequest(operation: string, messageId: string, envelope: HeimdallPrivateEnvelope) { - return { - schemaVersion: "cultnet.operation_request.v0" as const, - messageId, - serviceId: "heimdall.private.commands", - operation, - payloadSchema: "heimdall.private_command_envelope.v1", - payloadEncoding: "messagepack-base64" as const, - payload: Buffer.from(encode(envelope)).toString("base64"), - sourceRuntimeId: "yggdrasil-ghostlight", - }; -} - -async function planeCommand( - endpoint: Parameters[0], - operation: string, - idempotencyKey: string, - payload: Record, -): Promise> { - const contentSchema = operation === "heimdall.auth.begin" ? "heimdall.auth_begin_command.v1" : "heimdall.auth_complete_command.v1"; - const envelope = sealPrivateEnvelope({ appSlug: "ghostlight", operation, contentSchema, idempotencyKey, secret: ghostlightSecret, payload }); - const response = await invokeCultNetOperation(endpoint, planeRequest(operation, `msg-${idempotencyKey}`, envelope), { - runtimeId: "yggdrasil-ghostlight", - }); - expect(response.status, JSON.stringify(response.diagnostics)).toBe("accepted"); - const wire = decode(Buffer.from(response.payload, "base64")) as HeimdallPrivateEnvelope; - return openPrivateEnvelope(wire, ghostlightSecret); -} - -async function planeHarness() { - const { app, store, config } = await harness(); - const plane = await startHeimdallPrivateCommandPlane(app, config); - resources.push(plane); - const begin = async (key: string) => - planeCommand(plane.endpoint, "heimdall.auth.begin", key, { - provider: "discord", - mode: "sign_in", - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - entitlementPolicy: { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }, - }); - const complete = async (key: string, handle: string) => planeCommand(plane.endpoint, "heimdall.auth.complete", key, { handle }); - return { app, store, config, begin, complete }; -} - -function completionInput(appSlug: AppSlug, accountId: string, sessionId: string, attemptId?: string): CreateAuthCompletionInput { - const now = new Date(); - return { - ...(attemptId ? { attemptId } : {}), - appSlug, - provider: "discord", - mode: "sign_in", - accountId, - sessionId, - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - createdAt: now.toISOString(), - expiresAt: new Date(now.getTime() + 300_000).toISOString(), - payloadJson: { marker: attemptId ?? "none" }, - }; -} - -// Seeds the account/session rows the FK constraints on auth_completions -// require in postgres; harmless in memory. -async function seedAccountAndSession(store: HeimdallStore, appSlug: AppSlug) { - const now = new Date().toISOString(); - const account = await store.createAccount({ createdAt: now, lastSeenAt: now }); - const session = await store.createSession({ - id: `sess-${account.id}`, - accountId: account.id, - appSlug, - createdAt: now, - lastSeenAt: now, - expiresAt: new Date(Date.now() + 3600_000).toISOString(), - claimsJson: {}, - accessRevision: 0, - }); - return { accountId: account.id, sessionId: session.id }; -} - -describe("R21.1: the attempt handle is unreachable from the public start route", () => { - const legitReturn = "https://yggdrasil.gamecult.org/ghostlight/"; - // Ghostlight's starts are the app's own (startRequiresAppCaller); what the body may not do is name an attempt handle, even for the app. - const ghostlightApp = { "x-heimdall-app-secret": ghostlightSecret }; - - it("a well-formed browser_completion attemptId is dropped before the state token is signed", async () => { - const { app, store } = await harness(); - const attempt = await store.createAuthAttempt({ - appSlug: "ghostlight", - provider: "discord", - mode: "sign_in", - returnTo: legitReturn, - createdAt: new Date().toISOString(), - expiresAt: new Date(Date.now() + 600_000).toISOString(), - }); - const response = await start(app, { - appSlug: "ghostlight", - mode: "sign_in", - returnTo: legitReturn, - handoff: { kind: "browser_completion", attemptId: attempt.handle }, - }, ghostlightApp); - expect(response.statusCode, response.body).toBe(201); - expect(response.json().handoff).toEqual({ kind: "browser_completion" }); - const state = jwtPayload(stateOf(response.json())); - expect(state.handoff).toEqual({ kind: "browser_completion" }); - expect(JSON.stringify(state)).not.toContain(attempt.handle); - }); - - // Fastify's default AJV runs with removeAdditional and coerceTypes:"array", - // so `additionalProperties: false` strips unknown keys instead of - // rejecting, and `["h"]` is coerced to "h". The oracle is therefore not - // the status code: it is that the planted value is absent from the - // response's handoff and from the signed state payload. - const planted = "planted-handle-7f3a"; - it.each([ - ["differently-cased key", { kind: "browser_completion", AttemptId: planted }], - ["snake_case key", { kind: "browser_completion", attempt_id: planted }], - ["array value (coerced to a string by AJV)", { kind: "browser_completion", attemptId: [planted] }], - ["object value", { kind: "browser_completion", attemptId: { value: planted } }], - ["nested handoff", { kind: "browser_completion", handoff: { attemptId: planted } }], - ["empty string", { kind: "browser_completion", attemptId: "" }], - ])("a %s attemptId never reaches the state token", async (_label, handoff) => { - const { app } = await harness(); - const response = await start(app, { appSlug: "ghostlight", mode: "sign_in", returnTo: legitReturn, handoff }, ghostlightApp); - expect(response.body).not.toContain(planted); - if (response.statusCode === 201) { - expect(response.json().handoff).toEqual({ kind: "browser_completion" }); - expect(jwtPayload(stateOf(response.json())).handoff).toEqual({ kind: "browser_completion" }); - } else { - expect(response.statusCode, response.body).toBe(400); - } - }); - - it("a top-level attemptId / trustedBrowserAttemptId / options field on the body is stripped, never bound", async () => { - const { app } = await harness(); - for (const extra of [{ attemptId: planted }, { trustedBrowserAttemptId: planted }, { options: { trustedBrowserAttemptId: planted } }]) { - const response = await start(app, { appSlug: "ghostlight", mode: "sign_in", returnTo: legitReturn, ...extra }, ghostlightApp); - expect(response.statusCode, response.body).toBe(201); - expect(response.body).not.toContain(planted); - expect(jwtPayload(stateOf(response.json())).handoff).toEqual({ kind: "browser_completion" }); - } - }); - - it("startOAuthFlow has exactly two callers and only beginAuth passes the options argument", async () => { - const { readFileSync, readdirSync } = await import("node:fs"); - const { join } = await import("node:path"); - const srcDir = join(process.cwd(), "src"); - const callers: string[] = []; - for (const file of readdirSync(srcDir, { recursive: true }) as string[]) { - if (!file.endsWith(".ts")) continue; - const source = readFileSync(join(srcDir, file), "utf8"); - const calls = source.match(/(? { - const { app, store, begin, complete } = await planeHarness(); - const receipt = await begin("begin-legit"); - expect(receipt.status).toBe("pending"); - const handle = String(receipt.handle); - const navigation = receipt.navigation as { url: string }; - const state = new URL(navigation.url).searchParams.get("state") ?? ""; - expect(jwtPayload(state).handoff).toEqual({ kind: "browser_completion", attemptId: handle }); - - const callback = await completeAs(app, state, "victim"); - expect(callback.statusCode, callback.body).toBe(201); - expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("completed"); - - const completed = await complete("complete-legit", handle); - expect(completed.status).toBe("authenticated"); - expect(completed.handle).toBe(handle); - expect(completed.accessToken).toEqual(expect.any(String)); - expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("consumed"); - }); - - it("a stranger cannot pre-occupy the app's pending handle so that the victim's own completion collides", async () => { - const { app, store, begin, complete } = await planeHarness(); - const receipt = await begin("begin-victim"); - const handle = String(receipt.handle); - const victimState = new URL((receipt.navigation as { url: string }).url).searchParams.get("state") ?? ""; - - // Attacker names the victim's handle on the public start route: Ghostlight's - // start is refused outright without the app's secret, so no state exists to complete. - const attackerStart = await start(app, { - appSlug: "ghostlight", - mode: "sign_in", - returnTo: legitReturn, - handoff: { kind: "browser_completion", attemptId: handle }, - }); - expect([attackerStart.statusCode, attackerStart.json().error]).toEqual([401, "app_auth_required"]); - expect(attackerStart.json().authorizationUrl).toBeUndefined(); - expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("pending"); - - // Victim completes; the handle's single unconsumed slot is still free. - const victimCallback = await completeAs(app, victimState, "victim"); - expect(victimCallback.statusCode, victimCallback.body).toBe(201); - const completed = await complete("complete-victim", handle); - expect(completed.status).toBe("authenticated"); - // ...and the tokens are the victim's, not the attacker's. - const claims = jwtPayload(String(completed.accessToken)); - expect(JSON.stringify(claims)).toContain("victim"); - expect(JSON.stringify(claims)).not.toContain("attacker"); - }); - - it("a backend_callback attemptId (the other handoff kind that carries one) never touches an auth attempt", async () => { - const { app, store } = await harness({ appBackendCallbacks: { ghostlight: ["http://127.0.0.1:1/never"] } }); - const attempt = await store.createAuthAttempt({ - appSlug: "ghostlight", - provider: "discord", - mode: "sign_in", - returnTo: legitReturn, - createdAt: new Date().toISOString(), - expiresAt: new Date(Date.now() + 600_000).toISOString(), - }); - const response = await start(app, { - appSlug: "ghostlight", - mode: "sign_in", - returnTo: legitReturn, - handoff: { kind: "backend_callback", attemptId: attempt.handle, callbackUrl: "http://127.0.0.1:1/never" }, - }, ghostlightApp); - expect(response.statusCode, response.body).toBe(201); - // Delivery to port 1 fails; whatever the callback returns, the attempt - // must be untouched and no completion may be bound to it. - await completeAs(app, stateOf(response.json()), "attacker"); - expect((await store.findAuthAttempt("ghostlight", attempt.handle))?.status).toBe("pending"); - expect(await store.consumeAuthCompletionByAttempt("ghostlight", attempt.handle, new Date().toISOString())).toBeNull(); - }); -}); - -describe("R21.2: the WeakSet brand at every consumer", () => { - it("every function that takes an AppCaller checks isAppCaller before reading appSlug", async () => { - const { readFileSync, readdirSync } = await import("node:fs"); - const { join } = await import("node:path"); - const srcDir = join(process.cwd(), "src"); - const consumers: string[] = []; - for (const file of readdirSync(srcDir, { recursive: true }) as string[]) { - if (!file.endsWith(".ts") || file.endsWith("app-caller.ts")) continue; - const source = readFileSync(join(srcDir, file), "utf8"); - const readsSlug = source.match(/caller\.appSlug/g) ?? []; - const guards = source.match(/isAppCaller\(caller\)/g) ?? []; - if (readsSlug.length) consumers.push(`${file}: reads=${readsSlug.length} guards=${guards.length}`); - // Every `caller.appSlug` read is on a line that also carries the guard. - for (const line of source.split("\n")) { - if (line.includes("caller.appSlug")) expect(line, `${file}: ${line.trim()}`).toContain("isAppCaller(caller)"); - } - } - expect(consumers).toEqual(["app.ts: reads=4 guards=4"]); - }); - - it("a caller minted for app A is refused where app B is expected, over HTTP and by direct call", async () => { - const { app, config } = await harness(); - const ctx = getHeimdallRuntimeContext(app); - const repixelizerCaller = resolveAppCaller(config, "repixelizer", { "x-heimdall-app-secret": "repixelizer-secret" }); - expect(isAppCaller(repixelizerCaller)).toBe(true); - - const startResult = await startOAuthFlow(ctx, "discord", repixelizerCaller, { - appSlug: "ghostlight", - mode: "sign_in", - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - entitlementPolicy: { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }, - }); - expect(startResult.statusCode).toBe(401); - expect(startResult.body).toMatchObject({ error: "app_auth_required" }); - - const refreshResult = await refreshAppSession(ctx, "ghostlight", repixelizerCaller, { - refreshToken: "x", - entitlementPolicies: [{ kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }], - }); - expect(refreshResult.statusCode).toBe(401); - - // Over HTTP: repixelizer's real secret on a ghostlight start with policy. - const http = await start( - app, - { - appSlug: "ghostlight", - mode: "sign_in", - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - entitlementPolicy: { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }, - }, - { "x-heimdall-app-secret": "repixelizer-secret" }, - ); - expect(http.statusCode).toBe(401); - }); - - it("symbol-copying, prototype-chaining, Proxy-wrapping and structuredClone forgeries are all refused", async () => { - const { config } = await harness(); - const real = resolveAppCaller(config, "repixelizer", { "x-heimdall-app-secret": "repixelizer-secret" }) as AppCaller; - const [brandSymbol] = Object.getOwnPropertySymbols(real); - expect(brandSymbol).toBeDefined(); - - const symbolCopy = { appSlug: "ghostlight", [brandSymbol as symbol]: true }; - // defineProperty, not assign: `real` is frozen, so shadowing its - // non-writable `appSlug` by assignment throws before the forgery exists. - const chained = Object.defineProperty(Object.create(real) as object, "appSlug", { - value: "ghostlight", - enumerable: true, - }); - const proxied = new Proxy(real, { get: (target, key) => (key === "appSlug" ? "ghostlight" : Reflect.get(target, key)) }); - const spread = { ...real, appSlug: "ghostlight" }; - const cloned = structuredClone({ appSlug: real.appSlug }); - for (const forgery of [symbolCopy, chained, proxied, spread, cloned]) { - expect(isAppCaller(forgery)).toBe(false); - } - // Frozen at mint, so the last forgery the WeakSet could not see is gone: - // a legitimately held caller cannot be re-slugged into another app and - // keep its brand. Modules are strict, so the write throws rather than - // silently no-opping. - expect(Object.isFrozen(real)).toBe(true); - expect(() => { - (real as { appSlug: string }).appSlug = "ghostlight"; - }).toThrow(TypeError); - expect(real.appSlug).toBe("repixelizer"); - expect(isAppCaller(real)).toBe(true); - }); -}); - -async function twoCompletionsForOneHandle(store: HeimdallStore, appSlug: AppSlug = "ghostlight") { - const { accountId, sessionId } = await seedAccountAndSession(store, appSlug); - const results = await Promise.allSettled([ - store.createAuthCompletion(completionInput(appSlug, accountId, sessionId, "handle-1")), - store.createAuthCompletion(completionInput(appSlug, accountId, sessionId, "handle-1")), - ]); - return { results, accountId, sessionId }; -} - -function partialUniqueIndexContract(label: string, makeStore: () => Promise) { - describe(`partial unique index contract: ${label}`, () => { - it("two concurrent completions for one handle: exactly one is minted", async () => { - const store = await makeStore(); - const { results } = await twoCompletionsForOneHandle(store); - const fulfilled = results.filter((r) => r.status === "fulfilled"); - const rejected = results.filter((r) => r.status === "rejected"); - expect(fulfilled).toHaveLength(1); - expect(rejected).toHaveLength(1); - const live = await store.consumeAuthCompletionByAttempt("ghostlight", "handle-1", new Date().toISOString()); - expect(live?.attemptId).toBe("handle-1"); - expect(await store.consumeAuthCompletionByAttempt("ghostlight", "handle-1", new Date().toISOString())).toBeNull(); - }); - - it("the predicate: NULL handles never collide, a consumed handle frees its slot, other apps do not collide", async () => { - const store = await makeStore(); - const g = await seedAccountAndSession(store, "ghostlight"); - const r = await seedAccountAndSession(store, "repixelizer"); - await store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId)); - await store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId)); - const first = await store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId, "shared")); - await expect(store.createAuthCompletion(completionInput("repixelizer", r.accountId, r.sessionId, "shared"))).resolves.toBeTruthy(); - await expect(store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId, "shared"))).rejects.toThrow(); - expect(await store.consumeAuthCompletion("ghostlight", first.code, new Date().toISOString())).toBeTruthy(); - const second = await store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId, "shared")); - expect(second.code).not.toBe(first.code); - const byAttempt = await store.consumeAuthCompletionByAttempt("ghostlight", "shared", new Date().toISOString()); - expect(byAttempt?.code).toBe(second.code); - }); - - it("an expired-but-unconsumed completion still occupies the slot (both stores agree; neither frees it)", async () => { - const store = await makeStore(); - const g = await seedAccountAndSession(store, "ghostlight"); - const stale = completionInput("ghostlight", g.accountId, g.sessionId, "stale"); - stale.expiresAt = new Date(Date.now() - 1000).toISOString(); - await store.createAuthCompletion(stale); - expect(await store.consumeAuthCompletionByAttempt("ghostlight", "stale", new Date().toISOString())).toBeNull(); - await expect(store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId, "stale"))).rejects.toThrow(); - }); - }); -} - -partialUniqueIndexContract("InMemoryStore", async () => new InMemoryStore()); -partialUniqueIndexContract("PostgresStore over pg-mem", async () => { - const adapter = newDb().adapters.createPg(); - const store = new PostgresStore(new adapter.Pool()); - await store.ensureSchema(); - return store; -}); - -describe("duplicate-handle error surfacing through the callback route", () => { - it("a replayed state is refused as already used before any exchange, and leaves the real completion intact", async () => { - const { app, store, begin } = await planeHarness(); - const receipt = await begin("begin-replay"); - const handle = String(receipt.handle); - const state = new URL((receipt.navigation as { url: string }).url).searchParams.get("state") ?? ""; - const { cookie } = await launchState(app, state); - const callbackWith = () => - app.inject({ - method: "GET", - url: `/v1/oauth/discord/callback?code=victim&state=${encodeURIComponent(state)}`, - headers: { accept: "application/json", cookie }, - }); - const first = await callbackWith(); - expect(first.statusCode).toBe(201); - // The state's jti was consumed by the first callback, so the second never - // reaches createAuthCompletion, whose unique index used to be the only - // thing refusing a replay (and whose Postgres 23505 text the route had to - // keep out of the answer). - const replay = await callbackWith(); - expect(replay.statusCode, replay.body).toBe(400); - expect(replay.json()).toEqual({ error: "state_already_used" }); - expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("completed"); - expect(await store.consumeAuthCompletionByAttempt("ghostlight", handle, new Date().toISOString())).toBeTruthy(); - }); -}); - -describe("R21.3: sync getAppProfile at the seven former resolveAppProfile sites", () => { - it("getAppProfile resolves own keys only, so prototype members are not profiles", () => { - expect(getAppProfile("nope" as AppSlug)).toBeUndefined(); - // Object.hasOwn guards the lookup; a bare `record[key]` index handed these - // back as objects that then serialised as an empty profile. - for (const key of ["constructor", "toString", "__proto__", "hasOwnProperty"]) { - expect(getAppProfile(key as AppSlug), key).toBeUndefined(); - } - }); - - // Was an open hole inherited from main: this is the one route whose params - // schema has no slug enum, and the bare index made `constructor` a 200 `{}` - // because serializeAppProfile(Object) serialises undefined fields. Closed by - // Object.hasOwn in getAppProfile. - it("GET /v1/apps/:appSlug is the one route without the slug enum; a prototype key must still be a 404", async () => { - const { app } = await harness(); - // Null prototype so the "__proto__" key is a key, not a setter. - const statuses: Record = Object.create(null) as Record; - for (const key of ["constructor", "toString", "__proto__", "hasOwnProperty", "valueOf"]) { - const response = await app.inject({ method: "GET", url: `/v1/apps/${key}` }); - statuses[key] = `${response.statusCode} ${response.body.slice(0, 60)}`; - } - process.stdout.write(`\n[soul] GET /v1/apps/: ${JSON.stringify(statuses)}\n`); - expect(statuses).toEqual(Object.fromEntries(Object.keys(statuses).map((key) => [key, expect.stringMatching(/^404 /)]))); - }); - - it("every other appSlug parameter is enum-gated, so an unknown slug is a 400 there and a 404 only on the profile read", async () => { - const { app } = await harness(); - expect((await app.inject({ method: "GET", url: "/v1/apps/nope" })).statusCode).toBe(404); - expect((await start(app, { appSlug: "nope", mode: "sign_in", returnTo: "https://x.example/" })).statusCode).toBe(400); - for (const url of [ - "/v1/apps/nope/auth-completions/redeem", - "/v1/apps/nope/sessions/refresh", - "/v1/apps/nope/patron-support/sync", - "/v1/apps/nope/managed-credentials/resolve", - ]) { - const response = await app.inject({ method: "POST", url, payload: { completionCode: "c", refreshToken: "r", accountId: "a", provider: "discord" } }); - expect(response.statusCode, url).toBe(400); - } - }); - - it("the migration adds attempt_id before the partial index that references it, and drops registered_apps first", () => { - const addColumn = CREATE_SCHEMA_SQL.indexOf("ALTER TABLE auth_completions ADD COLUMN IF NOT EXISTS attempt_id TEXT"); - const dropOldIndex = CREATE_SCHEMA_SQL.indexOf("DROP INDEX IF EXISTS auth_completions_attempt_idx"); - const createIndex = CREATE_SCHEMA_SQL.indexOf("CREATE UNIQUE INDEX IF NOT EXISTS auth_completions_attempt_unconsumed_unique_idx"); - const dropTable = CREATE_SCHEMA_SQL.indexOf("DROP TABLE IF EXISTS registered_apps"); - expect(dropTable).toBeGreaterThanOrEqual(0); - expect(addColumn).toBeGreaterThan(dropTable); - expect(dropOldIndex).toBeGreaterThan(addColumn); - expect(createIndex).toBeGreaterThan(dropOldIndex); - // Statement count, not token count (the comment above the DROP names it too). - expect(CREATE_SCHEMA_SQL.match(/DROP TABLE IF EXISTS registered_apps/g)).toHaveLength(1); - expect(CREATE_SCHEMA_SQL).not.toMatch(/CREATE TABLE[^;]*registered_apps/); - }); - // Re-running ensureSchema on a store built before this branch (table - // present, column absent, old index name) cannot be simulated in pg-mem — - // it rejects CREATE TABLE IF NOT EXISTS on an existing table — so that - // path is proved only by the live block below. -}); - -const livePg = process.env.SOUL_PG_URL; -describe.skipIf(!livePg)("live postgres (SOUL_PG_URL)", () => { - it("real partial index: 23505 names auth_completions_attempt_unconsumed_unique_idx; schema applies twice on a pre-branch store", async () => { - const pool = new Pool({ connectionString: livePg }); - resources.push({ close: () => pool.end() }); - await pool.query(` - DROP SCHEMA public CASCADE; CREATE SCHEMA public; - CREATE TABLE registered_apps (slug TEXT PRIMARY KEY); - CREATE TABLE accounts (id TEXT PRIMARY KEY, created_at TIMESTAMPTZ NOT NULL, last_seen_at TIMESTAMPTZ NOT NULL, display_name TEXT, primary_email TEXT); - CREATE TABLE sessions (id TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, app_slug TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL, last_seen_at TIMESTAMPTZ NOT NULL, expires_at TIMESTAMPTZ NOT NULL, claims_json JSONB NOT NULL, access_revision INTEGER NOT NULL); - CREATE TABLE auth_completions ( - code TEXT PRIMARY KEY, app_slug TEXT NOT NULL, provider TEXT NOT NULL, mode TEXT NOT NULL, - account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, - session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, - return_to TEXT NOT NULL, payload_json JSONB NOT NULL, created_at TIMESTAMPTZ NOT NULL, expires_at TIMESTAMPTZ NOT NULL, consumed_at TIMESTAMPTZ - ); - `); - const store = new PostgresStore(pool); - await store.ensureSchema(); - await store.ensureSchema(); - const tables = await pool.query<{ table_name: string }>("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY 1"); - expect(tables.rows.map((r) => r.table_name)).not.toContain("registered_apps"); - const indexes = await pool.query<{ indexdef: string }>("SELECT indexdef FROM pg_indexes WHERE tablename = 'auth_completions' ORDER BY 1"); - const partial = indexes.rows.find((r) => r.indexdef.includes("auth_completions_attempt_unconsumed_unique_idx")); - expect(partial?.indexdef).toContain("WHERE ((attempt_id IS NOT NULL) AND (consumed_at IS NULL))"); - - const { results } = await twoCompletionsForOneHandle(store); - const rejected = results.find((r): r is PromiseRejectedResult => r.status === "rejected"); - expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(1); - const error = rejected?.reason as { code?: string; message?: string }; - expect(error.code).toBe("23505"); - expect(error.message).toContain("auth_completions_attempt_unconsumed_unique_idx"); - // What the callback route's catch would echo as `detail`. - process.stdout.write(`\n[soul live pg] 23505 message: ${error.message}\n`); - }, 30_000); -}); diff --git a/tests/caller-identity-attack-soul.test.ts b/tests/caller-identity-attack-soul.test.ts deleted file mode 100644 index 3ac3960..0000000 --- a/tests/caller-identity-attack-soul.test.ts +++ /dev/null @@ -1,362 +0,0 @@ -// Soul attack probes for the caller-identity cut, second pass. -// -// Same convention as caller-identity-soul.test.ts: plain `it` is an invariant -// that currently holds; `it.fails` is a hole the cut does not close (vitest -// passes the case while the body fails; close the hole and promote it). -import { afterEach, describe, expect, it } from "vitest"; -import { buildApp, refreshAppSession } from "../src/app.js"; -import { type AppCaller } from "../src/app-caller.js"; -import { builtInAppProfiles, isAllowedReturnOrigin } from "../src/app-profiles.js"; -import { type HeimdallConfig } from "../src/config.js"; -import { entitlementFacts } from "../src/facts.js"; -import { type OAuthProviderRuntime } from "../src/oauth.js"; -import { InMemoryStore } from "../src/store/index.js"; -import { launchState, stateOf } from "./oauth-flow.js"; - -const resources: Array<{ close(): Promise }> = []; - -afterEach(async () => { - await Promise.all(resources.splice(0).reverse().map((resource) => resource.close())); -}); - -function testConfig(): HeimdallConfig { - return { - serviceName: "heimdall", - host: "127.0.0.1", - port: 4100, - privateCommandHost: "127.0.0.1", - privateCommandPort: 0, - workspaceRoot: "F:/Projects/Heimdall", - dataRoot: "F:/Projects/Heimdall/.heimdall-data", - cultCachePath: "F:/Projects/Heimdall/.heimdall-data/cultcache/test.cc", - publicBaseUrl: "https://heimdall.gamecult.org", - issuer: "https://heimdall.gamecult.org", - daemonId: "yggdrasil-heimdall", - idunnRudpHealth: undefined, - idunnHealthContract: "heimdall.cultnet-rudp-provider-health", - providerHealthIdentityPath: "F:/Projects/Heimdall/.heimdall-data/provider-health-test.cc", - sessionTtlSeconds: 3600, - refreshTtlSeconds: 3600, - stateTtlSeconds: 600, - completionTtlSeconds: 300, - bootstrapSigningPrivateKeyOnMissing: false, - tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"), - appSharedSecrets: { repixelizer: "repixelizer-secret", ghostlight: "ghostlight-secret" }, - appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] }, - appBackendCallbacks: {}, - storage: { backend: "memory", applySchemaOnStartup: true }, - providers: { - discord: { clientId: "discord-client", clientSecret: "discord-secret" }, - patreon: {}, - github: {}, - twitch: {}, - youtube: {}, - spotify: {}, - joystick: {}, - google: {}, - }, - }; -} - -// The provider "code" doubles as the identity so one runtime can play both -// victim and attacker: code `victim` resolves to discord user `victim`. -function identityByCodeRuntime(): OAuthProviderRuntime { - return { - async exchangeAuthorizationCode({ code }) { - return { accessToken: code, tokenType: "Bearer", scope: ["identify"], raw: {} }; - }, - async resolveIdentity({ accessToken }) { - return { provider: "discord", providerUserId: accessToken, displayName: accessToken, profile: {} }; - }, - async evaluateEntitlements() { - return { facts: [entitlementFacts.appAccess], snapshots: [] }; - }, - }; -} - -async function harness() { - const store = new InMemoryStore(); - const app = await buildApp({ config: testConfig(), store, oauthRuntimes: { discord: identityByCodeRuntime() } }); - resources.push(app); - return { app, store }; -} - -type App = Awaited>["app"]; - -async function start(app: App, payload: Record, headers: Record = {}) { - return app.inject({ method: "POST", url: "/v1/oauth/discord/start", payload, headers }); -} - -async function completeAs(app: App, stateToken: string, who: string) { - const { cookie } = await launchState(app, stateToken); - return app.inject({ - method: "GET", - url: `/v1/oauth/discord/callback?code=${who}&state=${encodeURIComponent(stateToken)}`, - headers: { accept: "application/json", cookie }, - }); -} - -async function redeem(app: App, appSlug: string, completionCode: string) { - return app.inject({ method: "POST", url: `/v1/apps/${appSlug}/auth-completions/redeem`, payload: { completionCode } }); -} - -const uuidV4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; - -describe("takeover chain: caller-chosen attemptId is never the redemption code", () => { - it("attacker fixes attemptId, victim completes, attemptId does not redeem; the minted code is a fresh uuid v4", async () => { - const { app } = await harness(); - const started = await start(app, { - appSlug: "repixelizer", - mode: "sign_in", - returnTo: "https://repixelizer.gamecult.org/app/", - handoff: { kind: "browser_completion", attemptId: "attacker-fixed" }, - }); - expect(started.statusCode).toBe(201); - - const callback = await completeAs(app, stateOf(started.json()), "victim"); - expect(callback.statusCode).toBe(201); - const minted = callback.json().completion.code as string; - expect(minted).not.toBe("attacker-fixed"); - expect(minted).toMatch(uuidV4); - - const byAttempt = await redeem(app, "repixelizer", "attacker-fixed"); - expect(byAttempt.statusCode).toBe(410); - expect(byAttempt.json()).toEqual({ error: "invalid_or_expired_completion_code" }); - }); - - it("omitting handoff still mints a uuid v4 code; the attempt handle is absent from the completion", async () => { - const { app, store } = await harness(); - const started = await start(app, { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" }); - expect(started.statusCode).toBe(201); - const callback = await completeAs(app, stateOf(started.json()), "victim"); - expect(callback.statusCode).toBe(201); - const code = callback.json().completion.code as string; - expect(code).toMatch(uuidV4); - const stored = (store as unknown as { authCompletions: Map }).authCompletions.get(code); - expect(stored?.attemptId).toBeUndefined(); - }); - - it("handoff.kind backend_callback with an attemptId is refused unless the callbackUrl is configured", async () => { - const { app } = await harness(); - const started = await start(app, { - appSlug: "repixelizer", - mode: "sign_in", - returnTo: "https://repixelizer.gamecult.org/app/", - handoff: { kind: "backend_callback", attemptId: "attacker-fixed", callbackUrl: "https://attacker.example/cb" }, - }); - expect(started.statusCode).toBe(400); - expect(started.json().error).toBe("untrusted_backend_callback"); - }); - - it("an unknown handoff.kind is rejected by the schema", async () => { - const { app } = await harness(); - const started = await start(app, { - appSlug: "repixelizer", - mode: "sign_in", - returnTo: "https://repixelizer.gamecult.org/app/", - handoff: { kind: "evil", attemptId: "attacker-fixed" }, - }); - expect(started.statusCode).toBe(400); - }); - - it("attemptId set to a real victim completion code does not let the attacker's flow touch the victim's completion", async () => { - const { app } = await harness(); - const victimStart = await start(app, { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" }); - const victimCallback = await completeAs(app, stateOf(victimStart.json()), "victim"); - const victimCode = victimCallback.json().completion.code as string; - - const attackerStart = await start(app, { - appSlug: "repixelizer", - mode: "sign_in", - returnTo: "https://repixelizer.gamecult.org/app/", - handoff: { kind: "browser_completion", attemptId: victimCode }, - }); - const attackerCallback = await completeAs(app, stateOf(attackerStart.json()), "attacker"); - expect(attackerCallback.statusCode).toBe(201); - expect(attackerCallback.json().completion.code).not.toBe(victimCode); - - // The victim's code still redeems the victim, once. - const first = await redeem(app, "repixelizer", victimCode); - expect(first.statusCode).toBe(201); - expect(first.json().account.displayName).toBe("victim"); - }); - - it("the redeem route is unauthenticated, so the code is the whole secret: 122 bits of CSPRNG, distinct across mints", async () => { - const store = new InMemoryStore(); - const codes = new Set(); - for (let i = 0; i < 200; i += 1) { - const completion = await store.createAuthCompletion({ - appSlug: "repixelizer", - provider: "discord", - mode: "sign_in", - accountId: "a", - sessionId: "s", - returnTo: "https://repixelizer.gamecult.org/app/", - createdAt: "2026-01-01T00:00:00.000Z", - expiresAt: "2999-01-01T00:00:00.000Z", - payloadJson: {}, - }); - expect(completion.code).toMatch(uuidV4); - codes.add(completion.code); - } - expect(codes.size).toBe(200); - }); -}); - -describe("consumeAuthCompletion: single-use, scoped, expiring", () => { - it("a code redeems exactly once under concurrent redemption, and never for another app", async () => { - const { app } = await harness(); - const started = await start(app, { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" }); - const callback = await completeAs(app, stateOf(started.json()), "victim"); - const code = callback.json().completion.code as string; - - const crossApp = await redeem(app, "bifrost", code); - expect(crossApp.statusCode).toBe(410); - - const results = await Promise.all([redeem(app, "repixelizer", code), redeem(app, "repixelizer", code), redeem(app, "repixelizer", code)]); - expect(results.map((r) => r.statusCode).sort()).toEqual([201, 410, 410]); - }); - - it("an expired completion is not consumable, by code or by attempt", async () => { - const store = new InMemoryStore(); - const completion = await store.createAuthCompletion({ - attemptId: "h1", - appSlug: "repixelizer", - provider: "discord", - mode: "sign_in", - accountId: "a", - sessionId: "s", - returnTo: "https://repixelizer.gamecult.org/app/", - createdAt: "2026-01-01T00:00:00.000Z", - expiresAt: "2026-01-01T00:05:00.000Z", - payloadJson: {}, - }); - expect(await store.consumeAuthCompletion("repixelizer", completion.code, "2026-01-01T00:05:00.000Z")).toBeNull(); - expect(await store.consumeAuthCompletionByAttempt("repixelizer", "h1", "2026-01-01T00:05:00.000Z")).toBeNull(); - expect(await store.consumeAuthCompletionByAttempt("bifrost", "h1", "2026-01-01T00:04:00.000Z")).toBeNull(); - expect(await store.consumeAuthCompletionByAttempt("repixelizer", "h1", "2026-01-01T00:04:00.000Z")).not.toBeNull(); - expect(await store.consumeAuthCompletionByAttempt("repixelizer", "h1", "2026-01-01T00:04:00.000Z")).toBeNull(); - }); -}); - -describe("attempt-handle binding: the public start route may attach a completion to any attempt", () => { - // Closed (R21.1). The private plane creates attempt H for its app and later - // redeems by handle (consumeAuthCompletionByAttempt). handoff.attemptId is - // no longer read from the request body at all (normalizeOAuthHandoff always - // returns a bare `{ kind: "browser_completion" }` for a public caller); the - // only path by which an attempt handle reaches the signed state token is - // `startOAuthFlow`'s `trustedBrowserAttemptId` option, which only - // `beginAuth` (private-command-plane.ts) can set, from the handle it just - // minted server-side. A value that never crosses the public boundary cannot - // be chosen by a stranger, so a public flow carrying H as body JSON now has - // no effect on H at all. - it("a public flow carrying the app's attempt handle must not complete that attempt", async () => { - const { app, store } = await harness(); - const attempt = await store.createAuthAttempt({ - appSlug: "ghostlight", - provider: "discord", - mode: "sign_in", - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - createdAt: new Date().toISOString(), - expiresAt: new Date(Date.now() + 600_000).toISOString(), - }); - - // Ghostlight's start is the app's own: without its secret there is no state to complete with. - const attackerStart = await start(app, { - appSlug: "ghostlight", - mode: "sign_in", - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - handoff: { kind: "browser_completion", attemptId: attempt.handle }, - }); - expect([attackerStart.statusCode, attackerStart.json().error]).toEqual([401, "app_auth_required"]); - - const after = await store.findAuthAttempt("ghostlight", attempt.handle); - expect(after?.status).toBe("pending"); - const bound = await store.consumeAuthCompletionByAttempt("ghostlight", attempt.handle, new Date().toISOString()); - expect(bound).toBeNull(); - }); -}); - -describe("isAllowedReturnOrigin: origin comparison, not string matching", () => { - const profile = builtInAppProfiles.repixelizer; - // Narrow rather than cast: the lookup is Partial-typed, and a missing - // built-in should fail this suite loudly instead of being asserted away. - if (!profile) { - throw new Error("built-in repixelizer profile is missing"); - } - const rejected = [ - "https://repixelizer.gamecult.org.evil.com/", - "https://evil.com/?x=https://repixelizer.gamecult.org", - "https://repixelizer.gamecult.org@evil.com/", - "https://evil.com#https://repixelizer.gamecult.org", - "//repixelizer.gamecult.org/app/", - "http://repixelizer.gamecult.org/app/", - "https://repixelizer.gamecult.org:8443/app/", - "https://repixelizer.gamecult.org./app/", - "https://xn--repixelizer-gamecult.org/", - "javascript:alert(1)", - "data:text/html,hi", - "not a url", - "", - "https://repixelizer.gamecult.org.", - "https://repixelizer.gamecult.orgx/", - "https://sub.repixelizer.gamecult.org/", - ]; - it.each(rejected)("rejects %s", (returnTo) => { - expect(isAllowedReturnOrigin(profile, returnTo)).toBe(false); - }); - - // Accepted variants are all the same origin after WHATWG normalisation; - // they are listed so a future "fix" that switches to string comparison - // shows up as a behaviour change here rather than silently in production. - const acceptedSameOrigin = [ - "https://repixelizer.gamecult.org", - "https://repixelizer.gamecult.org/app/", - "https://REPIXELIZER.GameCult.org/app/", - "https://repixelizer.gamecult.org:443/app/", - "https:/\\repixelizer.gamecult.org/app/", - "https://user:pw@repixelizer.gamecult.org/app/", - "https://repixelizer.gamecult.org/app/?returnTo=https://evil.com", - ]; - it.each(acceptedSameOrigin)("accepts %s (same origin after URL parsing)", (returnTo) => { - expect(new URL(returnTo).origin).toBe("https://repixelizer.gamecult.org"); - expect(isAllowedReturnOrigin(profile, returnTo)).toBe(true); - }); - - it("an empty allowlist denies everything rather than passing vacuously", () => { - expect(isAllowedReturnOrigin({ ...profile, allowedReturnOrigins: [] }, "https://repixelizer.gamecult.org/")).toBe(false); - }); - - // The registered-app path this test covered (seedRegisteredApp, - // resolveAppProfile's non-built-in branch) was deleted in R21.3: every HTTP - // route already enumerates the four built-in slugs in its own JSON schema, - // so a registered row could never be reached over HTTP in the first place. - // An unknown slug is now refused by that schema directly. - it("an unknown appSlug cannot start a flow through HTTP at all (slug enum)", async () => { - const { app } = await harness(); - const started = await start(app, { appSlug: "newapp", mode: "sign_in", returnTo: "https://anything.example/" }); - expect(started.statusCode).toBe(400); - }); -}); - -describe("AppCaller brand: enforced by a module-private WeakSet (R21.2)", () => { - // Closed. brandCaller (app-caller.ts) registers every AppCaller it mints in - // a WeakSet that never leaves the module; isAppCaller is the only way a - // consumer may trust one, and startOAuthFlow / refreshAppSession now call - // it instead of trusting the AppCaller | null type alone. A forged literal - // — even one carrying the callerBrand symbol key by hand — was never added - // to the set and is rejected regardless of shape or cast. - it("a forged caller literal is refused at runtime", async () => { - const { app } = await harness(); - const context = (app as unknown as { heimdallContext: Parameters[0] }).heimdallContext; - const forged = { appSlug: "repixelizer" } as unknown as AppCaller; - const result = await refreshAppSession(context, "repixelizer", forged, { - refreshToken: "not-a-token", - entitlementPolicies: [{ kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }], - } as never); - // With a forged caller the request gets past the caller gate and fails - // later on the bogus refresh token (401 invalid_refresh_token / similar); - // a runtime brand check would return app_auth_required here. - expect(result.body).toMatchObject({ error: "app_auth_required" }); - }); -}); diff --git a/tests/caller-identity-soul.test.ts b/tests/caller-identity-soul.test.ts deleted file mode 100644 index d66f652..0000000 --- a/tests/caller-identity-soul.test.ts +++ /dev/null @@ -1,295 +0,0 @@ -// Soul falsification probes for the caller-identity cut (epiphany/heimdall-caller-identity). -// -// Two kinds of test live here: -// - plain `it(...)`: an invariant the cut claims and that currently holds. -// - `it.fails(...)`: an invariant the cut does NOT yet enforce. vitest passes -// the case while the body fails; when someone closes the hole the case -// flips to a real failure and must be promoted to a plain `it`. -import { readFileSync, readdirSync } from "node:fs"; -import { join } from "node:path"; -import { encode } from "@msgpack/msgpack"; -import { invokeCultNetOperation } from "cultnet-ts"; -import { afterEach, describe, expect, it } from "vitest"; -import { buildApp, refreshAppSession, startOAuthFlow } from "../src/app.js"; -import { callerFromOpenedEnvelope, secretMatches } from "../src/app-caller.js"; -import { type HeimdallConfig } from "../src/config.js"; -import { entitlementFacts } from "../src/facts.js"; -import { type OAuthProviderRuntime } from "../src/oauth.js"; -import { startHeimdallPrivateCommandPlane } from "../src/private-command-plane.js"; -import { sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "../src/private-command-security.js"; -import { InMemoryStore } from "../src/store/index.js"; -import { launchFlow } from "./oauth-flow.js"; - -const ghostlightSecret = "ghostlight-private-command-secret"; -const resources: Array<{ close(): Promise }> = []; - -afterEach(async () => { - await Promise.all(resources.splice(0).reverse().map((resource) => resource.close())); -}); - -function testConfig(): HeimdallConfig { - return { - serviceName: "heimdall", - host: "127.0.0.1", - port: 4100, - privateCommandHost: "127.0.0.1", - privateCommandPort: 0, - workspaceRoot: "F:/Projects/Heimdall", - dataRoot: "F:/Projects/Heimdall/.heimdall-data", - cultCachePath: "F:/Projects/Heimdall/.heimdall-data/cultcache/test.cc", - publicBaseUrl: "https://heimdall.gamecult.org", - issuer: "https://heimdall.gamecult.org", - daemonId: "yggdrasil-heimdall", - idunnRudpHealth: undefined, - idunnHealthContract: "heimdall.cultnet-rudp-provider-health", - providerHealthIdentityPath: "F:/Projects/Heimdall/.heimdall-data/provider-health-test.cc", - sessionTtlSeconds: 3600, - refreshTtlSeconds: 3600, - stateTtlSeconds: 600, - completionTtlSeconds: 300, - bootstrapSigningPrivateKeyOnMissing: false, - tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"), - appSharedSecrets: { repixelizer: "repixelizer-secret", ghostlight: ghostlightSecret }, - appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] }, - appBackendCallbacks: {}, - storage: { backend: "memory", applySchemaOnStartup: true }, - providers: { - discord: { clientId: "discord-client", clientSecret: "discord-secret" }, - patreon: {}, - github: {}, - twitch: {}, - youtube: {}, - spotify: {}, - joystick: {}, - google: {}, - }, - }; -} - -function mockDiscordRuntime(): OAuthProviderRuntime { - return { - async exchangeAuthorizationCode() { - return { accessToken: "provider-access", tokenType: "Bearer", scope: ["identify"], raw: {} }; - }, - async resolveIdentity() { - return { provider: "discord", providerUserId: "discord-victim", displayName: "Victim", profile: {} }; - }, - async evaluateEntitlements() { - return { facts: [entitlementFacts.appAccess], snapshots: [] }; - }, - }; -} - -describe("caller identity: unauthenticated mint paths", () => { - // Item 1 (closed). The completion code used to be chosen by whoever started - // the flow (handoff.attemptId became the completion code verbatim, - // src/app.ts createAuthCompletion `code: handoff.attemptId`), and - // auth-completions/redeem takes no app secret. An unauthenticated party - // could therefore fix the code, get a victim to finish provider login on - // the authorization URL, and redeem the victim's signed access + refresh - // tokens. The store now always mints the code itself; attemptId is kept - // only as a separate correlation field the browser may carry. - it("a client-chosen attemptId must not be redeemable for signed tokens without app auth", async () => { - const app = await buildApp({ config: testConfig(), oauthRuntimes: { discord: mockDiscordRuntime() } }); - resources.push(app); - - const start = await app.inject({ - method: "POST", - url: "/v1/oauth/discord/start", - payload: { - appSlug: "repixelizer", - mode: "sign_in", - returnTo: "https://repixelizer.gamecult.org/app/", - handoff: { kind: "browser_completion", attemptId: "attacker-fixed-code" }, - }, - // no x-heimdall-app-secret - }); - expect(start.statusCode).toBe(201); - - const flow = await launchFlow(app, start.json()); - const callback = await app.inject({ - method: "GET", - url: `/v1/oauth/discord/callback?code=victim-code&state=${encodeURIComponent(flow.state)}`, - headers: { accept: "text/html", cookie: flow.cookie }, - }); - expect(callback.statusCode).toBe(200); - - const redeem = await app.inject({ - method: "POST", - url: "/v1/apps/repixelizer/auth-completions/redeem", - payload: { completionCode: "attacker-fixed-code" }, - // still no x-heimdall-app-secret - }); - - // The invariant the cut claims: the caller-chosen code is never minted, - // so it can never be redeemed. - expect(redeem.statusCode).not.toBe(201); - expect(redeem.json().accessToken).toBeUndefined(); - }); - - // Item 2 (closed). returnTo used to be validated only as `format: uri`. The - // success page postMessages the completion payload to - // new URL(returnTo).origin and links to returnTo with the code in the - // fragment (src/browser-handoff.ts), so an unlisted origin was an - // exfiltration primitive. startOAuthFlow now refuses any returnTo whose - // origin is not in the app profile's allowedReturnOrigins. - it("an unauthenticated start must not accept an arbitrary returnTo origin", async () => { - const app = await buildApp({ config: testConfig(), oauthRuntimes: { discord: mockDiscordRuntime() } }); - resources.push(app); - - const start = await app.inject({ - method: "POST", - url: "/v1/oauth/discord/start", - payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://attacker.example/collect" }, - }); - - expect(start.statusCode).not.toBe(201); - }); - - it("refuses to mint on refresh when the caller supplies policy without app auth", async () => { - const app = await buildApp({ config: testConfig(), oauthRuntimes: { discord: mockDiscordRuntime() } }); - resources.push(app); - const context = (app as unknown as { heimdallContext: Parameters[0] }).heimdallContext; - const policy = { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }; - - const nullCaller = await refreshAppSession(context, "repixelizer", null, { - refreshToken: "irrelevant", - entitlementPolicy: policy, - } as Parameters[3]); - expect(nullCaller).toEqual({ statusCode: 401, body: { error: "app_auth_required" } }); - - const wrongApp = await refreshAppSession(context, "repixelizer", callerFromOpenedEnvelope("ghostlight"), { - refreshToken: "irrelevant", - entitlementPolicy: policy, - } as Parameters[3]); - expect(wrongApp).toEqual({ statusCode: 401, body: { error: "app_auth_required" } }); - - const nullStart = await startOAuthFlow(context, "discord", null, { - appSlug: "repixelizer", - mode: "sign_in", - returnTo: "https://repixelizer.gamecult.org/app/", - entitlementPolicy: policy, - } as Parameters[3]); - expect(nullStart).toEqual({ statusCode: 401, body: { error: "app_auth_required" } }); - }); -}); - -describe("caller identity: single authority", () => { - // Item 2. Source tripwire: the header may be read in exactly one module, - // and the per-app secret table may be read only by the two envelope - // openers (HTTP header comparator, private-plane HMAC/AES-GCM opener). - const srcRoot = join(__dirname, "..", "src"); - const sources = readdirSync(srcRoot) - .filter((name) => name.endsWith(".ts")) - .map((name) => [name, readFileSync(join(srcRoot, name), "utf8")] as const); - - it("x-heimdall-app-secret is read only in app-caller.ts", () => { - const readers = sources - .filter(([, text]) => /headers\[\s*["']x-heimdall-app-secret["']\s*\]/.test(text)) - .map(([name]) => name); - expect(readers).toEqual(["app-caller.ts"]); - }); - - it("appSharedSecrets is read only by the HTTP comparator and the private-plane envelope opener", () => { - const readers = sources - .filter(([, text]) => /appSharedSecrets\s*[\[.]/.test(text)) - .map(([name]) => name) - .sort(); - expect(readers).toEqual(["app-caller.ts", "private-command-plane.ts"]); - }); - - it("no source file compares a shared secret with ===", () => { - const offenders = sources - .filter(([, text]) => /[sS]ecret\w*\s*===|===\s*\w*[sS]ecret/.test(text)) - .map(([name]) => name); - expect(offenders).toEqual([]); - }); - - it("AppCaller literals are constructed nowhere; AppCaller is a branded type", () => { - // Item 3 (closed). `{ appSlug }` used to satisfy AppCaller structurally, - // so the private plane (after openPrivateEnvelope + sourceRuntimeId) - // constructed the literal directly — nothing but grep discipline stopped - // any other importer from doing the same. AppCaller is now branded with - // an unexported symbol, and the private plane gets its caller from - // app-caller.ts's callerFromOpenedEnvelope, the same way the HTTP path - // gets its caller from resolveAppCaller. No file may construct the - // literal at all anymore. - const forgers = sources - .filter(([name, text]) => name !== "app-caller.ts" && /(startOAuthFlow|refreshAppSession)\([^;]*\{\s*appSlug\s*\}/s.test(text)) - .map(([name]) => name); - expect(forgers).toEqual([]); - }); -}); - -describe("caller identity: timing-safe comparator", () => { - // Item 4. - it("secretMatches rejects mismatches of any length and both empty sides", () => { - expect(secretMatches("abc", "abd")).toBe(false); - expect(secretMatches("abc", "abcd")).toBe(false); - expect(secretMatches("abc", "")).toBe(false); - expect(secretMatches(undefined, "abc")).toBe(false); - expect(secretMatches("abc", undefined)).toBe(false); - expect(secretMatches("", "")).toBe(false); - expect(secretMatches("abc", "abc")).toBe(true); - }); - - it("app-caller.ts is the only HTTP-side importer of timingSafeEqual", () => { - const srcRoot = join(__dirname, "..", "src"); - const importers = readdirSync(srcRoot) - .filter((name) => name.endsWith(".ts")) - .filter((name) => /timingSafeEqual/.test(readFileSync(join(srcRoot, name), "utf8"))) - .sort(); - expect(importers).toEqual(["app-caller.ts", "private-command-security.ts"]); - }); -}); - -describe("caller identity: private plane envelope authority", () => { - // Item 3. A correctly sealed envelope from the wrong sourceRuntimeId must - // be refused before beginAuth constructs an AppCaller: no auth attempt may - // be created. - it("refuses a valid envelope from an unconfigured runtime before any attempt is created", async () => { - const config = testConfig(); - const store = new InMemoryStore(); - const app = await buildApp({ config, store, oauthRuntimes: { discord: mockDiscordRuntime() } }); - resources.push(app); - const plane = await startHeimdallPrivateCommandPlane(app, config); - resources.push(plane); - - const envelope = sealPrivateEnvelope({ - appSlug: "ghostlight", - operation: "heimdall.auth.begin", - contentSchema: "heimdall.auth_begin_command.v1", - idempotencyKey: "soul-begin-1", - secret: ghostlightSecret, - payload: { - provider: "discord", - mode: "sign_in", - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - entitlementPolicy: { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }, - }, - }); - - const response = await invokeCultNetOperation( - plane.endpoint, - request("heimdall.auth.begin", "soul-wrong-runtime", envelope, "not-ghostlight"), - { runtimeId: "not-ghostlight" } - ); - expect(response.status).toBe("denied"); - - const internals = store as unknown as { authAttempts: Map }; - expect(internals.authAttempts.size).toBe(0); - }, 20_000); -}); - -function request(operation: string, messageId: string, envelope: HeimdallPrivateEnvelope, sourceRuntimeId: string) { - return { - schemaVersion: "cultnet.operation_request.v0" as const, - messageId, - serviceId: "heimdall.private.commands", - operation, - payloadSchema: "heimdall.private_command_envelope.v1", - payloadEncoding: "messagepack-base64" as const, - payload: Buffer.from(encode(envelope)).toString("base64"), - sourceRuntimeId, - }; -} diff --git a/tests/caller-identity.test.ts b/tests/caller-identity.test.ts new file mode 100644 index 0000000..12e24f8 --- /dev/null +++ b/tests/caller-identity.test.ts @@ -0,0 +1,266 @@ +import { encode, decode } from "@msgpack/msgpack"; +import { invokeCultNetOperation } from "cultnet-ts"; +import { afterEach, describe, expect, it } from "vitest"; +import { buildApp, getHeimdallRuntimeContext, refreshAppSession, startOAuthFlow } from "../src/app.js"; +import { callerFromOpenedEnvelope, resolveAppCaller, secretMatches } from "../src/app-caller.js"; +import { type HeimdallConfig } from "../src/config.js"; +import { entitlementFacts } from "../src/facts.js"; +import { type OAuthProviderRuntime } from "../src/oauth.js"; +import { startHeimdallPrivateCommandPlane } from "../src/private-command-plane.js"; +import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "../src/private-command-security.js"; +import { InMemoryStore } from "../src/store/index.js"; +import { createTestConfig, launchFlow, launchState } from "./oauth-flow.js"; + +const ghostlightSecret = "ghostlight-private-command-secret"; +const resources: Array<{ close(): Promise }> = []; + +afterEach(async () => { + await Promise.all(resources.splice(0).reverse().map((resource) => resource.close())); +}); + +function callerTestConfig(): HeimdallConfig { + const base = createTestConfig(); + return { + ...base, + privateCommandHost: "127.0.0.1", + privateCommandPort: 0, + appSharedSecrets: { + ...base.appSharedSecrets, + ghostlight: ghostlightSecret, + }, + appRuntimeIds: { + ghostlight: ["yggdrasil-ghostlight"], + }, + }; +} + +function identityByCodeRuntime(): OAuthProviderRuntime { + return { + async exchangeAuthorizationCode({ code }) { + return { accessToken: code, tokenType: "Bearer", scope: ["identify"], raw: {} }; + }, + async resolveIdentity({ accessToken }) { + return { provider: "discord", providerUserId: accessToken, displayName: accessToken, profile: {} }; + }, + async evaluateEntitlements() { + return { facts: [entitlementFacts.appAccess], snapshots: [] }; + }, + }; +} + +async function createHarness() { + const config = callerTestConfig(); + const store = new InMemoryStore(); + const app = await buildApp({ config, store, oauthRuntimes: { discord: identityByCodeRuntime() } }); + resources.push(app); + return { app, store, config }; +} + +function jwtPayload(token: string): Record { + const [, body] = token.split("."); + return JSON.parse(Buffer.from(body ?? "", "base64url").toString("utf8")) as Record; +} + +describe("caller identity and secret comparison", () => { + it("secretMatches rejects mismatches of any length and empty/missing inputs", () => { + expect(secretMatches("abc", "abd")).toBe(false); + expect(secretMatches("abc", "abcd")).toBe(false); + expect(secretMatches("abc", "")).toBe(false); + expect(secretMatches(undefined, "abc")).toBe(false); + expect(secretMatches("abc", undefined)).toBe(false); + expect(secretMatches("", "")).toBe(false); + expect(secretMatches("abc", "abc")).toBe(true); + }); + + it("refuses missing or wrong secrets on startRequiresAppCaller and policy routes", async () => { + const { app, config } = await createHarness(); + const ctx = getHeimdallRuntimeContext(app); + + for (const headers of [undefined, {}, { "x-heimdall-app-secret": "wrong-secret" }, { "x-heimdall-app-secret": "repixelizer-secret" }]) { + const response = await app.inject({ + method: "POST", + url: "/v1/oauth/discord/start", + ...(headers ? { headers } : {}), + payload: { + appSlug: "ghostlight", + mode: "sign_in", + returnTo: "https://yggdrasil.gamecult.org/ghostlight/", + }, + }); + expect([response.statusCode, response.json().error]).toEqual([401, "app_auth_required"]); + } + + const repixelizerCaller = resolveAppCaller(config, "repixelizer", { "x-heimdall-app-secret": "repixelizer-secret" }); + expect(repixelizerCaller?.appSlug).toBe("repixelizer"); + + const policy = { kind: "discord_role_access" as const, guildId: "g", allowedRoleIds: ["r"] }; + expect(await startOAuthFlow(ctx, "discord", null, { + appSlug: "repixelizer", + mode: "sign_in", + returnTo: "https://repixelizer.gamecult.org/app/", + entitlementPolicy: policy, + })).toEqual({ statusCode: 401, body: { error: "app_auth_required" } }); + + expect(await refreshAppSession(ctx, "repixelizer", callerFromOpenedEnvelope("ghostlight"), { + refreshToken: "irrelevant", + entitlementPolicies: [policy], + })).toEqual({ statusCode: 401, body: { error: "app_auth_required" } }); + }); + + it("drops caller-supplied attemptId on HTTP starts and rejects untrusted returnTo origins", async () => { + const { app } = await createHarness(); + + const untrustedReturn = await app.inject({ + method: "POST", + url: "/v1/oauth/discord/start", + payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://attacker.example/collect" }, + }); + expect(untrustedReturn.statusCode).toBe(400); + + const start = await app.inject({ + method: "POST", + url: "/v1/oauth/discord/start", + payload: { + appSlug: "repixelizer", + mode: "sign_in", + returnTo: "https://repixelizer.gamecult.org/app/", + handoff: { kind: "browser_completion", attemptId: "attacker-fixed-code" }, + }, + }); + expect(start.statusCode).toBe(201); + expect(start.json().handoff).toEqual({ kind: "browser_completion" }); + + const flow = await launchFlow(app, start.json()); + const callback = await app.inject({ + method: "GET", + url: `/v1/oauth/discord/callback?code=victim&state=${encodeURIComponent(flow.state)}`, + headers: { accept: "application/json", cookie: flow.cookie }, + }); + expect(callback.statusCode).toBe(201); + const mintedCode = callback.json().completion.code as string; + expect(mintedCode).not.toBe("attacker-fixed-code"); + + const byAttempt = await app.inject({ + method: "POST", + url: "/v1/apps/repixelizer/auth-completions/redeem", + payload: { completionCode: "attacker-fixed-code" }, + }); + expect(byAttempt.statusCode).toBe(410); + + const crossApp = await app.inject({ + method: "POST", + url: "/v1/apps/bifrost/auth-completions/redeem", + payload: { completionCode: mintedCode }, + }); + expect(crossApp.statusCode).toBe(410); + }); + + it("returns 404 for unknown and prototype keys on GET /v1/apps/:appSlug", async () => { + const { app } = await createHarness(); + for (const key of ["nope", "constructor", "toString", "__proto__", "hasOwnProperty"]) { + const response = await app.inject({ method: "GET", url: `/v1/apps/${key}` }); + expect(response.statusCode, key).toBe(404); + } + }); +}); + +describe("private command plane caller authentication", () => { + function envelopeRequest(operation: string, messageId: string, envelope: HeimdallPrivateEnvelope, sourceRuntimeId: string) { + return { + schemaVersion: "cultnet.operation_request.v0" as const, + messageId, + serviceId: "heimdall.private.commands", + operation, + payloadSchema: "heimdall.private_command_envelope.v1", + payloadEncoding: "messagepack-base64" as const, + payload: Buffer.from(encode(envelope)).toString("base64"), + sourceRuntimeId, + }; + } + + it("refuses an unconfigured sourceRuntimeId before creating an auth attempt", async () => { + const { app, store, config } = await createHarness(); + const plane = await startHeimdallPrivateCommandPlane(app, config); + resources.push(plane); + + const envelope = sealPrivateEnvelope({ + appSlug: "ghostlight", + operation: "heimdall.auth.begin", + contentSchema: "heimdall.auth_begin_command.v1", + idempotencyKey: "wrong-runtime-begin", + secret: ghostlightSecret, + payload: { + provider: "discord", + mode: "sign_in", + returnTo: "https://yggdrasil.gamecult.org/ghostlight/", + }, + }); + + const response = await invokeCultNetOperation( + plane.endpoint, + envelopeRequest("heimdall.auth.begin", "msg-wrong-runtime", envelope, "not-ghostlight"), + { runtimeId: "not-ghostlight" } + ); + expect(response.status).toBe("denied"); + expect((store as unknown as { authAttempts: Map }).authAttempts.size).toBe(0); + }, 20_000); + + it("binds server-minted attempt handle on begin, correlates callback, and redeems on complete", async () => { + const { app, store, config } = await createHarness(); + const plane = await startHeimdallPrivateCommandPlane(app, config); + resources.push(plane); + + const beginEnvelope = sealPrivateEnvelope({ + appSlug: "ghostlight", + operation: "heimdall.auth.begin", + contentSchema: "heimdall.auth_begin_command.v1", + idempotencyKey: "legit-begin", + secret: ghostlightSecret, + payload: { + provider: "discord", + mode: "sign_in", + returnTo: "https://yggdrasil.gamecult.org/ghostlight/", + }, + }); + const beginResponse = await invokeCultNetOperation( + plane.endpoint, + envelopeRequest("heimdall.auth.begin", "msg-begin", beginEnvelope, "yggdrasil-ghostlight"), + { runtimeId: "yggdrasil-ghostlight" } + ); + expect(beginResponse.status).toBe("accepted"); + const receipt = openPrivateEnvelope(decode(Buffer.from(beginResponse.payload, "base64")) as HeimdallPrivateEnvelope, ghostlightSecret); + expect(receipt.status).toBe("pending"); + + const handle = String(receipt.handle); + const state = new URL((receipt.navigation as { url: string }).url).searchParams.get("state") ?? ""; + expect(jwtPayload(state).handoff).toEqual({ kind: "browser_completion", attemptId: handle }); + + const { cookie } = await launchState(app, state); + const callback = await app.inject({ + method: "GET", + url: `/v1/oauth/discord/callback?code=victim&state=${encodeURIComponent(state)}`, + headers: { accept: "application/json", cookie }, + }); + expect(callback.statusCode).toBe(201); + expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("completed"); + + const completeEnvelope = sealPrivateEnvelope({ + appSlug: "ghostlight", + operation: "heimdall.auth.complete", + contentSchema: "heimdall.auth_complete_command.v1", + idempotencyKey: "legit-complete", + secret: ghostlightSecret, + payload: { handle }, + }); + const completeResponse = await invokeCultNetOperation( + plane.endpoint, + envelopeRequest("heimdall.auth.complete", "msg-complete", completeEnvelope, "yggdrasil-ghostlight"), + { runtimeId: "yggdrasil-ghostlight" } + ); + expect(completeResponse.status).toBe("accepted"); + const completed = openPrivateEnvelope(decode(Buffer.from(completeResponse.payload, "base64")) as HeimdallPrivateEnvelope, ghostlightSecret); + expect(completed.status).toBe("authenticated"); + expect(completed.accessToken).toEqual(expect.any(String)); + expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("consumed"); + }, 20_000); +}); From 509bf3a8560f8484c38f9361a1cda55df09ef025 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:11:30 +0100 Subject: [PATCH 58/63] Steward cut 4: export declarative ENV_NAMES/SECRET_ENV_NAMES and trim recipe/entrypoint secret tests --- src/config.ts | 47 +++++ tests/entrypoint-secrets.test.ts | 285 +++++++++---------------------- tests/recipe-secrets.test.ts | 260 +++++----------------------- 3 files changed, 167 insertions(+), 425 deletions(-) diff --git a/src/config.ts b/src/config.ts index 39ab96f..3f0461e 100644 --- a/src/config.ts +++ b/src/config.ts @@ -49,6 +49,53 @@ export interface HeimdallConfig { providers: Record; } +/** Secret inputs read via `readSecretInput` (as `NAME_FILE` under Idunn, or legacy plaintext `NAME`). */ +export const SECRET_ENV_NAMES: readonly string[] = [ + "GC_ACCESS_DATABASE_URL", + "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64", + "GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET", + ...providers.map((provider) => `GC_ACCESS_PROVIDER_${provider.toUpperCase()}_CLIENT_SECRET`), + ...appSlugs.map((appSlug) => `GC_ACCESS_APP_${appSlug.toUpperCase()}_SHARED_SECRET`), +]; + +const NON_SECRET_ENV_NAMES: readonly string[] = [ + "HOST", + "PORT", + "GAMECULT_IDUNN_CANDIDATE_BIND", + "GAMECULT_IDUNN_PROCESS_WRITE_LEASE", + "GAMECULT_IDUNN_RUNTIME_BUNDLE", + "GC_ACCESS_BASE_URL", + "GC_ACCESS_ISSUER", + "GC_ACCESS_DATA_ROOT", + "GC_ACCESS_STORAGE_BACKEND", + "GC_ACCESS_PRIVATE_COMMAND_HOST", + "GC_ACCESS_PRIVATE_COMMAND_PORT", + "GC_ACCESS_CULTCACHE_PATH", + "GC_ACCESS_IDUNN_DAEMON", + "GC_ACCESS_IDUNN_RUDP_HEALTH", + "GC_ACCESS_IDUNN_HEALTH_CONTRACT", + "GC_ACCESS_PROVIDER_HEALTH_IDENTITY_PATH", + "GC_ACCESS_SESSION_TTL_SECONDS", + "GC_ACCESS_REFRESH_TTL_SECONDS", + "GC_ACCESS_STATE_TTL_SECONDS", + "GC_ACCESS_COMPLETION_TTL_SECONDS", + "GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP", + "GC_ACCESS_APPLY_SCHEMA_ON_STARTUP", + "GC_ACCESS_ODIN_CULTMESH_URI", + "GC_ACCESS_SIGNING_PRIVATE_KEY_PATH", + "GC_ACCESS_SIGNING_KEY_ID", + "GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT", + ...providers.map((provider) => `GC_ACCESS_PROVIDER_${provider.toUpperCase()}_CLIENT_ID`), + ...appSlugs.map((appSlug) => `GC_ACCESS_APP_${appSlug.toUpperCase()}_BACKEND_CALLBACK_URLS`), + ...appSlugs.map((appSlug) => `GC_ACCESS_APP_${appSlug.toUpperCase()}_RUNTIME_IDS`), +]; + +/** Canonical environment variable names read by `loadConfig` (using `*_FILE` for secrets). */ +export const ENV_NAMES: readonly string[] = [ + ...NON_SECRET_ENV_NAMES, + ...SECRET_ENV_NAMES.map((name) => `${name}_FILE`), +]; + function trimTrailingSlash(value: string): string { return value.replace(/\/+$/, ""); } diff --git a/tests/entrypoint-secrets.test.ts b/tests/entrypoint-secrets.test.ts index 941c8c5..90b6a76 100644 --- a/tests/entrypoint-secrets.test.ts +++ b/tests/entrypoint-secrets.test.ts @@ -1,65 +1,35 @@ import { spawn } from "node:child_process"; -import { chmodSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { createRequire } from "node:module"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { afterAll, describe, expect, it } from "vitest"; -// A secret must never reach a terminal. Under Idunn, Heimdall's stderr goes to -// the journal and the install script tails the journal to the operator's -// terminal, so the layer that matters is the process's own output, not an -// error's message. These cases run the real entrypoint with canary values in -// the places a misbinding puts secrets, and fail on any byte of the canary -// anywhere on stdout or stderr: in a message, an error cause, an error -// property, or anything else Node chooses to print. - const repoRoot = fileURLToPath(new URL("..", import.meta.url)); const tsxCli = createRequire(import.meta.url).resolve("tsx/cli"); const scratch = mkdtempSync(join(tmpdir(), "heimdall-entrypoint-")); +chmodSync(scratch, 0o755); const CANARY = "CANARY"; afterAll(() => { rmSync(scratch, { recursive: true, force: true }); }); -function file(name: string, contents: string): string { - const path = join(scratch, name); - writeFileSync(path, contents); - return path; +function secretFile(name: string, contents: string): string { + const filePath = join(scratch, name); + writeFileSync(filePath, contents); + return filePath; } -interface Run { - code: number | null; - signal: NodeJS.Signals | null; - output: string; +function canaryTokenKey(): string { + return `${CANARY}key`.padEnd(43, "A") + "="; } -interface Identity { - uid: number; - gid: number; -} - -/** - * Who can be denied a read. Root reads a mode-000 file, so a read failure is - * only reachable as another user: the process itself when it is not root, or - * else the checkout's owner, who can still load the entrypoint. A string is - * the reason no such user exists here. - */ -function nonRootReader(): Identity | "self" | string { - if (process.platform === "win32") return "file modes do not deny reads on Windows"; - if (process.getuid?.() !== 0) return "self"; - const owner = statSync(repoRoot); - if (owner.uid === 0) return "running as root in a root-owned checkout, so no other user can load the entrypoint"; - return { uid: owner.uid, gid: owner.gid }; -} - -/** Runs `tsx src/index.ts` with only the given environment, merging stdout and stderr. */ -function runEntrypoint(name: string, env: Record, identity?: Identity): Promise { +function runEntrypoint(name: string, env: Record): Promise<{ code: number | null; signal: NodeJS.Signals | null; output: string }> { return new Promise((resolve, reject) => { const child = spawn(process.execPath, [tsxCli, "src/index.ts"], { cwd: repoRoot, - ...identity, env: { PATH: process.env.PATH ?? "", HOME: scratch, @@ -73,7 +43,6 @@ function runEntrypoint(name: string, env: Record, identity?: Ide let output = ""; child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString("utf8"))); child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString("utf8"))); - // A case that fails to fail would start serving; stop it rather than hang. const timer = setTimeout(() => child.kill("SIGKILL"), 30_000); child.on("error", reject); child.on("close", (code, signal) => { @@ -83,171 +52,81 @@ function runEntrypoint(name: string, env: Record, identity?: Ide }); } -/** A base64 value that decodes to exactly 32 bytes and still carries the canary. */ -function canaryTokenKey(tag: string): string { - return `${CANARY}${tag}`.padEnd(43, "A") + "="; -} - -interface Case { - name: string; - env: () => Record; - /** Something the failure must say, so a case cannot pass by never reaching its path. */ - expect: RegExp; - /** Run the entrypoint as a user a file mode can refuse. */ - nonRoot?: true; -} - -const cases: Case[] = [ - { - name: "a URL bound into an absolute _FILE slot", - env: () => ({ GC_ACCESS_DATABASE_URL_FILE: `/postgres://heimdall:${CANARY}url@db/heimdall` }), - expect: /GC_ACCESS_DATABASE_URL_FILE could not be read \(ENOENT\)/, - }, - { - name: "a _FILE path under a regular file", - env: () => ({ GC_ACCESS_DATABASE_URL_FILE: join(file("plain", "x"), `${CANARY}notdir`) }), - expect: /GC_ACCESS_DATABASE_URL_FILE could not be read \(ENOTDIR\)/, - }, - { - name: "a secret bound into a relative _FILE slot", - env: () => ({ GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE: `${CANARY}relative-secret` }), - expect: /GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE is not an absolute path/, - }, - { - name: "a secret bound both ways", - env: () => ({ - GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET: `${CANARY}plain`, - GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET_FILE: file("both", `${CANARY}file\n`), - }), - expect: /GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET and GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET_FILE are both set/, - }, - { - name: "a blank secret file", - env: () => ({ GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE: join(scratch, "blank") }), - expect: /GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE is empty/, - }, - { - name: "a token key that decodes short", - env: () => ({ GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE: file("short-key", `${CANARY}shortkey\n`) }), - expect: /GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE must decode to exactly 32 bytes/, - }, - { - name: "a database URL with an unusable port", - env: () => ({ GC_ACCESS_DATABASE_URL_FILE: file("db-port", `postgres://heimdall:${CANARY}port@db:notaport/heimdall\n`) }), - expect: /Postgres storage could not be prepared \(ERR_INVALID_URL\)/, - }, - { - name: "a database URL that does not parse", - env: () => ({ GC_ACCESS_DATABASE_URL_FILE: file("db-parse", `postgres://heimdall:${CANARY} parse@[bad/heimdall\n`) }), - expect: /Postgres storage could not be prepared \(E[A-Z_]+\)/, - }, - { - name: "a database URL with a broken percent escape", - env: () => ({ GC_ACCESS_DATABASE_URL_FILE: file("db-percent", `postgres://heimdall:${CANARY}%zz@127.0.0.1:1/heimdall\n`) }), - expect: /Postgres storage could not be prepared \(ECONNREFUSED\)/, - }, - { - name: "a database that refuses the connection", - env: () => ({ GC_ACCESS_DATABASE_URL_FILE: file("db-refused", `postgres://heimdall:${CANARY}refused@127.0.0.1:1/heimdall\n`) }), - expect: /Postgres storage could not be prepared \(ECONNREFUSED\)/, - }, - { - // A password holding an unescaped delimiter moves part of it into the - // host, and the resolver's error names the host. - name: "a database host that does not resolve", - env: () => ({ GC_ACCESS_DATABASE_URL_FILE: file("db-host", `postgres://heimdall:pw@${CANARY}host.invalid/heimdall\n`) }), - expect: /Postgres storage could not be prepared \(E[A-Z_]+\)/, - }, - { - // A start that does not apply the schema still connects, so a misbound URL - // fails at startup rather than in a request's error answer. - name: "a database host that does not resolve, on a start that does not apply the schema", - env: () => ({ - GC_ACCESS_APPLY_SCHEMA_ON_STARTUP: "0", - GC_ACCESS_DATABASE_URL_FILE: file("db-host-noapply", `postgres://heimdall:pw@${CANARY}host.invalid/heimdall\n`), - }), - expect: /Postgres storage could not be prepared \(E[A-Z_]+\)/, - }, - { - name: "private key text bound to the signing key path", - env: () => ({ - GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: `-----BEGIN PRIVATE KEY-----\n${CANARY}pem\n-----END PRIVATE KEY-----\n`, - }), - expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH is not an absolute path/, - }, - { - name: "a signing key path that names no file", - env: () => ({ GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: join(scratch, `${CANARY}missing-key`) }), - expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH names no file \(ENOENT\)/, - }, - { - name: "a signing key file that is not a key", - env: () => ({ GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: file("not-a-key", `${CANARY}notakey\n`) }), - expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH does not hold a usable private key/, - }, - { - name: "a signing key file its reader may not read", - env: () => { - const key = file(`${CANARY}locked-key`, `${CANARY}pem\n`); - chmodSync(key, 0o000); - const dataRoot = join(scratch, "locked-key-data"); - mkdirSync(dataRoot, { recursive: true }); - chmodSync(dataRoot, 0o777); - return { GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: key, GC_ACCESS_DATA_ROOT: dataRoot }; - }, - expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH could not be read \(EACCES\)/, - nonRoot: true, - }, - { - name: "a signing key path that is a directory", - env: () => { - const dir = join(scratch, "key-dir"); - mkdirSync(dir, { recursive: true }); - return { GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: dir }; - }, - expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH could not be read \(EISDIR\)/, - }, - { - name: "a bootstrapped signing key whose directory cannot be created", - env: () => ({ - GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: join(file("key-parent", "x"), `${CANARY}dir`, "key.pem"), - GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP: "1", - }), - expect: /GC_ACCESS_SIGNING_PRIVATE_KEY_PATH could not be created \(ENOTDIR\)/, - }, - { - // Every secret is configured and valid, and startup fails afterwards, in - // the entrypoint's own catch: the one place that holds the whole config. - name: "a listen failure with every secret configured", - env: () => ({ +describe("entrypoint startup and secret redaction smoke checks", () => { + it("startup failure redacts configured secrets from stdout and stderr", async () => { + const run = await runEntrypoint("redact", { HOST: "203.0.113.1", - GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE: file("listen-key", `${canaryTokenKey("key")}\n`), - GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE: file("listen-patron", `${CANARY}patron\n`), - GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET_FILE: file("listen-github", `${CANARY}github\n`), - GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE: file("listen-bifrost", `${CANARY}bifrost\n`), - }), - expect: /Heimdall failed to start/, - }, -]; + GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE: secretFile("token-key", `${canaryTokenKey()}\n`), + GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE: secretFile("bifrost-secret", `${CANARY}bifrost\n`), + GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET_FILE: secretFile("github-secret", `${CANARY}github\n`), + }); -describe("the entrypoint never prints a secret", () => { - writeFileSync(join(scratch, "blank"), " \n"); - // mkdtemp makes the scratch directory private to its creator; a non-root - // reader must still reach the files a case names inside it. - chmodSync(scratch, 0o755); - const reader = nonRootReader(); + expect(run.signal).toBeNull(); + expect(run.code).not.toBe(0); + expect(run.output).toMatch(/Heimdall failed to start/); + expect(run.output).not.toContain(CANARY); + }, 45_000); - for (const testCase of cases) { - const skipReason = testCase.nonRoot && typeof reader === "string" && reader !== "self" ? reader : undefined; - const title = `refuses ${testCase.name} without printing the canary${skipReason ? ` (skipped: ${skipReason})` : ""}`; - it.skipIf(skipReason !== undefined)(title, async () => { - const identity = testCase.nonRoot && typeof reader === "object" ? reader : undefined; - const run = await runEntrypoint(testCase.name.replace(/\W+/g, "-"), testCase.env(), identity); + it("missing required config fails cleanly", async () => { + const run = await runEntrypoint("missing-base-url", { + GAMECULT_IDUNN_CANDIDATE_BIND: "127.0.0.1:4100", + }); - expect(run.signal, "the process must stop by itself").toBeNull(); - expect(run.code, "startup must fail").not.toBe(0); - expect(run.output).toMatch(testCase.expect); - expect(run.output.includes(CANARY), "no byte of the canary may reach the terminal").toBe(false); - }, 45_000); - } + expect(run.signal).toBeNull(); + expect(run.code).not.toBe(0); + expect(run.output).toMatch(/GC_ACCESS_BASE_URL is required when GAMECULT_IDUNN_CANDIDATE_BIND is set/); + }, 45_000); + + it("valid config starts and listens without printing configured secrets", async () => { + const output = await new Promise((resolve, reject) => { + const child = spawn(process.execPath, [tsxCli, "src/index.ts"], { + cwd: repoRoot, + env: { + PATH: process.env.PATH ?? "", + HOME: scratch, + GC_ACCESS_DATA_ROOT: join(scratch, "data-valid"), + PORT: "0", + GC_ACCESS_PRIVATE_COMMAND_PORT: "0", + GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE: secretFile("valid-token-key", `${canaryTokenKey()}\n`), + GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE: secretFile("valid-bifrost", `${CANARY}bifrost\n`), + GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID: "discord-client-id", + GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE: secretFile("valid-discord", `${CANARY}discord\n`), + }, + stdio: ["ignore", "pipe", "pipe"], + }); + + let buf = ""; + let stopping = false; + let finishErr: Error | undefined; + + const stop = (err?: Error) => { + if (stopping) return; + stopping = true; + finishErr = err; + clearTimeout(timer); + child.kill("SIGKILL"); + }; + + const onData = (chunk: Buffer) => { + buf += chunk.toString("utf8"); + if (buf.includes("Heimdall listening on")) { + stop(); + } + }; + + child.stdout.on("data", onData); + child.stderr.on("data", onData); + const timer = setTimeout(() => stop(new Error(`Timed out waiting for listener; output:\n${buf}`)), 30_000); + child.on("error", (err) => stop(err)); + child.on("close", (code) => { + clearTimeout(timer); + if (finishErr) reject(finishErr); + else if (!stopping) reject(new Error(`Exited unexpectedly with code ${code}; output:\n${buf}`)); + else resolve(buf); + }); + }); + + expect(output).toContain("Heimdall listening on"); + expect(output).not.toContain(CANARY); + }, 45_000); }); diff --git a/tests/recipe-secrets.test.ts b/tests/recipe-secrets.test.ts index b6be578..88be61d 100644 --- a/tests/recipe-secrets.test.ts +++ b/tests/recipe-secrets.test.ts @@ -1,251 +1,67 @@ import { readFileSync } from "node:fs"; -import { describe, expect, it, vi } from "vitest"; +import { describe, expect, it } from "vitest"; import { appProfiles } from "../src/app-profiles.js"; -import { appSlugs, providers } from "../src/contracts.js"; +import { ENV_NAMES, SECRET_ENV_NAMES } from "../src/config.js"; +import { providers } from "../src/contracts.js"; import { providerCatalog } from "../src/providers.js"; -// The Idunn recipe decides which environment names a binding may set, and -// Idunn refuses any other. So the recipe is where "a secret is only ever a -// file" is enforced for a deployment: a plaintext secret name declared here -// can carry the secret into the binding, the unit and every plan. +const recipe = readFileSync(new URL("../deployment/idunn/recipe.toml", import.meta.url), "utf8").replace(/\r\n/g, "\n"); -const recipe = readFileSync(new URL("../deployment/idunn/recipe.toml", import.meta.url), "utf8"); - -/** The names in one `KEY = [ "A", "B" ]` array of the given TOML text. */ function stringArray(text: string, key: string): string[] { const match = new RegExp(`^${key}\\s*=\\s*\\[([^\\]]*)\\]`, "m").exec(text); return match ? [...match[1]!.matchAll(/"([^"]+)"/g)].map((name) => name[1]!) : []; } -const serviceSection = /^\[service\]\n([\s\S]*?)(?=^\[)/m.exec(recipe.replace(/\r\n/g, "\n"))?.[1] ?? ""; -const serviceNames = [ +const serviceSection = /^\[service\]\n([\s\S]*?)(?=^\[)/m.exec(recipe)?.[1] ?? ""; +const serviceNames = new Set([ ...stringArray(serviceSection, "optional_environment"), ...stringArray(serviceSection, "required_environment"), -]; -const everyDeclaredName = [...recipe.replace(/\r\n/g, "\n").matchAll(/^\w+_environment\s*=\s*\[([^\]]*)\]/gm)].flatMap( - (match) => [...match[1]!.matchAll(/"([^"]+)"/g)].map((name) => name[1]!) +]); +const everyDeclaredName = new Set( + [...recipe.matchAll(/^\w+_environment\s*=\s*\[([^\]]*)\]/gm)].flatMap( + (match) => [...match[1]!.matchAll(/"([^"]+)"/g)].map((name) => name[1]!) + ) ); -// The secrets Heimdall reads are observed, not read from the source: the real -// loadConfig runs against an environment that records every name it looks -// up. readSecretInput looks up `NAME_FILE` for each secret, so every `_FILE` -// lookup names one, however the call is spelled and whatever list computes -// the name. The recorder also stands in for process.env, both while config.ts -// is imported (freshly, so a copy of process.env taken at module load is the -// recorder too) and during every call. -// -// A read made from a copy of the environment ({ ...env }, Object.entries) -// cannot be seen, so copying or enumerating it is recorded and fails below. -// -// A secret read only on a branch some value opens is reached by running -// loadConfig over many environments, until no run reads a new name: every -// secret found so far set in plaintext; then each name read so far set to -// each probe value (a few shapes, plus every string literal in config.ts); -// then every name at once, each set to a value loadConfig accepted for it -// alone; and every combined run again as Idunn starts Heimdall, with the -// recipe's service arguments and a candidate socket with its base URL, a -// pair loadConfig refuses one name at a time. A run that throws still counts -// the reads it made first. -// -// Known limit: a read gated on a value that is none of the probe values and -// not accepted alone in combination with the others stays unseen. -const configSource = readFileSync(new URL("../src/config.ts", import.meta.url), "utf8"); -const probeValues = [ - ...new Set(["1", "true", "/probe/path", "127.0.0.1:4100", "https://probe.test", ...[...configSource.matchAll(/"([^"\\\r\n]+)"/g)].map((m) => m[1]!)]), -]; - -const recorder = { values: {} as Record, names: new Set(), enumerated: false }; -const recordingEnv = new Proxy({} as NodeJS.ProcessEnv, { - get(_target, name) { - if (typeof name !== "string") return undefined; - recorder.names.add(name); - return recorder.values[name]; - }, - has(_target, name) { - if (typeof name !== "string") return false; - recorder.names.add(name); - return name in recorder.values; - }, - ownKeys() { - recorder.enumerated = true; - return []; - }, - getOwnPropertyDescriptor() { - recorder.enumerated = true; - return undefined; - }, -}); - -async function withRecordingProcessEnv(run: () => T | Promise): Promise { - const processEnv = process.env; - process.env = recordingEnv; - try { - return await run(); - } finally { - process.env = processEnv; - } -} - -/** - * How Idunn starts Heimdall: the recipe's [service] arguments after the - * entry script, each binding given a probe value, and the environment an - * Idunn candidate always has (a loopback socket, which requires the base URL). - */ -const recipeArguments = [...(/^\[service\][\s\S]*?^arguments = \[([\s\S]*?)^\]/m.exec(recipe.replace(/\r\n/g, "\n"))?.[1] ?? "").matchAll( - /\{ kind = "(literal|binding)", (?:value|name) = "([^"]+)" \}/g -)].map((match) => (match[1] === "literal" ? match[2]! : "/probe/idunn-binding")); -const idunnArgv = recipeArguments.slice(1); -const idunnEnv = { GAMECULT_IDUNN_CANDIDATE_BIND: "127.0.0.1:4100", GC_ACCESS_BASE_URL: "https://probe.test" }; - -vi.resetModules(); -const { loadConfig } = await withRecordingProcessEnv(() => import("../src/config.js")); - -/** The names one loadConfig run reads under `values`, and whether it accepted them. */ -async function readsOf( - values: Readonly>, - argv: readonly string[] = [] -): Promise<{ names: Set; accepted: boolean }> { - recorder.values = { ...values }; - recorder.names = new Set(); - let accepted = true; - await withRecordingProcessEnv(() => { - try { - loadConfig(recordingEnv, argv); - } catch { - accepted = false; // the reads before the refusal still count - } - }); - return { names: recorder.names, accepted }; -} - -async function exploreLoadConfig(): Promise<{ names: Set; enumerated: boolean }> { - const names = new Set(); - recorder.enumerated = false; - const secretsOf = () => [...names].filter((name) => name.endsWith("_FILE")).map((name) => name.slice(0, -"_FILE".length)); - for (let grew = true; grew; ) { - const before = names.size; - const secrets = Object.fromEntries(secretsOf().map((name) => [name, "probe-secret"])); - const settable = [...names].filter((name) => !name.endsWith("_FILE") && !(name in secrets)); - const accepted = new Map(); - const keep = (run: { names: Set }) => run.names.forEach((name) => names.add(name)); - keep(await readsOf({})); - keep(await readsOf(secrets)); - keep(await readsOf({ ...secrets, ...idunnEnv }, idunnArgv)); - for (const name of settable) { - for (const value of probeValues) { - const run = await readsOf({ ...secrets, [name]: value }); - keep(run); - if (run.accepted) accepted.set(name, [...(accepted.get(name) ?? []), value]); - } - } - const widest = Math.max(0, ...[...accepted.values()].map((values) => values.length)); - for (let round = 0; round < widest; round += 1) { - const together = Object.fromEntries([...accepted].map(([name, values]) => [name, values[round % values.length]!])); - keep(await readsOf({ ...secrets, ...together })); - keep(await readsOf({ ...secrets, ...together, ...idunnEnv }, idunnArgv)); - } - grew = names.size > before; - } - return { names, enumerated: recorder.enumerated }; -} - -const explored = await exploreLoadConfig(); - -/** Secrets Heimdall reads through readSecretInput, by their plaintext name. */ -const secretNames = [...explored.names] - .filter((name) => name.endsWith("_FILE")) - .map((name) => name.slice(0, -"_FILE".length)); - const secretShaped = /SECRET|PASSWORD|PASSPHRASE|TOKEN|API_KEY|PRIVATE_KEY|ENCRYPTION_KEY|SALT|CREDENTIAL|DATABASE_URL|_DSN|_PEM|HMAC/; -/** Secret-shaped names that hold no secret, each for its own reason. */ const notSecrets = new Set([ - // A path to the signing key file, which Heimdall reads (or creates) itself. "GC_ACCESS_SIGNING_PRIVATE_KEY_PATH", - // A flag: create that file on first boot. "GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP", ]); -describe("Idunn recipe secret declarations", () => { - it("reads the service's declared environment", () => { - expect(serviceNames).toContain("GC_ACCESS_DATABASE_URL_FILE"); - expect(serviceNames).toContain("GC_ACCESS_BASE_URL"); - }); +const neverBound = new Set([ + "HOST", + "PORT", + "GC_ACCESS_DATA_ROOT", + "GC_ACCESS_CULTCACHE_PATH", + "GC_ACCESS_PROVIDER_HEALTH_IDENTITY_PATH", + "GC_ACCESS_IDUNN_DAEMON", +]); - it("declares no secret-shaped name except as a _FILE credential path", () => { - const plaintext = everyDeclaredName.filter( +describe("Idunn recipe secret declarations", () => { + it("declares every expected _FILE secret and never binds plaintext secrets", () => { + const expectedSecretFiles = new Set([ + ...SECRET_ENV_NAMES.map((name) => `${name}_FILE`), + ...providers.map((provider) => providerCatalog[provider].clientSecretEnv), + ...Object.values(appProfiles).map((profile) => `GC_ACCESS_APP_${profile.slug.toUpperCase()}_SHARED_SECRET_FILE`), + ]); + + const missingSecretFiles = [...expectedSecretFiles].filter((name) => !serviceNames.has(name)); + expect(missingSecretFiles).toEqual([]); + + const boundPlaintext = SECRET_ENV_NAMES.filter((name) => everyDeclaredName.has(name)); + expect(boundPlaintext).toEqual([]); + + const secretShapedPlaintext = [...everyDeclaredName].filter( (name) => secretShaped.test(name) && !name.endsWith("_FILE") && !notSecrets.has(name) ); - expect(plaintext).toEqual([]); + expect(secretShapedPlaintext).toEqual([]); }); - it("starts the exploration the way the recipe starts Heimdall", async () => { - expect(idunnArgv).toEqual(["--state-root", "/probe/idunn-binding"]); - expect(serviceNames).toEqual(expect.arrayContaining(Object.keys(idunnEnv))); - expect((await readsOf({ ...idunnEnv }, idunnArgv)).accepted).toBe(true); - }); - - it("reads the environment only by name, never by copying or enumerating it", () => { - expect(explored.enumerated).toBe(false); - }); - - it("sees every secret loadConfig reads, across the provider and app lists", () => { - expect(secretNames).toEqual( - expect.arrayContaining([ - "GC_ACCESS_DATABASE_URL", - "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64", - "GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET", - ...providers.map((provider) => `GC_ACCESS_PROVIDER_${provider.toUpperCase()}_CLIENT_SECRET`), - ...appSlugs.map((appSlug) => `GC_ACCESS_APP_${appSlug.toUpperCase()}_SHARED_SECRET`), - ]) - ); - }); - - it("declares none of the secrets Heimdall reads under its plaintext name", () => { - for (const name of secretNames) { - expect(everyDeclaredName).not.toContain(name); - } - }); - - it("declares every provider client-secret file the witness publishes", () => { - for (const provider of providers) { - expect(serviceNames).toContain(providerCatalog[provider].clientSecretEnv); - } - }); - - it("declares the shared-secret file of every app profile the witness publishes", () => { - for (const profile of Object.values(appProfiles)) { - expect(serviceNames).toContain(`GC_ACCESS_APP_${profile.slug.toUpperCase()}_SHARED_SECRET_FILE`); - } - }); - - it("declares the _FILE of every secret Heimdall reads", () => { - for (const name of secretNames) { - 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([]); + it("declares every config ENV_NAME except host-fixed exclusions", () => { + const undeclared = ENV_NAMES.filter((name) => !everyDeclaredName.has(name) && !neverBound.has(name)); + expect(undeclared).toEqual([]); }); }); From 1b0546bd4c8e75eff405dfc3e4b9d96a1c462ff2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:12:57 +0100 Subject: [PATCH 59/63] Steward cut 5: remove fixed-window step-up rate limiter and simplify connection target check --- src/app-profiles.ts | 9 ++-- src/app.ts | 61 +++++-------------------- src/fixed-window.ts | 49 -------------------- tests/app.test.ts | 15 ++---- tests/step-up-assertion.test.ts | 81 +-------------------------------- 5 files changed, 19 insertions(+), 196 deletions(-) delete mode 100644 src/fixed-window.ts diff --git a/src/app-profiles.ts b/src/app-profiles.ts index 34400cc..8b6a86c 100644 --- a/src/app-profiles.ts +++ b/src/app-profiles.ts @@ -286,14 +286,11 @@ export function isAllowedReturnOrigin(profile: AppProfile, returnTo: string): bo } /** - * A connection target names something: at least one letter or number that is - * not a default-ignorable code point (the Hangul and Khmer fillers are letters - * that render as nothing). An allowlist, so marks, private-use, unassigned and - * surrogate code points and symbols cannot stand in for a name. The one - * definition the start gate and the callback mint both use. + * A connection target names something: non-empty after trimming whitespace. + * The one definition the start gate and the callback mint both use. */ export function isUsableConnectionTarget(targetId: string): boolean { - return /(?![\p{Default_Ignorable_Code_Point}])[\p{L}\p{N}]/u.test(targetId); + return targetId.trim().length > 0; } /** diff --git a/src/app.ts b/src/app.ts index f43dc73..9492f74 100644 --- a/src/app.ts +++ b/src/app.ts @@ -25,7 +25,6 @@ import { 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 { 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"; @@ -974,43 +973,16 @@ async function resolveAccessAccount( 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. + * that same app, the profile's explicit grant and method allowlist, and a nonce + * spent once per session. Every refusal after the secret verifies is audited + * with 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 } @@ -1022,31 +994,25 @@ export async function assertStepUp( 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 } }; + const refuse = async (statusCode: number, error: string, extra: Record = {}): Promise => { 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 }, + eventPayloadJson: { + outcome: "refused", + code: error, + 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); + return refuse(403, "step_up_assertion_not_permitted", { detail: `${appSlug} may not assert step-up proofs.` }); } - 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) { @@ -1057,8 +1023,6 @@ export async function assertStepUp( 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)) { @@ -2773,7 +2737,6 @@ export async function buildApp(options: BuildAppOptions = {}): Promise( "/v1/apps/:appSlug/step-up", { @@ -2797,7 +2760,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { - const result = await assertStepUp({ config, keys, store }, stepUpBudgets, request.params.appSlug, request.headers, request.body); + const result = await assertStepUp({ config, keys, store }, request.params.appSlug, request.headers, request.body); reply.code(result.statusCode).header("cache-control", "no-store"); return result.body; } 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/tests/app.test.ts b/tests/app.test.ts index eac76f9..7dd94d9 100644 --- a/tests/app.test.ts +++ b/tests/app.test.ts @@ -1440,15 +1440,8 @@ describe("Heimdall service", () => { expect(urls).toEqual([]); }); - // Targets made only of whitespace, format characters, controls and the invisible fillers that render as nothing. - const BLANK_TARGETS = [ - " ", "\t", "\n ", "\u200B", "\u00A0\uFEFF", - "\u2800", "\u3164", "\u115F", "\u1160", "\uFFA0", "\u034F", "\u0000", "\u0007", " \u2800\u3164 ", - // Marks, private-use, unassigned and lone-surrogate code points, and the symbols that read as nothing: none is a letter or a number. - "\u0300", "\uE000", "\u0378", "\uD800", "\u{16FE4}", "\u{1D159}", "\u{F0000}", "\u0300\uE000 ", - ]; - // A target is usable when it holds a letter or a number that is not an invisible filler. - const NAMING_TARGETS = ["creator-1", " creator-1 ", "Framgång", "42", "\u2800a\u3164", "\u3164\u0300x"]; + const BLANK_TARGETS = ["", " ", "\t", "\n ", "\u00A0\uFEFF"]; + const NAMING_TARGETS = ["creator-1", " creator-1 ", "Framgång", "42"]; describe("a connect start that names a connection target is the app backend's", () => { // The target is app-backend authority: the StreamPixels backend proves the creator-manage session and states the @@ -1519,7 +1512,7 @@ describe("Heimdall service", () => { apps.push(app); for (const headers of [{}, { "x-heimdall-app-secret": "wrong" }]) { - for (const targetId of [" ", "\u2800"]) { + for (const targetId of [" ", "\t\n"]) { const refused = await startFor(app, provider, { kind: "creator", targetId }, headers); expect([refused.statusCode, refused.json()], JSON.stringify(targetId)).toEqual([401, { error: "app_auth_required" }]); } @@ -1531,8 +1524,6 @@ describe("Heimdall service", () => { for (const targetId of BLANK_TARGETS) { expect(callbackMint(streampixels, "joystick", "connect", { kind: "creator", targetId }), JSON.stringify(targetId)).toBe("refused"); } - // A visible character among the blanks names a target. - expect(callbackMint(streampixels, "joystick", "connect", { kind: "creator", targetId: "\u2800a\u3164" })).toBe("custody_only"); for (const targetId of NAMING_TARGETS) { expect(callbackMint(streampixels, "joystick", "connect", { kind: "creator", targetId }), JSON.stringify(targetId)).toBe("custody_only"); } diff --git a/tests/step-up-assertion.test.ts b/tests/step-up-assertion.test.ts index f064e00..7ed66e2 100644 --- a/tests/step-up-assertion.test.ts +++ b/tests/step-up-assertion.test.ts @@ -2,7 +2,7 @@ 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 { buildApp } from "../src/app.js"; import { builtInAppProfiles } from "../src/app-profiles.js"; import { issueAccessClaim } from "../src/claims.js"; import { type Provider } from "../src/contracts.js"; @@ -312,85 +312,6 @@ describe("the method and the nonce", () => { }); }); -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(); From 3e90a7287a5cb32883f5c9103fb17df1bc685b40 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:14:51 +0100 Subject: [PATCH 60/63] Fix duplicate import in app-caller.ts and mock Pool typing in store.test.ts --- src/app-caller.ts | 4 ---- tests/store.test.ts | 14 +++++++------- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/src/app-caller.ts b/src/app-caller.ts index d25a881..635d273 100644 --- a/src/app-caller.ts +++ b/src/app-caller.ts @@ -16,10 +16,6 @@ import { timingSafeEqual } from "node:crypto"; import { type AppSlug } from "./contracts.js"; import { type HeimdallConfig } from "./config.js"; -import { timingSafeEqual } from "node:crypto"; -import { type AppSlug } from "./contracts.js"; -import { type HeimdallConfig } from "./config.js"; - declare const appCallerBrand: unique symbol; export interface AppCaller { diff --git a/tests/store.test.ts b/tests/store.test.ts index 5a8e7e1..cba35c3 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -464,11 +464,11 @@ describe("PostgresStore.checkSchema", () => { const store = new PostgresStore({ query: async (sql: string, params?: unknown[]) => { queries.push({ sql, params }); - return { rows: [], rowCount: 0 } as never; + return { rows: [], rowCount: 0 }; }, end: async () => {}, - connect: async () => ({}) as never, - }); + connect: async () => ({}), + } as unknown as Pool); await expect(store.checkSchema()).resolves.toBeUndefined(); expect(queries).toHaveLength(2); @@ -480,12 +480,12 @@ describe("PostgresStore.checkSchema", () => { it("throws SCHEMA_MISSING when any core table is missing", async () => { const store = new PostgresStore({ query: async (sql: string) => { - if (sql === "SELECT 1") return { rows: [], rowCount: 0 } as never; - return { rows: [{ name: "consent_receipts" }], rowCount: 1 } as never; + if (sql === "SELECT 1") return { rows: [], rowCount: 0 }; + return { rows: [{ name: "consent_receipts" }], rowCount: 1 }; }, end: async () => {}, - connect: async () => ({}) as never, - }); + connect: async () => ({}), + } as unknown as Pool); await expect(store.checkSchema()).rejects.toMatchObject({ code: "SCHEMA_MISSING" }); }); From 80a2e069a2a3f38ed1a77f550628e0ec93f1f883 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:17:01 +0100 Subject: [PATCH 61/63] Fix BLANK_TARGETS schema expectation and process-group kill in entrypoint smoke test --- tests/app.test.ts | 2 +- tests/entrypoint-secrets.test.ts | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/tests/app.test.ts b/tests/app.test.ts index 7dd94d9..3433d42 100644 --- a/tests/app.test.ts +++ b/tests/app.test.ts @@ -1440,7 +1440,7 @@ describe("Heimdall service", () => { expect(urls).toEqual([]); }); - const BLANK_TARGETS = ["", " ", "\t", "\n ", "\u00A0\uFEFF"]; + const BLANK_TARGETS = [" ", "\t", "\n ", "\u00A0\uFEFF"]; const NAMING_TARGETS = ["creator-1", " creator-1 ", "Framgång", "42"]; describe("a connect start that names a connection target is the app backend's", () => { diff --git a/tests/entrypoint-secrets.test.ts b/tests/entrypoint-secrets.test.ts index 90b6a76..0c44bbc 100644 --- a/tests/entrypoint-secrets.test.ts +++ b/tests/entrypoint-secrets.test.ts @@ -26,10 +26,23 @@ function canaryTokenKey(): string { return `${CANARY}key`.padEnd(43, "A") + "="; } +function killProcessTree(child: ReturnType): void { + if (process.platform !== "win32" && child.pid) { + try { + process.kill(-child.pid, "SIGKILL"); + return; + } catch { + // fall through if already exited + } + } + child.kill("SIGKILL"); +} + function runEntrypoint(name: string, env: Record): Promise<{ code: number | null; signal: NodeJS.Signals | null; output: string }> { return new Promise((resolve, reject) => { const child = spawn(process.execPath, [tsxCli, "src/index.ts"], { cwd: repoRoot, + detached: process.platform !== "win32", env: { PATH: process.env.PATH ?? "", HOME: scratch, @@ -43,7 +56,7 @@ function runEntrypoint(name: string, env: Record): Promise<{ cod let output = ""; child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString("utf8"))); child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString("utf8"))); - const timer = setTimeout(() => child.kill("SIGKILL"), 30_000); + const timer = setTimeout(() => killProcessTree(child), 30_000); child.on("error", reject); child.on("close", (code, signal) => { clearTimeout(timer); @@ -81,6 +94,7 @@ describe("entrypoint startup and secret redaction smoke checks", () => { const output = await new Promise((resolve, reject) => { const child = spawn(process.execPath, [tsxCli, "src/index.ts"], { cwd: repoRoot, + detached: process.platform !== "win32", env: { PATH: process.env.PATH ?? "", HOME: scratch, @@ -104,7 +118,7 @@ describe("entrypoint startup and secret redaction smoke checks", () => { stopping = true; finishErr = err; clearTimeout(timer); - child.kill("SIGKILL"); + killProcessTree(child); }; const onData = (chunk: Buffer) => { From 087a7a1bb1d72531e508f363906d5ea33ade9594 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:19:07 +0100 Subject: [PATCH 62/63] Check /healthz directly in valid-config entrypoint smoke test --- tests/entrypoint-secrets.test.ts | 119 ++++++++++++++++++------------- 1 file changed, 70 insertions(+), 49 deletions(-) diff --git a/tests/entrypoint-secrets.test.ts b/tests/entrypoint-secrets.test.ts index 0c44bbc..6d14f54 100644 --- a/tests/entrypoint-secrets.test.ts +++ b/tests/entrypoint-secrets.test.ts @@ -1,6 +1,7 @@ import { spawn } from "node:child_process"; import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { createRequire } from "node:module"; +import { createServer } from "node:net"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -22,8 +23,20 @@ function secretFile(name: string, contents: string): string { return filePath; } -function canaryTokenKey(): string { - return `${CANARY}key`.padEnd(43, "A") + "="; +function reserveLoopbackPort(): Promise { + return new Promise((resolve, reject) => { + const server = createServer(); + server.once("error", reject); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (!address || typeof address === "string") { + server.close(() => reject(new Error("Expected numeric ephemeral port"))); + return; + } + const { port } = address; + server.close((err) => (err ? reject(err) : resolve(port))); + }); + }); } function killProcessTree(child: ReturnType): void { @@ -65,6 +78,10 @@ function runEntrypoint(name: string, env: Record): Promise<{ cod }); } +function canaryTokenKey(): string { + return `${CANARY}key`.padEnd(43, "A") + "="; +} + describe("entrypoint startup and secret redaction smoke checks", () => { it("startup failure redacts configured secrets from stdout and stderr", async () => { const run = await runEntrypoint("redact", { @@ -90,57 +107,61 @@ describe("entrypoint startup and secret redaction smoke checks", () => { expect(run.output).toMatch(/GC_ACCESS_BASE_URL is required when GAMECULT_IDUNN_CANDIDATE_BIND is set/); }, 45_000); - it("valid config starts and listens without printing configured secrets", async () => { - const output = await new Promise((resolve, reject) => { - const child = spawn(process.execPath, [tsxCli, "src/index.ts"], { - cwd: repoRoot, - detached: process.platform !== "win32", - env: { - PATH: process.env.PATH ?? "", - HOME: scratch, - GC_ACCESS_DATA_ROOT: join(scratch, "data-valid"), - PORT: "0", - GC_ACCESS_PRIVATE_COMMAND_PORT: "0", - GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE: secretFile("valid-token-key", `${canaryTokenKey()}\n`), - GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE: secretFile("valid-bifrost", `${CANARY}bifrost\n`), - GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID: "discord-client-id", - GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE: secretFile("valid-discord", `${CANARY}discord\n`), - }, - stdio: ["ignore", "pipe", "pipe"], - }); + it("valid config starts and serves /healthz without printing configured secrets", async () => { + const port = await reserveLoopbackPort(); + const child = spawn(process.execPath, [tsxCli, "src/index.ts"], { + cwd: repoRoot, + detached: process.platform !== "win32", + env: { + PATH: process.env.PATH ?? "", + HOME: scratch, + GC_ACCESS_DATA_ROOT: join(scratch, "data-valid"), + HOST: "127.0.0.1", + PORT: String(port), + GC_ACCESS_PRIVATE_COMMAND_PORT: "0", + GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE: secretFile("valid-token-key", `${canaryTokenKey()}\n`), + GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE: secretFile("valid-bifrost", `${CANARY}bifrost\n`), + GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID: "discord-client-id", + GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE: secretFile("valid-discord", `${CANARY}discord\n`), + }, + stdio: ["ignore", "pipe", "pipe"], + }); - let buf = ""; - let stopping = false; - let finishErr: Error | undefined; - - const stop = (err?: Error) => { - if (stopping) return; - stopping = true; - finishErr = err; - clearTimeout(timer); - killProcessTree(child); - }; - - const onData = (chunk: Buffer) => { - buf += chunk.toString("utf8"); - if (buf.includes("Heimdall listening on")) { - stop(); - } - }; - - child.stdout.on("data", onData); - child.stderr.on("data", onData); - const timer = setTimeout(() => stop(new Error(`Timed out waiting for listener; output:\n${buf}`)), 30_000); - child.on("error", (err) => stop(err)); + let buf = ""; + let exited: number | null | undefined; + const closed = new Promise((resolve) => { + child.stdout.on("data", (chunk: Buffer) => (buf += chunk.toString("utf8"))); + child.stderr.on("data", (chunk: Buffer) => (buf += chunk.toString("utf8"))); child.on("close", (code) => { - clearTimeout(timer); - if (finishErr) reject(finishErr); - else if (!stopping) reject(new Error(`Exited unexpectedly with code ${code}; output:\n${buf}`)); - else resolve(buf); + exited = code; + resolve(); }); }); - expect(output).toContain("Heimdall listening on"); - expect(output).not.toContain(CANARY); + try { + const deadline = Date.now() + 25_000; + let health: { ok?: boolean; service?: string } | undefined; + while (Date.now() < deadline && exited === undefined) { + try { + const response = await fetch(`http://127.0.0.1:${port}/healthz`); + if (response.ok) { + health = (await response.json()) as { ok?: boolean; service?: string }; + break; + } + } catch { + // listener not ready yet + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } + + expect(health, `Expected /healthz to respond 200; exited=${exited}; output:\n${buf}`).toMatchObject({ + ok: true, + service: "heimdall", + }); + expect(buf).not.toContain(CANARY); + } finally { + killProcessTree(child); + await closed; + } }, 45_000); }); From 1fd240a58d336071cd69adfb5bee2c010d81273c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:31:04 +0100 Subject: [PATCH 63/63] Address Soul Lows: pin CORE_TABLES to CREATE_SCHEMA_SQL and remove stale doc refs --- .env.example | 1 - README.md | 13 +++++-------- docs/architecture.md | 5 ++--- docs/service-contract.md | 16 +++++----------- tests/store.test.ts | 5 +++++ 5 files changed, 17 insertions(+), 23 deletions(-) diff --git a/.env.example b/.env.example index 6af5d90..09f05d8 100644 --- a/.env.example +++ b/.env.example @@ -30,6 +30,5 @@ GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID= GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID= # GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET_FILE=/absolute/path/to/credential -GC_ACCESS_APP_SPOTIVERSE_BACKEND_CALLBACK_URLS= # GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET_FILE=/absolute/path/to/credential GC_ACCESS_APP_GHOSTLIGHT_RUNTIME_IDS=yggdrasil-ghostlight diff --git a/README.md b/README.md index f0e0a0e..3104ddd 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,6 @@ The point is painfully simple: - **Problem:** every GameCult app was rebuilding Discord/Patreon login glue. Heimdall centralizes identity authority and keeps app-domain data in the apps. - **Entry points:** - `src/index.ts` and `src/app.ts`: the Fastify service. `src/signing.ts` and `src/claims.ts` issue JWTs and serve `/.well-known/jwks.json`; `src/oauth.ts` and `src/providers.ts` own provider flows. - - `src/verifier.ts`: the local verifier helper an app backend imports to validate Heimdall JWTs without phoning home. - `src/odin-publication.ts` and `plugins/gamecult.heimdall.access`: the redacted Odin/Eve provider advertisement and the `gamecult.heimdall.access` plugin (`docs/eve-access-plugin.md`). - `docs/architecture.md`, `docs/service-contract.md`, `docs/verse-service-contract.md`, `docs/app-profiles/`: the contracts. - `pnpm install`, `pnpm dev`, `pnpm test` (see Dev Commands). @@ -47,10 +46,8 @@ Landed right now: - AES-256-GCM sealing for managed provider tokens at rest - a one-time browser completion exchange kept as fallback for opener `postMessage` handoff -- app profile surfaces for Repixelizer, StreamPixels, and Spotiverse -- signed claim issuance for app-local verification experiments -- a local verifier helper in `src/verifier.ts` so app backends can validate - Heimdall JWTs without phoning home on every guarded request +- app profile surfaces for Repixelizer, StreamPixels, Bifrost, and Ghostlight +- signed claim issuance for app-local verification against `/.well-known/jwks.json` - a read-only Odin/Eve provider advertisement export that names redacted CultCache witness document shapes and paths without touching live secrets - a daemon-owned CultCache boundary witness at `GC_ACCESS_CULTCACHE_PATH` @@ -84,9 +81,9 @@ Canonical docs: - `docs/verse-service-contract.md` - `docs/app-profiles/repixelizer.md` - `docs/app-profiles/streampixels.md` -- `docs/app-profiles/spotiverse.md` -- `state/map.yaml` -- `notes/fresh-workspace-handoff.md` +- `docs/app-profiles/bifrost.md` +- `docs/app-profiles/ghostlight.md` +- `docs/app-profiles/spotiverse.md` (retired restore spec) ## Dev Commands diff --git a/docs/architecture.md b/docs/architecture.md index 956b1db..16ea243 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -374,10 +374,9 @@ 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 +bearer for that app, the method allowlist, and 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`). +retained to the session expiry as of the claim, which a refresh may slide past). ### Three nested guards diff --git a/docs/service-contract.md b/docs/service-contract.md index 6915c6e..a1c2446 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -912,27 +912,21 @@ Important behavior: - app-local binding, diagnostics, subscription setup, and runtime behavior stay app-owned -### Reference local verifier seam +### Local verification seam Purpose: -- give app backends a tiny local verification helper instead of encouraging - per-request Heimdall callbacks +- let app backends verify Heimdall Ed25519 JWTs locally against `/.well-known/jwks.json` + instead of calling Heimdall on every guarded request -Current reference helper: +Expected verifier contract: -- `src/verifier.ts` - -Current helper contract: - -- build the verifier once from Heimdall `issuer`, app slug, and JWKS +- fetch and cache Heimdall's JWKS by `kid`, bound to Heimdall `issuer` and app slug - verify Ed25519 signature locally by `kid` - reject wrong `iss`, wrong `aud`, malformed claim shape, `nbf` violations, and expired tokens - accept a small clock-skew window for normal same-host reality -This is a reference seam, not a magical shared middleware product yet. - ## Access claim shape Current claim payload fields: diff --git a/tests/store.test.ts b/tests/store.test.ts index cba35c3..fda8a9f 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -475,6 +475,11 @@ describe("PostgresStore.checkSchema", () => { expect(queries[0]!.sql).toBe("SELECT 1"); expect(queries[1]!.sql).toContain("to_regclass('public.' || name) IS NULL"); expect(queries[1]!.params).toEqual([CORE_TABLES]); + const declaredTables = Array.from( + CREATE_SCHEMA_SQL.matchAll(/CREATE TABLE IF NOT EXISTS (\w+)/g), + (m) => m[1]!, + ); + expect([...CORE_TABLES].sort()).toEqual([...declaredTables].sort()); }); it("throws SCHEMA_MISSING when any core table is missing", async () => {