Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
2bcb2ca4e7 A first Google sign-in mints an account only under an app's invite grant (#18) 2026-11-29 20:04:06 +00:00
256d7dbfb1 Merge pull request 'Idunn recipe: declare every name loadConfig reads; state slot at the path the code writes' (#17) from heimdall/recipe-env-parity into main 2026-11-17 00:10:45 +00:00
Heimdall
4a0fb44b5b 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 <noreply@anthropic.com>
2026-11-17 00:10:44 +00:00
Heimdall
2f0dd0c3a7 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 <noreply@anthropic.com>
2026-11-17 00:00:45 +00:00
4fe367ac8d 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 <noreply@anthropic.com>
2026-11-14 01:59:11 +00:00
d957e5accb Merge pull request 'App-asserted step-up route: Bifrost asserts a native strong proof, Heimdall mints step_up_at + step_up_method' (#15) from heimdall/app-asserted-step-up into main 2026-11-13 20:19:55 +00:00
Heimdall
6ed6d8fa0d 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 <noreply@anthropic.com>
2026-11-13 20:19:41 +00:00
Heimdall
1259911632 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 <noreply@anthropic.com>
2026-11-13 20:13:13 +00:00
Heimdall
2f93809a29 Docs: app-asserted step-up route, step_up_method claim, Bifrost profile grant, architecture note, evidence line
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 20:01:46 +00:00
Heimdall
33a83c34c4 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:<name>.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 19:59:26 +00:00
54e15567c7 Merge pull request 'Member identity list and step-up-gated unlink; a link never moves an identity' (#14) from heimdall/identity-unlink into main 2026-11-13 19:22:35 +00:00
Heimdall
46e5d5364f Docs: a Twitch step-up proof is weaker; point the unlink section at the step-up note
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 19:21:45 +00:00
Heimdall
e9eef09446 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 <noreply@anthropic.com>
2026-11-13 19:21:45 +00:00
Heimdall
d8b8d25e81 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 <noreply@anthropic.com>
2026-11-13 18:59:21 +00:00
Heimdall
3afc956f92 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 <noreply@anthropic.com>
2026-11-13 18:59:21 +00:00
Heimdall
46d5044925 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 <noreply@anthropic.com>
2026-11-13 18:59:21 +00:00
c98e019c5d Merge pull request 'Consent bomb test: pin the inflate output cap, not a wall-clock bound' (#13) from heimdall/consent-bomb-deterministic into main 2026-11-13 07:15:09 +00:00
Heimdall
4aa9d03c4f 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 <noreply@anthropic.com>
2026-11-13 07:03:30 +00:00
96256d2839 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 <noreply@anthropic.com>
2026-11-13 05:58:45 +00:00
74004bf0ef Merge pull request 'Opt-in sign_in step-up (force_verify / prompt=login), app-authenticated, signed-state flag' (#11) from heimdall/signin-step-up into main 2026-11-12 23:22:19 +00:00
Heimdall
673713a015 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 <noreply@anthropic.com>
2026-11-12 23:21:12 +00:00
Heimdall
7a69d7567b Opt-in sign_in step-up: app-authenticated, signed-state flag, provider re-auth parameters, typed refusal
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 23:10:27 +00:00
afa1b74318 Merge pull request 'Docs: answer collector record and consent' (#6) from heimdall/answer-collector-consent into main 2026-11-10 17:12:26 +00:00
Heimdall
570e930043 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 <noreply@anthropic.com>
2026-11-10 17:12:15 +00:00
5fc626c7ec 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 <noreply@anthropic.com>
2026-11-09 12:18:26 +00:00
cbc069f02c Merge pull request 'Redeem refuses a target the completion did not record' (#10) from heimdall/redeem-refuse-unexpected-target into main 2026-11-09 12:13:54 +00:00
Heimdall
36b02ea135 Redeem refuses a target the completion did not record, symmetric with the missing one
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 12:03:14 +00:00
Heimdall
a021b02310 Test first: redeem refuses a target the completion never recorded
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 12:03:14 +00:00
b446add144 Merge pull request 'Record a failed refresh on the identity row so another process does not re-present the token' (#8) from heimdall/failed-refresh-marker into main 2026-11-09 10:31:02 +00:00
Heimdall
246f2d4f71 Tests: rotate fixtures carry consumedRefreshToken
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 10:27:35 +00:00
Heimdall
d4cd112193 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 <noreply@anthropic.com>
2026-11-09 10:22:14 +00:00
Heimdall
f2f1dabc06 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 <noreply@anthropic.com>
2026-11-09 10:07:24 +00:00
Heimdall
9c7d980165 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 <noreply@anthropic.com>
2026-11-08 21:56:40 +00:00
Heimdall
1118f235b0 Docs: name the process-death residual in the refresh contract
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 21:53:12 +00:00
Heimdall
9da4b12bc2 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 <noreply@anthropic.com>
2026-11-08 21:48:13 +00:00
Heimdall
a0bd9836b1 Count the new linked_identities column in the schema inventory test
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 21:40:39 +00:00
Heimdall
f5f4b2830f 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 <noreply@anthropic.com>
2026-11-08 21:35:13 +00:00
2bd5096d81 Merge pull request 'Refusal return contract: pin the fragment, carry the attempt id, document it' (#7) from heimdall/refusal-return-contract into main 2026-11-08 13:51:45 +00:00
Heimdall
0ea6691cd3 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 <noreply@anthropic.com>
2026-11-08 13:50:58 +00:00
61671d7fe8 Merge pull request 'Joystick consent: ask page, consent_refused, receipts, signed-in grants page with revoke' (#5) from heimdall/joystick-consent-flow-design into main 2026-11-08 13:45:58 +00:00
Heimdall
b6372e5a4f Named revocation-conflict tests on pg-mem, first-create doc line, npm fallback in test-live-pg
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 13:45:57 +00:00
Heimdall
f7a38a7d2a Doc the FK, the cookie and scope bounds, consent_text_missing
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 13:39:34 +00:00
Heimdall
af554ca013 Addendum: per-index predicate check, live second-revocation and missing-table cases, test-live-pg prerequisites
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 13:38:35 +00:00
Heimdall
767852ef96 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 <noreply@anthropic.com>
2026-11-08 13:37:13 +00:00
Heimdall
5ce8f1c14c Consent doc: ask cookie, carried wording, unique revocation, fixed link expiry
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 13:32:21 +00:00
Heimdall
d4f7dce098 Check the shown text before any code exchange; pin link expiry with a clock
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 13:31:43 +00:00
Heimdall
71ce9c16e4 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 <noreply@anthropic.com>
2026-11-08 13:30:39 +00:00
Heimdall
48207268d0 Consent flow doc: steward rulings and the built design; pin repeat-revoke
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 13:24:48 +00:00
Heimdall
7ca4e2355f 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 <noreply@anthropic.com>
2026-11-08 13:22:36 +00:00
Heimdall
aaeb175dc6 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 <noreply@anthropic.com>
2026-11-07 02:34:48 +00:00
Heimdall
d6a8d4238c 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 <noreply@anthropic.com>
2026-11-07 00:30:00 +00:00
Heimdall
cafdc52e5f 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 <noreply@anthropic.com>
2026-11-06 23:28:40 +00:00
Heimdall
4e99bfa628 Rule empty text and received_at ties from CultLib #12 follow-up
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 19:40:44 +00:00
Heimdall
2364979f0d 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 <noreply@anthropic.com>
2026-11-06 17:24:39 +00:00
Heimdall
d836f29e3a 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 <noreply@anthropic.com>
2026-11-06 14:31:45 +00:00
Heimdall
e8edd88efc Specify answer collector record and consent
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 13:30:45 +00:00
Heimdall
a7cdf0fea7 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 <noreply@anthropic.com>
2026-11-06 12:17:14 +00:00
fefd2ddf4a Merge pull request 'Live-Postgres tests: exercise the pending-link methods; add a standing live run' (#4) from heimdall/live-pg-exercise-pending-links into main 2026-11-06 00:32:56 +00:00
Heimdall
575be9cf49 Add scripts/test-live-pg.sh: run the suite against a throwaway Postgres
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 23:30:57 +00:00
Heimdall
70fd6396f4 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 <noreply@anthropic.com>
2026-11-05 23:30:23 +00:00
aa2edd3826 Merge pull request 'r2: bind OAuth completion to the launching browser, one use per state; gate connect starts' (#3) from heimdall/r2-state-binding into main 2026-11-05 17:16:39 +00:00
Heimdall
f1ddc2fffc Refuse an unbound or replayed state with a page back to the app, and keep use records through the skew
Browsers (Accept: text/html) refused for state_not_bound, state_already_launched
or state_already_used get the handoff page linking to return_to, re-checked
against the app's allowed origins; other callers keep the JSON code. A callback
with no binding denies the attempt its signed state names (pending only).
The memory store prunes a use record at exp + 30 s, as the state itself is
accepted that long; the schema comment says the same.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 17:16:38 +00:00
Heimdall
b541e094eb Merge heimdall-binds-completion (r2 state binding) into main's link and Google work; gate connect starts that carry a connection
Launch hop, signed per-flow cookie and one-use claims are merged with main's
link-initiator binding and Google OIDC (secrets now derived at launch).
A connect start carrying a connection target now needs the app's own secret.
Google, link and managed-credential tests go through the launch helper.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 12:46:05 +00:00
fd67d94aa3 Merge pull request 'Google OIDC provider: link-only, sub-keyed, PKCE and nonce' (#2) from heimdall/google-oidc-provider into main 2026-11-05 10:58:37 +00:00
heimdall
9123f2def0 Merge main (link-initiator binding) and reconcile the Google link with it
One initiator field (initiator_account_id) replaces link_account_id: a bearer
names it for requires_link providers, the authenticated app for the rest. One
refusal class (LinkRefusal, 403) replaces AccountLinkRefused. Provider count in
the verse test is 8.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 10:58:02 +00:00
da70416ebe Merge pull request 'Bind link mode to its initiator and redeem to its target' (#1) from heimdall/link-initiator-target-binding into main 2026-11-05 10:57:53 +00:00
Heimdall
c829429cd5 Google link is two-phase; callback evaluates all linked identities
The callback records a typed pending link (short TTL, single use) and
writes no linked identity; POST /v1/apps/:appSlug/links/confirm with the
Heimdall access token of the initiating account attaches it. A victim who
completes an attacker's link URL attaches nothing. The sign-in callback
also evaluates the account's other linked identities with the start-time
policy, so a Discord-origin member returning via Google keeps app_access.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-04 17:15:33 +00:00
Heimdall
8e870d20a0 Google OIDC provider: link-only, sub-keyed, PKCE and nonce
Google is a Heimdall provider behind Bifrost, with no direct upstream.
Scopes openid email profile; the callback verifies the id_token
(RS256 against Google's keys, iss, aud, exp, iat, nonce) and requires
a verified email. The identity key is sub, never the email.

PKCE verifier and nonce are derived from the state jti and Heimdall's
signing key, so nothing is stored between start and callback.

Google never mints an account. mode=link needs a Heimdall access token
for the app and attaches to that account only; sign_in signs in an
identity already linked; an unknown sub is refused, and a sub held by
another account is never moved. The six existing providers still mint
on first login.

Admitted to the bifrost profile only. The Idunn recipe declares the
Google client id and secret file.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-04 16:10:23 +00:00
Heimdall
84c54fbb5e Refuse a connection target on sign_in start
Connection targets ride only on connect and link starts, which carry
x-heimdall-app-secret. A sign_in start is open to any browser; with a
connection it now returns 400 connection_not_allowed_in_sign_in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 13:30:22 +00:00
Heimdall
0f2e294fcb Pin completion expiry at redeem: 410 at and after expiresAt, for any caller and target
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 09:50:34 +00:00
Heimdall
9f5a0e6938 Bind link mode to its initiator and redeem to its target
Link start needs an authenticated app and an initiatingAccountId, carried in
the signed state. The callback refuses an identity held by another account
(link_initiator_mismatch) and attaches an unlinked one to the initiator.
auth_completions stores target_id; redeem compares it and answers
completion_target_mismatch without consuming the code. Link completions are
redeemed only by the authenticated app.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 13:38:51 +00:00
Meta Vens
5146c722af Boot test: fail on a logged publication fault, and require presence at startup
A silent early return in the startup publication would otherwise pass, the 10 s
pulse loop filling in the frames later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 17:50:37 +02:00
Meta Vens
1a36175f3a Presence authority test: the Rust fixture's target is the fixture's own, not heimdall
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 17:49:23 +02:00
Meta Vens
c044155855 Heimdall opens its Idunn presence authority once, before it listens
index.ts declared the presence sequence below the startup try, so the bundle's
hoisted var was undefined at the first publish; decodePrivateIdentity refused the
Rust owner's integer-array key fields; both descriptors were re-read every pulse and
returned nothing after the first. openPresenceAuthority now reads the bundle facts and
each descriptor once (whole, from offset 0, then closed), owns the one publisher
sequence, and signs through them; a launch-contract fault throws before anything
listens, so the process exits non-zero. decodePrivateIdentity takes the shape of its
source and names the failed check, never a value. openActivationSigner and the
per-pulse descriptor reads are deleted.

tests/idunn-boot.test.ts boots the bundle under the Idunn launch contract and checks
the signed warming frames and the fail-fast exits. The descriptor, sequence and
generation tests now use the Rust-written fixtures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 17:48:08 +02:00
Meta Vens
c0d30e8081 Test fixtures: the Rust owner's Idunn runtime records, and one fake Idunn RUDP endpoint
tests/fixtures/idunn-runtime holds expected.cc, activation.cc, the activation seed,
the presence identity credential and the machine-id it is bound to, copied from
CultLib 217a9480 (Rust-written; test keys only). fake-idunn-rudp.ts is the accept
server idunn-rudp-health.test.ts built inline, now keeping a session per remote and
every delivered frame, so a boot test can receive several pulses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 17:48:02 +02:00
Meta Vens
e8548614c8 Generation test: bundle the generation process so a uid that cannot read the checkout can run it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:26:13 +02:00
Meta Vens
55732a901d Presence: the publisher sequence is in-process, the state root keeps no owner-only file, an Idunn generation never self-enrolls
nextPublisherSequence read and rewrote <dataRoot>/runtime-presence-sequence at
mode 0600, which the next generation (a fresh DynamicUser uid in the shared
state group) cannot open. Odin compares publisher_sequence only within one
activation and Idunn mints a new activation per start, so PublisherSequence
derives it from the observation clock, never below the previous value plus
one, as Muninn does. openProviderHealthIdentity under
GAMECULT_IDUNN_RUNTIME_BUNDLE now refuses when the presence descriptor is
absent instead of enrolling an identity Idunn does not trust.

Adds the cross-generation test (root only) and the sequence, no-dataRoot and
missing-descriptor tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:25:11 +02:00
Meta Vens
25d43d1121 Merge security/fastify-upgrade: fastify 5.12.7 advisories
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 23:06:25 +02:00
Meta Vens
899ea0b8fe Heimdall: fastify 5.8.5 to 5.12.7, find-my-way 9.5.0 to 9.10.0 (clears 5 High advisories)
GHSA-p68q-wchp-6fh7 authentication bypass via malformed URLs, header and request validation bypass, request body replacement, find-my-way HTTP/2 DoS. pnpm audit --prod: 8 vulnerabilities before, none after.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 21:00:47 +02:00
Meta Vens
c15fb97706 Test: malformed URL must not reach a sibling prefix's not-found handler (GHSA-p68q-wchp-6fh7)
Red on fastify 5.8.5, the live lockfile.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 21:00:46 +02:00
Meta Vens
4185e657bb Tests: state time windows to the second, requested_scopes shapes, the launch route's validation, the phases each route claims
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 20:25:52 +02:00
Meta Vens
5076e04950 Docs: the launch hop, the binding cookie and the callback refusals
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 20:13:18 +02:00
Meta Vens
3def0fb426 OAuth states complete once, only in the browser that launched them: a launch hop sets a signed binding cookie, launch and callback each consume the state, and the callback checks expiry
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 20:13:17 +02:00
Meta Vens
14e0cde26c Store: claimOAuthStateUse claims one use of a signed OAuth state per (jti, phase), on both stores and an INSERT-only table
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 20:13:16 +02:00
Meta Vens
607c2b0a20 Depend on @fastify/cookie for the OAuth binding cookie
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 20:13:16 +02:00
Meta Vens
c1dfe15dd5 Merge readme-front-door: README opens with value, problem, entry points, live versus planned 2026-10-22 20:04:06 +02:00
Meta Vens
c7cf78bbbc README: front door with value, problem, entry points, live versus planned
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 20:03:50 +02:00
Meta Vens
ece6ba1d62 Tests: a state completes once and only in the browser that launched it; the gate holds for every mode, provider and handoff (red against the callback that accepts any signed state)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 19:04:10 +02:00
Meta Vens
9fd152feff Tests: a foreign app's caller cannot start a Bifrost flow, with no policy attached
Kills the surviving mutant on the caller.appSlug comparison in startOAuthFlow: over HTTP a foreign secret never resolves to a caller, so only a direct call reaches that arm.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 18:24:42 +02:00
Meta Vens
ed964201d4 Docs: startRequiresAppCaller, and Heimdall authenticates while Bifrost issues identity
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 18:14:37 +02:00
Meta Vens
7e17a0e952 Start: a profile with startRequiresAppCaller refuses unauthenticated starts; set on Bifrost
Bifrost's browser binding is the secrecy of a nonce carried readable in the signed state, so only Bifrost may mint a Bifrost state. The gate sits in startOAuthFlow beside the entitlementPolicy caller check, so HTTP and the private command plane share it. Follows the red tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 18:14:37 +02:00
Meta Vens
6d43eacd84 Tests: apps that bind browser completion refuse unauthenticated starts (red; does not pass yet)
The replay of finding known-nonce-login-csrf at the HTTP surface, plus authenticated, cross-app and public-app cases.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 18:13:02 +02:00
Meta Vens
5952cce8a0 State: live d51fa6b proven by a human Twitch sign-in; Joystick consent remains
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 18:03:17 +02:00
Meta Vens
30a1ace6fd State: close eureka/joystick-h1 as accepted (merged, PR #1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 17:56:34 +02:00
Meta Vens
df05570ef6 State: Joystick H1 merged and live at d51fa6b; follow-ups recorded by id
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 17:56:25 +02:00
Meta Vens
d51fa6b999
Merge pull request #1 from GameCult/eureka/joystick-h1
Joystick.tv provider and serialized managed-credential refresh (cut H1)
2026-10-19 17:47:39 +02:00
Meta Vens
778eabaedc Docs: map managed credential custody, the callback mint and the open follow-ups
architecture.md gains a Managed credential custody section: the single
refresh owner, the store-port lock, per-process single flight, typed
revoked and refresh-failed answers, the provider descriptor token fields
and the one token request, the mode x role gates, custody-only
completions, verification layer and follow-ups by id. The spotify finding
now matches the removed spiverse profile; JOYSTICK joins the provider env
lists. implementation-plan and service-contract lose two stale lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:49:34 +02:00
Meta Vens
6db84bfae8 Pin the year boundary, the typed exchange failure and the start refusal's code
Closes StrykerJS survivors on the diff: the cap at exactly 365 days against a
second over, the rotating-exchange failure's typed code (and that a
non-rotating provider is unaffected), and the start refusal's error word.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:45:35 +02:00
Meta Vens
1d856ebd40 Code exchange: a rotating provider's grant without a refresh token fails the callback
Joystick rotates refresh tokens, so a code-exchange answer whose refresh_token
is absent or empty would store a credential the first refresh revokes. The
shared exchange now throws a typed ProviderResponseError before the identity
is resolved or anything is written. The residual-risk comment on the in-flight
refresh map cites its follow-up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:35:11 +02:00
Meta Vens
4e312828c3 Pin the handoff strip: a custody-only backend_callback delivery carries no refresh token
Delivers a joystick connect through a backend_callback handoff and checks the
posted body has no refreshToken or refresh and empty capabilities, so the
handoff spreading `issued` instead of `delivered` fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:34:44 +02:00
Meta Vens
09ea233592 Token answers: an expires_in beyond a year is unusable, so the default lifetime applies
A value like 3e11 overflowed the Date the expiry is stored as and surfaced
as an untyped error. usableExpiresIn now caps a usable value at 365 days;
the refresh path is pinned on memory and live Postgres.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:34:43 +02:00
Meta Vens
e1ac84fb70 Joystick custody needs a creator binding, at start and at the callback
callbackMint now takes the connection: custody_only is a connect for a
managed-connection-only provider bound to connection.kind creator with a
targetId. Anything else is refused at start with creator_connection_required
before any redirect, and at the callback from the signed state before the
code exchange. The streampixels profile note says what Heimdall guarantees
and records the S1 rule that SP's redeem treats a non-creator Joystick
completion as an error, never a sign-in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:34:24 +02:00
Meta Vens
26f264877a Pin the hybrid capability listing a viewer sign-in carries
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:04:12 +02:00
Meta Vens
a911da93d8 Claims: facts are the one owner of a capability-free claim
Every shared capability needs a non-empty anyOf, so an empty fact set already
yields no capabilities; the explicit empty list beside it was a second owner
no test could tell apart from the first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:34:41 +02:00
Meta Vens
655fcc7d22 Credential rotate decisions carry a required expiry
Refresh and exchange answers now type as ExpiringTokenSet, and a rotate
decision requires tokenExpiresAt, so neither store has a no-expiry rule left
to mutate: a NULL expiry can only be written by a revoke.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:29:10 +02:00
Meta Vens
32208cc8e2 Pin the callback's refusal of a signed state the provider has no role for
Re-signs a joystick connect state as sign_in and link with the app's own key
and shows the callback refuses before the code exchange and writes nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:27:28 +02:00
Meta Vens
a32be41878 Token answers: a default lifetime replaces an unknown expiry; a malformed refresh_token is typed
A token answer without a usable expires_in (absent, non-numeric, a string that
is not a positive integer) now takes the descriptor's
defaultAccessTokenLifetimeSeconds (3600 for every provider), so no issued
token has a NULL expiry that dueForRefresh would never refresh. A 2xx whose
refresh_token is present but not a string is the typed
provider_body_not_token_set (502 managed_credential_refresh_failed, tokens
kept); an empty string stays a missing token, so a rotating provider still
fails closed. The expiry rule is now pinned on memory and both live Postgres
rigs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:24:21 +02:00
Meta Vens
79ea0007d3 OAuth callback: mode and provider role decide what a completion mints
The start gate only refused early. The callback ignored the signed state's
mode, so a Joystick connect for StreamPixels redeemed into a viewer_access
session. callbackMint(profile, provider, mode) now decides at the callback:
identity providers keep a viewer session (Bifrost discord connect unchanged);
a connect for a managed-connection-only provider stores custody and mints a
claim with no facts, no capabilities and no refresh token (the refresh route
would recompute viewer_access from the account); anything else is refused.
StreamPixels' redeem reads only account, provider, mode, connection and
claimSet.identities, so it accepts the capability-free claim unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:23:53 +02:00
Meta Vens
6bdaed2a9b Token set check: drop the array clause the access_token check already decides
A JSON array has no string access_token, so the typeof check refuses it;
the separate Array.isArray clause was an equivalent mutant's worth of code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:44:20 +02:00
Meta Vens
c1fbc1261a OAuth start: connect keeps admitting identity providers, as Bifrost uses it
The first gate refused connect for a provider outside managedConnectionProviders,
which broke Bifrost's existing Discord connect. sign_in and link still take
identityProviders only, so a managed-only provider (Joystick) can never sign
anyone in or link; connect takes either list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:38:13 +02:00
Meta Vens
b15bf33b21 Refresh: one attempt per identity per process; waiters share its outcome
Callers that arrive while a refresh of one linked identity is in flight in
this process join it and receive its success or failure, instead of queuing
on the row lock and presenting the same refresh token again behind a failed
holder. The entry lives as long as the attempt, so a later request retries.
The store lock stays the cross-process guard; the residual risk (one
presentation per process per burst) is written into the service contract.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:34:39 +02:00
Meta Vens
d989860163 Refresh classification: revoke only on a 400 invalid_grant; any other answer keeps the tokens
A grant verdict is read from a 400 body by exact code, never from a 401, a
5xx or a 2xx. A 2xx that is not an object with a non-empty string
access_token and no error is refused as provider_body_not_token_set, so a
malformed success keeps the tokens and surfaces as the typed 502 for every
provider, rotating or not. A refresh answer without expires_in stores the
expiry as unknown rather than keeping the already-due one; an unknown expiry
is never due, so the next resolve does not refresh again.

Pins Soul's three surviving mutants: substring code match, the dropped
expiry rule, and the snapshot refresh token on a non-rotating provider.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:34:17 +02:00
Meta Vens
c554c00697 OAuth start: the profile's role lists decide which provider a mode may use
sign_in and link now take only identityProviders; connect takes only
managedConnectionProviders. supportsProvider(), which unioned the role lists
with entitlementSources and never looked at the mode, is deleted: a Joystick
sign_in for streampixels no longer starts, so a Deru sign-in cannot rewrite
his managed credential row. No built-in profile had a provider reachable
only through the union.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:31:59 +02:00
Meta Vens
34a8c6a81d Tests: a late decider still queues behind the one waiting on the in-memory chain
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:52:27 +02:00
Meta Vens
6b8c4a9c63 Tests: pin the refresh fast paths, boundaries and connection hygiene
Added after a diff-scoped StrykerJS run left survivors: no-lock paths, the
skew boundary, decision kinds, a vanished row, open-transaction hygiene on
the live store, and the token request's method, signal, token type and
scope handling.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:47:37 +02:00
Meta Vens
9b3d44f56a Tests: satisfy exactOptionalPropertyTypes in the Joystick stub
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:25:01 +02:00
Meta Vens
f6baadec0c Tests: refresh failures surface as the typed ManagedCredentialRefreshFailed; seven providers
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:20:18 +02:00
Meta Vens
7ce9588503 Postgres store: return created_at and updated_at as ISO strings too
The credential write returns updated_at; a Date there broke the equality the
port promises against the in-memory store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:18:12 +02:00
Meta Vens
3eaa9ef265 Declare Joystick in the Idunn recipe and document the locked refresh
Recipe optional_environment gains the Joystick client id and secret file;
service-contract documents the row lock, rotation fail-closed and the 410/502
answers; the StreamPixels profile names Heimdall as sole holder of provider
refresh tokens (F5).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:15:42 +02:00
Meta Vens
43b7072dfb Postgres store: return token_expires_at as the ISO string the port promises
pg returns a Date for TIMESTAMPTZ; a byte-identity check on a kept credential
saw a Date where the port types a string.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:15:12 +02:00
Meta Vens
1c38d12050 Add Joystick as a confidential, rotating managed-connection provider
Joystick joins the catalog (Basic client auth, rotatesRefreshTokens), resolves
identity by channel id, and is a streampixels managed-connection provider only:
it is not an identity provider for the profile (ruling signin-waits-for-public-bot).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:13:40 +02:00
Meta Vens
c81f923890 Refresh managed credentials under a row lock, with typed revocation
refreshLinkedIdentityCredentialIfNeeded is deleted. refreshManagedCredential
owns the policy; HeimdallStore.updateLinkedIdentityCredential owns the row
(SELECT ... FOR UPDATE in Postgres, a per-id chain in memory), so a refresh
token is presented once across concurrent requests and processes. invalid_grant
clears the tokens (410 managed_credential_revoked); any other failure keeps
them (502 managed_credential_refresh_failed). The "?? refreshToken" keep-old
fallback is gone; keeping it is an explicit branch for non-rotating providers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:11:34 +02:00
Meta Vens
0dbcd98019 Collapse ten per-provider token functions into one descriptor-driven request
Endpoint, client-auth method (RFC 7591 names) and rotation now live on
ProviderDescriptor; requestProviderTokens is the only code that talks to a
token endpoint. Failure labels are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:06:32 +02:00
Meta Vens
2108d1088b Handoff: rehydrate with plain python, not the repixelizer venv on E:
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:44:29 +02:00
Meta Vens
8066bcbbee State: Joystick H1 is the active cut; Ghostlight canaries demoted behind it
Points at campaign joystick:campaign:self; flags the 1086aee deploy fact as
last-recorded (2026-08-22, ~100 commits behind HEAD); drops the stale E:
path and repixelizer-venv rehydrate command from the handoff.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:44:24 +02:00
Meta Vens
7904e17cd2 Pin the predicate splitter on a quoted identifier
Soul pass 7's Y2, treating only single quotes as quoted text, survived:
no test gave the splitter a double-quoted identifier. One case now holds
an identifier containing " AND (" and checks it stays whole.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:18:53 +02:00
Meta Vens
996f21f58c Schema check: deterministic column collations, a named TEMP refusal, and kills for the printer
Soul pass 7, S7-3 and S7-4, P7-3 and P7-5.

Columns (S7-3): every declared column must be under a deterministic
collation. A case-insensitive provider_user_id whose key index compares
under "C" passed, and the store's own lookups then matched other users'
ids.

The check becomes checkSchemaRequirements(pool, requirements), with
Heimdall's store calling it with HEIMDALL_SCHEMA_REQUIREMENTS (its tables,
columns, keys and privileges). That seam lets a live test check a
predicate Postgres prints differently from how it is written (a literal
gains its cast): the check must still pass, so comparing the raw text
instead of the printed form (P7-3's Y1) now fails.

A role that may not create temporary tables was refused with 42501 and
told to check GC_ACCESS_DATABASE_URL_FILE (P7-5). The predicate printer now
refuses it as SCHEMA_TEMP_PRIVILEGE, and startup says to grant the role
TEMPORARY on its database, in fixed text.

New fixtures (S7-4): a case-insensitive collation on a key's first column
(Y3), NOT NULL added to a nullable column of linked_identities (Y5), and
every privilege on auth_completions except on attempt_id (Y8) are refused;
a key index that INCLUDEs an undeclared case-insensitive column starts
(Y4).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:52:41 +02:00
Meta Vens
588739857a Schema: name what the startup check does not prove
Soul pass 7, S7-2. The out-of-scope list named CHECK constraints, triggers
and row-level security. It now also names unique indexes beyond or
stricter than the required keys (including leftovers of an interrupted
concurrent build, which are enforced once ready), NOT NULL columns the
schema does not declare and that have no default, and column-level SELECT
under SELECT * or RETURNING *, which needs every column of the table.
Documentation only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:52:40 +02:00
Meta Vens
d029e08a2e Recipe test: explore loadConfig as Idunn starts Heimdall
Soul pass 7, S7-1. The exploration always called loadConfig with no
arguments, and the candidate socket alone is refused (it needs the base
URL), so neither the Idunn candidate path nor --state-root was ever run: a
secret read only there (Y6, Y7) went unseen.

The recipe's [service] arguments after the entry script, each binding
given a probe path, are now the argv of an Idunn-shaped run, together with
a loopback candidate socket and its base URL. That run is added on its own
and to every combined run. A test pins the parsed argv, that both
environment names are declared in the recipe, and that loadConfig accepts
the shape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:52:40 +02:00
Meta Vens
ca2366cecf Schema check: validity is the rule; pin the printed predicates
The mutations dropping indisvalid or indisready each survived alone,
because a failed CREATE INDEX CONCURRENTLY clears both. Postgres never
marks an index valid before it is ready (DROP INDEX CONCURRENTLY clears
validity first), so indisready adds nothing and is deleted. A fixture now
holds an index that is ready but not valid, the state an interrupted DROP
INDEX CONCURRENTLY leaves, set directly in pg_index by the admin role.

Comparing the raw declared predicate instead of Postgres's printing of it
survived too: the schema's one predicate splits into the same conditions
either way. A live test now pins printedDeclaredPredicates to the printed
predicate of the applied attempt index, so the printing itself is
checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 21:28:50 +02:00
Meta Vens
97632b7cfa Print the declared predicates in a module function, not a store method
The store's coverage test lists every method on PostgresStore as an
operation the workload must call, and the private predicate printer
counted as one. It is a helper of checkSchema, not a store operation, so
it becomes a function of the pool.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 21:11:18 +02:00
Meta Vens
eff5098c23 Schema check: the collation alias is not a reserved word
`collation` is reserved in Postgres, so the key check's query failed with
42601 on every database and every start refused. The live block showed it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:58:29 +02:00
Meta Vens
d2ac9696c7 Recipe test: combined runs from accepted values, config literals as probes, fresh import
Soul pass 6, F5 and F6. The all-at-once run set every name to one probe
value and died in loadConfig's first lines, so reads gated on a specific
value (Z4) or on two values late in the function (Z5) were missed, and a
copy of process.env taken at module load (Z6) was never the recorder.

Each name now gets each probe value alone, and the probe values include
every string literal in config.ts; the combined runs set every name at once
to values loadConfig accepted for it alone. config.ts is imported afresh
while the recorder is process.env, so a module-scope capture records too.
The remaining limit is stated in the test.

failureOf in the app tests now prints the error with util.inspect as well,
so a non-enumerable cause carrying the body (Z3) shows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:40:13 +02:00
Meta Vens
0444360733 Schema check: valid, deterministic keys; Postgres-printed predicates; column grants; nullability
Soul pass 6, F1-F4, F7 and F8.

Keys (F1, F2): a key is met only by a unique index that is valid and
ready, so the invalid index a failed CREATE UNIQUE INDEX CONCURRENTLY
leaves behind (every sign-in failing with 42P10, or one consume taking
two rows) is refused; and whose key columns compare under deterministic
collations, so a case-insensitive collation cannot merge two providers'
user ids into one row and move an identity between accounts.

Predicates (F3, F7): the declared predicates are printed by Postgres
itself, by indexing a temporary copy of each keyed table's declared
columns in one transaction that is rolled back, and compared with the
index's printed predicate as sets of top-level AND-ed conditions, split
by nesting and never inside quoted text. Case and structure are kept, so
((a OR b) AND c) and (a OR (b AND c)) differ, as do 'Pending' and
'pending', and an extra condition narrows the predicate and is refused.
Conditions in another order match.

F4: lookup-only indexes are no longer required (REQUIRED_RELATIONS is now
REQUIRED_TABLES; unique indexes are checked by shape in REQUIRED_KEYS), so
a renamed attempt index or a dropped lookup index starts. Privileges are
checked per column with has_column_privilege on every column the schema
declares, which a table grant satisfies; a role granted each needed
privilege column by column starts and runs every store operation, and one
holding INSERT on only one audit column is refused. On (c): a unique index
treats NULL keys as distinct unless it is NULLS NOT DISTINCT, so rows with
a NULL attempt_id never collide and `attempt_id IS NOT NULL` is redundant;
that condition may be absent from the attempt index's predicate, except on
a NULLS NOT DISTINCT index (refused). A key declared without a predicate
must have none, since ON CONFLICT cannot infer a partial arbiter.

F8: a column the schema leaves nullable must be nullable; NOT NULL added
to attempt_id is refused. CHECK constraints, triggers and row-level
security stay out of scope, as the schema comment says.

Every change is a live fixture: invalid identity key, invalid attempt
index over duplicate attempts, case-insensitive key, narrowed and
OR-widened predicates, NULLS NOT DISTINCT, NOT NULL added, partial column
grants are refused; reordered and unredundant predicates, a renamed
attempt index, dropped lookup indexes and column-by-column grants start.
The fake-pool code-mapping tests are replaced by unit tests of the
predicate comparison.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:40:12 +02:00
Meta Vens
6c0c87669f Schema check: a unique key is matched by shape, not name; quiet fixture pools
The rule mutation that stopped checking a named unique index by its name
survived, and rightly: an index of the same table, key columns, predicate,
uniqueness and immediacy keeps R21.1 whatever it is called, and the named
index's existence is already required as a relation. The name condition
and REQUIRED_KEYS' index field are deleted.

The live block failed 5 of 10 repeated runs with unhandled 57P01 errors:
a test's own pool, already ended, still had connections closing when the
forced drop terminated them, and nothing listened. Every pool the tests
open now goes through fixturePool, which ignores those errors; the store's
own pool keeps its listener and is not a fixture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 19:30:40 +02:00
Meta Vens
fd98e36186 Recipe test: explore loadConfig's branches, refuse environment copies
Soul pass 5, S5-7. The recording environment saw only the reads an empty
environment makes, so a secret read on a branch a value opens (X6) was
missed, and a read from a spread copy of the environment (X7) was
invisible.

loadConfig now runs 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 of five probe values, then all of them set to one probe
value at once; a run that throws keeps the reads it made first. Copying or
enumerating the environment (the Proxy's ownKeys and
getOwnPropertyDescriptor traps) is recorded, and a test refuses it, since
reads from a copy cannot be seen. HMAC joins the secret-shaped backstop
pattern.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 18:58:02 +02:00
Meta Vens
35f804f7ef Pin provider errors and Bifrost's reply exactly; defend errorIdentity's filters
Soul pass 5, S5-4: the provider-error tests proved only that the word
CANARY was absent, so a message carrying a 16-byte slice of the body (X1,
X2) passed, and the Bifrost success reply was checked with
objectContaining, so a 9-byte body head (X5) rode along. Each provider
error's message is now pinned exactly, the Bifrost success reply is pinned
as exactly status, supportFact and bifrostStatus, and every canary body
starts with the canary, so any prefix of it shows.

S5-5: errorIdentity's class and code filters had no test (X3, X4). Cases
now show a code or class name that carries input, is too long, is not a
string, or comes from a thrown non-Error or null is dropped, and a short
identifier survives.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 18:57:17 +02:00
Meta Vens
963150f537 Audit events never carry a completion code
Soul pass 5, S5-3: auth_completion_created stored completion.code, which
the unauthenticated redeem route turns into the session until it expires
(300 s by default), so the audit trail could redeem a live sign-in. The
two auth_completion_redeemed events (the HTTP redeem route and the private
command plane's redeem by attempt) stored the spent code as well.

All three payloads drop it. Nothing reads audit payloads back: the store
has no audit read, and no repository indexed by VoidBot consumes these
events. The event's sessionId already names the completion (one per
callback), so no replacement key is added. This matches Heimdall's own
witness contract, which says codes are redacted from audit exports.

Tests drive a sign-in through the HTTP redeem route and through the plane,
pin each payload exactly, and check the code appears in no audit event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 18:56:35 +02:00
Meta Vens
731ce08cfa Schema check: keys as the store relies on them, typed columns, per-table privileges
Soul pass 5, S5-1 and S5-2. checkSchema passed four databases the store
could not serve, and demanded privileges the store never uses.

Keys: every primary key and unique constraint, and each unique index the
schema creates by name, must stand as an immediate (not deferrable) unique
index whose key columns, counted by indnkeyatts and excluding INCLUDE
columns, are exactly the declared ones, with exactly the declared
predicate. A named index is checked by its name, so the partial attempt
index R21.1 depends on cannot be swapped for a plain or unpredicated one of
the same name. Predicates compare with case, parentheses and white space
removed, the form both the schema text and pg_get_expr reduce to.

Columns: each carries its declared type, compared as a type OID through
to_regtype.

Privileges: STORE_TABLE_PRIVILEGES in postgres.ts says what the store's
statements do to each table. audit_events needs INSERT only;
capability_grants and private_command_receipts need no UPDATE; nothing
needs DELETE. REQUIRED_TABLE_PRIVILEGES and REQUIRED_TABLES are gone.

The live block now proves the map both ways against a real Postgres: a
role granted exactly the map starts and runs every store operation (the
test checks it called every method), and for each privilege in the map,
a role granted all but that one is refused at startup and fails the same
workload with 42501. Each damage Soul found (a DEFERRABLE key, an INCLUDE
key, the attempt index replaced by a plain one of the same name, a retyped
column), plus an expression-widened key, an unpredicated or re-predicated
attempt index, is refused; a key index with extra INCLUDE columns starts.
Every refusal also proves its store left no connection open (tagged by
application_name), on the no-apply, apply and 42501 paths. Cases clone a
template database and the block has a 120 s budget, instead of building
the schema per case under the 5 s default that timed out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 18:55:45 +02:00
Meta Vens
b5d7b6b0cc A refused store closes its pool; pin the key's columns and uniqueness
The startup check's refusal left the store's pool open: the process exits
on it in production, but the connection outlived the refusal. createStore
now closes a store it refuses.

Two live cases the first run showed undefended (mutants D6 and D9): a
unique key replaced by a plain index on the same columns, and by a unique
index on other columns of the same count. The read-only-role case also
checks that no session of the role outlives the refusal. The fixture's
owner pool ignores the connection ends its own forced drop causes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:29:19 +02:00
Meta Vens
804f41f5f7 Pin that no provider error carries the provider's body
F1's second half, tested where it is decided: the Discord token exchange
(a 2xx body that is not JSON, and a 401), the Discord guild lookup and the
YouTube channel lookup each fail with a ProviderResponseError whose code
and status name the failure, and no printed form of the error (message,
stack, JSON) holds a byte of the canary body. Until now only the callers'
fixed answers were pinned, so a body in the message went unseen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:16:39 +02:00
Meta Vens
7be541467d Schema check: a key is a unique index on its columns, primary or not
The store's ON CONFLICT clauses and the foreign keys need a unique,
non-partial index on exactly the key's columns; whether it is the primary
key changes nothing a request does. Requiring the primary flag added a
refusal no failing request motivated, so it is dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:16:21 +02:00
Meta Vens
8541ae3f2f Startup proves the database can take Heimdall's writes
Soul pass 4, F4: the startup check passed on databases where every request
still failed: a role granted SELECT only (O2), and a table whose primary
key and key column were dropped (N), including on a start that applied the
schema, since CREATE ... IF NOT EXISTS leaves a damaged table as it is.

Every start now ends in checkSchema, after applying the schema or not. It
requires, read from the schema SQL: every relation; every column the
created tables declare, not only the added one (read from pg_attribute, so
a column the role may not see is not reported as missing); every primary
key and unique constraint as a non-partial unique index on exactly its
columns, which is what the store's ON CONFLICT clauses and the foreign
keys rely on; and SELECT, INSERT and UPDATE on every table. A missing
piece refuses with SCHEMA_MISSING, a missing privilege with
SCHEMA_PRIVILEGES, through the same fixed startup message.

A live-Postgres block drives createStore itself, skipped unless
HEIMDALL_TEST_PG_ADMIN_URL names a role that may create databases and
roles: a read-only role (and its canary password stays out of the
message), a dropped primary key with and without applying, a unique key
replaced by a partial one, and a dropped column.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:15:34 +02:00
Meta Vens
48915317ef Recipe test observes the secrets loadConfig reads
Soul pass 4, F3: the recipe test found Heimdall's secrets by parsing
readSecretInput calls out of the source, and an alias, a parenthesised
first argument or a colliding local name hid a new secret from it (S1-S3).

The test now runs the real loadConfig against an environment that records
every name looked up, standing in for process.env as well, and takes each
`_FILE` lookup as a secret: readSecretInput makes one per secret, however
the call is spelled and whatever list computes the name. Each must be
declared as `_FILE` in the recipe and never under its plaintext name. The
source scan and its table of computed names are deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:09:20 +02:00
Meta Vens
2e06678301 Patron support sync keeps Bifrost's answer by status alone
Soul pass 4, F2: the route stored Bifrost's whole response body in its
audit event and returned it to the caller, as `detail` on a refusal and as
`bifrostResponse` on success. Another service's body can quote the signed
fact or its own configuration.

Both audit events now carry bifrostStatus and no body; a refusal answers
502 with fixed text and Bifrost's status; success answers bifrostStatus in
place of the body, which no caller reads (Bifrost's docs name only the
route). The body is discarded unread.

Tests drive the route against a Bifrost that answers 200 and 403 with the
canary in its body, and pin the reply and the audit event exactly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:08:29 +02:00
Meta Vens
b5b980578c Backend handoff failure names the status, never the app's answer
Same class as Soul pass 4's F1: deliverBackendHandoff put the receiving
app's whole response body into its error message. The handoff carries
tokens and an app's error page can quote it, and the message reaches
whatever catches the error. It now names the status alone and discards the
body unread.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:07:45 +02:00
Meta Vens
698f5dfc0e Private command diagnostics carry class and code, never a message
Soul pass 4, F1: a provider's 2xx refresh answer that was not JSON made
JSON.parse quote the text around the fault, a refresh-token fragment among
it, and the plane returned that message in the reply's diagnostics. Those
travel outside the sealed envelope and Ghostlight logs them.

The plane's diagnostic is now fixed text plus the error's class and code,
through errorIdentity, which the failed-callback audit event now shares.
Every provider body Heimdall parses goes through readProviderJson: a
non-2xx answer or a body that is not JSON becomes a ProviderResponseError
(status and code, provider_status or provider_body_not_json) and no
parser message survives. This replaces ProviderHttpError and the separate
parses in the Discord guild lookup and the YouTube channel lookup.

Soul's canary probe is committed inverted: a refresh against a malformed
2xx body and against a 400 whose body holds the canary; no byte of it may
appear in the reply or its decoded failure payload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:07:16 +02:00
Meta Vens
efd11373b8 Audit event keeps a provider's HTTP status, never its body
Self's ruling: the failed-callback audit event lost the provider's status
when it stopped storing the message. A provider's non-2xx answer is now a
ProviderHttpError carrying the status, and its message no longer holds the
response body, which nothing needs and which can quote the request. The
audit event adds providerStatus: an integer in 100-599, or null.

Tests drive the real Discord token exchange against a 401 whose body holds
the canary, and throw a status of 9999.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:03:57 +02:00
Meta Vens
f94729f5f7 Relay's error description is set only when one survives
Typecheck under exactOptionalPropertyTypes refused the relay commit: a
provider error that filters down to nothing left errorDescription
explicitly undefined in the page and handoff payloads. The field is now
added only when a relayed value remains.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:50:58 +02:00
Meta Vens
7c14414cd2 The failed-callback audit event keeps the error's class and code
Self's ruling: the audit event stored error.message, and pg or resolver
text can carry fragments of a database URL. It now stores the error's
class name and its code, each checked against a narrow pattern. A test
puts the canary in the host of an ENOTFOUND error and checks that no
audit event holds it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:49:32 +02:00
Meta Vens
7de12e84be Relayed provider errors are printable, bounded and inert in the page
Self's ruling: the provider_error relay stays, because it is the protocol,
but its error and error_description are query parameters anyone can write.
Only the characters RFC 6749 4.1.2.1 allows in them survive (%x20-21,
%x23-5B, %x5D-7E), and each is cut to a bound (64 and 256). The JSON
answer, the browser page and the backend handoff all take the relayed
values.

The page has no template engine. Every value in it goes through
serializeForScript, which escapes `<`, apart from the fallback URL in the
link's href, which the URL serializer percent-encodes. A test puts
`<script>` in error_description and checks the page holds only its own
script tag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:49:30 +02:00
Meta Vens
cad12165a9 A start that does not apply the schema proves the schema is there
Self's ruling on the open apply=0 item: connecting proves the URL, not the
schema, so a good URL to an empty database started and then answered every
request with a 500 (42P01).

PostgresStore.checkSchema replaces checkConnection. One query finds every
table and index CREATE_SCHEMA_SQL creates and every column it adds, and
anything missing fails with SCHEMA_MISSING, which startup reports through
the same fixed message. The required names are read from CREATE_SCHEMA_SQL
itself, so a new table or migration is required as soon as it is written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:49:23 +02:00
Meta Vens
869802126c Pin the 4xx branch of the error handler with a thrown error
A mutant that put the message back into the non-validation 4xx answer
survived: Fastify 5.8.5's own 4xx errors (invalid or empty JSON body, 415,
413) carry fixed messages, so the JSON-parse and media-type cases could not
tell. The branch protects against any error thrown with a 4xx status, whose
message is whatever its thrower wrote. A test route now throws one with the
canary, and the answer must be the code alone.

The handler's comment and the earlier commit's message said JSON.parse and
the 415 quote input; in this Fastify they do not. The comment is corrected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:37:11 +02:00
Meta Vens
ca2e78f00c Recipe test reads its secret names from the source
Soul pass 3 (R3): the recipe test's list of secret names was written by
hand, and its secret-shaped pattern missed TOKEN, API_KEY, PRIVATE_KEY,
SALT, CREDENTIAL and DSN. A new secret could be read in the source and
declared in plaintext in the recipe without a failure.

The test now takes the names from every readSecretInput call under src/: a
literal as written, the two computed names over the lists that compute
them, and a failure for any argument it cannot expand. Every one of those
must be declared as its _FILE and never by its plaintext name. The pattern
is wider, with two named exemptions: the signing key's path and its
bootstrap flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:30:18 +02:00
Meta Vens
c626a86d55 A lost idle Postgres connection no longer kills Heimdall
Soul pass 3 (R2): the pool had no 'error' listener. pg emits an idle
client's connection loss there (a database restart, a terminated backend),
so the event went unheard, the process died, and Node printed the pg Client
with its connection parameters.

createPostgresStore now listens and writes one line naming the error code.
The pool has already dropped the dead client and connects again on the
next query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:30:15 +02:00
Meta Vens
0f5ffd9e69 Every start connects to Postgres; pin the signing key's read refusal
Soul pass 3 (R1, R4). With GC_ACCESS_APPLY_SCHEMA_ON_STARTUP=0, startup
never opened a connection, so a misbound database URL surfaced only in a
request's error answer. createStore now connects on every Postgres start:
it applies the schema when asked and otherwise runs `SELECT 1`, and either
failure is the same fixed message naming GC_ACCESS_DATABASE_URL_FILE and a
code. The entrypoint harness gains that case with the canary in the host.

The harness also pins the signing key's read-failure branch with a key file
of mode 000. Root reads such a file, so the case runs the entrypoint as a
user a mode can refuse: the test process itself when it is not root, or
else the checkout's owner. It is skipped, with the reason in its title, on
Windows or as root in a root-owned checkout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:30:10 +02:00
Meta Vens
33afcbf364 HTTP error answers carry fixed text, never an error's message
Soul pass 3 (R1): with no error handler, Fastify answered a 5xx with the
error's message. A store failure under a misbound database URL reached an
anonymous caller as `getaddrinfo ENOTFOUND <host>` or `database "<db>" does
not exist`, and a misbound URL puts part of the password in either. The same
default quoted the request body in a JSON parse error (Node's JSON.parse
message carries the input), the Content-Type header in a 415, and the path
in a 404.

buildApp now sets both handlers. A 5xx answers `{ error: "internal_error" }`
and writes one stderr line naming the method, the route pattern and the
error code. A schema failure answers the failed rules by schema path and
Ajv message, which come from the route's schema. Any other 4xx answers
`invalid_request` with the error code. An unknown route answers `not_found`.

The app's own answers had two more echoes: `unknown_app` quoted the slug,
and a failed provider callback put the caught error's text in the browser
page and the backend handoff (the JSON answer was already fixed). Both are
fixed text now; the full callback error stays in the audit event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:30:06 +02:00
Meta Vens
376dfbd2c2 Startup database failure names the input and a code, not the URL's parts
The entrypoint harness showed pg printing a piece of the database URL file
on a failed startup: `getaddrinfo ENOTFOUND <host>` for an unresolvable host.
A password with an unescaped delimiter moves part of itself into the host or
the database name, and the resolver or server error then prints it. The only
thing keeping a malformed URL out of stderr was pg dropping Node's `input`
property (Soul S5).

createStore now turns a schema-preparation failure into one error naming
GC_ACCESS_DATABASE_URL_FILE and the error code, with no cause. The harness
cases expect that message, and a new case puts the canary in the host.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:46:22 +02:00
Meta Vens
83d2f48256 Docs: secrets are _FILE names; drop the unread Spotiverse secret
Soul S4: the Bifrost handoff notes, the Bifrost profile and the service
contract still named plaintext secret variables; each now names the _FILE
credential path. .env.example and the Spotiverse profile taught
GC_ACCESS_APP_SPOTIVERSE_SHARED_SECRET_FILE, which nothing reads: spotiverse
is not in appSlugs. Both lines are removed rather than adding the slug.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:40:21 +02:00
Meta Vens
2800d88d10 Pin the recipe's secret declarations, and declare every app secret file
Soul S2: no test read deployment/idunn/recipe.toml, so a plaintext secret
name could be declared again (mutant ME) or a published _FILE name dropped
(mutant MF) with the suite green.

tests/recipe-secrets.test.ts reads the service's declared names and asserts
that no secret-shaped name is declared except as _FILE, that none of the
secrets Heimdall reads is declared under its plaintext name, and that every
provider client-secret file the witness publishes, every published app
profile's shared-secret file, and the database URL, token key and patron
secret files are declared.

The app-profile rule found two gaps: the witness publishes the repixelizer
and streampixels profiles and Heimdall reads their shared-secret files, but
the recipe declared neither, so an Idunn binding could not configure them.
Both are declared as optional, as GitHub and Spotify were for Soul F5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:40:21 +02:00
Meta Vens
d73a26dfd1 Pin no-leak at the terminal: run the real entrypoint with canaries
Soul S1 and S5: the secret tests checked error.message, but Node prints an
error's cause and properties too, and nothing tested src/index.ts. Soul's
mutants MA (the read error given `{ cause: error }`) and MI (the startup
catch printing the config) both leaked a canary to stderr with the suite
green.

tests/entrypoint-secrets.test.ts spawns `tsx src/index.ts` with only the
given environment and fails on any byte of the canary on stdout or stderr.
Each case must also stop by itself, fail, and say its expected refusal, so
none can pass by never reaching its path. Cases: a URL in an absolute _FILE
slot, a _FILE under a regular file, a relative _FILE, both forms set, a
blank file, a short token key, four malformed or refused database URLs in a
real file (pinning today's pg, which drops Node's `input` property), five
signing-key failures including the bootstrap mkdir, and a listen failure with
every secret configured, which is the entrypoint catch that holds the config.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:40:21 +02:00
Meta Vens
e091bb3fd1 Signing key path: absolute only, and no error carries the path
Soul S3: GC_ACCESS_SIGNING_PRIVATE_KEY_PATH is now the only way the signing
key gets in, and its errors printed the path: the missing-file message
interpolated it, and fs errors from the read and the bootstrap mkdir carried
it in their message and properties. An operator moving off the deleted inline
PEM input who binds the key text to _PATH would have the private key written
to the journal.

The path now takes the secret reader's rules. loadConfig refuses a relative
value, which PEM text always is. Every signing-key failure is a fresh error
naming only the variable and a code, with no cause and no properties.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:40:07 +02:00
Meta Vens
e35441e378 Pin the token-key length refusal custody now relies on
With custody's "set but empty" check deleted, the 32-byte length check is the
only refusal of a malformed token key, and StrykerJS showed nothing tested it
(forcing it off survived). A 16-, 31- and 33-byte key are each refused, and
the refusal does not carry the key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:03:24 +02:00
Meta Vens
fe26208f05 Docs and .env.example teach secrets as NAME_FILE credential files
Soul F4: the architecture configuration list, the Spotiverse restore steps and
.env.example still taught plaintext secret variables. The architecture list now
names only what src/config.ts reads, plain settings apart from secret files,
and drops the names nothing reads (GC_ACCESS_SESSION_SECRET, GC_ACCESS_ENABLED,
GC_ACCESS_INTERNAL_URL, the Discord bot token, the Patreon campaign id and
two TTLs). .env.example comments out the _FILE lines, because an empty
NAME_FILE= is refused at startup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:52:11 +02:00
Meta Vens
f8ff2b26ba Declare the GitHub and Spotify client-secret files the witness publishes
Soul F5: the provider witness names GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET_FILE
and GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET_FILE, but the recipe declared
neither, so an Idunn binding could not configure either provider. Both
providers are live code (the provider list, the catalog and the OAuth start
route serve them), so both names are declared as optional.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:51:18 +02:00
Meta Vens
0178d071c1 readSecretInput: never print the path, refuse relative paths and blank secrets
Soul F1: the unreadable-file error carried the NAME_FILE value, and Idunn
admits any string for a declared name, so a URL bound into
GC_ACCESS_DATABASE_URL_FILE by mistake was printed in full at startup. Errors
now name only the variable and an error code, and a NAME_FILE that is not an
absolute path is refused naming the variable alone.

Soul F2 and F6: a blank database URL file selected memory storage silently,
and a whitespace one selected postgres with a URL of " ". The reader now
refuses an empty or whitespace-only value from either form, so custody's own
"set but empty" check is redundant and is deleted; a short key still fails its
length check. The legacy service.env holds no blank secret-class value
(checked as name/blank booleans), so the legacy unit is unaffected.

Soul F3: tests pin that an empty NAME_FILE is refused rather than unset (S1),
and that each call site (token key, provider secret, app shared secret,
database URL, patron secret) refuses both forms, so no site can read the
plaintext name ahead of the reader (S6, S7, S8).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:50:53 +02:00
Meta Vens
9f0cd73299 Pin the newline and storage-selection rules StrykerJS found undefended
StrykerJS on the reader and its call sites left two findings about the
tests. Every trim fixture had its newline only at the end, so stripping the
first newline anywhere survived: a two-line value now pins "one trailing
newline". No fixture reached the memory branch of storage selection, so
forcing postgres, dropping the backend check or inverting it survived: the
memory default and an explicit backend of either kind are now pinned.

Idunn secret-files cut, Cut 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:49:23 +02:00
Meta Vens
ac86352972 Read every secret input from a credential file named by NAME_FILE
The recipe declared Heimdall's secrets as plain environment, so its admit
contract made the operator binding the only place their values could live,
and the binding was printed into a transcript. The recipe now declares each
secret only as its _FILE twin (GC_ACCESS_DATABASE_URL_FILE required, the rest
optional). A binding binds those under [workload.secret_files] to root:root
0400 credential files, and Idunn's rule that a binding binds only declared
names leaves a plaintext secret nowhere to go. GC_ACCESS_APP_SHARED_SECRET is
deleted outright: nothing reads it.

One reader, readSecretInput, serves every secret: it reads NAME_FILE and strips
one trailing newline, refuses NAME and NAME_FILE set together, and its errors
name the variable and path, never a value or file contents. Storage-backend
selection keys off the resolved database URL. The published provider witness
and the provider_not_configured body name the _FILE variables, and custody's
errors name GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE.

The plaintext fallback (NAME read while NAME_FILE is absent) is a named shim
for the legacy EnvironmentFile unit only; secret-files Cut 5 deletes it.

Idunn secret-files cut, Cut 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:30:57 +02:00
Meta Vens
d2d0778847 Delete the inline signing-key PEM input
GC_ACCESS_SIGNING_PRIVATE_KEY_PEM put the signing key's bytes into the
process environment, and so into any binding, unit or plan that carries
environment. The recipe never declared it and GC_ACCESS_SIGNING_PRIVATE_KEY_PATH
already covers the key as a file, which a binding binds through
[workload.secret_files]. The signing key is now always a file.

Idunn secret-files cut, Cut 1 (delete first).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:26:56 +02:00
88 changed files with 16622 additions and 1289 deletions

View file

@ -1,3 +1,5 @@
# Secrets are files: set NAME_FILE to the absolute path of a file holding only
# the value. An empty NAME_FILE= is refused, so unused ones stay commented out.
HOST=127.0.0.1 HOST=127.0.0.1
PORT=4100 PORT=4100
GC_ACCESS_PRIVATE_COMMAND_HOST=127.0.0.1 GC_ACCESS_PRIVATE_COMMAND_HOST=127.0.0.1
@ -5,31 +7,29 @@ GC_ACCESS_PRIVATE_COMMAND_PORT=4101
GC_ACCESS_BASE_URL=http://127.0.0.1:4100 GC_ACCESS_BASE_URL=http://127.0.0.1:4100
GC_ACCESS_ISSUER=http://127.0.0.1:4100 GC_ACCESS_ISSUER=http://127.0.0.1:4100
GC_ACCESS_STORAGE_BACKEND=memory GC_ACCESS_STORAGE_BACKEND=memory
GC_ACCESS_DATABASE_URL= # GC_ACCESS_DATABASE_URL_FILE=/absolute/path/to/credential
GC_ACCESS_APPLY_SCHEMA_ON_STARTUP=1 GC_ACCESS_APPLY_SCHEMA_ON_STARTUP=1
GC_ACCESS_SESSION_TTL_SECONDS=3600 GC_ACCESS_SESSION_TTL_SECONDS=3600
GC_ACCESS_STATE_TTL_SECONDS=600 GC_ACCESS_STATE_TTL_SECONDS=600
GC_ACCESS_COMPLETION_TTL_SECONDS=300 GC_ACCESS_COMPLETION_TTL_SECONDS=300
GC_ACCESS_SIGNING_PRIVATE_KEY_PEM=
GC_ACCESS_SIGNING_PRIVATE_KEY_PATH= GC_ACCESS_SIGNING_PRIVATE_KEY_PATH=
GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP=0 GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP=0
GC_ACCESS_SIGNING_KEY_ID= GC_ACCESS_SIGNING_KEY_ID=
GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64= # GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE=/absolute/path/to/credential
GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID= GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID=
GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET= # GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE=/absolute/path/to/credential
GC_ACCESS_PROVIDER_PATREON_CLIENT_ID= GC_ACCESS_PROVIDER_PATREON_CLIENT_ID=
GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET= # GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET_FILE=/absolute/path/to/credential
GC_ACCESS_PROVIDER_GITHUB_CLIENT_ID= GC_ACCESS_PROVIDER_GITHUB_CLIENT_ID=
GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET= # GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET_FILE=/absolute/path/to/credential
GC_ACCESS_PROVIDER_TWITCH_CLIENT_ID= GC_ACCESS_PROVIDER_TWITCH_CLIENT_ID=
GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET= # GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET_FILE=/absolute/path/to/credential
GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID= GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID=
GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET= # GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET_FILE=/absolute/path/to/credential
GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID= GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID=
GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET= # GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET_FILE=/absolute/path/to/credential
GC_ACCESS_APP_SPOTIVERSE_SHARED_SECRET=
GC_ACCESS_APP_SPOTIVERSE_BACKEND_CALLBACK_URLS= GC_ACCESS_APP_SPOTIVERSE_BACKEND_CALLBACK_URLS=
GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET= # GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET_FILE=/absolute/path/to/credential
GC_ACCESS_APP_GHOSTLIGHT_RUNTIME_IDS=yggdrasil-ghostlight GC_ACCESS_APP_GHOSTLIGHT_RUNTIME_IDS=yggdrasil-ghostlight

View file

@ -12,6 +12,19 @@ The point is painfully simple:
become "everything phones home for every request" become "everything phones home for every request"
- keep app-domain data separate so "shared auth" does not become "shared swamp" - keep app-domain data separate so "shared auth" does not become "shared swamp"
## Front Door
- **Value:** one shared auth authority: provider OAuth (Discord, Patreon, GitHub, Twitch, YouTube, Spotify, Google OIDC for linking), linked identities, grants, entitlements and session issuance, with Ed25519-signed claims that app backends verify locally.
- **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).
- **Live:** a stateful first slice: signing and JWKS, OAuth state for six providers, in-memory and Postgres stores, a real Discord callback path for the Repixelizer flow, sealed provider tokens, the loopback CultNet operation boundary, Idunn health publication, and the deployed Ghostlight Eve host consuming the discovered boundary.
- **Planned:** the two-account and eight-account Ghostlight human canaries, refresh and revocation flows, admin surfaces, and broader inspection projections beyond the redacted access boundary.
## Current Shape ## Current Shape
This repo now has a stateful first slice instead of a decorative skeleton. This repo now has a stateful first slice instead of a decorative skeleton.

View file

@ -131,17 +131,27 @@ arguments = [
] ]
transport = "http" transport = "http"
route_required = true route_required = true
# A secret input is declared only as its `*_FILE` name. The binding binds it
# under [workload.secret_files] to a root:root 0400 credential file, so the value
# never sits in the binding, the unit or a plan. Idunn refuses a binding that
# sets an undeclared name, so a plaintext secret has nowhere to go.
optional_environment = [ optional_environment = [
"CULTMESH_URI_ODIN_RUDP", "CULTMESH_URI_ODIN_RUDP",
"GC_ACCESS_APP_BIFROST_BACKEND_CALLBACK_URLS", "GC_ACCESS_APP_BIFROST_BACKEND_CALLBACK_URLS",
"GC_ACCESS_APP_BIFROST_SHARED_SECRET", "GC_ACCESS_APP_BIFROST_RUNTIME_IDS",
"GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE",
"GC_ACCESS_APP_GHOSTLIGHT_BACKEND_CALLBACK_URLS", "GC_ACCESS_APP_GHOSTLIGHT_BACKEND_CALLBACK_URLS",
"GC_ACCESS_APP_GHOSTLIGHT_RUNTIME_IDS", "GC_ACCESS_APP_GHOSTLIGHT_RUNTIME_IDS",
"GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET", "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_APPLY_SCHEMA_ON_STARTUP",
"GC_ACCESS_APP_SHARED_SECRET",
"GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT", "GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT",
"GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET", "GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE",
"GC_ACCESS_COMPLETION_TTL_SECONDS", "GC_ACCESS_COMPLETION_TTL_SECONDS",
"GC_ACCESS_IDUNN_HEALTH_CONTRACT", "GC_ACCESS_IDUNN_HEALTH_CONTRACT",
"GC_ACCESS_IDUNN_RUDP_HEALTH", "GC_ACCESS_IDUNN_RUDP_HEALTH",
@ -150,27 +160,36 @@ optional_environment = [
"GC_ACCESS_PRIVATE_COMMAND_HOST", "GC_ACCESS_PRIVATE_COMMAND_HOST",
"GC_ACCESS_PRIVATE_COMMAND_PORT", "GC_ACCESS_PRIVATE_COMMAND_PORT",
"GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID", "GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID",
"GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET", "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",
"GC_ACCESS_PROVIDER_JOYSTICK_CLIENT_ID",
"GC_ACCESS_PROVIDER_JOYSTICK_CLIENT_SECRET_FILE",
"GC_ACCESS_PROVIDER_PATREON_CLIENT_ID", "GC_ACCESS_PROVIDER_PATREON_CLIENT_ID",
"GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET", "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_ID",
"GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET", "GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET_FILE",
"GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID", "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID",
"GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET", "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET_FILE",
"GC_ACCESS_REFRESH_TTL_SECONDS",
"GC_ACCESS_SESSION_TTL_SECONDS", "GC_ACCESS_SESSION_TTL_SECONDS",
"GC_ACCESS_SIGNING_KEY_ID", "GC_ACCESS_SIGNING_KEY_ID",
"GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP", "GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP",
"GC_ACCESS_SIGNING_PRIVATE_KEY_PATH", "GC_ACCESS_SIGNING_PRIVATE_KEY_PATH",
"GC_ACCESS_STATE_TTL_SECONDS", "GC_ACCESS_STATE_TTL_SECONDS",
"GC_ACCESS_STORAGE_BACKEND", "GC_ACCESS_STORAGE_BACKEND",
"GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64", "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE",
] ]
required_environment = [ required_environment = [
"GAMECULT_IDUNN_RUNTIME_BUNDLE", "GAMECULT_IDUNN_RUNTIME_BUNDLE",
"GAMECULT_IDUNN_CANDIDATE_BIND", "GAMECULT_IDUNN_CANDIDATE_BIND",
"GAMECULT_IDUNN_PROCESS_WRITE_LEASE", "GAMECULT_IDUNN_PROCESS_WRITE_LEASE",
"GC_ACCESS_BASE_URL", "GC_ACCESS_BASE_URL",
"GC_ACCESS_DATABASE_URL", "GC_ACCESS_DATABASE_URL_FILE",
] ]
[service.health] [service.health]
@ -181,7 +200,7 @@ schema_generation = "heimdall-v1"
[[state.slots]] [[state.slots]]
id = "service" id = "service"
relative_path = "heimdall.service.cc" relative_path = "cultcache/heimdall.service.cc"
kind = "cultcache-file" kind = "cultcache-file"
schema = "heimdall.service_state.v1" schema = "heimdall.service_state.v1"
writer = "process-bound-single-writer" writer = "process-bound-single-writer"

View file

@ -0,0 +1,265 @@
# 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. 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`). 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.
## Notice
Consent is declared once per room, not per reply. Each experiment room carries
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` 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` 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
only `version` and `scope`. A change to either is a new state event and so 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 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
| field | type | rule |
|---|---|---|
| `member_id` | Heimdall member id | the accepting member. |
| `experiment_id` | string | the room. |
| `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. |
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). 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.
Open gap: the registration checkbox records no version. Void is raising this;
nothing here rules it.
## Answer record
One record per answer. Fields:
| field | type | rule |
|---|---|---|
| `sample_id` | string `<sample>@<version>` | names the thing answered about; `<version>` 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. |
| `scope` | `show` \| `study` \| `train` | copied from that notice version at answer time. Never edited afterwards. |
| `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 | 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. 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
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 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
- 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` 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 `<version>` of `sample_id` (`s@<version>`), `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.
- 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@<version>`, 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.
## 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.
## Training rule
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)`
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.
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
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
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; 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
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:
- redacted replies (recorded as exited);
- replies from unlinked senders;
- replies to an old sample version when the tally is for a newer one.
## 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 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.
- **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 room's notice state event.
- **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 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 notice version and scope it
recorded.
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.
## 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.

View file

@ -68,11 +68,46 @@ paid membership for the requested tier title, and POSTs a signed
`RecurringSupportSnapshot` fact to Bifrost's `RecurringSupportSnapshot` fact to Bifrost's
`/heimdall/patron-support/events` endpoint. `/heimdall/patron-support/events` endpoint.
The outbound fact uses `X-Heimdall-Signature-256` with the shared The outbound fact uses `X-Heimdall-Signature-256` with the shared secret
`GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET`. Bifrost verifies that HMAC, resolves Heimdall reads from `GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE`. Bifrost
the Heimdall account id to its local user account, deduplicates by provider verifies that HMAC, resolves the Heimdall account id to its local user account,
event id, records the support event, and derives patron points locally. deduplicates by provider event id, records the support event, and derives
patron points locally.
This route is a bridge from auth-owned Patreon evidence to Bifrost-owned This route is a bridge from auth-owned Patreon evidence to Bifrost-owned
governance meaning. Heimdall still does not own points, votes, tiers, ledger governance meaning. Heimdall still does not own points, votes, tiers, ledger
history, or payout policy. history, or payout policy.
## App-asserted step-up
Bifrost's profile carries `stepUpAssertion: { methods: ["bifrost-passkey",
"bifrost-email-code"] }`, the only such grant. With its secret and a member's
live Heimdall bearer, Bifrost calls `POST /v1/apps/bifrost/step-up` with
`{method, nonce}` after it has checked the factor itself, and receives an access
token for the same session whose `step_up_at` and `step_up_method` satisfy
Heimdall's unlink check. Bifrost must send a fresh nonce per assertion, keep
the returned token only for the action it is for, and never send a method it did
not verify: Heimdall cannot tell. Contract, codes, limits and what it does not
prove are in `docs/service-contract.md`.
Precondition and limit: Bifrost can call this only while it holds the member's
Heimdall bearer, which it deliberately does not today. Holding it in a cookie
ticket would turn cookie theft into bearer theft and, with a passkey or email
code, into unlink power. And unlink accepts any method: a `bifrost-email-code`
proof can unlink an identity a Google re-authentication would have guarded.
Requiring a method per route is the later hardening (identity moves).
## Identity moves
Bifrost's profile carries `identityMoves: { accountProofMethods:
["bifrost-passkey"] }`, the only such grant (its methods are a subset of
`stepUpAssertion.methods`). With its secret, `POST /v1/apps/bifrost/identity-moves`
moves logins from one Heimdall account to another when it presents fresh proofs
of both: Bifrost's merge saga owns survivor choice, preview and undo timing;
Heimdall moves what the proofs cover. A proof through one login moves only that
login; an asserted `bifrost-passkey` proof covers the whole source account;
`bifrost-email-code` proves an inbox and does not. A multi-login source without a
passkey therefore needs one fresh sign-in per login. Until the Google client is
live, a member's strong proof is the asserted passkey only; Discord and Patreon
give weak (300 s) proofs. Contract, refusal order and idempotency are in
`docs/service-contract.md`.

View file

@ -20,7 +20,7 @@
> still reports `providers=2/6`, which counts it. > still reports `providers=2/6`, which counts it.
> >
> **Why it was removed anyway:** `/v1/oauth/spotify/start` is gated by > **Why it was removed anyway:** `/v1/oauth/spotify/start` is gated by
> `supportsProvider(profile, provider)`, so a provider with no app behind it is > `admitsProviderForMode(profile, provider, mode)`, so a provider with no app behind it is
> unreachable. While the profile existed, that path was publicly reachable and > unreachable. While the profile existed, that path was publicly reachable and
> would have run a real OAuth handshake against a real client secret, taking > would have run a real OAuth handshake against a real client secret, taking
> custody of a user's Spotify refresh token on behalf of a consumer that could > custody of a user's Spotify refresh token on behalf of a consumer that could
@ -38,7 +38,7 @@ Everything below this line is still accurate. To bring Spotiverse back:
**`http://127.0.0.1:8796/auth/heimdall/callback`**; that exact URL was the **`http://127.0.0.1:8796/auth/heimdall/callback`**; that exact URL was the
allowlisted value. allowlisted value.
3. Configure `GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID` and 3. Configure `GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID` and
`GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET` in the host service environment. `GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET_FILE` pointing at a credential file.
They were removed from `/srv/heimdall/env/service.env` on retirement, so a They were removed from `/srv/heimdall/env/service.env` on retirement, so a
fresh Spotify application registration may be needed. fresh Spotify application registration may be needed.
4. Restore the three tests from `5a15f71` if the capabilities they covered 4. Restore the three tests from `5a15f71` if the capabilities they covered
@ -80,13 +80,12 @@ Heimdall needs:
```text ```text
GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID=... GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID=...
GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET=... GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET_FILE=/absolute/path/to/spotify-client-secret
GC_ACCESS_APP_SPOTIVERSE_SHARED_SECRET=...
GC_ACCESS_APP_SPOTIVERSE_BACKEND_CALLBACK_URLS=https://your-spotiverse-portal.example/auth/heimdall/callback GC_ACCESS_APP_SPOTIVERSE_BACKEND_CALLBACK_URLS=https://your-spotiverse-portal.example/auth/heimdall/callback
``` ```
Spotiverse needs only the Heimdall base URL, matching app secret, and local Spotiverse needs only the Heimdall base URL and local portal callback/return
portal callback/return URLs. The callback URL Spotiverse sends in URLs. The callback URL Spotiverse sends in
`HEIMDALL_CALLBACK_URL` must exactly match one URL in Heimdall's `HEIMDALL_CALLBACK_URL` must exactly match one URL in Heimdall's
`GC_ACCESS_APP_SPOTIVERSE_BACKEND_CALLBACK_URLS` allowlist unless both services `GC_ACCESS_APP_SPOTIVERSE_BACKEND_CALLBACK_URLS` allowlist unless both services
are running on the same local host. are running on the same local host.

View file

@ -20,7 +20,11 @@ Corroborated by `gamecult-ops/nginx/streampixels.gamecult.org.conf:14`
The current StreamPixels architecture already makes useful splits: The current StreamPixels architecture already makes useful splits:
- the web app owns the remembered viewer session - the web app owns the remembered viewer session
- the service owns provider OAuth exchange and identity resolution - Heimdall owns provider OAuth exchange, identity resolution and refresh-token
custody for Twitch, YouTube and Joystick; StreamPixels never calls a provider
token endpoint and holds no provider refresh token. It asks Heimdall for a
short-lived access token (`managed-credentials/resolve`) and treats `410
managed_credential_revoked` as "the creator must reconnect"
- the overlay remains auth-free - the overlay remains auth-free
- creator memberships and operator roles are separate from general viewer state - creator memberships and operator roles are separate from general viewer state
@ -38,7 +42,7 @@ In the service-first Heimdall version, the most likely reusable slice is:
- provider OAuth authority - provider OAuth authority
- identity-linking authority - identity-linking authority
- managed Twitch/YouTube credential custody for creator connections - managed Twitch/YouTube/Joystick credential custody for creator connections (Joystick is a managed connection only, not a viewer sign-in provider: `startOAuthFlow` admits `sign_in` and `link` only for `identityProviders` and `connect` only for `managedConnectionProviders` or `identityProviders`, and refuses anything else before any redirect. The callback decides again from the signed state's mode: a `connect` for a managed-connection-only provider is admitted only with `connection.kind` `creator` and a `targetId`, refused otherwise at start and again at the callback before the code exchange; an admitted one stores the credential and mints a claim with no facts, no capabilities and no refresh token. Heimdall's claim is therefore never a viewer session. Heimdall cannot stop an app from minting its own viewer from a completion, so StreamPixels' redeem must treat a non-creator Joystick completion as an error, never as a sign-in. This is an S1 rule, recorded for SP)
- entitlement refresh - entitlement refresh
- shared claim semantics - shared claim semantics

View file

@ -154,7 +154,11 @@ The important split:
- Heimdall owns provider OAuth, identity linking, entitlement refresh, signed - Heimdall owns provider OAuth, identity linking, entitlement refresh, signed
sessions, claims, grants, audit surfaces, and managed provider credential sessions, claims, grants, audit surfaces, and managed provider credential
custody custody. It authenticates; it does not issue GameCult identity. Bifrost is
the identity provider, and the account id Heimdall mints is an authenticator
handle. Remaining scar: Heimdall still creates that account id on first
login (`store.createAccount`, `src/app.ts`), which the chat work does not
need moved
- the host experiment owns its workload, queue, editor, render path, viewer - the host experiment owns its workload, queue, editor, render path, viewer
profile model, creator model, or other product-specific machinery profile model, creator model, or other product-specific machinery
- the host experiment also owns which local entity a connection attaches to, - the host experiment also owns which local entity a connection attaches to,
@ -305,6 +309,201 @@ Important rule:
connection is tied to a user or account rather than a purely app-local secret connection is tied to a user or account rather than a purely app-local secret
- app-specific binding semantics and runtime behavior still stay app-owned - app-specific binding semantics and runtime behavior still stay app-owned
## Managed credential custody
Source-grounded as of branch `eureka/joystick-h1` at 6db84bf (PR
GameCult/Heimdall#1, unmerged). Nothing here is deployed.
### One owner: `refreshManagedCredential`
`src/managed-credential.ts` owns every decision to present a stored refresh
token to a provider. The entitlement path (`refreshAppSession`), the Bifrost
Patreon sync and `managed-credentials/resolve` all call it; none of them reads
`tokenExpiresAt` or a provider token endpoint itself. The earlier
`refreshLinkedIdentityCredentialIfNeeded` is deleted, and callers no longer
write refreshed tokens through `upsertLinkedIdentity`: a refresh reaches the row
only through the store port below. The only other writer of credential columns
is the OAuth callback's grant write (`app.ts`, once).
| | |
|---|---|
| Input | a `StoredLinkedIdentity` snapshot, the config, the token custody (AES-256-GCM seal), the provider runtimes, an injectable clock and timeout |
| Output | `{kind: "current" or "revoked", identity}`, or a thrown `ManagedCredentialRefreshFailed` (carries the provider and nothing the provider said) |
| Forbidden writers | any caller writing token columns or `token_expires_at` outside `updateLinkedIdentityCredential` and the callback's grant write; any caller computing "is a refresh due" |
The snapshot is a hint. It may answer without a lock when the identity holds no
access token (`revoked`) or no refresh is due (`current`; due means a known
expiry within 5 minutes, a stored refresh token, and a runtime that refreshes).
It never decides that a refresh happens.
### One writer for `linked_identities` moves
An identity belongs to the account that holds it. `upsertLinkedIdentity` writes
the holder's own row (`ON CONFLICT (provider, provider_user_id) DO UPDATE ...
WHERE linked_identities.account_id = EXCLUDED.account_id`; it never sets
`account_id`) and throws `IdentityHeldElsewhereError` when another account holds
the identity. `unlinkLinkedIdentity` is the only delete: one transaction locks
the account row, refuses the account's last identity, and deletes the row only
for the account that holds it. The store role therefore holds DELETE on
`linked_identities`, checked at startup. The HTTP side (`/v1/me/identities`) is
in `service-contract.md`; an unlink needs a step-up proof inside 600 seconds.
`moveIdentities` is the only statement that sets `linked_identities.account_id`
to another account, reached only through `POST /v1/apps/{app}/identity-moves`.
One transaction locks both accounts in id order (opposite moves queue, they do
not deadlock), answers a repeated `moveId` from its `identity_moves` row,
re-checks the proof sessions, applies `decideMove` (one pure function both stores
call, so memory and Postgres cannot disagree), moves the rows with credentials
stripped, revokes the source's sessions, expires its pending links and unredeemed
completions, and appends the row. `identity_moves` is append-only (SELECT and
INSERT only, checked at startup). An alias (an account with no login and an
unreversed move from it) is derived inside the transaction to refuse moves into
or out of it, never stored; nothing resolves an alias to its destination, because
no consumer needs it and a chain of moves would make one hop wrong.
### Step-up proof has two sources
An access token's `step_up_at` is set in exactly two places: the `sign_in`
step-up callback (Heimdall asked the provider to re-authenticate; label
`provider:<name>`) and `assertStepUp`, the app-asserted route (the app says it
checked a factor; label from the profile's `stepUpAssertion.methods`). Both
feed the one reader, `proofTier` in `claims.ts` (unlink and identity moves both
read it: `strong` is a step-up inside 600 s, `weak` a sign-in inside 300 s via
`auth_at`), and a refresh sets neither. `proofCovers` says what a proof speaks
for: only a strong proof whose method the profile lists as an account proof
covers the whole account; any other proof covers the one login in
`auth_identity_id`. The
asserted route trusts the calling app and is bounded by the app secret, a live
bearer for that app, the method allowlist, a nonce claimed once per session
through `claimOAuthStateUse` (phase `step_up_assert`, no new table or grant;
retained to the session expiry as of the claim, which a refresh may slide past),
and in-process fixed-window limits (`src/fixed-window.ts`).
### Three nested guards
1. **Single flight, per process.** `refreshesInFlight` is keyed by store, then
linked identity id. A caller arriving while an attempt is in flight joins it
and receives its outcome, success or failure, so nobody queues behind a
failed holder and re-presents the same token. The entry ends with the
attempt; a later request retries.
2. **Store-port lock, across processes.**
`HeimdallStore.updateLinkedIdentityCredential(id, decide)` runs `decide`
against the row as read under the lock. `PostgresStore` takes
`SELECT ... FOR UPDATE` inside a transaction; `InMemoryStore` serialises per
id on a promise chain that deletes its entry only when it is still the tail.
`decide` re-checks `dueForRefresh` on the locked row, so a process that
waited finds the token already rotated and returns `keep`. The provider call
is aborted at 10 seconds (`MANAGED_CREDENTIAL_REFRESH_TIMEOUT_MS`), which
bounds how long any waiter holds a pooled connection.
3. **Decision, not mutation.** `decide` returns a `CredentialDecision`: `keep`,
`revoke`, or `rotate` with the access token, refresh token and
`tokenExpiresAt` all required. The store applies it and returns the row. The
new pair is persisted before the access token is returned. A store that
keeps the old expiry on rotate is a type error, not a test.
### Typed answers
- **Revoked** (`410 managed_credential_revoked`, audit
`managed_credential_revoked {provider, reason}`, all three token columns
cleared). Two reasons only: `provider_revoked`, an HTTP 400 whose OAuth
`error` is exactly `invalid_grant`; and `rotation_missing`, a well-formed
refresh answer without a refresh token from a provider whose descriptor says
`rotatesRefreshTokens`. An identity with no access token is also `revoked`.
`404` means no linked identity exists. On the entitlement path a revoked
identity is skipped; on the Bifrost sync it is `404
patreon_identity_not_linked` with Bifrost uncalled.
- **Refresh failed** (`502 managed_credential_refresh_failed`, tokens
untouched, retry allowed): invalid client, a 401 or 5xx whatever its body,
timeout, a 2xx without a string `access_token` or carrying `error`, a
`refresh_token` present but not a string, an empty or non-JSON body.
`ProviderResponseError.oauthError` is drawn only from the closed RFC 6749 code
set and is read only from a 400; no provider body reaches a message, stack or
audit payload.
- An empty-string `refresh_token` counts as missing.
### Provider descriptor and the one token request
`providerCatalog` (`src/providers.ts`) is the only place a provider's token
behaviour is written down. Fields beyond the authorize side:
- `tokenEndpoint`: where both grants go.
- `tokenEndpointAuthMethod`: `client_secret_basic` or `client_secret_post`
(RFC 7591 names); exactly one client-auth method per request.
- `rotatesRefreshTokens`: true only for Joystick. Drives fail-closed on
refresh (`rotation_missing`) and a failed callback on exchange when the grant
carries no refresh token.
- `defaultAccessTokenLifetimeSeconds`: 3600 for all seven providers. Applied
when an answer has no usable `expires_in`; unusable means absent, non-numeric,
not a positive number or positive-integer string, or above 365 days. An
unknown expiry is therefore never stored, so every credential comes due.
`requestProviderTokens(provider, config, grant)` in `src/oauth.ts` replaces the
ten per-provider exchange and refresh functions. Authorization-code and refresh
grants share it, it returns an `ExpiringTokenSet` (`expiresAt` required), and it
rejects a malformed 2xx typed as `provider_body_not_token_set` on both grants.
The per-provider runtimes keep only identity resolution.
### Mode x role at the gates
`src/app-profiles.ts` holds both questions, and the profile's role lists are
their only input:
- `admitsProviderForMode(profile, provider, mode)`, the start gate: `sign_in`
and `link` take `identityProviders` only; `connect` takes
`managedConnectionProviders` or `identityProviders` (Bifrost connects its
identity providers). `supportsProvider` is deleted.
- `callbackMint(profile, provider, mode, connection)`, decided at the callback
from the signed state and asked again at start, so an unbound connect never
reaches a redirect:
- `viewer_session`: the provider is in `identityProviders`; a normal session
with the profile's capabilities.
- `custody_only`: a `connect` for a provider that is only a managed
connection (Joystick on StreamPixels) with `connection.kind = "creator"` and
a non-empty `targetId`.
- `refused`: everything else, before the code exchange.
A custody-only completion stores the credential and issues a claim with no
facts, no capabilities and no hybrid capabilities (`withoutCapabilities` in
`src/claims.ts`, the one owner of a capability-free claim). The completion
payload and the `backend_callback` handoff carry no `refreshToken` or
`refresh`, because the refresh route recomputes facts from the account and would
turn that session into a viewer session. A session row still exists, and
`BackendHandoffSuccessPayload` types both fields optional for this reason. The
consumer's redeem reads only account id, provider, mode, connection and claim
identities, so the claim form is unchanged for it.
### Verification layer
The rules above are pinned by `tests/managed-credential.test.ts` on three rigs
(memory, Postgres with one app, Postgres with two pools),
`tests/provider-token-request.test.ts`, `tests/app.test.ts` (a matrix over all
profiles x providers x modes, callback mint, handoff strip) and
`tests/recipe-secrets.test.ts`. Evidence is the Yggdrasil `ygg-verify` run on
Linux (node:24, postgres:16, `HEIMDALL_REQUIRE_LIVE_PG=1`; 600 passed, 8
skipped, none a live-Postgres suite), hand and StrykerJS mutants over the diff,
and Soul's pass 4 verdict `joystick:verdict:cut-h1.s4`. The deploy path's own
builder was not used.
### Open follow-ups
- `joystick:follow_up:cross-process-failed-refresh-marker`: single flight is per
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` (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
deploy.
- `joystick:follow_up:joystick-viewer-signin-public-bot`: Joystick stays out of
StreamPixels `identityProviders` until the public bot is registered; viewer
sign-in must not rewrite a creator's credential row.
## Policy model ## Policy model
The shared authority should not hard-code one app's access rules. It should The shared authority should not hard-code one app's access rules. It should
@ -460,8 +659,9 @@ Only the browser-driven OAuth flow:
| Path | Why it must be public | | Path | Why it must be public |
|---|---| |---|---|
| `/v1/oauth/{provider}/start` | the user's browser goes here | | `/v1/oauth/{provider}/start` | the app's server calls it, with its app secret where the profile requires one |
| `/v1/oauth/{provider}/callback` | the provider redirects here; one-shot and not retryable | | `/v1/oauth/{provider}/launch` | the user's browser goes here first; it sets the binding cookie and redirects to the provider, once per state |
| `/v1/oauth/{provider}/callback` | the provider redirects here; one-shot: it needs the binding cookie and consumes the state |
| `/.well-known/jwks.json` | *nothing external consumes it today* — see below | | `/.well-known/jwks.json` | *nothing external consumes it today* — see below |
Everything else is internal by the design already written down: Everything else is internal by the design already written down:
@ -514,24 +714,17 @@ each provider**. That URL cannot move on deploy.
### Finding: the `spotify` provider outlived its consumer ### Finding: the `spotify` provider outlived its consumer
`spotiverse` is the only profile naming `spotify`, and Spotiverse was lost with `spotiverse` was the only profile naming `spotify`, and Spotiverse was lost with
the `E:` drive — it was a small daemon exposing the Spotify API to agents, and the `E:` drive. The profile has since been removed from the registry
it no longer exists in the swarm. (`docs/app-profiles/spotiverse.md` is the restore spec), and
`admitsProviderForMode` refuses a provider no profile lists, so
`/v1/oauth/spotify/start` no longer reaches a handshake.
What survives it: `GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID` and What survives: the `spotify` catalog entry and runtime, and, wherever an
`GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET` are configured in operator env still holds them, `GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID` and
`/srv/heimdall/env/service.env`, the profile is advertised in the public `GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET_FILE`. A live credential kept for a
discovery document, and `/v1/oauth/spotify/start` is reachable from the open consumer that does not exist is the shape that becomes an incident later.
web. That path would run a real OAuth handshake against a real client secret and Retire the provider config, or record why Spotiverse is expected back.
take custody of a user's Spotify refresh token on behalf of a consumer that
cannot use it.
This is not an active compromise. It is a live credential and a token-custody
code path kept alive for nothing, which is exactly the shape that becomes an
incident later. Retire the profile and the provider config together, or record
why Spotiverse is expected back. Retiring is a change to `src/app-profiles.ts`
and the provider catalog and should be decided on its own, not folded into the
boundary change.
## Deployment modes ## Deployment modes
@ -572,47 +765,46 @@ every app's audience or product data.
## Configuration split ## Configuration split
Suggested generic env surface: Heimdall reads plain settings from its environment and every secret from a
file. A secret input `NAME` is configured as `NAME_FILE`, the absolute path of
a file holding only that value; under Idunn the binding binds it in
`[workload.secret_files]` to a `root:root 0400` credential. A blank file is
refused at startup, and so is setting both `NAME` and `NAME_FILE`.
Plain settings:
- `GC_ACCESS_ENABLED=1`
- `GC_ACCESS_BASE_URL=https://heimdall.gamecult.org` - `GC_ACCESS_BASE_URL=https://heimdall.gamecult.org`
- `GC_ACCESS_INTERNAL_URL=http://127.0.0.1:4100` - `GC_ACCESS_ISSUER=https://heimdall.gamecult.org`
- `GC_ACCESS_SESSION_SECRET=...` - `GC_ACCESS_STORAGE_BACKEND=postgres`
- `GC_ACCESS_SIGNING_PRIVATE_KEY_PEM=...` - `GC_ACCESS_SIGNING_PRIVATE_KEY_PATH=/etc/gamecult/heimdall/credentials/signing-key.pem`
- `GC_ACCESS_SIGNING_PRIVATE_KEY_PATH=/var/lib/heimdall/signing-key.pem`
- `GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP=1` - `GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP=1`
- `GC_ACCESS_SIGNING_KEY_ID=...` - `GC_ACCESS_SIGNING_KEY_ID=...`
- `GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64=...`
- `GC_ACCESS_SESSION_TTL_SECONDS=3600` - `GC_ACCESS_SESSION_TTL_SECONDS=3600`
- `GC_ACCESS_STATE_TTL_SECONDS=600` - `GC_ACCESS_STATE_TTL_SECONDS=600`
- `GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID=...` - `GC_ACCESS_PROVIDER_{DISCORD,PATREON,GITHUB,TWITCH,YOUTUBE,SPOTIFY,JOYSTICK}_CLIENT_ID=...`
- `GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET=...` - `GC_ACCESS_APP_{APP_SLUG}_BACKEND_CALLBACK_URLS=...`
- `GC_ACCESS_PROVIDER_DISCORD_BOT_TOKEN=...`
- `GC_ACCESS_PROVIDER_PATREON_CLIENT_ID=...` Secret files:
- `GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET=...`
- `GC_ACCESS_PROVIDER_PATREON_CAMPAIGN_ID=...` - `GC_ACCESS_DATABASE_URL_FILE=/etc/gamecult/heimdall/credentials/GC_ACCESS_DATABASE_URL`
- `GC_ACCESS_PROVIDER_GITHUB_CLIENT_ID=...` - `GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE=...`
- `GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET=...` - `GC_ACCESS_PROVIDER_{DISCORD,PATREON,GITHUB,TWITCH,YOUTUBE,SPOTIFY,JOYSTICK}_CLIENT_SECRET_FILE=...`
- `GC_ACCESS_PROVIDER_TWITCH_CLIENT_ID=...` - `GC_ACCESS_APP_{APP_SLUG}_SHARED_SECRET_FILE=...`
- `GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET=...` - `GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE=...`
- `GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID=...`
- `GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET=...` `src/config.ts` is the complete list; `deployment/idunn/recipe.toml` declares
- `GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID=...` the subset an Idunn binding may set.
- `GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET=...`
- `GC_ACCESS_ENTITLEMENT_CACHE_TTL_SECONDS=900`
- `GC_ACCESS_PROVIDER_FAILURE_GRACE_SECONDS=3600`
Only configure the providers Heimdall actually owns for a given deployment. Only configure the providers Heimdall actually owns for a given deployment.
If `GC_ACCESS_SIGNING_PRIVATE_KEY_PEM` is absent, the current skeleton falls The signing key is always a file: `GC_ACCESS_SIGNING_PRIVATE_KEY_PATH` names
back to `GC_ACCESS_SIGNING_PRIVATE_KEY_PATH` if present, and can bootstrap that it, and Heimdall can bootstrap that file on first boot when
file on first boot when `GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP=1`. If `GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP=1`. If no path is configured, the current skeleton falls back to an
neither PEM nor path is configured, the current skeleton falls back to an
ephemeral dev signing key. That is acceptable for local iteration and ephemeral dev signing key. That is acceptable for local iteration and
absolutely not acceptable for real deployment. absolutely not acceptable for real deployment.
Managed provider tokens should be sealed at rest with a stable Managed provider tokens should be sealed at rest with a stable
`GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64` secret. The current runtime will still `GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE` secret. The current runtime will still
mint an ephemeral dev token key for in-memory local work, but persistent mint an ephemeral dev token key for in-memory local work, but persistent
Postgres deployments should treat a missing token-encryption key as a hard Postgres deployments should treat a missing token-encryption key as a hard
misconfiguration, not a vibe. misconfiguration, not a vibe.

View file

@ -44,7 +44,7 @@ What exists right now is:
and managed creator connections and managed creator connections
- an app-authenticated managed-credential resolve endpoint so StreamPixels can - an app-authenticated managed-credential resolve endpoint so StreamPixels can
call provider APIs without storing refresh tokens locally call provider APIs without storing refresh tokens locally
- managed Twitch/YouTube credentials refresh inside Heimdall before resolution - managed Twitch/YouTube/Joystick credentials refresh inside Heimdall before resolution
when they are expired or near expiry when they are expired or near expiry
- StreamPixels now starts viewer and creator Twitch/YouTube OAuth through - StreamPixels now starts viewer and creator Twitch/YouTube OAuth through
Heimdall, redeems one-time completion codes server-side, and keeps local Heimdall, redeems one-time completion codes server-side, and keeps local
@ -215,7 +215,7 @@ Landed in the first pass:
Still to do in this phase: Still to do in this phase:
- key rotation policy instead of just stable key loading - key rotation policy instead of just stable key loading
- token custody retrieval/refresh surfaces beyond initial storage - token custody retrieval and refresh have landed (see `docs/architecture.md`, Managed credential custody); the open pieces are the follow-ups listed there
### Phase 2: Heimdall service skeleton ### Phase 2: Heimdall service skeleton

View file

@ -0,0 +1,237 @@
# Joystick sign-in and consent: what was missing, and the flow that fills it
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
**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. The consent flow
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
`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 ask's own
cookie (`__Host-heimdall-ask-<jti>`), 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
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
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 `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), `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, 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
Signed in means a live Heimdall access token for any app (`Authorization:
Bearer`), or a page link minted from one.
- `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. 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
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`.
Heimdall can delete its copy; it cannot withdraw the permission at the
provider, and the page says so.
## 4. The steward's rulings
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. 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. 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
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.
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.
### 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
`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.

View file

@ -44,12 +44,11 @@ Purpose:
Notes: Notes:
- current skeleton signs with Ed25519 - current skeleton signs with Ed25519
- `GC_ACCESS_SIGNING_PRIVATE_KEY_PEM` still works for direct secret injection
- `GC_ACCESS_SIGNING_PRIVATE_KEY_PATH` lets the service load a persisted key - `GC_ACCESS_SIGNING_PRIVATE_KEY_PATH` lets the service load a persisted key
from disk from disk
- if the path is missing and `GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP=1`, the - if the path is missing and `GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP=1`, the
service bootstraps a new key file on first start service bootstraps a new key file on first start
- if neither PEM nor path is configured, the service still generates an - if no path is configured, the service still generates an
ephemeral dev key at startup and deserves no sympathy when the `kid` changes ephemeral dev key at startup and deserves no sympathy when the `kid` changes
### `GET /.well-known/heimdall-configuration` ### `GET /.well-known/heimdall-configuration`
@ -119,6 +118,8 @@ Supported providers in the skeleton:
- `twitch` - `twitch`
- `youtube` - `youtube`
- `spotify` - `spotify`
- `joystick`
- `google`
Request body: Request body:
@ -149,12 +150,29 @@ Response:
"appSlug": "repixelizer", "appSlug": "repixelizer",
"mode": "sign_in", "mode": "sign_in",
"callbackUrl": "https://heimdall.gamecult.org/v1/oauth/discord/callback", "callbackUrl": "https://heimdall.gamecult.org/v1/oauth/discord/callback",
"authorizationUrl": "https://discord.com/oauth2/authorize?...", "authorizationUrl": "https://heimdall.gamecult.org/v1/oauth/discord/launch?state=<signed-jwt>",
"stateToken": "<signed-jwt>",
"stateExpiresAt": "2026-04-26T12:10:00.000Z" "stateExpiresAt": "2026-04-26T12:10:00.000Z"
} }
``` ```
Send the user's browser to `authorizationUrl` unchanged. It is Heimdall's launch
hop, not the provider's URL.
### `GET /v1/oauth/{provider}/launch?state=<signed-jwt>`
The first thing the user's browser does with a state. Heimdall verifies the
state (signature, issuer, provider, `nbf`/`exp` with 30 s of skew), claims the
state's single launch, sets the binding cookie
`__Host-heimdall-oauth-<jti>` (`Path=/`, `Secure`, `HttpOnly`, `SameSite=Lax`,
`Max-Age` until the state expires; the value is a Heimdall-signed binding for
that state) and answers `302` to the provider's authorize URL, with
`Cache-Control: no-store` and `Referrer-Policy: no-referrer`. A second launch of
the same state is `400 state_already_launched` and sets no cookie. The state is
refused with `400 invalid_state`, `state_provider_mismatch` or `state_expired`.
The binding cookie needs an `https` public base URL (or `localhost`). A browser
must finish the flow in the browser that launched it.
Failure modes: Failure modes:
- `503 provider_not_configured` when the provider client id is missing - `503 provider_not_configured` when the provider client id is missing
@ -168,17 +186,109 @@ Failure modes:
- `401 app_auth_required` when the request body carries `entitlementPolicy` and - `401 app_auth_required` when the request body carries `entitlementPolicy` and
the caller did not authenticate as that app via `x-heimdall-app-secret` the caller did not authenticate as that app via `x-heimdall-app-secret`
(`resolveAppCaller`, `src/app-caller.ts`) -- this applies regardless of (`resolveAppCaller`, `src/app-caller.ts`) -- this applies regardless of
`handoff.kind` or app slug; a caller with no policy to attach needs no secret `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
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
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
authority, so only the authenticated app named by `appSlug` may start it. No
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.
- 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".
Launch note: Launch note:
- Discord and Patreon are the implemented provider runtimes for Repixelizer - Discord and Patreon are the implemented provider runtimes for Repixelizer
- Twitch and YouTube now have generic OAuth exchange and identity runtimes for - Twitch, YouTube and Joystick have generic OAuth exchange and identity runtimes for
StreamPixels viewer auth and managed creator connections StreamPixels viewer auth and managed creator connections
- GitHub is still catalogued for start URLs, but its callback runtime is not - GitHub is still catalogued for start URLs, but its callback runtime is not
implemented yet implemented yet
- Repixelizer launch can configure Discord and Patreon on its provider buttons - Repixelizer launch can configure Discord and Patreon on its provider buttons
### Google (OpenID Connect, link-only; mints only under an invite grant)
`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
`https://heimdall.gamecult.org/v1/oauth/google/callback` in production.
- Scopes `openid email profile`. The authorization request carries `state`
(signed, Heimdall's), a `nonce`, and a PKCE `S256` challenge, all built at the
launch hop, which is where the browser first meets the provider URL. The verifier
and the nonce are derived from the state's `jti` and Heimdall's signing key,
so nothing is stored between start and callback.
- The callback verifies the `id_token` (RS256 against Google's published
keys; `iss` is Google, `aud` is this client, `exp`, `iat`, `nonce`) and
requires a `sub` and a verified email. The account key is `sub`; the email
is a display and contact field and never a lookup key.
- `mode: "link"` needs `Authorization: Bearer <Heimdall access token>` for the
same app; the identity attaches to that token's account and to no other.
`mode: "sign_in"` signs in an account the `sub` is already linked to.
- A `sub` no account holds, arriving with `sign_in` and no invite grant, is
refused and mints nothing. A `sub` linked to another account is refused and
never moved. Both audit as `oauth_callback_failed` with error class
`LinkRefusal` and the code `identity_not_linked` or `link_initiator_mismatch`.
- Invite grant. An app whose profile sets `mayGrantFirstLogin` (only `bifrost`)
may start `mode: "sign_in"` with `firstLoginGrant: "invite"`, saying it has
invited this person. The start must carry that app's own secret: any other
caller, including a public start, is `401 app_auth_required`. An app whose
profile may not grant, any other mode, or any other value is
`400 first_login_grant_refused`. The grant rides only in the signed state
(`first_login_grant`), so nothing a browser sends can set it, and the state
stays single-use. At the callback a `sub` no account holds, under a grant,
mints one account with that identity linked, and audits
`account_minted_by_grant` with `{ provider, appSlug }`. A `sub` an account
already holds signs in to that account exactly as without a grant; the grant
never attaches an identity to an existing account and never moves one.
`mode: "link"` takes no grant and is unchanged.
- 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
`POST /v1/apps/:appSlug/links/confirm` with `{ pendingLinkId }` and the
Heimdall access token of the account that began the link; only that call
attaches the identity. A different account, an expired, used or unknown id
answers 410; a `sub` another account holds by then answers 409. A refused
confirm does not consume the link.
- A sign-in callback evaluates every linked identity of the account with the
start-time entitlement policy, so a member returning through Google keeps
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.
### `GET /v1/oauth/{provider}/callback` ### `GET /v1/oauth/{provider}/callback`
Purpose: Purpose:
@ -189,7 +299,11 @@ Purpose:
Current status: Current status:
- validates signed `state` - validates signed `state` (signature, issuer, provider, expiry), requires the
binding cookie the launch hop set, and consumes the state: a second callback
is `400 state_already_used`, a missing or foreign cookie `400 state_not_bound`,
an expired state `400 state_expired`; the binding is checked before the claim,
so a browser without the cookie cannot burn the launching browser's state
- returns provider errors cleanly - returns provider errors cleanly
- for Discord, exchanges the authorization code, resolves the provider - for Discord, exchanges the authorization code, resolves the provider
identity, persists the local account/link/session/audit records, evaluates identity, persists the local account/link/session/audit records, evaluates
@ -334,6 +448,11 @@ Request body:
} }
``` ```
Binding rules:
- A completion minted for a connection target (`connection.targetId` in the signed state) is redeemed only with `targetId` equal to it; absent or different answers `403 completion_target_mismatch` and leaves the code unconsumed.
- A `link` completion is redeemed only by the authenticated app backend (`x-heimdall-app-secret`); otherwise `401 app_auth_required`, code unconsumed. `link` start itself needs that authentication and `initiatingAccountId`; the callback refuses with `403 link_initiator_mismatch` when the provider identity belongs to a different account, and attaches an unlinked identity to the initiator.
Response: Response:
```json ```json
@ -431,9 +550,11 @@ Important behavior:
- the refresh token is signed by Heimdall and scoped to one app session - the refresh token is signed by Heimdall and scoped to one app session
- the access token remains short-lived; app backends still verify it locally - the access token remains short-lived; app backends still verify it locally
- if a stored provider access token is expired or near expiry, Heimdall uses - if a stored provider access token is expired or near expiry, Heimdall takes
the stored provider refresh token and persists any rotation before a row lock on the linked identity, re-reads it, uses the stored provider
evaluating entitlements refresh token and persists any rotation before evaluating entitlements; an
identity whose grant the provider has revoked (no stored access token)
contributes no entitlement
- any app authenticated via `x-heimdall-app-secret` (`resolveAppCaller`) may - any app authenticated via `x-heimdall-app-secret` (`resolveAppCaller`) may
send `entitlementPolicies`; Heimdall matches each stored identity to the send `entitlementPolicies`; Heimdall matches each stored identity to the
policy for that provider. Sending policy without authenticating is policy for that provider. Sending policy without authenticating is
@ -441,6 +562,256 @@ Important behavior:
- the endpoint is not a provider OAuth start path and should not produce a - the endpoint is not a provider OAuth start path and should not produce a
provider authorization URL provider authorization URL
### `GET /v1/me/identities`
The identities the signed-in account holds, for a member's own view.
Authentication: a live Heimdall access token for any app as
`Authorization: Bearer` (the same check as `/v1/me/grants`). `401
sign_in_required` otherwise. The answer is `Cache-Control: no-store`.
```json
{
"accountId": "uuid",
"identities": [
{
"id": "uuid",
"provider": "twitch",
"providerUserId": "12345",
"username": "name",
"displayName": "Name",
"linkedAt": "2026-11-13T12:00:00.000Z",
"scopes": ["user:read:email"]
}
]
}
```
`username` and `displayName` are present when the provider gave them. The
answer never carries a token column, the stored provider profile or the
account's email.
### `POST /v1/me/identities/{identityId}/unlink`
Takes one identity off the signed-in account. It is the only way a linked
identity is deleted, and it never takes the account's last one.
Authentication: a live Heimdall access token for any app, and fresh proof. The
body is empty or `null`.
- `401 sign_in_required`: no live bearer.
- `403 step_up_required`: the access token carries no `step_up_at` claim, or it
is in the future, or it is older than 600 seconds
(`STEP_UP_PROOF_TTL_SECONDS`, `src/claims.ts`). The remedy is a `sign_in`
start with `stepUp: true` (see step-up above) through an identity on the
account whose provider has re-authentication parameters, today twitch,
youtube and google, then the access token that sign-in returns.
- `404 identity_not_found`: no such identity, or one that belongs to another
account. The two are not distinguishable.
- `409 last_identity`: the account holds no other identity.
- `200`: `{"unlinked": {"id", "provider", "providerUserId"}, "identities": [...]}`
with the remaining list in the shape above.
`step_up_at` (epoch seconds) is set on the access claim only when the callback's
signed state has `step_up` true and mode `sign_in`, or by an app's `POST
/v1/apps/{appSlug}/step-up` assertion (below). A refresh never carries it:
tokens a refresh issues cannot unlink, so proof is renewed only by a new step-up
sign-in. The unlink writes the audit event `identity_unlinked` (provider and
identity id only). When the account then holds no identity of that provider, the
revocation receipts for its live grants of that provider are written, as the
grants revoke route writes them.
A Twitch step-up proof is weaker than YouTube's or Google's: `force_verify` does
not force credential re-entry (see the step-up note under the OAuth start
section, "The strengths differ").
Limits that stay:
- Access tokens issued before the unlink keep the unlinked identity in their
`identities` claim and its facts until they expire (`sessionTtlSeconds`).
- Discord and Patreon identities cannot give proof (no re-authentication
parameter); an account holding only those cannot unlink.
- A stolen access token minted by a step-up sign-in can unlink more than one
identity during its 600 second window.
- A sign-in through a provider whose identity is no longer linked mints a new
account.
A link no longer moves an identity: `upsertLinkedIdentity` refuses an identity
another account holds (`links/confirm` answers `409 identity_linked_elsewhere`,
the callback `link_initiator_mismatch`). An unlinked identity belongs to no
account and can be linked by any account through the normal link flow.
### `POST /v1/apps/{appSlug}/step-up`
An app asserts that a member just passed a factor the app itself checked (for
Bifrost: a passkey assertion or an emailed code), and receives an access token
that carries that proof. The unlink route's step-up check then passes unchanged.
Authentication: both, always.
- the app's secret in `x-heimdall-app-secret`, as for every app route; and
- the member's live Heimdall access token for the same app as
`Authorization: Bearer`.
Body (`additionalProperties` are dropped as on the sibling routes):
```json
{ "method": "bifrost-passkey", "nonce": "16 to 128 characters, fresh per assertion" }
```
Nonce: 16 to 128 characters of the base64url alphabet (`A-Za-z0-9_-`), so a
random token fits and spaces, controls and lone surrogates are a 400 schema
refusal. `method` is 1 to 64 characters and then must be in the profile's set.
Schema validation (body shape, `method` length, the nonce pattern and length,
the app slug) runs before the secret is checked and answers `400` with
Fastify's fixed schema error, the same for every caller whatever the secret and
never audited. Then the order of refusals, each a closed `error` code:
- `401 app_auth_required`: missing, wrong or another app's secret. The first
check of the handler; nothing is written.
- `403 step_up_assertion_not_permitted`: the app's profile has no
`stepUpAssertion` grant. Only `bifrost` has one; every other app is refused
with its own secret. This branch has its own small budget (5 per 60 s per
app); past it the answer is 429.
- `429 step_up_rate_limited` (`retryAfterSeconds`): the per-app budget (120 per
60 s, spent by every attempt that passed the secret and the grant, including
ones whose bearer then fails) is spent. In-process fixed windows: they reset
when the process restarts and are not shared between instances.
- `401 sign_in_required`: the bearer is missing, malformed, expired, signed by
another key, a refresh token, or rests on a session that is not live (no row,
wrong account, revoked or expired, revision moved). One answer for all of
them; it does not say whether an account exists.
- `403 bearer_app_mismatch`: a live bearer issued to another app. An app cannot
assert for a token issued to another app. It tells only a holder of the
secret and a valid bearer that the bearer is live and for another app, which
that holder already knows.
- `429 step_up_rate_limited`: the per-account budget (10 per 600 s) is spent.
It is checked after the bearer and its audience, before method and nonce.
- `400 unknown_step_up_method`: `method` is not in the profile's closed set
(`methods` in the answer lists it). Bifrost: `bifrost-passkey`,
`bifrost-email-code`. Provider labels (`provider:*`) cannot be asserted.
- `409 step_up_nonce_replayed`: that nonce was already spent for this session.
The claim is the store's `oauth_state_uses` single-use primitive with phase
`step_up_assert` and the key a SHA-256 of session id and nonce, so it holds
across restarts and instances. **Retention is the session's expiry as of the
claim plus 10.5 minutes (the 10 minute prune margin and 30 s clock skew), and
pruning is lazy: each successful claim deletes at most 50 expired rows.** A refresh slides the session's expiry
without bound, so a nonce can be pruned while its session is still live and
then be accepted again. Replaying it still needs the secret and a live
bearer, which is the power to assert with a fresh nonce; the nonce guards a
captured request, not a compromised app. A refused method or a rate-limited
attempt does not spend the nonce.
- `201`: `{"accessToken", "claimSet", "stepUp": {"at", "method", "validForSeconds"}}`,
`Cache-Control: no-store`.
What the minted token is: a copy of the bearer's claims with a new `jti`,
`iat` and `nbf`, `step_up_at` = now and `step_up_method` = the asserted method.
It keeps the bearer's `exp`, same `sid` and account. Facts, capabilities and
identities are the bearer's and are not recomputed, so the route adds proof and
no capability. It mints no refresh token and writes no session row: it cannot
extend a lifetime or a session. A later refresh carries neither claim. The proof
is good for the usual 600 seconds (`STEP_UP_PROOF_TTL_SECONDS`) and only until
the token's own `exp`.
Receipts: each assertion writes the audit event `step_up_asserted`, and each
refusal after the secret verified writes `step_up_assertion_refused`, except
that two kinds are not recorded row by row: a rate-limited refusal is recorded
once per window per budget (its first; the row's `budget` names `app`,
`account` or `notPermitted`), and an app without the grant once per window.
Every other refusal under budget still writes a row each, up to about 121 a
minute for a holder of the secret, and `audit_events` has no retention: that is
an open follow-up. Rows carry the
app, the account and session when the bearer resolved, `method` (null when it
was not in the allowlist), `outcome`, `code`, `budget` (rate-limit rows) and `nonceDigest`. Never the
secret, the bearer, the minted token or the nonce. A request without the secret,
or failing schema validation, writes nothing.
Precondition: the route is usable only once the app holds the member's Heimdall
bearer. Bifrost deliberately does not hold it today. Putting the bearer in a
cookie ticket would turn cookie theft into bearer theft and, with
`bifrost-passkey` or `bifrost-email-code`, into unlink power; whether and how
Bifrost keeps the bearer is its own decision and is not made here.
Unlink accepts any method today. A `bifrost-email-code` proof unlinks an
identity a Google re-authentication would have guarded. Identity moves
(below) are the first route to require a method for whole-account coverage;
unlink is unchanged.
What this does not prove: Heimdall cannot see the passkey or the code. It trusts
the calling app's word, exactly as it trusts `stepUpRequested` (asked, not
verified). The word is bounded by the app secret, a live member bearer for that
app, the profile's method allowlist, a single-use nonce, the proof window and
the rate limits. A compromised Bifrost can assert proofs only for members whose
live bearer it holds. `identity_unlinked` records the proof's `stepUpMethod`
(`provider:<name>`, 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: <destination>, 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` ### `POST /v1/apps/{appSlug}/managed-credentials/resolve`
Purpose: Purpose:
@ -452,8 +823,9 @@ Purpose:
Authentication: Authentication:
- requires `x-heimdall-app-secret` - requires `x-heimdall-app-secret`
- the configured secret comes from `GC_ACCESS_APP_{APP_SLUG}_SHARED_SECRET`, - the configured secret comes from the credential file named by
per app; there is no generic fallback secret shared across apps `GC_ACCESS_APP_{APP_SLUG}_SHARED_SECRET_FILE`, per app; there is no generic
fallback secret shared across apps
Request body: Request body:
@ -484,7 +856,58 @@ Important behavior:
- it returns access tokens only; refresh tokens remain in Heimdall custody - it returns access tokens only; refresh tokens remain in Heimdall custody
- when a stored managed credential is expired or within the refresh window, - when a stored managed credential is expired or within the refresh window,
Heimdall refreshes it before returning the access token and persists rotated Heimdall refreshes it before returning the access token and persists rotated
access/refresh tokens access/refresh tokens. The refresh runs under a row lock on the linked
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). 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 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, 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
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
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
- `410 {"error":"managed_credential_revoked","provider":...}`: the provider
rejected the grant (HTTP 400 whose OAuth `error` is exactly `invalid_grant`),
or the identity holds no access token.
The stored tokens are cleared and an audit event `managed_credential_revoked`
is written; the owner must reconnect. `404 managed_credential_not_found`
means no linked identity exists
- `502 {"error":"managed_credential_refresh_failed","provider":...}`: the
refresh failed for any reason that is not a grant verdict (invalid client,
a 401 or 5xx whatever its body says, timeout, a 2xx without a string
`access_token` or carrying an `error`, a `refresh_token` that is present but
not a string, an empty or non-JSON body). Stored tokens are untouched and a
later request may succeed. An empty-string `refresh_token` counts as missing,
so a rotating provider revokes (`rotation_missing`). A token answer without a
usable `expires_in` (absent, non-numeric, or not a positive number or
positive-integer string) stores the expiry as now plus the provider's default
access-token lifetime (3600 seconds), so an expiry is never unknown and the
credential always comes due for refresh
- app-local binding, diagnostics, subscription setup, and runtime behavior stay - app-local binding, diagnostics, subscription setup, and runtime behavior stay
app-owned app-owned
@ -524,6 +947,10 @@ Current claim payload fields:
- `typ` - `typ`
- `account_id` - `account_id`
- `access_revision` - `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:<name>` 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 - `display_name` optional
- `app.slug` - `app.slug`
- `app.profile_version` - `app.profile_version`

View file

@ -11,7 +11,8 @@ evidence only.
## Owner Map ## Owner Map
- Owner: Heimdall owns provider identity/linking, OAuth attempts, signed session and claim - Owner: Heimdall owns provider identity/linking (an authenticator handle, not
GameCult identity, which is Bifrost's), OAuth attempts, signed session and claim
issuance, entitlement refresh, managed provider token custody, grants, issuance, entitlement refresh, managed provider token custody, grants,
auth-completion handoffs, refresh sessions, and audit events. auth-completion handoffs, refresh sessions, and audit events.
- Inputs: provider OAuth callbacks, app profile requests, caller-supplied - Inputs: provider OAuth callbacks, app profile requests, caller-supplied

View file

@ -1,6 +1,6 @@
# Fresh Workspace Handoff # Fresh Workspace Handoff
This is the re-entry packet for `E:\Projects\Heimdall`. 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 It is intentionally short. Historical proof belongs in git history and the
distilled `state/evidence.jsonl` ledger; the shared architecture belongs in distilled `state/evidence.jsonl` ledger; the shared architecture belongs in
@ -12,8 +12,7 @@ distilled `state/evidence.jsonl` ledger; the shared architecture belongs in
From the repo root: From the repo root:
```powershell ```powershell
# This repo has no dedicated venv yet. Use any working Python 3.11+. python .\tools\heimdall_state.py status
E:\Projects\repixelizer\.venv\Scripts\python.exe .\tools\heimdall_state.py status
Get-Content '.\state\map.yaml' Get-Content '.\state\map.yaml'
Get-Content '.\notes\fresh-workspace-handoff.md' Get-Content '.\notes\fresh-workspace-handoff.md'
Get-Content '.\docs\architecture.md' Get-Content '.\docs\architecture.md'
@ -25,10 +24,25 @@ Get-Content '.\state\evidence.jsonl' -Tail 8
Do not trust this file for the exact live HEAD. Always check git. 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 ## Current Orientation
- Yggdrasil runs Heimdall Yggdrasil runs Heimdall `d51fa6b`, hand-deployed 2026-10-19 15:51Z;
`1086aee01169bf60e8a492b2740db1c6f3e8cabf` with CultLib 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` `5cefa0db0079a8e3ee22f29d7b9e6e5aa60912a9`
- Heimdall publishes four redacted access records to Odin under unique keys: - Heimdall publishes four redacted access records to Odin under unique keys:
`eve:provider:heimdall`, `heimdall:command-boundary`, `eve:provider:heimdall`, `heimdall:command-boundary`,
@ -148,8 +162,7 @@ Do not trust this file for the exact live HEAD. Always check git.
over `cultnet.transport.rudp.v0` when `GC_ACCESS_IDUNN_RUDP_HEALTH` is over `cultnet.transport.rudp.v0` when `GC_ACCESS_IDUNN_RUDP_HEALTH` is
configured; HTTP `/healthz`, JWKS, discovery, systemd, and nginx routing configured; HTTP `/healthz`, JWKS, discovery, systemd, and nginx routing
remain compatibility witnesses remain compatibility witnesses
- Yggdrasil now runs Heimdall commit - Since `1086aee` Heimdall persists its private
`1086aee01169bf60e8a492b2740db1c6f3e8cabf`. Heimdall persists its private
provider-health identity at `/srv/heimdall/keys/provider-health-identity.cc` provider-health identity at `/srv/heimdall/keys/provider-health-identity.cc`
and publishes canonical signed health independently of the slower Verse and publishes canonical signed health independently of the slower Verse
snapshot cadence. Idunn owns the exact root trust binding, authenticated snapshot cadence. Idunn owns the exact root trust binding, authenticated
@ -171,6 +184,8 @@ Do not trust this file for the exact live HEAD. Always check git.
## Next Real Move ## 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. Do not continue implementation automatically from a rehydrate-only request.
The Idunn/swarm health transport cut is live. Do not regress Heimdall to The Idunn/swarm health transport cut is live. Do not regress Heimdall to
@ -233,9 +248,10 @@ Bifrost needs browser verification after deployment:
- configure Heimdall with - configure Heimdall with
`GC_ACCESS_APP_BIFROST_BACKEND_CALLBACK_URLS=https://bifrost.gamecult.org/auth/heimdall/callback` `GC_ACCESS_APP_BIFROST_BACKEND_CALLBACK_URLS=https://bifrost.gamecult.org/auth/heimdall/callback`
- configure Heimdall with `GC_ACCESS_APP_BIFROST_SHARED_SECRET`, - configure Heimdall with `GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE`,
`GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT=https://bifrost.gamecult.org/heimdall/patron-support/events`, `GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT=https://bifrost.gamecult.org/heimdall/patron-support/events`,
and `GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET` and `GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE`, each naming a credential
file
- configure Bifrost with `Heimdall__DiscordGuildId`, - configure Bifrost with `Heimdall__DiscordGuildId`,
`Heimdall__DiscordAllowedRoleIds__0=<KTLST-role-id>`, and `Heimdall__DiscordAllowedRoleIds__0=<KTLST-role-id>`, and
`Heimdall__PatreonTierTitle=Inner Sanctum` `Heimdall__PatreonTierTitle=Inner Sanctum`

View file

@ -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`.

View file

@ -17,12 +17,13 @@
"bundle": "esbuild src/index.ts --bundle --platform=node --format=esm --target=node24 --outfile=dist/heimdall --external:pg-native --banner:js=\"#!/usr/bin/env node\nimport{createRequire}from'node:module';const require=createRequire(import.meta.url);\"" "bundle": "esbuild src/index.ts --bundle --platform=node --format=esm --target=node24 --outfile=dist/heimdall --external:pg-native --banner:js=\"#!/usr/bin/env node\nimport{createRequire}from'node:module';const require=createRequire(import.meta.url);\""
}, },
"dependencies": { "dependencies": {
"@fastify/cookie": "^11.1.3",
"@fastify/cors": "^11.2.0", "@fastify/cors": "^11.2.0",
"@msgpack/msgpack": "^3.1.3", "@msgpack/msgpack": "^3.1.3",
"@gamecult/cultcache-ts": "file:vendor/CultLib/packages/cultcache-ts", "@gamecult/cultcache-ts": "file:vendor/CultLib/packages/cultcache-ts",
"cultmesh-ts": "file:vendor/CultLib/packages/cultmesh-ts", "cultmesh-ts": "file:vendor/CultLib/packages/cultmesh-ts",
"cultnet-ts": "file:vendor/CultLib/packages/cultnet-ts", "cultnet-ts": "file:vendor/CultLib/packages/cultnet-ts",
"fastify": "^5.8.5", "fastify": "^5.12.6",
"pg": "^8.20.0", "pg": "^8.20.0",
"zod": "^3.25.76" "zod": "^3.25.76"
}, },

69
pnpm-lock.yaml generated
View file

@ -12,6 +12,9 @@ importers:
.: .:
dependencies: dependencies:
'@fastify/cookie':
specifier: ^11.1.3
version: 11.1.5
'@fastify/cors': '@fastify/cors':
specifier: ^11.2.0 specifier: ^11.2.0
version: 11.2.0 version: 11.2.0
@ -28,8 +31,8 @@ importers:
specifier: file:vendor/CultLib/packages/cultnet-ts specifier: file:vendor/CultLib/packages/cultnet-ts
version: file:vendor/CultLib/packages/cultnet-ts version: file:vendor/CultLib/packages/cultnet-ts
fastify: fastify:
specifier: ^5.8.5 specifier: ^5.12.6
version: 5.8.5 version: 5.12.7
pg: pg:
specifier: ^8.20.0 specifier: ^8.20.0
version: 8.20.0 version: 8.20.0
@ -229,6 +232,9 @@ packages:
'@fastify/ajv-compiler@4.0.5': '@fastify/ajv-compiler@4.0.5':
resolution: {integrity: sha512-KoWKW+MhvfTRWL4qrhUwAAZoaChluo0m0vbiJlGMt2GXvL4LVPQEjt8kSpHI3IBq5Rez8fg+XeH3cneztq+C7A==} resolution: {integrity: sha512-KoWKW+MhvfTRWL4qrhUwAAZoaChluo0m0vbiJlGMt2GXvL4LVPQEjt8kSpHI3IBq5Rez8fg+XeH3cneztq+C7A==}
'@fastify/cookie@11.1.5':
resolution: {integrity: sha512-hs7e0otf7n/lJMpt63EFdQb5/u8kO6DeexEtLPVTybSdItC6SwJ1O0vtTyWvKNR70LZcHLlsUr/y3jFpqtyWRA==}
'@fastify/cors@11.2.0': '@fastify/cors@11.2.0':
resolution: {integrity: sha512-LbLHBuSAdGdSFZYTLVA3+Ch2t+sA6nq3Ejc6XLAKiQ6ViS2qFnvicpj0htsx03FyYeLs04HfRNBsz/a8SvbcUw==} resolution: {integrity: sha512-LbLHBuSAdGdSFZYTLVA3+Ch2t+sA6nq3Ejc6XLAKiQ6ViS2qFnvicpj0htsx03FyYeLs04HfRNBsz/a8SvbcUw==}
@ -469,6 +475,10 @@ packages:
resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
engines: {node: '>=18'} engines: {node: '>=18'}
cookie@2.0.1:
resolution: {integrity: sha512-yuToqVvRrj6pfDXREyQAAv8SkAEk/8GS3jQRTiUMm66TVtBYmqQeoEjL2Lmq8Rpo6271vH76InTChTitEAm65w==}
engines: {node: '>=22'}
cultmesh-ts@file:vendor/CultLib/packages/cultmesh-ts: cultmesh-ts@file:vendor/CultLib/packages/cultmesh-ts:
resolution: {directory: vendor/CultLib/packages/cultmesh-ts, type: directory} resolution: {directory: vendor/CultLib/packages/cultmesh-ts, type: directory}
engines: {node: '>=18'} engines: {node: '>=18'}
@ -532,17 +542,26 @@ packages:
fast-json-stringify@6.3.0: fast-json-stringify@6.3.0:
resolution: {integrity: sha512-oRCntNDY/329HJPlmdNLIdogNtt6Vyjb1WuT01Soss3slIdyUp8kAcDU3saQTOquEK8KFVfwIIF7FebxUAu+yA==} resolution: {integrity: sha512-oRCntNDY/329HJPlmdNLIdogNtt6Vyjb1WuT01Soss3slIdyUp8kAcDU3saQTOquEK8KFVfwIIF7FebxUAu+yA==}
fast-json-stringify@7.1.3:
resolution: {integrity: sha512-5TDM1yOF/BDFOclKz2G6rs1RsIl5HXMCrg/npmdNIPNQCezshR5kIHjhwBNuMY67jhkTUAm9DguL8xkL/x0Wtw==}
fast-querystring@1.1.2: fast-querystring@1.1.2:
resolution: {integrity: sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==} resolution: {integrity: sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==}
fast-uri@3.1.0: fast-uri@3.1.0:
resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==} resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==}
fast-uri@4.2.3:
resolution: {integrity: sha512-I1PXwP5eAhlNlcdpjt9CgB59op2ZvZfxw+BkqGFVIUOgNpCVTcTqp3HhTX7brxj5vsip+nSY4nTvff+eIA76hg==}
fastify-plugin@5.1.0: fastify-plugin@5.1.0:
resolution: {integrity: sha512-FAIDA8eovSt5qcDgcBvDuX/v0Cjz0ohGhENZ/wpc3y+oZCY2afZ9Baqql3g/lC+OHRnciQol4ww7tuthOb9idw==} resolution: {integrity: sha512-FAIDA8eovSt5qcDgcBvDuX/v0Cjz0ohGhENZ/wpc3y+oZCY2afZ9Baqql3g/lC+OHRnciQol4ww7tuthOb9idw==}
fastify@5.8.5: fastify-plugin@6.0.1:
resolution: {integrity: sha512-Yqptv59pQzPgQUSIm87hMqHJmdkb1+GPxdE6vW6FRyVE9G86mt7rOghitiU4JHRaTyDUk9pfeKmDeu70lAwM4Q==} resolution: {integrity: sha512-4wW4RxSmvPXLrh5mgQEiu43qU3bw44N2ss4FTkTkQIbprUhE+/s43QX0j/ttcztdWK7PEkHqVthdc5GdEGDvjA==}
fastify@5.12.7:
resolution: {integrity: sha512-v4pEPsTRPuqlDIYiQFB+BHjVN4SdHX9u0ABk0ZDUKbbdY1vsNryUd1j4Z+jQEZajvYIVk047Kimva9/AJ79GYw==}
fastq@1.20.1: fastq@1.20.1:
resolution: {integrity: sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==} resolution: {integrity: sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==}
@ -556,8 +575,8 @@ packages:
picomatch: picomatch:
optional: true optional: true
find-my-way@9.5.0: find-my-way@9.10.0:
resolution: {integrity: sha512-VW2RfnmscZO5KgBY5XVyKREMW5nMZcxDy+buTOsL+zIPnBlbKm+00sgzoQzq1EVh4aALZLfKdwv6atBGcjvjrQ==} resolution: {integrity: sha512-eru+uCPQ2g+nLBkf84MHP/KyNNMar0BDy0j+i8Fb72GF9/YHBZ58q7FODUtfVV7XU9nfRUHXSmaM8NmZcIbZ4Q==}
engines: {node: '>=20'} engines: {node: '>=20'}
fsevents@2.3.3: fsevents@2.3.3:
@ -853,8 +872,8 @@ packages:
process-warning@4.0.1: process-warning@4.0.1:
resolution: {integrity: sha512-3c2LzQ3rY9d0hc1emcsHhfT9Jwz0cChib/QN89oME2R451w5fy3f0afAhERFZAwrbDU43wk12d0ORBpDVME50Q==} resolution: {integrity: sha512-3c2LzQ3rY9d0hc1emcsHhfT9Jwz0cChib/QN89oME2R451w5fy3f0afAhERFZAwrbDU43wk12d0ORBpDVME50Q==}
process-warning@5.0.0: process-warning@5.1.1:
resolution: {integrity: sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==} resolution: {integrity: sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==}
quick-format-unescaped@4.0.4: quick-format-unescaped@4.0.4:
resolution: {integrity: sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==} resolution: {integrity: sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==}
@ -1180,6 +1199,11 @@ snapshots:
ajv-formats: 3.0.1(ajv@8.20.0) ajv-formats: 3.0.1(ajv@8.20.0)
fast-uri: 3.1.0 fast-uri: 3.1.0
'@fastify/cookie@11.1.5':
dependencies:
cookie: 2.0.1
fastify-plugin: 6.0.1
'@fastify/cors@11.2.0': '@fastify/cors@11.2.0':
dependencies: dependencies:
fastify-plugin: 5.1.0 fastify-plugin: 5.1.0
@ -1387,6 +1411,8 @@ snapshots:
cookie@1.1.1: {} cookie@1.1.1: {}
cookie@2.0.1: {}
cultmesh-ts@file:vendor/CultLib/packages/cultmesh-ts: cultmesh-ts@file:vendor/CultLib/packages/cultmesh-ts:
dependencies: dependencies:
'@gamecult/cultcache-ts': file:vendor/CultLib/packages/cultcache-ts '@gamecult/cultcache-ts': file:vendor/CultLib/packages/cultcache-ts
@ -1475,15 +1501,28 @@ snapshots:
json-schema-ref-resolver: 3.0.0 json-schema-ref-resolver: 3.0.0
rfdc: 1.4.1 rfdc: 1.4.1
fast-json-stringify@7.1.3:
dependencies:
'@fastify/merge-json-schemas': 0.2.1
ajv: 8.20.0
ajv-formats: 3.0.1(ajv@8.20.0)
fast-uri: 4.2.3
json-schema-ref-resolver: 3.0.0
rfdc: 1.4.1
fast-querystring@1.1.2: fast-querystring@1.1.2:
dependencies: dependencies:
fast-decode-uri-component: 1.0.1 fast-decode-uri-component: 1.0.1
fast-uri@3.1.0: {} fast-uri@3.1.0: {}
fast-uri@4.2.3: {}
fastify-plugin@5.1.0: {} fastify-plugin@5.1.0: {}
fastify@5.8.5: fastify-plugin@6.0.1: {}
fastify@5.12.7:
dependencies: dependencies:
'@fastify/ajv-compiler': 4.0.5 '@fastify/ajv-compiler': 4.0.5
'@fastify/error': 4.2.0 '@fastify/error': 4.2.0
@ -1491,11 +1530,11 @@ snapshots:
'@fastify/proxy-addr': 5.1.0 '@fastify/proxy-addr': 5.1.0
abstract-logging: 2.0.1 abstract-logging: 2.0.1
avvio: 9.2.0 avvio: 9.2.0
fast-json-stringify: 6.3.0 fast-json-stringify: 7.1.3
find-my-way: 9.5.0 find-my-way: 9.10.0
light-my-request: 6.6.0 light-my-request: 6.6.0
pino: 10.3.1 pino: 10.3.1
process-warning: 5.0.0 process-warning: 5.1.1
rfdc: 1.4.1 rfdc: 1.4.1
secure-json-parse: 4.1.0 secure-json-parse: 4.1.0
semver: 7.7.4 semver: 7.7.4
@ -1509,7 +1548,7 @@ snapshots:
optionalDependencies: optionalDependencies:
picomatch: 4.0.4 picomatch: 4.0.4
find-my-way@9.5.0: find-my-way@9.10.0:
dependencies: dependencies:
fast-deep-equal: 3.1.3 fast-deep-equal: 3.1.3
fast-querystring: 1.1.2 fast-querystring: 1.1.2
@ -1733,7 +1772,7 @@ snapshots:
on-exit-leak-free: 2.1.2 on-exit-leak-free: 2.1.2
pino-abstract-transport: 3.0.0 pino-abstract-transport: 3.0.0
pino-std-serializers: 7.1.0 pino-std-serializers: 7.1.0
process-warning: 5.0.0 process-warning: 5.1.1
quick-format-unescaped: 4.0.4 quick-format-unescaped: 4.0.4
real-require: 0.2.0 real-require: 0.2.0
safe-stable-stringify: 2.5.0 safe-stable-stringify: 2.5.0
@ -1758,7 +1797,7 @@ snapshots:
process-warning@4.0.1: {} process-warning@4.0.1: {}
process-warning@5.0.0: {} process-warning@5.1.1: {}
quick-format-unescaped@4.0.4: {} quick-format-unescaped@4.0.4: {}

View file

@ -4,7 +4,7 @@
"type": "object", "type": "object",
"required": ["provider", "mode", "returnTo", "entitlementPolicy"], "required": ["provider", "mode", "returnTo", "entitlementPolicy"],
"properties": { "properties": {
"provider": { "enum": ["discord", "patreon", "github", "twitch", "youtube", "spotify"] }, "provider": { "enum": ["discord", "patreon", "github", "twitch", "youtube", "spotify", "joystick"] },
"mode": { "enum": ["sign_in", "link", "connect"] }, "mode": { "enum": ["sign_in", "link", "connect"] },
"returnTo": { "type": "string", "format": "uri" }, "returnTo": { "type": "string", "format": "uri" },
"entitlementPolicy": { "entitlementPolicy": {

28
scripts/test-live-pg.sh Executable file
View file

@ -0,0 +1,28 @@
#!/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
# 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 (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 || 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}"
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 "$@"

View file

@ -3,7 +3,7 @@ import {
type CapabilityDefinition, type CapabilityDefinition,
type CapabilityMode, type CapabilityMode,
} from "./capability-rules.js"; } from "./capability-rules.js";
import { type AppSlug, type LinkedIdentityInput, type OAuthEntitlementPolicy, type Provider } from "./contracts.js"; import { type AppSlug, type LinkedIdentityInput, type OAuthConnectionBinding, type OAuthEntitlementPolicy, type OAuthMode, type Provider } from "./contracts.js";
import { entitlementFacts, grantFacts, identityFacts } from "./facts.js"; import { entitlementFacts, grantFacts, identityFacts } from "./facts.js";
export type { CapabilityDefinition, CapabilityMode }; export type { CapabilityDefinition, CapabilityMode };
@ -45,6 +45,41 @@ export interface AppProfile {
* plane; absent for apps with no such requirement. * plane; absent for apps with no such requirement.
*/ */
requiredEntitlementPolicyKind?: OAuthEntitlementPolicy["kind"]; 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
* signed (not encrypted) state's return_to. If anyone could start a flow for
* this app, whoever learned a victim's nonce could mint a completion bound
* to it and sign the victim's browser in as themselves (login CSRF, finding
* known-nonce-login-csrf). So a start for this app is refused unless the
* caller is this app's authenticated caller: only the app can mint its own
* state. Absent for apps whose browser starts are public by design.
*/
startRequiresAppCaller?: boolean;
/**
* The app decides who is invited. Its authenticated sign_in start may carry
* `firstLoginGrant: "invite"`, which lets a provider that otherwise requires a
* link (Google) mint the account for an identity no account holds. The grant
* never attaches an identity to an existing account. Absent for every app that
* may not grant.
*/
mayGrantFirstLogin?: true;
/**
* The app may assert, with its secret and a member's live bearer, that the
* member just passed a factor the app itself checked (POST
* /v1/apps/{app}/step-up). Heimdall cannot see that factor and trusts the
* app, so the grant is explicit per app and closed per method: only these
* labels may be asserted, and they end up in the claim's step_up_method.
* Absent for every app that may not assert.
*/
stepUpAssertion?: { methods: readonly string[] };
/**
* The app may move linked identities between two accounts it holds proofs
* for (POST /v1/apps/{app}/identity-moves). `accountProofMethods` are the
* asserted step_up_method labels that prove a whole account rather than one
* login; each must be one of stepUpAssertion.methods. Absent: the app may not move.
*/
identityMoves?: { accountProofMethods: readonly string[] };
} }
/** The membership signal shared by every app that gates on GameCult membership. */ /** The membership signal shared by every app that gates on GameCult membership. */
@ -99,10 +134,10 @@ const repixelizerProfile: AppProfile = {
const streampixelsProfile: AppProfile = { const streampixelsProfile: AppProfile = {
slug: "streampixels", slug: "streampixels",
displayName: "StreamPixels", displayName: "StreamPixels",
profileVersion: "2026-04-26", profileVersion: "2026-10-19",
identityProviders: ["twitch", "youtube"], identityProviders: ["twitch", "youtube"],
entitlementSources: [], entitlementSources: [],
managedConnectionProviders: ["twitch", "youtube"], managedConnectionProviders: ["twitch", "youtube", "joystick"],
allowedReturnOrigins: ["https://streampixels.gamecult.org"], allowedReturnOrigins: ["https://streampixels.gamecult.org"],
capabilities: [ capabilities: [
{ {
@ -137,11 +172,16 @@ const streampixelsProfile: AppProfile = {
const bifrostProfile: AppProfile = { const bifrostProfile: AppProfile = {
slug: "bifrost", slug: "bifrost",
displayName: "Bifrost", displayName: "Bifrost",
profileVersion: "2026-06-08", profileVersion: "2026-11-04",
identityProviders: ["discord", "patreon"], identityProviders: ["discord", "patreon", "google"],
entitlementSources: ["discord", "patreon"], entitlementSources: ["discord", "patreon"],
managedConnectionProviders: [], managedConnectionProviders: [],
allowedReturnOrigins: ["https://bifrost.gamecult.org"], allowedReturnOrigins: ["https://bifrost.gamecult.org"],
startRequiresAppCaller: true,
mayGrantFirstLogin: true,
stepUpAssertion: { methods: ["bifrost-passkey", "bifrost-email-code"] },
// A passkey proves the account; an email code proves an inbox, which is one login's worth at most.
identityMoves: { accountProofMethods: ["bifrost-passkey"] },
capabilities: [ capabilities: [
{ {
key: "member_access", key: "member_access",
@ -222,12 +262,19 @@ export function serializeAppProfile(profile: AppProfile): Record<string, unknown
}; };
} }
export function supportsProvider(profile: AppProfile, provider: Provider): boolean { /**
return ( * Whether the profile admits this provider for this mode. The role lists
profile.identityProviders.includes(provider) || * decide: `sign_in` and `link` mint viewer identity, so they take only
profile.managedConnectionProviders.includes(provider) || * `identityProviders`; a provider that is only a managed connection (Joystick)
profile.entitlementSources.includes(provider) * can never sign anyone in or link. `connect` takes either list:
); * `managedConnectionProviders` for creator credentials, and
* `identityProviders` because Bifrost and its siblings already connect their
* identity providers. A provider in neither list is refused before any redirect.
*/
export function admitsProviderForMode(profile: AppProfile, provider: Provider, mode: OAuthMode): boolean {
return mode === "connect"
? profile.managedConnectionProviders.includes(provider) || profile.identityProviders.includes(provider)
: profile.identityProviders.includes(provider);
} }
/** /**
@ -243,3 +290,45 @@ export function isAllowedReturnOrigin(profile: AppProfile, returnTo: string): bo
return false; return false;
} }
} }
/**
* 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
* is only an early refusal). `viewer_session`: the provider is one of the
* profile's `identityProviders`, so the completion signs the account in with
* the profile's capabilities. `custody_only`: a `connect` for a provider that
* is only a managed connection (Joystick on StreamPixels), bound to a creator
* target, stores the creator credential and mints a claim with no capabilities
* and no refresh token. Without a creator binding it is `refused`, as is any
* other combination. The start gate asks this same question, so an unbound
* connect never reaches a redirect.
*/
export type CallbackMint = "viewer_session" | "custody_only" | "refused";
export function callbackMint(
profile: AppProfile,
provider: Provider,
mode: OAuthMode,
connection: OAuthConnectionBinding | null | undefined
): CallbackMint {
if (profile.identityProviders.includes(provider)) {
return "viewer_session";
}
return mode === "connect" &&
profile.managedConnectionProviders.includes(provider) &&
connection?.kind === "creator" &&
isUsableConnectionTarget(connection.targetId)
? "custody_only"
: "refused";
}

1894
src/app.ts

File diff suppressed because it is too large Load diff

View file

@ -19,11 +19,19 @@ interface BackendHandoffBase {
connection: OAuthConnectionBinding | null; connection: OAuthConnectionBinding | null;
} }
export interface BackendHandoffSuccessPayload extends BackendHandoffBase, IssuedAccessClaimResult { /** A custody-only completion (callbackMint) carries no refresh token. */
type RefreshFields = "refreshToken" | "refresh";
export interface BackendHandoffSuccessPayload
extends BackendHandoffBase,
Omit<IssuedAccessClaimResult, RefreshFields>,
Partial<Pick<IssuedAccessClaimResult, RefreshFields>> {
status: "success"; status: "success";
mode: OAuthMode; mode: OAuthMode;
account: AccountSummary; account: AccountSummary;
entitlements: EntitlementEvaluation; entitlements: EntitlementEvaluation;
/** The receipt of the consent a managed connection rests on. */
consentReceiptId?: string;
} }
export interface BackendHandoffErrorPayload extends BackendHandoffBase { export interface BackendHandoffErrorPayload extends BackendHandoffBase {
@ -31,9 +39,20 @@ export interface BackendHandoffErrorPayload extends BackendHandoffBase {
mode?: OAuthMode; mode?: OAuthMode;
error: string; error: string;
errorDescription?: string; errorDescription?: string;
/** Who said no, when `error` is consent_refused. */
by?: "viewer" | "provider";
} }
export type BackendHandoffPayload = BackendHandoffSuccessPayload | BackendHandoffErrorPayload; /** A verified link that waits for the initiating account's confirm: no session, no tokens. */
export interface BackendHandoffLinkPendingPayload extends BackendHandoffBase {
status: "link_pending";
mode: OAuthMode;
pendingLinkId: string;
expiresAt: string;
confirmEndpoint: string;
}
export type BackendHandoffPayload = BackendHandoffSuccessPayload | BackendHandoffErrorPayload | BackendHandoffLinkPendingPayload;
export async function deliverBackendHandoff(callbackUrl: string, payload: BackendHandoffPayload): Promise<void> { export async function deliverBackendHandoff(callbackUrl: string, payload: BackendHandoffPayload): Promise<void> {
const response = await fetch(callbackUrl, { const response = await fetch(callbackUrl, {
@ -44,10 +63,10 @@ export async function deliverBackendHandoff(callbackUrl: string, payload: Backen
body: JSON.stringify(payload), body: JSON.stringify(payload),
}); });
// The status alone: the app's answer body can quote the handoff, which
// carries tokens, and whatever catches this may record or print it.
if (!response.ok) { if (!response.ok) {
const body = await response.text(); await response.body?.cancel();
throw new Error( throw new Error(`Backend handoff delivery failed (status ${response.status}).`);
`Backend handoff delivery failed (status ${response.status}): ${body || "empty response"}`
);
} }
} }

View file

@ -12,7 +12,11 @@ export interface BrowserHandoffSuccess extends BrowserHandoffBase {
status: "success"; status: "success";
mode: OAuthMode; mode: OAuthMode;
completionCode?: string; completionCode?: string;
/** A verified link waiting for its initiator's confirm; carries no session. */
pendingLinkId?: string;
attemptId?: string; attemptId?: string;
/** The receipt of the consent a managed connection rests on. */
consentReceiptId?: string;
} }
export interface BrowserHandoffError extends BrowserHandoffBase { export interface BrowserHandoffError extends BrowserHandoffBase {
@ -20,6 +24,8 @@ export interface BrowserHandoffError extends BrowserHandoffBase {
error: string; error: string;
errorDescription?: string; errorDescription?: string;
attemptId?: string; attemptId?: string;
/** Who said no, when `error` is consent_refused. */
by?: "viewer" | "provider";
} }
export type BrowserHandoffPayload = BrowserHandoffSuccess | BrowserHandoffError; export type BrowserHandoffPayload = BrowserHandoffSuccess | BrowserHandoffError;
@ -45,17 +51,28 @@ function buildBrowserFallbackUrl(payload: BrowserHandoffPayload): string {
fragment.set("heimdall_attempt_id", payload.attemptId); 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) { if (payload.status === "success" && payload.completionCode) {
fragment.set("heimdall_completion_code", payload.completionCode); fragment.set("heimdall_completion_code", payload.completionCode);
} else if (payload.status === "success" && payload.pendingLinkId) {
fragment.set("heimdall_pending_link_id", payload.pendingLinkId);
} else { } else {
if (payload.status === "error") { if (payload.status === "error") {
fragment.set("heimdall_error", payload.error); fragment.set("heimdall_error", payload.error);
if (payload.by) {
fragment.set("heimdall_refused_by", payload.by);
}
if (payload.errorDescription) { if (payload.errorDescription) {
fragment.set("heimdall_error_description", payload.errorDescription); fragment.set("heimdall_error_description", payload.errorDescription);
} }
} }
} }
// URLSearchParams and the URL serializer percent-encode `"`, `<` and `>`,
// so the page can place this URL in an attribute as it is. Every other value
// in the page goes through serializeForScript; there is no template engine.
url.hash = fragment.toString(); url.hash = fragment.toString();
return url.toString(); return url.toString();
} }
@ -70,14 +87,19 @@ export function renderBrowserHandoffPage(payload: BrowserHandoffPayload): string
}); });
const scriptOrigin = serializeForScript(targetOrigin); const scriptOrigin = serializeForScript(targetOrigin);
const scriptFallbackUrl = serializeForScript(fallbackUrl); const scriptFallbackUrl = serializeForScript(fallbackUrl);
const scriptTitle = serializeForScript( const refused = payload.status === "error" && payload.error === "consent_refused";
payload.status === "success" ? "Authentication Complete" : "Authentication Failed" const pageTitle = refused ? "Not Connected" : payload.status === "success" ? "Authentication Complete" : "Authentication Failed";
); const scriptTitle = serializeForScript(pageTitle);
const scriptBody = serializeForScript( const scriptBody = serializeForScript(
payload.status === "success" refused
? payload.handoffKind === "backend_callback" ? "Nothing was connected and nothing was kept. You can return to the app."
? "The app backend has the auth result already. You can return to the app now." : payload.status === "success"
: "You can return to the app now." ? (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." : "The authentication flow failed. Return to the app to continue."
); );
@ -86,7 +108,7 @@ export function renderBrowserHandoffPage(payload: BrowserHandoffPayload): string
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>${payload.status === "success" ? "Authentication Complete" : "Authentication Failed"}</title> <title>${pageTitle}</title>
<style> <style>
:root { :root {
color-scheme: light dark; color-scheme: light dark;

View file

@ -11,6 +11,12 @@ import { identityFacts } from "./facts.js";
import { signJwt, type RuntimeKeyMaterial } from "./signing.js"; import { signJwt, type RuntimeKeyMaterial } from "./signing.js";
import { type CreateSessionInput, type HeimdallStore } from "./store/types.js"; import { type CreateSessionInput, type HeimdallStore } from "./store/types.js";
/** How long a step-up sign-in's proof stays good for an action that demands it (identity unlink). */
export const STEP_UP_PROOF_TTL_SECONDS = 600;
/** How long a plain sign-in's proof stays good for an action that accepts a weak proof (an identity move). */
export const AUTH_PROOF_TTL_SECONDS = 300;
function nowEpochSeconds(): number { function nowEpochSeconds(): number {
return Math.floor(Date.now() / 1000); return Math.floor(Date.now() / 1000);
} }
@ -39,9 +45,23 @@ export interface IssueAccessClaimInput {
displayName?: string; displayName?: string;
linkedIdentities: LinkedIdentityInput[]; linkedIdentities: LinkedIdentityInput[];
facts: string[]; facts: string[];
/**
* The claim names the account and its identities and carries no facts and
* no capabilities (a managed-credential connect for a provider that is not
* an identity provider). The facts are not even `identity.authenticated`.
*/
withoutCapabilities?: boolean;
sessionId?: string; sessionId?: string;
accessRevision?: number; accessRevision?: number;
ttlSeconds?: number; ttlSeconds?: number;
/** Epoch seconds of a step-up sign-in completing; only that callback sets it, a refresh never does. */
stepUpAt?: number;
/** Required with stepUpAt (`provider:<name>`); 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 { export interface IssuedAccessClaimResult {
@ -80,11 +100,15 @@ export async function issueAccessClaim(options: {
// would name an app no verifier can resolve a profile for. // would name an app no verifier can resolve a profile for.
throw new Error(`Cannot issue an access claim for unknown app '${options.input.appSlug}'.`); throw new Error(`Cannot issue an access claim for unknown app '${options.input.appSlug}'.`);
} }
const facts = normalizeFacts(options.input.accountId, options.input.linkedIdentities, options.input.facts); const withoutCapabilities = options.input.withoutCapabilities === true;
const factSet = new Set(facts); const facts = withoutCapabilities
? []
: normalizeFacts(options.input.accountId, options.input.linkedIdentities, options.input.facts);
// Every shared capability needs a non-empty anyOf (capability-rules), so an
// empty fact set yields no capabilities: facts are the one owner of that.
const sharedCapabilities = evaluateSharedCapabilities(profile, { const sharedCapabilities = evaluateSharedCapabilities(profile, {
accountId: options.input.accountId, accountId: options.input.accountId,
facts: factSet, facts: new Set(facts),
identities: options.input.linkedIdentities, identities: options.input.linkedIdentities,
}); });
@ -120,6 +144,18 @@ export async function issueAccessClaim(options: {
identities: options.input.linkedIdentities, identities: options.input.linkedIdentities,
}; };
if (options.input.stepUpAt !== undefined) {
claimSet.step_up_at = options.input.stepUpAt;
if (options.input.stepUpMethod !== undefined) {
claimSet.step_up_method = options.input.stepUpMethod;
}
}
if (options.input.authAt !== undefined && options.input.authIdentityId !== undefined) {
claimSet.auth_at = options.input.authAt;
claimSet.auth_identity_id = options.input.authIdentityId;
}
if (options.input.displayName) { if (options.input.displayName) {
claimSet.display_name = options.input.displayName; claimSet.display_name = options.input.displayName;
} }
@ -176,6 +212,67 @@ export async function issueAccessClaim(options: {
kid: options.keys.kid, kid: options.keys.kid,
}, },
sharedCapabilities, sharedCapabilities,
hybridCapabilities: profile.capabilities.filter((capability) => capability.mode === "hybrid"), hybridCapabilities: withoutCapabilities
? []
: 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<string, unknown>;
method: string;
}): { accessToken: string; claimSet: Record<string, unknown>; stepUpAt: number } {
const stepUpAt = nowEpochSeconds();
const claimSet = {
...options.bearerClaims,
jti: randomUUID(),
iat: stepUpAt,
nbf: stepUpAt,
step_up_at: stepUpAt,
step_up_method: options.method,
};
return { accessToken: signJwt(claimSet, options.keys), claimSet, stepUpAt };
}
/**
* How fresh a bearer's proof of the member is, from its claims alone:
* `strong` when a step-up (Heimdall's or the app's asserted one) happened in
* the last STEP_UP_PROOF_TTL_SECONDS, else `weak` when the sign-in did in the
* last AUTH_PROOF_TTL_SECONDS, else null. The one freshness rule: identity
* unlink and identity moves both read it.
*/
export function proofTier(claims: Record<string, unknown>, 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<string, unknown>,
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;
}

View file

@ -1,3 +1,4 @@
import { readFileSync } from "node:fs";
import path from "node:path"; import path from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { appSlugs, providers, type AppSlug, type Provider } from "./contracts.js"; import { appSlugs, providers, type AppSlug, type Provider } from "./contracts.js";
@ -35,7 +36,6 @@ export interface HeimdallConfig {
refreshTtlSeconds: number; refreshTtlSeconds: number;
stateTtlSeconds: number; stateTtlSeconds: number;
completionTtlSeconds: number; completionTtlSeconds: number;
signingPrivateKeyPem?: string;
signingPrivateKeyPath?: string; signingPrivateKeyPath?: string;
bootstrapSigningPrivateKeyOnMissing: boolean; bootstrapSigningPrivateKeyOnMissing: boolean;
signingKeyId?: string; signingKeyId?: string;
@ -121,11 +121,64 @@ function readIdunnCandidateBind(
return { host, port }; return { host, port };
} }
/**
* Read one secret input. Its value lives in a file named by `NAME_FILE`: under
* Idunn that is a systemd credential, so the value never enters a binding, a
* unit, a plan or the process environment. One trailing newline is stripped.
*
* LEGACY SHIM, deleted with the legacy EnvironmentFile unit (secret-files
* Cut 5): when `NAME_FILE` is absent, the plaintext `NAME` is read instead.
* Setting both is refused, so one input has one owner. Under Idunn the recipe
* declares only the `_FILE` names, so the plaintext form cannot be bound there.
*
* `NAME_FILE` must be an absolute path, and a value that is empty or only
* whitespace is refused: a blank secret is a misconfiguration, never "unset".
*
* Errors name only the variable and an error code. They never carry the path,
* a value or a file's contents: Idunn admits any string for a declared name, so
* a secret bound into a `_FILE` slot by mistake would otherwise be printed.
*/
export function readSecretInput(env: NodeJS.ProcessEnv, name: string): string | undefined {
const fileVariable = `${name}_FILE`;
const filePath = env[fileVariable];
const plaintext = env[name];
if (filePath !== undefined && plaintext !== undefined) {
throw new Error(`${name} and ${fileVariable} are both set; set only ${fileVariable}.`);
}
let value: string;
let source: string;
if (filePath === undefined) {
if (plaintext === undefined) {
return undefined;
}
value = plaintext;
source = name;
} else {
if (!path.isAbsolute(filePath)) {
throw new Error(`${fileVariable} is not an absolute path.`);
}
try {
value = readFileSync(filePath, "utf8").replace(/\r?\n$/, "");
} catch (error) {
const code = (error as NodeJS.ErrnoException).code ?? "read error";
throw new Error(`${fileVariable} could not be read (${code}).`);
}
source = fileVariable;
}
if (value.trim() === "") {
throw new Error(`${source} is empty.`);
}
return value;
}
function readProviderConfig(env: NodeJS.ProcessEnv, provider: Provider): ProviderClientConfig { function readProviderConfig(env: NodeJS.ProcessEnv, provider: Provider): ProviderClientConfig {
const prefix = `GC_ACCESS_PROVIDER_${provider.toUpperCase()}`; const prefix = `GC_ACCESS_PROVIDER_${provider.toUpperCase()}`;
const config: ProviderClientConfig = {}; const config: ProviderClientConfig = {};
const clientId = env[`${prefix}_CLIENT_ID`]; const clientId = env[`${prefix}_CLIENT_ID`];
const clientSecret = env[`${prefix}_CLIENT_SECRET`]; const clientSecret = readSecretInput(env, `${prefix}_CLIENT_SECRET`);
if (clientId) { if (clientId) {
config.clientId = clientId; config.clientId = clientId;
@ -201,8 +254,9 @@ export function loadConfig(
const issuer = trimTrailingSlash(env.GC_ACCESS_ISSUER ?? publicBaseUrl); const issuer = trimTrailingSlash(env.GC_ACCESS_ISSUER ?? publicBaseUrl);
const dataRoot = const dataRoot =
stateRootArgument ?? env.GC_ACCESS_DATA_ROOT ?? path.join(workspaceRoot, ".heimdall-data"); stateRootArgument ?? env.GC_ACCESS_DATA_ROOT ?? path.join(workspaceRoot, ".heimdall-data");
const databaseUrl = readSecretInput(env, "GC_ACCESS_DATABASE_URL");
const storageBackend = const storageBackend =
env.GC_ACCESS_STORAGE_BACKEND === "postgres" || env.GC_ACCESS_DATABASE_URL ? "postgres" : "memory"; env.GC_ACCESS_STORAGE_BACKEND === "postgres" || databaseUrl ? "postgres" : "memory";
const providersConfig = Object.fromEntries( const providersConfig = Object.fromEntries(
providers.map((provider) => [provider, readProviderConfig(env, provider)]) providers.map((provider) => [provider, readProviderConfig(env, provider)])
) as Record<Provider, ProviderClientConfig>; ) as Record<Provider, ProviderClientConfig>;
@ -210,7 +264,7 @@ export function loadConfig(
appSlugs appSlugs
.map((appSlug) => { .map((appSlug) => {
const envKey = `GC_ACCESS_APP_${appSlug.toUpperCase()}_SHARED_SECRET`; const envKey = `GC_ACCESS_APP_${appSlug.toUpperCase()}_SHARED_SECRET`;
return [appSlug, env[envKey]]; return [appSlug, readSecretInput(env, envKey)];
}) })
.filter(([, value]) => Boolean(value)) .filter(([, value]) => Boolean(value))
) as Partial<Record<AppSlug, string>>; ) as Partial<Record<AppSlug, string>>;
@ -278,33 +332,38 @@ export function loadConfig(
config.odinCultMeshUri = odinCultMeshUri; config.odinCultMeshUri = odinCultMeshUri;
} }
const signingPrivateKeyPem = env.GC_ACCESS_SIGNING_PRIVATE_KEY_PEM?.replace(/\\n/g, "\n"); // The signing key path follows the secret reader's rules: it must be
if (signingPrivateKeyPem) { // absolute, and no error repeats it. An operator moving off the deleted
config.signingPrivateKeyPem = signingPrivateKeyPem; // inline PEM input who binds the key text here would otherwise have the
} // private key printed back into the journal.
const signingPrivateKeyPath = env.GC_ACCESS_SIGNING_PRIVATE_KEY_PATH;
if (env.GC_ACCESS_SIGNING_PRIVATE_KEY_PATH) { if (signingPrivateKeyPath) {
config.signingPrivateKeyPath = env.GC_ACCESS_SIGNING_PRIVATE_KEY_PATH; if (!path.isAbsolute(signingPrivateKeyPath)) {
throw new Error("GC_ACCESS_SIGNING_PRIVATE_KEY_PATH is not an absolute path.");
}
config.signingPrivateKeyPath = signingPrivateKeyPath;
} }
if (env.GC_ACCESS_SIGNING_KEY_ID) { if (env.GC_ACCESS_SIGNING_KEY_ID) {
config.signingKeyId = env.GC_ACCESS_SIGNING_KEY_ID; config.signingKeyId = env.GC_ACCESS_SIGNING_KEY_ID;
} }
if (env.GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64) { const tokenEncryptionKeyBase64 = readSecretInput(env, "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64");
config.tokenEncryptionKeyBase64 = env.GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64; if (tokenEncryptionKeyBase64) {
config.tokenEncryptionKeyBase64 = tokenEncryptionKeyBase64;
} }
if (env.GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT) { if (env.GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT) {
config.bifrostPatronSupportEndpoint = env.GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT; config.bifrostPatronSupportEndpoint = env.GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT;
} }
if (env.GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET) { const bifrostPatronSupportSecret = readSecretInput(env, "GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET");
config.bifrostPatronSupportSecret = env.GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET; if (bifrostPatronSupportSecret) {
config.bifrostPatronSupportSecret = bifrostPatronSupportSecret;
} }
if (env.GC_ACCESS_DATABASE_URL) { if (databaseUrl) {
config.storage.databaseUrl = env.GC_ACCESS_DATABASE_URL; config.storage.databaseUrl = databaseUrl;
} }
return config; return config;

191
src/consent.ts Normal file
View file

@ -0,0 +1,191 @@
import { createHash } from "node:crypto";
import { type AppSlug, type Provider } from "./contracts.js";
import { getAppProfile } from "./app-profiles.js";
import { providerCatalog } from "./providers.js";
import { type StoredConsentReceipt } from "./store/index.js";
/**
* What Heimdall tells a person before it holds a provider credential for an
* app, and the page that lists what they agreed to. The wording is built from
* the facts the code holds (the app, the provider, the scopes sent), never
* from a promise the code does not keep. Any change to a line changes the
* digest every later receipt carries, so a reader can tell which wording a
* person saw.
*/
export interface ConsentAsk {
appSlug: AppSlug;
provider: Provider;
/** The scopes Heimdall will send the provider. */
scopes: readonly string[];
/** The origin the person returns to afterwards. */
returnOrigin: string;
}
export const GRANTS_PATH = "/v1/me/grants";
function appName(slug: AppSlug): string {
return getAppProfile(slug)?.displayName ?? slug;
}
/** The exact lines shown on the ask, apart from the two buttons. The digest is over these. */
export function consentLines(ask: ConsentAsk): string[] {
const app = appName(ask.appSlug);
const provider = providerCatalog[ask.provider].displayName;
return [
`${app} asks Heimdall to hold a connection to your ${provider} account.`,
`Heimdall will ask ${provider} for these permissions: ${ask.scopes.join(", ")}.`,
`Heimdall keeps an encrypted refresh token and access token for this connection until you take it back or ${provider} ends it.`,
`${app}'s server can ask Heimdall for a current access token and use it for those permissions. It never receives the refresh token.`,
`If you say no, nothing is kept.`,
`You can take this back at any time. Heimdall then deletes its copy of the tokens and stops handing out access tokens. The permission stays with ${provider} until you remove it in your ${provider} settings.`,
`Afterwards you are returned to ${ask.returnOrigin}.`,
];
}
/** The labels on the two buttons. They are wording the person agrees to, so they are part of the text. */
export function consentButtons(ask: ConsentAsk): { go: string; no: string } {
return { go: `Continue to ${providerCatalog[ask.provider].displayName}`, no: "No, return to the app" };
}
/**
* Everything the person reads before answering, as one text: the lines and the
* button labels. It is built once, when the ask is rendered, and that exact
* text travels with the flow to the receipt; nothing rebuilds it later.
*/
export function consentText(ask: ConsentAsk): string {
const { go, no } = consentButtons(ask);
return [...consentLines(ask), go, no].join("\n");
}
export function digestOfText(text: string): string {
return createHash("sha256").update(text, "utf8").digest("hex");
}
export function consentDigest(ask: ConsentAsk): string {
return digestOfText(consentText(ask));
}
export function escapeHtml(value: string): string {
return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
}
const pageStyle = `
:root { color-scheme: light dark; font-family: ui-sans-serif, system-ui, sans-serif; }
body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #11161d; color: #f4f7fb; }
main { width: min(38rem, calc(100vw - 2rem)); border-radius: 1rem; padding: 1.5rem; background: rgba(20, 27, 36, 0.96); box-shadow: 0 24px 60px rgba(0, 0, 0, 0.3); }
h1 { margin: 0 0 0.75rem; font-size: 1.35rem; }
p, li { line-height: 1.5; color: #d5dce6; }
ul { padding-left: 1.2rem; }
code { color: #d8eefe; }
button { font: inherit; font-weight: 600; border: 0; border-radius: 999px; padding: 0.75rem 1rem; margin: 0.25rem 0.5rem 0.25rem 0; cursor: pointer; }
button.go { color: #11161d; background: #d8eefe; }
button.no { color: #f4f7fb; background: #2c3745; }
section { border-top: 1px solid #2c3745; padding: 0.75rem 0; }
small { color: #9aacbe; }`;
function page(title: string, body: string): string {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escapeHtml(title)}</title>
<style>${pageStyle}
</style>
</head>
<body>
<main>
${body}
</main>
</body>
</html>`;
}
/** 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) =>
`<button class="${decision === "continue" ? "go" : "no"}" type="submit" name="decision" value="${decision}">${escapeHtml(label)}</button>`;
return page(
`${appName(ask.appSlug)} wants to connect ${provider}`,
` <h1>${escapeHtml(headline!)}</h1>
<ul>
${rest.map((line) => ` <li>${escapeHtml(line)}</li>`).join("\n")}
</ul>
<form method="post" action="/v1/oauth/${ask.provider}/consent">
<input type="hidden" name="state" value="${escapeHtml(state)}">
${form("continue", consentButtons(ask).go)}
${form("decline", consentButtons(ask).no)}
</form>`
);
}
export interface GrantView {
consentText: string;
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<string, StoredConsentReceipt & { kind: "revocation" }>();
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,
consentText: receipt.consentText,
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 <code>${escapeHtml(grant.id)}</code>; wording <code>${escapeHtml(grant.consentPageDigest.slice(0, 12))}</code>`;
if (grant.status === "revoked") {
return ` <section><strong>${header}</strong> <small>taken back ${escapeHtml(grant.revokedAt ?? "")}; receipt <code>${escapeHtml(grant.revocationReceiptId ?? "")}</code></small><br><small>${detail}</small></section>`;
}
return ` <section><strong>${header}</strong> <small>active</small><br><small>${detail}</small>
<form method="post" action="${GRANTS_PATH}/${escapeHtml(grant.id)}/revoke">
<input type="hidden" name="t" value="${escapeHtml(pageToken)}">
<button class="no" type="submit">Take this back</button>
</form></section>`;
})
.join("\n")
: ` <p>You have not connected anything through Heimdall.</p>`;
return page(
"Your connections",
` <h1>Your connections</h1>
${notice ? ` <p><strong>${escapeHtml(notice)}</strong></p>\n` : ""}${cards}
<p><small>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.</small></p>`
);
}

View file

@ -1,4 +1,4 @@
export const providers = ["discord", "patreon", "github", "twitch", "youtube", "spotify"] as const; export const providers = ["discord", "patreon", "github", "twitch", "youtube", "spotify", "joystick", "google"] as const;
export type Provider = (typeof providers)[number]; export type Provider = (typeof providers)[number];
@ -73,9 +73,19 @@ export interface OAuthStartRequest {
mode: OAuthMode; mode: OAuthMode;
returnTo: string; returnTo: string;
connection?: OAuthConnectionBinding; connection?: OAuthConnectionBinding;
/** Link mode only: the account the authenticated app says is linking. Carried in the signed state. */
initiatingAccountId?: string;
handoff?: OAuthHandoff; handoff?: OAuthHandoff;
requestedScopes?: string[]; requestedScopes?: string[];
entitlementPolicy?: OAuthEntitlementPolicy; entitlementPolicy?: OAuthEntitlementPolicy;
/** Sign_in only, app-authenticated: ask the provider for a real re-authentication. Off when absent. */
stepUp?: boolean;
/**
* Sign_in only, from an app whose profile may grant (`mayGrantFirstLogin`): the app has
* invited this person, so a provider that otherwise requires a link may mint the
* first account. Carried in the signed state; never read from a browser.
*/
firstLoginGrant?: "invite";
} }
export interface OAuthStatePayload { export interface OAuthStatePayload {
@ -92,8 +102,15 @@ export interface OAuthStatePayload {
mode: OAuthMode; mode: OAuthMode;
return_to: string; return_to: string;
connection: OAuthConnectionBinding | null; connection: OAuthConnectionBinding | null;
initiator_account_id: string | null;
handoff: OAuthHandoff | null; handoff: OAuthHandoff | null;
entitlement_policy: OAuthEntitlementPolicy | null; entitlement_policy: OAuthEntitlementPolicy | null;
/** The start's requestedScopes, carried so the launch hop can build the provider URL from the signed state alone. */
requested_scopes: string[] | null;
/** The start's step-up request. Signed, so the launch hop reads it here and nowhere else; null when not asked. */
step_up: true | null;
/** The start's first-login grant. Signed, so only the app's own start can set it; null when not granted. */
first_login_grant: "invite" | null;
} }
export interface LinkedIdentityInput { export interface LinkedIdentityInput {
@ -105,6 +122,8 @@ export interface LinkedIdentityInput {
export interface RedeemAuthCompletionRequest { export interface RedeemAuthCompletionRequest {
completionCode: string; completionCode: string;
/** Required when the completion was minted for a connection target; must equal it. */
targetId?: string;
} }
export type HeimdallAuthAttemptStatus = "pending" | "completed" | "denied" | "consumed" | "expired"; export type HeimdallAuthAttemptStatus = "pending" | "completed" | "denied" | "consumed" | "expired";
@ -142,6 +161,19 @@ export interface AccessClaimPayload {
typ: "heimdall_access"; typ: "heimdall_access";
account_id: string; account_id: string;
access_revision: number; 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:<name>` for a step-up
* sign-in Heimdall ran, or one of the calling app's allowlisted method
* labels when the app asserted it (POST /v1/apps/{app}/step-up). Present
* exactly when step_up_at is; never carried by a refresh.
*/
step_up_method?: string;
/** Epoch seconds of the sign-in this access token was minted by, with auth_identity_id; absent unless a sign_in callback minted it, and never carried by a refresh. */
auth_at?: number;
/** The linked_identities.id the sign-in came through; present exactly when auth_at is. It is the only record of which login proved the session, and it describes the sign-in, not an asserted factor. */
auth_identity_id?: string;
display_name?: string; display_name?: string;
app: { app: {
slug: AppSlug; slug: AppSlug;

View file

@ -12,15 +12,11 @@ export interface TokenCustody {
} }
function decodeConfiguredKey(base64Value: string): Buffer { function decodeConfiguredKey(base64Value: string): Buffer {
const normalized = base64Value.trim(); // readSecretInput refuses a blank key; a short one fails the length check.
if (!normalized) { const key = Buffer.from(base64Value.trim(), "base64");
throw new Error("GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64 is set but empty.");
}
const key = Buffer.from(normalized, "base64");
if (key.byteLength !== TOKEN_KEY_BYTES) { if (key.byteLength !== TOKEN_KEY_BYTES) {
throw new Error( throw new Error(
`GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64 must decode to exactly ${TOKEN_KEY_BYTES} bytes for AES-256-GCM.` `GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE must decode to exactly ${TOKEN_KEY_BYTES} bytes for AES-256-GCM.`
); );
} }
@ -51,7 +47,7 @@ export function createTokenCustody(config: HeimdallConfig): TokenCustody {
: (() => { : (() => {
if (config.storage.backend === "postgres") { if (config.storage.backend === "postgres") {
throw new Error( throw new Error(
"GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64 is required when Heimdall uses persistent postgres storage." "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE is required when Heimdall uses persistent postgres storage."
); );
} }

49
src/fixed-window.ts Normal file
View file

@ -0,0 +1,49 @@
// 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<string, { startedAt: number; used: number }>();
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);
}
}
}

228
src/google-oidc.ts Normal file
View file

@ -0,0 +1,228 @@
import { createHash, createPublicKey, sign, verify, type KeyObject } from "node:crypto";
/**
* Google sign-in as OpenID Connect: the id_token is the identity, and this
* file is the one place that decides whether to believe it. The subject
* (`sub`) is the account key; the email is a claim about the subject, never
* its key.
*/
export const GOOGLE_ISSUERS = ["https://accounts.google.com", "accounts.google.com"] as const;
export const GOOGLE_JWKS_URI = "https://www.googleapis.com/oauth2/v3/certs";
const CLOCK_LEEWAY_SECONDS = 60;
const DEFAULT_JWKS_TTL_SECONDS = 3600;
const MAX_JWKS_TTL_SECONDS = 24 * 3600;
/** An unknown `kid` refetches the key set at most this often. */
const MIN_JWKS_REFETCH_MS = 60_000;
export type GoogleIdTokenFailure =
| "malformed"
| "unsupported_algorithm"
| "unknown_key"
| "bad_signature"
| "bad_issuer"
| "bad_audience"
| "expired"
| "not_yet_valid"
| "bad_nonce"
| "missing_subject"
| "email_missing"
| "email_not_verified"
| "jwks_unavailable";
/** A refusal that names the rule that failed and quotes nothing from the token. */
export class GoogleIdTokenError extends Error {
readonly code: GoogleIdTokenFailure;
constructor(code: GoogleIdTokenFailure) {
super(`Google id_token refused (${code}).`);
this.name = "GoogleIdTokenError";
this.code = code;
}
}
export interface GoogleIdentityClaims {
sub: string;
email: string;
name?: string;
picture?: string;
hd?: string;
}
interface Jwk {
kid?: string;
kty?: string;
alg?: string;
n?: string;
e?: string;
}
let cachedKeys: { keys: Map<string, KeyObject>; expiresAt: number; fetchedAt: number } | null = null;
export function resetGoogleJwksCache(): void {
cachedKeys = null;
}
async function fetchGoogleKeys(now: number): Promise<{ keys: Map<string, KeyObject>; expiresAt: number; fetchedAt: number }> {
let response: Response;
try {
response = await fetch(GOOGLE_JWKS_URI, { headers: { Accept: "application/json" } });
} catch {
throw new GoogleIdTokenError("jwks_unavailable");
}
if (!response.ok) {
throw new GoogleIdTokenError("jwks_unavailable");
}
let body: { keys?: Jwk[] };
try {
body = (await response.json()) as { keys?: Jwk[] };
} catch {
throw new GoogleIdTokenError("jwks_unavailable");
}
const keys = new Map<string, KeyObject>();
for (const jwk of body.keys ?? []) {
if (jwk.kty !== "RSA" || !jwk.kid || (jwk.alg !== undefined && jwk.alg !== "RS256")) continue;
try {
keys.set(jwk.kid, createPublicKey({ key: jwk as never, format: "jwk" }));
} catch {
// A key Node cannot read verifies nothing; the others stand.
}
}
const maxAge = /max-age=(\d+)/.exec(response.headers.get("cache-control") ?? "");
const ttl = Math.min(maxAge ? Number(maxAge[1]) : DEFAULT_JWKS_TTL_SECONDS, MAX_JWKS_TTL_SECONDS);
return { keys, expiresAt: now + ttl * 1000, fetchedAt: now };
}
async function keyForKid(kid: string, now: number): Promise<KeyObject> {
if (cachedKeys && cachedKeys.expiresAt > now) {
const hit = cachedKeys.keys.get(kid);
if (hit) return hit;
// Unknown kid in a live cache: Google may have rotated. Refetch, but not on every bad token.
if (now - cachedKeys.fetchedAt < MIN_JWKS_REFETCH_MS) {
throw new GoogleIdTokenError("unknown_key");
}
}
cachedKeys = await fetchGoogleKeys(now);
const key = cachedKeys.keys.get(kid);
if (!key) throw new GoogleIdTokenError("unknown_key");
return key;
}
function decodeSegment(segment: string): Record<string, unknown> {
try {
const value = JSON.parse(Buffer.from(segment, "base64url").toString("utf8")) as unknown;
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
return value as Record<string, unknown>;
}
} catch {
// fallthrough
}
throw new GoogleIdTokenError("malformed");
}
/**
* Verifies a Google id_token for this client. Order is signature first, then
* claims, so no claim of an unauthenticated token decides anything. Refuses
* on: algorithm other than RS256, unknown key, bad signature, `iss` not
* Google, `aud` not this client (an array `aud` also needs `azp` to be this
* client), `exp` passed, `iat` or `nbf` in the future, `nonce` not the one
* this authorization request carried, no `sub`, no `email`, and an email
* Google has not verified.
*/
export async function verifyGoogleIdToken(
idToken: string,
expected: { clientId: string; nonce: string },
nowMs: number = Date.now()
): Promise<GoogleIdentityClaims> {
const parts = idToken.split(".");
if (parts.length !== 3 || parts.some((part) => part === "")) {
throw new GoogleIdTokenError("malformed");
}
const [encodedHeader, encodedPayload, encodedSignature] = parts as [string, string, string];
const header = decodeSegment(encodedHeader);
if (header.alg !== "RS256") {
throw new GoogleIdTokenError("unsupported_algorithm");
}
if (typeof header.kid !== "string" || header.kid === "") {
throw new GoogleIdTokenError("unknown_key");
}
const key = await keyForKid(header.kid, nowMs);
const signatureValid = verify(
"RSA-SHA256",
Buffer.from(`${encodedHeader}.${encodedPayload}`, "utf8"),
key,
Buffer.from(encodedSignature, "base64url")
);
if (!signatureValid) {
throw new GoogleIdTokenError("bad_signature");
}
const claims = decodeSegment(encodedPayload);
const nowSeconds = Math.floor(nowMs / 1000);
if (typeof claims.iss !== "string" || !(GOOGLE_ISSUERS as readonly string[]).includes(claims.iss)) {
throw new GoogleIdTokenError("bad_issuer");
}
const aud = claims.aud;
const audienceOk =
typeof aud === "string"
? aud === expected.clientId
: Array.isArray(aud) && aud.includes(expected.clientId) && claims.azp === expected.clientId;
if (!audienceOk) {
throw new GoogleIdTokenError("bad_audience");
}
if (typeof claims.exp !== "number" || claims.exp + CLOCK_LEEWAY_SECONDS <= nowSeconds) {
throw new GoogleIdTokenError("expired");
}
if (typeof claims.iat !== "number" || claims.iat - CLOCK_LEEWAY_SECONDS > nowSeconds) {
throw new GoogleIdTokenError("not_yet_valid");
}
if (claims.nbf !== undefined && (typeof claims.nbf !== "number" || claims.nbf - CLOCK_LEEWAY_SECONDS > nowSeconds)) {
throw new GoogleIdTokenError("not_yet_valid");
}
if (typeof claims.nonce !== "string" || claims.nonce !== expected.nonce) {
throw new GoogleIdTokenError("bad_nonce");
}
if (typeof claims.sub !== "string" || claims.sub === "" || claims.sub.length > 255) {
throw new GoogleIdTokenError("missing_subject");
}
if (typeof claims.email !== "string" || claims.email === "") {
throw new GoogleIdTokenError("email_missing");
}
if (claims.email_verified !== true && claims.email_verified !== "true") {
throw new GoogleIdTokenError("email_not_verified");
}
const identity: GoogleIdentityClaims = { sub: claims.sub, email: claims.email };
if (typeof claims.name === "string" && claims.name !== "") identity.name = claims.name;
if (typeof claims.picture === "string" && claims.picture !== "") identity.picture = claims.picture;
if (typeof claims.hd === "string" && claims.hd !== "") identity.hd = claims.hd;
return identity;
}
/**
* The PKCE verifier and the nonce of one authorization request, derived from
* the request's state `jti` and Heimdall's signing key instead of stored. The
* state token travels through the browser and carries the `jti`, so whoever
* can read the redirect can read the `jti`; they cannot compute an Ed25519
* signature over it. The signature is deterministic, so start and callback
* derive the same pair, and nothing is persisted between them.
*/
export function deriveOidcSecrets(stateJti: string, signingKey: KeyObject): {
codeVerifier: string;
codeChallenge: string;
nonce: string;
} {
const derive = (label: string): string =>
createHash("sha256")
.update(sign(null, Buffer.from(`heimdall:oidc:${label}:${stateJti}`, "utf8"), signingKey))
.digest("base64url");
const codeVerifier = derive("pkce-verifier");
return {
codeVerifier,
codeChallenge: createHash("sha256").update(codeVerifier, "ascii").digest("base64url"),
nonce: derive("nonce"),
};
}

View file

@ -1,4 +1,3 @@
import path from "node:path";
import { resolveWriteLease, WriteLeaseNotHeldError } from "./process-write-lease.js"; import { resolveWriteLease, WriteLeaseNotHeldError } from "./process-write-lease.js";
import { buildApp } from "./app.js"; import { buildApp } from "./app.js";
import { loadConfig } from "./config.js"; import { loadConfig } from "./config.js";
@ -7,14 +6,16 @@ import { publishHeimdallOdinState } from "./odin-publication.js";
import { startHeimdallPrivateCommandPlane } from "./private-command-plane.js"; import { startHeimdallPrivateCommandPlane } from "./private-command-plane.js";
import type { CultNetOperationServer } from "cultnet-ts"; import type { CultNetOperationServer } from "cultnet-ts";
import { createHeimdallRuntimePulse, buildHeimdallHealthDetail, publishHeimdallVerseState } from "./verse-state.js"; import { createHeimdallRuntimePulse, buildHeimdallHealthDetail, publishHeimdallVerseState } from "./verse-state.js";
import { import { openPresenceAuthority } from "./runtime-presence.js";
buildPresenceStatement,
nextPublisherSequence,
readRuntimeBundleFacts,
type RuntimeBundleFacts,
} from "./runtime-presence.js";
const config = loadConfig(); const config = loadConfig();
// Under Idunn the launch's presence keys, bundle facts and publisher sequence
// open here, before anything listens. A launch-contract fault throws, uncaught,
// and the process exits non-zero with no listener: Idunn fails Warming in
// seconds rather than waiting on a candidate that can never sign.
const presenceAuthority = config.idunnRuntimeBundlePath
? await openPresenceAuthority(config)
: undefined;
const app = await buildApp({ config }); const app = await buildApp({ config });
const versePulseIntervalMs = 60_000; const versePulseIntervalMs = 60_000;
const healthPulseIntervalMs = 10_000; const healthPulseIntervalMs = 10_000;
@ -70,13 +71,6 @@ async function publishVerseState(): Promise<void> {
await publishHeimdallOdinState(config, pulse); await publishHeimdallOdinState(config, pulse);
} }
/**
* Read once and keep: the bundle is Idunn's immutable record of this launch and
* cannot change while the process lives, so re-reading it every pulse would be
* work that can only ever return the same answer or fail.
*/
let runtimeBundleFacts: RuntimeBundleFacts | undefined;
async function publishHealthState(): Promise<void> { async function publishHealthState(): Promise<void> {
const pulse = createHeimdallRuntimePulse(config); const pulse = createHeimdallRuntimePulse(config);
@ -94,32 +88,17 @@ async function publishHealthState(): Promise<void> {
? buildHeimdallHealthDetail(config, pulse) ? buildHeimdallHealthDetail(config, pulse)
: `Heimdall candidate warming; ${lease.reason}`; : `Heimdall candidate warming; ${lease.reason}`;
if (!config.idunnRuntimeBundlePath) { if (!presenceAuthority) {
// Outside Idunn there is no launch to attest and nothing that admits the // Outside Idunn there is no launch to attest and nothing that admits the
// statement; publishing is simply not part of that world. // statement; publishing is simply not part of that world.
return; return;
} }
runtimeBundleFacts ??= await readRuntimeBundleFacts(config.idunnRuntimeBundlePath); const state = lease.mayWrite ? "active" : "warming";
const presence = presenceAuthority.sign(state, detail, Date.parse(pulse.updatedAt));
const observedAtUnixMillis = Date.parse(pulse.updatedAt);
const presence = await buildPresenceStatement({
bundle: runtimeBundleFacts,
state: lease.mayWrite ? "active" : "warming",
detail,
boundEndpoint: `http://${config.host}:${config.port}`,
// A warming candidate holds no lease and must not claim one; the contract
// refuses the pair, and Idunn needs the warming statement to promote it.
writeLeaseSha256: null,
observedAtUnixMillis,
publisherSequence: await nextPublisherSequence(
path.join(config.dataRoot, "runtime-presence-sequence"),
),
providerHealthIdentityPath: config.providerHealthIdentityPath,
});
await publishIdunnRudpHealth(config, { await publishIdunnRudpHealth(config, {
daemonId: config.daemonId, daemonId: config.daemonId,
state: lease.mayWrite ? "active" : "warming", state,
detail, detail,
observedAt: pulse.updatedAt, observedAt: pulse.updatedAt,
presence, presence,

219
src/managed-credential.ts Normal file
View file

@ -0,0 +1,219 @@
import { type HeimdallConfig } from "./config.js";
import { type Provider } from "./contracts.js";
import { type TokenCustody } from "./custody.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";
/** A stored access token this close to expiry (or past it) is refreshed before use. */
export const MANAGED_CREDENTIAL_REFRESH_SKEW_MS = 5 * 60 * 1000;
/**
* The longest a refresh may hold the row lock: the provider call is aborted
* at this bound, and every waiter holds a pooled connection for at most this
* long behind the holder.
*/
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;
tokenCustody: TokenCustody;
oauthRuntimes: OAuthRuntimeRegistry;
clock?: () => number;
timeoutMs?: number;
}
export type ManagedCredentialRevocationReason = "provider_revoked" | "rotation_missing";
/** `revoked` means the identity holds no access token: the provider took the grant back, or it was never held. */
export type ManagedCredentialOutcome =
| { kind: "current"; identity: StoredLinkedIdentity }
| { kind: "revoked"; identity: StoredLinkedIdentity };
/**
* The provider could not be asked, or answered with something that is not a
* grant verdict (invalid_client, 5xx, timeout, malformed body). The stored
* tokens are untouched. Carries the provider and nothing the provider said.
*/
export class ManagedCredentialRefreshFailed extends Error {
readonly code = "managed_credential_refresh_failed";
readonly provider: Provider;
constructor(provider: Provider) {
super(`${providerCatalog[provider].displayName} managed credential refresh failed.`);
this.name = "ManagedCredentialRefreshFailed";
this.provider = provider;
}
}
function dueForRefresh(identity: StoredLinkedIdentity, runtime: OAuthProviderRuntime, now: number): boolean {
if (!identity.tokenExpiresAt || !identity.refreshTokenEncrypted || !runtime.refreshAccessToken) {
return false;
}
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;
}
/**
* Refreshes in flight in this process, per store and linked identity. The row
* lock serialises processes; it cannot tell a waiter that queued behind a
* failed holder from a caller that arrived after the failure, so each waiter
* would present the same refresh token again. Callers that arrive while an
* 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.
*
* 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<HeimdallStore, Map<string, Promise<ManagedCredentialOutcome>>>();
/**
* The one refresh policy. `snapshot` is a hint: it may skip the lock when no
* refresh is due and never decides one. The row's lock owns when a refresh
* token is presented across processes; this process makes one attempt per
* identity at a time; the decision is made on the row as read under the lock.
*/
export async function refreshManagedCredential(
ctx: ManagedCredentialContext,
snapshot: StoredLinkedIdentity
): Promise<ManagedCredentialOutcome> {
const clock = ctx.clock ?? Date.now;
const runtime = ctx.oauthRuntimes[snapshot.provider];
if (!snapshot.accessTokenEncrypted) {
return { kind: "revoked", identity: snapshot };
}
if (!dueForRefresh(snapshot, runtime, clock())) {
return { kind: "current", identity: snapshot };
}
let inFlight = refreshesInFlight.get(ctx.store);
if (!inFlight) {
inFlight = new Map();
refreshesInFlight.set(ctx.store, inFlight);
}
const joined = inFlight.get(snapshot.id);
if (joined) {
return joined;
}
const attempt = refreshUnderLock(ctx, snapshot).finally(() => {
inFlight.delete(snapshot.id);
});
inFlight.set(snapshot.id, attempt);
return attempt;
}
async function refreshUnderLock(
ctx: ManagedCredentialContext,
snapshot: StoredLinkedIdentity
): Promise<ManagedCredentialOutcome> {
const clock = ctx.clock ?? Date.now;
const provider = snapshot.provider;
const runtime = ctx.oauthRuntimes[provider];
let revocation: ManagedCredentialRevocationReason | undefined;
let failed = false;
const rotation = (locked: StoredLinkedIdentity, refreshed: ExpiringTokenSet, updatedAt: string): CredentialDecision => {
let refreshTokenEncrypted: string;
if (refreshed.refreshToken) {
refreshTokenEncrypted = ctx.tokenCustody.encrypt(refreshed.refreshToken);
} else if (providerCatalog[provider].rotatesRefreshTokens) {
revocation = "rotation_missing";
return { kind: "revoke", updatedAt };
} else {
refreshTokenEncrypted = locked.refreshTokenEncrypted!;
}
// The refreshed set always carries an expiry (the provider's, or the
// descriptor's default lifetime): the old one is already due, and an
// unknown one would never come due (dueForRefresh).
return {
kind: "rotate",
accessTokenEncrypted: ctx.tokenCustody.encrypt(refreshed.accessToken),
refreshTokenEncrypted,
tokenExpiresAt: refreshed.expiresAt,
scopes: refreshed.scope.length ? refreshed.scope : locked.scopes,
updatedAt,
consumedRefreshToken: providerCatalog[provider].rotatesRefreshTokens,
};
};
const decide = async (locked: StoredLinkedIdentity): Promise<CredentialDecision> => {
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({
accountId: snapshot.accountId,
eventType: "managed_credential_revoked",
eventPayloadJson: { provider, reason: revocation },
createdAt: new Date(clock()).toISOString(),
});
}
if (failed) {
throw new ManagedCredentialRefreshFailed(provider);
}
if (!committed) {
return { kind: "revoked", identity: withoutTokens(snapshot) };
}
return { kind: committed.accessTokenEncrypted ? "current" : "revoked", identity: committed };
}

View file

@ -7,6 +7,8 @@ import {
} from "./contracts.js"; } from "./contracts.js";
import { type HeimdallConfig } from "./config.js"; import { type HeimdallConfig } from "./config.js";
import { entitlementFacts } from "./facts.js"; import { entitlementFacts } from "./facts.js";
import { verifyGoogleIdToken } from "./google-oidc.js";
import { providerCatalog } from "./providers.js";
import { type CreateEntitlementSnapshotInput } from "./store/types.js"; import { type CreateEntitlementSnapshotInput } from "./store/types.js";
export interface OAuthTokenSet { export interface OAuthTokenSet {
@ -40,17 +42,30 @@ export interface OAuthCallbackContext {
entitlementPolicy: OAuthEntitlementPolicy | null; entitlementPolicy: OAuthEntitlementPolicy | null;
} }
/** A token set whose access-token expiry is known: the provider's own, or the descriptor's default. */
export type ExpiringTokenSet = OAuthTokenSet & { expiresAt: string };
export interface OAuthProviderRuntime { export interface OAuthProviderRuntime {
exchangeAuthorizationCode(options: { exchangeAuthorizationCode(options: {
config: HeimdallConfig; config: HeimdallConfig;
code: string; code: string;
redirectUri: string; redirectUri: string;
/** PKCE verifier of an OIDC provider's request (RFC 7636). */
codeVerifier?: string;
}): Promise<OAuthTokenSet>; }): Promise<OAuthTokenSet>;
refreshAccessToken?(options: { refreshAccessToken?(options: {
config: HeimdallConfig; config: HeimdallConfig;
refreshToken: string; refreshToken: string;
}): Promise<OAuthTokenSet>; signal?: AbortSignal;
resolveIdentity(options: { config: HeimdallConfig; accessToken: string }): Promise<ResolvedIdentity>; }): Promise<ExpiringTokenSet>;
resolveIdentity(options: {
config: HeimdallConfig;
accessToken: string;
/** The exchange's answer: an OIDC provider's identity is its id_token, not a lookup with the access token. */
tokenSet?: OAuthTokenSet;
/** The nonce this authorization request carried; an OIDC provider's id_token must echo it. */
oidcNonce?: string;
}): Promise<ResolvedIdentity>;
evaluateEntitlements(options: { evaluateEntitlements(options: {
config: HeimdallConfig; config: HeimdallConfig;
callback: OAuthCallbackContext; callback: OAuthCallbackContext;
@ -59,19 +74,75 @@ export interface OAuthProviderRuntime {
}): Promise<EntitlementEvaluation>; }): Promise<EntitlementEvaluation>;
} }
function buildErrorMessage(status: number, body: string, fallback: string): string { const oauthErrorCodes = [
return `${fallback} (status ${status}): ${body || "empty response"}`; "invalid_request",
"invalid_client",
"invalid_grant",
"unauthorized_client",
"unsupported_grant_type",
"invalid_scope",
] as const;
export type OAuthErrorCode = (typeof oauthErrorCodes)[number];
function readOAuthErrorCode(text: string): OAuthErrorCode | undefined {
try {
const error = (JSON.parse(text) as { error?: unknown } | null)?.error;
return oauthErrorCodes.find((code) => code === error);
} catch {
return undefined;
}
} }
async function fetchJson<T>(input: string | URL, init: RequestInit, fallbackError: string): Promise<T> { /**
const response = await fetch(input, init); * A provider answer Heimdall cannot use: a non-2xx status, or a body that is
const text = await response.text(); * not JSON. It carries the status and a code, never the body or the parser's
* message: a provider's body can quote the request or hold tokens (JSON.parse
* quotes the text around the fault), and whatever catches this may record,
* print or relay it.
*/
export class ProviderResponseError extends Error {
readonly status: number;
readonly code: "provider_status" | "provider_body_not_json" | "provider_body_not_token_set";
/**
* The RFC 6749 section 5.2 error code of a refusal, when the provider sent
* one from that closed set. The only value taken from a provider's body.
*/
readonly oauthError: OAuthErrorCode | undefined;
if (!response.ok) { constructor(status: number, code: ProviderResponseError["code"], failure: string, oauthError?: OAuthErrorCode) {
throw new Error(buildErrorMessage(response.status, text, fallbackError)); super(`${failure} (status ${status}, ${code}).`);
this.name = "ProviderResponseError";
this.status = status;
this.code = code;
this.oauthError = oauthError;
} }
}
return (text ? JSON.parse(text) : {}) as T; /** The JSON body of a provider's answer; refuses any other answer by status and code alone. */
async function readProviderJson<T>(response: Response, failure: string): Promise<T> {
const text = await response.text();
if (!response.ok) {
// RFC 6749 section 5.2 sends a grant verdict as 400 only. The same JSON
// behind a 401, a 5xx or a gateway page is not one.
throw new ProviderResponseError(
response.status,
"provider_status",
failure,
response.status === 400 ? readOAuthErrorCode(text) : undefined
);
}
if (!text) {
return {} as T;
}
try {
return JSON.parse(text) as T;
} catch {
throw new ProviderResponseError(response.status, "provider_body_not_json", failure);
}
}
async function fetchJson<T>(input: string | URL, init: RequestInit, failure: string): Promise<T> {
return readProviderJson<T>(await fetch(input, init), failure);
} }
function normalizeScopes(scope: string | string[] | undefined): string[] { function normalizeScopes(scope: string | string[] | undefined): string[] {
@ -82,512 +153,134 @@ function normalizeScopes(scope: string | string[] | undefined): string[] {
return scope?.split(/\s+/).filter(Boolean) ?? []; return scope?.split(/\s+/).filter(Boolean) ?? [];
} }
async function exchangeDiscordAuthorizationCode(options: { export type TokenGrant =
config: HeimdallConfig; | { grant_type: "authorization_code"; code: string; redirect_uri: string; code_verifier?: string }
code: string; | { grant_type: "refresh_token"; refresh_token: string };
redirectUri: string;
}): Promise<OAuthTokenSet> { /**
const providerConfig = options.config.providers.discord; * The one token request: endpoint, client authentication and rotation all come
* from the provider's descriptor. `basic` sends the client as an Authorization
* header and nothing in the body; `post` sends it in the body. A refresh token
* is returned only when the provider sent one; keeping or discarding the old
* one is the caller's rule (ProviderDescriptor.rotatesRefreshTokens).
*/
export async function requestProviderTokens(
provider: Provider,
config: HeimdallConfig,
grant: TokenGrant,
signal?: AbortSignal
): Promise<ExpiringTokenSet> {
const descriptor = providerCatalog[provider];
const providerConfig = config.providers[provider];
if (!providerConfig.clientId || !providerConfig.clientSecret) { if (!providerConfig.clientId || !providerConfig.clientSecret) {
throw new Error("Discord OAuth is not fully configured."); throw new Error(`${descriptor.displayName} OAuth is not fully configured.`);
} }
const body = new URLSearchParams({ const body = new URLSearchParams(grant);
grant_type: "authorization_code", const headers: Record<string, string> = {
code: options.code, "Content-Type": "application/x-www-form-urlencoded",
redirect_uri: options.redirectUri, Accept: "application/json",
}); };
const basicAuth = Buffer.from(`${providerConfig.clientId}:${providerConfig.clientSecret}`).toString("base64"); if (descriptor.tokenEndpointAuthMethod === "client_secret_basic") {
const tokenResponse = await fetchJson<{ headers.Authorization = `Basic ${Buffer.from(`${providerConfig.clientId}:${providerConfig.clientSecret}`).toString("base64")}`;
access_token: string; } else {
refresh_token?: string; body.set("client_id", providerConfig.clientId);
token_type: string; body.set("client_secret", providerConfig.clientSecret);
expires_in: number; }
scope?: string | string[];
}>(
"https://discord.com/api/v10/oauth2/token",
{
method: "POST",
headers: {
Authorization: `Basic ${basicAuth}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body,
},
"Discord token exchange failed"
);
const tokenSet: OAuthTokenSet = { const init: RequestInit = { method: "POST", headers, body };
accessToken: tokenResponse.access_token, if (signal) {
tokenType: tokenResponse.token_type, init.signal = signal;
scope: normalizeScopes(tokenResponse.scope), }
expiresAt: new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString(), const label = grant.grant_type === "refresh_token" ? "refresh" : "exchange";
raw: tokenResponse as unknown as Record<string, unknown>, const failure = `${descriptor.displayName} token ${label} failed`;
const response = await fetch(descriptor.tokenEndpoint, init);
const answer = await readProviderJson<unknown>(response, failure);
// A 2xx is a token set only when it is an object holding a string access
// token and no error.
if (
typeof answer !== "object" ||
answer === null ||
typeof (answer as { access_token?: unknown }).access_token !== "string" ||
!(answer as { access_token: string }).access_token ||
(answer as { error?: unknown }).error !== undefined
) {
throw new ProviderResponseError(response.status, "provider_body_not_token_set", failure);
}
const tokenResponse = answer as {
access_token: string;
refresh_token?: unknown;
token_type?: string;
expires_in?: unknown;
scope?: string | string[];
}; };
// A refresh token that is present must be a string: anything else is a
// malformed grant answer, refused here as a typed failure rather than
// reaching custody as a TypeError.
if (tokenResponse.refresh_token !== undefined && typeof tokenResponse.refresh_token !== "string") {
throw new ProviderResponseError(response.status, "provider_body_not_token_set", failure);
}
// Nothing issued here has an unknown expiry: an answer without a usable
// expires_in takes the descriptor's default lifetime.
const lifetimeSeconds = usableExpiresIn(tokenResponse.expires_in) ?? descriptor.defaultAccessTokenLifetimeSeconds;
const tokenSet: ExpiringTokenSet = {
accessToken: tokenResponse.access_token,
tokenType: tokenResponse.token_type ?? "Bearer",
scope: normalizeScopes(tokenResponse.scope),
expiresAt: new Date(Date.now() + lifetimeSeconds * 1000).toISOString(),
raw: tokenResponse as unknown as Record<string, unknown>,
};
if (tokenResponse.refresh_token) { if (tokenResponse.refresh_token) {
tokenSet.refreshToken = tokenResponse.refresh_token; tokenSet.refreshToken = tokenResponse.refresh_token;
} }
return tokenSet; return tokenSet;
} }
async function refreshDiscordAccessToken(options: { /** The longest access token lifetime taken at its word: a year. Anything above is not a lifetime. */
config: HeimdallConfig; const MAX_USABLE_EXPIRES_IN_SECONDS = 365 * 24 * 60 * 60;
refreshToken: string;
}): Promise<OAuthTokenSet> {
const providerConfig = options.config.providers.discord;
if (!providerConfig.clientId || !providerConfig.clientSecret) {
throw new Error("Discord OAuth is not fully configured.");
}
const basicAuth = Buffer.from(`${providerConfig.clientId}:${providerConfig.clientSecret}`).toString("base64"); /**
const tokenResponse = await fetchJson<{ * A positive finite number of seconds, or a string that is a positive integer,
access_token: string; * no longer than a year. A larger value would overflow the Date the expiry is
refresh_token?: string; * stored as, so it is unusable and the descriptor's default lifetime applies.
token_type: string; */
expires_in: number; function usableExpiresIn(value: unknown): number | undefined {
scope?: string | string[]; const seconds = typeof value === "string" && /^\s*\d+\s*$/.test(value) ? Number(value) : value;
}>( return typeof seconds === "number" && Number.isFinite(seconds) && seconds > 0 && seconds <= MAX_USABLE_EXPIRES_IN_SECONDS
"https://discord.com/api/v10/oauth2/token", ? seconds
{ : undefined;
method: "POST", }
headers: {
Authorization: `Basic ${basicAuth}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: options.refreshToken,
}),
},
"Discord token refresh failed"
);
const tokenSet: OAuthTokenSet = { function sharedRuntimeExchange(provider: Provider): OAuthProviderRuntime["exchangeAuthorizationCode"] {
accessToken: tokenResponse.access_token, return async (options) => {
tokenType: tokenResponse.token_type, const tokenSet = await requestProviderTokens(provider, options.config, {
scope: normalizeScopes(tokenResponse.scope), grant_type: "authorization_code",
expiresAt: new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString(), code: options.code,
raw: tokenResponse as unknown as Record<string, unknown>, redirect_uri: options.redirectUri,
...(options.codeVerifier !== undefined ? { code_verifier: options.codeVerifier } : {}),
});
// A rotating provider's refresh token is the only way back to the
// credential: a grant that arrives without one would be stored as a row
// the first refresh revokes, so the callback fails before it writes.
if (providerCatalog[provider].rotatesRefreshTokens && !tokenSet.refreshToken) {
throw new ProviderResponseError(200, "provider_body_not_token_set", `${providerCatalog[provider].displayName} token exchange failed`);
}
return tokenSet;
}; };
if (tokenResponse.refresh_token) {
tokenSet.refreshToken = tokenResponse.refresh_token;
}
return tokenSet;
} }
async function exchangePatreonAuthorizationCode(options: { function sharedRuntimeRefresh(provider: Provider): NonNullable<OAuthProviderRuntime["refreshAccessToken"]> {
config: HeimdallConfig; return (options) =>
code: string; requestProviderTokens(
redirectUri: string; provider,
}): Promise<OAuthTokenSet> { options.config,
const providerConfig = options.config.providers.patreon; { grant_type: "refresh_token", refresh_token: options.refreshToken },
if (!providerConfig.clientId || !providerConfig.clientSecret) { options.signal
throw new Error("Patreon OAuth is not fully configured."); );
}
const body = new URLSearchParams({
grant_type: "authorization_code",
code: options.code,
client_id: providerConfig.clientId,
client_secret: providerConfig.clientSecret,
redirect_uri: options.redirectUri,
});
const tokenResponse = await fetchJson<{
access_token: string;
refresh_token?: string;
token_type: string;
expires_in?: number;
scope?: string | string[];
}>(
"https://www.patreon.com/api/oauth2/token",
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body,
},
"Patreon token exchange failed"
);
const tokenSet: OAuthTokenSet = {
accessToken: tokenResponse.access_token,
tokenType: tokenResponse.token_type,
scope: normalizeScopes(tokenResponse.scope),
raw: tokenResponse as unknown as Record<string, unknown>,
};
if (tokenResponse.refresh_token) {
tokenSet.refreshToken = tokenResponse.refresh_token;
}
if (tokenResponse.expires_in) {
tokenSet.expiresAt = new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString();
}
return tokenSet;
} }
async function refreshPatreonAccessToken(options: {
config: HeimdallConfig;
refreshToken: string;
}): Promise<OAuthTokenSet> {
const providerConfig = options.config.providers.patreon;
if (!providerConfig.clientId || !providerConfig.clientSecret) {
throw new Error("Patreon OAuth is not fully configured.");
}
const tokenResponse = await fetchJson<{
access_token: string;
refresh_token?: string;
token_type: string;
expires_in?: number;
scope?: string | string[];
}>(
"https://www.patreon.com/api/oauth2/token",
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: options.refreshToken,
client_id: providerConfig.clientId,
client_secret: providerConfig.clientSecret,
}),
},
"Patreon token refresh failed"
);
const tokenSet: OAuthTokenSet = {
accessToken: tokenResponse.access_token,
tokenType: tokenResponse.token_type,
scope: normalizeScopes(tokenResponse.scope),
raw: tokenResponse as unknown as Record<string, unknown>,
};
if (tokenResponse.refresh_token) {
tokenSet.refreshToken = tokenResponse.refresh_token;
}
if (tokenResponse.expires_in) {
tokenSet.expiresAt = new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString();
}
return tokenSet;
}
async function exchangeTwitchAuthorizationCode(options: {
config: HeimdallConfig;
code: string;
redirectUri: string;
}): Promise<OAuthTokenSet> {
const providerConfig = options.config.providers.twitch;
if (!providerConfig.clientId || !providerConfig.clientSecret) {
throw new Error("Twitch OAuth is not fully configured.");
}
const tokenResponse = await fetchJson<{
access_token: string;
refresh_token?: string;
token_type: string;
expires_in?: number;
scope?: string | string[];
}>(
"https://id.twitch.tv/oauth2/token",
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
client_id: providerConfig.clientId,
client_secret: providerConfig.clientSecret,
code: options.code,
grant_type: "authorization_code",
redirect_uri: options.redirectUri,
}),
},
"Twitch token exchange failed"
);
const tokenSet: OAuthTokenSet = {
accessToken: tokenResponse.access_token,
tokenType: tokenResponse.token_type,
scope: normalizeScopes(tokenResponse.scope),
raw: tokenResponse as unknown as Record<string, unknown>,
};
if (tokenResponse.refresh_token) {
tokenSet.refreshToken = tokenResponse.refresh_token;
}
if (tokenResponse.expires_in) {
tokenSet.expiresAt = new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString();
}
return tokenSet;
}
async function refreshTwitchAccessToken(options: {
config: HeimdallConfig;
refreshToken: string;
}): Promise<OAuthTokenSet> {
const providerConfig = options.config.providers.twitch;
if (!providerConfig.clientId || !providerConfig.clientSecret) {
throw new Error("Twitch OAuth is not fully configured.");
}
const tokenResponse = await fetchJson<{
access_token: string;
refresh_token?: string;
token_type: string;
expires_in?: number;
scope?: string | string[];
}>(
"https://id.twitch.tv/oauth2/token",
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
client_id: providerConfig.clientId,
client_secret: providerConfig.clientSecret,
grant_type: "refresh_token",
refresh_token: options.refreshToken,
}),
},
"Twitch token refresh failed"
);
const tokenSet: OAuthTokenSet = {
accessToken: tokenResponse.access_token,
tokenType: tokenResponse.token_type,
scope: normalizeScopes(tokenResponse.scope),
raw: tokenResponse as unknown as Record<string, unknown>,
};
if (tokenResponse.refresh_token) {
tokenSet.refreshToken = tokenResponse.refresh_token;
}
if (tokenResponse.expires_in) {
tokenSet.expiresAt = new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString();
}
return tokenSet;
}
async function exchangeYouTubeAuthorizationCode(options: {
config: HeimdallConfig;
code: string;
redirectUri: string;
}): Promise<OAuthTokenSet> {
const providerConfig = options.config.providers.youtube;
if (!providerConfig.clientId || !providerConfig.clientSecret) {
throw new Error("YouTube OAuth is not fully configured.");
}
const tokenResponse = await fetchJson<{
access_token: string;
refresh_token?: string;
token_type: string;
expires_in?: number;
scope?: string | string[];
id_token?: string;
}>(
"https://oauth2.googleapis.com/token",
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
client_id: providerConfig.clientId,
client_secret: providerConfig.clientSecret,
code: options.code,
grant_type: "authorization_code",
redirect_uri: options.redirectUri,
}),
},
"YouTube token exchange failed"
);
const tokenSet: OAuthTokenSet = {
accessToken: tokenResponse.access_token,
tokenType: tokenResponse.token_type,
scope: normalizeScopes(tokenResponse.scope),
raw: tokenResponse as unknown as Record<string, unknown>,
};
if (tokenResponse.refresh_token) {
tokenSet.refreshToken = tokenResponse.refresh_token;
}
if (tokenResponse.expires_in) {
tokenSet.expiresAt = new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString();
}
return tokenSet;
}
async function refreshYouTubeAccessToken(options: {
config: HeimdallConfig;
refreshToken: string;
}): Promise<OAuthTokenSet> {
const providerConfig = options.config.providers.youtube;
if (!providerConfig.clientId || !providerConfig.clientSecret) {
throw new Error("YouTube OAuth is not fully configured.");
}
const tokenResponse = await fetchJson<{
access_token: string;
refresh_token?: string;
token_type: string;
expires_in?: number;
scope?: string | string[];
}>(
"https://oauth2.googleapis.com/token",
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
client_id: providerConfig.clientId,
client_secret: providerConfig.clientSecret,
grant_type: "refresh_token",
refresh_token: options.refreshToken,
}),
},
"YouTube token refresh failed"
);
const tokenSet: OAuthTokenSet = {
accessToken: tokenResponse.access_token,
tokenType: tokenResponse.token_type,
scope: normalizeScopes(tokenResponse.scope),
raw: tokenResponse as unknown as Record<string, unknown>,
};
if (tokenResponse.refresh_token) {
tokenSet.refreshToken = tokenResponse.refresh_token;
}
if (tokenResponse.expires_in) {
tokenSet.expiresAt = new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString();
}
return tokenSet;
}
async function exchangeSpotifyAuthorizationCode(options: {
config: HeimdallConfig;
code: string;
redirectUri: string;
}): Promise<OAuthTokenSet> {
const providerConfig = options.config.providers.spotify;
if (!providerConfig.clientId || !providerConfig.clientSecret) {
throw new Error("Spotify OAuth is not fully configured.");
}
const basicAuth = Buffer.from(`${providerConfig.clientId}:${providerConfig.clientSecret}`).toString("base64");
const tokenResponse = await fetchJson<{
access_token: string;
refresh_token?: string;
token_type: string;
expires_in?: number;
scope?: string | string[];
}>(
"https://accounts.spotify.com/api/token",
{
method: "POST",
headers: {
Authorization: `Basic ${basicAuth}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
grant_type: "authorization_code",
code: options.code,
redirect_uri: options.redirectUri,
}),
},
"Spotify token exchange failed"
);
const tokenSet: OAuthTokenSet = {
accessToken: tokenResponse.access_token,
tokenType: tokenResponse.token_type,
scope: normalizeScopes(tokenResponse.scope),
raw: tokenResponse as unknown as Record<string, unknown>,
};
if (tokenResponse.refresh_token) {
tokenSet.refreshToken = tokenResponse.refresh_token;
}
if (tokenResponse.expires_in) {
tokenSet.expiresAt = new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString();
}
return tokenSet;
}
async function refreshSpotifyAccessToken(options: {
config: HeimdallConfig;
refreshToken: string;
}): Promise<OAuthTokenSet> {
const providerConfig = options.config.providers.spotify;
if (!providerConfig.clientId || !providerConfig.clientSecret) {
throw new Error("Spotify OAuth is not fully configured.");
}
const basicAuth = Buffer.from(`${providerConfig.clientId}:${providerConfig.clientSecret}`).toString("base64");
const tokenResponse = await fetchJson<{
access_token: string;
refresh_token?: string;
token_type: string;
expires_in?: number;
scope?: string | string[];
}>(
"https://accounts.spotify.com/api/token",
{
method: "POST",
headers: {
Authorization: `Basic ${basicAuth}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: options.refreshToken,
}),
},
"Spotify token refresh failed"
);
const tokenSet: OAuthTokenSet = {
accessToken: tokenResponse.access_token,
tokenType: tokenResponse.token_type,
scope: normalizeScopes(tokenResponse.scope),
raw: tokenResponse as unknown as Record<string, unknown>,
};
if (tokenResponse.refresh_token) {
tokenSet.refreshToken = tokenResponse.refresh_token;
}
if (tokenResponse.expires_in) {
tokenSet.expiresAt = new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString();
}
return tokenSet;
}
async function resolveDiscordIdentity(options: { accessToken: string }): Promise<ResolvedIdentity> { async function resolveDiscordIdentity(options: { accessToken: string }): Promise<ResolvedIdentity> {
const user = await fetchJson<{ const user = await fetchJson<{
@ -772,7 +465,7 @@ async function resolveYouTubeIdentity(options: { accessToken: string }): Promise
}); });
if (channelResponse.ok) { if (channelResponse.ok) {
const payload = (await channelResponse.json()) as { const payload = await readProviderJson<{
items?: Array<{ items?: Array<{
id: string; id: string;
snippet?: { snippet?: {
@ -785,7 +478,7 @@ async function resolveYouTubeIdentity(options: { accessToken: string }): Promise
}; };
}; };
}>; }>;
}; }>(channelResponse, "YouTube channel lookup failed");
const channel = payload.items?.[0]; const channel = payload.items?.[0];
if (channel?.id) { if (channel?.id) {
@ -845,6 +538,31 @@ async function resolveYouTubeIdentity(options: { accessToken: string }): Promise
return identity; return identity;
} }
async function resolveGoogleIdentity(options: {
config: HeimdallConfig;
tokenSet?: OAuthTokenSet;
oidcNonce?: string;
}): Promise<ResolvedIdentity> {
const clientId = options.config.providers.google.clientId;
const idToken = options.tokenSet?.raw.id_token;
if (!clientId || typeof idToken !== "string" || !options.oidcNonce) {
throw new Error("Google sign-in needs a client id, an id_token and the request's nonce.");
}
const claims = await verifyGoogleIdToken(idToken, { clientId, nonce: options.oidcNonce });
const identity: ResolvedIdentity = {
provider: "google",
providerUserId: claims.sub,
username: claims.email,
displayName: claims.name ?? claims.email,
primaryEmail: claims.email,
profile: { sub: claims.sub, email: claims.email, email_verified: true, name: claims.name, picture: claims.picture, hd: claims.hd },
};
if (claims.picture) {
identity.avatarUrl = claims.picture;
}
return identity;
}
async function resolveSpotifyIdentity(options: { accessToken: string }): Promise<ResolvedIdentity> { async function resolveSpotifyIdentity(options: { accessToken: string }): Promise<ResolvedIdentity> {
const profile = await fetchJson<{ const profile = await fetchJson<{
id?: string; id?: string;
@ -886,6 +604,45 @@ async function resolveSpotifyIdentity(options: { accessToken: string }): Promise
return identity; return identity;
} }
async function resolveJoystickIdentity(options: { accessToken: string }): Promise<ResolvedIdentity> {
const profile = await fetchJson<{
channel_id?: string;
username?: string;
nickname?: string;
photo_url?: string;
}>(
"https://api.joystick.tv/api/v1/me/identity",
{
headers: {
Authorization: `Bearer ${options.accessToken}`,
},
},
"Joystick identity lookup failed"
);
if (!profile.channel_id) {
throw new Error("Joystick identity response did not include a channel id.");
}
const identity: ResolvedIdentity = {
provider: "joystick",
providerUserId: profile.channel_id,
profile: profile as unknown as Record<string, unknown>,
};
const displayName = profile.nickname ?? profile.username;
if (profile.username) {
identity.username = profile.username;
}
if (displayName) {
identity.displayName = displayName;
}
if (profile.photo_url) {
identity.avatarUrl = profile.photo_url;
}
return identity;
}
async function evaluateDiscordEntitlements(options: { async function evaluateDiscordEntitlements(options: {
config: HeimdallConfig; config: HeimdallConfig;
callback: OAuthCallbackContext; callback: OAuthCallbackContext;
@ -926,16 +683,11 @@ async function evaluateDiscordEntitlements(options: {
}; };
} }
const text = await response.text(); const member = await readProviderJson<{
if (!response.ok) {
throw new Error(buildErrorMessage(response.status, text, "Discord guild member lookup failed"));
}
const member = (text ? JSON.parse(text) : {}) as {
nick?: string; nick?: string;
roles?: string[]; roles?: string[];
joined_at?: string; joined_at?: string;
}; }>(response, "Discord guild member lookup failed");
const roles = member.roles ?? []; const roles = member.roles ?? [];
const matchedRoles = allowedRoleIds.filter((roleId) => roles.includes(roleId)); const matchedRoles = allowedRoleIds.filter((roleId) => roles.includes(roleId));
const facts: string[] = []; const facts: string[] = [];
@ -1198,22 +950,22 @@ async function evaluatePatreonEntitlements(options: {
} }
const discordRuntime: OAuthProviderRuntime = { const discordRuntime: OAuthProviderRuntime = {
exchangeAuthorizationCode: exchangeDiscordAuthorizationCode, exchangeAuthorizationCode: sharedRuntimeExchange("discord"),
refreshAccessToken: refreshDiscordAccessToken, refreshAccessToken: sharedRuntimeRefresh("discord"),
resolveIdentity: resolveDiscordIdentity, resolveIdentity: resolveDiscordIdentity,
evaluateEntitlements: evaluateDiscordEntitlements, evaluateEntitlements: evaluateDiscordEntitlements,
}; };
const patreonRuntime: OAuthProviderRuntime = { const patreonRuntime: OAuthProviderRuntime = {
exchangeAuthorizationCode: exchangePatreonAuthorizationCode, exchangeAuthorizationCode: sharedRuntimeExchange("patreon"),
refreshAccessToken: refreshPatreonAccessToken, refreshAccessToken: sharedRuntimeRefresh("patreon"),
resolveIdentity: resolvePatreonIdentity, resolveIdentity: resolvePatreonIdentity,
evaluateEntitlements: evaluatePatreonEntitlements, evaluateEntitlements: evaluatePatreonEntitlements,
}; };
const twitchRuntime: OAuthProviderRuntime = { const twitchRuntime: OAuthProviderRuntime = {
exchangeAuthorizationCode: exchangeTwitchAuthorizationCode, exchangeAuthorizationCode: sharedRuntimeExchange("twitch"),
refreshAccessToken: refreshTwitchAccessToken, refreshAccessToken: sharedRuntimeRefresh("twitch"),
resolveIdentity: resolveTwitchIdentity, resolveIdentity: resolveTwitchIdentity,
async evaluateEntitlements() { async evaluateEntitlements() {
return { facts: [], snapshots: [] }; return { facts: [], snapshots: [] };
@ -1221,23 +973,41 @@ const twitchRuntime: OAuthProviderRuntime = {
}; };
const youtubeRuntime: OAuthProviderRuntime = { const youtubeRuntime: OAuthProviderRuntime = {
exchangeAuthorizationCode: exchangeYouTubeAuthorizationCode, exchangeAuthorizationCode: sharedRuntimeExchange("youtube"),
refreshAccessToken: refreshYouTubeAccessToken, refreshAccessToken: sharedRuntimeRefresh("youtube"),
resolveIdentity: resolveYouTubeIdentity, resolveIdentity: resolveYouTubeIdentity,
async evaluateEntitlements() { async evaluateEntitlements() {
return { facts: [], snapshots: [] }; return { facts: [], snapshots: [] };
}, },
}; };
const googleRuntime: OAuthProviderRuntime = {
exchangeAuthorizationCode: sharedRuntimeExchange("google"),
refreshAccessToken: sharedRuntimeRefresh("google"),
resolveIdentity: resolveGoogleIdentity,
async evaluateEntitlements() {
return { facts: [], snapshots: [] };
},
};
const spotifyRuntime: OAuthProviderRuntime = { const spotifyRuntime: OAuthProviderRuntime = {
exchangeAuthorizationCode: exchangeSpotifyAuthorizationCode, exchangeAuthorizationCode: sharedRuntimeExchange("spotify"),
refreshAccessToken: refreshSpotifyAccessToken, refreshAccessToken: sharedRuntimeRefresh("spotify"),
resolveIdentity: resolveSpotifyIdentity, resolveIdentity: resolveSpotifyIdentity,
async evaluateEntitlements() { async evaluateEntitlements() {
return { facts: [], snapshots: [] }; return { facts: [], snapshots: [] };
}, },
}; };
const joystickRuntime: OAuthProviderRuntime = {
exchangeAuthorizationCode: sharedRuntimeExchange("joystick"),
refreshAccessToken: sharedRuntimeRefresh("joystick"),
resolveIdentity: resolveJoystickIdentity,
async evaluateEntitlements() {
return { facts: [], snapshots: [] };
},
};
const notImplementedRuntime: OAuthProviderRuntime = { const notImplementedRuntime: OAuthProviderRuntime = {
async exchangeAuthorizationCode() { async exchangeAuthorizationCode() {
throw new Error("Provider callback exchange is not implemented yet."); throw new Error("Provider callback exchange is not implemented yet.");
@ -1260,5 +1030,7 @@ export function createOAuthRuntimeRegistry(): OAuthRuntimeRegistry {
twitch: twitchRuntime, twitch: twitchRuntime,
youtube: youtubeRuntime, youtube: youtubeRuntime,
spotify: spotifyRuntime, spotify: spotifyRuntime,
joystick: joystickRuntime,
google: googleRuntime,
}; };
} }

View file

@ -7,7 +7,7 @@ import {
type CultNetOperationServer, type CultNetOperationServer,
} from "cultnet-ts"; } from "cultnet-ts";
import { type FastifyInstance } from "fastify"; import { type FastifyInstance } from "fastify";
import { getHeimdallRuntimeContext, refreshAppSession, startOAuthFlow, verifyRefreshToken } from "./app.js"; import { errorIdentity, getHeimdallRuntimeContext, refreshAppSession, startOAuthFlow, verifyRefreshToken } from "./app.js";
import { callerFromOpenedEnvelope } from "./app-caller.js"; import { callerFromOpenedEnvelope } from "./app-caller.js";
import { getAppProfile } from "./app-profiles.js"; import { getAppProfile } from "./app-profiles.js";
import { executeHeimdallAccessPlugin, HEIMDALL_ACCESS_PLUGIN_ID, type EvePluginAbiRequest } from "./access-plugin.js"; import { executeHeimdallAccessPlugin, HEIMDALL_ACCESS_PLUGIN_ID, type EvePluginAbiRequest } from "./access-plugin.js";
@ -138,6 +138,12 @@ export async function startHeimdallPrivateCommandPlane(
} }
return response(request, cachedResult.status, cachedResult.envelope, config.daemonId); return response(request, cachedResult.status, cachedResult.envelope, config.daemonId);
} catch (error) { } catch (error) {
// The reply's diagnostics travel outside the sealed envelope, and the
// caller logs them. Errors caught here carry input: JSON.parse quotes
// a provider's body, a store error names the database. So the
// diagnostic is fixed text plus the error's class and code; anything
// more lives only in a sealed payload the plane authored.
const { errorClass, errorCode } = errorIdentity(error);
return { return {
schemaVersion: "cultnet.operation_response.v0", schemaVersion: "cultnet.operation_response.v0",
messageId: request.messageId, messageId: request.messageId,
@ -147,7 +153,7 @@ export async function startHeimdallPrivateCommandPlane(
payloadSchema: "gamecult.cultnet.operation_failure.v1", payloadSchema: "gamecult.cultnet.operation_failure.v1",
payloadEncoding: "messagepack-base64", payloadEncoding: "messagepack-base64",
payload: Buffer.from(encode({ code: "private-command-denied", message: "Heimdall denied the private command." })).toString("base64"), payload: Buffer.from(encode({ code: "private-command-denied", message: "Heimdall denied the private command." })).toString("base64"),
diagnostics: [error instanceof Error ? error.message : "Private command failed."], diagnostics: [`Heimdall denied the private command (${errorClass}${errorCode ? `, ${errorCode}` : ""}).`],
sourceRuntimeId: config.daemonId, sourceRuntimeId: config.daemonId,
}; };
} }
@ -299,7 +305,6 @@ async function beginAuth(
throw new Error(String(startPayload.detail ?? startPayload.error ?? "OAuth start was denied.")); throw new Error(String(startPayload.detail ?? startPayload.error ?? "OAuth start was denied."));
} }
const authorizationUrl = String(startPayload.authorizationUrl ?? ""); const authorizationUrl = String(startPayload.authorizationUrl ?? "");
const authorizationOrigin = new URL(authorizationUrl).origin;
return { return {
status: "accepted", status: "accepted",
payloadSchema: "heimdall.auth_begin_receipt.v1", payloadSchema: "heimdall.auth_begin_receipt.v1",
@ -310,7 +315,7 @@ async function beginAuth(
expiresAt: attempt.expiresAt, expiresAt: attempt.expiresAt,
navigation: { navigation: {
url: authorizationUrl, url: authorizationUrl,
allowedOrigins: [authorizationOrigin, new URL(config.publicBaseUrl).origin], allowedOrigins: [new URL(config.publicBaseUrl).origin],
}, },
}, },
}; };
@ -351,7 +356,6 @@ async function completeAuth(
eventPayloadJson: { eventPayloadJson: {
provider: completion.provider, provider: completion.provider,
mode: completion.mode, mode: completion.mode,
completionCode: completion.code,
}, },
createdAt: now, createdAt: now,
}); });

View file

@ -7,7 +7,7 @@ import {
sign, sign,
type KeyObject, type KeyObject,
} from "node:crypto"; } from "node:crypto";
import { readFileSync } from "node:fs"; import { closeSync, fstatSync, readSync } from "node:fs";
import { chmod, readFile } from "node:fs/promises"; import { chmod, readFile } from "node:fs/promises";
import { SingleFileMessagePackBackingStore, type CultCacheEnvelope } from "@gamecult/cultcache-ts"; import { SingleFileMessagePackBackingStore, type CultCacheEnvelope } from "@gamecult/cultcache-ts";
import { readPrivateStoreRecord } from "./idunn-store.js"; import { readPrivateStoreRecord } from "./idunn-store.js";
@ -71,7 +71,7 @@ export async function openOrEnrollProviderHealthIdentity(path: string): Promise<
if (existing.length !== 1) { if (existing.length !== 1) {
throw new Error("Provider-health identity store must contain exactly one record."); throw new Error("Provider-health identity store must contain exactly one record.");
} }
return decodePrivateIdentity(existing[0]!.payload, await readMachineId()); return decodePrivateIdentity(existing[0]!.payload, await readMachineId(), "bin");
} }
const PRESENCE_IDENTITY_FD_NAME = "gamecult-runtime-presence-identity"; const PRESENCE_IDENTITY_FD_NAME = "gamecult-runtime-presence-identity";
@ -124,19 +124,50 @@ export function passedDescriptor(
*/ */
export async function openProviderHealthIdentity( export async function openProviderHealthIdentity(
path: string, path: string,
env: NodeJS.ProcessEnv = process.env env: NodeJS.ProcessEnv = process.env,
machineId: () => Promise<string> = readMachineId
): Promise<PrivateIdentity> { ): Promise<PrivateIdentity> {
const descriptor = passedDescriptor(PRESENCE_IDENTITY_FD_NAME, env); const descriptor = passedDescriptor(PRESENCE_IDENTITY_FD_NAME, env);
if (descriptor === undefined) { if (descriptor === undefined) {
if (env.GAMECULT_IDUNN_RUNTIME_BUNDLE) {
// Inside an Idunn generation a self-enrolled key is one Idunn does not
// trust, and its private store would land in a state root the next
// generation must share. The descriptor is the only identity there.
throw new Error(
`Idunn runtime bundle is set but the ${PRESENCE_IDENTITY_FD_NAME} descriptor was not passed; refusing to self-enroll`
);
}
return openOrEnrollProviderHealthIdentity(path); return openOrEnrollProviderHealthIdentity(path);
} }
const payload = readPrivateStoreRecord( const payload = readPrivateStoreRecord(
readFileSync(descriptor), readPassedDescriptor(descriptor),
"Idunn runtime presence identity" "Idunn runtime presence identity"
); );
return decodePrivateIdentity(payload, await readMachineId()); // The descriptor's writer is the Rust owner, whose key fields are integer arrays.
return decodePrivateIdentity(payload, await machineId(), "int-array");
}
/**
* Read a passed descriptor whole, from offset 0, and close it. A descriptor is
* a one-shot input: reading it again starts at the offset the last read left,
* which is the end, so the owner reads once at open and keeps what it decoded.
*/
export function readPassedDescriptor(descriptor: number): Buffer {
try {
const size = fstatSync(descriptor).size;
const bytes = Buffer.alloc(size);
let read = 0;
while (read < size) {
const count = readSync(descriptor, bytes, read, size - read, read);
if (count === 0) break;
read += count;
}
return bytes.subarray(0, read);
} finally {
closeSync(descriptor);
}
} }
export function signProviderHealthPayload(identity: PrivateIdentity, payload: Uint8Array): Uint8Array { export function signProviderHealthPayload(identity: PrivateIdentity, payload: Uint8Array): Uint8Array {
@ -168,23 +199,58 @@ export function providerHealthPublicIdentity(identity: PrivateIdentity): {
return { identityId: identity.identityId, publicKeyHex: Buffer.from(identity.publicKey).toString("hex") }; return { identityId: identity.identityId, publicKeyHex: Buffer.from(identity.publicKey).toString("hex") };
} }
function decodePrivateIdentity(payload: Uint8Array, machineId: string): PrivateIdentity { /**
* Which writer produced the record. The self-enrolling store this process
* writes keeps key fields as MessagePack bin; the Rust owner (cultnet-rs
* service_identity.rs) serialises a Vec<u8> without serde_bytes, so its key
* fields are arrays of integers. Each source is read in its own shape and the
* other is refused.
*/
type KeyShape = "bin" | "int-array";
function keyBytes(value: unknown, shape: KeyShape, field: string): Uint8Array {
const bytes =
shape === "bin"
? value instanceof Uint8Array
? value
: undefined
: Array.isArray(value) &&
value.every((byte) => typeof byte === "number" && Number.isInteger(byte) && byte >= 0 && byte <= 255)
? Uint8Array.from(value as number[])
: undefined;
if (bytes === undefined || bytes.length !== 32) {
throw new Error(
`Provider-health identity key shape check failed: ${field} is not a 32-byte ${shape === "bin" ? "binary" : "integer-array"} key field.`
);
}
return bytes;
}
function decodePrivateIdentity(payload: Uint8Array, machineId: string, shape: KeyShape): PrivateIdentity {
const value = decode(payload); const value = decode(payload);
if (!Array.isArray(value) || value.length !== 10) { if (!Array.isArray(value) || value.length !== 10) {
throw new Error("Provider-health identity payload is malformed."); throw new Error("Provider-health identity schema check failed: payload is not a 10-field record.");
} }
const [schema, identityId, publicKey, protectedSeed, protector, binding, version] = value; const [schema, identityId, publicKeyField, protectedSeedField, protector, binding, version] = value;
if ( if (schema !== PRIVATE_SCHEMA) {
schema !== PRIVATE_SCHEMA || throw new Error("Provider-health identity schema check failed: unexpected schema id.");
typeof identityId !== "string" || }
!(publicKey instanceof Uint8Array) || publicKey.length !== 32 || if (typeof identityId !== "string") {
!(protectedSeed instanceof Uint8Array) || protectedSeed.length !== 32 || throw new Error("Provider-health identity id check failed: id is not a string.");
protector !== "linux_file_mode_machine_id_binding" || }
binding !== protectorBinding(machineId) || const publicKey = keyBytes(publicKeyField, shape, "public key");
version !== "v1" || const protectedSeed = keyBytes(protectedSeedField, shape, "protected seed");
identityId !== deriveIdentityId(publicKey) if (protector !== "linux_file_mode_machine_id_binding") {
) { throw new Error("Provider-health identity protector check failed: unexpected protector.");
throw new Error("Provider-health identity does not belong to this host or profile."); }
if (binding !== protectorBinding(machineId)) {
throw new Error("Provider-health identity binding check failed: not bound to this host's machine id.");
}
if (version !== "v1") {
throw new Error("Provider-health identity version check failed: unexpected version.");
}
if (identityId !== deriveIdentityId(publicKey)) {
throw new Error("Provider-health identity id check failed: id does not derive from the public key.");
} }
const seed = xorSeed(protectedSeed, binding); const seed = xorSeed(protectedSeed, binding);
const privateKey = privateKeyFromSeed(seed); const privateKey = privateKeyFromSeed(seed);

View file

@ -6,11 +6,40 @@ export interface ProviderDescriptor {
key: Provider; key: Provider;
displayName: string; displayName: string;
authorizationEndpoint: string; authorizationEndpoint: string;
tokenEndpoint: string;
/** RFC 7591 names: how the client authenticates at the token endpoint. */
tokenEndpointAuthMethod: "client_secret_basic" | "client_secret_post";
/** True when a refresh response replaces the refresh token and the old one dies. */
rotatesRefreshTokens: boolean;
/**
* Seconds an access token lives when a token answer carries no usable
* `expires_in` (RFC 6749 5.1 makes it RECOMMENDED, not required). An unknown
* expiry is never stored: the credential would never come due for refresh.
*/
defaultAccessTokenLifetimeSeconds: number;
defaultScopes: string[]; defaultScopes: string[];
roles: ProviderRole[]; roles: ProviderRole[];
clientIdEnv: string; clientIdEnv: string;
clientSecretEnv: string; clientSecretEnv: string;
additionalAuthorizationParams?: Record<string, string>; additionalAuthorizationParams?: Record<string, string>;
/**
* 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<string, string>;
/**
* What a callback does with a (provider, subject) no account holds yet.
* `mints_account` is every provider's behaviour before Google: the first
* login makes an account. `requires_link` never mints: the identity
* attaches only to the account a verified link start bound
* (`initiator_account_id`), otherwise the callback refuses. Google is a second
* door into a person who already has an account, so a first Google login
* must not make a stranger of them.
*/
firstLogin: "mints_account" | "requires_link";
/** OpenID Connect: the callback verifies an id_token and uses PKCE (S256) and a nonce. */
oidc?: true;
} }
export const providerCatalog: Record<Provider, ProviderDescriptor> = { export const providerCatalog: Record<Provider, ProviderDescriptor> = {
@ -18,42 +47,68 @@ export const providerCatalog: Record<Provider, ProviderDescriptor> = {
key: "discord", key: "discord",
displayName: "Discord", displayName: "Discord",
authorizationEndpoint: "https://discord.com/oauth2/authorize", authorizationEndpoint: "https://discord.com/oauth2/authorize",
tokenEndpoint: "https://discord.com/api/v10/oauth2/token",
tokenEndpointAuthMethod: "client_secret_basic",
rotatesRefreshTokens: false,
defaultAccessTokenLifetimeSeconds: 3600,
defaultScopes: ["identify", "guilds.members.read"], defaultScopes: ["identify", "guilds.members.read"],
roles: ["identity", "entitlement"], roles: ["identity", "entitlement"],
firstLogin: "mints_account",
clientIdEnv: "GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID", clientIdEnv: "GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID",
clientSecretEnv: "GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET", clientSecretEnv: "GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE",
}, },
patreon: { patreon: {
key: "patreon", key: "patreon",
displayName: "Patreon", displayName: "Patreon",
authorizationEndpoint: "https://www.patreon.com/oauth2/authorize", authorizationEndpoint: "https://www.patreon.com/oauth2/authorize",
tokenEndpoint: "https://www.patreon.com/api/oauth2/token",
tokenEndpointAuthMethod: "client_secret_post",
rotatesRefreshTokens: false,
defaultAccessTokenLifetimeSeconds: 3600,
defaultScopes: ["identity", "identity[email]"], defaultScopes: ["identity", "identity[email]"],
roles: ["identity", "entitlement"], roles: ["identity", "entitlement"],
firstLogin: "mints_account",
clientIdEnv: "GC_ACCESS_PROVIDER_PATREON_CLIENT_ID", clientIdEnv: "GC_ACCESS_PROVIDER_PATREON_CLIENT_ID",
clientSecretEnv: "GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET", clientSecretEnv: "GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET_FILE",
}, },
github: { github: {
key: "github", key: "github",
displayName: "GitHub", displayName: "GitHub",
authorizationEndpoint: "https://github.com/login/oauth/authorize", authorizationEndpoint: "https://github.com/login/oauth/authorize",
tokenEndpoint: "https://github.com/login/oauth/access_token",
tokenEndpointAuthMethod: "client_secret_post",
rotatesRefreshTokens: false,
defaultAccessTokenLifetimeSeconds: 3600,
defaultScopes: ["read:user", "user:email"], defaultScopes: ["read:user", "user:email"],
roles: ["identity", "managed_credential"], roles: ["identity", "managed_credential"],
firstLogin: "mints_account",
clientIdEnv: "GC_ACCESS_PROVIDER_GITHUB_CLIENT_ID", clientIdEnv: "GC_ACCESS_PROVIDER_GITHUB_CLIENT_ID",
clientSecretEnv: "GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET", clientSecretEnv: "GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET_FILE",
}, },
twitch: { twitch: {
key: "twitch", key: "twitch",
displayName: "Twitch", displayName: "Twitch",
authorizationEndpoint: "https://id.twitch.tv/oauth2/authorize", authorizationEndpoint: "https://id.twitch.tv/oauth2/authorize",
tokenEndpoint: "https://id.twitch.tv/oauth2/token",
tokenEndpointAuthMethod: "client_secret_post",
rotatesRefreshTokens: false,
defaultAccessTokenLifetimeSeconds: 3600,
defaultScopes: ["user:read:email"], defaultScopes: ["user:read:email"],
roles: ["identity", "managed_credential"], roles: ["identity", "managed_credential"],
firstLogin: "mints_account",
clientIdEnv: "GC_ACCESS_PROVIDER_TWITCH_CLIENT_ID", clientIdEnv: "GC_ACCESS_PROVIDER_TWITCH_CLIENT_ID",
clientSecretEnv: "GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET", 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: { youtube: {
key: "youtube", key: "youtube",
displayName: "YouTube", displayName: "YouTube",
authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth", authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
tokenEndpoint: "https://oauth2.googleapis.com/token",
tokenEndpointAuthMethod: "client_secret_post",
rotatesRefreshTokens: false,
defaultAccessTokenLifetimeSeconds: 3600,
defaultScopes: [ defaultScopes: [
"openid", "openid",
"email", "email",
@ -61,50 +116,115 @@ export const providerCatalog: Record<Provider, ProviderDescriptor> = {
"https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/youtube.readonly",
], ],
roles: ["identity", "managed_credential"], roles: ["identity", "managed_credential"],
firstLogin: "mints_account",
clientIdEnv: "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID", clientIdEnv: "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID",
clientSecretEnv: "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET", clientSecretEnv: "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET_FILE",
additionalAuthorizationParams: { additionalAuthorizationParams: {
access_type: "offline", access_type: "offline",
include_granted_scopes: "true", include_granted_scopes: "true",
prompt: "consent", prompt: "consent",
}, },
// login forces re-authentication; consent is kept because this provider always asks for it.
stepUpAuthorizationParams: { prompt: "login consent" },
}, },
spotify: { spotify: {
key: "spotify", key: "spotify",
displayName: "Spotify", displayName: "Spotify",
authorizationEndpoint: "https://accounts.spotify.com/authorize", authorizationEndpoint: "https://accounts.spotify.com/authorize",
tokenEndpoint: "https://accounts.spotify.com/api/token",
tokenEndpointAuthMethod: "client_secret_basic",
rotatesRefreshTokens: false,
defaultAccessTokenLifetimeSeconds: 3600,
defaultScopes: [ defaultScopes: [
"user-read-currently-playing", "user-read-currently-playing",
"user-read-playback-state", "user-read-playback-state",
"user-modify-playback-state", "user-modify-playback-state",
], ],
roles: ["identity", "managed_credential"], roles: ["identity", "managed_credential"],
firstLogin: "mints_account",
clientIdEnv: "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID", clientIdEnv: "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID",
clientSecretEnv: "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET", clientSecretEnv: "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET_FILE",
},
google: {
key: "google",
displayName: "Google",
authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
tokenEndpoint: "https://oauth2.googleapis.com/token",
tokenEndpointAuthMethod: "client_secret_post",
rotatesRefreshTokens: false,
defaultAccessTokenLifetimeSeconds: 3600,
defaultScopes: ["openid", "email", "profile"],
roles: ["identity"],
firstLogin: "requires_link",
oidc: true,
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",
displayName: "Joystick",
authorizationEndpoint: "https://joystick.tv/api/oauth/authorize",
tokenEndpoint: "https://api.joystick.tv/api/oauth/token",
tokenEndpointAuthMethod: "client_secret_basic",
rotatesRefreshTokens: true,
defaultAccessTokenLifetimeSeconds: 3600,
defaultScopes: ["identity:read", "stream:read", "chat:read", "followers:read", "subscribers:read"],
roles: ["identity", "managed_credential"],
firstLogin: "mints_account",
clientIdEnv: "GC_ACCESS_PROVIDER_JOYSTICK_CLIENT_ID",
clientSecretEnv: "GC_ACCESS_PROVIDER_JOYSTICK_CLIENT_SECRET_FILE",
}, },
}; };
/** 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: { export function buildAuthorizationUrl(options: {
provider: Provider; provider: Provider;
clientId: string; clientId: string;
redirectUri: string; redirectUri: string;
state: string; state: string;
requestedScopes: string[] | undefined; 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 { }): string {
const descriptor = providerCatalog[options.provider]; const descriptor = providerCatalog[options.provider];
const url = new URL(descriptor.authorizationEndpoint); 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("client_id", options.clientId);
url.searchParams.set("redirect_uri", options.redirectUri); url.searchParams.set("redirect_uri", options.redirectUri);
url.searchParams.set("response_type", "code"); url.searchParams.set("response_type", "code");
url.searchParams.set("scope", scopes.join(" ")); url.searchParams.set("scope", scopes.join(" "));
url.searchParams.set("state", options.state); url.searchParams.set("state", options.state);
if (descriptor.oidc) {
if (!options.oidc) {
throw new Error(`${descriptor.displayName} is an OIDC provider: its authorization URL needs a nonce and a PKCE challenge.`);
}
url.searchParams.set("nonce", options.oidc.nonce);
url.searchParams.set("code_challenge", options.oidc.codeChallenge);
url.searchParams.set("code_challenge_method", "S256");
}
for (const [key, value] of Object.entries(descriptor.additionalAuthorizationParams ?? {})) { for (const [key, value] of Object.entries(descriptor.additionalAuthorizationParams ?? {})) {
url.searchParams.set(key, value); 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(); return url.toString();
} }

View file

@ -19,8 +19,6 @@
import path from "node:path"; import path from "node:path";
import { createHash, createPrivateKey, type KeyObject } from "node:crypto"; import { createHash, createPrivateKey, type KeyObject } from "node:crypto";
import { readFileSync } from "node:fs";
import { readFile, writeFile, rename } from "node:fs/promises";
import { decode } from "@msgpack/msgpack"; import { decode } from "@msgpack/msgpack";
import { import {
@ -34,11 +32,14 @@ import {
type RuntimePresenceState, type RuntimePresenceState,
} from "cultnet-ts"; } from "cultnet-ts";
import type { HeimdallConfig } from "./config.js";
import { readIdunnStoreRecord } from "./idunn-store.js"; import { readIdunnStoreRecord } from "./idunn-store.js";
import { import {
openProviderHealthIdentity, openProviderHealthIdentity,
passedDescriptor, passedDescriptor,
readPassedDescriptor,
signWithIdentity, signWithIdentity,
type PrivateIdentity,
} from "./provider-health-identity.js"; } from "./provider-health-identity.js";
const PKCS8_ED25519_SEED_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex"); const PKCS8_ED25519_SEED_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
@ -178,70 +179,37 @@ export async function readRuntimeBundleFacts(bundlePath: string): Promise<Runtim
} }
/** /**
* Open the activation signing key Idunn passed as a descriptor. * The publisher sequence a process stamps on its presence statements.
* *
* The credential is exactly 32 bytes: the raw Ed25519 seed. It is passed as a * Odin compares `publisher_sequence` only against stored presence of the same
* parent-only descriptor and not as a path, so only the process Idunn launched * activation, and Idunn mints a fresh activation for every start, continuity
* can produce this half of the proof. * restarts included. So the sequence need only strictly increase within this
* process; nothing has to survive a restart, and nothing is written to the
* state root. Muninn derives its sequence the same way: the observation clock,
* never below the previous value plus one.
*/ */
export function openActivationSigner(env: NodeJS.ProcessEnv = process.env): KeyObject | undefined { export class PublisherSequence {
const descriptor = passedDescriptor(IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME, env); private last = 0;
if (descriptor === undefined) {
return undefined;
}
const seed = readFileSync(descriptor);
if (seed.length !== 32) {
throw new Error("Idunn runtime activation credential is not a 32-byte seed");
}
return createPrivateKey({
key: Buffer.concat([PKCS8_ED25519_SEED_PREFIX, seed]),
format: "der",
type: "pkcs8",
});
}
/** next(observedAtUnixMillis: number): number {
* The publisher sequence must strictly increase for the life of a signer if (!Number.isSafeInteger(observedAtUnixMillis)) {
* identity, because Idunn treats a repeat or a regression as a replay and throw new Error("observedAtUnixMillis is not a safe integer");
* refuses the observation.
*
* An in-process counter is therefore not enough: a restart would reset it and
* every statement afterwards would be refused until the count climbed past the
* old high-water mark. It lives beside the target's state instead, and is
* advanced before use.
*/
export async function nextPublisherSequence(sequencePath: string): Promise<number> {
let current = 0;
try {
const raw = (await readFile(sequencePath, "utf8")).trim();
const parsed = Number(raw);
if (Number.isSafeInteger(parsed) && parsed > 0) {
current = parsed;
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
throw error;
} }
this.last = Math.max(observedAtUnixMillis, this.last + 1);
return this.last;
} }
const next = current + 1;
// Written through a temporary file: a torn write here would look like a
// regression and cost the target every future observation.
const temporary = `${sequencePath}.next`;
await writeFile(temporary, `${next}\n`, { mode: 0o600 });
await rename(temporary, sequencePath);
return next;
} }
export interface PresenceStatementInputs { export interface PresenceStatementInputs {
bundle: RuntimeBundleFacts; bundle: RuntimeBundleFacts;
identity: PrivateIdentity;
activationKey: KeyObject;
state: RuntimePresenceState; state: RuntimePresenceState;
detail: string; detail: string;
boundEndpoint: string | null; boundEndpoint: string | null;
writeLeaseSha256: string | null; writeLeaseSha256: string | null;
observedAtUnixMillis: number; observedAtUnixMillis: number;
publisherSequence: number; publisherSequence: number;
providerHealthIdentityPath: string;
env?: NodeJS.ProcessEnv;
} }
export interface PresenceStatement { export interface PresenceStatement {
@ -250,24 +218,14 @@ export interface PresenceStatement {
} }
/** /**
* Build and dual-sign one presence statement. * Build and dual-sign one presence statement from keys and facts already open.
* *
* Returns the target alongside the bytes because the document key must equal * Returns the target alongside the bytes because the document key must equal
* the signed target; Odin refuses the pair when they differ, and that is the * the signed target; Odin refuses the pair when they differ, and that is the
* one part of the envelope the transport cannot infer. * one part of the envelope the transport cannot infer.
*/ */
export async function buildPresenceStatement( export function buildPresenceStatement(inputs: PresenceStatementInputs): PresenceStatement {
inputs: PresenceStatementInputs, const { identity } = inputs;
): Promise<PresenceStatement> {
const env = inputs.env ?? process.env;
const activationKey = openActivationSigner(env);
if (activationKey === undefined) {
throw new Error(
"Idunn passed no runtime activation credential, so this process cannot prove it is the " +
"incarnation Idunn started",
);
}
const identity = await openProviderHealthIdentity(inputs.providerHealthIdentityPath, env);
const presence: RuntimePresenceHealth = { const presence: RuntimePresenceHealth = {
target: inputs.bundle.target, target: inputs.bundle.target,
@ -295,7 +253,7 @@ export async function buildPresenceStatement(
const proof = runtimePresenceProofPayload(presence); const proof = runtimePresenceProofPayload(presence);
const signature = signWithIdentity(identity, runtimePresenceProviderSigningMessage(proof)); const signature = signWithIdentity(identity, runtimePresenceProviderSigningMessage(proof));
const activationSignature = signWithIdentity( const activationSignature = signWithIdentity(
{ ...identity, privateKey: activationKey }, { ...identity, privateKey: inputs.activationKey },
runtimePresenceActivationSigningMessage(proof), runtimePresenceActivationSigningMessage(proof),
); );
@ -304,3 +262,72 @@ export async function buildPresenceStatement(
payload: encodeRuntimePresenceHealth(presence, signature, activationSignature), payload: encodeRuntimePresenceHealth(presence, signature, activationSignature),
}; };
} }
export interface PresenceAuthority {
sign(
state: RuntimePresenceState,
detail: string,
observedAtUnixMillis: number,
): PresenceStatement;
}
/**
* Open everything this launch's presence statements stand on, once, before the
* process listens: Idunn's bundle facts, the activation seed and the presence
* identity (each descriptor is read whole and closed), and the one publisher
* sequence. It owns them for the life of the process; a pulse supplies only its
* state, detail and observation time.
*
* A launch-contract fault (a missing or malformed bundle, descriptor or
* identity) throws here, so the process exits before it accepts a request and
* Idunn fails Warming at once, instead of a listener that can never sign.
*/
export async function openPresenceAuthority(
config: Pick<HeimdallConfig, "idunnRuntimeBundlePath" | "host" | "port" | "providerHealthIdentityPath">,
env: NodeJS.ProcessEnv = process.env,
machineId?: () => Promise<string>,
): Promise<PresenceAuthority> {
if (!config.idunnRuntimeBundlePath) {
throw new Error("no Idunn runtime bundle path: presence has no launch to attest");
}
const bundle = await readRuntimeBundleFacts(config.idunnRuntimeBundlePath);
const activationDescriptor = passedDescriptor(IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME, env);
if (activationDescriptor === undefined) {
throw new Error(
"Idunn passed no runtime activation credential, so this process cannot prove it is the " +
"incarnation Idunn started",
);
}
const seed = readPassedDescriptor(activationDescriptor);
if (seed.length !== 32) {
throw new Error("Idunn runtime activation credential is not a 32-byte seed");
}
const activationKey = createPrivateKey({
key: Buffer.concat([PKCS8_ED25519_SEED_PREFIX, seed]),
format: "der",
type: "pkcs8",
});
const identity = await openProviderHealthIdentity(config.providerHealthIdentityPath, env, machineId);
const boundEndpoint = `http://${config.host}:${config.port}`;
const sequence = new PublisherSequence();
return {
sign: (state, detail, observedAtUnixMillis) =>
buildPresenceStatement({
bundle,
identity,
activationKey,
state,
detail,
boundEndpoint,
// A warming candidate holds no lease and must not claim one; the
// contract refuses the pair, and Idunn needs the warming statement to
// promote it.
writeLeaseSha256: null,
observedAtUnixMillis,
publisherSequence: sequence.next(observedAtUnixMillis),
}),
};
}

View file

@ -26,7 +26,7 @@ export interface RuntimeKeyMaterial {
privateKey: KeyObject; privateKey: KeyObject;
publicKey: KeyObject; publicKey: KeyObject;
publicJwk: PublicSigningJwk; publicJwk: PublicSigningJwk;
source: "configured_pem" | "configured_file" | "bootstrapped_file" | "ephemeral_dev"; source: "configured_file" | "bootstrapped_file" | "ephemeral_dev";
} }
function encodeBase64Url(input: string | Buffer): string { function encodeBase64Url(input: string | Buffer): string {
@ -56,8 +56,30 @@ function exportPrivateKeyPem(privateKey: KeyObject): string {
return typeof exported === "string" ? exported : exported.toString("utf8"); return typeof exported === "string" ? exported : exported.toString("utf8");
} }
const SIGNING_KEY_VARIABLE = "GC_ACCESS_SIGNING_PRIVATE_KEY_PATH";
/**
* Every signing-key failure names only the variable and an error code. It
* carries no path, no file contents and no cause, because Node prints an
* error's cause and properties along with its message.
*/
function signingKeyError(failure: string, error: unknown): Error {
const code = (error as NodeJS.ErrnoException | undefined)?.code ?? "error";
return new Error(`${SIGNING_KEY_VARIABLE} ${failure} (${code}).`);
}
function loadPrivateKeyFromPath(path: string): KeyObject { function loadPrivateKeyFromPath(path: string): KeyObject {
return createPrivateKey(readFileSync(path, "utf8")); let pem: string;
try {
pem = readFileSync(path, "utf8");
} catch (error) {
throw signingKeyError("could not be read", error);
}
try {
return createPrivateKey(pem);
} catch (error) {
throw signingKeyError("does not hold a usable private key", error);
}
} }
function createOrLoadPrivateKeyFromPath(config: HeimdallConfig): { function createOrLoadPrivateKeyFromPath(config: HeimdallConfig): {
@ -81,12 +103,16 @@ function createOrLoadPrivateKeyFromPath(config: HeimdallConfig): {
if (!config.bootstrapSigningPrivateKeyOnMissing) { if (!config.bootstrapSigningPrivateKeyOnMissing) {
throw new Error( throw new Error(
`Signing key file '${path}' does not exist. Set GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP=1 to create it on first boot.` `${SIGNING_KEY_VARIABLE} names no file (ENOENT). Set GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP=1 to create it on first boot.`
); );
} }
const privateKey = generateKeyPairSync("ed25519").privateKey; const privateKey = generateKeyPairSync("ed25519").privateKey;
mkdirSync(dirname(path), { recursive: true }); try {
mkdirSync(dirname(path), { recursive: true });
} catch (error) {
throw signingKeyError("could not be created", error);
}
try { try {
writeFileSync(path, exportPrivateKeyPem(privateKey), { writeFileSync(path, exportPrivateKeyPem(privateKey), {
encoding: "utf8", encoding: "utf8",
@ -99,7 +125,7 @@ function createOrLoadPrivateKeyFromPath(config: HeimdallConfig): {
}; };
} catch (error) { } catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") { if ((error as NodeJS.ErrnoException).code !== "EEXIST") {
throw error; throw signingKeyError("could not be created", error);
} }
return { return {
@ -110,12 +136,7 @@ function createOrLoadPrivateKeyFromPath(config: HeimdallConfig): {
} }
export function createRuntimeKeyMaterial(config: HeimdallConfig): RuntimeKeyMaterial { export function createRuntimeKeyMaterial(config: HeimdallConfig): RuntimeKeyMaterial {
const loaded = config.signingPrivateKeyPem const loaded = createOrLoadPrivateKeyFromPath(config);
? {
privateKey: createPrivateKey(config.signingPrivateKeyPem),
source: "configured_pem" as const,
}
: createOrLoadPrivateKeyFromPath(config);
const privateKey = loaded.privateKey; const privateKey = loaded.privateKey;
const publicKey = createPublicKey(privateKey); const publicKey = createPublicKey(privateKey);
const exportedJwk = publicKey.export({ format: "jwk" }) as Jwk; const exportedJwk = publicKey.export({ format: "jwk" }) as Jwk;

View file

@ -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<Provider>;
/** 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,
}));
}

View file

@ -3,13 +3,22 @@ import { type AppSlug, type LinkedIdentityInput, type Provider } from "../contra
import { import {
type CreateAccountInput, type CreateAccountInput,
type CreateAuthAttemptInput, type CreateAuthAttemptInput,
type ClaimOAuthStateUseInput,
OAUTH_STATE_PRUNE_BATCH,
oauthStatePruneCutoffMs,
type CreateAuthCompletionInput, type CreateAuthCompletionInput,
type CreateConsentReceiptInput,
type CreatePendingLinkInput,
type StoredConsentReceipt,
type StoredPendingLink,
type CreateAuditEventInput, type CreateAuditEventInput,
type CreateCapabilityGrantInput, type CreateCapabilityGrantInput,
type CredentialDecision,
type CreateEntitlementSnapshotInput, type CreateEntitlementSnapshotInput,
type CreateSessionInput, type CreateSessionInput,
type CreatePrivateCommandReceiptInput, type CreatePrivateCommandReceiptInput,
type HeimdallStore, type HeimdallStore,
IdentityHeldElsewhereError,
type StoredAccount, type StoredAccount,
type StoredAuthAttempt, type StoredAuthAttempt,
type StoredAuthCompletion, type StoredAuthCompletion,
@ -17,8 +26,13 @@ import {
type StoredLinkedIdentity, type StoredLinkedIdentity,
type StoredSession, type StoredSession,
type StoredPrivateCommandReceipt, type StoredPrivateCommandReceipt,
type MoveIdentitiesInput,
type MoveResult,
type StoredIdentityMove,
type UnlinkResult,
type UpsertLinkedIdentityInput, type UpsertLinkedIdentityInput,
} from "./types.js"; } from "./types.js";
import { decideMove, movedRecord } from "./identity-move.js";
function clone<T>(value: T): T { function clone<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T; return JSON.parse(JSON.stringify(value)) as T;
@ -37,6 +51,8 @@ function isGrantActive(grant: StoredCapabilityGrant, appSlug: AppSlug, at: strin
} }
export class InMemoryStore implements HeimdallStore { export class InMemoryStore implements HeimdallStore {
/** Tail of each linked identity's credential-decision chain; an entry is removed when it drains. */
private readonly credentialChains = new Map<string, Promise<unknown>>();
private readonly accounts = new Map<string, StoredAccount>(); private readonly accounts = new Map<string, StoredAccount>();
private readonly linkedIdentities = new Map<string, StoredLinkedIdentity>(); private readonly linkedIdentities = new Map<string, StoredLinkedIdentity>();
private readonly grants = new Map<string, StoredCapabilityGrant>(); private readonly grants = new Map<string, StoredCapabilityGrant>();
@ -44,9 +60,14 @@ export class InMemoryStore implements HeimdallStore {
private readonly authAttempts = new Map<string, StoredAuthAttempt>(); private readonly authAttempts = new Map<string, StoredAuthAttempt>();
private readonly privateCommandReceipts = new Map<string, StoredPrivateCommandReceipt>(); private readonly privateCommandReceipts = new Map<string, StoredPrivateCommandReceipt>();
private readonly authCompletions = new Map<string, StoredAuthCompletion>(); private readonly authCompletions = new Map<string, StoredAuthCompletion>();
private readonly pendingLinks = new Map<string, StoredPendingLink>();
private readonly authCompletionsByAttempt = new Map<string, string>(); private readonly authCompletionsByAttempt = new Map<string, string>();
/** `${jti}:${phase}` -> the state's expiresAt. */
private readonly oauthStateUses = new Map<string, string>();
private readonly entitlementSnapshots = new Map<string, CreateEntitlementSnapshotInput>(); private readonly entitlementSnapshots = new Map<string, CreateEntitlementSnapshotInput>();
private readonly auditEvents = new Map<string, CreateAuditEventInput>(); private readonly auditEvents = new Map<string, CreateAuditEventInput>();
private readonly consentReceipts: StoredConsentReceipt[] = [];
private readonly identityMoves = new Map<string, StoredIdentityMove>();
async ensureSchema(): Promise<void> { async ensureSchema(): Promise<void> {
return; return;
@ -134,6 +155,9 @@ export class InMemoryStore implements HeimdallStore {
const existing = [...this.linkedIdentities.values()].find( const existing = [...this.linkedIdentities.values()].find(
(identity) => identity.provider === input.provider && identity.providerUserId === input.providerUserId (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 id = existing?.id ?? input.id ?? randomUUID();
const linkedIdentity: StoredLinkedIdentity = { const linkedIdentity: StoredLinkedIdentity = {
id, id,
@ -174,6 +198,130 @@ export class InMemoryStore implements HeimdallStore {
return clone(linkedIdentity); return clone(linkedIdentity);
} }
async unlinkLinkedIdentity(accountId: string, identityId: string): Promise<UnlinkResult> {
const target = this.linkedIdentities.get(identityId);
if (!target || target.accountId !== accountId) return { kind: "not_found" };
const held = [...this.linkedIdentities.values()].filter((identity) => identity.accountId === accountId).length;
if (held <= 1) return { kind: "last_identity" };
this.linkedIdentities.delete(identityId);
return { kind: "unlinked", identity: clone(target) };
}
/** No await between the reads and the writes: the event loop is the lock. */
async moveIdentities(input: MoveIdentitiesInput): Promise<MoveResult> {
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<StoredIdentityMove | null> {
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<CredentialDecision>,
): Promise<StoredLinkedIdentity | null> {
const previous = this.credentialChains.get(id) ?? Promise.resolve();
const run = previous.then(async () => {
const current = this.linkedIdentities.get(id);
if (!current) {
return null;
}
const decision = await decide(clone(current));
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;
if (decision.kind === "rotate") {
next.accessTokenEncrypted = decision.accessTokenEncrypted;
next.refreshTokenEncrypted = decision.refreshTokenEncrypted;
next.tokenExpiresAt = decision.tokenExpiresAt;
next.scopes = [...decision.scopes];
}
this.linkedIdentities.set(id, clone(next));
return clone(next);
});
const tail = run.catch(() => undefined);
this.credentialChains.set(id, tail);
void tail.then(() => {
if (this.credentialChains.get(id) === tail) {
this.credentialChains.delete(id);
}
});
return run;
}
async listLinkedIdentitiesForAccount(accountId: string): Promise<LinkedIdentityInput[]> { async listLinkedIdentitiesForAccount(accountId: string): Promise<LinkedIdentityInput[]> {
return [...this.linkedIdentities.values()] return [...this.linkedIdentities.values()]
.filter((identity) => identity.accountId === accountId) .filter((identity) => identity.accountId === accountId)
@ -350,6 +498,7 @@ export class InMemoryStore implements HeimdallStore {
accountId: input.accountId, accountId: input.accountId,
sessionId: input.sessionId, sessionId: input.sessionId,
returnTo: input.returnTo, returnTo: input.returnTo,
...(input.targetId ? { targetId: input.targetId } : {}),
createdAt: input.createdAt, createdAt: input.createdAt,
expiresAt: input.expiresAt, expiresAt: input.expiresAt,
payloadJson: clone(input.payloadJson), payloadJson: clone(input.payloadJson),
@ -362,6 +511,11 @@ export class InMemoryStore implements HeimdallStore {
return clone(completion); return clone(completion);
} }
async findAuthCompletion(appSlug: AppSlug, code: string): Promise<StoredAuthCompletion | null> {
const completion = this.authCompletions.get(code);
return completion && completion.appSlug === appSlug ? clone(completion) : null;
}
async consumeAuthCompletion(appSlug: AppSlug, code: string, at: string): Promise<StoredAuthCompletion | null> { async consumeAuthCompletion(appSlug: AppSlug, code: string, at: string): Promise<StoredAuthCompletion | null> {
const completion = this.authCompletions.get(code); const completion = this.authCompletions.get(code);
if (!completion) { if (!completion) {
@ -384,6 +538,42 @@ export class InMemoryStore implements HeimdallStore {
return this.consumeAuthCompletion(appSlug, code, at); return this.consumeAuthCompletion(appSlug, code, at);
} }
async createPendingLink(input: CreatePendingLinkInput): Promise<StoredPendingLink> {
const link: StoredPendingLink = { id: randomUUID(), ...clone(input) };
this.pendingLinks.set(link.id, clone(link));
return clone(link);
}
async consumePendingLink(appSlug: AppSlug, id: string, accountId: string, at: string): Promise<StoredPendingLink | null> {
const link = this.pendingLinks.get(id);
if (!link || link.appSlug !== appSlug || link.accountId !== accountId || link.expiresAt <= at || link.consumedAt) {
return null;
}
link.consumedAt = at;
return clone(link);
}
async claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise<boolean> {
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;
}
async upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise<void> { async upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise<void> {
const key = `${input.accountId}:${input.provider}:${input.scope}`; const key = `${input.accountId}:${input.provider}:${input.scope}`;
this.entitlementSnapshots.set(key, clone(input)); this.entitlementSnapshots.set(key, clone(input));
@ -396,4 +586,22 @@ export class InMemoryStore implements HeimdallStore {
}); });
this.auditEvents.set(event.id ?? randomUUID(), event); this.auditEvents.set(event.id ?? randomUUID(), event);
} }
async createConsentReceipt(input: CreateConsentReceiptInput): Promise<{ receipt: StoredConsentReceipt; created: boolean }> {
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 };
}
const receipt = { id: randomUUID(), ...clone(input) } as StoredConsentReceipt;
this.consentReceipts.push(clone(receipt));
return { receipt: clone(receipt), created: true };
}
async listConsentReceipts(accountId: string): Promise<StoredConsentReceipt[]> {
return this.consentReceipts.filter((receipt) => receipt.accountId === accountId).map(clone);
}
} }

View file

@ -8,13 +8,37 @@ export { InMemoryStore } from "./in-memory.js";
export { PostgresStore, createPostgresStore } from "./postgres.js"; export { PostgresStore, createPostgresStore } from "./postgres.js";
export async function createStore(config: HeimdallConfig): Promise<HeimdallStore> { export async function createStore(config: HeimdallConfig): Promise<HeimdallStore> {
const store = if (config.storage.backend !== "postgres") {
config.storage.backend === "postgres" return new InMemoryStore();
? createPostgresStore(config.storage.databaseUrl ?? "postgres://127.0.0.1/heimdall") }
: new InMemoryStore();
if (config.storage.applySchemaOnStartup) { const store = createPostgresStore(config.storage.databaseUrl ?? "postgres://127.0.0.1/heimdall");
await store.ensureSchema(); try {
// Every start connects and proves the database can take its requests,
// whether or not it applied the schema first (CREATE ... IF NOT EXISTS
// leaves a damaged table as it is), so a misbound URL, an empty or
// damaged database, or a role that may not write fails here rather than
// in the first request.
if (config.storage.applySchemaOnStartup) {
await store.ensureSchema();
}
await store.checkSchema();
} catch (error) {
// pg's and Node's errors name the host, the database or the URL itself,
// and any of those can hold part of a secret that was bound or escaped
// wrongly. Startup prints this error, so it names only the input and a
// code, and carries no cause.
const code = (error as { code?: unknown }).code;
// A refused store is never handed out, so it is closed here: its pool
// would otherwise hold the connection open.
await store.close().catch(() => 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}.`);
} }
return store; return store;

View file

@ -1,17 +1,30 @@
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { Pool, type PoolClient, type QueryResultRow } from "pg"; import { Pool, type PoolClient, type QueryResultRow } from "pg";
import { type AppSlug, type HeimdallAuthAttemptStatus, type LinkedIdentityInput, type Provider } from "../contracts.js"; import { type AppSlug, type HeimdallAuthAttemptStatus, type LinkedIdentityInput, type Provider } from "../contracts.js";
import { CREATE_SCHEMA_SQL } from "./schema.js"; import { decideMove, movedRecord, type MoveFacts } from "./identity-move.js";
import { CREATE_SCHEMA_SQL, REQUIRED_COLUMNS, REQUIRED_KEYS, REQUIRED_TABLES } from "./schema.js";
import { import {
type CreateAccountInput, type CreateAccountInput,
type CreateAuthAttemptInput, type CreateAuthAttemptInput,
type ClaimOAuthStateUseInput,
type CreateAuthCompletionInput, type CreateAuthCompletionInput,
type CreateConsentReceiptInput,
type CreatePendingLinkInput,
type StoredConsentReceipt,
type StoredPendingLink,
type CreateAuditEventInput, type CreateAuditEventInput,
type CreateCapabilityGrantInput, type CreateCapabilityGrantInput,
type CredentialDecision,
type CreateEntitlementSnapshotInput, type CreateEntitlementSnapshotInput,
type CreateSessionInput, type CreateSessionInput,
type CreatePrivateCommandReceiptInput, type CreatePrivateCommandReceiptInput,
type HeimdallStore, type HeimdallStore,
IdentityHeldElsewhereError,
type MoveIdentitiesInput,
type MoveResult,
type StoredIdentityMove,
OAUTH_STATE_PRUNE_BATCH,
oauthStatePruneCutoffMs,
type StoredAccount, type StoredAccount,
type StoredAuthAttempt, type StoredAuthAttempt,
type StoredAuthCompletion, type StoredAuthCompletion,
@ -19,6 +32,7 @@ import {
type StoredLinkedIdentity, type StoredLinkedIdentity,
type StoredSession, type StoredSession,
type StoredPrivateCommandReceipt, type StoredPrivateCommandReceipt,
type UnlinkResult,
type UpsertLinkedIdentityInput, type UpsertLinkedIdentityInput,
} from "./types.js"; } from "./types.js";
@ -41,6 +55,7 @@ interface LinkedIdentityRow extends QueryResultRow {
access_token_encrypted: string | null; access_token_encrypted: string | null;
refresh_token_encrypted: string | null; refresh_token_encrypted: string | null;
token_expires_at: string | null; token_expires_at: string | null;
refresh_failed_at: string | null;
scopes: string; scopes: string;
profile_json: Record<string, unknown>; profile_json: Record<string, unknown>;
created_at: string; created_at: string;
@ -81,12 +96,26 @@ interface AuthCompletionRow extends QueryResultRow {
account_id: string; account_id: string;
session_id: string; session_id: string;
return_to: string; return_to: string;
target_id: string | null;
payload_json: Record<string, unknown>; payload_json: Record<string, unknown>;
created_at: string | Date; created_at: string | Date;
expires_at: string | Date; expires_at: string | Date;
consumed_at: string | Date | null; consumed_at: string | Date | null;
} }
interface PendingLinkRow extends QueryResultRow {
id: string;
app_slug: AppSlug;
account_id: string;
provider: Provider;
provider_user_id: string;
identity_json: StoredPendingLink["identity"];
return_to: string;
created_at: string | Date;
expires_at: string | Date;
consumed_at: string | Date | null;
}
interface AuthAttemptRow extends QueryResultRow { interface AuthAttemptRow extends QueryResultRow {
handle: string; handle: string;
app_slug: AppSlug; app_slug: AppSlug;
@ -150,6 +179,42 @@ function mapAccountRow(row: AccountRow): StoredAccount {
return account; 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<Pool, "query">, moveId: string): Promise<StoredIdentityMove | null> {
const result = await db.query<IdentityMoveRow>("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<Pool, "query">, accountId: string): Promise<boolean> {
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 { function mapLinkedIdentityRow(row: LinkedIdentityRow): StoredLinkedIdentity {
const identity: StoredLinkedIdentity = { const identity: StoredLinkedIdentity = {
id: row.id, id: row.id,
@ -158,8 +223,8 @@ function mapLinkedIdentityRow(row: LinkedIdentityRow): StoredLinkedIdentity {
providerUserId: row.provider_user_id, providerUserId: row.provider_user_id,
scopes: parseScopes(row.scopes), scopes: parseScopes(row.scopes),
profileJson: row.profile_json, profileJson: row.profile_json,
createdAt: row.created_at, createdAt: new Date(row.created_at).toISOString(),
updatedAt: row.updated_at, updatedAt: new Date(row.updated_at).toISOString(),
}; };
if (row.username) { if (row.username) {
@ -183,7 +248,12 @@ function mapLinkedIdentityRow(row: LinkedIdentityRow): StoredLinkedIdentity {
} }
if (row.token_expires_at) { if (row.token_expires_at) {
identity.tokenExpiresAt = row.token_expires_at; // pg hands back a Date for TIMESTAMPTZ whatever the row type says; the port promises ISO strings.
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; return identity;
@ -229,6 +299,59 @@ 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;
consent_text: 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 ?? "",
consentText: row.consent_text ?? "",
};
}
function mapPendingLinkRow(row: PendingLinkRow): StoredPendingLink {
const link: StoredPendingLink = {
id: row.id,
appSlug: row.app_slug,
accountId: row.account_id,
provider: row.provider,
providerUserId: row.provider_user_id,
identity: row.identity_json,
returnTo: row.return_to,
createdAt: normalizeTimestamp(row.created_at),
expiresAt: normalizeTimestamp(row.expires_at),
};
if (row.consumed_at) {
link.consumedAt = normalizeTimestamp(row.consumed_at);
}
return link;
}
function mapAuthCompletionRow(row: AuthCompletionRow): StoredAuthCompletion { function mapAuthCompletionRow(row: AuthCompletionRow): StoredAuthCompletion {
const completion: StoredAuthCompletion = { const completion: StoredAuthCompletion = {
code: row.code, code: row.code,
@ -247,6 +370,10 @@ function mapAuthCompletionRow(row: AuthCompletionRow): StoredAuthCompletion {
completion.attemptId = row.attempt_id; completion.attemptId = row.attempt_id;
} }
if (row.target_id) {
completion.targetId = row.target_id;
}
if (row.consumed_at) { if (row.consumed_at) {
completion.consumedAt = normalizeTimestamp(row.consumed_at); completion.consumedAt = normalizeTimestamp(row.consumed_at);
} }
@ -284,13 +411,291 @@ function mapAuthAttemptRow(row: AuthAttemptRow): StoredAuthAttempt {
return attempt; 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<Record<string, readonly ("SELECT" | "INSERT" | "UPDATE" | "DELETE")[]>> = {
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<Record<string, readonly string[]>>;
}
/** 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<Pool, "query">, requirements: SchemaRequirements): Promise<string[]> {
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<Pool, "query">, requirements: SchemaRequirements): Promise<void> {
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 { export class PostgresStore implements HeimdallStore {
constructor(private readonly pool: Pick<Pool, "query" | "end">) {} constructor(private readonly pool: Pick<Pool, "query" | "end" | "connect">) {}
async ensureSchema(): Promise<void> { async ensureSchema(): Promise<void> {
await this.pool.query(CREATE_SCHEMA_SQL); await this.pool.query(CREATE_SCHEMA_SQL);
} }
/** Proves, before Heimdall serves, that the database can take its requests (checkSchemaRequirements). */
async checkSchema(): Promise<void> {
await checkSchemaRequirements(this.pool, HEIMDALL_SCHEMA_REQUIREMENTS);
}
async close(): Promise<void> { async close(): Promise<void> {
await this.pool.end(); await this.pool.end();
} }
@ -423,16 +828,17 @@ export class PostgresStore implements HeimdallStore {
) )
ON CONFLICT (provider, provider_user_id) ON CONFLICT (provider, provider_user_id)
DO UPDATE SET DO UPDATE SET
account_id = EXCLUDED.account_id,
username = EXCLUDED.username, username = EXCLUDED.username,
display_name = EXCLUDED.display_name, display_name = EXCLUDED.display_name,
primary_email = EXCLUDED.primary_email, primary_email = EXCLUDED.primary_email,
access_token_encrypted = EXCLUDED.access_token_encrypted, access_token_encrypted = EXCLUDED.access_token_encrypted,
refresh_token_encrypted = EXCLUDED.refresh_token_encrypted, refresh_token_encrypted = EXCLUDED.refresh_token_encrypted,
token_expires_at = EXCLUDED.token_expires_at, token_expires_at = EXCLUDED.token_expires_at,
refresh_failed_at = NULL,
scopes = EXCLUDED.scopes, scopes = EXCLUDED.scopes,
profile_json = EXCLUDED.profile_json, profile_json = EXCLUDED.profile_json,
updated_at = EXCLUDED.updated_at updated_at = EXCLUDED.updated_at
WHERE linked_identities.account_id = EXCLUDED.account_id
RETURNING * RETURNING *
`, `,
[ [
@ -453,7 +859,221 @@ 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<UnlinkResult> {
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<LinkedIdentityRow>(
"DELETE FROM linked_identities WHERE id = $2 AND account_id = $1 RETURNING *",
[accountId, identityId]
);
result = deleted.rows[0] ? { kind: "unlinked", identity: mapLinkedIdentityRow(deleted.rows[0]) } : { kind: "not_found" };
}
await client.query("COMMIT");
return result;
} catch (error) {
await client.query("ROLLBACK");
throw error;
}
} finally {
client.release();
}
}
async moveIdentities(input: MoveIdentitiesInput): Promise<MoveResult> {
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<LinkedIdentityRow>(
"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<StoredIdentityMove | null> {
return selectIdentityMove(this.pool, moveId);
}
async updateLinkedIdentityCredential(
id: string,
decide: (locked: StoredLinkedIdentity) => Promise<CredentialDecision>,
): Promise<StoredLinkedIdentity | null> {
const client = await this.pool.connect();
try {
await client.query("BEGIN");
let decision: CredentialDecision | undefined;
try {
const locked = await client.query<LinkedIdentityRow>(
"SELECT * FROM linked_identities WHERE id = $1 FOR UPDATE",
[id]
);
if (!locked.rowCount) {
await client.query("COMMIT");
return null;
}
const row = mapLinkedIdentityRow(expectRow(locked.rows[0], "updateLinkedIdentityCredential"));
decision = await decide(row);
let committed = row;
if (decision.kind === "failed") {
const marked = await client.query<LinkedIdentityRow>(
"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<LinkedIdentityRow>(
`
UPDATE linked_identities
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
RETURNING *
`,
[
id,
nullable(rotated?.accessTokenEncrypted),
nullable(rotated?.refreshTokenEncrypted),
nullable(rotated?.tokenExpiresAt),
(rotated?.scopes ?? row.scopes).join(" "),
decision.updatedAt,
]
);
committed = mapLinkedIdentityRow(expectRow(written.rows[0], "updateLinkedIdentityCredential"));
}
await client.query("COMMIT");
return committed;
} catch (error) {
await client.query("ROLLBACK");
if (decision?.kind === "rotate" || decision?.kind === "revoke") {
// 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 ${spent ? "refresh_token_encrypted = NULL, " : ""}refresh_failed_at = $2 WHERE id = $1`,
[id, decision.updatedAt]
)
.catch(() => undefined);
}
throw error;
}
} finally {
client.release();
}
} }
async listLinkedIdentitiesForAccount(accountId: string): Promise<LinkedIdentityInput[]> { async listLinkedIdentitiesForAccount(accountId: string): Promise<LinkedIdentityInput[]> {
@ -682,9 +1302,9 @@ export class PostgresStore implements HeimdallStore {
` `
INSERT INTO auth_completions ( INSERT INTO auth_completions (
code, attempt_id, app_slug, provider, mode, account_id, session_id, code, attempt_id, app_slug, provider, mode, account_id, session_id,
return_to, payload_json, created_at, expires_at return_to, target_id, payload_json, created_at, expires_at
) )
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
RETURNING * RETURNING *
`, `,
[ [
@ -696,6 +1316,7 @@ export class PostgresStore implements HeimdallStore {
input.accountId, input.accountId,
input.sessionId, input.sessionId,
input.returnTo, input.returnTo,
input.targetId ?? null,
JSON.stringify(input.payloadJson), JSON.stringify(input.payloadJson),
input.createdAt, input.createdAt,
input.expiresAt, input.expiresAt,
@ -705,6 +1326,14 @@ export class PostgresStore implements HeimdallStore {
return mapAuthCompletionRow(expectRow(result.rows[0], "createAuthCompletion")); return mapAuthCompletionRow(expectRow(result.rows[0], "createAuthCompletion"));
} }
async findAuthCompletion(appSlug: AppSlug, code: string): Promise<StoredAuthCompletion | null> {
const result = await this.pool.query<AuthCompletionRow>(
"SELECT * FROM auth_completions WHERE code = $1 AND app_slug = $2",
[code, appSlug]
);
return result.rowCount ? mapAuthCompletionRow(expectRow(result.rows[0], "findAuthCompletion")) : null;
}
async consumeAuthCompletion(appSlug: AppSlug, code: string, at: string): Promise<StoredAuthCompletion | null> { async consumeAuthCompletion(appSlug: AppSlug, code: string, at: string): Promise<StoredAuthCompletion | null> {
const result = await this.pool.query<AuthCompletionRow>( const result = await this.pool.query<AuthCompletionRow>(
` `
@ -739,6 +1368,78 @@ export class PostgresStore implements HeimdallStore {
return result.rowCount ? mapAuthCompletionRow(expectRow(result.rows[0], "consumeAuthCompletionByAttempt")) : null; return result.rowCount ? mapAuthCompletionRow(expectRow(result.rows[0], "consumeAuthCompletionByAttempt")) : null;
} }
async createPendingLink(input: CreatePendingLinkInput): Promise<StoredPendingLink> {
const result = await this.pool.query<PendingLinkRow>(
`
INSERT INTO pending_links (
id, app_slug, account_id, provider, provider_user_id, identity_json,
return_to, created_at, expires_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING *
`,
[
randomUUID(),
input.appSlug,
input.accountId,
input.provider,
input.providerUserId,
JSON.stringify(input.identity),
input.returnTo,
input.createdAt,
input.expiresAt,
]
);
return mapPendingLinkRow(expectRow(result.rows[0], "createPendingLink"));
}
async consumePendingLink(appSlug: AppSlug, id: string, accountId: string, at: string): Promise<StoredPendingLink | null> {
const result = await this.pool.query<PendingLinkRow>(
`
UPDATE pending_links
SET consumed_at = $4
WHERE id = $1
AND app_slug = $2
AND account_id = $3
AND consumed_at IS NULL
AND expires_at > $4
RETURNING *
`,
[id, appSlug, accountId, at]
);
return result.rowCount ? mapPendingLinkRow(expectRow(result.rows[0], "consumePendingLink")) : null;
}
async claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise<boolean> {
// 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)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT DO NOTHING
`,
[input.jti, input.phase, input.appSlug, input.usedAt, input.expiresAt]
);
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<void> { async upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise<void> {
await this.pool.query( await this.pool.query(
` `
@ -769,6 +1470,52 @@ export class PostgresStore implements HeimdallStore {
); );
} }
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<ConsentReceiptRow>(
`
INSERT INTO consent_receipts (
id, kind, account_id, app_slug, provider, created_at,
scopes_asked, scopes_granted, consent_page_digest, consent_text, revokes_receipt_id
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
ON CONFLICT DO NOTHING
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,
grant ? grant.consentText : null,
input.kind === "revocation" ? input.revokesReceiptId : null,
]
);
if (result.rowCount) {
return { receipt: mapConsentReceiptRow(expectRow(result.rows[0], "createConsentReceipt")), created: true };
}
const existing = await this.pool.query<ConsentReceiptRow>(
`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<StoredConsentReceipt[]> {
const result = await this.pool.query<ConsentReceiptRow>(
`SELECT * FROM consent_receipts WHERE account_id = $1 ORDER BY created_at, id`,
[accountId]
);
return result.rows.map(mapConsentReceiptRow);
}
async createAuditEvent(input: CreateAuditEventInput): Promise<void> { async createAuditEvent(input: CreateAuditEventInput): Promise<void> {
await this.pool.query( await this.pool.query(
` `
@ -791,9 +1538,21 @@ export class PostgresStore implements HeimdallStore {
} }
} }
export function createPostgresStore(databaseUrl: string): HeimdallStore { export function createPostgresStore(databaseUrl: string): PostgresStore {
const pool = new Pool({ const pool = new Pool({
connectionString: databaseUrl, connectionString: databaseUrl,
}); });
// An idle client whose connection ends (a database restart, an
// administrator terminating the backend) is emitted here. Unheard, the
// event kills the process and Node prints the pg Client, connection
// parameters included. The pool has already dropped the dead client and
// opens a new one on the next query, so this only says what happened, by
// code.
pool.on("error", (error) => {
const code = (error as { code?: unknown }).code;
console.error(
`Heimdall lost an idle Postgres connection (${typeof code === "string" ? code : "error"}); the pool reconnects on the next query.`
);
});
return new PostgresStore(pool); return new PostgresStore(pool);
} }

View file

@ -82,6 +82,19 @@ CREATE TABLE IF NOT EXISTS private_command_receipts (
CREATE INDEX IF NOT EXISTS private_command_receipts_expiry_idx CREATE INDEX IF NOT EXISTS private_command_receipts_expiry_idx
ON private_command_receipts(expires_at); ON private_command_receipts(expires_at);
CREATE TABLE IF NOT EXISTS pending_links (
id TEXT PRIMARY KEY,
app_slug TEXT NOT NULL,
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
provider TEXT NOT NULL,
provider_user_id TEXT NOT NULL,
identity_json JSONB NOT NULL,
return_to TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
expires_at TIMESTAMPTZ NOT NULL,
consumed_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS auth_completions ( CREATE TABLE IF NOT EXISTS auth_completions (
code TEXT PRIMARY KEY, code TEXT PRIMARY KEY,
app_slug TEXT NOT NULL, app_slug TEXT NOT NULL,
@ -106,6 +119,15 @@ CREATE INDEX IF NOT EXISTS auth_completions_lookup_idx
-- redeem the completion it created without ever needing the code. -- redeem the completion it created without ever needing the code.
ALTER TABLE auth_completions ADD COLUMN IF NOT EXISTS attempt_id TEXT; ALTER TABLE auth_completions ADD COLUMN IF NOT EXISTS attempt_id TEXT;
-- The connection target the signed state named (connection.targetId). Redeem
-- 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 -- 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 -- second completion for the same handle would let the by-attempt UPDATE in
-- consumeAuthCompletionByAttempt match more than one row, silently consuming -- consumeAuthCompletionByAttempt match more than one row, silently consuming
@ -119,6 +141,23 @@ CREATE UNIQUE INDEX IF NOT EXISTS auth_completions_attempt_unconsumed_unique_idx
ON auth_completions(app_slug, attempt_id) ON auth_completions(app_slug, attempt_id)
WHERE attempt_id IS NOT NULL AND consumed_at IS NULL; WHERE attempt_id IS NOT NULL AND consumed_at IS NULL;
-- 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. 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,
app_slug TEXT NOT NULL,
used_at TIMESTAMPTZ NOT NULL,
expires_at TIMESTAMPTZ NOT NULL,
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 ( CREATE TABLE IF NOT EXISTS capability_grants (
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
@ -149,6 +188,57 @@ CREATE TABLE IF NOT EXISTS entitlement_snapshots (
UNIQUE(account_id, provider, scope) 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,
consent_text TEXT,
revokes_receipt_id TEXT,
UNIQUE(id, account_id),
FOREIGN KEY (revokes_receipt_id, account_id) REFERENCES consent_receipts(id, account_id)
);
-- 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;
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 ( CREATE TABLE IF NOT EXISTS audit_events (
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
account_id TEXT, account_id TEXT,
@ -162,3 +252,86 @@ CREATE TABLE IF NOT EXISTS audit_events (
CREATE INDEX IF NOT EXISTS audit_events_lookup_idx CREATE INDEX IF NOT EXISTS audit_events_lookup_idx
ON audit_events(account_id, session_id, app_slug, created_at); 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(),
})),
];

View file

@ -33,12 +33,86 @@ export interface StoredLinkedIdentity {
accessTokenEncrypted?: string; accessTokenEncrypted?: string;
refreshTokenEncrypted?: string; refreshTokenEncrypted?: string;
tokenExpiresAt?: string; tokenExpiresAt?: string;
/** When a refresh attempt last failed; cleared by the next rotation, revocation or re-link. */
refreshFailedAt?: string;
scopes: string[]; scopes: string[];
profileJson: Record<string, unknown>; profileJson: Record<string, unknown>;
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
} }
/**
* An upsert named an identity another account holds. A provider identity
* belongs to the account that holds it until that account unlinks it; no
* write moves it.
*/
export class IdentityHeldElsewhereError extends Error {
constructor() {
super("This provider identity is held by another account.");
this.name = "IdentityHeldElsewhereError";
}
}
/** What unlinkLinkedIdentity decided; `identity` is the row as it was deleted. */
export type UnlinkResult =
| { kind: "unlinked"; identity: StoredLinkedIdentity }
| { kind: "last_identity" }
| { kind: "not_found" };
/** One login a move carried; `credentialStripped` is history written at the move (the row held a token the move dropped). */
export interface MovedIdentity {
id: string;
provider: Provider;
providerUserId: string;
credentialStripped: boolean;
}
/** What each side's proofs were, as tiers and methods only: never a token, sid, email or name. */
export interface IdentityMoveProof {
from: { tier: "strong" | "weak"; method: string | null; identityId: string | null }[];
to: { tier: "strong" | "weak"; method: string | null; identityId: string | null } | null;
}
/** The append-only record of one move. */
export interface StoredIdentityMove {
id: string;
appSlug: AppSlug;
fromAccountId: string;
toAccountId: string;
reversesMoveId?: string;
moved: MovedIdentity[];
proof: IdentityMoveProof;
createdAt: string;
}
export interface MoveIdentitiesInput {
moveId: string;
appSlug: AppSlug;
fromAccountId: string;
toAccountId: string;
/** The logins to carry, or every login the source holds. */
identityIds: readonly string[] | "all";
/** What the caller's from-proofs cover: the whole account, or exactly these logins. */
covers: "account" | readonly string[];
/** Sessions the proofs rested on; each must still be live when the transaction commits. */
proofSessions: readonly { appSlug: AppSlug; sessionId: string; accountId: string; accessRevision: number }[];
reversesMoveId?: string;
proof: IdentityMoveProof;
at: string;
}
/** What moveIdentities decided. Refusals write nothing. */
export type MoveResult =
| { kind: "moved"; move: StoredIdentityMove }
| { kind: "replayed"; move: StoredIdentityMove }
| { kind: "move_id_conflict" }
| { kind: "proof_lapsed" }
| { kind: "already_moved" }
| { kind: "identity_not_found" }
| { kind: "identity_not_proved" }
| { kind: "provider_conflict"; provider: Provider }
| { kind: "not_reversible" };
export interface UpsertLinkedIdentityInput { export interface UpsertLinkedIdentityInput {
id?: string; id?: string;
accountId: string; accountId: string;
@ -56,6 +130,27 @@ export interface UpsertLinkedIdentityInput {
updatedAt: string; updatedAt: string;
} }
/**
* What the owner of a refresh decides after reading the row under its lock.
* `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" }
| {
kind: "rotate";
accessTokenEncrypted: string;
refreshTokenEncrypted: string;
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 };
export interface StoredSession { export interface StoredSession {
id: string; id: string;
accountId: string; accountId: string;
@ -142,18 +237,46 @@ export interface StoredAuthCompletion {
accountId: string; accountId: string;
sessionId: string; sessionId: string;
returnTo: string; returnTo: string;
/** The connection target the signed state named, if any; compared at redeem. */
targetId?: string;
createdAt: string; createdAt: string;
expiresAt: string; expiresAt: string;
consumedAt?: string; consumedAt?: string;
payloadJson: Record<string, unknown>; payloadJson: Record<string, unknown>;
} }
/** 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;
/** `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;
}
export interface CreateAuthCompletionInput { export interface CreateAuthCompletionInput {
/** /**
* Correlation handle only (see StoredAuthCompletion.attemptId). The store * Correlation handle only (see StoredAuthCompletion.attemptId). The store
* always mints `code` itself; a caller cannot choose it. * always mints `code` itself; a caller cannot choose it.
*/ */
attemptId?: string; attemptId?: string;
targetId?: string;
appSlug: AppSlug; appSlug: AppSlug;
provider: Provider; provider: Provider;
mode: OAuthMode; mode: OAuthMode;
@ -165,6 +288,28 @@ export interface CreateAuthCompletionInput {
payloadJson: Record<string, unknown>; payloadJson: Record<string, unknown>;
} }
/**
* A link the callback has verified but not written. The identity attaches to
* `accountId` (the account whose Heimdall access token began the link) only
* when that same account confirms it; until then no linked-identity row
* exists. `identity` holds the already-encrypted row to write.
*/
export interface StoredPendingLink {
id: string;
appSlug: AppSlug;
accountId: string;
provider: Provider;
providerUserId: string;
identity: UpsertLinkedIdentityInput;
returnTo: string;
createdAt: string;
expiresAt: string;
consumedAt?: string;
}
/** The store mints `id`; a caller cannot choose it. */
export type CreatePendingLinkInput = Omit<StoredPendingLink, "id" | "consumedAt">;
export interface StoredAuthAttempt { export interface StoredAuthAttempt {
handle: string; handle: string;
appSlug: AppSlug; appSlug: AppSlug;
@ -202,6 +347,33 @@ export interface StoredPrivateCommandReceipt {
export type CreatePrivateCommandReceiptInput = 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 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;
accountId: string;
appSlug: AppSlug;
provider: Provider;
createdAt: string;
} & (
| { kind: "grant"; scopesAsked: string[]; scopesGranted: string[]; consentPageDigest: string; consentText: 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<R, "id">
: never
: never;
export interface HeimdallStore { export interface HeimdallStore {
ensureSchema(): Promise<void>; ensureSchema(): Promise<void>;
close(): Promise<void>; close(): Promise<void>;
@ -212,7 +384,37 @@ export interface HeimdallStore {
findStoredLinkedIdentity(provider: Provider, providerUserId: string): Promise<StoredLinkedIdentity | null>; findStoredLinkedIdentity(provider: Provider, providerUserId: string): Promise<StoredLinkedIdentity | null>;
findStoredLinkedIdentityForAccount(accountId: string, provider: Provider): Promise<StoredLinkedIdentity | null>; findStoredLinkedIdentityForAccount(accountId: string, provider: Provider): Promise<StoredLinkedIdentity | null>;
listStoredLinkedIdentitiesForAccount(accountId: string): Promise<StoredLinkedIdentity[]>; listStoredLinkedIdentitiesForAccount(accountId: string): Promise<StoredLinkedIdentity[]>;
/** Writes the holder's own row; throws IdentityHeldElsewhereError rather than move another account's identity. */
upsertLinkedIdentity(input: UpsertLinkedIdentityInput): Promise<StoredLinkedIdentity>; upsertLinkedIdentity(input: UpsertLinkedIdentityInput): Promise<StoredLinkedIdentity>;
/**
* 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<UnlinkResult>;
/**
* 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<MoveResult>;
findIdentityMove(moveId: string): Promise<StoredIdentityMove | null>;
/**
* 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
* committed before this resolves, so a rotated pair is persisted before any
* caller sees the new access token. Returns the committed row, or null when
* no row has that id. A throw from `decide` writes nothing.
*/
updateLinkedIdentityCredential(
id: string,
decide: (locked: StoredLinkedIdentity) => Promise<CredentialDecision>,
): Promise<StoredLinkedIdentity | null>;
listLinkedIdentitiesForAccount(accountId: string): Promise<LinkedIdentityInput[]>; listLinkedIdentitiesForAccount(accountId: string): Promise<LinkedIdentityInput[]>;
createCapabilityGrant(input: CreateCapabilityGrantInput): Promise<StoredCapabilityGrant>; createCapabilityGrant(input: CreateCapabilityGrantInput): Promise<StoredCapabilityGrant>;
listActiveGrants(accountId: string, appSlug: AppSlug, at: string): Promise<StoredCapabilityGrant[]>; listActiveGrants(accountId: string, appSlug: AppSlug, at: string): Promise<StoredCapabilityGrant[]>;
@ -235,6 +437,8 @@ export interface HeimdallStore {
createPrivateCommandReceipt(input: CreatePrivateCommandReceiptInput): Promise<StoredPrivateCommandReceipt>; createPrivateCommandReceipt(input: CreatePrivateCommandReceiptInput): Promise<StoredPrivateCommandReceipt>;
findPrivateCommandReceipt(appSlug: AppSlug, idempotencyKey: string): Promise<StoredPrivateCommandReceipt | null>; findPrivateCommandReceipt(appSlug: AppSlug, idempotencyKey: string): Promise<StoredPrivateCommandReceipt | null>;
createAuthCompletion(input: CreateAuthCompletionInput): Promise<StoredAuthCompletion>; createAuthCompletion(input: CreateAuthCompletionInput): Promise<StoredAuthCompletion>;
/** Read a completion without consuming it, so redeem can refuse a mismatch without burning the code. */
findAuthCompletion(appSlug: AppSlug, code: string): Promise<StoredAuthCompletion | null>;
consumeAuthCompletion(appSlug: AppSlug, code: string, at: string): Promise<StoredAuthCompletion | null>; consumeAuthCompletion(appSlug: AppSlug, code: string, at: string): Promise<StoredAuthCompletion | null>;
/** /**
* Consume a completion by its correlated attempt handle instead of its * Consume a completion by its correlated attempt handle instead of its
@ -243,6 +447,27 @@ export interface HeimdallStore {
* it created without ever needing to know (or forge) the code. * it created without ever needing to know (or forge) the code.
*/ */
consumeAuthCompletionByAttempt(appSlug: AppSlug, attemptId: string, at: string): Promise<StoredAuthCompletion | null>; consumeAuthCompletionByAttempt(appSlug: AppSlug, attemptId: string, at: string): Promise<StoredAuthCompletion | null>;
createPendingLink(input: CreatePendingLinkInput): Promise<StoredPendingLink>;
/**
* Single-use redemption: returns the link only for the app and the account
* it was begun by, before it expires and once. A mismatch returns null and
* leaves the link unconsumed.
*/
consumePendingLink(appSlug: AppSlug, id: string, accountId: string, at: string): Promise<StoredPendingLink | null>;
upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise<void>; upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise<void>;
/**
* Claim one use of a signed OAuth state: true only for the first claim of
* (jti, phase), false for every later one. Without it a state is a bearer
* token any number of browsers can complete, so an attacker who learns a
* victim's state completes it as themselves and hands the victim a code
* for the attacker's account. `expiresAt` is the state's own expiry; the
* state is refused at that time before any claim, so the record is dead
* after it and a store may drop it.
*/
claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise<boolean>;
createAuditEvent(input: CreateAuditEventInput): Promise<void>; createAuditEvent(input: CreateAuditEventInput): Promise<void>;
/** `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<StoredConsentReceipt[]>;
} }

View file

@ -12,6 +12,15 @@
"docs/implementation-plan.md" "docs/implementation-plan.md"
], ],
"notes": "Current mainline. Repixelizer is the first auth-blank binding target; StreamPixels is the migration and boundary stress test." "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."
} }
] ]
} }

View file

@ -35,3 +35,9 @@
{"ts":"2026-08-22T02:01:00+00:00","type":"deployment","status":"accepted","note":"Yggdrasil runs Heimdall 1086aee01169bf60e8a492b2740db1c6f3e8cabf with CultLib 5cefa0db0079a8e3ee22f29d7b9e6e5aa60912a9. Odin b4f9a2e95f0b41cebdeddc49223781d1d3c7b42a returns Heimdall's provider, command boundary, Eve plugin, and transport profile under unique catalog keys. Ghostlight b515ca90c25573005a616244143803b37f2d06ec accepted canonical auth.begin through the Odin-resolved boundary; only advertised Discord and Heimdall navigation origins reached the browser."} {"ts":"2026-08-22T02:01:00+00:00","type":"deployment","status":"accepted","note":"Yggdrasil runs Heimdall 1086aee01169bf60e8a492b2740db1c6f3e8cabf with CultLib 5cefa0db0079a8e3ee22f29d7b9e6e5aa60912a9. Odin b4f9a2e95f0b41cebdeddc49223781d1d3c7b42a returns Heimdall's provider, command boundary, Eve plugin, and transport profile under unique catalog keys. Ghostlight b515ca90c25573005a616244143803b37f2d06ec accepted canonical auth.begin through the Odin-resolved boundary; only advertised Discord and Heimdall navigation origins reached the browser."}
{"ts": "2026-09-06T22:12:03+00:00", "type": "design", "status": "accepted", "note": "App slugs are no longer compile-time. AppSlug is a string; membership is a registry lookup, or isAppSlug shape validation where no store is reachable (the offline verifier). Capability rules are data (anyOf over Heimdall's own fact vocabulary), replacing a per-profile evaluateSharedCapabilities function that could not be accepted from a stranger. POST /v1/apps registers in RFC 7591 shape, gated on GC_ACCESS_APP_REGISTRATION_SECRET and closed until it is set. Built-in slugs are reserved so a registration cannot shadow a shipped app's audience. Motivation: a creator self-hosting Erycina alongside Heimdall would otherwise maintain a patched auth server to add one slug."} {"ts": "2026-09-06T22:12:03+00:00", "type": "design", "status": "accepted", "note": "App slugs are no longer compile-time. AppSlug is a string; membership is a registry lookup, or isAppSlug shape validation where no store is reachable (the offline verifier). Capability rules are data (anyOf over Heimdall's own fact vocabulary), replacing a per-profile evaluateSharedCapabilities function that could not be accepted from a stranger. POST /v1/apps registers in RFC 7591 shape, gated on GC_ACCESS_APP_REGISTRATION_SECRET and closed until it is set. Built-in slugs are reserved so a registration cannot shadow a shipped app's audience. Motivation: a creator self-hosting Erycina alongside Heimdall would otherwise maintain a patched auth server to add one slug."}
{"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 -> <slug>.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-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 -> <slug>.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)."}
{"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:<name>; 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"}

View file

@ -59,13 +59,14 @@ data_flow:
- reject per-request auth round-trip chatter - reject per-request auth round-trip chatter
active_subgoals: active_subgoals:
- Pressure the deployed Ghostlight gamecult.heimdall.access integration with two- and eight-account human canaries. - 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. - Keep the shared architecture explicit and separate from app profiles.
- Preserve the default boundary that app-domain data remains app-owned. - Preserve the default boundary that app-domain data remains app-owned.
- Align the plan to Heimdall as a Yggdrasil-hosted authority service. - 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. - 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. - 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 viewer identity and managed creator-provider credentials without moving StreamPixels domain state into Heimdall. - 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: accepted_design:
- `gamecult.heimdall.access` owns access-gate representation and browser navigation semantics; it has no access-grant or provider-state authority. - `gamecult.heimdall.access` owns access-gate representation and browser navigation semantics; it has no access-grant or provider-state authority.
@ -94,7 +95,7 @@ accepted_design:
landed_baseline: 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. - 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 1086aee01169bf60e8a492b2740db1c6f3e8cabf with CultLib 5cefa0db0079a8e3ee22f29d7b9e6e5aa60912a9; live Ghostlight auth.begin through Odin discovery is accepted. - 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. - 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. - 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. - Shared architecture extracted into its own repo and renamed to Heimdall.
@ -125,5 +126,5 @@ rejected_paths:
reason: reusing auth mechanics does not justify centralizing app-domain audience or product data reason: reusing auth mechanics does not justify centralizing app-domain audience or product data
current_status: current_status:
summary: Yggdrasil runs the gamecult.heimdall.access plugin and encrypted loopback begin, complete, refresh, and logout plane at 1086aee01169bf60e8a492b2740db1c6f3e8cabf. Odin returns all four redacted discovery records, Ghostlight resolves the boundary through Odin, and live anonymous auth.begin is accepted without exposing claims or secrets. 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 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. 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.

View file

@ -8,6 +8,7 @@ import { entitlementFacts } from "../src/facts.js";
import { startHeimdallPrivateCommandPlane } from "../src/private-command-plane.js"; import { startHeimdallPrivateCommandPlane } from "../src/private-command-plane.js";
import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "../src/private-command-security.js"; import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "../src/private-command-security.js";
import { type OAuthProviderRuntime } from "../src/oauth.js"; import { type OAuthProviderRuntime } from "../src/oauth.js";
import { launchState } from "./oauth-flow.js";
const secret = "ghostlight-private-command-secret"; const secret = "ghostlight-private-command-secret";
const resources: Array<{ close(): Promise<unknown> }> = []; const resources: Array<{ close(): Promise<unknown> }> = [];
@ -107,9 +108,12 @@ describe("Heimdall Eve access plugin", () => {
const begin = openPrivateEnvelope(beginWire, secret); const begin = openPrivateEnvelope(beginWire, secret);
expect(begin.schema).toBe("heimdall.auth_begin_receipt.v1"); expect(begin.schema).toBe("heimdall.auth_begin_receipt.v1");
const handle = String(begin.handle); const handle = String(begin.handle);
const navigation = begin.navigation as { url: string }; const navigation = begin.navigation as { url: string; allowedOrigins: string[] };
const state = new URL(navigation.url).searchParams.get("state"); const state = new URL(navigation.url).searchParams.get("state");
expect(state).toBeTruthy(); expect(state).toBeTruthy();
// The browser goes to Heimdall's launch hop first, and only Heimdall's origin is allowed.
expect(navigation.url.startsWith("https://heimdall.gamecult.org/v1/oauth/discord/launch?state=")).toBe(true);
expect(navigation.allowedOrigins).toEqual(["https://heimdall.gamecult.org"]);
const pendingEnvelope = sealPrivateEnvelope({ const pendingEnvelope = sealPrivateEnvelope({
appSlug: "ghostlight", appSlug: "ghostlight",
@ -124,9 +128,11 @@ describe("Heimdall Eve access plugin", () => {
const pending = openPrivateEnvelope(decodeEnvelope(pendingResponse.payload), secret); const pending = openPrivateEnvelope(decodeEnvelope(pendingResponse.payload), secret);
expect(pending).toMatchObject({ status: "pending", handle }); expect(pending).toMatchObject({ status: "pending", handle });
const { cookie } = await launchState(app, state ?? "");
const callback = await app.inject({ const callback = await app.inject({
method: "GET", method: "GET",
url: `/v1/oauth/discord/callback?code=test-code&state=${encodeURIComponent(state ?? "")}`, url: `/v1/oauth/discord/callback?code=test-code&state=${encodeURIComponent(state ?? "")}`,
headers: { cookie },
}); });
expect(callback.statusCode, callback.body).toBe(201); expect(callback.statusCode, callback.body).toBe(201);
// The completion code is always minted by the store now, never the // The completion code is always minted by the store now, never the
@ -291,7 +297,7 @@ function testConfig(): HeimdallConfig {
storage: { backend: "memory", applySchemaOnStartup: true }, storage: { backend: "memory", applySchemaOnStartup: true },
providers: { providers: {
discord: { clientId: "discord-client", clientSecret: "discord-secret" }, discord: { clientId: "discord-client", clientSecret: "discord-secret" },
patreon: {}, github: {}, twitch: {}, youtube: {}, spotify: {}, patreon: {}, github: {}, twitch: {}, youtube: {}, spotify: {}, joystick: {}, google: {},
}, },
}; };
} }

File diff suppressed because it is too large Load diff

View file

@ -24,6 +24,7 @@ import { InMemoryStore } from "../src/store/index.js";
import { PostgresStore } from "../src/store/postgres.js"; import { PostgresStore } from "../src/store/postgres.js";
import { CREATE_SCHEMA_SQL } from "../src/store/schema.js"; import { CREATE_SCHEMA_SQL } from "../src/store/schema.js";
import { type CreateAuthCompletionInput, type HeimdallStore } from "../src/store/types.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 ghostlightSecret = "ghostlight-private-command-secret";
const resources: Array<{ close(): Promise<unknown> }> = []; const resources: Array<{ close(): Promise<unknown> }> = [];
@ -65,6 +66,8 @@ function testConfig(overrides: Partial<HeimdallConfig> = {}): HeimdallConfig {
twitch: {}, twitch: {},
youtube: {}, youtube: {},
spotify: {}, spotify: {},
joystick: {},
google: {},
}, },
...overrides, ...overrides,
}; };
@ -101,10 +104,11 @@ async function start(app: App, payload: unknown, headers: Record<string, string>
} }
async function completeAs(app: App, stateToken: string, who: string) { async function completeAs(app: App, stateToken: string, who: string) {
const { cookie } = await launchState(app, stateToken);
return app.inject({ return app.inject({
method: "GET", method: "GET",
url: `/v1/oauth/discord/callback?code=${who}&state=${encodeURIComponent(stateToken)}`, url: `/v1/oauth/discord/callback?code=${who}&state=${encodeURIComponent(stateToken)}`,
headers: { accept: "application/json" }, headers: { accept: "application/json", cookie },
}); });
} }
@ -212,7 +216,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route",
}); });
expect(response.statusCode, response.body).toBe(201); expect(response.statusCode, response.body).toBe(201);
expect(response.json().handoff).toEqual({ kind: "browser_completion" }); expect(response.json().handoff).toEqual({ kind: "browser_completion" });
const state = jwtPayload(response.json().stateToken as string); const state = jwtPayload(stateOf(response.json()));
expect(state.handoff).toEqual({ kind: "browser_completion" }); expect(state.handoff).toEqual({ kind: "browser_completion" });
expect(JSON.stringify(state)).not.toContain(attempt.handle); expect(JSON.stringify(state)).not.toContain(attempt.handle);
}); });
@ -236,7 +240,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route",
expect(response.body).not.toContain(planted); expect(response.body).not.toContain(planted);
if (response.statusCode === 201) { if (response.statusCode === 201) {
expect(response.json().handoff).toEqual({ kind: "browser_completion" }); expect(response.json().handoff).toEqual({ kind: "browser_completion" });
expect(jwtPayload(response.json().stateToken as string).handoff).toEqual({ kind: "browser_completion" }); expect(jwtPayload(stateOf(response.json())).handoff).toEqual({ kind: "browser_completion" });
} else { } else {
expect(response.statusCode, response.body).toBe(400); expect(response.statusCode, response.body).toBe(400);
} }
@ -248,7 +252,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route",
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 });
expect(response.statusCode, response.body).toBe(201); expect(response.statusCode, response.body).toBe(201);
expect(response.body).not.toContain(planted); expect(response.body).not.toContain(planted);
expect(jwtPayload(response.json().stateToken as string).handoff).toEqual({ kind: "browser_completion" }); expect(jwtPayload(stateOf(response.json())).handoff).toEqual({ kind: "browser_completion" });
} }
}); });
@ -263,8 +267,8 @@ describe("R21.1: the attempt handle is unreachable from the public start route",
const calls = source.match(/(?<!function )startOAuthFlow\(/g) ?? []; const calls = source.match(/(?<!function )startOAuthFlow\(/g) ?? [];
if (calls.length) callers.push(`${file}:${calls.length}`); if (calls.length) callers.push(`${file}:${calls.length}`);
if (file.endsWith("app.ts")) { if (file.endsWith("app.ts")) {
// The HTTP route's call ends at the body; no fifth argument. // The HTTP route passes only the bearer-derived linkAccountId; never an attempt handle.
expect(source).toMatch(/startOAuthFlow\(\{ config, keys, store \}, request\.params\.provider, caller, request\.body\);/); expect(source).toMatch(/startOAuthFlow\(\{ config, keys, store \}, request\.params\.provider, caller, request\.body, \{\s*\.\.\.\(linkAccountId !== undefined \? \{ linkAccountId \} : \{\}\),\s*\}\);/);
} }
} }
expect(callers.sort()).toEqual(["app.ts:1", "private-command-plane.ts:1"]); expect(callers.sort()).toEqual(["app.ts:1", "private-command-plane.ts:1"]);
@ -305,7 +309,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route",
handoff: { kind: "browser_completion", attemptId: handle }, handoff: { kind: "browser_completion", attemptId: handle },
}); });
expect(attackerStart.statusCode).toBe(201); expect(attackerStart.statusCode).toBe(201);
const attackerCallback = await completeAs(app, attackerStart.json().stateToken as string, "attacker"); const attackerCallback = await completeAs(app, stateOf(attackerStart.json()), "attacker");
expect(attackerCallback.statusCode, attackerCallback.body).toBe(201); expect(attackerCallback.statusCode, attackerCallback.body).toBe(201);
expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("pending"); expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("pending");
@ -339,7 +343,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route",
expect(response.statusCode, response.body).toBe(201); expect(response.statusCode, response.body).toBe(201);
// Delivery to port 1 fails; whatever the callback returns, the attempt // Delivery to port 1 fails; whatever the callback returns, the attempt
// must be untouched and no completion may be bound to it. // must be untouched and no completion may be bound to it.
await completeAs(app, response.json().stateToken as string, "attacker"); await completeAs(app, stateOf(response.json()), "attacker");
expect((await store.findAuthAttempt("ghostlight", attempt.handle))?.status).toBe("pending"); expect((await store.findAuthAttempt("ghostlight", attempt.handle))?.status).toBe("pending");
expect(await store.consumeAuthCompletionByAttempt("ghostlight", attempt.handle, new Date().toISOString())).toBeNull(); expect(await store.consumeAuthCompletionByAttempt("ghostlight", attempt.handle, new Date().toISOString())).toBeNull();
}); });
@ -362,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)"); if (line.includes("caller.appSlug")) expect(line, `${file}: ${line.trim()}`).toContain("isAppCaller(caller)");
} }
} }
expect(consumers).toEqual(["app.ts: reads=2 guards=2"]); 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 () => { it("a caller minted for app A is refused where app B is expected, over HTTP and by direct call", async () => {
@ -492,26 +496,27 @@ partialUniqueIndexContract("PostgresStore over pg-mem", async () => {
}); });
describe("duplicate-handle error surfacing through the callback route", () => { describe("duplicate-handle error surfacing through the callback route", () => {
it("state tokens are replayable, and a replay while the handle's completion is unconsumed echoes the store error in a 502", async () => { 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 { app, store, begin } = await planeHarness();
const receipt = await begin("begin-replay"); const receipt = await begin("begin-replay");
const handle = String(receipt.handle); const handle = String(receipt.handle);
const state = new URL((receipt.navigation as { url: string }).url).searchParams.get("state") ?? ""; const state = new URL((receipt.navigation as { url: string }).url).searchParams.get("state") ?? "";
const first = await completeAs(app, state, "victim"); 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); expect(first.statusCode).toBe(201);
const replay = await completeAs(app, state, "victim"); // The state's jti was consumed by the first callback, so the second never
// Nothing consumed the state's jti, so the second exchange still runs and // reaches createAuthCompletion, whose unique index used to be the only
// reaches createAuthCompletion, where the unique index refuses it. The // thing refusing a replay (and whose Postgres 23505 text the route had to
// route's catch (app.ts ~1290) now answers with a fixed detail rather than // keep out of the answer).
// the store's own text, so a Postgres 23505 cannot hand the caller a const replay = await callbackWith();
// constraint name. The full text stays in the audit event. expect(replay.statusCode, replay.body).toBe(400);
expect(replay.statusCode, replay.body).toBe(502); expect(replay.json()).toEqual({ error: "state_already_used" });
expect(replay.json()).toMatchObject({
error: "oauth_callback_failed",
detail: "The provider callback could not be completed.",
});
expect(JSON.stringify(replay.json())).not.toContain("unconsumed completion");
// The failed replay must not have damaged the real completion.
expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("completed"); expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("completed");
expect(await store.consumeAuthCompletionByAttempt("ghostlight", handle, new Date().toISOString())).toBeTruthy(); expect(await store.consumeAuthCompletionByAttempt("ghostlight", handle, new Date().toISOString())).toBeTruthy();
}); });

View file

@ -11,6 +11,7 @@ import { type HeimdallConfig } from "../src/config.js";
import { entitlementFacts } from "../src/facts.js"; import { entitlementFacts } from "../src/facts.js";
import { type OAuthProviderRuntime } from "../src/oauth.js"; import { type OAuthProviderRuntime } from "../src/oauth.js";
import { InMemoryStore } from "../src/store/index.js"; import { InMemoryStore } from "../src/store/index.js";
import { launchState, stateOf } from "./oauth-flow.js";
const resources: Array<{ close(): Promise<unknown> }> = []; const resources: Array<{ close(): Promise<unknown> }> = [];
@ -51,6 +52,8 @@ function testConfig(): HeimdallConfig {
twitch: {}, twitch: {},
youtube: {}, youtube: {},
spotify: {}, spotify: {},
joystick: {},
google: {},
}, },
}; };
} }
@ -85,10 +88,11 @@ async function start(app: App, payload: Record<string, unknown>, headers: Record
} }
async function completeAs(app: App, stateToken: string, who: string) { async function completeAs(app: App, stateToken: string, who: string) {
const { cookie } = await launchState(app, stateToken);
return app.inject({ return app.inject({
method: "GET", method: "GET",
url: `/v1/oauth/discord/callback?code=${who}&state=${encodeURIComponent(stateToken)}`, url: `/v1/oauth/discord/callback?code=${who}&state=${encodeURIComponent(stateToken)}`,
headers: { accept: "application/json" }, headers: { accept: "application/json", cookie },
}); });
} }
@ -109,7 +113,7 @@ describe("takeover chain: caller-chosen attemptId is never the redemption code",
}); });
expect(started.statusCode).toBe(201); expect(started.statusCode).toBe(201);
const callback = await completeAs(app, started.json().stateToken as string, "victim"); const callback = await completeAs(app, stateOf(started.json()), "victim");
expect(callback.statusCode).toBe(201); expect(callback.statusCode).toBe(201);
const minted = callback.json().completion.code as string; const minted = callback.json().completion.code as string;
expect(minted).not.toBe("attacker-fixed"); expect(minted).not.toBe("attacker-fixed");
@ -124,7 +128,7 @@ describe("takeover chain: caller-chosen attemptId is never the redemption code",
const { app, store } = await harness(); const { app, store } = await harness();
const started = await start(app, { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" }); const started = await start(app, { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" });
expect(started.statusCode).toBe(201); expect(started.statusCode).toBe(201);
const callback = await completeAs(app, started.json().stateToken as string, "victim"); const callback = await completeAs(app, stateOf(started.json()), "victim");
expect(callback.statusCode).toBe(201); expect(callback.statusCode).toBe(201);
const code = callback.json().completion.code as string; const code = callback.json().completion.code as string;
expect(code).toMatch(uuidV4); expect(code).toMatch(uuidV4);
@ -158,7 +162,7 @@ describe("takeover chain: caller-chosen attemptId is never the redemption code",
it("attemptId set to a real victim completion code does not let the attacker's flow touch the victim's completion", async () => { 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 { app } = await harness();
const victimStart = await start(app, { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" }); const victimStart = await start(app, { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" });
const victimCallback = await completeAs(app, victimStart.json().stateToken as string, "victim"); const victimCallback = await completeAs(app, stateOf(victimStart.json()), "victim");
const victimCode = victimCallback.json().completion.code as string; const victimCode = victimCallback.json().completion.code as string;
const attackerStart = await start(app, { const attackerStart = await start(app, {
@ -167,7 +171,7 @@ describe("takeover chain: caller-chosen attemptId is never the redemption code",
returnTo: "https://repixelizer.gamecult.org/app/", returnTo: "https://repixelizer.gamecult.org/app/",
handoff: { kind: "browser_completion", attemptId: victimCode }, handoff: { kind: "browser_completion", attemptId: victimCode },
}); });
const attackerCallback = await completeAs(app, attackerStart.json().stateToken as string, "attacker"); const attackerCallback = await completeAs(app, stateOf(attackerStart.json()), "attacker");
expect(attackerCallback.statusCode).toBe(201); expect(attackerCallback.statusCode).toBe(201);
expect(attackerCallback.json().completion.code).not.toBe(victimCode); expect(attackerCallback.json().completion.code).not.toBe(victimCode);
@ -203,7 +207,7 @@ describe("consumeAuthCompletion: single-use, scoped, expiring", () => {
it("a code redeems exactly once under concurrent redemption, and never for another app", async () => { it("a code redeems exactly once under concurrent redemption, and never for another app", async () => {
const { app } = await harness(); const { app } = await harness();
const started = await start(app, { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" }); const started = await start(app, { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" });
const callback = await completeAs(app, started.json().stateToken as string, "victim"); const callback = await completeAs(app, stateOf(started.json()), "victim");
const code = callback.json().completion.code as string; const code = callback.json().completion.code as string;
const crossApp = await redeem(app, "bifrost", code); const crossApp = await redeem(app, "bifrost", code);
@ -264,7 +268,7 @@ describe("attempt-handle binding: the public start route may attach a completion
handoff: { kind: "browser_completion", attemptId: attempt.handle }, handoff: { kind: "browser_completion", attemptId: attempt.handle },
}); });
expect(attackerStart.statusCode).toBe(201); expect(attackerStart.statusCode).toBe(201);
await completeAs(app, attackerStart.json().stateToken as string, "attacker"); await completeAs(app, stateOf(attackerStart.json()), "attacker");
const after = await store.findAuthAttempt("ghostlight", attempt.handle); const after = await store.findAuthAttempt("ghostlight", attempt.handle);
expect(after?.status).toBe("pending"); expect(after?.status).toBe("pending");

View file

@ -18,6 +18,7 @@ import { type OAuthProviderRuntime } from "../src/oauth.js";
import { startHeimdallPrivateCommandPlane } from "../src/private-command-plane.js"; import { startHeimdallPrivateCommandPlane } from "../src/private-command-plane.js";
import { sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "../src/private-command-security.js"; import { sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "../src/private-command-security.js";
import { InMemoryStore } from "../src/store/index.js"; import { InMemoryStore } from "../src/store/index.js";
import { launchFlow } from "./oauth-flow.js";
const ghostlightSecret = "ghostlight-private-command-secret"; const ghostlightSecret = "ghostlight-private-command-secret";
const resources: Array<{ close(): Promise<unknown> }> = []; const resources: Array<{ close(): Promise<unknown> }> = [];
@ -59,6 +60,8 @@ function testConfig(): HeimdallConfig {
twitch: {}, twitch: {},
youtube: {}, youtube: {},
spotify: {}, spotify: {},
joystick: {},
google: {},
}, },
}; };
} }
@ -103,10 +106,11 @@ describe("caller identity: unauthenticated mint paths", () => {
}); });
expect(start.statusCode).toBe(201); expect(start.statusCode).toBe(201);
const flow = await launchFlow(app, start.json());
const callback = await app.inject({ const callback = await app.inject({
method: "GET", method: "GET",
url: `/v1/oauth/discord/callback?code=victim-code&state=${encodeURIComponent(start.json().stateToken as string)}`, url: `/v1/oauth/discord/callback?code=victim-code&state=${encodeURIComponent(flow.state)}`,
headers: { accept: "text/html" }, headers: { accept: "text/html", cookie: flow.cookie },
}); });
expect(callback.statusCode).toBe(200); expect(callback.statusCode).toBe(200);

View file

@ -0,0 +1,225 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { loadConfig, readSecretInput } from "../src/config.js";
import { appSlugs, providers } from "../src/contracts.js";
import { providerCatalog, providerExpectedEnv } from "../src/providers.js";
// Secret inputs arrive as files named by `NAME_FILE` (systemd credentials under
// Idunn). These tests pin the reader's rules and that every secret Heimdall
// consumes goes through it.
const tempDirs: string[] = [];
function tempDir(): string {
const dir = mkdtempSync(join(tmpdir(), "heimdall-secret-input-"));
tempDirs.push(dir);
return dir;
}
function secretFile(contents: string, name = "secret"): string {
const path = join(tempDir(), name);
writeFileSync(path, contents);
return path;
}
function thrownMessage(action: () => unknown): string {
try {
action();
} catch (error) {
return (error as Error).message;
}
throw new Error("expected the action to throw");
}
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("readSecretInput", () => {
it("reads the value from the file named by NAME_FILE and strips exactly one trailing newline", () => {
const cases: Array<[string, string]> = [
["from-the-file\n", "from-the-file"],
["from-the-file\r\n", "from-the-file"],
["two-newlines\n\n", "two-newlines\n"],
["line-one\nline-two\n", "line-one\nline-two"],
[" inner spaces kept \n", " inner spaces kept "],
["no-newline", "no-newline"],
];
for (const [contents, expected] of cases) {
const env = { EXAMPLE_SECRET_FILE: secretFile(contents) };
expect(readSecretInput(env, "EXAMPLE_SECRET")).toBe(expected);
}
});
it("returns undefined when neither form is set", () => {
expect(readSecretInput({}, "EXAMPLE_SECRET")).toBeUndefined();
});
it("falls back to the plaintext name only while NAME_FILE is absent (legacy shim)", () => {
expect(readSecretInput({ EXAMPLE_SECRET: "legacy-plaintext" }, "EXAMPLE_SECRET")).toBe("legacy-plaintext");
});
it("refuses both forms at once, and the refusal carries neither value", () => {
const fileCanary = "canary-file-7c1e0f";
const plainCanary = "canary-plain-93ab2d";
const env = {
EXAMPLE_SECRET: plainCanary,
EXAMPLE_SECRET_FILE: secretFile(fileCanary),
};
const message = thrownMessage(() => readSecretInput(env, "EXAMPLE_SECRET"));
expect(message).toContain("EXAMPLE_SECRET_FILE");
expect(message).toMatch(/both set/);
expect(message).not.toContain(fileCanary);
expect(message).not.toContain(plainCanary);
expect(message).not.toContain("canary");
});
it("refuses both forms even when the plaintext form is empty", () => {
const env = { EXAMPLE_SECRET: "", EXAMPLE_SECRET_FILE: secretFile("value") };
expect(() => readSecretInput(env, "EXAMPLE_SECRET")).toThrow(/both set/);
});
it("refuses an unreadable path naming only the variable and the code, not the path", () => {
// A secret bound into a _FILE slot by mistake must not be printed back.
const canaryPath = join(tempDir(), "canary-path-3b7e1d");
const message = thrownMessage(() => readSecretInput({ EXAMPLE_SECRET_FILE: canaryPath }, "EXAMPLE_SECRET"));
expect(message).toContain("EXAMPLE_SECRET_FILE");
expect(message).toContain("ENOENT");
expect(message).not.toContain("canary");
});
it("refuses a _FILE value that is not an absolute path, without echoing it", () => {
for (const value of ["postgres://heimdall:canary-pw-6f02aa@db/heimdall", "relative/canary-rel-0c9d", ""]) {
const message = thrownMessage(() => readSecretInput({ EXAMPLE_SECRET_FILE: value }, "EXAMPLE_SECRET"));
expect(message).toBe("EXAMPLE_SECRET_FILE is not an absolute path.");
}
});
it("does not treat an empty _FILE as unset, even with no plaintext form", () => {
expect(() => readSecretInput({ EXAMPLE_SECRET_FILE: "" }, "EXAMPLE_SECRET")).toThrow(/EXAMPLE_SECRET_FILE/);
});
it("refuses an unreadable file, and carries no byte of what sits in or beside it", () => {
const dir = tempDir();
const canary = "canary-sibling-5d2f88";
writeFileSync(join(dir, "sibling"), canary);
const notAFile = join(dir, "credential");
mkdirSync(notAFile);
writeFileSync(join(notAFile, "inside"), canary);
const message = thrownMessage(() => readSecretInput({ EXAMPLE_SECRET_FILE: notAFile }, "EXAMPLE_SECRET"));
expect(message).toBe("EXAMPLE_SECRET_FILE could not be read (EISDIR).");
});
it("refuses a blank secret file rather than treating it as unset", () => {
for (const contents of ["", "\n", " \n", "\t\r\n", " "]) {
const env = { EXAMPLE_SECRET_FILE: secretFile(contents) };
expect(thrownMessage(() => readSecretInput(env, "EXAMPLE_SECRET"))).toBe("EXAMPLE_SECRET_FILE is empty.");
}
});
it("refuses a blank plaintext secret too", () => {
for (const value of ["", " ", "\n"]) {
expect(thrownMessage(() => readSecretInput({ EXAMPLE_SECRET: value }, "EXAMPLE_SECRET"))).toBe(
"EXAMPLE_SECRET is empty."
);
}
});
it("keeps a value whose only whitespace is inside or around real content", () => {
const env = { EXAMPLE_SECRET_FILE: secretFile(" padded value \n") };
expect(readSecretInput(env, "EXAMPLE_SECRET")).toBe(" padded value ");
});
});
describe("loadConfig secret inputs", () => {
it("configures every secret Heimdall consumes from its _FILE twin alone", () => {
const env: Record<string, string> = {};
const expected = new Map<string, string>();
function bind(name: string): string {
const value = `value-of-${name.toLowerCase()}`;
env[`${name}_FILE`] = secretFile(`${value}\n`, name);
expected.set(name, value);
return value;
}
const databaseUrl = bind("GC_ACCESS_DATABASE_URL");
const tokenKey = bind("GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64");
const patronSecret = bind("GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET");
const providerSecrets = Object.fromEntries(
providers.map((provider) => [provider, bind(`GC_ACCESS_PROVIDER_${provider.toUpperCase()}_CLIENT_SECRET`)])
);
const appSecrets = Object.fromEntries(
appSlugs.map((slug) => [slug, bind(`GC_ACCESS_APP_${slug.toUpperCase()}_SHARED_SECRET`)])
);
const config = loadConfig(env, []);
expect(config.storage.databaseUrl).toBe(databaseUrl);
expect(config.tokenEncryptionKeyBase64).toBe(tokenKey);
expect(config.bifrostPatronSupportSecret).toBe(patronSecret);
for (const provider of providers) {
expect(config.providers[provider].clientSecret).toBe(providerSecrets[provider]);
}
expect(config.appSharedSecrets).toEqual(appSecrets);
});
it("selects postgres storage from a database URL given only as a file", () => {
const config = loadConfig(
{ GC_ACCESS_DATABASE_URL_FILE: secretFile("postgres://heimdall@localhost/heimdall\n") },
[]
);
expect(config.storage.backend).toBe("postgres");
});
it("keeps memory storage when no database URL is bound, and postgres when it is asked for", () => {
expect(loadConfig({}, []).storage.backend).toBe("memory");
expect(loadConfig({ GC_ACCESS_STORAGE_BACKEND: "memory" }, []).storage.backend).toBe("memory");
expect(loadConfig({ GC_ACCESS_STORAGE_BACKEND: "postgres" }, []).storage.backend).toBe("postgres");
});
it("refuses to start when the database URL file is absent", () => {
const missing = join(tempDir(), "database-url");
const message = thrownMessage(() => loadConfig({ GC_ACCESS_DATABASE_URL_FILE: missing }, []));
expect(message).toBe("GC_ACCESS_DATABASE_URL_FILE could not be read (ENOENT).");
});
it("refuses to start on a blank database URL file instead of falling back to memory storage", () => {
for (const contents of ["", "\n", " \n"]) {
const env = { GC_ACCESS_DATABASE_URL_FILE: secretFile(contents) };
expect(() => loadConfig(env, [])).toThrow("GC_ACCESS_DATABASE_URL_FILE is empty.");
}
});
// One per call site: a site that reads the plaintext name itself before the
// reader would let the plaintext win silently instead of refusing.
const bothSetSites: Array<[string, string]> = [
["token encryption key", "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64"],
["provider client secret", "GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET"],
["app shared secret", "GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET"],
["database URL", "GC_ACCESS_DATABASE_URL"],
["patron support secret", "GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET"],
];
for (const [site, name] of bothSetSites) {
it(`refuses the ${site} bound both ways at startup`, () => {
const env = { [name]: "plain", [`${name}_FILE`]: secretFile("file") };
expect(() => loadConfig(env, [])).toThrow(`${name} and ${name}_FILE are both set`);
});
}
it("publishes provider secret variable names that actually configure the secret", () => {
for (const provider of providers) {
const secretVariable = providerCatalog[provider].clientSecretEnv;
expect(providerExpectedEnv(provider)).toContain(secretVariable);
const config = loadConfig({ [secretVariable]: secretFile(`${provider}-secret\n`) }, []);
expect(config.providers[provider].clientSecret).toBe(`${provider}-secret`);
}
});
});

View file

@ -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<typeof import("../src/consent.js")>();
return { ...real, consentText: (ask: Parameters<typeof real.consentText>[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");
});

View file

@ -0,0 +1,253 @@
import { spawn } from "node:child_process";
import { chmodSync, mkdirSync, mkdtempSync, rmSync, statSync, 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-"));
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;
}
interface Run {
code: number | null;
signal: NodeJS.Signals | null;
output: string;
}
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<string, string>, identity?: Identity): Promise<Run> {
return new Promise((resolve, reject) => {
const child = spawn(process.execPath, [tsxCli, "src/index.ts"], {
cwd: repoRoot,
...identity,
env: {
PATH: process.env.PATH ?? "",
HOME: scratch,
GC_ACCESS_DATA_ROOT: join(scratch, `data-${name}`),
PORT: "0",
GC_ACCESS_PRIVATE_COMMAND_PORT: "0",
...env,
},
stdio: ["ignore", "pipe", "pipe"],
});
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) => {
clearTimeout(timer);
resolve({ code, signal, output });
});
});
}
/** 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<string, string>;
/** 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: () => ({
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/,
},
];
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();
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);
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);
}
});

View file

@ -0,0 +1,47 @@
import Fastify, { type FastifyReply, type FastifyRequest } from "fastify";
import { afterEach, describe, expect, it } from "vitest";
// GHSA-p68q-wchp-6fh7 (fastify < 5.12.2): a malformed request target under one
// plugin prefix, with a method that has no route in the main router, was
// dispatched to the not-found handler of a sibling plugin, skipping that
// handler's preHandler. This pins the framework fix; it is not about a Heimdall
// route.
describe("fastify malformed URL under sibling not-found handlers", () => {
const apps: Array<ReturnType<typeof Fastify>> = [];
afterEach(async () => {
await Promise.all(apps.splice(0).map((app) => app.close()));
});
async function build() {
const app = Fastify();
apps.push(app);
await app.register(async (pub) => {
pub.get("/ping", async () => "pong");
}, { prefix: "/public" });
await app.register(async (priv) => {
priv.setNotFoundHandler(
{
preHandler: async (request: FastifyRequest, reply: FastifyReply) => {
if (!request.headers.authorization) return reply.code(401).send({ error: "auth" });
},
},
(_request: FastifyRequest, reply: FastifyReply) => reply.code(404).send({ secret: "PRIVATE-TENANT-DATA" }),
);
priv.get("/x", async () => "x");
}, { prefix: "/private" });
return app;
}
it("fails closed with 400 and never reaches another prefix's not-found handler", async () => {
const app = await build();
const response = await app.inject({ method: "DELETE", url: "/public/%zz" });
expect(response.body).not.toContain("PRIVATE-TENANT-DATA");
expect(response.statusCode).toBe(400);
});
it("still runs the authenticated not-found preHandler for a well-formed URL", async () => {
const app = await build();
const response = await app.inject({ method: "DELETE", url: "/private/nothing" });
expect(response.statusCode).toBe(401);
});
});

64
tests/fixtures/fake-idunn-rudp.ts vendored Normal file
View file

@ -0,0 +1,64 @@
/**
* A stand-in for Idunn's health endpoint: it accepts each RUDP connect, acks
* the frame that follows and keeps every delivered frame. Heimdall opens a
* fresh socket and session per publication, so sessions are kept per remote.
*/
import dgram from "node:dgram";
import {
CultNetRudpSession,
decodeRudpPacket,
encodeRudpPacket,
type CultNetTransportFrame,
} from "cultnet-ts";
export interface FakeIdunnRudp {
port: number;
frames: CultNetTransportFrame[];
/** Resolves with the nth delivered frame (0-based) once it has arrived. */
frame(index: number): Promise<CultNetTransportFrame>;
close(): void;
}
export async function startFakeIdunnRudp(): Promise<FakeIdunnRudp> {
const server = dgram.createSocket("udp4");
const sessions = new Map<string, CultNetRudpSession>();
const frames: CultNetTransportFrame[] = [];
const waiting: Array<{ index: number; resolve: (frame: CultNetTransportFrame) => void }> = [];
server.on("message", (wire, remote) => {
const packet = decodeRudpPacket(wire);
const key = `${remote.address}:${remote.port}`;
if (packet.packetType === "connect") {
const session = new CultNetRudpSession({
connectionId: 0x1d0d0001,
initialSequence: 1,
resendDelayMs: 100,
});
sessions.set(key, session);
server.send(encodeRudpPacket(session.acceptConnect(packet, Date.now())), remote.port, remote.address);
return;
}
const session = sessions.get(key);
if (!session) return;
const result = session.receive(packet, Date.now());
if (result.reply) server.send(encodeRudpPacket(result.reply), remote.port, remote.address);
for (const frame of result.delivered) {
frames.push(frame);
for (const waiter of waiting.filter((entry) => entry.index === frames.length - 1)) waiter.resolve(frame);
}
if (result.delivered.length > 0) {
server.send(encodeRudpPacket(session.createAck()), remote.port, remote.address);
}
});
await new Promise<void>((resolve) => server.bind(0, "127.0.0.1", resolve));
return {
port: server.address().port,
frames,
frame: (index) =>
frames[index]
? Promise.resolve(frames[index]!)
: new Promise((resolve) => waiting.push({ index, resolve })),
close: () => server.close(),
};
}

View file

@ -0,0 +1 @@
* -text

11
tests/fixtures/idunn-runtime/README.md vendored Normal file
View file

@ -0,0 +1,11 @@
# Idunn runtime fixtures
Written by the Rust owner, not by Heimdall's tests. Copied byte for byte from CultLib
`217a9480`, `packages/cultnet-ts/test/fixtures/idunn-runtime/web` (`expected.cc`,
`activation.cc`, `activation-key.seed`, `provider-identity.credential`) and that directory's
`machine-id`. CultLib regenerates them with `packages/cultnet-rs/examples/idunn_runtime_fixture.rs`
(its own README has the Yggdrasil command); the provider identity is bound to `machine-id`, so a
test that decodes it supplies that machine id instead of `/etc/machine-id`.
Every key here is a test key. `provider-identity.credential` is the shape Idunn passes on the
presence-identity descriptor: key fields are 32-integer arrays, which only the Rust owner writes.

View file

@ -0,0 +1 @@
¯ÂOd×f¯l*oµ‘ÀFªv‰n<E280B0>hLûÑpšS´p

Binary file not shown.

BIN
tests/fixtures/idunn-runtime/expected.cc vendored Normal file

Binary file not shown.

View file

@ -0,0 +1 @@
c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1

Binary file not shown.

61
tests/fixtures/presence-descriptors.ts vendored Normal file
View file

@ -0,0 +1,61 @@
/**
* What Idunn hands a generation for runtime presence: the bundle directory, a
* parent-only identity store and an activation seed, the last two passed as
* descriptors named in LISTEN_FDNAMES. The bytes are the Rust owner's, copied
* from CultLib (see idunn-runtime/README.md); every key in them is a test key.
*/
import { closeSync, openSync } from "node:fs";
import { chmod, copyFile, mkdir, readFile } from "node:fs/promises";
import path from "node:path";
import { IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME } from "cultnet-ts";
export const idunnRuntimeFixtures = path.join(import.meta.dirname, "idunn-runtime");
const FIXTURE_FILES = [
"expected.cc",
"activation.cc",
"activation-key.seed",
"provider-identity.credential",
"machine-id",
] as const;
/** The machine id the fixture identity is bound to, in place of /etc/machine-id. */
export const fixtureMachineId = async (dir: string = idunnRuntimeFixtures): Promise<string> =>
(await readFile(path.join(dir, "machine-id"), "utf8")).trim();
/** Copy the fixtures into `dir`, readable by any uid (the children run as others). */
export async function writePresenceFixtures(dir: string): Promise<void> {
await mkdir(dir, { recursive: true });
await chmod(dir, 0o755);
for (const name of FIXTURE_FILES) {
const target = path.join(dir, name);
await copyFile(path.join(idunnRuntimeFixtures, name), target);
await chmod(target, 0o644);
}
}
/** Open both descriptors and name them the way systemd's LISTEN_FDNAMES does. */
export function openPresenceDescriptors(dir: string): { env: NodeJS.ProcessEnv; close: () => void } {
const fds = [
[openSync(path.join(dir, "provider-identity.credential"), "r"), "gamecult-runtime-presence-identity"],
[openSync(path.join(dir, "activation-key.seed"), "r"), IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME],
] as const;
const names: string[] = [];
for (const [fd, name] of fds) {
while (names.length < fd - 3) names.push(`pad-${names.length}`);
names[fd - 3] = name;
}
return {
env: { LISTEN_FDNAMES: names.join(":") },
// The authority closes each descriptor it reads; this releases only what it did not.
close: () =>
fds.forEach(([fd]) => {
try {
closeSync(fd);
} catch {
// already closed by the reader
}
}),
};
}

View file

@ -0,0 +1,57 @@
/**
* One Idunn generation, as a process: it runs as the uid and gid its parent
* gave it, under UMask=0007, and does what Heimdall does to a state root on a
* pulse. The parent test spawns two of these under different uids that share
* a group.
*
* argv: <role: first|next> <stateRoot> <fixtureDir>
*/
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { loadConfig } from "../../src/config.js";
import { openPresenceAuthority } from "../../src/runtime-presence.js";
import { fixtureMachineId, openPresenceDescriptors } from "./presence-descriptors.js";
import { createHeimdallRuntimePulse, publishHeimdallVerseState } from "../../src/verse-state.js";
const [role, stateRoot, fixtureDir] = process.argv.slice(2) as [string, string, string];
process.umask(0o007);
const config = loadConfig({
GC_ACCESS_BASE_URL: "https://heimdall.example.test",
GC_ACCESS_DATA_ROOT: stateRoot,
});
async function publishPresence(): Promise<void> {
const descriptors = openPresenceDescriptors(fixtureDir);
try {
const authority = await openPresenceAuthority(
{
idunnRuntimeBundlePath: fixtureDir,
host: config.host,
port: config.port,
providerHealthIdentityPath: path.join(stateRoot, "provider-health-identity.cc"),
},
descriptors.env,
() => fixtureMachineId(fixtureDir),
);
authority.sign("warming", "generation probe", Date.now());
} finally {
descriptors.close();
}
}
if (role === "next") {
// Generation N+1 reads what N left before it replaces it.
const previous = await readFile(config.cultCachePath);
if (previous.length === 0) throw new Error("previous generation's snapshot is empty");
}
await publishHeimdallVerseState(config, createHeimdallRuntimePulse(config));
await publishPresence();
if (role === "first") {
// The 0600 counter the 2026-09-07 generation left behind. Nothing reads it
// now; it stays as the stale fixture the next generation must live beside.
await writeFile(path.join(stateRoot, "runtime-presence-sequence"), "41\n", { mode: 0o600 });
}

675
tests/google-link.test.ts Normal file
View file

@ -0,0 +1,675 @@
import { createHash, createSign, generateKeyPairSync } from "node:crypto";
import { afterEach, describe, expect, it, vi } from "vitest";
import { type FastifyInstance } from "fastify";
import { buildApp } from "../src/app.js";
import { loadConfig, type HeimdallConfig } from "../src/config.js";
import { resetGoogleJwksCache } from "../src/google-oidc.js";
import { type OAuthProviderRuntime } from "../src/oauth.js";
import { IdentityHeldElsewhereError, InMemoryStore } from "../src/store/index.js";
import { launchFlow, launchWithRedirect, stateOf, type LaunchedFlow } from "./oauth-flow.js";
const CLIENT_ID = "google-client";
const REDIRECT = "https://heimdall.gamecult.org/v1/oauth/google/callback";
const rsa = generateKeyPairSync("rsa", { modulusLength: 2048 });
const originalFetch = globalThis.fetch;
const apps: FastifyInstance[] = [];
function config(): HeimdallConfig {
const base = loadConfig({
GC_ACCESS_BASE_URL: "https://heimdall.gamecult.org",
GC_ACCESS_PROVIDER_GOOGLE_CLIENT_ID: CLIENT_ID,
GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID: "discord-client",
} as NodeJS.ProcessEnv);
return {
...base,
storage: { backend: "memory", applySchemaOnStartup: true },
tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"),
bootstrapSigningPrivateKeyOnMissing: true,
appSharedSecrets: { ...base.appSharedSecrets, bifrost: "bifrost-secret", repixelizer: "repixelizer-secret" },
providers: {
...base.providers,
google: { clientId: CLIENT_ID, clientSecret: "google-secret" },
discord: { clientId: "discord-client", clientSecret: "discord-secret" },
},
};
}
function discordRuntime(providerUserId: string, name: string): OAuthProviderRuntime {
return {
async exchangeAuthorizationCode() {
return { accessToken: "d-at", refreshToken: "d-rt", tokenType: "Bearer", scope: ["identify"], expiresAt: "2099-01-01T00:00:00.000Z", raw: {} };
},
async resolveIdentity() {
return { provider: "discord", providerUserId, username: name, displayName: name, profile: { id: providerUserId } };
},
// Discord grants app access only under a policy the app named at start.
async evaluateEntitlements(input) {
return { facts: input.callback.entitlementPolicy ? ["entitlement.app_access"] : [], snapshots: [] };
},
};
}
// Bifrost refuses an unauthenticated start: its backend holds the app secret.
const BIFROST_APP = { "x-heimdall-app-secret": "bifrost-secret" };
function b64(value: unknown): string {
return Buffer.from(JSON.stringify(value)).toString("base64url");
}
function signedIdToken(claims: Record<string, unknown>): string {
const now = Math.floor(Date.now() / 1000);
const body = `${b64({ alg: "RS256", kid: "k1" })}.${b64({
iss: "https://accounts.google.com",
aud: CLIENT_ID,
azp: CLIENT_ID,
sub: "g-sub-1",
email: "person@example.org",
email_verified: true,
name: "Person",
iat: now,
exp: now + 600,
...claims,
})}`;
return `${body}.${createSign("RSA-SHA256").update(body).sign(rsa.privateKey).toString("base64url")}`;
}
interface GoogleLeg {
tokenRequests: URLSearchParams[];
}
/** Google's two endpoints: the key set, and a token endpoint whose id_token echoes the nonce it was told. */
function fakeGoogle(options: { nonceFrom: () => string | undefined; claims?: Record<string, unknown> }): GoogleLeg {
const leg: GoogleLeg = { tokenRequests: [] };
globalThis.fetch = (async (input: string | URL, init?: RequestInit) => {
const url = String(input);
if (url === "https://www.googleapis.com/oauth2/v3/certs") {
return new Response(
JSON.stringify({ keys: [{ ...(rsa.publicKey.export({ format: "jwk" }) as object), kid: "k1", alg: "RS256" }] }),
{ status: 200 }
);
}
if (url === "https://oauth2.googleapis.com/token") {
leg.tokenRequests.push(new URLSearchParams(String(init?.body)));
return new Response(
JSON.stringify({
access_token: "g-at",
token_type: "Bearer",
expires_in: 3600,
scope: "openid email profile",
id_token: signedIdToken({ nonce: options.nonceFrom(), ...options.claims }),
}),
{ status: 200 }
);
}
throw new Error(`unexpected fetch ${url}`);
}) as typeof fetch;
return leg;
}
function accountCount(store: InMemoryStore): number {
return (store as unknown as { accounts: Map<string, unknown> }).accounts.size;
}
async function signInWithDiscord(app: FastifyInstance, providerUserId = "discord-1"): Promise<{ accessToken: string; accountId: string }> {
const start = await app.inject({
method: "POST",
url: "/v1/oauth/discord/start",
headers: BIFROST_APP,
payload: { appSlug: "bifrost", mode: "sign_in", returnTo: "https://bifrost.gamecult.org/auth/heimdall/complete" },
});
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=c&state=${encodeURIComponent(flow.state)}`,
headers: { cookie: flow.cookie },
});
expect(callback.statusCode).toBe(201);
const body = callback.json();
return { accessToken: body.accessToken as string, accountId: body.account.id as string };
}
async function build(store = new InMemoryStore(), discordUser = "discord-1") {
const app = await buildApp({ config: config(), store, oauthRuntimes: { discord: discordRuntime(discordUser, "Person") } });
apps.push(app);
return { app, store };
}
function startGoogle(app: FastifyInstance, accessToken?: string, mode: "link" | "sign_in" = "link") {
return app.inject({
method: "POST",
url: "/v1/oauth/google/start",
headers: { ...BIFROST_APP, ...(accessToken ? { authorization: `Bearer ${accessToken}` } : {}) },
payload: { appSlug: "bifrost", mode, returnTo: "https://bifrost.gamecult.org/auth/heimdall/complete" },
});
}
function callbackGoogle(app: FastifyInstance, flow: LaunchedFlow) {
return app.inject({
method: "GET",
url: `/v1/oauth/google/callback?code=g-code&state=${encodeURIComponent(flow.state)}`,
headers: { cookie: flow.cookie },
});
}
const DISCORD_POLICY = { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["member"] } as const;
/** Begin a link with `token`, let Google answer as `claims` says, and return the callback's answer. */
async function linkGoogleCallback(app: FastifyInstance, token: string, claims?: Record<string, unknown>) {
const start = await startGoogle(app, token);
expect(start.statusCode).toBe(201);
const startFlow = await launchWithRedirect(app, start.json());
const url = startFlow.url;
fakeGoogle({ nonceFrom: () => url.searchParams.get("nonce") ?? undefined, ...(claims ? { claims } : {}) });
return callbackGoogle(app, startFlow);
}
function confirmLink(app: FastifyInstance, token: string | undefined, pendingLinkId: string) {
return app.inject({
method: "POST",
url: "/v1/apps/bifrost/links/confirm",
headers: token ? { authorization: `Bearer ${token}` } : {},
payload: { pendingLinkId },
});
}
/** The whole link: callback, then the initiator's confirm. */
async function linkGoogle(app: FastifyInstance, token: string, claims?: Record<string, unknown>) {
const done = await linkGoogleCallback(app, token, claims);
expect(done.statusCode).toBe(201);
const confirmed = await confirmLink(app, token, done.json().pendingLinkId);
expect(confirmed.statusCode).toBe(201);
return confirmed;
}
afterEach(async () => {
globalThis.fetch = originalFetch;
resetGoogleJwksCache();
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();
const { accessToken } = await signInWithDiscord(app);
const start = await startGoogle(app, accessToken);
expect(start.statusCode).toBe(201);
expect(start.json().callbackUrl).toBe(REDIRECT);
const startFlow = await launchWithRedirect(app, start.json());
const url = startFlow.url;
expect(`${url.origin}${url.pathname}`).toBe("https://accounts.google.com/o/oauth2/v2/auth");
expect(url.searchParams.get("client_id")).toBe(CLIENT_ID);
expect(url.searchParams.get("redirect_uri")).toBe(REDIRECT);
expect(url.searchParams.get("response_type")).toBe("code");
expect(url.searchParams.get("scope")).toBe("openid email profile");
expect(url.searchParams.get("state")).toBe(stateOf(start.json()));
expect(url.searchParams.get("nonce")).toMatch(/^[A-Za-z0-9_-]{43}$/);
expect(url.searchParams.get("code_challenge")).toMatch(/^[A-Za-z0-9_-]{43}$/);
expect(url.searchParams.get("code_challenge_method")).toBe("S256");
});
it("links Google to the account that asked, with PKCE proven end to end and the id_token's nonce matched", async () => {
const { app, store } = await build();
const { accessToken, accountId } = await signInWithDiscord(app);
const start = await startGoogle(app, accessToken);
const startFlow = await launchWithRedirect(app, start.json());
const url = startFlow.url;
const leg = fakeGoogle({ nonceFrom: () => url.searchParams.get("nonce") ?? undefined });
const done = await callbackGoogle(app, startFlow);
// Phase one verified the identity and recorded it; it linked nothing and issued no session.
expect(done.statusCode).toBe(201);
expect(done.json().status).toBe("link_pending");
expect(done.json().accessToken).toBeUndefined();
expect(await store.findStoredLinkedIdentity("google", "g-sub-1")).toBeNull();
const confirmed = await confirmLink(app, accessToken, done.json().pendingLinkId);
expect(confirmed.statusCode).toBe(201);
expect(confirmed.json().accountId).toBe(accountId);
expect(accountCount(store)).toBe(1);
const sent = leg.tokenRequests[0]!;
expect(sent.get("grant_type")).toBe("authorization_code");
expect(sent.get("redirect_uri")).toBe(REDIRECT);
// The verifier Heimdall sent hashes to the challenge it put in the authorization URL.
expect(createHash("sha256").update(sent.get("code_verifier") ?? "", "ascii").digest("base64url")).toBe(
url.searchParams.get("code_challenge")
);
const stored = await store.findStoredLinkedIdentity("google", "g-sub-1");
expect(stored?.accountId).toBe(accountId);
expect(stored?.primaryEmail).toBe("person@example.org");
});
it("signs in the account Google is linked to, with no session, and mints nothing", async () => {
const { app, store } = await build();
const { accessToken, accountId } = await signInWithDiscord(app);
await linkGoogle(app, accessToken);
const signIn = await startGoogle(app, undefined, "sign_in");
expect(signIn.statusCode).toBe(201);
const signInFlow = await launchWithRedirect(app, signIn.json());
const signInUrl = signInFlow.url;
fakeGoogle({ nonceFrom: () => signInUrl.searchParams.get("nonce") ?? undefined });
const done = await callbackGoogle(app, signInFlow);
expect(done.statusCode).toBe(201);
expect(done.json().account.id).toBe(accountId);
expect(accountCount(store)).toBe(1);
});
it("refuses a link start whose named initiator is not the bearer's account", async () => {
const { app, store } = await build();
const a = await signInWithDiscord(app, "discord-1");
const start = await app.inject({
method: "POST",
url: "/v1/oauth/google/start",
headers: { ...BIFROST_APP, authorization: `Bearer ${a.accessToken}` },
payload: {
appSlug: "bifrost",
mode: "link",
returnTo: "https://bifrost.gamecult.org/auth/heimdall/complete",
initiatingAccountId: `${a.accountId}-other`,
},
});
expect([start.statusCode, start.json().error]).toEqual([400, "link_initiator_conflict"]);
expect(accountCount(store)).toBe(1);
});
it("refuses a link start with no Heimdall session", async () => {
const { app, store } = await build();
const start = await startGoogle(app);
expect(start.statusCode).toBe(401);
expect(start.json().error).toBe("link_session_required");
expect(accountCount(store)).toBe(0);
});
it.each([
["a garbage bearer", () => "not-a-token"],
["a token for another app", async (app: FastifyInstance) => {
const start = await app.inject({
method: "POST",
url: "/v1/oauth/discord/start",
payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" },
});
const flow = await launchFlow(app, start.json());
const cb = await app.inject({ method: "GET", url: `/v1/oauth/discord/callback?code=c&state=${encodeURIComponent(flow.state)}`, headers: { cookie: flow.cookie } });
return cb.json().accessToken as string;
}],
])("refuses a link start carrying %s", async (_name, token) => {
const { app, store } = await build();
const bearer = await token(app);
const before = accountCount(store);
const start = await startGoogle(app, bearer);
expect(start.statusCode).toBe(401);
expect(start.json().error).toBe("invalid_link_session");
expect(accountCount(store)).toBe(before);
});
it("refuses a first Google login from a subject no account holds, and mints no account for it", async () => {
// The person who has a Discord account arrives with Google for the first time, signing in rather than linking.
const { app, store } = await build();
await signInWithDiscord(app);
const start = await startGoogle(app, undefined, "sign_in");
expect(start.statusCode).toBe(201);
const startFlow = await launchWithRedirect(app, start.json());
const url = startFlow.url;
fakeGoogle({ nonceFrom: () => url.searchParams.get("nonce") ?? undefined });
const before = accountCount(store);
const done = await callbackGoogle(app, startFlow);
expect(done.statusCode).toBe(403);
expect(done.json().error).toBe("identity_not_linked");
expect(accountCount(store)).toBe(before);
expect(await store.findStoredLinkedIdentity("google", "g-sub-1")).toBeNull();
});
it("never moves or merges: a Google subject already linked to one account cannot be linked to another", 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);
// A second person, a second account, the same Google subject.
const second = await build(store, "discord-2");
const b = await signInWithDiscord(second.app, "discord-2");
expect(b.accountId).not.toBe(a.accountId);
const startB = await startGoogle(second.app, b.accessToken);
const startBFlow = await launchWithRedirect(second.app, startB.json());
const urlB = startBFlow.url;
fakeGoogle({ nonceFrom: () => urlB.searchParams.get("nonce") ?? undefined });
const done = await callbackGoogle(second.app, startBFlow);
expect(done.statusCode).toBe(403);
expect((await store.findStoredLinkedIdentity("google", "g-sub-1"))?.accountId).toBe(a.accountId);
});
it.each([
["an unverified email", { email_verified: false }],
["another client's audience", { aud: "other-client", azp: "other-client" }],
["a nonce this request did not carry", { nonce: "replayed" }],
["an expired token", { exp: Math.floor(Date.now() / 1000) - 3600 }],
])("links nothing when the id_token has %s", async (_name, claims) => {
const { app, store } = await build();
const { accessToken } = await signInWithDiscord(app);
const start = await startGoogle(app, accessToken);
const startFlow = await launchWithRedirect(app, start.json());
const url = startFlow.url;
fakeGoogle({ nonceFrom: () => url.searchParams.get("nonce") ?? undefined, claims });
const done = await callbackGoogle(app, startFlow);
expect(done.statusCode).toBe(502);
expect(await store.findStoredLinkedIdentity("google", "g-sub-1")).toBeNull();
expect(accountCount(store)).toBe(1);
});
it("keys the identity by sub: the same email under a different sub is a different, unlinkable identity", async () => {
const { app, store } = await build();
const { accessToken, accountId } = await signInWithDiscord(app);
await linkGoogle(app, accessToken, { sub: "g-sub-2" });
expect((await store.findStoredLinkedIdentity("google", "g-sub-2"))?.accountId).toBe(accountId);
expect(await store.findStoredLinkedIdentity("google", "person@example.org")).toBeNull();
});
describe("link is two-phase", () => {
it("a victim completing an attacker's link URL attaches the victim's Google sub to no account", async () => {
const store = new InMemoryStore();
const attacker = await build(store, "discord-attacker");
const a = await signInWithDiscord(attacker.app, "discord-attacker");
const victim = await build(store, "discord-victim");
const v = await signInWithDiscord(victim.app, "discord-victim");
// The attacker begins a link and sends the Google URL to the victim, who finishes it as themselves.
const done = await linkGoogleCallback(attacker.app, a.accessToken, { sub: "victim-google-sub" });
expect(done.statusCode).toBe(201);
expect(await store.findStoredLinkedIdentity("google", "victim-google-sub")).toBeNull();
// The victim's app holds the victim's token: Heimdall refuses it, and the link stays unwritten.
const asVictim = await confirmLink(victim.app, v.accessToken, done.json().pendingLinkId);
expect(asVictim.statusCode).toBe(410);
expect(await store.findStoredLinkedIdentity("google", "victim-google-sub")).toBeNull();
// No token at all, and a garbage token, are refused the same way.
expect((await confirmLink(attacker.app, undefined, done.json().pendingLinkId)).statusCode).toBe(401);
expect((await confirmLink(attacker.app, "garbage", done.json().pendingLinkId)).statusCode).toBe(401);
expect(await store.findStoredLinkedIdentity("google", "victim-google-sub")).toBeNull();
// The refused attempts did not burn the pending link: its initiator can still confirm it.
expect((await confirmLink(attacker.app, a.accessToken, done.json().pendingLinkId)).statusCode).toBe(201);
});
it("signing in with Google cannot reach a Google sub the attacker's pending link recorded", async () => {
const { app } = await build();
const a = await signInWithDiscord(app);
await linkGoogleCallback(app, a.accessToken, { sub: "victim-google-sub" });
const signIn = await startGoogle(app, undefined, "sign_in");
const signInFlow = await launchWithRedirect(app, signIn.json());
const url = signInFlow.url;
fakeGoogle({ nonceFrom: () => url.searchParams.get("nonce") ?? undefined, claims: { sub: "victim-google-sub" } });
expect((await callbackGoogle(app, signInFlow)).statusCode).toBe(403);
});
it("a pending link is single-use", async () => {
const { app } = await build();
const a = await signInWithDiscord(app);
const done = await linkGoogleCallback(app, a.accessToken);
expect((await confirmLink(app, a.accessToken, done.json().pendingLinkId)).statusCode).toBe(201);
expect((await confirmLink(app, a.accessToken, done.json().pendingLinkId)).statusCode).toBe(410);
});
it("a pending link expires after the completion TTL", async () => {
const { app, store } = await build();
const a = await signInWithDiscord(app);
const done = await linkGoogleCallback(app, a.accessToken);
const ttlMs = Date.parse(done.json().expiresAt) - Date.now();
expect(ttlMs).toBeGreaterThan(0);
expect(ttlMs).toBeLessThanOrEqual(300_000);
vi.useFakeTimers({ toFake: ["Date"], now: Date.now() + 301_000 });
try {
expect((await confirmLink(app, a.accessToken, done.json().pendingLinkId)).statusCode).toBe(410);
} finally {
vi.useRealTimers();
}
expect(await store.findStoredLinkedIdentity("google", "g-sub-1")).toBeNull();
});
it("a pending link is bound to its app: another app's session cannot confirm it", async () => {
const { app, store } = await build();
const a = await signInWithDiscord(app);
const done = await linkGoogleCallback(app, a.accessToken);
const other = await app.inject({
method: "POST",
url: "/v1/oauth/discord/start",
payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" },
});
const flow = await launchFlow(app, other.json());
const cb = await app.inject({ method: "GET", url: `/v1/oauth/discord/callback?code=c&state=${encodeURIComponent(flow.state)}`, headers: { cookie: flow.cookie } });
const res = await app.inject({
method: "POST",
url: "/v1/apps/repixelizer/links/confirm",
headers: { authorization: `Bearer ${cb.json().accessToken}` },
payload: { pendingLinkId: done.json().pendingLinkId },
});
expect(res.statusCode).toBe(410);
expect(await store.findStoredLinkedIdentity("google", "g-sub-1")).toBeNull();
});
it("refuses at confirm a sub another account linked in between, and never moves it", async () => {
const store = new InMemoryStore();
const first = await build(store, "discord-1");
const a = await signInWithDiscord(first.app, "discord-1");
const second = await build(store, "discord-2");
const b = await signInWithDiscord(second.app, "discord-2");
const pendingA = await linkGoogleCallback(first.app, a.accessToken);
const pendingB = await linkGoogleCallback(second.app, b.accessToken);
expect((await confirmLink(first.app, a.accessToken, pendingA.json().pendingLinkId)).statusCode).toBe(201);
const lost = await confirmLink(second.app, b.accessToken, pendingB.json().pendingLinkId);
expect(lost.statusCode).toBe(409);
expect((await store.findStoredLinkedIdentity("google", "g-sub-1"))?.accountId).toBe(a.accountId);
});
});
describe("entitlements at the callback", () => {
it("a Discord-origin member returning through Google keeps entitlement.app_access under the start-time policy", async () => {
const { app } = await build();
const member = await signInWithDiscord(app);
await linkGoogle(app, member.accessToken);
const start = await app.inject({
method: "POST",
url: "/v1/oauth/google/start",
headers: { "x-heimdall-app-secret": "bifrost-secret" },
payload: {
appSlug: "bifrost",
mode: "sign_in",
returnTo: "https://bifrost.gamecult.org/auth/heimdall/complete",
entitlementPolicy: DISCORD_POLICY,
},
});
expect(start.statusCode).toBe(201);
const startFlow = await launchWithRedirect(app, start.json());
const url = startFlow.url;
fakeGoogle({ nonceFrom: () => url.searchParams.get("nonce") ?? undefined });
const done = await callbackGoogle(app, startFlow);
expect(done.statusCode).toBe(201);
expect(done.json().claimSet.facts).toContain("entitlement.app_access");
});
it("without a start-time policy the other identities grant nothing", async () => {
const { app } = await build();
const member = await signInWithDiscord(app);
await linkGoogle(app, member.accessToken);
const start = await startGoogle(app, undefined, "sign_in");
const startFlow = await launchWithRedirect(app, start.json());
const url = startFlow.url;
fakeGoogle({ nonceFrom: () => url.searchParams.get("nonce") ?? undefined });
const done = await callbackGoogle(app, startFlow);
expect(done.statusCode).toBe(201);
expect(done.json().claimSet.facts).not.toContain("entitlement.app_access");
});
});
it("leaves the six existing providers minting on first login", async () => {
const { app, store } = await build();
await signInWithDiscord(app);
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<string, unknown> = {}, headers: Record<string, string> = 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<string, unknown>) {
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<string, { eventType: string; eventPayloadJson?: unknown }> }).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);
});
});

197
tests/google-oidc.test.ts Normal file
View file

@ -0,0 +1,197 @@
import { createSign, generateKeyPairSync, type KeyObject } from "node:crypto";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
deriveOidcSecrets,
GoogleIdTokenError,
resetGoogleJwksCache,
verifyGoogleIdToken,
type GoogleIdTokenFailure,
} from "../src/google-oidc.js";
const CLIENT_ID = "google-client.apps.googleusercontent.com";
const NONCE = "the-nonce";
const NOW_MS = Date.parse("2026-11-04T12:00:00.000Z");
const NOW_S = Math.floor(NOW_MS / 1000);
const rsa = generateKeyPairSync("rsa", { modulusLength: 2048 });
const otherRsa = generateKeyPairSync("rsa", { modulusLength: 2048 });
const originalFetch = globalThis.fetch;
let jwksFetches = 0;
function jwks(kidKeys: Record<string, KeyObject>) {
return {
keys: Object.entries(kidKeys).map(([kid, key]) => ({
...(key.export({ format: "jwk" }) as Record<string, string>),
kid,
alg: "RS256",
use: "sig",
})),
};
}
function serveJwks(kidKeys: Record<string, KeyObject>) {
globalThis.fetch = (async (input: string | URL) => {
expect(String(input)).toBe("https://www.googleapis.com/oauth2/v3/certs");
jwksFetches += 1;
return new Response(JSON.stringify(jwks(kidKeys)), { status: 200, headers: { "cache-control": "public, max-age=3600" } });
}) as typeof fetch;
}
function b64(value: unknown): string {
return Buffer.from(JSON.stringify(value)).toString("base64url");
}
function idToken(
claims: Record<string, unknown> = {},
options: { kid?: string; alg?: string; key?: KeyObject; omit?: string[] } = {}
): string {
const payload: Record<string, unknown> = {
iss: "https://accounts.google.com",
aud: CLIENT_ID,
azp: CLIENT_ID,
sub: "110169484474386276334",
email: "meta@example.org",
email_verified: true,
name: "Meta",
picture: "https://lh3.googleusercontent.com/a/x",
nonce: NONCE,
iat: NOW_S - 10,
exp: NOW_S + 3000,
...claims,
};
for (const key of options.omit ?? []) delete payload[key];
const header = b64({ alg: options.alg ?? "RS256", typ: "JWT", kid: options.kid ?? "k1" });
const body = `${header}.${b64(payload)}`;
const signature = createSign("RSA-SHA256").update(body).sign(options.key ?? rsa.privateKey).toString("base64url");
return `${body}.${signature}`;
}
async function refusal(token: string, nonce = NONCE): Promise<GoogleIdTokenFailure> {
try {
await verifyGoogleIdToken(token, { clientId: CLIENT_ID, nonce }, NOW_MS);
} catch (error) {
expect(error).toBeInstanceOf(GoogleIdTokenError);
return (error as GoogleIdTokenError).code;
}
throw new Error("the token was accepted");
}
beforeEach(() => {
resetGoogleJwksCache();
jwksFetches = 0;
serveJwks({ k1: rsa.publicKey });
});
afterEach(() => {
globalThis.fetch = originalFetch;
});
describe("verifyGoogleIdToken", () => {
it("accepts a good token and returns the subject as the identity", async () => {
const claims = await verifyGoogleIdToken(idToken(), { clientId: CLIENT_ID, nonce: NONCE }, NOW_MS);
expect(claims).toEqual({
sub: "110169484474386276334",
email: "meta@example.org",
name: "Meta",
picture: "https://lh3.googleusercontent.com/a/x",
});
});
it("accepts the bare-host issuer Google also uses", async () => {
await expect(verifyGoogleIdToken(idToken({ iss: "accounts.google.com" }), { clientId: CLIENT_ID, nonce: NONCE }, NOW_MS)).resolves.toMatchObject({
sub: "110169484474386276334",
});
});
it.each<[string, () => string, GoogleIdTokenFailure]>([
["a foreign issuer", () => idToken({ iss: "https://evil.example" }), "bad_issuer"],
["an issuer that merely contains Google's", () => idToken({ iss: "https://accounts.google.com.evil.example" }), "bad_issuer"],
["another client's audience", () => idToken({ aud: "other-client", azp: "other-client" }), "bad_audience"],
["an array audience whose azp is not this client", () => idToken({ aud: [CLIENT_ID, "other"], azp: "other" }), "bad_audience"],
["an array audience with no azp", () => idToken({ aud: [CLIENT_ID], azp: undefined }), "bad_audience"],
["an expired token", () => idToken({ exp: NOW_S - 61 }), "expired"],
["a token with no exp", () => idToken({}, { omit: ["exp"] }), "expired"],
["a token issued in the future", () => idToken({ iat: NOW_S + 3600 }), "not_yet_valid"],
["a token with no iat", () => idToken({}, { omit: ["iat"] }), "not_yet_valid"],
["a nonce this request did not carry", () => idToken({ nonce: "someone-elses" }), "bad_nonce"],
["a token with no nonce", () => idToken({}, { omit: ["nonce"] }), "bad_nonce"],
["no subject", () => idToken({}, { omit: ["sub"] }), "missing_subject"],
["an empty subject", () => idToken({ sub: "" }), "missing_subject"],
["no email", () => idToken({}, { omit: ["email"] }), "email_missing"],
["an unverified email", () => idToken({ email_verified: false }), "email_not_verified"],
["no email_verified claim", () => idToken({}, { omit: ["email_verified"] }), "email_not_verified"],
["a string email_verified other than true", () => idToken({ email_verified: "yes" }), "email_not_verified"],
["alg none", () => idToken({}, { alg: "none" }), "unsupported_algorithm"],
["alg HS256", () => idToken({}, { alg: "HS256" }), "unsupported_algorithm"],
["a key Google does not publish", () => idToken({}, { kid: "unknown" }), "unknown_key"],
["a signature by another key under Google's kid", () => idToken({}, { key: otherRsa.privateKey }), "bad_signature"],
["three empty parts", () => "..", "malformed"],
["two parts", () => "a.b", "malformed"],
])("refuses %s", async (_name, make, code) => {
expect(await refusal(make())).toBe(code);
});
it("checks the signature before it believes any claim", async () => {
// A forged payload with every claim right is still refused as a bad signature.
const forged = idToken({}, { key: otherRsa.privateKey });
expect(await refusal(forged)).toBe("bad_signature");
});
it("takes email_verified string 'true' as Google's older tokens spell it", async () => {
await expect(verifyGoogleIdToken(idToken({ email_verified: "true" }), { clientId: CLIENT_ID, nonce: NONCE }, NOW_MS)).resolves.toMatchObject({
email: "meta@example.org",
});
});
it("caches Google's keys and refetches once for a rotated kid, not for every bad token", async () => {
await verifyGoogleIdToken(idToken(), { clientId: CLIENT_ID, nonce: NONCE }, NOW_MS);
await verifyGoogleIdToken(idToken(), { clientId: CLIENT_ID, nonce: NONCE }, NOW_MS + 1000);
expect(jwksFetches).toBe(1);
serveJwks({ k1: rsa.publicKey, k2: otherRsa.publicKey });
const rotated = idToken({}, { kid: "k2", key: otherRsa.privateKey });
// Inside the refetch floor the unknown kid is refused without a fetch.
await expect(verifyGoogleIdToken(rotated, { clientId: CLIENT_ID, nonce: NONCE }, NOW_MS + 2000)).rejects.toMatchObject({ code: "unknown_key" });
expect(jwksFetches).toBe(1);
await expect(verifyGoogleIdToken(rotated, { clientId: CLIENT_ID, nonce: NONCE }, NOW_MS + 120_000)).resolves.toMatchObject({ sub: "110169484474386276334" });
expect(jwksFetches).toBe(2);
});
it("refuses with jwks_unavailable when Google's key endpoint fails", async () => {
resetGoogleJwksCache();
globalThis.fetch = (async () => new Response("down", { status: 503 })) as typeof fetch;
expect(await refusal(idToken())).toBe("jwks_unavailable");
});
it("never quotes the token in its refusal", async () => {
const token = idToken({ email: "secret-person@example.org", nonce: "wrong" });
try {
await verifyGoogleIdToken(token, { clientId: CLIENT_ID, nonce: NONCE }, NOW_MS);
} catch (error) {
expect(String((error as Error).message)).not.toContain("secret-person");
expect(String((error as Error).message)).not.toContain(token.slice(0, 20));
}
});
});
describe("deriveOidcSecrets", () => {
const key = generateKeyPairSync("ed25519").privateKey;
const otherKey = generateKeyPairSync("ed25519").privateKey;
it("is the same pair for the same state and Heimdall key, so nothing is stored between start and callback", () => {
expect(deriveOidcSecrets("jti-1", key)).toEqual(deriveOidcSecrets("jti-1", key));
});
it("differs per state, per Heimdall key, and between verifier and nonce", () => {
const a = deriveOidcSecrets("jti-1", key);
expect(deriveOidcSecrets("jti-2", key).codeVerifier).not.toBe(a.codeVerifier);
expect(deriveOidcSecrets("jti-2", key).nonce).not.toBe(a.nonce);
expect(deriveOidcSecrets("jti-1", otherKey).codeVerifier).not.toBe(a.codeVerifier);
expect(a.codeVerifier).not.toBe(a.nonce);
});
it("yields an RFC 7636 verifier (43-128 unreserved characters) and its S256 challenge", () => {
const { codeVerifier, codeChallenge } = deriveOidcSecrets("jti-1", key);
expect(codeVerifier).toMatch(/^[A-Za-z0-9_-]{43,128}$/);
expect(codeChallenge).toMatch(/^[A-Za-z0-9_-]{43}$/);
expect(codeChallenge).not.toBe(codeVerifier);
});
});

View file

@ -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<ReturnType<typeof buildApp>>[] = [];
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<ReturnType<typeof rig>>;
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<ReturnType<typeof acct>>;
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<string, string> = 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<string, unknown> };
}
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" });
});
});

View file

@ -0,0 +1,334 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
import { buildApp } from "../src/app.js";
import { issueAccessClaim } from "../src/claims.js";
import { type Provider } from "../src/contracts.js";
import { type OAuthProviderRuntime } from "../src/oauth.js";
import { createRuntimeKeyMaterial, decodeJwt, signJwt, verifyJwt } from "../src/signing.js";
import { IdentityHeldElsewhereError, InMemoryStore } from "../src/store/index.js";
import { createTestConfig, launchFlow, launchState, stateOf } from "./oauth-flow.js";
// The member's identity surface: list what an account holds, and take one
// identity off it. Taking one off is the account's own decision made with
// fresh proof (a step-up sign-in inside the proof window), never the
// bearer's alone. These tests drive both routes over HTTP as an app would.
const returnTo = "https://streampixels.gamecult.org/signin/return";
const spAuth = { "x-heimdall-app-secret": "streampixels-secret" };
const now = "2026-11-13T12:00:00.000Z";
function runtime(provider: "twitch" | "youtube", providerUserId: string): OAuthProviderRuntime {
return {
async exchangeAuthorizationCode() {
return { accessToken: "at", refreshToken: "rt", tokenType: "Bearer", scope: ["user:read:email"], raw: {} };
},
async resolveIdentity() {
return { provider, providerUserId, username: providerUserId, profile: { id: providerUserId } };
},
async evaluateEntitlements() {
return { facts: [], snapshots: [] };
},
};
}
const dir = mkdtempSync(join(tmpdir(), "heimdall-unlink-"));
const config = { ...createTestConfig(), signingPrivateKeyPath: join(dir, "signing.pem"), bootstrapSigningPrivateKeyOnMissing: true };
afterAll(() => rmSync(dir, { recursive: true, force: true }));
const apps: Awaited<ReturnType<typeof buildApp>>[] = [];
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<ReturnType<typeof rig>>;
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<string, unknown> };
}
const bearer = (token: string) => ({ authorization: `Bearer ${token}` });
const list = (r: Rig, token?: string) => r.app.inject({ method: "GET", url: "/v1/me/identities", headers: token ? bearer(token) : {} });
const unlink = (r: Rig, id: string, token?: string, payload?: unknown) =>
r.app.inject({ method: "POST", url: `/v1/me/identities/${encodeURIComponent(id)}/unlink`, headers: token ? bearer(token) : {}, ...(payload !== undefined ? { payload: payload as object } : {}) });
describe("step_up_at on the access claim", () => {
it("a step-up sign-in's claim carries it; an ordinary sign-in and a refresh do not", async () => {
const r = await rig();
await seedAccount(r, [["twitch", "t-1"], ["youtube", "y-1"]]);
const before = Math.floor(Date.now() / 1000);
const stepped = await signIn(r, true);
expect(stepped.claimSet.step_up_at).toBeGreaterThanOrEqual(before);
expect(stepped.claimSet.step_up_at).toBeLessThanOrEqual(Math.floor(Date.now() / 1000));
expect(stepped.claimSet.step_up_method).toBe("provider:twitch");
const plain = (await signIn(r, false)).claimSet;
expect(plain.step_up_at).toBeUndefined();
expect(plain.step_up_method).toBeUndefined();
const refreshed = await r.app.inject({ method: "POST", url: "/v1/apps/streampixels/sessions/refresh", payload: { refreshToken: stepped.refreshToken } });
expect(refreshed.statusCode).toBe(201);
expect(refreshed.json().claimSet.step_up_at, "a refresh never renews proof").toBeUndefined();
expect(refreshed.json().claimSet.step_up_method).toBeUndefined();
});
});
describe("GET /v1/me/identities", () => {
it("is 401 sign_in_required without a live bearer", async () => {
const r = await rig();
for (const token of [undefined, "not-a-token"]) {
const res = await list(r, token);
expect([res.statusCode, res.json().error]).toEqual([401, "sign_in_required"]);
}
});
it("lists the caller's identities and nothing that is a credential, a profile or an email", async () => {
const r = await rig();
const { account, rows } = await seedAccount(r, [["twitch", "t-1"], ["discord", "d-9"]]);
await seedAccount(r, [["youtube", "y-other"]]);
const { accessToken } = await signIn(r, false);
const res = await list(r, accessToken);
expect(res.statusCode).toBe(200);
expect(res.headers["cache-control"]).toBe("no-store");
const body = res.json();
expect(body.accountId).toBe(account.id);
expect(body.identities).toEqual([
// The sign-in above refreshed the twitch row from what the provider returned.
{ id: rows[0]!.id, provider: "twitch", providerUserId: "t-1", username: "t-1", linkedAt: now, scopes: ["user:read:email"] },
{ id: rows[1]!.id, provider: "discord", providerUserId: "d-9", username: "discord-name", displayName: "discord display", linkedAt: now, scopes: ["identify"] },
]);
expect(res.body).not.toMatch(/CIPHERTEXT|PROFILE-CANARY|secret@example|primary_email|primaryEmail/);
});
});
describe("POST /v1/me/identities/:identityId/unlink", () => {
it("is 401 without a live bearer", async () => {
const r = await rig();
const { rows } = await seedAccount(r, [["twitch", "t-1"], ["youtube", "y-1"]]);
expect((await unlink(r, rows[1]!.id)).statusCode).toBe(401);
expect((await unlink(r, rows[1]!.id, "garbage")).statusCode).toBe(401);
});
it("is 403 step_up_required for a bearer with no proof, and for a refresh-issued one, and removes nothing", async () => {
const r = await rig();
const { account, rows } = await seedAccount(r, [["twitch", "t-1"], ["youtube", "y-1"]]);
const plain = await signIn(r, false);
const denied = await unlink(r, rows[1]!.id, plain.accessToken);
expect([denied.statusCode, denied.json().error]).toEqual([403, "step_up_required"]);
expect(denied.json().detail).toMatch(/twitch, youtube and google/);
const stepped = await signIn(r, true);
const refreshed = await r.app.inject({ method: "POST", url: "/v1/apps/streampixels/sessions/refresh", payload: { refreshToken: stepped.refreshToken } });
const viaRefresh = await unlink(r, rows[1]!.id, refreshed.json().accessToken);
expect([viaRefresh.statusCode, viaRefresh.json().error]).toEqual([403, "step_up_required"]);
expect(await r.store.listStoredLinkedIdentitiesForAccount(account.id)).toHaveLength(2);
});
it("is 403 for proof older than the window and for proof dated in the future; 599 s old still passes", async () => {
const r = await rig();
const { account, rows } = await seedAccount(r, [["twitch", "t-1"], ["youtube", "y-1"], ["discord", "d-1"]]);
const issueWith = async (stepUpAt: number) =>
(await issueAccessClaim({
config,
keys: r.keys,
store: r.store,
input: { appSlug: "streampixels", accountId: account.id, linkedIdentities: [], facts: [], stepUpAt },
})).accessToken;
const nowS = Math.floor(Date.now() / 1000);
for (const at of [nowS - 601, nowS + 120]) {
const res = await unlink(r, rows[1]!.id, await issueWith(at));
expect([res.statusCode, res.json().error], String(at - nowS)).toEqual([403, "step_up_required"]);
}
expect(await r.store.listStoredLinkedIdentitiesForAccount(account.id)).toHaveLength(3);
const edge = await unlink(r, rows[1]!.id, await issueWith(nowS - 599));
expect(edge.statusCode).toBe(200);
});
it("a step-up sign-in's bearer unlinks: 200 with the remaining list, an audit event without credentials", async () => {
const r = await rig();
const { account, rows } = await seedAccount(r, [["twitch", "t-1"], ["discord", "d-9"]]);
const audit = vi.spyOn(r.store, "createAuditEvent");
const { accessToken } = await signIn(r, true);
const res = await unlink(r, rows[1]!.id, accessToken, null);
expect(res.statusCode).toBe(200);
expect(res.headers["cache-control"]).toBe("no-store");
expect(res.json().unlinked).toEqual({ id: rows[1]!.id, provider: "discord", providerUserId: "d-9" });
expect(res.json().identities.map((i: { id: string }) => i.id)).toEqual([rows[0]!.id]);
expect(res.body).not.toMatch(/CIPHERTEXT|PROFILE-CANARY|secret@example/);
expect(await r.store.listStoredLinkedIdentitiesForAccount(account.id)).toHaveLength(1);
const event = audit.mock.calls.map(([e]) => e).find((e) => e.eventType === "identity_unlinked");
expect(event?.accountId).toBe(account.id);
expect(event?.eventPayloadJson).toEqual({ provider: "discord", identityId: rows[1]!.id, stepUpMethod: "provider:twitch" });
});
it("the account's only identity is 409 last_identity and the row stays", async () => {
const r = await rig();
const { account, rows } = await seedAccount(r, [["twitch", "t-1"]]);
const { accessToken } = await signIn(r, true);
const res = await unlink(r, rows[0]!.id, accessToken);
expect([res.statusCode, res.json().error]).toEqual([409, "last_identity"]);
expect(await r.store.listStoredLinkedIdentitiesForAccount(account.id)).toHaveLength(1);
});
it("another account's identity and a nonexistent one are the same 404", async () => {
const r = await rig();
await seedAccount(r, [["twitch", "t-1"], ["discord", "d-9"]]);
const other = await seedAccount(r, [["youtube", "y-other"], ["github", "g-other"]]);
const { accessToken } = await signIn(r, true);
const foreign = await unlink(r, other.rows[0]!.id, accessToken);
const missing = await unlink(r, "no-such-id", accessToken);
expect([foreign.statusCode, foreign.json().error]).toEqual([404, "identity_not_found"]);
expect([missing.statusCode, missing.body]).toEqual([404, foreign.body]);
expect(await r.store.listStoredLinkedIdentitiesForAccount(other.account.id)).toHaveLength(2);
});
it("an unlinked identity belongs to no one, and another account can then link it, but not before", async () => {
const r = await rig();
const mine = await seedAccount(r, [["twitch", "t-1"], ["discord", "d-9"]]);
const theirs = await seedAccount(r, [["youtube", "y-other"]]);
const input = { accountId: theirs.account.id, provider: "discord" as const, providerUserId: "d-9", scopes: [], profileJson: {}, createdAt: now, updatedAt: now };
await expect(r.store.upsertLinkedIdentity(input)).rejects.toBeInstanceOf(IdentityHeldElsewhereError);
const { accessToken } = await signIn(r, true);
expect((await unlink(r, mine.rows[1]!.id, accessToken)).statusCode).toBe(200);
await expect(r.store.upsertLinkedIdentity(input)).resolves.toMatchObject({ accountId: theirs.account.id });
});
it("writes revocation receipts for the provider's live grants when its last identity goes, and not before", async () => {
const r = await rig();
const { account, rows } = await seedAccount(r, [["twitch", "t-1"], ["youtube", "y-1"], ["youtube", "y-2"]]);
const grant = async (provider: Provider) =>
(await r.store.createConsentReceipt({ kind: "grant", accountId: account.id, appSlug: "streampixels", provider, createdAt: now, scopesAsked: ["a"], scopesGranted: ["a"], consentPageDigest: "d", consentText: "t" })).receipt;
const ytGrant = await grant("youtube");
const twGrant = await grant("twitch");
const { accessToken } = await signIn(r, true);
// A second youtube identity remains: the grant's provider still holds a credential.
expect((await unlink(r, rows[1]!.id, accessToken)).statusCode).toBe(200);
expect((await r.store.listConsentReceipts(account.id)).filter((x) => x.kind === "revocation")).toHaveLength(0);
// The last youtube identity goes (twitch stays as the sign-in identity): youtube's grant is revoked, twitch's is not.
const audit = vi.spyOn(r.store, "createAuditEvent");
expect((await unlink(r, rows[2]!.id, accessToken)).statusCode).toBe(200);
const revocations = (await r.store.listConsentReceipts(account.id)).filter((x) => x.kind === "revocation");
expect(revocations.map((x) => x.kind === "revocation" && x.revokesReceiptId)).toEqual([ytGrant.id]);
expect(revocations.map((x) => x.provider)).toEqual(["youtube"]);
expect(twGrant.id).not.toBe(ytGrant.id);
expect(audit.mock.calls.map(([e]) => e.eventType)).toEqual(expect.arrayContaining(["identity_unlinked", "consent_revoked"]));
});
it("proof past the window refuses even a bearer that was fresh when issued", async () => {
const r = await rig();
const { rows } = await seedAccount(r, [["twitch", "t-1"], ["discord", "d-9"]]);
vi.useFakeTimers({ toFake: ["Date"] });
const { accessToken } = await signIn(r, true);
vi.setSystemTime(Date.now() + 601_000);
const res = await unlink(r, rows[1]!.id, accessToken);
expect([res.statusCode, res.json().error]).toEqual([403, "step_up_required"]);
});
it("the proof window's edge: exactly 600 s old still passes, 601 s does not (frozen clock)", async () => {
const r = await rig();
const { account, rows } = await seedAccount(r, [["twitch", "t-1"], ["youtube", "y-1"], ["discord", "d-1"]]);
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date("2026-11-13T12:00:00.000Z"));
const nowS = Math.floor(Date.now() / 1000);
const issueWith = async (stepUpAt: number) =>
(await issueAccessClaim({ config, keys: r.keys, store: r.store, input: { appSlug: "streampixels", accountId: account.id, linkedIdentities: [], facts: [], stepUpAt } })).accessToken;
const tooOld = await unlink(r, rows[1]!.id, await issueWith(nowS - 601));
expect([tooOld.statusCode, tooOld.json().error]).toEqual([403, "step_up_required"]);
const edge = await unlink(r, rows[1]!.id, await issueWith(nowS - 600));
expect(edge.statusCode).toBe(200);
});
it("a one-identity bearer naming another account's identity gets 404, not 409", async () => {
const r = await rig();
await seedAccount(r, [["twitch", "t-1"]]);
const other = await seedAccount(r, [["youtube", "y-other"], ["github", "g-other"]]);
const { accessToken } = await signIn(r, true);
const res = await unlink(r, other.rows[0]!.id, accessToken);
expect([res.statusCode, res.json().error]).toEqual([404, "identity_not_found"]);
});
it("a step_up state in a non-sign_in mode (forged, signed) yields no step_up_at", async () => {
const r = await rig();
const { account } = await seedAccount(r, [["twitch", "t-1"]]);
const started = await r.app.inject({
method: "POST",
url: "/v1/oauth/twitch/start",
headers: spAuth,
payload: { appSlug: "streampixels", mode: "link", initiatingAccountId: account.id, returnTo },
});
expect(started.statusCode).toBe(201);
const verified = verifyJwt(stateOf(started.json()), r.keys.publicKey) as { valid: boolean; payload: Record<string, unknown> };
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();
});
});

320
tests/idunn-boot.test.ts Normal file
View file

@ -0,0 +1,320 @@
import { execFile, spawn, type ChildProcess } from "node:child_process";
import { createPublicKey, createPrivateKey, verify } from "node:crypto";
import dgram from "node:dgram";
import { chmod, copyFile, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
import { closeSync, openSync } from "node:fs";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { decode, encode } from "@msgpack/msgpack";
import {
RUNTIME_PRESENCE_SLOT,
parseCultNetMessage,
runtimePresenceActivationSigningMessage,
runtimePresenceProviderSigningMessage,
} from "cultnet-ts";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { startFakeIdunnRudp, type FakeIdunnRudp } from "./fixtures/fake-idunn-rudp.js";
import { idunnRuntimeFixtures } from "./fixtures/presence-descriptors.js";
const run = promisify(execFile);
const GENERATION_UID = 61184;
const STATE_GID = 4242;
const ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
const PKCS8_ED25519_SEED_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
// The launch needs root (to pick the uid and bind a machine-id) and a mount
// namespace (so the fixture machine-id does not replace the host's). The
// stopgap's node container has both; anywhere else the test steps aside.
const canLaunch =
process.getuid?.() === 0 &&
(await run("unshare", ["--mount", "--", "true"]).then(
() => true,
() => false
));
/**
* The artifact under test. By default the esbuild bundle `pnpm bundle` makes,
* run by this process's node; a runbook proves a sealed release by naming its
* bundle and node here instead.
*/
const bundleOverride = process.env.HEIMDALL_BOOT_BUNDLE;
const nodeOverride = process.env.HEIMDALL_BOOT_NODE;
async function freePort(): Promise<number> {
return new Promise((resolve, reject) => {
const probe = net.createServer();
probe.once("error", reject);
probe.listen(0, "127.0.0.1", () => {
const { port } = probe.address() as net.AddressInfo;
probe.close(() => resolve(port));
});
});
}
interface Launch {
child: ChildProcess;
stderr: () => string;
exited: Promise<number | null>;
candidatePort: number;
}
describe.skipIf(!canLaunch)("the bundle booted as Idunn launches it", () => {
let base: string;
let bundle: string;
let node: string;
let idunn: FakeIdunnRudp;
let odin: dgram.Socket;
let odinPort: number;
const launched: ChildProcess[] = [];
beforeAll(async () => {
base = await mkdtemp(path.join(os.tmpdir(), "heimdall-boot-"));
await chmod(base, 0o755);
if (bundleOverride) {
bundle = bundleOverride;
} else {
await run("corepack", ["pnpm", "bundle"], { cwd: path.join(import.meta.dirname, "..") });
bundle = path.join(base, "heimdall.mjs");
await copyFile(path.join(import.meta.dirname, "..", "dist", "heimdall"), bundle);
await chmod(bundle, 0o644);
}
node = nodeOverride ?? process.execPath;
idunn = await startFakeIdunnRudp();
odin = dgram.createSocket("udp4");
await new Promise<void>((resolve) => odin.bind(0, "127.0.0.1", resolve));
odinPort = odin.address().port;
}, 120_000);
afterAll(() => {
for (const child of launched) child.kill("SIGKILL");
idunn?.close();
odin?.close();
});
/** Credential files as Idunn holds them: readable only by the parent. */
async function credentials(dir: string, identity: Buffer | undefined) {
await mkdir(dir, { recursive: true });
const seed = path.join(dir, "activation-key.seed");
await copyFile(path.join(idunnRuntimeFixtures, "activation-key.seed"), seed);
await chmod(seed, 0o400);
let identityFile: string | undefined;
if (identity) {
identityFile = path.join(dir, "provider-identity.credential");
await writeFile(identityFile, identity, { mode: 0o400 });
}
return { seed, identityFile };
}
/** Start the bundle as the generation unit does, with the fixture machine-id bound over the host's. */
async function launch(label: string, identity: Buffer | undefined): Promise<Launch> {
const dir = path.join(base, label);
await mkdir(dir, { recursive: true });
await chmod(dir, 0o755);
// Idunn's runtime bundle: the two records, read-only.
const bundleDir = path.join(dir, "bundle");
await mkdir(bundleDir);
for (const name of ["expected.cc", "activation.cc"]) {
await copyFile(path.join(idunnRuntimeFixtures, name), path.join(bundleDir, name));
await chmod(path.join(bundleDir, name), 0o444);
}
await chmod(bundleDir, 0o555);
const machineId = path.join(dir, "machine-id");
await copyFile(path.join(idunnRuntimeFixtures, "machine-id"), machineId);
await chmod(machineId, 0o444);
const stateRoot = path.join(dir, "state");
await mkdir(stateRoot);
await run("chown", [`0:${STATE_GID}`, stateRoot]);
await chmod(stateRoot, 0o2770);
const heimdall = path.join(dir, "heimdall.mjs");
await copyFile(bundle, heimdall);
await chmod(heimdall, 0o444);
const files = await credentials(path.join(dir, "credentials"), identity);
const candidatePort = await freePort();
const fds = [openSync(files.seed, "r")];
const names = ["gamecult-idunn-runtime-activation-key"];
if (files.identityFile) {
fds.push(openSync(files.identityFile, "r"));
names.push("gamecult-runtime-presence-identity");
}
const env = {
PATH: process.env.PATH ?? "",
LISTEN_FDS: String(fds.length),
LISTEN_FDNAMES: names.join(":"),
GAMECULT_IDUNN_CANDIDATE_BIND: `127.0.0.1:${candidatePort}`,
GAMECULT_IDUNN_RUNTIME_BUNDLE: bundleDir,
GAMECULT_IDUNN_PROCESS_WRITE_LEASE: path.join(dir, "process-write-lease.cc"),
GC_ACCESS_BASE_URL: "https://heimdall.test",
GC_ACCESS_ISSUER: "https://heimdall.test",
GC_ACCESS_STORAGE_BACKEND: "memory",
GC_ACCESS_IDUNN_RUDP_HEALTH: `127.0.0.1:${idunn.port}`,
GC_ACCESS_IDUNN_HEALTH_CONTRACT: "heimdall.cultnet-rudp-provider-health",
GC_ACCESS_ODIN_CULTMESH_URI: `rudp://127.0.0.1:${odinPort}`,
CULTMESH_URI_ODIN_RUDP: `rudp://127.0.0.1:${odinPort}`,
GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP: "1",
GC_ACCESS_SIGNING_PRIVATE_KEY_PATH: path.join(stateRoot, "signing.pem"),
GC_ACCESS_SIGNING_KEY_ID: "boot-test",
};
// uid, gid and umask as Idunn's DynamicUser unit gives them. The fixture
// machine-id is bound only inside this mount namespace.
const script =
`mount --bind ${machineId} /etc/machine-id && ` +
`exec setpriv --reuid ${GENERATION_UID} --regid ${STATE_GID} --clear-groups ` +
`sh -c 'umask 0007; cd ${dir}; exec ${node} heimdall.mjs --state-root ${stateRoot}'`;
const child = spawn("unshare", ["--mount", "--", "sh", "-c", script], {
env,
stdio: ["ignore", "ignore", "pipe", ...fds],
});
launched.push(child);
fds.forEach((fd) => closeSync(fd));
let stderr = "";
child.stderr!.on("data", (chunk: Buffer) => {
stderr += chunk.toString();
});
const exited = new Promise<number | null>((resolve) => child.once("exit", (code) => resolve(code)));
return { child, stderr: () => stderr, exited, candidatePort };
}
async function answers(port: number): Promise<number | undefined> {
return fetch(`http://127.0.0.1:${port}/.well-known/jwks.json`).then(
(response) => response.status,
() => undefined
);
}
it("signs warming presence on every pulse and answers HTTP", async () => {
const credential = await readFile(path.join(idunnRuntimeFixtures, "provider-identity.credential"));
const generation = await launch("signs", credential);
// Startup publication, then one per 10 s pulse. A publication fault is
// reported as it is logged rather than after the frames never arrive.
const publicationFault = new Promise<never>((_resolve, reject) => {
const watch = setInterval(() => {
if (generation.stderr().includes(" failed on ")) {
clearInterval(watch);
reject(new Error(`publication failed; stderr: ${generation.stderr()}`));
}
}, 200);
void idunn.frame(2).then(() => clearInterval(watch));
});
const exitedEarly = generation.exited.then((code) => {
throw new Error(`bundle exited ${code}; stderr: ${generation.stderr()}`);
});
// The first statement is the startup publication, which follows the listen
// directly; the 10 s pulse loop has not yet fired.
await Promise.race([
idunn.frame(0),
publicationFault,
exitedEarly,
new Promise<never>((_resolve, reject) =>
setTimeout(() => reject(new Error(`no presence at startup; stderr: ${generation.stderr()}`)), 8_000)
),
]);
await Promise.race([idunn.frame(2), publicationFault, exitedEarly]);
expect(await answers(generation.candidatePort)).toBe(200);
// Public keys of the two proofs, from the fixtures' test keys.
const store = decode(credential) as unknown[][];
const record = decode(store[0]![2] as Uint8Array) as unknown[];
const providerKey = createPublicKey({
key: Buffer.concat([ED25519_SPKI_PREFIX, Buffer.from(record[2] as number[])]),
format: "der",
type: "spki",
});
const activationKey = createPublicKey(
createPrivateKey({
key: Buffer.concat([
PKCS8_ED25519_SEED_PREFIX,
await readFile(path.join(idunnRuntimeFixtures, "activation-key.seed")),
]),
format: "der",
type: "pkcs8",
})
);
let previousSequence = 0;
for (const frame of idunn.frames.slice(0, 3)) {
const message = parseCultNetMessage(decode(frame.payload), "cultnet.schema.v0");
if (message.schemaVersion !== "cultnet.document_put_raw.v0") throw new Error("not a raw document put");
const fields = decode(message.document.payload) as unknown[];
expect(fields[RUNTIME_PRESENCE_SLOT.state]).toBe("warming");
const unsigned = [...fields];
unsigned[RUNTIME_PRESENCE_SLOT.signature] = new Uint8Array();
unsigned[RUNTIME_PRESENCE_SLOT.activationSignature] = new Uint8Array();
const proof = encode(unsigned);
expect(
verify(
null,
runtimePresenceProviderSigningMessage(proof),
providerKey,
fields[RUNTIME_PRESENCE_SLOT.signature] as Uint8Array
)
).toBe(true);
expect(
verify(
null,
runtimePresenceActivationSigningMessage(proof),
activationKey,
fields[RUNTIME_PRESENCE_SLOT.activationSignature] as Uint8Array
)
).toBe(true);
const sequence = fields[RUNTIME_PRESENCE_SLOT.publisherSequence] as number;
expect(sequence).toBeGreaterThan(previousSequence);
previousSequence = sequence;
}
expect(generation.stderr()).not.toContain("failed on startup");
expect(generation.stderr()).not.toContain("failed on interval");
generation.child.kill("SIGKILL");
}, 90_000);
it.each([
["the identity descriptor is not passed", undefined, "gamecult-runtime-presence-identity"],
["the identity is damaged", "damaged", "identity id check"],
])("exits before listening when %s", async (_name, damage, expected) => {
const credential = await readFile(path.join(idunnRuntimeFixtures, "provider-identity.credential"));
const store = decode(credential) as unknown[][];
const record = decode(store[0]![2] as Uint8Array) as unknown[];
const publicKey = [...(record[2] as number[])];
const original = { publicKeyHex: Buffer.from(publicKey).toString("hex"), id: record[1] as string, binding: record[5] as string };
let identity: Buffer | undefined;
if (damage) {
publicKey[0] = publicKey[0]! ^ 1;
record[2] = publicKey;
identity = Buffer.from(encode([[store[0]![0], store[0]![1], encode(record), store[0]![3], store[0]![4]]]));
}
const started = Date.now();
const generation = await launch(damage ? "damaged" : "no-identity", identity);
const code = await Promise.race([
generation.exited,
new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), 5_000)),
]);
expect(code, generation.stderr()).not.toBe("timeout");
expect(code).not.toBe(0);
expect(Date.now() - started).toBeLessThan(6_000);
expect(await answers(generation.candidatePort)).toBeUndefined();
expect(generation.stderr()).toContain(expected);
// No byte of the credential: not the key bytes, not the id, not the binding.
expect(generation.stderr()).not.toContain(original.publicKeyHex);
expect(generation.stderr()).not.toContain(original.id.slice(0, 16));
expect(generation.stderr()).not.toContain(original.binding.slice(-16));
}, 30_000);
});

View file

@ -1,18 +1,12 @@
import dgram from "node:dgram";
import { mkdtemp } from "node:fs/promises"; import { mkdtemp } from "node:fs/promises";
import os from "node:os"; import os from "node:os";
import path from "node:path"; import path from "node:path";
import { decode } from "@msgpack/msgpack"; import { decode } from "@msgpack/msgpack";
import { import { parseCultNetMessage } from "cultnet-ts";
CultNetRudpSession,
decodeRudpPacket,
encodeRudpPacket,
parseCultNetMessage,
type CultNetTransportFrame,
} from "cultnet-ts";
import { describe, expect, it, vi } from "vitest"; import { describe, expect, it, vi } from "vitest";
import { loadConfig } from "../src/config.js"; import { loadConfig } from "../src/config.js";
import { publishIdunnRudpHealth } from "../src/idunn-rudp-health.js"; import { publishIdunnRudpHealth } from "../src/idunn-rudp-health.js";
import { startFakeIdunnRudp } from "./fixtures/fake-idunn-rudp.js";
vi.mock("node:fs/promises", async (importOriginal) => { vi.mock("node:fs/promises", async (importOriginal) => {
const original = await importOriginal<typeof import("node:fs/promises")>(); const original = await importOriginal<typeof import("node:fs/promises")>();
@ -27,37 +21,12 @@ vi.mock("node:fs/promises", async (importOriginal) => {
describe("Heimdall Idunn health publication", () => { describe("Heimdall Idunn health publication", () => {
it("completes the canonical RUDP handshake before publishing its signed frame", async () => { it("completes the canonical RUDP handshake before publishing its signed frame", async () => {
const server = dgram.createSocket("udp4"); const server = await startFakeIdunnRudp();
const session = new CultNetRudpSession({
connectionId: 0x1d0d0001,
initialSequence: 1,
resendDelayMs: 100,
});
let resolveFrame!: (frame: CultNetTransportFrame) => void;
const frameReceived = new Promise<CultNetTransportFrame>((resolve) => {
resolveFrame = resolve;
});
server.on("message", (wire, remote) => {
const packet = decodeRudpPacket(wire);
if (packet.packetType === "connect") {
server.send(encodeRudpPacket(session.acceptConnect(packet, Date.now())), remote.port, remote.address);
return;
}
const result = session.receive(packet, Date.now());
if (result.reply) server.send(encodeRudpPacket(result.reply), remote.port, remote.address);
for (const frame of result.delivered) resolveFrame(frame);
if (result.delivered.length > 0) {
server.send(encodeRudpPacket(session.createAck()), remote.port, remote.address);
}
});
await new Promise<void>((resolve) => server.bind(0, "127.0.0.1", resolve));
try { try {
const tmp = await mkdtemp(path.join(os.tmpdir(), "heimdall-idunn-rudp-")); const tmp = await mkdtemp(path.join(os.tmpdir(), "heimdall-idunn-rudp-"));
const address = server.address();
const config = loadConfig({ const config = loadConfig({
GC_ACCESS_IDUNN_RUDP_HEALTH: `127.0.0.1:${address.port}`, GC_ACCESS_IDUNN_RUDP_HEALTH: `127.0.0.1:${server.port}`,
GC_ACCESS_PROVIDER_HEALTH_IDENTITY_PATH: path.join(tmp, "provider-health-identity.cc"), GC_ACCESS_PROVIDER_HEALTH_IDENTITY_PATH: path.join(tmp, "provider-health-identity.cc"),
}); });
const observedAt = "2026-08-22T00:45:00.000Z"; const observedAt = "2026-08-22T00:45:00.000Z";
@ -78,7 +47,7 @@ describe("Heimdall Idunn health publication", () => {
observedAt, observedAt,
presence, presence,
}); });
const frame = await frameReceived; const frame = await server.frame(0);
const message = parseCultNetMessage(decode(frame.payload), "cultnet.schema.v0"); const message = parseCultNetMessage(decode(frame.payload), "cultnet.schema.v0");
expect(frame.channelId).toBe("schema"); expect(frame.channelId).toBe("schema");

View file

@ -0,0 +1,686 @@
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, startOAuthFlow } from "../src/app.js";
import { resolveAppCaller } from "../src/app-caller.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";
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<typeof import("node:zlib")>();
return {
...real,
inflateRawSync: ((buf: Parameters<typeof real.inflateRawSync>[0], opts?: Parameters<typeof real.inflateRawSync>[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.
const apps: FastifyInstance[] = [];
afterEach(async () => {
vi.useRealTimers();
vi.restoreAllMocks();
while (apps.length) await apps.pop()?.close();
});
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-<user>` 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<string, unknown> = { kind: "browser_completion" }) {
const response = await app.inject({
method: "POST",
url: "/v1/oauth/joystick/start",
headers: secret,
payload: {
appSlug: "streampixels",
mode: "connect",
connection: { kind: "creator", targetId: "creator-1" },
returnTo: "https://streampixels.gamecult.org/settings",
handoff,
},
});
expect(response.statusCode).toBe(201);
return stateOf(response.json());
}
const launchUrl = (state: string) => `/v1/oauth/joystick/launch?state=${encodeURIComponent(state)}`;
const cookieNamed = (prefix: string) => (response: { headers: Record<string, unknown> }) =>
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 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);
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") {
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 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, bindingCookieOf(go)!, `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<Record<string, any>>; receipts: Array<Record<string, any>> };
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("<script");
expect(page.headers["content-security-policy"]).toContain("form-action 'self' https://joystick.tv");
});
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("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 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("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("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 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 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).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<typeof getHeimdallRuntimeContext>, 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 inflated under that cap", 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" });
// 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" });
});
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 () => {
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 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" },
{ ...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_not_bound" });
expect(await store.findStoredLinkedIdentity("joystick", "joy-a")).toBeNull();
const events = [...(store as unknown as { auditEvents: Map<string, { eventType: string; eventPayloadJson: unknown }> }).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<string, { eventType: string }> }).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<Record<string, unknown>> = [];
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);
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"],
["error", "consent_refused", "provider"],
]);
});
});
/** 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<typeof stateOf>[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);
const go = await answer(app, state, "continue", cookie);
expect(go.statusCode).toBe(302);
return { state, cookie: bindingCookieOf(go)! };
}
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("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(/&#39;/g, "'").replace(/&quot;/g, '"').replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&amp;/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);
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);
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}/);
});
});
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);
const events = [...(store as unknown as { auditEvents: Map<string, { eventType: string }> }).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 () => {
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("<script");
const token = url.searchParams.get("t")!;
const post = await app.inject({
method: "POST",
url: `/v1/me/grants/${a.consentReceiptId}/revoke`,
headers: { ...form, accept: "text/html" },
payload: new URLSearchParams({ t: token }).toString(),
});
expect(post.statusCode).toBe(200);
expect(post.body).toContain("Taken back.");
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")!;
// 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);
// 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<string, { eventType: string }> }).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");
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);
});
});

284
tests/link-binding.test.ts Normal file
View file

@ -0,0 +1,284 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { buildApp } from "../src/app.js";
import { type HeimdallConfig } from "../src/config.js";
import { type OAuthProviderRuntime } from "../src/oauth.js";
import { createRuntimeKeyMaterial, signJwt, verifyJwt } from "../src/signing.js";
import { IdentityHeldElsewhereError, InMemoryStore } from "../src/store/index.js";
import { launchFlow } from "./oauth-flow.js";
function createTestConfig(): HeimdallConfig {
return {
serviceName: "heimdall",
host: "127.0.0.1",
port: 4100,
workspaceRoot: "E:/Projects/Heimdall",
dataRoot: "E:/Projects/Heimdall/.heimdall-data",
cultCachePath: "E:/Projects/Heimdall/.heimdall-data/cultcache/heimdall.service.cc",
publicBaseUrl: "https://heimdall.gamecult.org",
issuer: "https://heimdall.gamecult.org",
daemonId: "yggdrasil-heimdall",
idunnRudpHealth: undefined,
idunnHealthContract: "heimdall.cultnet-rudp-provider-health",
providerHealthIdentityPath: "E:/Projects/Heimdall/.heimdall-data/provider-health-identity.cc",
sessionTtlSeconds: 3600,
refreshTtlSeconds: 60 * 60 * 24 * 30,
stateTtlSeconds: 600,
completionTtlSeconds: 300,
bootstrapSigningPrivateKeyOnMissing: false,
tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"),
appSharedSecrets: {
streampixels: "streampixels-secret",
repixelizer: "repixelizer-secret",
bifrost: "bifrost-secret",
},
appBackendCallbacks: {
bifrost: ["https://bifrost.gamecult.org/auth/heimdall/callback"],
repixelizer: ["https://repixelizer.gamecult.org/api/auth/heimdall/callback"],
},
storage: {
backend: "memory",
applySchemaOnStartup: true,
},
providers: {
discord: { clientId: "discord-client", clientSecret: "discord-secret" },
patreon: { clientId: "patreon-client", clientSecret: "patreon-secret" },
github: { clientId: "github-client", clientSecret: "github-secret" },
twitch: { clientId: "twitch-client", clientSecret: "twitch-secret" },
youtube: { clientId: "youtube-client", clientSecret: "youtube-secret" },
spotify: { clientId: "spotify-client", clientSecret: "spotify-secret" },
joystick: { clientId: "joystick-client", clientSecret: "joystick-secret" },
google: { clientId: "google-client", clientSecret: "google-secret" },
},
};
}
// Link mode binds a provider identity to the account an authenticated app
// named at start. These tests pin the three places that binding is decided:
// the callback (initiator), the completion row (target), and redeem (caller,
// target, replay).
const returnTo = "https://repixelizer.gamecult.org/app/";
const appAuth = { "x-heimdall-app-secret": "repixelizer-secret" };
function discordRuntime(providerUserId: string): OAuthProviderRuntime {
return {
async exchangeAuthorizationCode() {
return { accessToken: "at", refreshToken: "rt", tokenType: "Bearer", scope: ["identify"], raw: {} };
},
async resolveIdentity() {
return { provider: "discord", providerUserId, username: providerUserId, profile: { id: providerUserId } };
},
async evaluateEntitlements() {
return { facts: [], snapshots: [] };
},
};
}
const apps: Awaited<ReturnType<typeof buildApp>>[] = [];
afterEach(async () => {
vi.useRealTimers();
await Promise.all(apps.splice(0).map((app) => app.close()));
});
async function rig(providerUserId: string, config: HeimdallConfig = createTestConfig()) {
const store = new InMemoryStore();
const app = await buildApp({ config, store, oauthRuntimes: { discord: discordRuntime(providerUserId) } });
apps.push(app);
const now = new Date().toISOString();
const initiator = await store.createAccount({ createdAt: now, lastSeenAt: now });
return { app, store, initiator };
}
type Rig = Awaited<ReturnType<typeof rig>>;
function start(r: Rig, payload: Record<string, unknown>, headers: Record<string, string> = appAuth) {
return r.app.inject({ method: "POST", url: "/v1/oauth/discord/start", headers, payload: { appSlug: "repixelizer", returnTo, ...payload } });
}
/** The browser follows authorizationUrl through the launch hop, then returns with the state, or with `forged` in its place, and the cookie it was handed. */
async function callback(r: Rig, started: { authorizationUrl: string }, forged?: (state: string) => string) {
const flow = await launchFlow(r.app, started);
const state = forged ? forged(flow.state) : flow.state;
return r.app.inject({
method: "GET",
url: `/v1/oauth/discord/callback?code=c&state=${encodeURIComponent(state)}`,
headers: { cookie: flow.cookie },
});
}
function redeem(r: Rig, payload: Record<string, unknown>, headers: Record<string, string> = {}) {
return r.app.inject({ method: "POST", url: "/v1/apps/repixelizer/auth-completions/redeem", headers, payload });
}
describe("link start names its initiator", () => {
it("refuses an unauthenticated link start, a missing or unknown initiator, and an initiator outside link mode", async () => {
const r = await rig("d-1");
const mode = { mode: "link", initiatingAccountId: r.initiator.id };
expect((await start(r, mode, {})).statusCode).toBe(401);
expect((await start(r, mode, { "x-heimdall-app-secret": "wrong" })).statusCode).toBe(401);
const missing = await start(r, { mode: "link" });
expect([missing.statusCode, missing.json().error]).toEqual([400, "link_initiator_required"]);
const unknown = await start(r, { mode: "link", initiatingAccountId: "no-such-account" });
expect([unknown.statusCode, unknown.json().error]).toEqual([400, "link_initiator_unknown"]);
const stray = await start(r, { mode: "sign_in", initiatingAccountId: r.initiator.id }, {});
expect([stray.statusCode, stray.json().error]).toEqual([400, "initiator_only_in_link_mode"]);
});
});
describe("sign_in start carries no connection target", () => {
it("refuses connection.targetId on sign_in with connection_not_allowed_in_sign_in, with or without app auth", async () => {
const r = await rig("d-si");
const connection = { kind: "creator", targetId: "victim-target" };
for (const headers of [{}, appAuth]) {
const res = await start(r, { mode: "sign_in", connection }, headers);
expect([res.statusCode, res.json().error]).toEqual([400, "connection_not_allowed_in_sign_in"]);
}
expect((await start(r, { mode: "sign_in" }, {})).statusCode).toBe(201);
});
});
describe("link callback holds the provider identity to the initiator", () => {
it("attaches an unlinked identity to the initiating account, not a new one", async () => {
const r = await rig("d-new");
const started = await start(r, { mode: "link", initiatingAccountId: r.initiator.id });
expect(started.statusCode).toBe(201);
const done = await callback(r, started.json());
expect(done.statusCode).toBe(201);
expect(done.json().account.id).toBe(r.initiator.id);
expect((await r.store.findAccountByLinkedIdentity("discord", "d-new"))?.id).toBe(r.initiator.id);
});
it("refuses with link_initiator_mismatch when the identity already belongs to another account, and mints nothing", async () => {
const r = await rig("d-held");
const now = new Date().toISOString();
const other = await r.store.createAccount({ createdAt: now, lastSeenAt: now });
await r.store.upsertLinkedIdentity({ accountId: other.id, provider: "discord", providerUserId: "d-held", scopes: [], profileJson: {}, createdAt: now, updatedAt: now });
const started = await start(r, { mode: "link", initiatingAccountId: r.initiator.id });
const done = await callback(r, started.json());
expect(done.statusCode).toBe(403);
expect(done.json().error).toBe("link_initiator_mismatch");
expect(done.json().completion).toBeUndefined();
expect(done.body).not.toContain("accessToken");
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 {
const config = { ...createTestConfig(), signingPrivateKeyPath: join(dir, "signing.pem"), bootstrapSigningPrivateKeyOnMissing: true };
const r = await rig("d-forged", config);
const keys = createRuntimeKeyMaterial({ ...config, bootstrapSigningPrivateKeyOnMissing: false });
const started = await start(r, { mode: "link", initiatingAccountId: r.initiator.id });
const done = await callback(r, started.json(), (state) => {
const verified = verifyJwt(state, keys.publicKey) as { valid: boolean; payload: Record<string, unknown> };
expect(verified.valid).toBe(true);
return signJwt({ ...verified.payload, initiator_account_id: null }, keys);
});
expect([done.statusCode, done.json().error]).toEqual([403, "link_initiator_missing"]);
expect(await r.store.findAccountByLinkedIdentity("discord", "d-forged")).toBeNull();
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
describe("redeem binds caller, target and replay", () => {
async function linked(r: Rig, targetId: string | undefined) {
const started = await start(r, {
mode: "link",
initiatingAccountId: r.initiator.id,
...(targetId ? { connection: { kind: "account", targetId } } : {}),
});
const done = await callback(r, started.json());
expect(done.statusCode).toBe(201);
return done.json().completion.code as string;
}
it("redeems a link completion only for the authenticated app, and a refused caller does not burn the code", async () => {
const r = await rig("d-r1");
const completionCode = await linked(r, undefined);
const anonymous = await redeem(r, { completionCode });
expect([anonymous.statusCode, anonymous.json().error]).toEqual([401, "app_auth_required"]);
expect((await redeem(r, { completionCode }, { "x-heimdall-app-secret": "wrong" })).statusCode).toBe(401);
expect((await redeem(r, { completionCode }, appAuth)).statusCode).toBe(201);
});
it("refuses a wrong or missing target with completion_target_mismatch without consuming the code", async () => {
const r = await rig("d-r2");
const completionCode = await linked(r, "target-a");
for (const payload of [{ completionCode, targetId: "target-b" }, { completionCode }]) {
const refused = await redeem(r, payload, appAuth);
expect([refused.statusCode, refused.json().error]).toEqual([403, "completion_target_mismatch"]);
expect(refused.json().accessToken).toBeUndefined();
}
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");
expect((await redeem(r, { completionCode, targetId: "target-a" }, appAuth)).statusCode).toBe(201);
expect((await redeem(r, { completionCode, targetId: "target-a" }, appAuth)).statusCode).toBe(410);
});
it("refuses a completion at and after its expiry with 410, whatever the caller and target, and honours it just before", async () => {
// completionTtlSeconds is 300. Only Date is faked: the app and store run on real timers.
vi.useFakeTimers({ toFake: ["Date"] });
const t0 = Date.parse("2026-11-03T00:00:00.000Z");
const ttlMs = createTestConfig().completionTtlSeconds * 1000;
const expired = { statusCode: 410, error: "invalid_or_expired_completion_code" };
const outcome = async (r: Rig, payload: Record<string, unknown>) => {
const res = await redeem(r, payload, appAuth);
return { statusCode: res.statusCode, error: res.json().error };
};
vi.setSystemTime(t0);
const r = await rig("d-exp");
const code = await linked(r, "target-a");
const row = await r.store.findAuthCompletion("repixelizer", code);
expect(row?.expiresAt).toBe(new Date(t0 + ttlMs).toISOString());
// Just before expiry the right caller and target redeem it.
const early = await rig("d-exp-early");
const earlyCode = await linked(early, "target-a");
vi.setSystemTime(t0 + ttlMs - 1);
expect((await redeem(early, { completionCode: earlyCode, targetId: "target-a" }, appAuth)).statusCode).toBe(201);
// At the expiry instant and after it: 410, for the right target and for a wrong one (not 403), unconsumed.
for (const at of [t0 + ttlMs, t0 + ttlMs + 1]) {
vi.setSystemTime(at);
expect(await outcome(r, { completionCode: code, targetId: "target-a" })).toEqual(expired);
expect(await outcome(r, { completionCode: code, targetId: "target-b" })).toEqual(expired);
}
expect((await r.store.findAuthCompletion("repixelizer", code))?.consumedAt).toBeUndefined();
});
it("stores the target on the completion row", async () => {
const r = await rig("d-r4");
const completionCode = await linked(r, "target-a");
expect((await r.store.findAuthCompletion("repixelizer", completionCode))?.targetId).toBe("target-a");
});
});

File diff suppressed because it is too large Load diff

158
tests/oauth-flow.ts Normal file
View file

@ -0,0 +1,158 @@
import { expect } from "vitest";
import { type FastifyInstance } from "fastify";
import { type HeimdallConfig } from "../src/config.js";
import { entitlementFacts } from "../src/facts.js";
import { type OAuthProviderRuntime } from "../src/oauth.js";
import { decodeJwt } from "../src/signing.js";
export function createTestConfig(): HeimdallConfig {
return {
serviceName: "heimdall",
host: "127.0.0.1",
port: 4100,
workspaceRoot: "E:/Projects/Heimdall",
dataRoot: "E:/Projects/Heimdall/.heimdall-data",
cultCachePath: "E:/Projects/Heimdall/.heimdall-data/cultcache/heimdall.service.cc",
publicBaseUrl: "https://heimdall.gamecult.org",
issuer: "https://heimdall.gamecult.org",
daemonId: "yggdrasil-heimdall",
idunnRudpHealth: undefined,
idunnHealthContract: "heimdall.cultnet-rudp-provider-health",
providerHealthIdentityPath: "E:/Projects/Heimdall/.heimdall-data/provider-health-identity.cc",
sessionTtlSeconds: 3600,
refreshTtlSeconds: 60 * 60 * 24 * 30,
stateTtlSeconds: 600,
completionTtlSeconds: 300,
bootstrapSigningPrivateKeyOnMissing: false,
tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"),
appSharedSecrets: {
streampixels: "streampixels-secret",
repixelizer: "repixelizer-secret",
bifrost: "bifrost-secret",
},
appBackendCallbacks: {
bifrost: ["https://bifrost.gamecult.org/auth/heimdall/callback"],
repixelizer: ["https://repixelizer.gamecult.org/api/auth/heimdall/callback"],
},
storage: {
backend: "memory",
applySchemaOnStartup: true,
},
providers: {
discord: { clientId: "discord-client", clientSecret: "discord-secret" },
patreon: { clientId: "patreon-client", clientSecret: "patreon-secret" },
github: { clientId: "github-client", clientSecret: "github-secret" },
twitch: { clientId: "twitch-client", clientSecret: "twitch-secret" },
youtube: { clientId: "youtube-client", clientSecret: "youtube-secret" },
spotify: { clientId: "spotify-client", clientSecret: "spotify-secret" },
joystick: { clientId: "joystick-client", clientSecret: "joystick-secret" },
google: { clientId: "google-client", clientSecret: "google-secret" },
},
};
}
export function createMockDiscordRuntime(): OAuthProviderRuntime {
return {
async exchangeAuthorizationCode() {
return {
accessToken: "discord-access-token",
refreshToken: "discord-refresh-token",
tokenType: "Bearer",
scope: ["identify", "guilds.members.read"],
expiresAt: "2026-04-26T13:00:00.000Z",
raw: { source: "test" },
};
},
async resolveIdentity() {
return {
provider: "discord",
providerUserId: "discord-user-123",
username: "meta",
displayName: "Meta",
primaryEmail: "meta@gamecult.org",
profile: { id: "discord-user-123", username: "meta" },
};
},
async evaluateEntitlements({ callback }) {
return {
facts: [entitlementFacts.appAccess],
snapshots: [
{
accountId: callback.accountId,
provider: "discord",
scope: "repixelizer:discord_role_access:gamecult-guild",
evaluatedAt: "2026-04-26T12:00:00.000Z",
isAllowed: true,
reasonCode: "matched_role",
reasonDetail: "Matched Repixelizer access role.",
rawSummaryJson: {
guildId: "gamecult-guild",
matchedRoles: ["role-repixelizer"],
},
},
],
};
},
};
}
/** What a start returns that the browser needs: the launch URL, whose query carries the signed state. */
export interface StartBody {
authorizationUrl: string;
}
export function stateOf(start: StartBody): string {
return new URL(start.authorizationUrl).searchParams.get("state") ?? "";
}
export interface LaunchedFlow {
state: string;
/** The `name=value` pair a browser sends back to the callback. */
cookie: string;
}
export function setCookieOf(response: { headers: Record<string, unknown> }): string[] {
return [response.headers["set-cookie"]].flat().filter((value): value is string => typeof value === "string");
}
async function followLaunch(app: FastifyInstance, state: string): Promise<LaunchedFlow & { providerUrl: URL }> {
const provider = decodeJwt(state).payload.provider as string;
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-ask-"));
expect(asked, "the ask sets its own 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();
return { state, cookie: (set as string).split(";")[0] as string, providerUrl: new URL(response.headers.location as string) };
}
/** What a browser does with a state it was handed: open the launch hop for the state's provider and keep the cookie it sets. */
export async function launchState(app: FastifyInstance, state: string): Promise<LaunchedFlow> {
const { providerUrl: _providerUrl, ...flow } = await followLaunch(app, state);
return flow;
}
/** Drives what a user's browser does after a start: follow authorizationUrl to the launch hop and keep its cookie. */
export function launchFlow(app: FastifyInstance, start: StartBody): Promise<LaunchedFlow> {
return launchState(app, stateOf(start));
}
/** The launch hop's answer in full: the cookie the browser keeps and the provider URL it is redirected to. */
export async function launchWithRedirect(app: FastifyInstance, start: StartBody): Promise<LaunchedFlow & { url: URL }> {
const { providerUrl, ...flow } = await followLaunch(app, stateOf(start));
return { ...flow, url: providerUrl };
}
/** 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<URL> {
return (await followLaunch(app, stateOf(start))).providerUrl;
}

View file

@ -0,0 +1,596 @@
import { generateKeyPairSync, randomUUID } from "node:crypto";
import { afterEach, describe, expect, it, vi } from "vitest";
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
// them (finding state-replay). Soul's attack: a Bifrost state is readable in
// the URL the victim's browser is sent to, so an attacker who sees it opens it
// in their own browser, finishes the provider login as themselves, and hands
// the victim the resulting completion code.
const apps: FastifyInstance[] = [];
afterEach(async () => {
vi.useRealTimers();
while (apps.length) {
await apps.pop()?.close();
}
});
const victimAttempt = "VICTIM-ATTEMPT-NONCE";
const bifrostReturn = `https://bifrost.gamecult.org/auth/heimdall/complete?attempt=${victimAttempt}`;
async function newApp() {
const app = await buildApp({ config: createTestConfig(), oauthRuntimes: { discord: createMockDiscordRuntime() } });
apps.push(app);
return app;
}
async function bifrostStart(app: FastifyInstance, extra: Record<string, unknown> = {}) {
const response = await app.inject({
method: "POST",
url: "/v1/oauth/discord/start",
headers: { "x-heimdall-app-secret": "bifrost-secret" },
payload: { appSlug: "bifrost", mode: "sign_in", returnTo: bifrostReturn, handoff: { kind: "browser_completion" }, ...extra },
});
expect(response.statusCode).toBe(201);
return response.json() as { authorizationUrl: string };
}
function launchUrl(start: { authorizationUrl: string }): string {
const url = new URL(start.authorizationUrl);
return `${url.pathname}${url.search}`;
}
function callback(app: FastifyInstance, state: string, cookie?: string, query = "code=attacker-code") {
return app.inject({
method: "GET",
url: `/v1/oauth/discord/callback?${query}&state=${encodeURIComponent(state)}`,
...(cookie ? { headers: { cookie } } : {}),
});
}
describe("OAuth state binding", () => {
it("Soul's replay fails: one state, at most one completion code, and only for the browser that launched it", async () => {
const app = await newApp();
const start = await bifrostStart(app);
const state = stateOf(start);
const victim = await launchFlow(app, start);
// The attacker holds the same state. A second launch yields no cookie and no redirect.
const attackerLaunch = await app.inject({ method: "GET", url: launchUrl(start) });
expect(attackerLaunch.statusCode).toBe(400);
expect(attackerLaunch.json()).toEqual({ error: "state_already_launched" });
expect(setCookieOf(attackerLaunch)).toEqual([]);
expect(attackerLaunch.headers.location).toBeUndefined();
// Without the cookie the callback refuses and mints nothing.
const attackerCallback = await callback(app, state);
expect(attackerCallback.statusCode).toBe(400);
expect(attackerCallback.json()).toEqual({ error: "state_not_bound" });
expect(attackerCallback.body).not.toContain("completion");
// The victim's callback still completes, once.
const victimCallback = await callback(app, state, victim.cookie, "code=victim-code");
expect(victimCallback.statusCode).toBe(201);
const completionCode = victimCallback.json().completion.code as string;
const redeem = await app.inject({
method: "POST",
url: "/v1/apps/bifrost/auth-completions/redeem",
payload: { completionCode },
});
expect(redeem.statusCode).toBe(201);
expect(redeem.json()).toEqual(expect.objectContaining({ status: "success", appSlug: "bifrost" }));
const second = await callback(app, state, victim.cookie, "code=victim-code");
expect(second.statusCode).toBe(400);
expect(second.json()).toEqual({ error: "state_already_used" });
expect(second.body).not.toContain("completion");
});
it("a stranger's callback needs no launch to be refused: no cookie, no completion code", async () => {
const app = await newApp();
const start = await bifrostStart(app);
const response = await callback(app, stateOf(start));
expect(response.statusCode).toBe(400);
expect(response.json()).toEqual({ error: "state_not_bound" });
expect(response.body).not.toContain("completion");
});
it("a cookie for another flow, another key, another type, or the wrong lifetime does not bind", async () => {
const app = await newApp();
const ctx = getHeimdallRuntimeContext(app);
const own = await bifrostStart(app);
const attackerFlow = await app.inject({
method: "POST",
url: "/v1/oauth/discord/start",
payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" },
});
const attackerStart = attackerFlow.json() as { authorizationUrl: string };
const attackerCookie = (await launchFlow(app, attackerStart)).cookie;
const ownState = stateOf(own);
const ownJti = decodeJwt(ownState).payload.jti as string;
const name = `__Host-heimdall-oauth-${ownJti}`;
const now = Math.floor(Date.now() / 1000);
const binding = (overrides: Record<string, unknown>, keys = ctx.keys) =>
signJwt({ typ: "heimdall_oauth_binding", iss: ctx.config.issuer, jti: ownJti, iat: now, exp: now + 300, ...overrides }, keys);
const foreignKeys = (() => {
const pair = generateKeyPairSync("ed25519");
return { ...ctx.keys, privateKey: pair.privateKey, publicKey: pair.publicKey };
})();
const forged: Record<string, string> = {
"another flow's binding under this flow's cookie name": `${name}=${attackerCookie.split("=")[1]}`,
"a binding signed with a different key": `${name}=${binding({}, foreignKeys)}`,
"a binding for a different jti": `${name}=${binding({ jti: "someone-else" })}`,
"a binding of another type": `${name}=${binding({ typ: "heimdall_oauth_state" })}`,
"a binding from another issuer": `${name}=${binding({ iss: "https://elsewhere.example" })}`,
"an expired binding": `${name}=${binding({ exp: now - 5 })}`,
"the state token used as the cookie": `${name}=${ownState}`,
"a binding whose exp is a string": `${name}=${binding({ exp: String(now + 300) })}`,
"an empty cookie": `${name}=`,
};
for (const [label, cookie] of Object.entries(forged)) {
const response = await callback(app, ownState, cookie);
expect(response.statusCode, label).toBe(400);
expect(response.json(), label).toEqual({ error: "state_not_bound" });
}
// A correctly signed binding for this jti is the one thing that binds.
const good = await callback(app, ownState, `${name}=${binding({})}`);
expect(good.statusCode).toBe(201);
});
it("the cookie is checked before the state is consumed: a stranger cannot burn or deny the victim's flow", async () => {
const app = await newApp();
const ctx = getHeimdallRuntimeContext(app);
const attempt = await ctx.store.createAuthAttempt({
handle: "attempt-1",
appSlug: "repixelizer",
provider: "discord",
mode: "sign_in",
returnTo: "https://repixelizer.gamecult.org/app/",
createdAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + 600_000).toISOString(),
});
const caller = resolveAppCaller(ctx.config, "repixelizer", { "x-heimdall-app-secret": "repixelizer-secret" });
const started = await startOAuthFlow(
ctx,
"discord",
caller,
{ appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/", handoff: { kind: "browser_completion" } },
{ trustedBrowserAttemptId: attempt.handle }
);
expect(started.statusCode).toBe(201);
const start = started.body as unknown as { authorizationUrl: string };
const victim = await launchFlow(app, start);
// A cookieless provider error, which would deny the attempt, and a cookieless code: both refused.
for (const query of ["error=access_denied", "code=attacker-code", ""]) {
const stranger = await callback(app, victim.state, undefined, query);
expect(stranger.statusCode, query).toBe(400);
expect(stranger.json(), query).toEqual({ error: "state_not_bound" });
}
// The state is still unclaimed, so the launcher's cookie still completes it...
const response = await callback(app, victim.state, victim.cookie, "code=victim-code");
expect(response.statusCode).toBe(201);
});
it("a callback with no binding denies the attempt its state names, once, and never a completed one", async () => {
const app = await newApp();
const ctx = getHeimdallRuntimeContext(app);
const make = async (handle: string) => {
await ctx.store.createAuthAttempt({
handle,
appSlug: "repixelizer",
provider: "discord",
mode: "sign_in",
returnTo: "https://repixelizer.gamecult.org/app/",
createdAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + 600_000).toISOString(),
});
const caller = resolveAppCaller(ctx.config, "repixelizer", { "x-heimdall-app-secret": "repixelizer-secret" });
const started = await startOAuthFlow(
ctx,
"discord",
caller,
{ appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/", handoff: { kind: "browser_completion" } },
{ trustedBrowserAttemptId: handle }
);
return started.body as unknown as { authorizationUrl: string };
};
// Lapsed cookie: the launcher launched, then its cookie is gone at the callback.
const lapsed = await make("lapsed");
await launchFlow(app, lapsed);
const refused = await callback(app, stateOf(lapsed), undefined, "code=c");
expect(refused.json()).toEqual({ error: "state_not_bound" });
const denied = await ctx.store.findAuthAttempt("repixelizer", "lapsed");
expect(denied?.status).toBe("denied");
expect(denied?.denialCode).toBe("state_not_bound");
// A completed attempt stays completed under a later cookieless callback.
const done = await make("done");
const launched = await launchFlow(app, done);
expect((await callback(app, launched.state, launched.cookie, "code=c")).statusCode).toBe(201);
await callback(app, launched.state, undefined, "code=c");
expect(["completed", "consumed"]).toContain((await ctx.store.findAuthAttempt("repixelizer", "done"))?.status);
});
it("a state with no jti is refused as invalid and names no attempt to deny", async () => {
const app = await newApp();
const ctx = getHeimdallRuntimeContext(app);
const original = decodeJwt(stateOf(await bifrostStart(app))).payload;
const { jti: _jti, ...rest } = original;
const token = signJwt(rest, ctx.keys);
const response = await callback(app, token, undefined, "code=c");
expect(response.statusCode).toBe(400);
expect(response.json()).toEqual({ error: "invalid_state" });
});
describe("a browser refused for its binding gets a page back to the app, not bare JSON", () => {
const html = { accept: "text/html" };
const get = (app: FastifyInstance, url: string, cookie?: string) =>
app.inject({ method: "GET", url, headers: { ...html, ...(cookie ? { cookie } : {}) } });
it("on a cookieless callback, a lapsed cookie and a reloaded launch", async () => {
const app = await newApp();
const start = await bifrostStart(app);
const state = stateOf(start);
const reloadBeforeLaunch = await get(app, `/v1/oauth/discord/callback?code=c&state=${encodeURIComponent(state)}`);
expect(reloadBeforeLaunch.statusCode).toBe(400);
expect(reloadBeforeLaunch.headers["content-type"]).toContain("text/html");
expect(reloadBeforeLaunch.body).toContain("state_not_bound");
expect(reloadBeforeLaunch.body).toContain("https://bifrost.gamecult.org/auth/heimdall/complete");
const victim = await launchFlow(app, start);
const reloaded = await get(app, launchUrl(start));
expect(reloaded.statusCode).toBe(400);
expect(reloaded.headers["content-type"]).toContain("text/html");
expect(reloaded.body).toContain("state_already_launched");
expect(setCookieOf(reloaded)).toEqual([]);
// Handoff reload: the page after a completed callback, loaded again.
expect((await get(app, `/v1/oauth/discord/callback?code=c&state=${encodeURIComponent(victim.state)}`, victim.cookie)).statusCode).toBeLessThan(300);
const reload = await get(app, `/v1/oauth/discord/callback?code=c&state=${encodeURIComponent(victim.state)}`, victim.cookie);
expect(reload.statusCode).toBe(400);
expect(reload.headers["content-type"]).toContain("text/html");
expect(reload.body).toContain("state_already_used");
});
it("never links to an origin the app does not own, and JSON stays JSON without Accept", async () => {
const app = await newApp();
const ctx = getHeimdallRuntimeContext(app);
const original = decodeJwt(stateOf(await bifrostStart(app))).payload;
const token = signJwt({ ...original, return_to: "https://evil.example/steal" }, ctx.keys);
const evil = await get(app, `/v1/oauth/discord/callback?code=c&state=${encodeURIComponent(token)}`);
expect(evil.statusCode).toBe(400);
expect(evil.json()).toEqual({ error: "state_not_bound" });
expect(evil.body).not.toContain("evil.example");
const plain = await callback(app, stateOf(await bifrostStart(app)));
expect(plain.json()).toEqual({ error: "state_not_bound" });
});
});
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 () => {
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("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" });
});
// 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"],
["not yet valid", { nbf: Math.floor(Date.now() / 1000) + 100 }, "state_expired"],
["another issuer", { iss: "https://elsewhere.example" }, "invalid_state"],
["another provider in aud", { aud: "patreon" }, "state_provider_mismatch"],
["another provider in provider", { provider: "patreon", aud: "patreon" }, "state_provider_mismatch"],
["a wrong type", { typ: "heimdall_refresh" }, "invalid_state"],
])("%s", async (_label, change, error) => {
const app = await newApp();
const ctx = getHeimdallRuntimeContext(app);
const start = await bifrostStart(app);
const original = decodeJwt(stateOf(start)).payload;
const token = signJwt({ ...original, ...change }, ctx.keys);
const launch = await app.inject({ method: "GET", url: `/v1/oauth/discord/launch?state=${encodeURIComponent(token)}` });
expect(launch.statusCode).toBe(400);
expect(launch.json()).toEqual({ error });
expect(setCookieOf(launch)).toEqual([]);
const cookie = `__Host-heimdall-oauth-${original.jti as string}=${signJwt({ typ: "heimdall_oauth_binding", iss: ctx.config.issuer, jti: original.jti, iat: 0, exp: 4_000_000_000 }, ctx.keys)}`;
const response = await callback(app, token, cookie);
expect(response.statusCode).toBe(400);
expect(response.json()).toEqual({ error });
expect(response.body).not.toContain(token.slice(20, 60));
});
it("a state inside the 30 s skew still works, as a refresh token does", async () => {
const app = await newApp();
const ctx = getHeimdallRuntimeContext(app);
const start = await bifrostStart(app);
const original = decodeJwt(stateOf(start)).payload;
const token = signJwt({ ...original, exp: Math.floor(Date.now() / 1000) - 10 }, ctx.keys);
const launch = await app.inject({ method: "GET", url: `/v1/oauth/discord/launch?state=${encodeURIComponent(token)}` });
expect(launch.statusCode).toBe(302);
});
it("a tampered signature, a malformed token and a provider that is not the route's", async () => {
const app = await newApp();
const start = await bifrostStart(app);
const state = stateOf(start);
const tampered = `${state.slice(0, -4)}AAAA`;
for (const token of [tampered, "not-a-jwt", "a.b"]) {
const launch = await app.inject({ method: "GET", url: `/v1/oauth/discord/launch?state=${encodeURIComponent(token)}` });
expect(launch.statusCode).toBe(400);
expect(launch.json()).toEqual({ error: "invalid_state" });
expect(launch.body).not.toContain(token);
}
const wrongRoute = await app.inject({ method: "GET", url: `/v1/oauth/patreon/launch?state=${encodeURIComponent(state)}` });
expect(wrongRoute.statusCode).toBe(400);
expect(wrongRoute.json()).toEqual({ error: "state_provider_mismatch" });
});
});
it("the launch response and the binding cookie carry the protections the binding relies on", async () => {
const app = await newApp();
const start = await bifrostStart(app, { requestedScopes: ["identify", "email"] });
const jti = decodeJwt(stateOf(start)).payload.jti as string;
const launch = await app.inject({ method: "GET", url: launchUrl(start) });
expect(launch.statusCode).toBe(302);
const cookies = setCookieOf(launch);
expect(cookies).toHaveLength(1);
const cookie = cookies[0] as string;
expect(cookie.startsWith(`__Host-heimdall-oauth-${jti}=`)).toBe(true);
const attributes = cookie.split(";").slice(1).map((part) => part.trim());
expect(attributes).toEqual(expect.arrayContaining(["Path=/", "Secure", "HttpOnly", "SameSite=Lax"]));
expect(attributes.some((attribute) => /^domain=/i.test(attribute))).toBe(false);
const maxAge = Number(attributes.find((attribute) => attribute.startsWith("Max-Age="))?.slice("Max-Age=".length));
expect(maxAge).toBeGreaterThan(0);
expect(maxAge).toBeLessThanOrEqual(600);
const location = new URL(launch.headers.location as string);
expect(location.origin + location.pathname).toBe("https://discord.com/oauth2/authorize");
expect(location.searchParams.get("state")).toBe(stateOf(start));
expect(location.searchParams.get("scope")).toBe("identify email");
expect(location.searchParams.get("client_id")).toBe("discord-client");
expect(location.searchParams.get("redirect_uri")).toBe("https://heimdall.gamecult.org/v1/oauth/discord/callback");
expect(launch.headers["cache-control"]).toBe("no-store");
expect(launch.headers["referrer-policy"]).toBe("no-referrer");
const done = await callback(app, stateOf(start), cookie.split(";")[0], "code=c");
expect(done.statusCode).toBe(201);
const cleared = setCookieOf(done).find((value) => value.startsWith(`__Host-heimdall-oauth-${jti}=`));
expect(cleared).toBeDefined();
expect(cleared).toMatch(/Max-Age=0/);
expect(cleared?.startsWith(`__Host-heimdall-oauth-${jti}=;`)).toBe(true);
});
it("a launch for a provider with no client id is 503 and burns nothing", async () => {
const config = { ...createTestConfig(), providers: { ...createTestConfig().providers } };
const app = await buildApp({ config, oauthRuntimes: { discord: createMockDiscordRuntime() } });
apps.push(app);
const start = await bifrostStart(app);
config.providers.discord = { clientId: undefined, clientSecret: undefined } as unknown as typeof config.providers.discord;
const refused = await app.inject({ method: "GET", url: launchUrl(start) });
expect(refused.statusCode).toBe(503);
expect(refused.json().error).toBe("provider_not_configured");
expect(setCookieOf(refused)).toEqual([]);
});
it("every start returns Heimdall's launch URL and no state token", async () => {
const app = await newApp();
for (const [headers, payload] of [
[{}, { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" }],
[
{ "x-heimdall-app-secret": "bifrost-secret" },
{ appSlug: "bifrost", mode: "sign_in", returnTo: bifrostReturn },
],
] as const) {
const response = await app.inject({ method: "POST", url: "/v1/oauth/discord/start", headers, payload });
expect(response.statusCode).toBe(201);
const body = response.json();
expect(body.stateToken).toBeUndefined();
expect(new URL(body.authorizationUrl).origin + new URL(body.authorizationUrl).pathname).toBe(
"https://heimdall.gamecult.org/v1/oauth/discord/launch"
);
expect(body.stateExpiresAt).toEqual(expect.any(String));
}
});
it("claims the launch and the callback of a state under their own phases, until the state's expiry", async () => {
const app = await newApp();
const ctx = getHeimdallRuntimeContext(app);
const spy = vi.spyOn(ctx.store, "claimOAuthStateUse");
const start = await bifrostStart(app);
const { jti, exp } = decodeJwt(stateOf(start)).payload as { jti: string; exp: number };
const victim = await launchFlow(app, start);
expect((await callback(app, victim.state, victim.cookie, "code=victim-code")).statusCode).toBe(201);
const expiresAt = new Date(exp * 1000).toISOString();
expect(spy.mock.calls.map(([claim]) => claim)).toEqual([
{ jti, phase: "launch", appSlug: "bifrost", usedAt: expect.any(String), expiresAt },
{ jti, phase: "callback", appSlug: "bifrost", usedAt: expect.any(String), expiresAt },
]);
});
it("the launch route validates its provider and its state parameter", async () => {
const app = await newApp();
for (const url of ["/v1/oauth/discord/launch", "/v1/oauth/discord/launch?state=", "/v1/oauth/bogus/launch?state=abc"]) {
const response = await app.inject({ method: "GET", url });
expect(response.statusCode, url).toBe(400);
expect(response.json().error, url).toBe("invalid_request");
}
});
it("a state's requested scopes are null, absent, or a list of strings, and nothing else", async () => {
const app = await newApp();
const ctx = getHeimdallRuntimeContext(app);
const start = await bifrostStart(app);
const original = decodeJwt(stateOf(start)).payload;
const launchWith = async (change: Record<string, unknown>) => {
const rest = { ...original };
delete rest.requested_scopes;
const token = signJwt({ ...rest, jti: randomUUID(), ...change }, ctx.keys);
return app.inject({ method: "GET", url: `/v1/oauth/discord/launch?state=${encodeURIComponent(token)}` });
};
for (const [label, change] of [
["absent", {}],
["null", { requested_scopes: null }],
["a list", { requested_scopes: ["identify"] }],
] as const) {
expect((await launchWith(change)).statusCode, label).toBe(302);
}
for (const [label, change] of [
["a string", { requested_scopes: "identify" }],
["a list with a number", { requested_scopes: ["identify", 7] }],
["a list of numbers", { requested_scopes: [1, 2] }],
["an object", { requested_scopes: { 0: "identify" } }],
] as const) {
const response = await launchWith(change);
expect(response.statusCode, label).toBe(400);
expect(response.json(), label).toEqual({ error: "invalid_state" });
}
});
it("the time windows hold to the second: a state from nbf - 30 s to exp + 30 s, a binding until its exp", async () => {
const app = await newApp();
const ctx = getHeimdallRuntimeContext(app);
const start = await bifrostStart(app);
const original = decodeJwt(stateOf(start)).payload;
vi.useFakeTimers({ toFake: ["Date"] });
const now = 1_900_000_000;
vi.setSystemTime(now * 1000);
const stateWith = (change: Record<string, unknown>) =>
signJwt({ ...original, jti: randomUUID(), nbf: now - 1, exp: now + 600, ...change }, ctx.keys);
const launch = (token: string) =>
app.inject({ method: "GET", url: `/v1/oauth/discord/launch?state=${encodeURIComponent(token)}` });
expect((await launch(stateWith({ exp: now - 30 }))).json()).toEqual({ error: "state_expired" });
expect((await launch(stateWith({ exp: now - 29 }))).statusCode).toBe(302);
expect((await launch(stateWith({ nbf: now + 31 }))).json()).toEqual({ error: "state_expired" });
expect((await launch(stateWith({ nbf: now + 30 }))).statusCode).toBe(302);
const token = stateWith({});
const jti = decodeJwt(token).payload.jti as string;
const bindingWith = (exp: number) =>
`__Host-heimdall-oauth-${jti}=${signJwt({ typ: "heimdall_oauth_binding", iss: ctx.config.issuer, jti, iat: now - 5, exp }, ctx.keys)}`;
expect((await callback(app, token, bindingWith(now))).json()).toEqual({ error: "state_not_bound" });
expect((await callback(app, token, bindingWith(now + 1))).statusCode).toBe(201);
});
});

View file

@ -1,18 +1,17 @@
import { mkdtemp, readFile, writeFile } from "node:fs/promises"; import { access, mkdtemp, readFile, writeFile } from "node:fs/promises";
import { openSync, closeSync } from "node:fs"; import { openSync } from "node:fs";
import os from "node:os"; import os from "node:os";
import path from "node:path"; import path from "node:path";
import { encode } from "@msgpack/msgpack"; import { decode, encode } from "@msgpack/msgpack";
import { SingleFileMessagePackBackingStore } from "@gamecult/cultcache-ts";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { import {
openOrEnrollProviderHealthIdentity,
openProviderHealthIdentity, openProviderHealthIdentity,
passedDescriptor, passedDescriptor,
providerHealthPublicIdentity, providerHealthPublicIdentity,
} from "../src/provider-health-identity.js"; } from "../src/provider-health-identity.js";
import { fixtureMachineId, idunnRuntimeFixtures } from "./fixtures/presence-descriptors.js";
const machineIdAvailable = await readFile("/etc/machine-id", "utf8").then( const machineIdAvailable = await readFile("/etc/machine-id", "utf8").then(
() => true, () => true,
@ -23,59 +22,79 @@ const machineIdAvailable = await readFile("/etc/machine-id", "utf8").then(
* The identity is machine-id bound, so enrolment only works where a machine-id * The identity is machine-id bound, so enrolment only works where a machine-id
* exists. These run on Linux and are skipped elsewhere. * exists. These run on Linux and are skipped elsewhere.
*/ */
describe.skipIf(!machineIdAvailable)("presence identity from a passed descriptor", () => { /** Name the presence descriptor so it lands on whatever fd open() returned. */
it("reads an Idunn-written store, not a cultcache-ts one", async () => { function presenceEnv(fd: number): NodeJS.ProcessEnv {
// The lookup maps a name index onto 3 + index, so the name list is padded
// until the presence entry lands on the descriptor open() actually returned.
// Assuming it is 3 is how this passes on one machine and reads the wrong
// descriptor on another.
const names = [
...Array.from({ length: fd - 3 }, (_, i) => `pad-${i}`),
"gamecult-runtime-presence-identity",
].join(":");
return { LISTEN_FDNAMES: names, LISTEN_PID: String(process.pid) };
}
describe("presence identity from a passed descriptor", () => {
it("decodes the Rust owner's record, whose key fields are integer arrays", async () => {
const dir = await mkdtemp(path.join(os.tmpdir(), "heimdall-presence-")); const dir = await mkdtemp(path.join(os.tmpdir(), "heimdall-presence-"));
const fd = openSync(path.join(idunnRuntimeFixtures, "provider-identity.credential"), "r");
// Enrol with the TypeScript client to get a genuine machine-bound payload, const opened = await openProviderHealthIdentity(
// then re-wrap that payload the way cultcache-rs writes a store: a bare path.join(dir, "would-be-self-enrolled.cc"),
// array of positional [key, type, payload, stored_at, schema_id] envelopes. presenceEnv(fd),
// Idunn writes with the Rust client, and cultcache-ts cannot read that fixtureMachineId
// layout, so wrapping it here is what makes this test resemble reality.
const tsStore = path.join(dir, "ts-enrolled.cc");
const enrolled = await openOrEnrollProviderHealthIdentity(tsStore);
const records = await new SingleFileMessagePackBackingStore(tsStore).pullAll();
expect(records).toHaveLength(1);
const idunnStore = path.join(dir, "runtime-presence-identity.cc");
await writeFile(
idunnStore,
encode([
[
"gamecult-provider-health-identity",
"gamecult.provider_health_identity.private.v1",
records[0]!.payload,
"2026-09-06T00:00:00.000Z",
"gamecult.provider_health_identity.private.v1",
],
])
); );
const fd = openSync(idunnStore, "r"); // The fixture's own public key means it came from the descriptor. A fresh
try { // self-enrolment would produce a different key, which is exactly the failure
// The lookup maps a name index onto 3 + index, so the name list is padded // that makes Idunn refuse this daemon's health and stall promotion.
// until the presence entry lands on whatever descriptor open() actually const store = decode(await readFile(path.join(idunnRuntimeFixtures, "provider-identity.credential"))) as unknown[][];
// returned. Assuming it is 3 is how this passes on one machine and reads const record = decode(store[0]![2] as Uint8Array) as unknown[];
// the wrong descriptor on another. expect(providerHealthPublicIdentity(opened).publicKeyHex).toBe(
const names = [ Buffer.from(record[2] as number[]).toString("hex")
...Array.from({ length: fd - 3 }, (_, i) => `pad-${i}`), );
"gamecult-runtime-presence-identity", await expect(access(path.join(dir, "would-be-self-enrolled.cc"))).rejects.toMatchObject({ code: "ENOENT" });
].join(":"); });
const opened = await openProviderHealthIdentity( it("refuses a bin-shaped record on the descriptor path, naming the key-shape check and no value", async () => {
path.join(dir, "would-be-self-enrolled.cc"), const dir = await mkdtemp(path.join(os.tmpdir(), "heimdall-presence-bin-"));
{ LISTEN_FDNAMES: names, LISTEN_PID: String(process.pid) } const store = decode(await readFile(path.join(idunnRuntimeFixtures, "provider-identity.credential"))) as unknown[][];
); const record = decode(store[0]![2] as Uint8Array) as unknown[];
// What this process's own enroller writes: the same record with bin key fields.
const binRecord = record.map((field, index) =>
index === 2 || index === 3 ? Uint8Array.from(field as number[]) : field
);
const binStore = path.join(dir, "bin-shaped.cc");
await writeFile(binStore, encode([[store[0]![0], store[0]![1], encode(binRecord), store[0]![3], store[0]![4]]]));
const fd = openSync(binStore, "r");
// Same key means it came from the descriptor. A fresh self-enrolment const failure = await openProviderHealthIdentity(path.join(dir, "x.cc"), presenceEnv(fd), fixtureMachineId).then(
// would produce a different key -- which is exactly the failure that () => undefined,
// makes Idunn refuse this daemon's health and stall promotion. (error: Error) => error
expect(providerHealthPublicIdentity(opened).publicKeyHex).toBe( );
providerHealthPublicIdentity(enrolled).publicKeyHex
); expect(failure?.message).toContain("key shape check");
} finally { expect(failure?.message).not.toContain((record[1] as string).slice(0, 16));
closeSync(fd); });
}
it.each([
["schema", 0, "bogus", "schema check"],
["protector", 4, "bogus", "protector check"],
["binding", 5, "bogus", "binding check"],
["version", 6, "v9", "version check"],
])("a record failing only the %s check is refused by that check", async (_name, index, replacement, check) => {
const dir = await mkdtemp(path.join(os.tmpdir(), "heimdall-presence-check-"));
const store = decode(await readFile(path.join(idunnRuntimeFixtures, "provider-identity.credential"))) as unknown[][];
const record = decode(store[0]![2] as Uint8Array) as unknown[];
record[index] = replacement;
const damaged = path.join(dir, "damaged.cc");
await writeFile(damaged, encode([[store[0]![0], store[0]![1], encode(record), store[0]![3], store[0]![4]]]));
const fd = openSync(damaged, "r");
await expect(
openProviderHealthIdentity(path.join(dir, "x.cc"), presenceEnv(fd), fixtureMachineId)
).rejects.toThrow(check);
}); });
}); });
@ -112,3 +131,29 @@ describe("presence identity descriptor selection", () => {
}); });
}); });
}); });
describe("an Idunn generation without the presence identity descriptor", () => {
it("refuses, naming the descriptor, and enrolls nothing", async () => {
const dir = await mkdtemp(path.join(os.tmpdir(), "heimdall-nodescriptor-"));
const identityPath = path.join(dir, "provider-health-identity.cc");
await expect(
openProviderHealthIdentity(identityPath, {
GAMECULT_IDUNN_RUNTIME_BUNDLE: "/run/idunn/bundle",
LISTEN_FDNAMES: "some-other-descriptor",
})
).rejects.toThrow("gamecult-runtime-presence-identity");
await expect(access(identityPath)).rejects.toMatchObject({ code: "ENOENT" });
});
it("still self-enrolls outside Idunn", async () => {
if (!machineIdAvailable) return;
const dir = await mkdtemp(path.join(os.tmpdir(), "heimdall-outside-idunn-"));
const identityPath = path.join(dir, "provider-health-identity.cc");
await openProviderHealthIdentity(identityPath, {});
await expect(access(identityPath)).resolves.toBeUndefined();
});
});

View file

@ -0,0 +1,153 @@
// A private command's reply travels partly outside its sealed envelope: the
// status, the failure payload and the diagnostics are plaintext, and the
// calling app logs the diagnostics. Soul pass 4 found a provider's refresh
// token there: a 2xx refresh answer that is not JSON made JSON.parse quote the
// text around the fault, and the plane returned that message as a diagnostic.
// These tests drive the real Discord runtime with only fetch stubbed.
import { decode, encode } from "@msgpack/msgpack";
import { invokeCultNetOperation } from "cultnet-ts";
import { afterEach, expect, it, vi } from "vitest";
import { buildApp } from "../src/app.js";
import { type HeimdallConfig } from "../src/config.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 { launchState } from "./oauth-flow.js";
const secret = "ghostlight-private-command-secret";
const resources: Array<{ close(): Promise<unknown> }> = [];
afterEach(async () => {
vi.unstubAllGlobals();
await Promise.all(resources.splice(0).reverse().map((r) => r.close()));
});
function config(): HeimdallConfig {
return {
serviceName: "heimdall", host: "127.0.0.1", port: 4100, privateCommandHost: "127.0.0.1", privateCommandPort: 0,
workspaceRoot: "/tmp", dataRoot: "/tmp/.hd", cultCachePath: "/tmp/.hd/t.cc",
publicBaseUrl: "https://heimdall.gamecult.org", issuer: "https://heimdall.gamecult.org", daemonId: "yggdrasil-heimdall",
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: {},
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<string, unknown>) {
const envelope = sealPrivateEnvelope({ appSlug: "ghostlight", 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" });
}
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`. */
async function refreshAgainst(refreshAnswer: () => Response) {
let refreshing = false;
vi.stubGlobal("fetch", async (url: string | URL, init?: RequestInit) => {
const u = String(url);
if (u.endsWith("/oauth2/token")) {
if (new URLSearchParams(String(init?.body)).get("grant_type") === "refresh_token") {
refreshing = true;
return refreshAnswer();
}
return new Response(
JSON.stringify({ access_token: "first-access", refresh_token: "first-refresh", token_type: "Bearer", expires_in: 60, scope: "identify" }),
{ status: 200 }
);
}
if (u.endsWith("/users/@me")) return new Response(JSON.stringify({ id: "u1", username: "u1" }), { status: 200 });
if (u.includes("/member")) return new Response(JSON.stringify({ roles: ["r"] }), { status: 200 });
return new Response("{}", { status: 404 });
});
const cfg = config();
const app = await buildApp({ config: cfg, store: new InMemoryStore() });
resources.push(app);
const plane = await startHeimdallPrivateCommandPlane(app, cfg);
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 }));
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({
method: "GET",
url: `/v1/oauth/discord/callback?code=c1&state=${encodeURIComponent(state)}`,
headers: { accept: "application/json", cookie },
});
expect(callback.statusCode, callback.body).toBe(201);
const done = open(await command(plane.endpoint, "heimdall.auth.complete", "heimdall.auth_complete_command.v1", "k2", { handle: begin.handle }));
expect(done.status).toBe("authenticated");
const reply = await command(plane.endpoint, "heimdall.auth.refresh", "heimdall.auth_refresh_command.v1", "k3",
{ refreshToken: done.refreshToken, entitlementPolicy: policy });
expect(refreshing).toBe(true);
return reply;
}
/** Every plaintext byte of a reply: the message itself and its decoded failure payload. */
function plaintext(reply: { payload: string }): string {
return JSON.stringify(reply) + JSON.stringify(decode(Buffer.from(reply.payload, "base64")));
}
it("keeps a provider's malformed 2xx refresh body out of every plaintext part of the reply", async () => {
const reply = await refreshAgainst(
() => new Response('{"access_token":"CANARYaccess0123456789","refresh_token":CANARYrefresh0123456789,"token_type":"Bearer"}', { status: 200 })
);
expect(reply.status).toBe("denied");
expect(reply.diagnostics).toEqual(["Heimdall denied the private command (ManagedCredentialRefreshFailed, managed_credential_refresh_failed)."]);
expect(plaintext(reply)).not.toContain("CANARY");
});
it("keeps a provider's refusal body out of every plaintext part of the reply", async () => {
const reply = await refreshAgainst(() => new Response('CANARYrefused {"error":"invalid_grant"}', { status: 400 }));
expect(reply.status).toBe("denied");
expect(reply.diagnostics).toEqual(["Heimdall denied the private command (ManagedCredentialRefreshFailed, managed_credential_refresh_failed)."]);
expect(plaintext(reply)).not.toContain("CANARY");
});
it("keeps the completion code out of the audit trail when the plane redeems by attempt", async () => {
vi.stubGlobal("fetch", async (url: string | URL) => {
const u = String(url);
if (u.endsWith("/oauth2/token")) {
return new Response(
JSON.stringify({ access_token: "a", refresh_token: "r", token_type: "Bearer", expires_in: 60, scope: "identify" }),
{ status: 200 }
);
}
if (u.endsWith("/users/@me")) return new Response(JSON.stringify({ id: "u1", username: "u1" }), { status: 200 });
if (u.includes("/member")) return new Response(JSON.stringify({ roles: ["r"] }), { status: 200 });
return new Response("{}", { status: 404 });
});
const cfg = config();
const store = new InMemoryStore();
const app = await buildApp({ config: cfg, store });
resources.push(app);
const plane = await startHeimdallPrivateCommandPlane(app, cfg);
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 }));
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({
method: "GET",
url: `/v1/oauth/discord/callback?code=c1&state=${encodeURIComponent(state)}`,
headers: { accept: "application/json", cookie },
});
const code = (callback.json().completion as { code: string }).code;
const done = open(await command(plane.endpoint, "heimdall.auth.complete", "heimdall.auth_complete_command.v1", "k2", { handle: begin.handle }));
expect(done.status).toBe("authenticated");
const events = [...(store as unknown as { auditEvents: Map<string, { eventType: string; eventPayloadJson: unknown }> }).auditEvents.values()];
expect(events.filter((event) => event.eventType === "auth_completion_redeemed").map((event) => event.eventPayloadJson)).toEqual([
{ provider: "discord", mode: "sign_in" },
]);
expect(JSON.stringify(events)).not.toContain(code);
});

View file

@ -0,0 +1,307 @@
import { inspect } from "node:util";
import { afterEach, describe, expect, it } from "vitest";
import { type HeimdallConfig } from "../src/config.js";
import { providers, type Provider } from "../src/contracts.js";
import { createOAuthRuntimeRegistry, requestProviderTokens } from "../src/oauth.js";
import { providerCatalog } from "../src/providers.js";
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
function configFor(): HeimdallConfig {
return {
providers: Object.fromEntries(providers.map((p) => [p, { clientId: `${p}-client`, clientSecret: `${p}-secret` }])),
} as unknown as HeimdallConfig;
}
interface Captured {
url: string;
method: string | undefined;
headers: Record<string, string>;
body: URLSearchParams;
}
function capture(answer: () => Response): { calls: Captured[] } {
const calls: Captured[] = [];
globalThis.fetch = (async (input: string | URL, init?: RequestInit) => {
calls.push({
url: String(input),
method: init?.method,
headers: init?.headers as Record<string, string>,
body: init?.body as URLSearchParams,
});
return answer();
}) as typeof fetch;
return { calls };
}
const ok = () =>
new Response(JSON.stringify({ access_token: "a", refresh_token: "r", token_type: "Bearer", expires_in: 3600, scope: "x y" }), {
status: 200,
});
const requestable: Provider[] = [...providers];
describe("requestProviderTokens follows the provider descriptor", () => {
it.each(requestable.flatMap((p) => [[p, "authorization_code"] as const, [p, "refresh_token"] as const]))(
"%s %s hits its token endpoint with its client-auth method only",
async (provider, grantType) => {
const { calls } = capture(ok);
const descriptor = providerCatalog[provider];
const grant =
grantType === "authorization_code"
? ({ grant_type: "authorization_code", code: "the-code", redirect_uri: "https://h/cb" } as const)
: ({ grant_type: "refresh_token", refresh_token: "the-refresh" } as const);
const tokens = await requestProviderTokens(provider, configFor(), grant);
expect(calls).toHaveLength(1);
const call = calls[0]!;
expect(call.url).toBe(descriptor.tokenEndpoint);
expect(call.method).toBe("POST");
expect(call.headers["Content-Type"]).toBe("application/x-www-form-urlencoded");
expect(call.headers.Accept).toBe("application/json");
expect(call.body.get("grant_type")).toBe(grantType);
if (descriptor.tokenEndpointAuthMethod === "client_secret_basic") {
expect(call.headers.Authorization).toBe(`Basic ${Buffer.from(`${provider}-client:${provider}-secret`).toString("base64")}`);
expect(call.body.has("client_id")).toBe(false);
expect(call.body.has("client_secret")).toBe(false);
} else {
expect(call.headers.Authorization).toBeUndefined();
expect(call.body.get("client_id")).toBe(`${provider}-client`);
expect(call.body.get("client_secret")).toBe(`${provider}-secret`);
}
expect(tokens.accessToken).toBe("a");
expect(tokens.refreshToken).toBe("r");
expect(tokens.scope).toEqual(["x", "y"]);
expect(Date.parse(tokens.expiresAt ?? "")).toBeGreaterThan(Date.now());
}
);
it("sends the code and redirect uri on exchange and the refresh token on refresh", async () => {
const { calls } = capture(ok);
await requestProviderTokens("spotify", configFor(), { grant_type: "authorization_code", code: "C", redirect_uri: "https://h/cb" });
await requestProviderTokens("spotify", configFor(), { grant_type: "refresh_token", refresh_token: "R" });
expect(calls[0]!.body.get("code")).toBe("C");
expect(calls[0]!.body.get("redirect_uri")).toBe("https://h/cb");
expect(calls[1]!.body.get("refresh_token")).toBe("R");
expect(calls[1]!.body.has("code")).toBe(false);
});
const everyProvider = Object.keys(providerCatalog) as Provider[];
it("gives every provider a default access-token lifetime of 3600 seconds", () => {
for (const provider of everyProvider) {
expect(providerCatalog[provider].defaultAccessTokenLifetimeSeconds).toBe(3600);
}
});
// expires_in is RECOMMENDED (RFC 6749 5.1): unusable means the default, never an unknown expiry.
it.each([
["no expires_in", undefined, 3600],
["a zero expires_in", 0, 3600],
["a negative expires_in", -5, 3600],
["a null expires_in", null, 3600],
["an object expires_in", {}, 3600],
["a non-numeric string", "abc", 3600],
["an empty string", "", 3600],
["a negative string", "-1", 3600],
["a zero string", "0", 3600],
["a fractional string", "12.5", 3600],
["an exponent string", "1e3", 3600],
["a numeric string", "7200", 7200],
["a padded numeric string", " 7200 ", 7200],
["a number", 7200, 7200],
])("stores now plus the right lifetime for %s, on every provider and grant", async (_n, expiresIn, seconds) => {
for (const provider of everyProvider) {
for (const grant of [
{ grant_type: "authorization_code", code: "c", redirect_uri: "u" } as const,
{ grant_type: "refresh_token", refresh_token: "R" } as const,
]) {
capture(() => new Response(JSON.stringify({ access_token: "a", ...(expiresIn === undefined ? {} : { expires_in: expiresIn }) }), { status: 200 }));
const before = Date.now();
const tokens = await requestProviderTokens(provider, configFor(), grant);
const stored = Date.parse(tokens.expiresAt ?? "");
expect(stored - before).toBeGreaterThanOrEqual(seconds * 1000);
expect(stored - before).toBeLessThan(seconds * 1000 + 5_000);
expect(tokens.refreshToken).toBeUndefined();
}
}
});
it("takes the default lifetime for an expires_in too large to be a date", async () => {
capture(() => new Response('{"access_token":"a","expires_in":1e999}', { status: 200 }));
const before = Date.now();
const tokens = await requestProviderTokens("twitch", configFor(), { grant_type: "refresh_token", refresh_token: "R" });
expect(Date.parse(tokens.expiresAt ?? "") - before).toBeLessThan(3600 * 1000 + 5_000);
});
it.each([
["exactly a year", 31_536_000, 31_536_000],
["a second over a year", 31_536_001, 3600],
["3e11", 3e11, 3600],
["3e11 as a string", "300000000000", 3600],
])("takes an expires_in of %s as %i seconds' worth of lifetime", async (_n, expiresIn, seconds) => {
capture(() => new Response(JSON.stringify({ access_token: "a", expires_in: expiresIn }), { status: 200 }));
const before = Date.now();
const tokens = await requestProviderTokens("twitch", configFor(), { grant_type: "refresh_token", refresh_token: "R" });
expect(Date.parse(tokens.expiresAt ?? "") - before).toBeGreaterThanOrEqual(seconds * 1000 - 1000);
expect(Date.parse(tokens.expiresAt ?? "") - before).toBeLessThan(seconds * 1000 + 5_000);
});
it.each([
["no refresh_token", {}],
["an empty refresh_token", { refresh_token: "" }],
])("a rotating provider's code exchange with %s is a typed malformed token set; a non-rotating one is not", async (_n, extra) => {
capture(() => new Response(JSON.stringify({ access_token: "a", expires_in: 3600, ...extra }), { status: 200 }));
const runtimes = createOAuthRuntimeRegistry();
const exchange = { config: configFor(), code: "c", redirectUri: "https://h/cb" };
await expect(runtimes.joystick.exchangeAuthorizationCode(exchange)).rejects.toMatchObject({
name: "ProviderResponseError",
code: "provider_body_not_token_set",
});
expect((await runtimes.twitch.exchangeAuthorizationCode(exchange)).refreshToken).toBeUndefined();
});
it.each([
["a number", 42],
["an object", { a: 1 }],
["an array", ["r"]],
["true", true],
["null", null],
])("refuses a 2xx whose refresh_token is %s as a malformed token set", async (_n, refreshToken) => {
capture(() => new Response(JSON.stringify({ access_token: "a", refresh_token: refreshToken, expires_in: 3600 }), { status: 200 }));
await expect(
requestProviderTokens("twitch", configFor(), { grant_type: "refresh_token", refresh_token: "R" })
).rejects.toMatchObject({ code: "provider_body_not_token_set" });
});
it("reads an empty-string refresh_token as no refresh token", async () => {
capture(() => new Response(JSON.stringify({ access_token: "a", refresh_token: "", expires_in: 3600 }), { status: 200 }));
const tokens = await requestProviderTokens("twitch", configFor(), { grant_type: "refresh_token", refresh_token: "R" });
expect(tokens.refreshToken).toBeUndefined();
});
it.each([
["authorization_code", { grant_type: "authorization_code", code: "c", redirect_uri: "u" } as const, "exchange"],
["refresh_token", { grant_type: "refresh_token", refresh_token: "r" } as const, "refresh"],
])("keeps the failure label for %s", async (_g, grant, word) => {
capture(() => new Response("nope", { status: 500 }));
await expect(requestProviderTokens("youtube", configFor(), grant)).rejects.toThrow(
`YouTube token ${word} failed (status 500, provider_status).`
);
});
it("passes the abort signal to the provider call", async () => {
let seen: AbortSignal | null | undefined;
globalThis.fetch = (async (_input: string | URL, init?: RequestInit) => {
seen = init?.signal;
return ok();
}) as typeof fetch;
const controller = new AbortController();
await requestProviderTokens("twitch", configFor(), { grant_type: "refresh_token", refresh_token: "r" }, controller.signal);
expect(seen).toBe(controller.signal);
});
it("keeps the provider's token type and defaults a missing one to Bearer", async () => {
capture(() => new Response(JSON.stringify({ access_token: "a", token_type: "bearer" }), { status: 200 }));
expect((await requestProviderTokens("twitch", configFor(), { grant_type: "refresh_token", refresh_token: "r" })).tokenType).toBe("bearer");
capture(() => new Response(JSON.stringify({ access_token: "a" }), { status: 200 }));
expect((await requestProviderTokens("twitch", configFor(), { grant_type: "refresh_token", refresh_token: "r" })).tokenType).toBe("Bearer");
});
it("trims scope entries and drops empty ones", async () => {
capture(() => new Response(JSON.stringify({ access_token: "a", scope: [" a ", "", "b"] }), { status: 200 }));
expect((await requestProviderTokens("twitch", configFor(), { grant_type: "refresh_token", refresh_token: "r" })).scope).toEqual(["a", "b"]);
});
it.each([
["an empty body", ""],
["an empty object", "{}"],
["JSON null", "null"],
["a JSON array", "[]"],
["an error beside an access token", JSON.stringify({ access_token: "a", error: "invalid_grant" })],
["an empty access token", JSON.stringify({ access_token: "" })],
["a numeric access token", JSON.stringify({ access_token: 5 })],
])("refuses a 2xx with %s as not a token set, carrying nothing of the body", async (_name, body) => {
capture(() => new Response(body, { status: 200 }));
const error = await requestProviderTokens("twitch", configFor(), { grant_type: "refresh_token", refresh_token: "r" }).then(
() => {
throw new Error("expected a refusal");
},
(e: unknown) => e as Error & { code?: string; status?: number; oauthError?: unknown }
);
expect(error.name).toBe("ProviderResponseError");
expect(error.code).toBe("provider_body_not_token_set");
expect(error.status).toBe(200);
expect(error.oauthError).toBeUndefined();
});
it("sets no refreshToken key when the provider sent none", async () => {
capture(() => new Response(JSON.stringify({ access_token: "a" }), { status: 200 }));
const tokens = await requestProviderTokens("twitch", configFor(), { grant_type: "refresh_token", refresh_token: "r" });
expect("refreshToken" in tokens).toBe(false);
});
it.each([
["only the secret missing", { clientId: "id" }],
["only the id missing", { clientSecret: "secret" }],
])("refuses a provider with %s", async (_n, partial) => {
const config = { providers: { twitch: partial } } as unknown as HeimdallConfig;
await expect(requestProviderTokens("twitch", config, { grant_type: "refresh_token", refresh_token: "r" })).rejects.toThrow(
"Twitch OAuth is not fully configured."
);
});
it("refuses an unconfigured provider by display name", async () => {
const config = { providers: { patreon: {} } } as unknown as HeimdallConfig;
await expect(
requestProviderTokens("patreon", config, { grant_type: "refresh_token", refresh_token: "r" })
).rejects.toThrow("Patreon OAuth is not fully configured.");
});
});
describe("oauthError is a closed set", () => {
const refresh = { grant_type: "refresh_token", refresh_token: "r" } as const;
async function failure(body: string, status = 400) {
capture(() => new Response(body, { status }));
return requestProviderTokens("twitch", configFor(), refresh).then(
() => {
throw new Error("expected a refusal");
},
(error: unknown) => error as Error & { oauthError?: string }
);
}
it("takes invalid_grant from the body and carries nothing else of it", async () => {
const error = await failure(JSON.stringify({ error: "invalid_grant", error_description: "CANARY" }));
expect(error.oauthError).toBe("invalid_grant");
expect(`${error.message} ${error.stack} ${inspect(error, { depth: 5, showHidden: true })} ${JSON.stringify(error)}`).not.toContain("CANARY");
});
it.each([401, 403, 429, 500, 502, 503])("takes no oauthError from a %i, whatever its body says", async (status) => {
const error = await failure(JSON.stringify({ error: "invalid_grant" }), status);
expect(error.oauthError).toBeUndefined();
});
it.each(["invalid_grant_extra", "not_invalid_grant", "INVALID_GRANT", " invalid_grant", "invalid_grant "])(
"takes the code by exact match only: %j is no code",
async (code) => {
const error = await failure(JSON.stringify({ error: code }));
expect(error.oauthError).toBeUndefined();
}
);
it.each([
["an error outside the RFC set", JSON.stringify({ error: "CANARY_unknown" })],
["a non-string error", JSON.stringify({ error: { code: "invalid_grant" } })],
["a body that is not JSON", "CANARY <html>"],
["JSON null", "null"],
])("leaves oauthError undefined for %s", async (_name, body) => {
const error = await failure(body);
expect(error.oauthError).toBeUndefined();
expect(`${error.message} ${inspect(error, { depth: 5, showHidden: true })}`).not.toContain("CANARY");
});
});

View file

@ -0,0 +1,83 @@
import { mkdtemp, readdir, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { loadConfig } from "../src/config.js";
import { PublisherSequence, openPresenceAuthority } from "../src/runtime-presence.js";
import { fixtureMachineId, openPresenceDescriptors, writePresenceFixtures } from "./fixtures/presence-descriptors.js";
describe("PublisherSequence", () => {
it("starts at the observed millis", () => {
expect(new PublisherSequence().next(1_700_000_000_000)).toBe(1_700_000_000_000);
});
it("strictly increases for equal, earlier and later observations", () => {
const sequence = new PublisherSequence();
const first = sequence.next(1_700_000_000_000);
const equal = sequence.next(1_700_000_000_000);
const earlier = sequence.next(1_699_999_990_000);
const later = sequence.next(1_700_000_050_000);
expect([first, equal, earlier, later]).toEqual([
1_700_000_000_000,
1_700_000_000_001,
1_700_000_000_002,
1_700_000_050_000,
]);
});
it("never falls below the observed millis once the clock moves ahead", () => {
const sequence = new PublisherSequence();
sequence.next(1_700_000_000_000);
sequence.next(1_700_000_000_000);
sequence.next(1_700_000_000_000);
expect(sequence.next(1_700_000_000_002)).toBe(1_700_000_000_003);
expect(sequence.next(1_700_000_000_010)).toBe(1_700_000_000_010);
});
it("refuses a value that is not a safe integer and keeps its place", () => {
const sequence = new PublisherSequence();
expect(sequence.next(10)).toBe(10);
for (const bad of [Number.NaN, Number.POSITIVE_INFINITY, 1.5, 2 ** 60]) {
expect(() => sequence.next(bad)).toThrow("observedAtUnixMillis");
}
expect(sequence.next(5)).toBe(11);
});
});
describe("the presence authority", () => {
it("opens once, touches no path under dataRoot, and signs every pulse after its descriptors are gone", async () => {
const dir = await mkdtemp(path.join(os.tmpdir(), "heimdall-nodataroot-"));
const fixtures = path.join(dir, "fixtures");
await writePresenceFixtures(fixtures);
// A regular file as dataRoot: opening anything beneath it fails with
// ENOTDIR for every uid, root included.
const dataRoot = path.join(dir, "not-a-directory");
await writeFile(dataRoot, "");
const config = loadConfig({
GC_ACCESS_BASE_URL: "https://heimdall.example.test",
GC_ACCESS_DATA_ROOT: dataRoot,
});
const descriptors = openPresenceDescriptors(fixtures);
try {
const authority = await openPresenceAuthority(
{ ...config, idunnRuntimeBundlePath: fixtures },
descriptors.env,
fixtureMachineId,
);
// The descriptors were read whole and closed: a second read would find
// nothing, so signing again proves the authority holds what it decoded.
const observedAtUnixMillis = Date.parse("2026-10-23T12:00:00.000Z");
const first = authority.sign("warming", "probe", observedAtUnixMillis);
const second = authority.sign("warming", "probe", observedAtUnixMillis);
expect(first.target).toBe("streampixels-web");
expect(second.target).toBe("streampixels-web");
expect(Buffer.from(second.payload).equals(Buffer.from(first.payload))).toBe(false);
} finally {
descriptors.close();
}
expect((await readdir(dir)).sort()).toEqual(["fixtures", "not-a-directory"]);
});
});

View file

@ -0,0 +1,251 @@
import { readFileSync } from "node:fs";
import { describe, expect, it, vi } from "vitest";
import { appProfiles } from "../src/app-profiles.js";
import { appSlugs, 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");
/** 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 = [
...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]!)
);
// 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<string, string>, names: new Set<string>(), 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<T>(run: () => T | Promise<T>): Promise<T> {
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<Record<string, string>>,
argv: readonly string[] = []
): Promise<{ names: Set<string>; 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<string>; enumerated: boolean }> {
const names = new Set<string>();
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<string, string[]>();
const keep = (run: { names: Set<string> }) => 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");
});
it("declares no secret-shaped name except as a _FILE credential path", () => {
const plaintext = everyDeclaredName.filter(
(name) => secretShaped.test(name) && !name.endsWith("_FILE") && !notSecrets.has(name)
);
expect(plaintext).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([]);
});
});

View file

@ -38,6 +38,8 @@ function createTestConfig(overrides: Partial<HeimdallConfig> = {}): HeimdallConf
twitch: {}, twitch: {},
youtube: {}, youtube: {},
spotify: {}, spotify: {},
joystick: {},
google: {},
}, },
...overrides, ...overrides,
}; };
@ -64,6 +66,22 @@ describe("Heimdall security helpers", () => {
expect(custody.decrypt(encrypted)).toBe("discord-access-token"); expect(custody.decrypt(encrypted)).toBe("discord-access-token");
}); });
it("refuses a token key that does not decode to 32 bytes, without echoing it", () => {
for (const length of [16, 31, 33]) {
const key = Buffer.alloc(length, 7).toString("base64");
const message = (() => {
try {
createTokenCustody({ ...createTestConfig(), tokenEncryptionKeyBase64: key });
} catch (error) {
return (error as Error).message;
}
throw new Error(`a ${length}-byte key was accepted`);
})();
expect(message).toMatch(/GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE must decode to exactly 32 bytes/);
expect(message).not.toContain(key);
}
});
it("refuses persistent provider-token storage without a stable encryption key", () => { it("refuses persistent provider-token storage without a stable encryption key", () => {
expect(() => expect(() =>
createTokenCustody( createTokenCustody(

View file

@ -0,0 +1,98 @@
import { execFile } from "node:child_process";
import { chmod, chown, mkdir, mkdtemp, readdir, stat } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { build } from "esbuild";
import { describe, expect, it } from "vitest";
import { writePresenceFixtures } from "./fixtures/presence-descriptors.js";
const run = promisify(execFile);
const STATE_GID = 4242;
const GENERATION_N = 61184;
const GENERATION_N_PLUS_1 = 61185;
// Creating uids and groups needs root; the stopgap's node container runs as root.
const isRoot = process.getuid?.() === 0;
async function walk(dir: string): Promise<string[]> {
const found: string[] = [];
for (const entry of await readdir(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
found.push(full);
if (entry.isDirectory()) found.push(...(await walk(full)));
}
return found;
}
/**
* Idunn gives every generation a fresh DynamicUser uid and one shared group,
* UMask=0007, and a 2770 setgid state root. Generation N+1 runs beside or after
* N and must be able to read and replace everything N left there.
*/
describe.skipIf(!isRoot)("Idunn state root across generations", () => {
it("generation N+1, a different uid in the same group, reads and replaces generation N's state", async () => {
const base = await mkdtemp(path.join(os.tmpdir(), "heimdall-generations-"));
await chmod(base, 0o755);
// The fixtures stand in for what Idunn passes as descriptors.
const fixtures = path.join(base, "fixtures");
await writePresenceFixtures(fixtures);
const stateRoot = path.join(base, "state");
await mkdir(stateRoot);
await chown(stateRoot, 0, STATE_GID);
await chmod(stateRoot, 0o2770);
// The generations run as uids that cannot read the checkout, so each runs
// one self-contained bundle built into the world-readable scratch root.
const child = path.join(base, "generation.mjs");
await build({
entryPoints: [path.join(import.meta.dirname, "fixtures", "state-root-generation-child.ts")],
bundle: true,
platform: "node",
format: "esm",
target: "node24",
outfile: child,
external: ["pg-native"],
banner: {
js: "import{createRequire}from'node:module';const require=createRequire(import.meta.url);",
},
logLevel: "silent",
});
await chmod(child, 0o644);
const generation = (role: "first" | "next", uid: number) =>
run(process.execPath, [child, role, stateRoot, fixtures], {
uid,
gid: STATE_GID,
cwd: base,
env: { PATH: process.env.PATH ?? "", HOME: fixtures },
});
await generation("first", GENERATION_N);
const left = await walk(stateRoot);
expect(left.map((entry) => path.relative(stateRoot, entry)).sort()).toEqual([
"cultcache",
path.join("cultcache", "heimdall.service.cc"),
"runtime-presence-sequence",
]);
await generation("next", GENERATION_N_PLUS_1);
// Generation N+1 replaced the snapshot, and no owner-only file is left
// behind for generation N+2: everything but the stale 0600 fixture is
// readable and writable by the state group.
const snapshot = await stat(path.join(stateRoot, "cultcache", "heimdall.service.cc"));
expect(snapshot.uid).toBe(GENERATION_N_PLUS_1);
expect(snapshot.gid).toBe(STATE_GID);
for (const entry of await walk(stateRoot)) {
if (path.basename(entry) === "runtime-presence-sequence") continue;
expect((await stat(entry)).mode & 0o060, path.relative(stateRoot, entry)).toBe(0o060);
}
expect((await readdir(stateRoot)).sort()).toEqual(["cultcache", "runtime-presence-sequence"]);
}, 60_000);
});

View file

@ -0,0 +1,435 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
import { buildApp, STEP_UP_ASSERT_LIMITS } from "../src/app.js";
import { builtInAppProfiles } from "../src/app-profiles.js";
import { issueAccessClaim } from "../src/claims.js";
import { type Provider } from "../src/contracts.js";
import { createRuntimeKeyMaterial, signJwt, verifyJwt } from "../src/signing.js";
import { InMemoryStore } from "../src/store/index.js";
import { type CreateAuditEventInput } from "../src/store/types.js";
import { createTestConfig } from "./oauth-flow.js";
// An app asserting a step-up proof for its member: POST /v1/apps/{app}/step-up.
// Driven over HTTP through the real Fastify app, the way Bifrost would call it,
// with the unlink route as the consumer of the proof it mints.
const now = "2026-11-13T12:00:00.000Z";
const secret = "bifrost-secret";
const appAuth = { "x-heimdall-app-secret": secret };
const nonce = (tag: string) => `nonce-${tag.replace(/[^A-Za-z0-9_-]/g, "_")}-`.padEnd(32, "x");
const dir = mkdtempSync(join(tmpdir(), "heimdall-stepup-assert-"));
const config = { ...createTestConfig(), signingPrivateKeyPath: join(dir, "signing.pem"), bootstrapSigningPrivateKeyOnMissing: true };
afterAll(() => rmSync(dir, { recursive: true, force: true }));
const apps: Awaited<ReturnType<typeof buildApp>>[] = [];
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<ReturnType<typeof rig>>;
/** 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<string, string>; 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:<name>", async () => {
// The sign_in path itself is proved in identity-unlink.test.ts; here the claim input is the contract.
const r = await rig();
const m = await member(r);
const issued = await issueAccessClaim({
config, keys: r.keys, store: r.store,
input: { appSlug: "bifrost", accountId: m.account.id, linkedIdentities: [], facts: [], stepUpAt: nowS(), stepUpMethod: "provider:google" },
});
expect(issued.claimSet.step_up_method).toBe("provider:google");
});
});
describe("it is never issuable without both credentials", () => {
it("401 app_auth_required for a missing, wrong, or another app's secret, even with a good bearer; nothing is written", async () => {
const r = await rig();
const m = await member(r);
for (const headers of [{}, { "x-heimdall-app-secret": "wrong" }, { "x-heimdall-app-secret": "streampixels-secret" }, { "x-heimdall-app-secret": "" }]) {
const res = await assertStepUp(r, { headers, token: m.token });
expect(res.statusCode).toBe(401);
expect(res.json()).toEqual({ error: "app_auth_required" });
}
expect(r.audit.filter((e) => e.eventType.startsWith("step_up"))).toEqual([]);
});
it("401 sign_in_required for a missing, garbage, expired, foreign-signed, revoked-session or unknown-session bearer; the same answer for each", async () => {
const r = await rig();
const m = await member(r);
const claims = claimsOf(m.token, r);
const past = nowS() - 10;
const other = createRuntimeKeyMaterial({ ...config, signingPrivateKeyPath: join(dir, "other.pem"), bootstrapSigningPrivateKeyOnMissing: true });
const bad: Array<[string, string | undefined]> = [
["missing", undefined],
["garbage", "not-a-token"],
["expired", signJwt({ ...claims, iat: past - 100, nbf: past - 100, exp: past }, r.keys)],
["foreign key", signJwt(claims, other)],
["unknown session", signJwt({ ...claims, sid: "no-such-session" }, r.keys)],
["wrong account for the session", signJwt({ ...claims, account_id: "someone-else" }, r.keys)],
["refresh token as bearer", m.issued.refreshToken],
];
for (const [label, token] of bad) {
const res = await assertStepUp(r, { token, nonce: nonce(label) });
expect([label, ...refused(res)]).toEqual([label, 401, "sign_in_required"]);
expect(res.body).not.toContain("account");
}
// A revoked session: the row is closed and its revision moved on.
expect(await r.store.revokeSession("bifrost", m.sid, m.account.id, 1, now)).not.toBeNull();
const revoked = await assertStepUp(r, { token: m.token, nonce: nonce("revoked") });
expect(refused(revoked)).toEqual([401, "sign_in_required"]);
expect(r.audit.some((e) => e.eventType === "step_up_asserted")).toBe(false);
});
it("a bearer issued to another app is 403 bearer_app_mismatch, never a proof, and says nothing about the account", async () => {
const r = await rig();
const sp = await member(r, "streampixels");
const res = await assertStepUp(r, { token: sp.token });
expect(refused(res)).toEqual([403, "bearer_app_mismatch"]);
expect(res.body).not.toContain(sp.account.id);
// A token for a session that does not exist is indistinguishable from garbage, whatever app it names.
const ghost = signJwt({ ...claimsOf(sp.token, r), sid: "ghost" }, r.keys);
expect(refused(await assertStepUp(r, { token: ghost }))).toEqual([401, "sign_in_required"]);
});
it("only a profile that grants it may assert: every other app is 403 with its own secret and a live bearer", async () => {
expect(Object.values(builtInAppProfiles).filter((p) => p.stepUpAssertion).map((p) => p.slug)).toEqual(["bifrost"]);
const r = await rig();
for (const [slug, appSecret] of [["streampixels", "streampixels-secret"], ["repixelizer", "repixelizer-secret"]] as const) {
const m = await member(r, slug);
const res = await assertStepUp(r, { app: slug, headers: { "x-heimdall-app-secret": appSecret }, token: m.token });
expect([slug, ...refused(res)]).toEqual([slug, 403, "step_up_assertion_not_permitted"]);
expect(res.json()).not.toHaveProperty("accessToken");
}
// Another app's secret on bifrost's route is still app_auth_required, not the flag.
const b = await member(r);
expect(refused(await assertStepUp(r, { headers: { "x-heimdall-app-secret": "streampixels-secret" }, token: b.token }))).toEqual([401, "app_auth_required"]);
});
});
describe("the method and the nonce", () => {
it("rejects a method outside the profile's closed set with 400, names the set, and does not spend the nonce", async () => {
const r = await rig();
const m = await member(r);
for (const method of ["passkey", "provider:google", "streampixels-passkey", "BIFROST-PASSKEY", "bifrost-passkey "]) {
const res = await assertStepUp(r, { token: m.token, method, nonce: nonce("m") });
expect([method, ...refused(res)]).toEqual([method, 400, "unknown_step_up_method"]);
expect(res.json().methods).toEqual(["bifrost-passkey", "bifrost-email-code"]);
}
expect((await assertStepUp(r, { token: m.token, method: "bifrost-email-code", nonce: nonce("m") })).statusCode).toBe(201);
});
it("malformed bodies are 400 before anything is minted", async () => {
const r = await rig();
const m = await member(r);
for (const payload of [{}, { method: "bifrost-passkey" }, { nonce: nonce("a") }, { method: "bifrost-passkey", nonce: "short" }, { method: "bifrost-passkey", nonce: "has a space in it, 16+ chars" }, { method: "bifrost-passkey", nonce: `${"a".repeat(20)}\ud800` }, { method: "bifrost-passkey", nonce: "a".repeat(129) }, { method: "bifrost-passkey", nonce: "ok-looking-nonce-é-ünï" }, { method: 7, nonce: nonce("a") }]) {
expect((await assertStepUp(r, { token: m.token, payload })).statusCode, JSON.stringify(payload)).toBe(400);
}
expect(auditOf(r, "step_up_asserted")).toEqual([]);
});
it("a nonce is single-use per session: the second try is 409, another session may use the same value", async () => {
const r = await rig();
const m = await member(r);
const second = await member(r, "bifrost", [], m.account.id);
expect((await assertStepUp(r, { token: m.token })).statusCode).toBe(201);
const replay = await assertStepUp(r, { token: m.token });
expect(refused(replay)).toEqual([409, "step_up_nonce_replayed"]);
expect(replay.json()).not.toHaveProperty("accessToken");
// The replay does not depend on which method rides with it.
expect(refused(await assertStepUp(r, { token: m.token, method: "bifrost-email-code" }))).toEqual([409, "step_up_nonce_replayed"]);
expect((await assertStepUp(r, { token: second.token })).statusCode).toBe(201);
});
it("a nonce is retained to the session's expiry as of the claim plus the 10.5 min prune horizon; a refresh slides the session past that and the nonce can be reused (documented limit)", async () => {
const r = await rig();
const m = await member(r);
vi.useFakeTimers({ toFake: ["Date"] });
const t0 = Date.now();
const R = config.refreshTtlSeconds * 1000;
expect((await assertStepUp(r, { token: m.token, nonce: nonce("N") })).statusCode).toBe(201);
vi.setSystemTime(t0 + R - 60_000);
const refreshed = await r.app.inject({ method: "POST", url: "/v1/apps/bifrost/sessions/refresh", payload: { refreshToken: m.issued.refreshToken } });
expect(refreshed.statusCode).toBe(201);
const token = refreshed.json().accessToken as string;
expect(refused(await assertStepUp(r, { token, nonce: nonce("N") })).join()).toBe("409,step_up_nonce_replayed");
// 10 min past the old expiry: a claim runs the prune, and N is still inside the 10.5 min horizon (10 min margin + 30 s skew).
vi.setSystemTime(t0 + R + 10 * 60_000);
expect((await assertStepUp(r, { token, nonce: nonce("M") })).statusCode).toBe(201);
expect(refused(await assertStepUp(r, { token, nonce: nonce("N") }))).toEqual([409, "step_up_nonce_replayed"]);
// Past the horizon the next claim prunes N (lazily, with the claim) while the session lives on.
vi.setSystemTime(t0 + R + 10 * 60_000 + 31_000 + 2_000);
expect((await assertStepUp(r, { token, nonce: nonce("K") })).statusCode).toBe(201);
expect((await assertStepUp(r, { token, nonce: nonce("N") })).statusCode).toBe(201);
});
it("a nonce stays spent for the session's life, past the access token's own expiry, and across a restart of the process", async () => {
const r = await rig();
const m = await member(r);
expect((await assertStepUp(r, { token: m.token })).statusCode).toBe(201);
// A second app instance over the same store has no memory of the first: the store carries the claim.
const again = await buildApp({ config, store: r.store });
apps.push(again);
const res = await again.inject({ method: "POST", url: "/v1/apps/bifrost/step-up", headers: { ...appAuth, ...bearer(m.token) }, payload: { method: "bifrost-passkey", nonce: nonce("a") } });
expect(refused(res)).toEqual([409, "step_up_nonce_replayed"]);
});
});
describe("rate limits", () => {
it("trips per account, leaves other accounts alone, and turns over with the window", async () => {
const r = await rig();
const m = await member(r);
const other = await member(r);
vi.useFakeTimers({ toFake: ["Date"] });
for (let i = 0; i < STEP_UP_ASSERT_LIMITS.account.max; i += 1) {
expect((await assertStepUp(r, { token: m.token, nonce: nonce(`r${i}`) })).statusCode, `attempt ${i}`).toBe(201);
}
const tripped = await assertStepUp(r, { token: m.token, nonce: nonce("over") });
expect(refused(tripped)).toEqual([429, "step_up_rate_limited"]);
expect(tripped.json().retryAfterSeconds).toBeGreaterThan(0);
expect(tripped.json()).not.toHaveProperty("accessToken");
expect((await assertStepUp(r, { token: other.token })).statusCode).toBe(201);
vi.setSystemTime(Date.now() + STEP_UP_ASSERT_LIMITS.account.windowMs + 1000);
expect((await assertStepUp(r, { token: m.token, nonce: nonce("after") })).statusCode).toBe(201);
// The tripped attempt did not spend its nonce.
expect((await assertStepUp(r, { token: m.token, nonce: nonce("over") })).statusCode).toBe(201);
});
it("trips per app across accounts, counting attempts that failed their bearer", async () => {
const r = await rig();
const m = await member(r);
vi.useFakeTimers({ toFake: ["Date"] });
for (let i = 0; i < STEP_UP_ASSERT_LIMITS.app.max; i += 1) {
expect((await assertStepUp(r, { token: "garbage", nonce: nonce(`g${i}`) })).statusCode).toBe(401);
}
expect(refused(await assertStepUp(r, { token: m.token }))).toEqual([429, "step_up_rate_limited"]);
vi.setSystemTime(Date.now() + STEP_UP_ASSERT_LIMITS.app.windowMs + 1000);
expect((await assertStepUp(r, { token: m.token })).statusCode).toBe(201);
});
});
describe("flood handling", () => {
it("the not-permitted budget is per app: one app's flood neither blocks bifrost's own call nor another ungranted app's first refusal", async () => {
const r = await rig();
const sp = await member(r, "streampixels");
const rp = await member(r, "repixelizer");
const b = await member(r);
const as = (app: string, appSecret: string, token: string, i: number) => assertStepUp(r, { app, headers: { "x-heimdall-app-secret": appSecret }, token, nonce: nonce(`i${i}`) });
for (let i = 0; i < 50; i += 1) await as("streampixels", "streampixels-secret", sp.token, i);
expect((await as("streampixels", "streampixels-secret", sp.token, 99)).statusCode).toBe(429);
expect(refused(await as("repixelizer", "repixelizer-secret", rp.token, 1))).toEqual([403, "step_up_assertion_not_permitted"]);
expect((await assertStepUp(r, { token: b.token })).statusCode).toBe(201);
});
it("a flood is not an audit flood: an app without the grant is audited once per window, a tripped budget once per window", async () => {
const r = await rig();
const sp = await member(r, "streampixels");
vi.useFakeTimers({ toFake: ["Date"] });
const codes: Record<number, number> = {};
for (let i = 0; i < 500; i += 1) {
const res = await assertStepUp(r, { app: "streampixels", headers: { "x-heimdall-app-secret": "streampixels-secret" }, token: sp.token, nonce: nonce(`f${i}`) });
codes[res.statusCode] = (codes[res.statusCode] ?? 0) + 1;
}
expect(codes).toEqual({ 403: STEP_UP_ASSERT_LIMITS.notPermitted.max, 429: 500 - STEP_UP_ASSERT_LIMITS.notPermitted.max });
const rows = (code: string) => auditOf(r, "step_up_assertion_refused").filter((e) => e.eventPayloadJson.code === code);
expect(rows("step_up_assertion_not_permitted")).toHaveLength(1);
expect(rows("step_up_rate_limited")).toHaveLength(1);
expect(rows("step_up_rate_limited")[0]!.eventPayloadJson.budget).toBe("notPermitted");
vi.setSystemTime(Date.now() + STEP_UP_ASSERT_LIMITS.notPermitted.windowMs + 1000);
await assertStepUp(r, { app: "streampixels", headers: { "x-heimdall-app-secret": "streampixels-secret" }, token: sp.token });
expect(rows("step_up_assertion_not_permitted")).toHaveLength(2);
// The same for the granted app's per-app and per-account budgets.
const m = await member(r);
const before = r.audit.length;
for (let i = 0; i < 300; i += 1) await assertStepUp(r, { token: "garbage", nonce: nonce(`g${i}`) });
expect(r.audit.length - before, "garbage-bearer refusals up to the budget, then one row for the trip").toBe(STEP_UP_ASSERT_LIMITS.app.max + 1);
vi.setSystemTime(Date.now() + STEP_UP_ASSERT_LIMITS.app.windowMs + 1000);
const mark = r.audit.length;
for (let i = 0; i < 30; i += 1) await assertStepUp(r, { token: m.token, nonce: nonce(`a${i}`) });
const accountRows = r.audit.slice(mark);
expect(accountRows.filter((e) => e.eventType === "step_up_asserted")).toHaveLength(STEP_UP_ASSERT_LIMITS.account.max);
const trips = accountRows.filter((e) => e.eventPayloadJson.code === "step_up_rate_limited");
expect(trips.map((e) => e.eventPayloadJson.budget)).toEqual(["account"]);
});
});
describe("receipts", () => {
it("records every assertion and every post-secret refusal with account, app, session, method, outcome and time, and nothing secret", async () => {
const r = await rig();
const m = await member(r);
const sp = await member(r, "streampixels");
const printed: string[] = [];
for (const channel of ["log", "info", "warn", "error", "debug"] as const) vi.spyOn(console, channel).mockImplementation((...a) => void printed.push(a.join(" ")));
vi.spyOn(process.stdout, "write").mockImplementation((chunk: unknown) => (printed.push(String(chunk)), true));
vi.spyOn(process.stderr, "write").mockImplementation((chunk: unknown) => (printed.push(String(chunk)), true));
const nonceOk = nonce("ok-CANARY");
const nonceBadMethod = nonce("bad-CANARY");
const responses = [
await assertStepUp(r, { token: m.token, nonce: nonceOk }),
await assertStepUp(r, { token: m.token, nonce: nonceOk }),
await assertStepUp(r, { token: m.token, method: "evil-CANARY-method", nonce: nonceBadMethod }),
await assertStepUp(r, { token: sp.token, nonce: nonce("mismatch-CANARY") }),
await assertStepUp(r, { token: "garbage-CANARY", nonce: nonce("anon-CANARY") }),
];
expect(responses.map((x) => x.statusCode)).toEqual([201, 409, 400, 403, 401]);
const ok = auditOf(r, "step_up_asserted");
expect(ok).toHaveLength(1);
expect(ok[0]).toMatchObject({ accountId: m.account.id, sessionId: m.sid, appSlug: "bifrost", eventPayloadJson: { outcome: "asserted", method: "bifrost-passkey" } });
expect(Date.parse(ok[0]!.createdAt)).not.toBeNaN();
const refusals = auditOf(r, "step_up_assertion_refused");
expect(refusals.map((e) => e.eventPayloadJson.code)).toEqual(["step_up_nonce_replayed", "unknown_step_up_method", "bearer_app_mismatch", "sign_in_required"]);
expect(refusals.map((e) => e.accountId)).toEqual([m.account.id, m.account.id, sp.account.id, undefined]);
expect(refusals[1]!.eventPayloadJson.method).toBeNull();
expect(refusals.every((e) => e.appSlug === "bifrost" && e.eventPayloadJson.outcome === "refused")).toBe(true);
for (const e of [...ok, ...refusals.slice(0, 2)]) expect(e.eventPayloadJson.nonceDigest).toMatch(/^[0-9a-f]{64}$/);
const everything = JSON.stringify([r.audit, printed, responses.map((x) => x.body.replace(/"accessToken":"[^"]+"/, ""))]);
const minted = responses[0]!.json().accessToken as string;
const secrets = [secret, m.token, sp.token, m.issued.refreshToken, "CANARY"];
for (const needle of secrets) expect(everything, needle).not.toContain(needle);
expect(JSON.stringify(r.audit)).not.toContain(minted);
expect(printed.join("")).not.toContain(minted);
// A stored session row holds nothing the minted token adds.
expect(JSON.stringify(await r.store.findSession("bifrost", m.sid))).not.toContain("step_up");
});
});

209
tests/step-up.test.ts Normal file
View file

@ -0,0 +1,209 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
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 { createRuntimeKeyMaterial, decodeJwt, signJwt, verifyJwt } 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<ReturnType<typeof buildApp>>[] = [];
afterEach(async () => {
await Promise.all(apps.splice(0).map((app) => app.close()));
});
async function rig(config = createTestConfig()) {
const app = await buildApp({
config,
store: new InMemoryStore(),
oauthRuntimes: { twitch: runtime("twitch", "t-1"), youtube: runtime("youtube", "y-1") },
});
apps.push(app);
return app;
}
type App = Awaited<ReturnType<typeof rig>>;
function start(
app: App,
provider: string,
payload: Record<string, unknown> = {},
headers: Record<string, string> = {},
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);
// 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");
}
});
});
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<string, string>, 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<string, unknown> };
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<string, unknown> };
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 });
}
});
});

File diff suppressed because it is too large Load diff

View file

@ -71,7 +71,7 @@ describe("Heimdall verse runtime publication", () => {
expect(bySchema.get("idunn.daemon_health")).toEqual([ expect(bySchema.get("idunn.daemon_health")).toEqual([
"yggdrasil-heimdall", "yggdrasil-heimdall",
"active", "active",
"Heimdall auth runtime active; storage=postgres; providers=2/6; apps=4; healthTransport=CultNet/RUDP", "Heimdall auth runtime active; storage=postgres; providers=2/8; apps=4; healthTransport=CultNet/RUDP",
"2026-06-16T17:10:00.000Z", "2026-06-16T17:10:00.000Z",
"heimdall.cultnet-rudp-provider-health", "heimdall.cultnet-rudp-provider-health",
"daemon-published", "daemon-published",

View file

@ -31,6 +31,8 @@ describe("Heimdall Verse witness advertisement", () => {
"twitch", "twitch",
"youtube", "youtube",
"spotify", "spotify",
"joystick",
"google",
]); ]);
expect(advertisement.appProfiles.map((profile) => profile.slug)).toEqual([ expect(advertisement.appProfiles.map((profile) => profile.slug)).toEqual([
"repixelizer", "repixelizer",