diff --git a/.env.example b/.env.example index fbf1e68..5ccc57e 100644 --- a/.env.example +++ b/.env.example @@ -5,7 +5,10 @@ GC_ACCESS_ISSUER=http://127.0.0.1:4100 GC_ACCESS_SESSION_TTL_SECONDS=3600 GC_ACCESS_STATE_TTL_SECONDS=600 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_PROVIDER_DISCORD_CLIENT_ID= GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET= diff --git a/README.md b/README.md index bbc315f..edf91f3 100644 --- a/README.md +++ b/README.md @@ -20,21 +20,23 @@ Landed right now: - a TypeScript/Fastify service scaffold under `src/` - Ed25519 JWT signing plus `/.well-known/jwks.json` +- file-backed signing-key loading/bootstrap so restart does not vaporize the + service identity when you configure a real key path - signed OAuth start-state scaffolding for Discord, Patreon, GitHub, Twitch, and YouTube - durable auth/control-plane storage with in-memory and Postgres backends - account, linked-identity, session, grant, entitlement snapshot, and audit persistence - a real Discord OAuth callback path for the first Repixelizer access flow +- AES-256-GCM sealing for managed provider tokens at rest - a one-time browser completion exchange for opener `postMessage` handoff - app profile surfaces for Repixelizer and StreamPixels - signed claim issuance for app-local verification experiments +- a local verifier helper in `src/verifier.ts` so app backends can validate + Heimdall JWTs without phoning home on every guarded request Still not landed: -- non-ephemeral signing key handling -- real token encryption at rest instead of "encrypted" field names doing - cosplay - end-to-end app integrations in consumer repos - refresh/revocation flows and admin surfaces diff --git a/docs/architecture.md b/docs/architecture.md index a3b3c95..94d75cf 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -443,7 +443,10 @@ Suggested generic env surface: - `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_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=...` @@ -465,8 +468,17 @@ Suggested generic env surface: 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 an ephemeral dev signing key. That is acceptable for local iteration -and absolutely not acceptable for real deployment. +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 +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 +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. Per-app binding should live in code or profile config, not in cloned provider env namespaces. App-local binding and runtime config such as creator diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 0f6a782..8a42733 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -29,6 +29,9 @@ What exists right now is: - a real Discord provider callback slice for Repixelizer access - a one-time browser completion handoff so auth callback pages can post back to the opener instead of leaking final app auth in URL fragments +- file-backed signing-key loading/bootstrap for stable service identity +- AES-256-GCM token sealing for managed provider credentials at rest +- a local verifier helper that app backends can use against Heimdall JWKS - explicit state/doctrine scaffolding so the plan does not immediately turn into soup @@ -60,7 +63,7 @@ Goals: - define OAuth start/callback/link surfaces - define grant and entitlement persistence boundaries - define how app backends verify claims locally - This is now the next missing seam, not a hypothetical one. + This seam now exists in reference form and needs its first real consumer. ### 3. Make Repixelizer the first auth-blank consumer @@ -101,8 +104,8 @@ Landed in the first pass: Still to do in this phase: -- production-safe signing key persistence -- token custody hardening instead of plain placeholder storage +- key rotation policy instead of just stable key loading +- token custody retrieval/refresh surfaces beyond initial storage ### Phase 2: Heimdall service skeleton @@ -116,8 +119,7 @@ Landed in the first pass: Next in this phase: - provider refresh/revocation flows -- non-ephemeral signing key handling -- token encryption at rest +- connection lifecycle and token-rotation work ### Phase 3: Repixelizer binding @@ -125,7 +127,7 @@ Next in this phase: - consume the one-time completion flow from the Repixelizer frontend/backend - gate `POST /api/jobs` - gate per-job read/cancel/event routes by local session ownership -- land a small verifier seam so Repixelizer can trust Heimdall JWTs locally +- consume the landed verifier seam so Repixelizer can trust Heimdall JWTs locally ### Phase 4: StreamPixels authority migration diff --git a/docs/service-contract.md b/docs/service-contract.md index 022b7d9..a9f1b11 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -29,6 +29,8 @@ Response: "service": "heimdall", "issuer": "https://heimdall.gamecult.org", "storageBackend": "memory", + "signingKeySource": "configured_file", + "tokenCustodySource": "configured", "now": "2026-04-26T12:00:00.000Z" } ``` @@ -42,9 +44,13 @@ Purpose: Notes: - current skeleton signs with Ed25519 -- if `GC_ACCESS_SIGNING_PRIVATE_KEY_PEM` is absent, the service generates an - ephemeral dev key at startup -- production should use a persisted private key and stable `kid` +- `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 + ephemeral dev key at startup and deserves no sympathy when the `kid` changes ### `GET /.well-known/heimdall-configuration` @@ -238,6 +244,27 @@ Important behavior: - app backends should redeem them server-side - the browser should not keep the final access token in callback URL fragments +### Reference local verifier seam + +Purpose: + +- give app backends a tiny local verification helper instead of encouraging + per-request Heimdall callbacks + +Current reference helper: + +- `src/verifier.ts` + +Current helper contract: + +- build the verifier once from Heimdall `issuer`, app slug, and JWKS +- verify Ed25519 signature locally by `kid` +- reject wrong `iss`, wrong `aud`, malformed claim shape, `nbf` violations, + and expired tokens +- accept a small clock-skew window for normal same-host reality + +This is a reference seam, not a magical shared middleware product yet. + ### `POST /v1/apps/{appSlug}/claims/issue` Purpose: @@ -332,17 +359,14 @@ Examples: The following are not landed yet: -- non-ephemeral signing key handling -- actual token encryption at rest and secret-management policy - refresh/revocation flows -- app-facing middleware packages or reference verifiers - admin/grant management surfaces ## Next implementation move -Build the first consumer seam and harden the custody story: +Consume the hardened slice in the first real app binding: -- persisted signing key material -- real token encryption at rest -- a reference verifier / middleware contract for app backends - the first Repixelizer consumer binding that trusts Heimdall claims locally +- the first Repixelizer backend redeem path for completion codes +- any missing app-local session bridge or verifier middleware sugar that makes + that integration less feral diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 3188cd8..95b9cde 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -50,6 +50,12 @@ Do not trust this file for the exact live HEAD. Always check git. claim issuance for the Repixelizer slice - browser-style auth handoff now uses a one-time completion code posted back to the opener, with backend redemption instead of fragment-token handoff +- signing keys can now load from a persisted file path and bootstrap that file + on first boot when explicitly enabled +- managed provider tokens are now sealed at rest with AES-256-GCM instead of + being dumped into "encrypted" columns raw like an insult +- `src/verifier.ts` now provides a small local JWT verifier seam for app + backends - Repixelizer is the first auth-blank binding target - StreamPixels is the migration target with useful existing auth seams that should not be flattened into mush @@ -73,12 +79,11 @@ Do not continue implementation automatically from a rehydrate-only request. If the user asks to continue, the current next move is to harden and consume the landed slice: -- persisted signing key material -- real token encryption at rest -- a reference verifier / middleware seam for app backends - the first Repixelizer consumer integration that opens auth in a new browser context, redeems Heimdall completion codes server-side, and trusts Heimdall claims locally +- any small app-facing middleware sugar needed once that integration starts + colliding with real routes without dragging app-domain data into the shared layer and without forcing per-request auth round-trips. diff --git a/src/app.ts b/src/app.ts index 804f5bd..2e8506a 100644 --- a/src/app.ts +++ b/src/app.ts @@ -18,6 +18,7 @@ import { mapIssueClaimRequest, issueAccessClaim, type IssueAccessClaimInput } fr import { getAppProfile, serializeAppProfile, supportsProvider } from "./app-profiles.js"; import { renderBrowserHandoffPage } from "./browser-handoff.js"; import { type HeimdallConfig, loadConfig } from "./config.js"; +import { createTokenCustody, type TokenCustody } from "./custody.js"; import { grantFact } from "./facts.js"; import { createOAuthRuntimeRegistry, type OAuthRuntimeRegistry } from "./oauth.js"; import { buildAuthorizationUrl, providerCatalog, providerExpectedEnv } from "./providers.js"; @@ -29,6 +30,7 @@ interface BuildAppOptions { config?: HeimdallConfig; store?: HeimdallStore; oauthRuntimes?: Partial; + tokenCustody?: TokenCustody; } function buildDiscovery(config: HeimdallConfig) { @@ -126,12 +128,13 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { await store.close(); }); @@ -146,6 +149,8 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { + if (config.storage.backend === "postgres") { + throw new Error( + "GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64 is required when Heimdall uses persistent postgres storage." + ); + } + + return randomBytes(TOKEN_KEY_BYTES); + })(); + const source: TokenCustody["source"] = config.tokenEncryptionKeyBase64 ? "configured" : "ephemeral_dev"; + + return { + source, + encrypt(plaintext: string): string { + const iv = randomBytes(TOKEN_IV_BYTES); + const cipher = createCipheriv("aes-256-gcm", key, iv); + const sealed = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]); + const authTag = cipher.getAuthTag(); + + return `${TOKEN_ENVELOPE_PREFIX}:${iv.toString("base64url")}.${sealed.toString("base64url")}.${authTag.toString("base64url")}`; + }, + decrypt(ciphertext: string): string { + const envelope = decodeEnvelope(ciphertext); + const decipher = createDecipheriv("aes-256-gcm", key, envelope.iv); + decipher.setAuthTag(envelope.authTag); + const plaintext = Buffer.concat([decipher.update(envelope.sealed), decipher.final()]); + return plaintext.toString("utf8"); + }, + }; +} diff --git a/src/signing.ts b/src/signing.ts index c20944a..72a5728 100644 --- a/src/signing.ts +++ b/src/signing.ts @@ -7,6 +7,8 @@ import { verify, type KeyObject, } from "node:crypto"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname } from "node:path"; import { type HeimdallConfig } from "./config.js"; type Jwk = { @@ -16,12 +18,15 @@ type Jwk = { [key: string]: unknown; }; +export type PublicSigningJwk = Jwk & { alg: "EdDSA"; kid: string; use: "sig" }; + export interface RuntimeKeyMaterial { alg: "EdDSA"; kid: string; privateKey: KeyObject; publicKey: KeyObject; - publicJwk: Jwk & { alg: "EdDSA"; kid: string; use: "sig" }; + publicJwk: PublicSigningJwk; + source: "configured_pem" | "configured_file" | "bootstrapped_file" | "ephemeral_dev"; } function encodeBase64Url(input: string | Buffer): string { @@ -43,10 +48,75 @@ function buildKeyId(publicJwk: Jwk, explicitKeyId?: string): string { return `ed25519-${thumbprint.slice(0, 12)}`; } +function exportPrivateKeyPem(privateKey: KeyObject): string { + const exported = privateKey.export({ + format: "pem", + type: "pkcs8", + }) as string | Buffer; + return typeof exported === "string" ? exported : exported.toString("utf8"); +} + +function loadPrivateKeyFromPath(path: string): KeyObject { + return createPrivateKey(readFileSync(path, "utf8")); +} + +function createOrLoadPrivateKeyFromPath(config: HeimdallConfig): { + privateKey: KeyObject; + source: RuntimeKeyMaterial["source"]; +} { + const path = config.signingPrivateKeyPath; + if (!path) { + return { + privateKey: generateKeyPairSync("ed25519").privateKey, + source: "ephemeral_dev", + }; + } + + if (existsSync(path)) { + return { + privateKey: loadPrivateKeyFromPath(path), + source: "configured_file", + }; + } + + 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.` + ); + } + + const privateKey = generateKeyPairSync("ed25519").privateKey; + mkdirSync(dirname(path), { recursive: true }); + try { + writeFileSync(path, exportPrivateKeyPem(privateKey), { + encoding: "utf8", + mode: 0o600, + flag: "wx", + }); + return { + privateKey, + source: "bootstrapped_file", + }; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") { + throw error; + } + + return { + privateKey: loadPrivateKeyFromPath(path), + source: "configured_file", + }; + } +} + export function createRuntimeKeyMaterial(config: HeimdallConfig): RuntimeKeyMaterial { - const privateKey = config.signingPrivateKeyPem - ? createPrivateKey(config.signingPrivateKeyPem) - : generateKeyPairSync("ed25519").privateKey; + const loaded = config.signingPrivateKeyPem + ? { + privateKey: createPrivateKey(config.signingPrivateKeyPem), + source: "configured_pem" as const, + } + : createOrLoadPrivateKeyFromPath(config); + const privateKey = loaded.privateKey; const publicKey = createPublicKey(privateKey); const exportedJwk = publicKey.export({ format: "jwk" }) as Jwk; const kid = buildKeyId(exportedJwk, config.signingKeyId); @@ -62,6 +132,7 @@ export function createRuntimeKeyMaterial(config: HeimdallConfig): RuntimeKeyMate kid, use: "sig", }, + source: loaded.source, }; } diff --git a/src/store/in-memory.ts b/src/store/in-memory.ts index 438641c..803def7 100644 --- a/src/store/in-memory.ts +++ b/src/store/in-memory.ts @@ -93,6 +93,16 @@ export class InMemoryStore implements HeimdallStore { return null; } + async findStoredLinkedIdentity(provider: Provider, providerUserId: string): Promise { + for (const linkedIdentity of this.linkedIdentities.values()) { + if (linkedIdentity.provider === provider && linkedIdentity.providerUserId === providerUserId) { + return clone(linkedIdentity); + } + } + + return null; + } + async upsertLinkedIdentity(input: UpsertLinkedIdentityInput): Promise { const existing = [...this.linkedIdentities.values()].find( (identity) => identity.provider === input.provider && identity.providerUserId === input.providerUserId diff --git a/src/store/postgres.ts b/src/store/postgres.ts index 5cb4e83..36e26ec 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -274,6 +274,21 @@ export class PostgresStore implements HeimdallStore { return result.rowCount ? mapAccountRow(expectRow(result.rows[0], "findAccountByLinkedIdentity")) : null; } + async findStoredLinkedIdentity(provider: Provider, providerUserId: string): Promise { + const result = await this.pool.query( + ` + SELECT * + FROM linked_identities + WHERE provider = $1 + AND provider_user_id = $2 + LIMIT 1 + `, + [provider, providerUserId] + ); + + return result.rowCount ? mapLinkedIdentityRow(expectRow(result.rows[0], "findStoredLinkedIdentity")) : null; + } + async upsertLinkedIdentity(input: UpsertLinkedIdentityInput): Promise { const id = input.id ?? randomUUID(); const result = await this.pool.query( diff --git a/src/store/types.ts b/src/store/types.ts index f0c3979..9a3a30d 100644 --- a/src/store/types.ts +++ b/src/store/types.ts @@ -154,6 +154,7 @@ export interface HeimdallStore { createAccount(input: CreateAccountInput): Promise; touchAccount(accountId: string, at: string, updates?: { displayName?: string; primaryEmail?: string }): Promise; findAccountByLinkedIdentity(provider: Provider, providerUserId: string): Promise; + findStoredLinkedIdentity(provider: Provider, providerUserId: string): Promise; upsertLinkedIdentity(input: UpsertLinkedIdentityInput): Promise; listLinkedIdentitiesForAccount(accountId: string): Promise; createCapabilityGrant(input: CreateCapabilityGrantInput): Promise; diff --git a/src/verifier.ts b/src/verifier.ts new file mode 100644 index 0000000..d1d5d60 --- /dev/null +++ b/src/verifier.ts @@ -0,0 +1,161 @@ +import { createPublicKey, type KeyObject } from "node:crypto"; +import { appSlugs, providers, type AccessClaimPayload, type AppSlug, type LinkedIdentityInput, type Provider } from "./contracts.js"; +import { type PublicSigningJwk, verifyJwt } from "./signing.js"; + +export interface HeimdallVerifierOptions { + issuer: string; + appSlug: AppSlug; + jwks: { + keys: PublicSigningJwk[]; + }; + allowedClockSkewSeconds?: number; +} + +export type VerifyAccessTokenResult = + | { + valid: true; + header: Record; + claimSet: AccessClaimPayload; + } + | { + valid: false; + error: string; + }; + +function isLinkedIdentity(value: unknown): value is LinkedIdentityInput { + if (!value || typeof value !== "object") { + return false; + } + + const record = value as Record; + if ( + typeof record.provider !== "string" || + !providers.includes(record.provider as Provider) || + typeof record.providerUserId !== "string" + ) { + return false; + } + + if (record.username !== undefined && typeof record.username !== "string") { + return false; + } + + if (record.displayName !== undefined && typeof record.displayName !== "string") { + return false; + } + + return true; +} + +function parseAccessClaimPayload(payload: Record): AccessClaimPayload | null { + if ( + payload.typ !== "heimdall_access" || + typeof payload.iss !== "string" || + typeof payload.aud !== "string" || + !appSlugs.includes(payload.aud as AppSlug) || + typeof payload.sub !== "string" || + typeof payload.sid !== "string" || + typeof payload.jti !== "string" || + typeof payload.iat !== "number" || + typeof payload.nbf !== "number" || + typeof payload.exp !== "number" || + typeof payload.account_id !== "string" || + typeof payload.access_revision !== "number" || + !payload.app || + typeof payload.app !== "object" || + typeof (payload.app as Record).slug !== "string" || + !appSlugs.includes((payload.app as Record).slug as AppSlug) || + typeof (payload.app as Record).profile_version !== "string" || + !Array.isArray(payload.facts) || + !payload.facts.every((fact) => typeof fact === "string") || + !Array.isArray(payload.capabilities) || + !payload.capabilities.every((capability) => typeof capability === "string") || + !Array.isArray(payload.identities) || + !payload.identities.every(isLinkedIdentity) + ) { + return null; + } + + if (payload.display_name !== undefined && typeof payload.display_name !== "string") { + return null; + } + + return payload as unknown as AccessClaimPayload; +} + +function buildKeyIndex(jwks: { keys: PublicSigningJwk[] }): Map { + return new Map( + jwks.keys.map((jwk) => [ + jwk.kid, + createPublicKey({ + key: jwk, + format: "jwk", + }), + ]) + ); +} + +export function createHeimdallAccessTokenVerifier(options: HeimdallVerifierOptions): { + verify(token: string, now?: Date): VerifyAccessTokenResult; +} { + const keyIndex = buildKeyIndex(options.jwks); + const allowedClockSkewSeconds = Math.max(0, Math.trunc(options.allowedClockSkewSeconds ?? 30)); + + return { + verify(token: string, now = new Date()): VerifyAccessTokenResult { + const [encodedHeader] = token.split("."); + if (!encodedHeader) { + return { valid: false, error: "Malformed JWT." }; + } + + let header: Record; + try { + header = JSON.parse(Buffer.from(encodedHeader, "base64url").toString("utf8")) as Record; + } catch { + return { valid: false, error: "Malformed JWT header." }; + } + + if (header.alg !== "EdDSA" || typeof header.kid !== "string") { + return { valid: false, error: "Unsupported JWT signing header." }; + } + + const publicKey = keyIndex.get(header.kid); + if (!publicKey) { + return { valid: false, error: `Unknown signing key id '${header.kid}'.` }; + } + + const verified = verifyJwt(token, publicKey); + if (!verified.valid) { + return verified; + } + + const claimSet = parseAccessClaimPayload(verified.payload); + if (!claimSet) { + return { valid: false, error: "JWT payload is not a valid Heimdall access claim." }; + } + + if (claimSet.iss !== options.issuer) { + return { valid: false, error: "JWT issuer does not match the configured Heimdall issuer." }; + } + + if (claimSet.aud !== options.appSlug || claimSet.app.slug !== options.appSlug) { + return { valid: false, error: "JWT audience does not match the expected app slug." }; + } + + const nowEpochSeconds = Math.floor(now.getTime() / 1000); + if (claimSet.nbf > nowEpochSeconds + allowedClockSkewSeconds) { + return { valid: false, error: "JWT is not valid yet." }; + } + + if (claimSet.exp <= nowEpochSeconds - allowedClockSkewSeconds) { + return { valid: false, error: "JWT has expired." }; + } + + return { + valid: true, + header: verified.header, + claimSet, + }; + }, + }; +} diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 837b39c..ced60d1 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -7,3 +7,4 @@ {"ts": "2026-04-26T11:49:41+00:00", "type": "implementation", "status": "accepted", "note": "The first stateful Heimdall slice landed durable auth-control-plane persistence plus a real Discord callback path for Repixelizer, with accounts, linked identities, sessions, grants, entitlement snapshots, and audit events stored behind in-memory/Postgres backends."} {"ts": "2026-04-26T13:58:45+00:00", "type": "design", "status": "accepted", "note": "Heimdall claim facts should prefer provider-agnostic, app-facing entitlement names such as entitlement.app_access. Provider-specific evidence like Discord role matches stays in linked identities and entitlement snapshots unless a consumer truly needs that upstream detail in the claim surface."} {"ts": "2026-04-26T14:22:37+00:00", "type": "implementation", "status": "accepted", "note": "Browser-style Heimdall auth handoff now uses a short-lived one-time completion code: the callback page posts the result to the opener, tries to close itself, and the app backend redeems the code with Heimdall instead of receiving the final access token in a callback URL fragment."} +{"ts": "2026-04-26T15:22:58+00:00", "type": "implementation", "status": "accepted", "note": "Heimdall now supports file-backed signing-key loading/bootstrap, AES-256-GCM token sealing for managed provider credentials at rest, and a local JWT verifier seam in src/verifier.ts; the next move shifts from custody hardening to the first real Repixelizer consumer integration."} diff --git a/state/map.yaml b/state/map.yaml index f8f9b72..86023a6 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -78,6 +78,7 @@ landed_baseline: - Initial Heimdall service skeleton landed with discovery, JWKS, OAuth start/callback contract surfaces, and claim issuance scaffolding. - Durable auth persistence landed for accounts, linked identities, sessions, grants, entitlement snapshots, and audit events. - The first real provider slice landed for Discord callback exchange, identity resolution, entitlement evaluation, and session/claim issuance for Repixelizer. + - Signing-key persistence/bootstrap, managed token encryption at rest, and a local verifier seam landed for the first real consumer integration pass. rejected_paths: - name: per_app_auth_copy_paste @@ -88,5 +89,5 @@ rejected_paths: reason: reusing auth mechanics does not justify centralizing app-domain audience or product data current_status: - summary: Heimdall now has a stateful first provider slice plus a proper browser handoff: TypeScript/Fastify runtime, Ed25519 JWT signing, JWKS/discovery exposure, signed OAuth start-state handling, durable auth/control-plane persistence, a real Discord callback path, and a one-time completion-code exchange that lets browser auth contexts post back to the opener without leaking final app auth in URL fragments. The key boundary still holds: Heimdall owns auth/control-plane authority and credential custody; app-domain bindings and runtime behavior remain app-owned. - next_action: Consume the new handoff in the first real Repixelizer integration and harden custody: persisted signing key material, real token encryption at rest, and a small verifier/integration contract so Repixelizer can redeem Heimdall completion codes server-side and trust Heimdall claims locally. + summary: Heimdall now has a hardened first provider slice: TypeScript/Fastify runtime, Ed25519 JWT signing with file-backed key support, JWKS/discovery exposure, signed OAuth start-state handling, durable auth/control-plane persistence, a real Discord callback path, AES-256-GCM token sealing for managed provider credentials at rest, a local JWT verifier seam for app backends, and a one-time completion-code exchange that lets browser auth contexts post back to the opener without leaking final app auth in URL fragments. The key boundary still holds: Heimdall owns auth/control-plane authority and credential custody; app-domain bindings and runtime behavior remain app-owned. + next_action: Consume the hardened slice in the first real Repixelizer integration: open auth in a new browser context, redeem Heimdall completion codes server-side, trust Heimdall claims locally through the verifier seam, and add any tiny app-local session bridge needed without dragging app-domain data into Heimdall. diff --git a/tests/app.test.ts b/tests/app.test.ts index 72724e3..9441798 100644 --- a/tests/app.test.ts +++ b/tests/app.test.ts @@ -5,6 +5,8 @@ import { type HeimdallConfig } from "../src/config.js"; import { entitlementFacts, grantFacts, identityFacts } from "../src/facts.js"; import { type OAuthProviderRuntime } from "../src/oauth.js"; import { verifyJwt } from "../src/signing.js"; +import { createHeimdallAccessTokenVerifier } from "../src/verifier.js"; +import { InMemoryStore } from "../src/store/index.js"; function createTestConfig(): HeimdallConfig { return { @@ -16,6 +18,8 @@ function createTestConfig(): HeimdallConfig { sessionTtlSeconds: 3600, stateTtlSeconds: 600, completionTtlSeconds: 300, + bootstrapSigningPrivateKeyOnMissing: false, + tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"), storage: { backend: "memory", applySchemaOnStartup: true, @@ -95,6 +99,21 @@ function getPublicKey(app: FastifyInstance) { ).heimdallContext.keys.publicKey; } +function getHeimdallContext(app: FastifyInstance) { + return (app as FastifyInstance & { + heimdallContext: { + keys: { + publicKey: Parameters[1]; + publicJwk: { alg: "EdDSA"; kid: string; use: "sig"; [key: string]: unknown }; + }; + tokenCustody: { + decrypt(ciphertext: string): string; + }; + store: InMemoryStore; + }; + }).heimdallContext; +} + async function startDiscordSignIn(app: FastifyInstance): Promise { const response = await app.inject({ method: "POST", @@ -183,8 +202,10 @@ describe("Heimdall service", () => { }); it("completes a provider callback and issues a verified Repixelizer claim", async () => { + const store = new InMemoryStore(); const app = await buildApp({ config: createTestConfig(), + store, oauthRuntimes: { discord: createMockDiscordRuntime(), }, @@ -214,6 +235,17 @@ describe("Heimdall service", () => { ); expect(payload.entitlements.facts).toEqual(expect.arrayContaining([entitlementFacts.appAccess])); + const storedIdentity = await store.findStoredLinkedIdentity("discord", "discord-user-123"); + expect(storedIdentity).toEqual(expect.objectContaining({ provider: "discord" })); + expect(storedIdentity?.accessTokenEncrypted).toMatch(/^gc_tok_v1:/); + expect(storedIdentity?.accessTokenEncrypted).not.toBe("discord-access-token"); + expect(getHeimdallContext(app).tokenCustody.decrypt(storedIdentity?.accessTokenEncrypted ?? "")).toBe( + "discord-access-token" + ); + expect(getHeimdallContext(app).tokenCustody.decrypt(storedIdentity?.refreshTokenEncrypted ?? "")).toBe( + "discord-refresh-token" + ); + const verified = verifyJwt(payload.accessToken as string, getPublicKey(app)); expect(verified.valid).toBe(true); if (verified.valid) { @@ -326,6 +358,25 @@ describe("Heimdall service", () => { expect(payload.sharedCapabilities).toEqual( expect.arrayContaining(["app_access", "queue_submit", "admin_access"]) ); + + const verifier = createHeimdallAccessTokenVerifier({ + issuer: "https://heimdall.gamecult.org", + appSlug: "repixelizer", + jwks: { + keys: [getHeimdallContext(app).keys.publicJwk], + }, + }); + expect(verifier.verify(payload.accessToken as string)).toEqual( + expect.objectContaining({ + valid: true, + claimSet: expect.objectContaining({ + aud: "repixelizer", + app: expect.objectContaining({ + slug: "repixelizer", + }), + }), + }) + ); }); it("exposes StreamPixels hybrid capability seams without granting them blindly", async () => { diff --git a/tests/security.test.ts b/tests/security.test.ts new file mode 100644 index 0000000..2dd1253 --- /dev/null +++ b/tests/security.test.ts @@ -0,0 +1,100 @@ +import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { afterEach, describe, expect, it } from "vitest"; +import { type HeimdallConfig } from "../src/config.js"; +import { createTokenCustody } from "../src/custody.js"; +import { createRuntimeKeyMaterial } from "../src/signing.js"; + +function createTestConfig(overrides: Partial = {}): HeimdallConfig { + return { + serviceName: "heimdall", + host: "127.0.0.1", + port: 4100, + publicBaseUrl: "https://heimdall.gamecult.org", + issuer: "https://heimdall.gamecult.org", + sessionTtlSeconds: 3600, + stateTtlSeconds: 600, + completionTtlSeconds: 300, + bootstrapSigningPrivateKeyOnMissing: false, + storage: { + backend: "memory", + applySchemaOnStartup: true, + }, + apps: { + repixelizer: { + discordGuildId: "gamecult-guild", + discordAllowedRoleIds: ["role-repixelizer"], + }, + }, + providers: { + discord: {}, + patreon: {}, + github: {}, + twitch: {}, + youtube: {}, + }, + ...overrides, + }; +} + +const tempDirs: string[] = []; + +afterEach(() => { + while (tempDirs.length) { + rmSync(tempDirs.pop() ?? "", { force: true, recursive: true }); + } +}); + +describe("Heimdall security helpers", () => { + it("round-trips provider tokens through AES-GCM custody", () => { + const custody = createTokenCustody({ + ...createTestConfig(), + tokenEncryptionKeyBase64: Buffer.alloc(32, 23).toString("base64"), + }); + + const encrypted = custody.encrypt("discord-access-token"); + expect(encrypted).toMatch(/^gc_tok_v1:/); + expect(encrypted).not.toBe("discord-access-token"); + expect(custody.decrypt(encrypted)).toBe("discord-access-token"); + }); + + it("refuses persistent provider-token storage without a stable encryption key", () => { + expect(() => + createTokenCustody( + createTestConfig({ + storage: { + backend: "postgres", + applySchemaOnStartup: true, + databaseUrl: "postgres://127.0.0.1/heimdall", + }, + }) + ) + ).toThrow(/GC_ACCESS_TOKEN_ENCRYPTION_KEY_BASE64/); + }); + + it("bootstraps and then reuses a file-backed signing key", () => { + const tempDir = mkdtempSync(join(tmpdir(), "heimdall-signing-")); + tempDirs.push(tempDir); + const signingKeyPath = join(tempDir, "keys", "heimdall-signing-key.pem"); + + const first = createRuntimeKeyMaterial( + createTestConfig({ + signingPrivateKeyPath: signingKeyPath, + bootstrapSigningPrivateKeyOnMissing: true, + }) + ); + const second = createRuntimeKeyMaterial( + createTestConfig({ + signingPrivateKeyPath: signingKeyPath, + bootstrapSigningPrivateKeyOnMissing: false, + }) + ); + + expect(first.source).toBe("bootstrapped_file"); + expect(second.source).toBe("configured_file"); + expect(first.kid).toBe(second.kid); + expect(existsSync(signingKeyPath)).toBe(true); + expect(readFileSync(signingKeyPath, "utf8")).toContain("BEGIN PRIVATE KEY"); + }); +}); diff --git a/tests/store.test.ts b/tests/store.test.ts index 9b7f4bf..818f352 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -53,6 +53,15 @@ describe("PostgresStore", () => { }, ]); + const storedIdentity = await store.findStoredLinkedIdentity("discord", "discord-user-123"); + expect(storedIdentity).toEqual( + expect.objectContaining({ + provider: "discord", + accessTokenEncrypted: "encrypted-access-token", + refreshTokenEncrypted: "encrypted-refresh-token", + }) + ); + await store.createCapabilityGrant({ accountId: account.id, scopeType: "app",