diff --git a/.env.example b/.env.example index 9b1ba8b..6af5d90 100644 --- a/.env.example +++ b/.env.example @@ -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 PORT=4100 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_ISSUER=http://127.0.0.1:4100 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_SESSION_TTL_SECONDS=3600 GC_ACCESS_STATE_TTL_SECONDS=600 GC_ACCESS_COMPLETION_TTL_SECONDS=300 -GC_ACCESS_SIGNING_PRIVATE_KEY_PEM= GC_ACCESS_SIGNING_PRIVATE_KEY_PATH= GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP=0 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_SECRET= +# GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE=/absolute/path/to/credential 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_SECRET= +# GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET_FILE=/absolute/path/to/credential 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_SECRET= +# GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET_FILE=/absolute/path/to/credential 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_GHOSTLIGHT_SHARED_SECRET= +# GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET_FILE=/absolute/path/to/credential GC_ACCESS_APP_GHOSTLIGHT_RUNTIME_IDS=yggdrasil-ghostlight diff --git a/README.md b/README.md index a34dc85..b86dbdc 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,19 @@ The point is painfully simple: become "everything phones home for every request" - 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), 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 This repo now has a stateful first slice instead of a decorative skeleton. diff --git a/deployment/idunn/recipe.toml b/deployment/idunn/recipe.toml index aa1e138..f520258 100644 --- a/deployment/idunn/recipe.toml +++ b/deployment/idunn/recipe.toml @@ -131,17 +131,22 @@ arguments = [ ] transport = "http" 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 = [ "CULTMESH_URI_ODIN_RUDP", "GC_ACCESS_APP_BIFROST_BACKEND_CALLBACK_URLS", - "GC_ACCESS_APP_BIFROST_SHARED_SECRET", + "GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE", "GC_ACCESS_APP_GHOSTLIGHT_BACKEND_CALLBACK_URLS", "GC_ACCESS_APP_GHOSTLIGHT_RUNTIME_IDS", - "GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET", + "GC_ACCESS_APP_GHOSTLIGHT_SHARED_SECRET_FILE", + "GC_ACCESS_APP_REPIXELIZER_SHARED_SECRET_FILE", + "GC_ACCESS_APP_STREAMPIXELS_SHARED_SECRET_FILE", "GC_ACCESS_APPLY_SCHEMA_ON_STARTUP", - "GC_ACCESS_APP_SHARED_SECRET", "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_IDUNN_HEALTH_CONTRACT", "GC_ACCESS_IDUNN_RUDP_HEALTH", @@ -150,27 +155,31 @@ optional_environment = [ "GC_ACCESS_PRIVATE_COMMAND_HOST", "GC_ACCESS_PRIVATE_COMMAND_PORT", "GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID", - "GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET", + "GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE", + "GC_ACCESS_PROVIDER_GITHUB_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_SECRET", + "GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET_FILE", + "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET_FILE", "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_SECRET", + "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET_FILE", "GC_ACCESS_SESSION_TTL_SECONDS", "GC_ACCESS_SIGNING_KEY_ID", "GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP", "GC_ACCESS_SIGNING_PRIVATE_KEY_PATH", "GC_ACCESS_STATE_TTL_SECONDS", "GC_ACCESS_STORAGE_BACKEND", - "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64", + "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE", ] required_environment = [ "GAMECULT_IDUNN_RUNTIME_BUNDLE", "GAMECULT_IDUNN_CANDIDATE_BIND", "GAMECULT_IDUNN_PROCESS_WRITE_LEASE", "GC_ACCESS_BASE_URL", - "GC_ACCESS_DATABASE_URL", + "GC_ACCESS_DATABASE_URL_FILE", ] [service.health] diff --git a/docs/app-profiles/bifrost.md b/docs/app-profiles/bifrost.md index 99d37b6..976452f 100644 --- a/docs/app-profiles/bifrost.md +++ b/docs/app-profiles/bifrost.md @@ -68,10 +68,11 @@ paid membership for the requested tier title, and POSTs a signed `RecurringSupportSnapshot` fact to Bifrost's `/heimdall/patron-support/events` endpoint. -The outbound fact uses `X-Heimdall-Signature-256` with the shared -`GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET`. Bifrost verifies that HMAC, resolves -the Heimdall account id to its local user account, deduplicates by provider -event id, records the support event, and derives patron points locally. +The outbound fact uses `X-Heimdall-Signature-256` with the shared secret +Heimdall reads from `GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE`. Bifrost +verifies that HMAC, resolves the Heimdall account id to its local user account, +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 governance meaning. Heimdall still does not own points, votes, tiers, ledger diff --git a/docs/app-profiles/spotiverse.md b/docs/app-profiles/spotiverse.md index ed52874..a847fba 100644 --- a/docs/app-profiles/spotiverse.md +++ b/docs/app-profiles/spotiverse.md @@ -20,7 +20,7 @@ > still reports `providers=2/6`, which counts it. > > **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 > 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 @@ -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 allowlisted value. 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 fresh Spotify application registration may be needed. 4. Restore the three tests from `5a15f71` if the capabilities they covered @@ -80,13 +80,12 @@ Heimdall needs: ```text GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID=... -GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET=... -GC_ACCESS_APP_SPOTIVERSE_SHARED_SECRET=... +GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET_FILE=/absolute/path/to/spotify-client-secret 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 -portal callback/return URLs. The callback URL Spotiverse sends in +Spotiverse needs only the Heimdall base URL and local portal callback/return +URLs. The callback URL Spotiverse sends in `HEIMDALL_CALLBACK_URL` must exactly match one URL in Heimdall's `GC_ACCESS_APP_SPOTIVERSE_BACKEND_CALLBACK_URLS` allowlist unless both services are running on the same local host. diff --git a/docs/app-profiles/streampixels.md b/docs/app-profiles/streampixels.md index f28b40a..dbd91f1 100644 --- a/docs/app-profiles/streampixels.md +++ b/docs/app-profiles/streampixels.md @@ -20,7 +20,11 @@ Corroborated by `gamecult-ops/nginx/streampixels.gamecult.org.conf:14` The current StreamPixels architecture already makes useful splits: - 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 - 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 - 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 - shared claim semantics diff --git a/docs/architecture.md b/docs/architecture.md index 5f290af..8ae5c19 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -305,6 +305,159 @@ Important rule: 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 +## 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. + +### 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`: connect starts are + unauthenticated, so anyone can name `{creator, targetId}`; the callback + re-check proves a binding exists, not that the caller owns it. It also owns + the whitespace-only `targetId` that passes both gates and the callback's + fail-open `''` fallback for a vanished profile (finding + `joystick:finding:cut-h1.s4.whitespace-targetid-passes-custody-gate`). Must + land before the public Joystick bot or a second creator. +- `joystick:follow_up: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 The shared authority should not hard-code one app's access rules. It should @@ -514,24 +667,17 @@ each provider**. That URL cannot move on deploy. ### Finding: the `spotify` provider outlived its consumer -`spotiverse` is 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 -it no longer exists in the swarm. +`spotiverse` was the only profile naming `spotify`, and Spotiverse was lost with +the `E:` drive. The profile has since been removed from the registry +(`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 -`GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET` are configured in -`/srv/heimdall/env/service.env`, the profile is advertised in the public -discovery document, and `/v1/oauth/spotify/start` is reachable from the open -web. That path would run a real OAuth handshake against a real client secret and -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. +What survives: the `spotify` catalog entry and runtime, and, wherever an +operator env still holds them, `GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID` and +`GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET_FILE`. A live credential kept for a +consumer that does not exist is the shape that becomes an incident later. +Retire the provider config, or record why Spotiverse is expected back. ## Deployment modes @@ -572,47 +718,46 @@ every app's audience or product data. ## 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_INTERNAL_URL=http://127.0.0.1:4100` -- `GC_ACCESS_SESSION_SECRET=...` -- `GC_ACCESS_SIGNING_PRIVATE_KEY_PEM=...` -- `GC_ACCESS_SIGNING_PRIVATE_KEY_PATH=/var/lib/heimdall/signing-key.pem` +- `GC_ACCESS_ISSUER=https://heimdall.gamecult.org` +- `GC_ACCESS_STORAGE_BACKEND=postgres` +- `GC_ACCESS_SIGNING_PRIVATE_KEY_PATH=/etc/gamecult/heimdall/credentials/signing-key.pem` - `GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP=1` - `GC_ACCESS_SIGNING_KEY_ID=...` -- `GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64=...` - `GC_ACCESS_SESSION_TTL_SECONDS=3600` - `GC_ACCESS_STATE_TTL_SECONDS=600` -- `GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID=...` -- `GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET=...` -- `GC_ACCESS_PROVIDER_DISCORD_BOT_TOKEN=...` -- `GC_ACCESS_PROVIDER_PATREON_CLIENT_ID=...` -- `GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET=...` -- `GC_ACCESS_PROVIDER_PATREON_CAMPAIGN_ID=...` -- `GC_ACCESS_PROVIDER_GITHUB_CLIENT_ID=...` -- `GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET=...` -- `GC_ACCESS_PROVIDER_TWITCH_CLIENT_ID=...` -- `GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET=...` -- `GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID=...` -- `GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET=...` -- `GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID=...` -- `GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET=...` -- `GC_ACCESS_ENTITLEMENT_CACHE_TTL_SECONDS=900` -- `GC_ACCESS_PROVIDER_FAILURE_GRACE_SECONDS=3600` +- `GC_ACCESS_PROVIDER_{DISCORD,PATREON,GITHUB,TWITCH,YOUTUBE,SPOTIFY,JOYSTICK}_CLIENT_ID=...` +- `GC_ACCESS_APP_{APP_SLUG}_BACKEND_CALLBACK_URLS=...` + +Secret files: + +- `GC_ACCESS_DATABASE_URL_FILE=/etc/gamecult/heimdall/credentials/GC_ACCESS_DATABASE_URL` +- `GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64_FILE=...` +- `GC_ACCESS_PROVIDER_{DISCORD,PATREON,GITHUB,TWITCH,YOUTUBE,SPOTIFY,JOYSTICK}_CLIENT_SECRET_FILE=...` +- `GC_ACCESS_APP_{APP_SLUG}_SHARED_SECRET_FILE=...` +- `GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE=...` + +`src/config.ts` is the complete list; `deployment/idunn/recipe.toml` declares +the subset an Idunn binding may set. Only configure the providers Heimdall actually owns for a given deployment. -If `GC_ACCESS_SIGNING_PRIVATE_KEY_PEM` is absent, the current skeleton falls -back to `GC_ACCESS_SIGNING_PRIVATE_KEY_PATH` if present, and can bootstrap that -file on first boot when `GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP=1`. If -neither PEM nor path is configured, the current skeleton falls back to an +The signing key is always a file: `GC_ACCESS_SIGNING_PRIVATE_KEY_PATH` names +it, and Heimdall can bootstrap that file on first boot when +`GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP=1`. If no path is configured, the current skeleton falls back to an ephemeral dev signing key. That is acceptable for local iteration and absolutely not acceptable for real deployment. 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 Postgres deployments should treat a missing token-encryption key as a hard misconfiguration, not a vibe. diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 9a1f84d..44bcbc7 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -44,7 +44,7 @@ What exists right now is: and managed creator connections - an app-authenticated managed-credential resolve endpoint so StreamPixels can 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 - StreamPixels now starts viewer and creator Twitch/YouTube OAuth through 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: - 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 diff --git a/docs/service-contract.md b/docs/service-contract.md index 54df1a9..1567ae5 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -44,12 +44,11 @@ Purpose: Notes: - 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 from disk - if the path is missing and `GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP=1`, the 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 ### `GET /.well-known/heimdall-configuration` @@ -119,6 +118,7 @@ Supported providers in the skeleton: - `twitch` - `youtube` - `spotify` +- `joystick` Request body: @@ -173,7 +173,7 @@ Failure modes: Launch note: - 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 - GitHub is still catalogued for start URLs, but its callback runtime is not implemented yet @@ -431,9 +431,11 @@ Important behavior: - 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 -- if a stored provider access token is expired or near expiry, Heimdall uses - the stored provider refresh token and persists any rotation before - evaluating entitlements +- if a stored provider access token is expired or near expiry, Heimdall takes + a row lock on the linked identity, re-reads it, uses the stored provider + 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 send `entitlementPolicies`; Heimdall matches each stored identity to the policy for that provider. Sending policy without authenticating is @@ -452,8 +454,9 @@ Purpose: Authentication: - requires `x-heimdall-app-secret` -- the configured secret comes from `GC_ACCESS_APP_{APP_SLUG}_SHARED_SECRET`, - per app; there is no generic fallback secret shared across apps +- the configured secret comes from the credential file named by + `GC_ACCESS_APP_{APP_SLUG}_SHARED_SECRET_FILE`, per app; there is no generic + fallback secret shared across apps Request body: @@ -484,7 +487,36 @@ Important behavior: - it returns access tokens only; refresh tokens remain in Heimdall custody - when a stored managed credential is expired or within the refresh window, 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), so + nobody re-presents a token behind a failed holder in that burst. Residual + risk, tracked as follow-up `joystick:follow_up:cross-process-failed-refresh-marker`: + the guard is one presentation per process per burst, so N + Heimdall processes can present one token N times after a transient failure. + 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-owned diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 9a4fdab..9d23cf1 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -1,6 +1,6 @@ # 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 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: ```powershell -# This repo has no dedicated venv yet. Use any working Python 3.11+. -E:\Projects\repixelizer\.venv\Scripts\python.exe .\tools\heimdall_state.py status +python .\tools\heimdall_state.py status Get-Content '.\state\map.yaml' Get-Content '.\notes\fresh-workspace-handoff.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. +## Active Work + +Joystick H1 is merged and live (PR GameCult/Heimdall#1; campaign +`joystick:campaign:self`). Next: `joystick:follow_up:h1-joystick-consent-round-trip`, then +StreamPixels S0/S1 (other sessions). Open Heimdall follow-ups, by id: +`joystick:follow_up:cross-process-failed-refresh-marker`, +`joystick:follow_up:connect-start-needs-app-auth`, +`joystick:follow_up:heimdall-idunn-onboarding`, +`joystick:follow_up:joystick-viewer-signin-public-bot`. The Ghostlight KLTST +canaries below stay open, behind them. + ## Current Orientation -- Yggdrasil runs Heimdall - `1086aee01169bf60e8a492b2740db1c6f3e8cabf` with CultLib +Yggdrasil runs Heimdall `d51fa6b`, hand-deployed 2026-10-19 15:51Z; +gamecult-ops `210a1af` records backup, rollback and provenance. Facts below +about Odin, Ghostlight and CultLib pins were verified at `1086aee` (2026-08-22) +and are not re-verified at `d51fa6b`. + +- At `1086aee01169bf60e8a492b2740db1c6f3e8cabf` Heimdall ran with CultLib `5cefa0db0079a8e3ee22f29d7b9e6e5aa60912a9` - Heimdall publishes four redacted access records to Odin under unique keys: `eve:provider:heimdall`, `heimdall:command-boundary`, @@ -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 configured; HTTP `/healthz`, JWKS, discovery, systemd, and nginx routing remain compatibility witnesses -- Yggdrasil now runs Heimdall commit - `1086aee01169bf60e8a492b2740db1c6f3e8cabf`. Heimdall persists its private +- Since `1086aee` Heimdall persists its private provider-health identity at `/srv/heimdall/keys/provider-health-identity.cc` and publishes canonical signed health independently of the slower Verse snapshot cadence. Idunn owns the exact root trust binding, authenticated @@ -171,6 +184,8 @@ Do not trust this file for the exact live HEAD. Always check git. ## Next Real Move +The Active Work follow-ups first. Everything below is the standing queue. + Do not continue implementation automatically from a rehydrate-only request. The Idunn/swarm health transport cut is live. Do not regress Heimdall to @@ -233,9 +248,10 @@ Bifrost needs browser verification after deployment: - configure Heimdall with `GC_ACCESS_APP_BIFROST_BACKEND_CALLBACK_URLS=https://bifrost.gamecult.org/auth/heimdall/callback` -- configure Heimdall with `GC_ACCESS_APP_BIFROST_SHARED_SECRET`, +- configure Heimdall with `GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE`, `GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT=https://bifrost.gamecult.org/heimdall/patron-support/events`, - and `GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET` + and `GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE`, each naming a credential + file - configure Bifrost with `Heimdall__DiscordGuildId`, `Heimdall__DiscordAllowedRoleIds__0=`, and `Heimdall__PatreonTierTitle=Inner Sanctum` diff --git a/package.json b/package.json index 0c6cf4f..36394ef 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "@gamecult/cultcache-ts": "file:vendor/CultLib/packages/cultcache-ts", "cultmesh-ts": "file:vendor/CultLib/packages/cultmesh-ts", "cultnet-ts": "file:vendor/CultLib/packages/cultnet-ts", - "fastify": "^5.8.5", + "fastify": "^5.12.6", "pg": "^8.20.0", "zod": "^3.25.76" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 005bb26..855ad01 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -28,8 +28,8 @@ importers: specifier: file:vendor/CultLib/packages/cultnet-ts version: file:vendor/CultLib/packages/cultnet-ts fastify: - specifier: ^5.8.5 - version: 5.8.5 + specifier: ^5.12.6 + version: 5.12.7 pg: specifier: ^8.20.0 version: 8.20.0 @@ -532,17 +532,23 @@ packages: fast-json-stringify@6.3.0: resolution: {integrity: sha512-oRCntNDY/329HJPlmdNLIdogNtt6Vyjb1WuT01Soss3slIdyUp8kAcDU3saQTOquEK8KFVfwIIF7FebxUAu+yA==} + fast-json-stringify@7.1.3: + resolution: {integrity: sha512-5TDM1yOF/BDFOclKz2G6rs1RsIl5HXMCrg/npmdNIPNQCezshR5kIHjhwBNuMY67jhkTUAm9DguL8xkL/x0Wtw==} + fast-querystring@1.1.2: resolution: {integrity: sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==} fast-uri@3.1.0: resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==} + fast-uri@4.2.3: + resolution: {integrity: sha512-I1PXwP5eAhlNlcdpjt9CgB59op2ZvZfxw+BkqGFVIUOgNpCVTcTqp3HhTX7brxj5vsip+nSY4nTvff+eIA76hg==} + fastify-plugin@5.1.0: resolution: {integrity: sha512-FAIDA8eovSt5qcDgcBvDuX/v0Cjz0ohGhENZ/wpc3y+oZCY2afZ9Baqql3g/lC+OHRnciQol4ww7tuthOb9idw==} - fastify@5.8.5: - resolution: {integrity: sha512-Yqptv59pQzPgQUSIm87hMqHJmdkb1+GPxdE6vW6FRyVE9G86mt7rOghitiU4JHRaTyDUk9pfeKmDeu70lAwM4Q==} + fastify@5.12.7: + resolution: {integrity: sha512-v4pEPsTRPuqlDIYiQFB+BHjVN4SdHX9u0ABk0ZDUKbbdY1vsNryUd1j4Z+jQEZajvYIVk047Kimva9/AJ79GYw==} fastq@1.20.1: resolution: {integrity: sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==} @@ -556,8 +562,8 @@ packages: picomatch: optional: true - find-my-way@9.5.0: - resolution: {integrity: sha512-VW2RfnmscZO5KgBY5XVyKREMW5nMZcxDy+buTOsL+zIPnBlbKm+00sgzoQzq1EVh4aALZLfKdwv6atBGcjvjrQ==} + find-my-way@9.10.0: + resolution: {integrity: sha512-eru+uCPQ2g+nLBkf84MHP/KyNNMar0BDy0j+i8Fb72GF9/YHBZ58q7FODUtfVV7XU9nfRUHXSmaM8NmZcIbZ4Q==} engines: {node: '>=20'} fsevents@2.3.3: @@ -853,8 +859,8 @@ packages: process-warning@4.0.1: resolution: {integrity: sha512-3c2LzQ3rY9d0hc1emcsHhfT9Jwz0cChib/QN89oME2R451w5fy3f0afAhERFZAwrbDU43wk12d0ORBpDVME50Q==} - process-warning@5.0.0: - resolution: {integrity: sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==} + process-warning@5.1.1: + resolution: {integrity: sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==} quick-format-unescaped@4.0.4: resolution: {integrity: sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==} @@ -1475,15 +1481,26 @@ snapshots: json-schema-ref-resolver: 3.0.0 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: dependencies: fast-decode-uri-component: 1.0.1 fast-uri@3.1.0: {} + fast-uri@4.2.3: {} + fastify-plugin@5.1.0: {} - fastify@5.8.5: + fastify@5.12.7: dependencies: '@fastify/ajv-compiler': 4.0.5 '@fastify/error': 4.2.0 @@ -1491,11 +1508,11 @@ snapshots: '@fastify/proxy-addr': 5.1.0 abstract-logging: 2.0.1 avvio: 9.2.0 - fast-json-stringify: 6.3.0 - find-my-way: 9.5.0 + fast-json-stringify: 7.1.3 + find-my-way: 9.10.0 light-my-request: 6.6.0 pino: 10.3.1 - process-warning: 5.0.0 + process-warning: 5.1.1 rfdc: 1.4.1 secure-json-parse: 4.1.0 semver: 7.7.4 @@ -1509,7 +1526,7 @@ snapshots: optionalDependencies: picomatch: 4.0.4 - find-my-way@9.5.0: + find-my-way@9.10.0: dependencies: fast-deep-equal: 3.1.3 fast-querystring: 1.1.2 @@ -1733,7 +1750,7 @@ snapshots: on-exit-leak-free: 2.1.2 pino-abstract-transport: 3.0.0 pino-std-serializers: 7.1.0 - process-warning: 5.0.0 + process-warning: 5.1.1 quick-format-unescaped: 4.0.4 real-require: 0.2.0 safe-stable-stringify: 2.5.0 @@ -1758,7 +1775,7 @@ snapshots: process-warning@4.0.1: {} - process-warning@5.0.0: {} + process-warning@5.1.1: {} quick-format-unescaped@4.0.4: {} diff --git a/schemas/heimdall.auth_begin_command.v1.schema.json b/schemas/heimdall.auth_begin_command.v1.schema.json index 81fdaf8..ca22ccf 100644 --- a/schemas/heimdall.auth_begin_command.v1.schema.json +++ b/schemas/heimdall.auth_begin_command.v1.schema.json @@ -4,7 +4,7 @@ "type": "object", "required": ["provider", "mode", "returnTo", "entitlementPolicy"], "properties": { - "provider": { "enum": ["discord", "patreon", "github", "twitch", "youtube", "spotify"] }, + "provider": { "enum": ["discord", "patreon", "github", "twitch", "youtube", "spotify", "joystick"] }, "mode": { "enum": ["sign_in", "link", "connect"] }, "returnTo": { "type": "string", "format": "uri" }, "entitlementPolicy": { diff --git a/src/app-profiles.ts b/src/app-profiles.ts index bede115..3489a48 100644 --- a/src/app-profiles.ts +++ b/src/app-profiles.ts @@ -3,7 +3,7 @@ import { type CapabilityDefinition, type CapabilityMode, } from "./capability-rules.js"; -import { type AppSlug, type LinkedIdentityInput, type 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"; export type { CapabilityDefinition, CapabilityMode }; @@ -99,10 +99,10 @@ const repixelizerProfile: AppProfile = { const streampixelsProfile: AppProfile = { slug: "streampixels", displayName: "StreamPixels", - profileVersion: "2026-04-26", + profileVersion: "2026-10-19", identityProviders: ["twitch", "youtube"], entitlementSources: [], - managedConnectionProviders: ["twitch", "youtube"], + managedConnectionProviders: ["twitch", "youtube", "joystick"], allowedReturnOrigins: ["https://streampixels.gamecult.org"], capabilities: [ { @@ -222,12 +222,19 @@ export function serializeAppProfile(profile: AppProfile): Record { - const expiresAt = options.linkedIdentity.tokenExpiresAt ? Date.parse(options.linkedIdentity.tokenExpiresAt) : undefined; - if ( - !expiresAt || - expiresAt - Date.now() > MANAGED_CREDENTIAL_REFRESH_SKEW_MS || - !options.linkedIdentity.refreshTokenEncrypted - ) { - return options.linkedIdentity; - } - - const runtime = options.oauthRuntimes[options.linkedIdentity.provider]; - if (!runtime.refreshAccessToken) { - return options.linkedIdentity; - } - - const refreshToken = options.tokenCustody.decrypt(options.linkedIdentity.refreshTokenEncrypted); - const refreshed = await runtime.refreshAccessToken({ - config: options.config, - refreshToken, - }); - - const upsertInput: UpsertLinkedIdentityInput = { - id: options.linkedIdentity.id, - accountId: options.linkedIdentity.accountId, - provider: options.linkedIdentity.provider, - providerUserId: options.linkedIdentity.providerUserId, - accessTokenEncrypted: options.tokenCustody.encrypt(refreshed.accessToken), - refreshTokenEncrypted: options.tokenCustody.encrypt(refreshed.refreshToken ?? refreshToken), - scopes: refreshed.scope.length ? refreshed.scope : options.linkedIdentity.scopes, - profileJson: options.linkedIdentity.profileJson, - createdAt: options.linkedIdentity.createdAt, - updatedAt: options.now, - }; - const tokenExpiresAt = refreshed.expiresAt ?? options.linkedIdentity.tokenExpiresAt; - if (tokenExpiresAt !== undefined) { - upsertInput.tokenExpiresAt = tokenExpiresAt; - } - if (options.linkedIdentity.username !== undefined) { - upsertInput.username = options.linkedIdentity.username; - } - if (options.linkedIdentity.displayName !== undefined) { - upsertInput.displayName = options.linkedIdentity.displayName; - } - if (options.linkedIdentity.primaryEmail !== undefined) { - upsertInput.primaryEmail = options.linkedIdentity.primaryEmail; - } - - return options.store.upsertLinkedIdentity(upsertInput); -} - function storedIdentityToResolvedIdentity(identity: StoredLinkedIdentity) { const resolved = { provider: identity.provider, @@ -426,7 +392,6 @@ async function evaluateStoredEntitlements(options: { appSlug: AppSlug; accountId: string; entitlementPolicies: OAuthEntitlementPolicy[]; - now: string; }): Promise { const profile = getAppProfile(options.appSlug); if (!profile) { @@ -436,19 +401,13 @@ async function evaluateStoredEntitlements(options: { const facts: string[] = []; for (const storedIdentity of linkedIdentities) { - if (!profile.entitlementSources.includes(storedIdentity.provider) || !storedIdentity.accessTokenEncrypted) { + if (!profile.entitlementSources.includes(storedIdentity.provider)) { continue; } - const linkedIdentity = await refreshLinkedIdentityCredentialIfNeeded({ - config: options.config, - store: options.store, - tokenCustody: options.tokenCustody, - oauthRuntimes: options.oauthRuntimes, - linkedIdentity: storedIdentity, - now: options.now, - }); - if (!linkedIdentity.accessTokenEncrypted) { + const refreshed = await refreshManagedCredential(options, storedIdentity); + const linkedIdentity = refreshed.identity; + if (refreshed.kind === "revoked" || !linkedIdentity.accessTokenEncrypted) { continue; } @@ -532,13 +491,23 @@ export async function startOAuthFlow( const { config, keys } = ctx; const profile = getAppProfile(input.appSlug); if (!profile) { - return { statusCode: 404, body: { error: "unknown_app", detail: `No app '${input.appSlug}' is registered.` } }; + return { statusCode: 404, body: { error: "unknown_app", detail: "No app is registered under that slug." } }; } - if (!supportsProvider(profile, provider)) { + if (!admitsProviderForMode(profile, provider, input.mode)) { return { statusCode: 400, - body: { error: "provider_not_supported_for_app", provider, appSlug: profile.slug }, + body: { error: "provider_not_supported_for_app", provider, mode: input.mode, appSlug: profile.slug }, + }; + } + + if (callbackMint(profile, provider, input.mode, input.connection) === "refused") { + return { + statusCode: 400, + body: { + error: "creator_connection_required", + detail: `${provider} on ${profile.slug} is a managed creator connection: connect needs connection.kind creator and a targetId.`, + }, }; } @@ -690,7 +659,6 @@ export async function refreshAppSession( appSlug, accountId: refreshClaim.account_id, entitlementPolicies, - now: nowIso, }); const issueInput: IssueAccessClaimInput = { appSlug, @@ -736,6 +704,31 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { + const status = error.statusCode !== undefined && error.statusCode >= 400 && error.statusCode < 600 ? error.statusCode : 500; + const code = typeof error.code === "string" ? error.code : "error"; + reply.code(status); + if (status >= 500) { + console.error(`Heimdall ${request.method} ${request.routeOptions.url ?? "(no route)"} failed (${code}).`); + return { error: "internal_error" }; + } + if (error.validation) { + // Ajv's messages and schema paths come from the route's schema, not the request. + const failures = error.validation.map((failure) => `${failure.schemaPath} ${failure.message ?? failure.keyword}`); + return { error: "invalid_request", detail: `${error.validationContext ?? "request"}: ${failures.join("; ")}` }; + } + return { error: "invalid_request", code }; + }); + app.setNotFoundHandler((_request, reply) => { + reply.code(404); + return { error: "not_found" }; + }); app.decorate("heimdallContext", { config, keys, store, oauthRuntimes, tokenCustody }); app.addHook("onClose", async () => { await store.close(); @@ -788,7 +781,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise= 100 && status <= 599 ? status : null, }, createdAt: nowIso, }); @@ -1316,7 +1336,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise, + Partial> { status: "success"; mode: OAuthMode; account: AccountSummary; @@ -44,10 +50,10 @@ export async function deliverBackendHandoff(callbackUrl: string, payload: Backen 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) { - const body = await response.text(); - throw new Error( - `Backend handoff delivery failed (status ${response.status}): ${body || "empty response"}` - ); + await response.body?.cancel(); + throw new Error(`Backend handoff delivery failed (status ${response.status}).`); } } diff --git a/src/browser-handoff.ts b/src/browser-handoff.ts index d3ce0fa..e23601e 100644 --- a/src/browser-handoff.ts +++ b/src/browser-handoff.ts @@ -56,6 +56,9 @@ function buildBrowserFallbackUrl(payload: BrowserHandoffPayload): string { } } + // 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(); return url.toString(); } diff --git a/src/claims.ts b/src/claims.ts index 11c42ea..4440ed3 100644 --- a/src/claims.ts +++ b/src/claims.ts @@ -39,6 +39,12 @@ export interface IssueAccessClaimInput { displayName?: string; linkedIdentities: LinkedIdentityInput[]; 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; accessRevision?: number; ttlSeconds?: number; @@ -80,11 +86,15 @@ export async function issueAccessClaim(options: { // 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}'.`); } - const facts = normalizeFacts(options.input.accountId, options.input.linkedIdentities, options.input.facts); - const factSet = new Set(facts); + const withoutCapabilities = options.input.withoutCapabilities === true; + 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, { accountId: options.input.accountId, - facts: factSet, + facts: new Set(facts), identities: options.input.linkedIdentities, }); @@ -176,6 +186,8 @@ export async function issueAccessClaim(options: { kid: options.keys.kid, }, sharedCapabilities, - hybridCapabilities: profile.capabilities.filter((capability) => capability.mode === "hybrid"), + hybridCapabilities: withoutCapabilities + ? [] + : profile.capabilities.filter((capability) => capability.mode === "hybrid"), }; } diff --git a/src/config.ts b/src/config.ts index c60b96a..39ab96f 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,3 +1,4 @@ +import { readFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { appSlugs, providers, type AppSlug, type Provider } from "./contracts.js"; @@ -35,7 +36,6 @@ export interface HeimdallConfig { refreshTtlSeconds: number; stateTtlSeconds: number; completionTtlSeconds: number; - signingPrivateKeyPem?: string; signingPrivateKeyPath?: string; bootstrapSigningPrivateKeyOnMissing: boolean; signingKeyId?: string; @@ -121,11 +121,64 @@ function readIdunnCandidateBind( 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 { const prefix = `GC_ACCESS_PROVIDER_${provider.toUpperCase()}`; const config: ProviderClientConfig = {}; const clientId = env[`${prefix}_CLIENT_ID`]; - const clientSecret = env[`${prefix}_CLIENT_SECRET`]; + const clientSecret = readSecretInput(env, `${prefix}_CLIENT_SECRET`); if (clientId) { config.clientId = clientId; @@ -201,8 +254,9 @@ export function loadConfig( const issuer = trimTrailingSlash(env.GC_ACCESS_ISSUER ?? publicBaseUrl); const dataRoot = stateRootArgument ?? env.GC_ACCESS_DATA_ROOT ?? path.join(workspaceRoot, ".heimdall-data"); + const databaseUrl = readSecretInput(env, "GC_ACCESS_DATABASE_URL"); 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( providers.map((provider) => [provider, readProviderConfig(env, provider)]) ) as Record; @@ -210,7 +264,7 @@ export function loadConfig( appSlugs .map((appSlug) => { const envKey = `GC_ACCESS_APP_${appSlug.toUpperCase()}_SHARED_SECRET`; - return [appSlug, env[envKey]]; + return [appSlug, readSecretInput(env, envKey)]; }) .filter(([, value]) => Boolean(value)) ) as Partial>; @@ -278,33 +332,38 @@ export function loadConfig( config.odinCultMeshUri = odinCultMeshUri; } - const signingPrivateKeyPem = env.GC_ACCESS_SIGNING_PRIVATE_KEY_PEM?.replace(/\\n/g, "\n"); - if (signingPrivateKeyPem) { - config.signingPrivateKeyPem = signingPrivateKeyPem; - } - - if (env.GC_ACCESS_SIGNING_PRIVATE_KEY_PATH) { - config.signingPrivateKeyPath = env.GC_ACCESS_SIGNING_PRIVATE_KEY_PATH; + // The signing key path follows the secret reader's rules: it must be + // absolute, and no error repeats it. An operator moving off the deleted + // 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 (signingPrivateKeyPath) { + 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) { config.signingKeyId = env.GC_ACCESS_SIGNING_KEY_ID; } - if (env.GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64) { - config.tokenEncryptionKeyBase64 = env.GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64; + const tokenEncryptionKeyBase64 = readSecretInput(env, "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64"); + if (tokenEncryptionKeyBase64) { + config.tokenEncryptionKeyBase64 = tokenEncryptionKeyBase64; } if (env.GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT) { config.bifrostPatronSupportEndpoint = env.GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT; } - if (env.GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET) { - config.bifrostPatronSupportSecret = env.GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET; + const bifrostPatronSupportSecret = readSecretInput(env, "GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET"); + if (bifrostPatronSupportSecret) { + config.bifrostPatronSupportSecret = bifrostPatronSupportSecret; } - if (env.GC_ACCESS_DATABASE_URL) { - config.storage.databaseUrl = env.GC_ACCESS_DATABASE_URL; + if (databaseUrl) { + config.storage.databaseUrl = databaseUrl; } return config; diff --git a/src/contracts.ts b/src/contracts.ts index 743bfdc..d6cab2a 100644 --- a/src/contracts.ts +++ b/src/contracts.ts @@ -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"] as const; export type Provider = (typeof providers)[number]; diff --git a/src/custody.ts b/src/custody.ts index d2849c1..baa45b0 100644 --- a/src/custody.ts +++ b/src/custody.ts @@ -12,15 +12,11 @@ export interface TokenCustody { } function decodeConfiguredKey(base64Value: string): Buffer { - const normalized = base64Value.trim(); - if (!normalized) { - throw new Error("GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64 is set but empty."); - } - - const key = Buffer.from(normalized, "base64"); + // readSecretInput refuses a blank key; a short one fails the length check. + const key = Buffer.from(base64Value.trim(), "base64"); if (key.byteLength !== TOKEN_KEY_BYTES) { 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") { 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." ); } diff --git a/src/index.ts b/src/index.ts index 4c89a70..0bc13c3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,3 @@ -import path from "node:path"; import { resolveWriteLease, WriteLeaseNotHeldError } from "./process-write-lease.js"; import { buildApp } from "./app.js"; import { loadConfig } from "./config.js"; @@ -7,14 +6,16 @@ import { publishHeimdallOdinState } from "./odin-publication.js"; import { startHeimdallPrivateCommandPlane } from "./private-command-plane.js"; import type { CultNetOperationServer } from "cultnet-ts"; import { createHeimdallRuntimePulse, buildHeimdallHealthDetail, publishHeimdallVerseState } from "./verse-state.js"; -import { - buildPresenceStatement, - nextPublisherSequence, - readRuntimeBundleFacts, - type RuntimeBundleFacts, -} from "./runtime-presence.js"; +import { openPresenceAuthority } from "./runtime-presence.js"; 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 versePulseIntervalMs = 60_000; const healthPulseIntervalMs = 10_000; @@ -70,13 +71,6 @@ async function publishVerseState(): Promise { 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 { const pulse = createHeimdallRuntimePulse(config); @@ -94,32 +88,17 @@ async function publishHealthState(): Promise { ? buildHeimdallHealthDetail(config, pulse) : `Heimdall candidate warming; ${lease.reason}`; - if (!config.idunnRuntimeBundlePath) { + if (!presenceAuthority) { // Outside Idunn there is no launch to attest and nothing that admits the // statement; publishing is simply not part of that world. return; } - runtimeBundleFacts ??= await readRuntimeBundleFacts(config.idunnRuntimeBundlePath); - - 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, - }); + const state = lease.mayWrite ? "active" : "warming"; + const presence = presenceAuthority.sign(state, detail, Date.parse(pulse.updatedAt)); await publishIdunnRudpHealth(config, { daemonId: config.daemonId, - state: lease.mayWrite ? "active" : "warming", + state, detail, observedAt: pulse.updatedAt, presence, diff --git a/src/managed-credential.ts b/src/managed-credential.ts new file mode 100644 index 0000000..32e9f51 --- /dev/null +++ b/src/managed-credential.ts @@ -0,0 +1,181 @@ +import { type HeimdallConfig } from "./config.js"; +import { type Provider } from "./contracts.js"; +import { type TokenCustody } from "./custody.js"; +import { type OAuthProviderRuntime, type OAuthRuntimeRegistry, ProviderResponseError } from "./oauth.js"; +import { 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; + +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; +} + +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. + * + * Known residual risk (docs/service-contract.md): one presentation per + * process per burst, so N processes may present one token N times. The + * cross-process failed-refresh marker that would close it is + * joystick:follow_up:cross-process-failed-refresh-marker. + */ +const refreshesInFlight = new WeakMap>>(); + +/** + * 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 { + 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 { + const clock = ctx.clock ?? Date.now; + const provider = snapshot.provider; + const runtime = ctx.oauthRuntimes[provider]; + + let revocation: ManagedCredentialRevocationReason | undefined; + const decide = async (locked: StoredLinkedIdentity): Promise => { + if (!locked.accessTokenEncrypted || !dueForRefresh(locked, runtime, clock())) { + return { kind: "keep" }; + } + const updatedAt = new Date(clock()).toISOString(); + const refreshToken = ctx.tokenCustody.decrypt(locked.refreshTokenEncrypted!); + + let refreshed; + try { + refreshed = await runtime.refreshAccessToken!({ + config: ctx.config, + refreshToken, + signal: AbortSignal.timeout(ctx.timeoutMs ?? MANAGED_CREDENTIAL_REFRESH_TIMEOUT_MS), + }); + } catch (error) { + if (error instanceof ProviderResponseError && error.oauthError === "invalid_grant") { + revocation = "provider_revoked"; + return { kind: "revoke", updatedAt }; + } + throw new ManagedCredentialRefreshFailed(provider); + } + + 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, + }; + }; + + 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 (!committed) { + return { kind: "revoked", identity: withoutTokens(snapshot) }; + } + return { kind: committed.accessTokenEncrypted ? "current" : "revoked", identity: committed }; +} diff --git a/src/oauth.ts b/src/oauth.ts index 564b7b8..b6658e8 100644 --- a/src/oauth.ts +++ b/src/oauth.ts @@ -7,6 +7,7 @@ import { } from "./contracts.js"; import { type HeimdallConfig } from "./config.js"; import { entitlementFacts } from "./facts.js"; +import { providerCatalog } from "./providers.js"; import { type CreateEntitlementSnapshotInput } from "./store/types.js"; export interface OAuthTokenSet { @@ -40,6 +41,9 @@ export interface OAuthCallbackContext { 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 { exchangeAuthorizationCode(options: { config: HeimdallConfig; @@ -49,7 +53,8 @@ export interface OAuthProviderRuntime { refreshAccessToken?(options: { config: HeimdallConfig; refreshToken: string; - }): Promise; + signal?: AbortSignal; + }): Promise; resolveIdentity(options: { config: HeimdallConfig; accessToken: string }): Promise; evaluateEntitlements(options: { config: HeimdallConfig; @@ -59,19 +64,75 @@ export interface OAuthProviderRuntime { }): Promise; } -function buildErrorMessage(status: number, body: string, fallback: string): string { - return `${fallback} (status ${status}): ${body || "empty response"}`; +const oauthErrorCodes = [ + "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(input: string | URL, init: RequestInit, fallbackError: string): Promise { - const response = await fetch(input, init); - const text = await response.text(); +/** + * A provider answer Heimdall cannot use: a non-2xx status, or a body that is + * 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) { - throw new Error(buildErrorMessage(response.status, text, fallbackError)); + constructor(status: number, code: ProviderResponseError["code"], failure: string, oauthError?: OAuthErrorCode) { + 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(response: Response, failure: string): Promise { + 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(input: string | URL, init: RequestInit, failure: string): Promise { + return readProviderJson(await fetch(input, init), failure); } function normalizeScopes(scope: string | string[] | undefined): string[] { @@ -82,512 +143,133 @@ function normalizeScopes(scope: string | string[] | undefined): string[] { return scope?.split(/\s+/).filter(Boolean) ?? []; } -async function exchangeDiscordAuthorizationCode(options: { - config: HeimdallConfig; - code: string; - redirectUri: string; -}): Promise { - const providerConfig = options.config.providers.discord; +export type TokenGrant = + | { grant_type: "authorization_code"; code: string; redirect_uri: string } + | { grant_type: "refresh_token"; refresh_token: string }; + +/** + * 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 { + const descriptor = providerCatalog[provider]; + const providerConfig = config.providers[provider]; 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({ - grant_type: "authorization_code", - code: options.code, - redirect_uri: options.redirectUri, - }); - 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://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 body = new URLSearchParams(grant); + const headers: Record = { + "Content-Type": "application/x-www-form-urlencoded", + Accept: "application/json", + }; + if (descriptor.tokenEndpointAuthMethod === "client_secret_basic") { + headers.Authorization = `Basic ${Buffer.from(`${providerConfig.clientId}:${providerConfig.clientSecret}`).toString("base64")}`; + } else { + body.set("client_id", providerConfig.clientId); + body.set("client_secret", providerConfig.clientSecret); + } - const tokenSet: OAuthTokenSet = { - accessToken: tokenResponse.access_token, - tokenType: tokenResponse.token_type, - scope: normalizeScopes(tokenResponse.scope), - expiresAt: new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString(), - raw: tokenResponse as unknown as Record, + const init: RequestInit = { method: "POST", headers, body }; + if (signal) { + init.signal = signal; + } + const label = grant.grant_type === "refresh_token" ? "refresh" : "exchange"; + const failure = `${descriptor.displayName} token ${label} failed`; + const response = await fetch(descriptor.tokenEndpoint, init); + const answer = await readProviderJson(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, + }; if (tokenResponse.refresh_token) { tokenSet.refreshToken = tokenResponse.refresh_token; } - return tokenSet; } -async function refreshDiscordAccessToken(options: { - config: HeimdallConfig; - refreshToken: string; -}): Promise { - const providerConfig = options.config.providers.discord; - if (!providerConfig.clientId || !providerConfig.clientSecret) { - throw new Error("Discord OAuth is not fully configured."); - } +/** The longest access token lifetime taken at its word: a year. Anything above is not a lifetime. */ +const MAX_USABLE_EXPIRES_IN_SECONDS = 365 * 24 * 60 * 60; - 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://discord.com/api/v10/oauth2/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, - }), - }, - "Discord token refresh failed" - ); +/** + * A positive finite number of seconds, or a string that is a positive integer, + * no longer than a year. A larger value would overflow the Date the expiry is + * stored as, so it is unusable and the descriptor's default lifetime applies. + */ +function usableExpiresIn(value: unknown): number | undefined { + 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 + ? seconds + : undefined; +} - const tokenSet: OAuthTokenSet = { - accessToken: tokenResponse.access_token, - tokenType: tokenResponse.token_type, - scope: normalizeScopes(tokenResponse.scope), - expiresAt: new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString(), - raw: tokenResponse as unknown as Record, +function sharedRuntimeExchange(provider: Provider): OAuthProviderRuntime["exchangeAuthorizationCode"] { + return async (options) => { + const tokenSet = await requestProviderTokens(provider, options.config, { + grant_type: "authorization_code", + code: options.code, + redirect_uri: options.redirectUri, + }); + // 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: { - config: HeimdallConfig; - code: string; - redirectUri: string; -}): Promise { - const providerConfig = options.config.providers.patreon; - if (!providerConfig.clientId || !providerConfig.clientSecret) { - 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, - }; - - 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; +function sharedRuntimeRefresh(provider: Provider): NonNullable { + return (options) => + requestProviderTokens( + provider, + options.config, + { grant_type: "refresh_token", refresh_token: options.refreshToken }, + options.signal + ); } -async function refreshPatreonAccessToken(options: { - config: HeimdallConfig; - refreshToken: string; -}): Promise { - 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, - }; - - 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 { - 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, - }; - - 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 { - 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, - }; - - 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 { - 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, - }; - - 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 { - 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, - }; - - 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 { - 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, - }; - - 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 { - 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, - }; - - 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 { const user = await fetchJson<{ @@ -772,7 +454,7 @@ async function resolveYouTubeIdentity(options: { accessToken: string }): Promise }); if (channelResponse.ok) { - const payload = (await channelResponse.json()) as { + const payload = await readProviderJson<{ items?: Array<{ id: string; snippet?: { @@ -785,7 +467,7 @@ async function resolveYouTubeIdentity(options: { accessToken: string }): Promise }; }; }>; - }; + }>(channelResponse, "YouTube channel lookup failed"); const channel = payload.items?.[0]; if (channel?.id) { @@ -886,6 +568,45 @@ async function resolveSpotifyIdentity(options: { accessToken: string }): Promise return identity; } +async function resolveJoystickIdentity(options: { accessToken: string }): Promise { + 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, + }; + 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: { config: HeimdallConfig; callback: OAuthCallbackContext; @@ -926,16 +647,11 @@ async function evaluateDiscordEntitlements(options: { }; } - const text = await response.text(); - if (!response.ok) { - throw new Error(buildErrorMessage(response.status, text, "Discord guild member lookup failed")); - } - - const member = (text ? JSON.parse(text) : {}) as { + const member = await readProviderJson<{ nick?: string; roles?: string[]; joined_at?: string; - }; + }>(response, "Discord guild member lookup failed"); const roles = member.roles ?? []; const matchedRoles = allowedRoleIds.filter((roleId) => roles.includes(roleId)); const facts: string[] = []; @@ -1198,22 +914,22 @@ async function evaluatePatreonEntitlements(options: { } const discordRuntime: OAuthProviderRuntime = { - exchangeAuthorizationCode: exchangeDiscordAuthorizationCode, - refreshAccessToken: refreshDiscordAccessToken, + exchangeAuthorizationCode: sharedRuntimeExchange("discord"), + refreshAccessToken: sharedRuntimeRefresh("discord"), resolveIdentity: resolveDiscordIdentity, evaluateEntitlements: evaluateDiscordEntitlements, }; const patreonRuntime: OAuthProviderRuntime = { - exchangeAuthorizationCode: exchangePatreonAuthorizationCode, - refreshAccessToken: refreshPatreonAccessToken, + exchangeAuthorizationCode: sharedRuntimeExchange("patreon"), + refreshAccessToken: sharedRuntimeRefresh("patreon"), resolveIdentity: resolvePatreonIdentity, evaluateEntitlements: evaluatePatreonEntitlements, }; const twitchRuntime: OAuthProviderRuntime = { - exchangeAuthorizationCode: exchangeTwitchAuthorizationCode, - refreshAccessToken: refreshTwitchAccessToken, + exchangeAuthorizationCode: sharedRuntimeExchange("twitch"), + refreshAccessToken: sharedRuntimeRefresh("twitch"), resolveIdentity: resolveTwitchIdentity, async evaluateEntitlements() { return { facts: [], snapshots: [] }; @@ -1221,8 +937,8 @@ const twitchRuntime: OAuthProviderRuntime = { }; const youtubeRuntime: OAuthProviderRuntime = { - exchangeAuthorizationCode: exchangeYouTubeAuthorizationCode, - refreshAccessToken: refreshYouTubeAccessToken, + exchangeAuthorizationCode: sharedRuntimeExchange("youtube"), + refreshAccessToken: sharedRuntimeRefresh("youtube"), resolveIdentity: resolveYouTubeIdentity, async evaluateEntitlements() { return { facts: [], snapshots: [] }; @@ -1230,14 +946,23 @@ const youtubeRuntime: OAuthProviderRuntime = { }; const spotifyRuntime: OAuthProviderRuntime = { - exchangeAuthorizationCode: exchangeSpotifyAuthorizationCode, - refreshAccessToken: refreshSpotifyAccessToken, + exchangeAuthorizationCode: sharedRuntimeExchange("spotify"), + refreshAccessToken: sharedRuntimeRefresh("spotify"), resolveIdentity: resolveSpotifyIdentity, async evaluateEntitlements() { return { facts: [], snapshots: [] }; }, }; +const joystickRuntime: OAuthProviderRuntime = { + exchangeAuthorizationCode: sharedRuntimeExchange("joystick"), + refreshAccessToken: sharedRuntimeRefresh("joystick"), + resolveIdentity: resolveJoystickIdentity, + async evaluateEntitlements() { + return { facts: [], snapshots: [] }; + }, +}; + const notImplementedRuntime: OAuthProviderRuntime = { async exchangeAuthorizationCode() { throw new Error("Provider callback exchange is not implemented yet."); @@ -1260,5 +985,6 @@ export function createOAuthRuntimeRegistry(): OAuthRuntimeRegistry { twitch: twitchRuntime, youtube: youtubeRuntime, spotify: spotifyRuntime, + joystick: joystickRuntime, }; } diff --git a/src/private-command-plane.ts b/src/private-command-plane.ts index bfa346b..6d3025b 100644 --- a/src/private-command-plane.ts +++ b/src/private-command-plane.ts @@ -7,7 +7,7 @@ import { type CultNetOperationServer, } from "cultnet-ts"; 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 { getAppProfile } from "./app-profiles.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); } 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 { schemaVersion: "cultnet.operation_response.v0", messageId: request.messageId, @@ -147,7 +153,7 @@ export async function startHeimdallPrivateCommandPlane( payloadSchema: "gamecult.cultnet.operation_failure.v1", payloadEncoding: "messagepack-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, }; } @@ -351,7 +357,6 @@ async function completeAuth( eventPayloadJson: { provider: completion.provider, mode: completion.mode, - completionCode: completion.code, }, createdAt: now, }); diff --git a/src/provider-health-identity.ts b/src/provider-health-identity.ts index 847d39c..ca89f2c 100644 --- a/src/provider-health-identity.ts +++ b/src/provider-health-identity.ts @@ -7,7 +7,7 @@ import { sign, type KeyObject, } from "node:crypto"; -import { readFileSync } from "node:fs"; +import { closeSync, fstatSync, readSync } from "node:fs"; import { chmod, readFile } from "node:fs/promises"; import { SingleFileMessagePackBackingStore, type CultCacheEnvelope } from "@gamecult/cultcache-ts"; import { readPrivateStoreRecord } from "./idunn-store.js"; @@ -71,7 +71,7 @@ export async function openOrEnrollProviderHealthIdentity(path: string): Promise< if (existing.length !== 1) { 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"; @@ -124,19 +124,50 @@ export function passedDescriptor( */ export async function openProviderHealthIdentity( path: string, - env: NodeJS.ProcessEnv = process.env + env: NodeJS.ProcessEnv = process.env, + machineId: () => Promise = readMachineId ): Promise { const descriptor = passedDescriptor(PRESENCE_IDENTITY_FD_NAME, env); 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); } const payload = readPrivateStoreRecord( - readFileSync(descriptor), + readPassedDescriptor(descriptor), "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 { @@ -168,23 +199,58 @@ export function providerHealthPublicIdentity(identity: PrivateIdentity): { 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 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); 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; - if ( - schema !== PRIVATE_SCHEMA || - typeof identityId !== "string" || - !(publicKey instanceof Uint8Array) || publicKey.length !== 32 || - !(protectedSeed instanceof Uint8Array) || protectedSeed.length !== 32 || - protector !== "linux_file_mode_machine_id_binding" || - binding !== protectorBinding(machineId) || - version !== "v1" || - identityId !== deriveIdentityId(publicKey) - ) { - throw new Error("Provider-health identity does not belong to this host or profile."); + const [schema, identityId, publicKeyField, protectedSeedField, protector, binding, version] = value; + if (schema !== PRIVATE_SCHEMA) { + throw new Error("Provider-health identity schema check failed: unexpected schema id."); + } + if (typeof identityId !== "string") { + throw new Error("Provider-health identity id check failed: id is not a string."); + } + const publicKey = keyBytes(publicKeyField, shape, "public key"); + const protectedSeed = keyBytes(protectedSeedField, shape, "protected seed"); + if (protector !== "linux_file_mode_machine_id_binding") { + throw new Error("Provider-health identity protector check failed: unexpected protector."); + } + 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 privateKey = privateKeyFromSeed(seed); diff --git a/src/providers.ts b/src/providers.ts index e5c3775..77eebf4 100644 --- a/src/providers.ts +++ b/src/providers.ts @@ -6,6 +6,17 @@ export interface ProviderDescriptor { key: Provider; displayName: 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[]; roles: ProviderRole[]; clientIdEnv: string; @@ -18,42 +29,62 @@ export const providerCatalog: Record = { key: "discord", displayName: "Discord", 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"], roles: ["identity", "entitlement"], clientIdEnv: "GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID", - clientSecretEnv: "GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET", + clientSecretEnv: "GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET_FILE", }, patreon: { key: "patreon", displayName: "Patreon", 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]"], roles: ["identity", "entitlement"], clientIdEnv: "GC_ACCESS_PROVIDER_PATREON_CLIENT_ID", - clientSecretEnv: "GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET", + clientSecretEnv: "GC_ACCESS_PROVIDER_PATREON_CLIENT_SECRET_FILE", }, github: { key: "github", displayName: "GitHub", 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"], roles: ["identity", "managed_credential"], clientIdEnv: "GC_ACCESS_PROVIDER_GITHUB_CLIENT_ID", - clientSecretEnv: "GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET", + clientSecretEnv: "GC_ACCESS_PROVIDER_GITHUB_CLIENT_SECRET_FILE", }, twitch: { key: "twitch", displayName: "Twitch", 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"], roles: ["identity", "managed_credential"], clientIdEnv: "GC_ACCESS_PROVIDER_TWITCH_CLIENT_ID", - clientSecretEnv: "GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET", + clientSecretEnv: "GC_ACCESS_PROVIDER_TWITCH_CLIENT_SECRET_FILE", }, youtube: { key: "youtube", displayName: "YouTube", 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", @@ -62,7 +93,7 @@ export const providerCatalog: Record = { ], roles: ["identity", "managed_credential"], clientIdEnv: "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_ID", - clientSecretEnv: "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET", + clientSecretEnv: "GC_ACCESS_PROVIDER_YOUTUBE_CLIENT_SECRET_FILE", additionalAuthorizationParams: { access_type: "offline", include_granted_scopes: "true", @@ -73,6 +104,10 @@ export const providerCatalog: Record = { key: "spotify", displayName: "Spotify", authorizationEndpoint: "https://accounts.spotify.com/authorize", + tokenEndpoint: "https://accounts.spotify.com/api/token", + tokenEndpointAuthMethod: "client_secret_basic", + rotatesRefreshTokens: false, + defaultAccessTokenLifetimeSeconds: 3600, defaultScopes: [ "user-read-currently-playing", "user-read-playback-state", @@ -80,7 +115,20 @@ export const providerCatalog: Record = { ], roles: ["identity", "managed_credential"], clientIdEnv: "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID", - clientSecretEnv: "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET", + clientSecretEnv: "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET_FILE", + }, + 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"], + clientIdEnv: "GC_ACCESS_PROVIDER_JOYSTICK_CLIENT_ID", + clientSecretEnv: "GC_ACCESS_PROVIDER_JOYSTICK_CLIENT_SECRET_FILE", }, }; diff --git a/src/runtime-presence.ts b/src/runtime-presence.ts index 8cf0615..3c1054b 100644 --- a/src/runtime-presence.ts +++ b/src/runtime-presence.ts @@ -19,8 +19,6 @@ import path from "node:path"; 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 { @@ -34,11 +32,14 @@ import { type RuntimePresenceState, } from "cultnet-ts"; +import type { HeimdallConfig } from "./config.js"; import { readIdunnStoreRecord } from "./idunn-store.js"; import { openProviderHealthIdentity, passedDescriptor, + readPassedDescriptor, signWithIdentity, + type PrivateIdentity, } from "./provider-health-identity.js"; const PKCS8_ED25519_SEED_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex"); @@ -178,70 +179,37 @@ export async function readRuntimeBundleFacts(bundlePath: string): Promise { - 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; + next(observedAtUnixMillis: number): number { + if (!Number.isSafeInteger(observedAtUnixMillis)) { + throw new Error("observedAtUnixMillis is not a safe integer"); } + 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 { bundle: RuntimeBundleFacts; + identity: PrivateIdentity; + activationKey: KeyObject; state: RuntimePresenceState; detail: string; boundEndpoint: string | null; writeLeaseSha256: string | null; observedAtUnixMillis: number; publisherSequence: number; - providerHealthIdentityPath: string; - env?: NodeJS.ProcessEnv; } 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 * the signed target; Odin refuses the pair when they differ, and that is the * one part of the envelope the transport cannot infer. */ -export async function buildPresenceStatement( - inputs: PresenceStatementInputs, -): Promise { - 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); +export function buildPresenceStatement(inputs: PresenceStatementInputs): PresenceStatement { + const { identity } = inputs; const presence: RuntimePresenceHealth = { target: inputs.bundle.target, @@ -295,7 +253,7 @@ export async function buildPresenceStatement( const proof = runtimePresenceProofPayload(presence); const signature = signWithIdentity(identity, runtimePresenceProviderSigningMessage(proof)); const activationSignature = signWithIdentity( - { ...identity, privateKey: activationKey }, + { ...identity, privateKey: inputs.activationKey }, runtimePresenceActivationSigningMessage(proof), ); @@ -304,3 +262,72 @@ export async function buildPresenceStatement( 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, + env: NodeJS.ProcessEnv = process.env, + machineId?: () => Promise, +): Promise { + 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), + }), + }; +} diff --git a/src/signing.ts b/src/signing.ts index 72a5728..b7d72aa 100644 --- a/src/signing.ts +++ b/src/signing.ts @@ -26,7 +26,7 @@ export interface RuntimeKeyMaterial { privateKey: KeyObject; publicKey: KeyObject; publicJwk: PublicSigningJwk; - source: "configured_pem" | "configured_file" | "bootstrapped_file" | "ephemeral_dev"; + source: "configured_file" | "bootstrapped_file" | "ephemeral_dev"; } function encodeBase64Url(input: string | Buffer): string { @@ -56,8 +56,30 @@ function exportPrivateKeyPem(privateKey: KeyObject): string { 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 { - 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): { @@ -81,12 +103,16 @@ function createOrLoadPrivateKeyFromPath(config: HeimdallConfig): { if (!config.bootstrapSigningPrivateKeyOnMissing) { 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; - mkdirSync(dirname(path), { recursive: true }); + try { + mkdirSync(dirname(path), { recursive: true }); + } catch (error) { + throw signingKeyError("could not be created", error); + } try { writeFileSync(path, exportPrivateKeyPem(privateKey), { encoding: "utf8", @@ -99,7 +125,7 @@ function createOrLoadPrivateKeyFromPath(config: HeimdallConfig): { }; } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") { - throw error; + throw signingKeyError("could not be created", error); } return { @@ -110,12 +136,7 @@ function createOrLoadPrivateKeyFromPath(config: HeimdallConfig): { } export function createRuntimeKeyMaterial(config: HeimdallConfig): RuntimeKeyMaterial { - const loaded = config.signingPrivateKeyPem - ? { - privateKey: createPrivateKey(config.signingPrivateKeyPem), - source: "configured_pem" as const, - } - : createOrLoadPrivateKeyFromPath(config); + const loaded = createOrLoadPrivateKeyFromPath(config); const privateKey = loaded.privateKey; const publicKey = createPublicKey(privateKey); const exportedJwk = publicKey.export({ format: "jwk" }) as Jwk; diff --git a/src/store/in-memory.ts b/src/store/in-memory.ts index 5583ac4..6a53dad 100644 --- a/src/store/in-memory.ts +++ b/src/store/in-memory.ts @@ -6,6 +6,7 @@ import { type CreateAuthCompletionInput, type CreateAuditEventInput, type CreateCapabilityGrantInput, + type CredentialDecision, type CreateEntitlementSnapshotInput, type CreateSessionInput, type CreatePrivateCommandReceiptInput, @@ -37,6 +38,8 @@ function isGrantActive(grant: StoredCapabilityGrant, appSlug: AppSlug, at: strin } 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>(); private readonly accounts = new Map(); private readonly linkedIdentities = new Map(); private readonly grants = new Map(); @@ -174,6 +177,43 @@ export class InMemoryStore implements HeimdallStore { return clone(linkedIdentity); } + async updateLinkedIdentityCredential( + id: string, + decide: (locked: StoredLinkedIdentity) => Promise, + ): Promise { + 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); + } + const next: StoredLinkedIdentity = { ...current, updatedAt: decision.updatedAt }; + 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 { return [...this.linkedIdentities.values()] .filter((identity) => identity.accountId === accountId) diff --git a/src/store/index.ts b/src/store/index.ts index 7617594..69abbe6 100644 --- a/src/store/index.ts +++ b/src/store/index.ts @@ -8,13 +8,37 @@ export { InMemoryStore } from "./in-memory.js"; export { PostgresStore, createPostgresStore } from "./postgres.js"; export async function createStore(config: HeimdallConfig): Promise { - const store = - config.storage.backend === "postgres" - ? createPostgresStore(config.storage.databaseUrl ?? "postgres://127.0.0.1/heimdall") - : new InMemoryStore(); + if (config.storage.backend !== "postgres") { + return new InMemoryStore(); + } - if (config.storage.applySchemaOnStartup) { - await store.ensureSchema(); + const store = createPostgresStore(config.storage.databaseUrl ?? "postgres://127.0.0.1/heimdall"); + 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; diff --git a/src/store/postgres.ts b/src/store/postgres.ts index a9c376f..487f375 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -1,13 +1,14 @@ import { randomUUID } from "node:crypto"; import { Pool, type PoolClient, type QueryResultRow } from "pg"; import { type AppSlug, type HeimdallAuthAttemptStatus, type LinkedIdentityInput, type Provider } from "../contracts.js"; -import { CREATE_SCHEMA_SQL } from "./schema.js"; +import { CREATE_SCHEMA_SQL, REQUIRED_COLUMNS, REQUIRED_KEYS, REQUIRED_TABLES } from "./schema.js"; import { type CreateAccountInput, type CreateAuthAttemptInput, type CreateAuthCompletionInput, type CreateAuditEventInput, type CreateCapabilityGrantInput, + type CredentialDecision, type CreateEntitlementSnapshotInput, type CreateSessionInput, type CreatePrivateCommandReceiptInput, @@ -158,8 +159,8 @@ function mapLinkedIdentityRow(row: LinkedIdentityRow): StoredLinkedIdentity { providerUserId: row.provider_user_id, scopes: parseScopes(row.scopes), profileJson: row.profile_json, - createdAt: row.created_at, - updatedAt: row.updated_at, + createdAt: new Date(row.created_at).toISOString(), + updatedAt: new Date(row.updated_at).toISOString(), }; if (row.username) { @@ -183,7 +184,8 @@ function mapLinkedIdentityRow(row: LinkedIdentityRow): StoredLinkedIdentity { } 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(); } return identity; @@ -284,13 +286,279 @@ function mapAuthAttemptRow(row: AuthAttemptRow): StoredAuthAttempt { return attempt; } +/** + * The AND-ed conditions of a predicate as Postgres prints it, each without a + * pair of parentheses that encloses all of it. Postgres flattens a chain of + * ANDs into one list, so `((a) AND (b) AND (c))` yields `a`, `b`, `c`. An OR, + * or an AND nested under one, stays whole: `((a OR b) AND c)` yields `a OR b` + * and `c`, and `(a OR (b AND c))` yields itself. Quoted text is never split. + */ +export function predicateConditions(printed: string): string[] { + const unwrap = (text: string): string => { + let current = text.trim(); + while (current.startsWith("(") && closingParenthesis(current, 0) === current.length - 1) { + current = current.slice(1, -1).trim(); + } + return current; + }; + const whole = unwrap(printed); + if (whole === "") return []; + const parts: string[] = []; + let depth = 0; + let quote: string | undefined; + let start = 0; + for (let position = 0; position < whole.length; position += 1) { + const character = whole[position]!; + if (quote) { + if (character === quote) quote = undefined; + } else if (character === "'" || character === '"') { + quote = character; + } else if (character === "(") { + depth += 1; + } else if (character === ")") { + depth -= 1; + } else if (depth === 0 && whole.startsWith(" AND ", position)) { + parts.push(whole.slice(start, position)); + start = position + " AND ".length; + position = start - 1; + } + } + parts.push(whole.slice(start)); + return parts.map(unwrap); +} + +/** The index of the parenthesis closing the one at `open`, outside quoted text, or -1. */ +function closingParenthesis(text: string, open: number): number { + let depth = 0; + let quote: string | undefined; + for (let position = open; position < text.length; position += 1) { + const character = text[position]!; + if (quote) { + if (character === quote) quote = undefined; + } else if (character === "'" || character === '"') { + quote = character; + } else if (character === "(") { + depth += 1; + } else if (character === ")") { + depth -= 1; + if (depth === 0) return position; + } + } + return -1; +} + +/** + * Whether an index predicate, as Postgres prints it, keeps exactly the rows + * the declared one (printed the same way) does: the same set of AND-ed + * conditions, ignoring `key_column IS NOT NULL` unless the index treats NULLs + * as equal, since otherwise rows with a NULL key never collide anyway. + */ +export function samePredicate(declared: string, actual: string, keyColumns: string[], nullsNotDistinct: boolean): boolean { + // A key without a predicate must have none: ON CONFLICT cannot infer a + // partial index as its arbiter. + if (predicateConditions(declared).length === 0) return actual.trim() === ""; + const redundant = new Set(nullsNotDistinct ? [] : keyColumns.map((column) => `${column} IS NOT NULL`)); + const conditions = (printed: string) => + [...new Set(predicateConditions(printed).filter((condition) => !redundant.has(condition)))].sort(); + const left = conditions(declared); + const right = conditions(actual); + return left.length === right.length && left.every((condition, index) => condition === right[index]); +} + +/** + * What the store's statements do to each table, and so the privileges its + * database role needs: it reads what it returns or looks up, inserts what it + * creates, updates what it changes or upserts, and deletes nothing. + * audit_events is written and never read back. + */ +export const STORE_TABLE_PRIVILEGES: Readonly> = { + accounts: ["SELECT", "INSERT", "UPDATE"], + linked_identities: ["SELECT", "INSERT", "UPDATE"], + sessions: ["SELECT", "INSERT", "UPDATE"], + auth_attempts: ["SELECT", "INSERT", "UPDATE"], + private_command_receipts: ["SELECT", "INSERT"], + auth_completions: ["SELECT", "INSERT", "UPDATE"], + capability_grants: ["SELECT", "INSERT"], + entitlement_snapshots: ["SELECT", "INSERT", "UPDATE"], + audit_events: ["INSERT"], +}; + +/** What a database must hold for a store to serve it; see checkSchemaRequirements. */ +export interface SchemaRequirements { + tables: readonly string[]; + columns: readonly { table: string; column: string; type: string; nullable: boolean }[]; + keys: readonly { table: string; columns: string; predicate: string }[]; + privileges: Readonly>; +} + +/** What Heimdall's store needs, read from its schema and its statements. */ +export const HEIMDALL_SCHEMA_REQUIREMENTS: SchemaRequirements = { + tables: REQUIRED_TABLES, + columns: REQUIRED_COLUMNS, + keys: REQUIRED_KEYS, + privileges: STORE_TABLE_PRIVILEGES, +}; + +/** + * Each required key's predicate as Postgres prints it back (empty for none). + * One simple-protocol round trip on one connection: a transaction that builds + * a temporary copy of each keyed table's declared columns, indexes it with the + * declared predicate, reads the printed form and rolls back. The names and SQL + * come from the requirements, which are constants, never input. A role that + * may not create temporary tables fails with code SCHEMA_TEMP_PRIVILEGE. + */ +export async function printedDeclaredPredicates(pool: Pick, requirements: SchemaRequirements): Promise { + const partial = requirements.keys.flatMap((required, index) => (required.predicate ? [{ ...required, index }] : [])); + if (partial.length === 0) return requirements.keys.map(() => ""); + const statements = partial.flatMap(({ table, columns, predicate, index }) => { + const probe = `heimdall_key_probe_${index}`; + const declared = requirements.columns + .filter((column) => column.table === table) + .map((column) => `${column.column} ${column.type}`) + .join(", "); + return [ + `CREATE TEMP TABLE ${probe} (${declared}) ON COMMIT DROP`, + `CREATE UNIQUE INDEX ${probe}_idx ON ${probe} (${columns}) WHERE ${predicate}`, + ]; + }); + const select = partial + .map(({ index }) => `SELECT ${index} AS key, pg_get_expr(indpred, indrelid) AS predicate FROM pg_index WHERE indexrelid = 'pg_temp.heimdall_key_probe_${index}_idx'::regclass`) + .join(" UNION ALL "); + let results: Array<{ rows: Array<{ key: number; predicate: string }> }>; + try { + results = (await pool.query(["BEGIN", ...statements, select, "ROLLBACK"].join(";\n"))) as unknown as typeof results; + } catch (error) { + if ((error as { code?: unknown }).code === "42501") { + throw Object.assign(new Error("The Heimdall database role may not create temporary tables."), { code: "SCHEMA_TEMP_PRIVILEGE" }); + } + throw error; + } + const printed = results[results.length - 2]!.rows; + return requirements.keys.map((_, index) => printed.find((row) => row.key === index)?.predicate ?? ""); +} + +/** + * Proves that the database can take a store's requests: every required + * table; every column with its declared type, under a deterministic + * collation, and nullable where declared nullable; every unique key; and + * every privilege, held on the table or on each of its columns. A missing or + * altered piece fails with code SCHEMA_MISSING and a missing privilege with + * SCHEMA_PRIVILEGES; neither error names the piece. + * + * A key is met by a unique index on its table that is valid (a failed + * CREATE INDEX CONCURRENTLY or an interrupted DROP INDEX CONCURRENTLY leaves + * one that is not; Postgres never marks an index valid before it is ready), + * immediate (ON CONFLICT refuses a deferrable arbiter), has exactly the key's + * columns as its key columns (INCLUDE columns aside), compares them under + * deterministic collations (a case-insensitive one would merge two + * providers' user ids into one row), and has the key's predicate. A + * predicate matches when both, as Postgres prints them, are the same set of + * AND-ed conditions; a `key_column IS NOT NULL` condition may be absent on + * either side, because a unique index never makes NULL keys collide unless + * it is NULLS NOT DISTINCT. Postgres prints the declared predicates itself + * (printedDeclaredPredicates). + * + * What this does not prove is listed where the schema is: see schema.ts. + */ +export async function checkSchemaRequirements(pool: Pick, requirements: SchemaRequirements): Promise { + const declaredPredicates = await printedDeclaredPredicates(pool, requirements); + const privileges = Object.entries(requirements.privileges).flatMap(([table, wanted]) => + wanted.map((privilege) => ({ table, privilege })) + ); + const result = await pool.query<{ + kind: "missing" | "privilege" | "candidate"; + key: number | null; + predicate: string | null; + nulls_not_distinct: boolean | null; + }>( + ` + SELECT 'missing' AS kind, NULL::int AS key, NULL::text AS predicate, NULL::boolean AS nulls_not_distinct + FROM unnest($1::text[]) AS name WHERE to_regclass(name) IS NULL + UNION ALL + SELECT 'missing', NULL, NULL, NULL + FROM unnest($2::text[], $3::text[], $4::text[], $5::boolean[]) AS required(table_name, column_name, type_name, nullable) + WHERE NOT EXISTS ( + SELECT 1 FROM pg_attribute a + WHERE a.attrelid = to_regclass(required.table_name) + AND a.attname = required.column_name + AND a.attnum > 0 + AND NOT a.attisdropped + AND a.atttypid = to_regtype(required.type_name) + AND (NOT required.nullable OR NOT a.attnotnull) + AND NOT EXISTS (SELECT 1 FROM pg_collation c WHERE c.oid = a.attcollation AND NOT c.collisdeterministic) + ) + UNION ALL + SELECT 'candidate', required.key::int, pg_get_expr(i.indpred, i.indrelid), + coalesce((to_jsonb(i) ->> 'indnullsnotdistinct')::boolean, false) + FROM unnest($6::text[], $7::text[]) WITH ORDINALITY AS required(table_name, columns, key) + JOIN pg_index i ON i.indrelid = to_regclass(required.table_name) + WHERE i.indisunique + AND i.indisvalid + AND i.indimmediate + AND i.indnkeyatts = cardinality(string_to_array(required.columns, ',')) + AND ( + SELECT string_agg(a.attname, ',' ORDER BY a.attname) + FROM unnest(i.indkey::int2[]) WITH ORDINALITY AS key(attnum, position) + JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = key.attnum + WHERE key.position <= i.indnkeyatts + ) = required.columns + AND NOT EXISTS ( + SELECT 1 FROM unnest(i.indcollation::oid[]) WITH ORDINALITY AS key_collation(oid, position) + JOIN pg_collation c ON c.oid = key_collation.oid + WHERE key_collation.position <= i.indnkeyatts AND NOT c.collisdeterministic + ) + UNION ALL + SELECT 'privilege', NULL, NULL, NULL + FROM unnest($8::text[], $9::text[]) AS required(table_name, privilege) + WHERE EXISTS ( + SELECT 1 FROM unnest($2::text[], $3::text[]) AS used(table_name, column_name) + JOIN pg_attribute a ON a.attrelid = to_regclass(used.table_name) AND a.attname = used.column_name AND NOT a.attisdropped + WHERE used.table_name = required.table_name + AND NOT has_column_privilege(a.attrelid, a.attnum, required.privilege) + ) + `, + [ + requirements.tables, + requirements.columns.map((required) => required.table), + requirements.columns.map((required) => required.column), + requirements.columns.map((required) => required.type), + requirements.columns.map((required) => required.nullable), + requirements.keys.map((required) => required.table), + requirements.keys.map((required) => required.columns), + privileges.map((required) => required.table), + privileges.map((required) => required.privilege), + ] + ); + const keyMet = requirements.keys.map((required, index) => + result.rows.some( + (row) => + row.kind === "candidate" && + row.key === index + 1 && + samePredicate(declaredPredicates[index]!, row.predicate ?? "", required.columns.split(","), row.nulls_not_distinct === true) + ) + ); + if (result.rows.some((row) => row.kind === "missing") || keyMet.includes(false)) { + throw Object.assign(new Error("The Heimdall schema is not applied."), { code: "SCHEMA_MISSING" }); + } + if (result.rows.some((row) => row.kind === "privilege")) { + throw Object.assign(new Error("The Heimdall database role lacks a privilege the store needs."), { + code: "SCHEMA_PRIVILEGES", + }); + } +} + export class PostgresStore implements HeimdallStore { - constructor(private readonly pool: Pick) {} + constructor(private readonly pool: Pick) {} async ensureSchema(): Promise { await this.pool.query(CREATE_SCHEMA_SQL); } + /** Proves, before Heimdall serves, that the database can take its requests (checkSchemaRequirements). */ + async checkSchema(): Promise { + await checkSchemaRequirements(this.pool, HEIMDALL_SCHEMA_REQUIREMENTS); + } + async close(): Promise { await this.pool.end(); } @@ -456,6 +724,60 @@ export class PostgresStore implements HeimdallStore { return mapLinkedIdentityRow(expectRow(result.rows[0], "upsertLinkedIdentity")); } + async updateLinkedIdentityCredential( + id: string, + decide: (locked: StoredLinkedIdentity) => Promise, + ): Promise { + const client = await this.pool.connect(); + try { + await client.query("BEGIN"); + try { + const locked = await client.query( + "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")); + const decision = await decide(row); + let committed = row; + if (decision.kind !== "keep") { + const rotated = decision.kind === "rotate" ? decision : undefined; + const written = await client.query( + ` + UPDATE linked_identities + SET access_token_encrypted = $2, + refresh_token_encrypted = $3, + token_expires_at = $4, + 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"); + throw error; + } + } finally { + client.release(); + } + } + async listLinkedIdentitiesForAccount(accountId: string): Promise { const result = await this.pool.query( ` @@ -791,9 +1113,21 @@ export class PostgresStore implements HeimdallStore { } } -export function createPostgresStore(databaseUrl: string): HeimdallStore { +export function createPostgresStore(databaseUrl: string): PostgresStore { const pool = new Pool({ 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); } diff --git a/src/store/schema.ts b/src/store/schema.ts index 17ddc49..420f5e6 100644 --- a/src/store/schema.ts +++ b/src/store/schema.ts @@ -162,3 +162,86 @@ CREATE TABLE IF NOT EXISTS audit_events ( CREATE INDEX IF NOT EXISTS audit_events_lookup_idx ON audit_events(account_id, session_id, app_slug, created_at); `; + +const schemaText = CREATE_SCHEMA_SQL.replace(/\r\n/g, "\n"); +const createdTables = [...schemaText.matchAll(/^CREATE TABLE IF NOT EXISTS (\w+) \(\n([\s\S]*?)\n\);/gm)].map((match) => ({ + table: match[1]!, + lines: match[2]!.split("\n").map((line) => line.trim().replace(/,$/, "")), +})); + +/** Sorted and comma-separated, the form the schema check compares key columns in. */ +function columnList(text: string): string { + return text.split(",").map((column) => column.trim()).sort().join(","); +} + +/** The columns of a `PRIMARY KEY (a, b)` or `UNIQUE(a, b)` line, as a column list. */ +function keyColumns(line: string, keyword: "PRIMARY KEY" | "UNIQUE"): string | undefined { + const match = new RegExp(`^${keyword}\\s*\\(([^)]*)\\)`).exec(line); + return match ? columnList(match[1]!) : undefined; +} + +/* + * What every start must find before it serves, read from the SQL above so the + * two cannot drift. A start that applies the schema checks as well, because + * CREATE ... IF NOT EXISTS leaves a damaged table as it is. Indexes that only + * speed lookups are not required; the unique ones are, by shape, in + * REQUIRED_KEYS. + * + * Out of scope, each able to make a write fail on a database that passes the + * check: CHECK constraints; triggers; row-level security; unique indexes + * beyond the required keys, or stricter than them, including the leftovers of + * an interrupted concurrent index build (a valid extra one refuses rows the + * store expects to write, and even an invalid one that is ready is enforced + * on writes); NOT NULL columns the schema does not declare and that have no + * default, which the store's INSERTs leave out; and SELECT granted column by + * column when a statement reads `SELECT *` or `RETURNING *`, which needs + * SELECT on every column the table has, not only the declared ones. + */ + +/** Every table the schema creates. */ +export const REQUIRED_TABLES = createdTables.map(({ table }) => table); + +/** + * Every column a created table declares and every column the schema adds to + * an existing table, each with its declared type, and whether it is nullable: + * the store reads and writes values as that type, and leaves a nullable + * column null, so a column retyped or made NOT NULL under it fails its writes. + */ +export const REQUIRED_COLUMNS = [ + ...createdTables.flatMap(({ table, lines }) => + lines + .filter((line) => !/^(?:PRIMARY KEY|UNIQUE)\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(), + })), +]; diff --git a/src/store/types.ts b/src/store/types.ts index d1fabcf..5307e1f 100644 --- a/src/store/types.ts +++ b/src/store/types.ts @@ -56,6 +56,23 @@ export interface UpsertLinkedIdentityInput { updatedAt: string; } +/** + * What the owner of a refresh decides after reading the row under its lock. + * `rotate` and `revoke` write token columns, scopes and updated_at only; they + * never touch account, profile or identity fields. + */ +export type CredentialDecision = + | { kind: "keep" } + | { + kind: "rotate"; + accessTokenEncrypted: string; + refreshTokenEncrypted: string; + tokenExpiresAt: string; + scopes: string[]; + updatedAt: string; + } + | { kind: "revoke"; updatedAt: string }; + export interface StoredSession { id: string; accountId: string; @@ -213,6 +230,17 @@ export interface HeimdallStore { findStoredLinkedIdentityForAccount(accountId: string, provider: Provider): Promise; listStoredLinkedIdentitiesForAccount(accountId: string): Promise; upsertLinkedIdentity(input: UpsertLinkedIdentityInput): Promise; + /** + * Serialise decisions about one row's credential. `decide` receives the row + * as read under the lock (never a caller's snapshot) and the decision is + * 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, + ): Promise; listLinkedIdentitiesForAccount(accountId: string): Promise; createCapabilityGrant(input: CreateCapabilityGrantInput): Promise; listActiveGrants(accountId: string, appSlug: AppSlug, at: string): Promise; diff --git a/state/branches.json b/state/branches.json index ea9d340..32cd28f 100644 --- a/state/branches.json +++ b/state/branches.json @@ -12,6 +12,15 @@ "docs/implementation-plan.md" ], "notes": "Current mainline. Repixelizer is the first auth-blank binding target; StreamPixels is the migration and boundary stress test." + }, + { + "id": "eureka/joystick-h1", + "hypothesis": "One locked refresh primitive plus a Joystick OAuth provider in Heimdall lets StreamPixels ingest Joystick without ever presenting a provider refresh token.", + "status": "accepted", + "artifacts": [ + "state/map.yaml" + ], + "notes": "Merged as PR GameCult/Heimdall#1 (d51fa6b), deployed to Yggdrasil 2026-10-19 15:51Z; gamecult-ops 210a1af. Campaign joystick:campaign:self." } ] } diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 3178947..5329d5f 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -35,3 +35,5 @@ {"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-08T12:20:12+00:00", "type": "security", "status": "accepted", "note": "epiphany/heimdall-caller-identity, second Hands pass: closed the two Soul-proven holes. (1) auth-completions redeem code is now always store-minted (never handoff.attemptId); attemptId survives only as a separate correlation field on StoredAuthCompletion/CreateAuthCompletionInput, and a new store.consumeAuthCompletionByAttempt(appSlug, attemptId, at) lets the private command plane's completeAuth redeem by the handle it already owns instead of forging an HTTP self-call with completionCode=handle. (2) startOAuthFlow now refuses any returnTo whose origin is not in AppProfile.allowedReturnOrigins (repixelizer/streampixels/bifrost -> .gamecult.org, ghostlight -> yggdrasil.gamecult.org per its docs/app-profiles doc and existing test fixtures; a registered app's allowlist is derived from its stored redirectUris origins). AppCaller is now branded with an unexported Symbol (app-caller.ts); private-command-plane.ts's two { appSlug } literals are gone, replaced by app-caller.ts's callerFromOpenedEnvelope. Deleted: validateAppRegistration, AppRegistrationRequest, RegistrationProblem, AppRegistrationError, HeimdallStore.registerApp (writer). Kept: findRegisteredApp/listRegisteredApps/resolveAppProfile fallback -- AppSlug is a plain string (contracts.ts), registered_apps is a real extension point for a slug Heimdall was never rebuilt for, and isBuiltInApp's only production call site (listAppProfiles) depends on that fallback existing; a row is now provisioned by direct SQL (or InMemoryStore.seedRegisteredApp in tests), not by any app-facing writer. Deleted the two appSlug===\"ghostlight\" branches in private-command-plane.ts; the requirement is now AppProfile.requiredEntitlementPolicyKind, checked generically through resolveAppProfile. tsc --noEmit clean; vitest 94 passed/1 pre-existing-skip, only pre-existing failure is tests/odin-publication.test.ts (Cannot find module 'cultcache-ts', present on main too).", "branch": "epiphany/heimdall-caller-identity"} +{"ts": "2026-10-19T15:56:24+00:00", "type": "design", "status": "accepted", "note": "Refresh is now one locked primitive for every provider (replaces unserialized refreshLinkedIdentityCredentialIfNeeded); Joystick is managed-only (Heimdall-held credential, no viewer sign-in until joystick:follow_up:joystick-viewer-signin-public-bot). Merged in PR #1, live at d51fa6b; campaign joystick:campaign:self.", "branch": "eureka/joystick-h1"} +{"ts": "2026-10-19T16:03:16+00:00", "type": "verification", "status": "accepted", "note": "Live d51fa6b (H1) verified by a real human sign-in: the operator's StreamPixels Twitch sign-in through Heimdall start/callback, 2026-10-19 ('Twitch auth worked fine'); a streampixels session was created 16:02:33Z, after the 15:51Z switch. Joystick consent round trip still open: joystick:follow_up:h1-joystick-consent-round-trip."} diff --git a/state/map.yaml b/state/map.yaml index 71e57dc..4aa4d5a 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -59,13 +59,14 @@ data_flow: - reject per-request auth round-trip chatter 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. - Preserve the default boundary that app-domain data remains app-owned. - Align the plan to Heimdall as a Yggdrasil-hosted authority service. - Publish Heimdall daemon health and boundary state for Idunn/Odin without moving auth truth out of Heimdall. - Verify the Discord and Patreon Repixelizer auth paths with real provider credentials, stable signing, persistent storage, and live browser callback verification. - - Wire StreamPixels through Heimdall for Twitch/YouTube 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: - `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: - 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. - 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. @@ -125,5 +126,5 @@ rejected_paths: reason: reusing auth mechanics does not justify centralizing app-domain audience or product data 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. - 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. + summary: Yggdrasil runs Heimdall release d51fa6b (hand-deployed 2026-10-19 15:51Z, gamecult-ops 210a1af), which includes Joystick H1 (PR #1). The plugin and encrypted loopback begin, complete, refresh and logout plane, the Odin discovery records and Ghostlight resolution were verified at 1086aee (2026-08-22) and are not re-verified at d51fa6b. + next_action: Run joystick:follow_up:h1-joystick-consent-round-trip, then StreamPixels S0/S1 (other sessions). Still open behind that: separate-account KLTST completion, refresh, logout, privacy, and stale-attempt canaries through the deployed Ghostlight Eve host; keep provider credential rotation on the operator list because prior tool output exposed OAuth secrets. diff --git a/tests/access-plugin.test.ts b/tests/access-plugin.test.ts index b5027d0..4789bf8 100644 --- a/tests/access-plugin.test.ts +++ b/tests/access-plugin.test.ts @@ -291,7 +291,7 @@ function testConfig(): HeimdallConfig { storage: { backend: "memory", applySchemaOnStartup: true }, providers: { discord: { clientId: "discord-client", clientSecret: "discord-secret" }, - patreon: {}, github: {}, twitch: {}, youtube: {}, spotify: {}, + patreon: {}, github: {}, twitch: {}, youtube: {}, spotify: {}, joystick: {}, }, }; } diff --git a/tests/app.test.ts b/tests/app.test.ts index 1b200f0..7f4d96d 100644 --- a/tests/app.test.ts +++ b/tests/app.test.ts @@ -1,10 +1,16 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { inspect } from "node:util"; import { afterEach, describe, expect, it } from "vitest"; import { type FastifyInstance } from "fastify"; -import { buildApp } from "../src/app.js"; +import { buildApp, errorIdentity } from "../src/app.js"; +import { builtInAppProfiles, callbackMint } from "../src/app-profiles.js"; +import { deliverBackendHandoff, type BackendHandoffPayload } from "../src/backend-handoff.js"; import { type HeimdallConfig, loadConfig } from "../src/config.js"; import { entitlementFacts, identityFacts } from "../src/facts.js"; -import { createOAuthRuntimeRegistry, type OAuthProviderRuntime } from "../src/oauth.js"; -import { verifyJwt } from "../src/signing.js"; +import { createOAuthRuntimeRegistry, ProviderResponseError, type OAuthProviderRuntime } from "../src/oauth.js"; +import { createRuntimeKeyMaterial, signJwt, verifyJwt } from "../src/signing.js"; import { InMemoryStore } from "../src/store/index.js"; function createTestConfig(): HeimdallConfig { @@ -47,6 +53,7 @@ function createTestConfig(): HeimdallConfig { 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" }, }, }; } @@ -517,7 +524,7 @@ describe("Heimdall service", () => { } }); - it("syncs a linked Patreon membership into a signed Bifrost support fact", async () => { + async function syncPatronSupport(bifrostAnswer: () => Response) { const baseConfig = createTestConfig(); const config = { ...baseConfig, @@ -588,7 +595,7 @@ describe("Heimdall service", () => { bifrostBody = String(init?.body ?? ""); const headers = init?.headers as Record; bifrostSignature = headers["x-heimdall-signature-256"] ?? ""; - return new Response("processed", { status: 200 }); + return bifrostAnswer(); } return new Response("unexpected request", { status: 500 }); @@ -607,6 +614,15 @@ describe("Heimdall service", () => { }, }); + const auditEvents = [...(store as unknown as { auditEvents: Map }).auditEvents.values()]; + return { response, auditEvents, bifrostBody, bifrostSignature, now }; + } + + it("syncs a linked Patreon membership into a signed Bifrost support fact", async () => { + const { response, auditEvents, bifrostBody, bifrostSignature, now } = await syncPatronSupport( + () => new Response("CANARYbifrost processed", { status: 200 }) + ); + expect(response.statusCode, response.body).toBe(200); expect(bifrostSignature).toMatch(/^sha256=[0-9a-f]{64}$/); expect(JSON.parse(bifrostBody)).toEqual({ @@ -623,12 +639,45 @@ describe("Heimdall service", () => { providerSubscriptionId: "member-789", notes: "Verified active Patreon membership for tier Inner Sanctum.", }); - expect(response.json()).toEqual( - expect.objectContaining({ - status: "synced", - bifrostResponse: "processed", - }) + // Exactly these fields: no part of Bifrost's body rides along. + expect(response.json()).toEqual({ status: "synced", supportFact: JSON.parse(bifrostBody), bifrostStatus: 200 }); + expect(auditEvents.map((event) => [event.eventType, event.eventPayloadJson])).toEqual([ + [ + "bifrost_patron_support_synced", + { + provider: "patreon", + requiredTierTitle: "Inner Sanctum", + providerEventId: "patreon-membership-snapshot:patreon-user-456:member-789:2026-06-09:1500", + bifrostStatus: 200, + }, + ], + ]); + expect(response.body + JSON.stringify(auditEvents)).not.toContain("CANARY"); + }); + + it("answers a Bifrost refusal with fixed text and its status, never its body", async () => { + const { response, auditEvents } = await syncPatronSupport( + () => new Response('CANARYrefusal {"error":"bad signature"}', { status: 403 }) ); + + expect(response.statusCode).toBe(502); + expect(response.json()).toEqual({ + error: "bifrost_patron_support_rejected", + statusCode: 403, + detail: "Bifrost refused the patron support fact.", + }); + expect(auditEvents.map((event) => [event.eventType, event.eventPayloadJson])).toEqual([ + [ + "bifrost_patron_support_sync_failed", + { + provider: "patreon", + requiredTierTitle: "Inner Sanctum", + providerEventId: "patreon-membership-snapshot:patreon-user-456:member-789:2026-06-09:1500", + bifrostStatus: 403, + }, + ], + ]); + expect(response.body + JSON.stringify(auditEvents)).not.toContain("CANARY"); }); it("redeems a completion code exactly once", async () => { @@ -675,6 +724,33 @@ describe("Heimdall service", () => { expect(secondRedeemResponse.statusCode).toBe(410); }); + it("keeps the completion code out of the audit trail, live or redeemed", async () => { + const store = new InMemoryStore(); + const app = await buildApp({ config: createTestConfig(), store, oauthRuntimes: { discord: createMockDiscordRuntime() } }); + apps.push(app); + const auditEvents = () => + [...(store as unknown as { auditEvents: Map }).auditEvents.values()]; + + const stateToken = await startDiscordSignIn(app); + const callback = await app.inject({ + method: "GET", + url: `/v1/oauth/discord/callback?code=test-code&state=${encodeURIComponent(stateToken)}`, + }); + const { code, expiresAt } = callback.json().completion as { code: string; expiresAt: string }; + const created = auditEvents().filter((event) => event.eventType === "auth_completion_created"); + expect(created.map((event) => event.eventPayloadJson)).toEqual([{ provider: "discord", mode: "sign_in", expiresAt }]); + expect(created[0]!.sessionId).toEqual(expect.any(String)); + // While the code is live, the audit trail must not be a way to redeem it. + expect(JSON.stringify(auditEvents())).not.toContain(code); + + const redeem = await app.inject({ method: "POST", url: "/v1/apps/repixelizer/auth-completions/redeem", payload: { completionCode: code } }); + expect(redeem.statusCode).toBe(201); + const redeemed = auditEvents().filter((event) => event.eventType === "auth_completion_redeemed"); + expect(redeemed.map((event) => event.eventPayloadJson)).toEqual([{ provider: "discord", mode: "sign_in" }]); + expect(redeemed[0]!.sessionId).toBe(created[0]!.sessionId); + expect(JSON.stringify(auditEvents())).not.toContain(code); + }); + it("refreshes a Repixelizer app claim from a Heimdall refresh token without provider OAuth", async () => { const store = new InMemoryStore(); let exchangeCalls = 0; @@ -903,7 +979,8 @@ describe("Heimdall service", () => { expect(profileResponse.json()).toEqual( expect.objectContaining({ slug: "streampixels", - managedConnectionProviders: ["twitch", "youtube"], + identityProviders: ["twitch", "youtube"], + managedConnectionProviders: ["twitch", "youtube", "joystick"], }) ); }); @@ -1167,6 +1244,361 @@ describe("Heimdall service", () => { expect(credentialResponse.body).not.toContain("rotated-twitch-refresh-token"); }); + it("revocation-is-typed: a revoked identity contributes no entitlement at session refresh", async () => { + const store = new InMemoryStore(); + let evaluations = 0; + const base = createMockDiscordRuntime(); + const app = await buildApp({ + config: createTestConfig(), + store, + oauthRuntimes: { + discord: { + ...base, + async exchangeAuthorizationCode() { + return { + accessToken: "expired-discord-access-token", + refreshToken: "discord-refresh-token", + tokenType: "Bearer", + scope: ["identify"], + expiresAt: "2026-04-26T13:00:00.000Z", + raw: {}, + }; + }, + async refreshAccessToken() { + throw new ProviderResponseError(400, "provider_status", "Discord token refresh failed", "invalid_grant"); + }, + async evaluateEntitlements(options) { + evaluations += 1; + return base.evaluateEntitlements(options); + }, + }, + }, + }); + apps.push(app); + + const stateToken = await startDiscordSignIn(app); + const callbackResponse = await app.inject({ + method: "GET", + url: `/v1/oauth/discord/callback?code=test-code&state=${encodeURIComponent(stateToken)}`, + }); + expect(callbackResponse.statusCode).toBe(201); + const evaluationsAtSignIn = evaluations; + + const refreshResponse = await app.inject({ + method: "POST", + url: "/v1/apps/repixelizer/sessions/refresh", + headers: { "x-heimdall-app-secret": "repixelizer-secret" }, + payload: { + refreshToken: callbackResponse.json().refreshToken as string, + entitlementPolicies: [{ kind: "discord_role_access", guildId: "gamecult-guild", allowedRoleIds: ["role-repixelizer"] }], + }, + }); + + expect(refreshResponse.statusCode).toBe(201); + expect(evaluations).toBe(evaluationsAtSignIn); + const accountId = callbackResponse.json().account.id as string; + const row = await store.findStoredLinkedIdentityForAccount(accountId, "discord"); + expect(row?.accessTokenEncrypted).toBeUndefined(); + expect(row?.refreshTokenEncrypted).toBeUndefined(); + }); + + it("revocation-is-typed: a revoked Patreon identity is not linked for Bifrost sync and Bifrost is not called", async () => { + const baseConfig = createTestConfig(); + const store = new InMemoryStore(); + const app = await buildApp({ + config: { + ...baseConfig, + bifrostPatronSupportEndpoint: "https://bifrost.gamecult.org/heimdall/patron-support/events", + bifrostPatronSupportSecret: "bifrost-support-secret", + }, + store, + oauthRuntimes: { + patreon: { + ...createOAuthRuntimeRegistry().patreon, + async refreshAccessToken() { + throw new ProviderResponseError(400, "provider_status", "Patreon token refresh failed", "invalid_grant"); + }, + }, + }, + }); + apps.push(app); + const context = getHeimdallContext(app); + const now = "2026-06-09T17:00:00.000Z"; + await store.createAccount({ id: "acct-p", createdAt: now, lastSeenAt: now }); + await store.upsertLinkedIdentity({ + accountId: "acct-p", + provider: "patreon", + providerUserId: "patreon-user-456", + accessTokenEncrypted: context.tokenCustody.encrypt("patreon-access-token"), + refreshTokenEncrypted: context.tokenCustody.encrypt("patreon-refresh-token"), + tokenExpiresAt: "2026-06-09T17:01:00.000Z", + scopes: [], + profileJson: {}, + createdAt: now, + updatedAt: now, + }); + const urls: string[] = []; + globalThis.fetch = async (input) => { + urls.push(String(input)); + return new Response("unexpected", { status: 500 }); + }; + + const response = await app.inject({ + method: "POST", + url: "/v1/apps/bifrost/patron-support/sync", + headers: { "x-heimdall-app-secret": "bifrost-secret" }, + payload: { accountId: "acct-p", requiredTierTitle: "Inner Sanctum", supportedAtUtc: now }, + }); + + expect(response.statusCode).toBe(404); + expect(response.json()).toEqual({ error: "patreon_identity_not_linked" }); + expect(urls).toEqual([]); + }); + + describe("joystick connect", () => { + const creator = { kind: "creator", targetId: "creator-1" }; + async function connect(app: FastifyInstance, extra: Record = { connection: creator }) { + const start = await app.inject({ + method: "POST", + url: "/v1/oauth/joystick/start", + payload: { appSlug: "streampixels", mode: "connect", returnTo: "https://streampixels.gamecult.org/auth/connect", ...extra }, + }); + return start; + } + + it.each([ + ["no connection", {}, "creator_connection_required"], + ["an account connection", { connection: { kind: "account", targetId: "victim-1" } }, "creator_connection_required"], + ["an empty targetId", { connection: { kind: "creator", targetId: "" } }, "invalid_request"], + ])("refuses a joystick connect with %s at start, before any redirect", async (_name, extra, error) => { + const app = await buildApp({ config: createTestConfig() }); + apps.push(app); + const start = await connect(app, extra); + expect(start.statusCode).toBe(400); + expect(start.json().error).toBe(error); + expect(start.json().authorizationUrl).toBeUndefined(); + expect(start.json().stateToken).toBeUndefined(); + }); + + it.each([ + ["no connection", null], + ["an account connection", { kind: "account", targetId: "victim-1" }], + ["an empty targetId", { kind: "creator", targetId: "" }], + ])("the callback refuses a signed joystick connect with %s before the code exchange, and nothing is written", async (_name, connection) => { + const dir = mkdtempSync(join(tmpdir(), "heimdall-forge-")); + try { + const config = { ...createTestConfig(), signingPrivateKeyPath: join(dir, "signing.pem"), bootstrapSigningPrivateKeyOnMissing: true }; + const store = new InMemoryStore(); + const app = await buildApp({ config, store }); + apps.push(app); + const keys = createRuntimeKeyMaterial({ ...config, bootstrapSigningPrivateKeyOnMissing: false }); + const calls = stubJoystick({ channel_id: "chan-forged", username: "deru" }); + const stateToken = (await connect(app)).json().stateToken as string; + const verified = verifyJwt(stateToken, keys.publicKey); + expect(verified.valid).toBe(true); + const forged = signJwt({ ...(verified as { payload: Record }).payload, connection }, keys); + + const callback = await app.inject({ + method: "GET", + url: `/v1/oauth/joystick/callback?code=c&state=${encodeURIComponent(forged)}`, + }); + expect(callback.statusCode).toBeGreaterThanOrEqual(400); + expect(calls).toEqual([]); + expect(await store.findStoredLinkedIdentity("joystick", "chan-forged")).toBeNull(); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("a backend_callback delivery of a joystick connect carries no refresh token and no capabilities", async () => { + const callbackUrl = "https://streampixels.gamecult.org/api/heimdall/callback"; + const app = await buildApp({ + config: { ...createTestConfig(), appBackendCallbacks: { streampixels: [callbackUrl] } }, + }); + apps.push(app); + stubJoystick({ channel_id: "chan-hand", username: "deru" }); + const providerFetch = globalThis.fetch; + const deliveries: Array> = []; + globalThis.fetch = (async (input: string | URL, init?: RequestInit) => { + if (String(input) === callbackUrl) { + deliveries.push(JSON.parse(String(init?.body)) as Record); + return new Response(null, { status: 204 }); + } + return providerFetch(input, init); + }) as typeof fetch; + + const start = await connect(app, { + connection: creator, + handoff: { kind: "backend_callback", attemptId: "attempt-js-1", callbackUrl }, + }); + expect(start.statusCode).toBe(201); + const callback = await app.inject({ + method: "GET", + url: `/v1/oauth/joystick/callback?code=c&state=${encodeURIComponent(start.json().stateToken as string)}`, + }); + expect(callback.statusCode).toBeLessThan(300); + + expect(deliveries).toHaveLength(1); + const delivered = deliveries[0]!; + expect(delivered).toMatchObject({ status: "success", handoffKind: "backend_callback", mode: "connect", attemptId: "attempt-js-1" }); + expect(typeof delivered.accessToken).toBe("string"); + expect(delivered.refreshToken).toBeUndefined(); + expect(delivered.refresh).toBeUndefined(); + expect(delivered.claimSet.capabilities).toEqual([]); + expect(JSON.stringify(delivered)).not.toContain("js-refresh"); + }); + + it("starts a streampixels connect at joystick.tv with the five scopes and the callback redirect", async () => { + const app = await buildApp({ config: createTestConfig() }); + apps.push(app); + const start = await connect(app); + expect(start.statusCode).toBe(201); + const url = new URL(start.json().authorizationUrl as string); + expect(`${url.origin}${url.pathname}`).toBe("https://joystick.tv/api/oauth/authorize"); + expect(url.searchParams.get("client_id")).toBe("joystick-client"); + expect(url.searchParams.get("scope")).toBe("identity:read stream:read chat:read followers:read subscribers:read"); + expect(url.searchParams.get("redirect_uri")).toBe("https://heimdall.gamecult.org/v1/oauth/joystick/callback"); + }); + + it.each(["sign_in", "link"] as const)( + "refuses %s for joystick on streampixels before any redirect, and Deru's managed row is untouched", + async (mode) => { + const store = new InMemoryStore(); + const app = await buildApp({ config: createTestConfig(), store }); + apps.push(app); + stubJoystick({ channel_id: "deru-chan", username: "deru" }); + const stateToken = (await connect(app)).json().stateToken as string; + const connected = await app.inject({ + method: "GET", + url: `/v1/oauth/joystick/callback?code=a&state=${encodeURIComponent(stateToken)}`, + }); + const accountId = connected.json().account.id as string; + const before = await store.findStoredLinkedIdentityForAccount(accountId, "joystick"); + + const start = await app.inject({ + method: "POST", + url: "/v1/oauth/joystick/start", + payload: { appSlug: "streampixels", mode, returnTo: "https://streampixels.gamecult.org/auth/connect" }, + }); + expect(start.statusCode).toBe(400); + expect(start.json()).toMatchObject({ error: "provider_not_supported_for_app", provider: "joystick", mode }); + expect(start.json().authorizationUrl).toBeUndefined(); + expect(await store.findStoredLinkedIdentityForAccount(accountId, "joystick")).toEqual(before); + } + ); + + function stubJoystick(identity: Record) { + const calls: Array<{ url: string; headers: Record; body?: URLSearchParams | undefined }> = []; + globalThis.fetch = (async (input: string | URL, init?: RequestInit) => { + const url = String(input); + calls.push({ url, headers: (init?.headers ?? {}) as Record, body: init?.body as URLSearchParams | undefined }); + if (url === "https://api.joystick.tv/api/oauth/token") { + return new Response( + JSON.stringify({ access_token: "js-access", refresh_token: "js-refresh", token_type: "Bearer", expires_in: 864000 }), + { status: 200 } + ); + } + if (url === "https://api.joystick.tv/api/v1/me/identity") { + return new Response(JSON.stringify(identity), { status: 200 }); + } + return new Response("unexpected", { status: 500 }); + }) as typeof fetch; + return calls; + } + + it.each(["sign_in", "link"] as const)( + "the callback refuses a signed %s state for joystick on streampixels before the code exchange, and nothing is written", + async (mode) => { + // The start gate already refuses these words, so the state is re-signed with the app's own key. + const dir = mkdtempSync(join(tmpdir(), "heimdall-forge-")); + try { + const config = { ...createTestConfig(), signingPrivateKeyPath: join(dir, "signing.pem"), bootstrapSigningPrivateKeyOnMissing: true }; + const store = new InMemoryStore(); + const app = await buildApp({ config, store }); + apps.push(app); + const keys = createRuntimeKeyMaterial({ ...config, bootstrapSigningPrivateKeyOnMissing: false }); + const calls = stubJoystick({ channel_id: "chan-forged", username: "deru" }); + const stateToken = (await connect(app)).json().stateToken as string; + const verified = verifyJwt(stateToken, keys.publicKey); + expect(verified.valid).toBe(true); + const forged = signJwt({ ...(verified as { payload: Record }).payload, mode }, keys); + + const callback = await app.inject({ + method: "GET", + url: `/v1/oauth/joystick/callback?code=c&state=${encodeURIComponent(forged)}`, + }); + expect(callback.statusCode).toBeGreaterThanOrEqual(400); + expect(callback.body).not.toContain("viewer_access"); + expect(calls).toEqual([]); + expect(await store.findStoredLinkedIdentity("joystick", "chan-forged")).toBeNull(); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + } + ); + + it("exchanges the code with Basic client auth and links the identity by channel id", async () => { + const store = new InMemoryStore(); + const app = await buildApp({ config: createTestConfig(), store }); + apps.push(app); + const calls = stubJoystick({ channel_id: "chan-9", username: "deru", nickname: "Deru!", photo_url: "https://img/x.png" }); + const stateToken = (await connect(app)).json().stateToken as string; + + const callback = await app.inject({ + method: "GET", + url: `/v1/oauth/joystick/callback?code=the-code&state=${encodeURIComponent(stateToken)}`, + }); + expect(callback.statusCode).toBeLessThan(300); + + const exchange = calls.find((c) => c.url === "https://api.joystick.tv/api/oauth/token")!; + expect(exchange.headers.Authorization).toBe(`Basic ${Buffer.from("joystick-client:joystick-secret").toString("base64")}`); + expect(exchange.body!.get("grant_type")).toBe("authorization_code"); + expect(exchange.body!.get("code")).toBe("the-code"); + expect(exchange.body!.get("redirect_uri")).toBe("https://heimdall.gamecult.org/v1/oauth/joystick/callback"); + expect(exchange.body!.has("client_secret")).toBe(false); + const identityCall = calls.find((c) => c.url === "https://api.joystick.tv/api/v1/me/identity")!; + expect(identityCall.headers.Authorization).toBe("Bearer js-access"); + + const accountId = callback.json().account.id as string; + const row = await store.findStoredLinkedIdentityForAccount(accountId, "joystick"); + expect(row).toMatchObject({ providerUserId: "chan-9", username: "deru", displayName: "Deru!" }); + expect(row?.accessTokenEncrypted).toEqual(expect.any(String)); + expect(row?.accessTokenEncrypted).not.toContain("js-access"); + expect(row?.refreshTokenEncrypted).toEqual(expect.any(String)); + const left = Date.parse(row!.tokenExpiresAt!) - Date.now(); + expect(left).toBeGreaterThan(863_000 * 1000); + expect(left).toBeLessThanOrEqual(864_000 * 1000); + }); + + it("falls back to the username for the display name", async () => { + const store = new InMemoryStore(); + const app = await buildApp({ config: createTestConfig(), store }); + apps.push(app); + stubJoystick({ channel_id: "chan-9", username: "deru" }); + const stateToken = (await connect(app)).json().stateToken as string; + const callback = await app.inject({ + method: "GET", + url: `/v1/oauth/joystick/callback?code=c&state=${encodeURIComponent(stateToken)}`, + }); + const row = await store.findStoredLinkedIdentityForAccount(callback.json().account.id as string, "joystick"); + expect(row?.displayName).toBe("deru"); + }); + + it("fails the callback when the identity has no channel id", async () => { + const store = new InMemoryStore(); + const app = await buildApp({ config: createTestConfig(), store }); + apps.push(app); + stubJoystick({ username: "deru" }); + const stateToken = (await connect(app)).json().stateToken as string; + const callback = await app.inject({ + method: "GET", + url: `/v1/oauth/joystick/callback?code=c&state=${encodeURIComponent(stateToken)}`, + }); + expect(callback.statusCode).toBeGreaterThanOrEqual(400); + expect(await store.findStoredLinkedIdentity("joystick", "undefined")).toBeNull(); + }); + }); + it("no longer honors a global shared secret across apps", async () => { // A per-app identity model with a global fallback is a two-app shared // secret in practice (R6, fork 2). GC_ACCESS_APP_SHARED_SECRET alone must @@ -1221,3 +1653,545 @@ describe("Heimdall service", () => { expect(tokenSet.scope).toEqual(["user:read:email"]); }); }); + +// An answer never carries an input value. The canary stands in for whatever a +// failure could quote: part of a misbound database URL in a pg or resolver +// error, a request body, a header, a path, or a 4xx error's own message. +describe("error answers never echo an input", () => { + const CANARY = "CANARY"; + + function failingStore(): InMemoryStore { + const store = new InMemoryStore(); + store.consumeAuthCompletion = async () => { + throw Object.assign(new Error(`getaddrinfo ENOTFOUND ${CANARY}host.invalid`), { + code: "ENOTFOUND", + hostname: `${CANARY}host.invalid`, + }); + }; + return store; + } + + it("answers a store failure with a fixed 500 body and logs only the route and code", async () => { + const app = await buildApp({ config: createTestConfig(), store: failingStore() }); + apps.push(app); + const logged: string[] = []; + const originalError = console.error; + console.error = (...args: unknown[]) => void logged.push(args.map(String).join(" ")); + try { + const response = await app.inject({ + method: "POST", + url: "/v1/apps/bifrost/auth-completions/redeem", + payload: { completionCode: "x" }, + }); + + expect(response.statusCode).toBe(500); + expect(response.json()).toEqual({ error: "internal_error" }); + } finally { + console.error = originalError; + } + expect(logged).toEqual(["Heimdall POST /v1/apps/:appSlug/auth-completions/redeem failed (ENOTFOUND)."]); + }); + + it("answers a body that is not JSON without quoting it", async () => { + const app = await buildApp({ config: createTestConfig() }); + apps.push(app); + + const response = await app.inject({ + method: "POST", + url: "/v1/apps/bifrost/auth-completions/redeem", + headers: { "content-type": "application/json" }, + payload: `${CANARY}notjson`, + }); + + expect(response.statusCode).toBe(400); + expect(response.json().error).toBe("invalid_request"); + expect(response.body).not.toContain(CANARY); + }); + + it("answers any other 4xx error by its code, not its message", async () => { + const app = await buildApp({ config: createTestConfig() }); + apps.push(app); + app.get("/v1/probe-4xx", async () => { + throw Object.assign(new Error(`refused ${CANARY}input`), { statusCode: 409, code: "PROBE_REFUSED" }); + }); + + const response = await app.inject({ method: "GET", url: "/v1/probe-4xx" }); + + expect(response.statusCode).toBe(409); + expect(response.json()).toEqual({ error: "invalid_request", code: "PROBE_REFUSED" }); + }); + + it("answers an unsupported media type without quoting the header", async () => { + const app = await buildApp({ config: createTestConfig() }); + apps.push(app); + + const response = await app.inject({ + method: "POST", + url: "/v1/apps/bifrost/auth-completions/redeem", + headers: { "content-type": `application/${CANARY}` }, + payload: "x", + }); + + expect(response.statusCode).toBe(415); + expect(response.body).not.toContain(CANARY); + }); + + it("names the failed schema rule without quoting the request", async () => { + const app = await buildApp({ config: createTestConfig() }); + apps.push(app); + + const response = await app.inject({ + method: "POST", + url: "/v1/apps/bifrost/auth-completions/redeem", + payload: { [`${CANARY}extra`]: `${CANARY}value` }, + }); + + expect(response.statusCode).toBe(400); + expect(response.json().error).toBe("invalid_request"); + expect(response.json().detail).toMatch(/^body: #\//); + expect(response.body).not.toContain(CANARY); + }); + + it("answers an unknown route or app without quoting the path", async () => { + const app = await buildApp({ config: createTestConfig() }); + apps.push(app); + + const route = await app.inject({ method: "GET", url: `/v1/${CANARY}route` }); + expect(route.statusCode).toBe(404); + expect(route.json()).toEqual({ error: "not_found" }); + + const unknownApp = await app.inject({ method: "GET", url: `/v1/apps/${CANARY}app` }); + expect(unknownApp.statusCode).toBe(404); + expect(unknownApp.json().error).toBe("unknown_app"); + expect(unknownApp.body).not.toContain(CANARY); + + const start = await app.inject({ + method: "POST", + url: "/v1/oauth/discord/start", + payload: { appSlug: `${CANARY}app`, mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" }, + }); + expect(start.statusCode).toBe(400); + expect(start.body).not.toContain(CANARY); + }); + + function failingDiscordRuntime(): OAuthProviderRuntime { + return { + ...createMockDiscordRuntime(), + async exchangeAuthorizationCode() { + throw new SyntaxError(`Unexpected token 'a', "access_token=${CANARY}token" is not valid JSON`); + }, + }; + } + + it("renders a failed provider callback page without the failure's text", async () => { + const app = await buildApp({ config: createTestConfig(), oauthRuntimes: { discord: failingDiscordRuntime() } }); + apps.push(app); + + const stateToken = await startDiscordSignIn(app); + const response = await app.inject({ + method: "GET", + url: `/v1/oauth/discord/callback?code=test-code&state=${encodeURIComponent(stateToken)}`, + headers: { accept: "text/html" }, + }); + + expect(response.headers["content-type"]).toContain("text/html"); + expect(response.body).toContain("oauth_callback_failed"); + expect(response.body).not.toContain(CANARY); + }); + + it("delivers a failed provider callback to the app backend without the failure's text", async () => { + const deliveries: string[] = []; + globalThis.fetch = async (_input, init) => { + deliveries.push(String(init?.body)); + return new Response(null, { status: 204 }); + }; + const app = await buildApp({ config: createTestConfig(), oauthRuntimes: { discord: failingDiscordRuntime() } }); + apps.push(app); + + const start = await app.inject({ + method: "POST", + url: "/v1/oauth/discord/start", + payload: { + appSlug: "repixelizer", + mode: "sign_in", + returnTo: "https://repixelizer.gamecult.org/app/", + handoff: { + kind: "backend_callback", + attemptId: "attempt-123", + callbackUrl: "https://repixelizer.gamecult.org/api/auth/heimdall/callback", + }, + }, + }); + expect(start.statusCode).toBe(201); + const response = await app.inject({ + method: "GET", + url: `/v1/oauth/discord/callback?code=test-code&state=${encodeURIComponent(start.json().stateToken as string)}`, + }); + + expect(response.statusCode).toBe(502); + expect(response.body).not.toContain(CANARY); + expect(deliveries).toHaveLength(1); + expect(JSON.parse(deliveries[0]!)).toMatchObject({ status: "error", error: "oauth_callback_failed" }); + expect(deliveries[0]).not.toContain(CANARY); + }); +}); + +// The provider's error and error_description are relayed, but they arrive as +// query parameters anyone can write: only RFC 6749's characters survive, each +// is bounded, and the page cannot be made to run what they carry. +describe("the relayed provider error", () => { + const injected = `"\\\u0007é${"x".repeat(300)}`; + const allowed = /^[\x20-\x21\x23-\x5b\x5d-\x7e]*$/; + + function providerErrorUrl(stateToken: string): string { + const query = new URLSearchParams({ state: stateToken, error: `${"e".repeat(100)}\u0000`, error_description: injected }); + return `/v1/oauth/discord/callback?${query.toString()}`; + } + + it("is printable and bounded in the JSON answer", async () => { + const app = await buildApp({ config: createTestConfig() }); + apps.push(app); + + const response = await app.inject({ method: "GET", url: providerErrorUrl(await startDiscordSignIn(app)) }); + + expect(response.statusCode).toBe(400); + const { providerError, providerErrorDescription } = response.json() as Record; + expect(providerError).toBe("e".repeat(64)); + expect(providerErrorDescription).toHaveLength(256); + expect(providerErrorDescription).toMatch(allowed); + expect(String(providerErrorDescription).startsWith("xxx")).toBe(true); + }); + + it("cannot inject markup into the browser page, and is bounded there", async () => { + const app = await buildApp({ config: createTestConfig() }); + apps.push(app); + + const response = await app.inject({ + method: "GET", + url: providerErrorUrl(await startDiscordSignIn(app)), + headers: { accept: "text/html" }, + }); + + expect(response.headers["content-type"]).toContain("text/html"); + expect(response.body.match(/