diff --git a/src/store/in-memory.ts b/src/store/in-memory.ts index 6a53dad..5fc91ba 100644 --- a/src/store/in-memory.ts +++ b/src/store/in-memory.ts @@ -3,6 +3,7 @@ import { type AppSlug, type LinkedIdentityInput, type Provider } from "../contra import { type CreateAccountInput, type CreateAuthAttemptInput, + type ClaimOAuthStateUseInput, type CreateAuthCompletionInput, type CreateAuditEventInput, type CreateCapabilityGrantInput, @@ -48,6 +49,8 @@ export class InMemoryStore implements HeimdallStore { private readonly privateCommandReceipts = new Map(); private readonly authCompletions = new Map(); private readonly authCompletionsByAttempt = new Map(); + /** `${jti}:${phase}` -> the state's expiresAt. */ + private readonly oauthStateUses = new Map(); private readonly entitlementSnapshots = new Map(); private readonly auditEvents = new Map(); @@ -424,6 +427,20 @@ export class InMemoryStore implements HeimdallStore { return this.consumeAuthCompletion(appSlug, code, at); } + async claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise { + for (const [key, expiresAt] of this.oauthStateUses) { + if (expiresAt <= input.usedAt) { + this.oauthStateUses.delete(key); + } + } + const key = `${input.jti}:${input.phase}`; + if (this.oauthStateUses.has(key)) { + return false; + } + this.oauthStateUses.set(key, input.expiresAt); + return true; + } + async upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise { const key = `${input.accountId}:${input.provider}:${input.scope}`; this.entitlementSnapshots.set(key, clone(input)); diff --git a/src/store/postgres.ts b/src/store/postgres.ts index 487f375..4ee0ea1 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -5,6 +5,7 @@ import { CREATE_SCHEMA_SQL, REQUIRED_COLUMNS, REQUIRED_KEYS, REQUIRED_TABLES } f import { type CreateAccountInput, type CreateAuthAttemptInput, + type ClaimOAuthStateUseInput, type CreateAuthCompletionInput, type CreateAuditEventInput, type CreateCapabilityGrantInput, @@ -378,6 +379,7 @@ export const STORE_TABLE_PRIVILEGES: Readonly { + // No conflict target and no RETURNING: both need SELECT, and the role has INSERT only. + const result = await this.pool.query( + ` + INSERT INTO oauth_state_uses (jti, phase, app_slug, used_at, expires_at) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT DO NOTHING + `, + [input.jti, input.phase, input.appSlug, input.usedAt, input.expiresAt] + ); + return result.rowCount === 1; + } + async upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise { await this.pool.query( ` diff --git a/src/store/schema.ts b/src/store/schema.ts index 420f5e6..80dfa6e 100644 --- a/src/store/schema.ts +++ b/src/store/schema.ts @@ -119,6 +119,20 @@ CREATE UNIQUE INDEX IF NOT EXISTS auth_completions_attempt_unconsumed_unique_idx ON auth_completions(app_slug, attempt_id) WHERE attempt_id IS NOT NULL AND consumed_at IS NULL; +-- One use per (state jti, phase): a signed OAuth state launches once and +-- completes once. The first INSERT for a pair wins; ON CONFLICT DO NOTHING +-- reports every later claim as no row. The store deletes nothing, so rows stay +-- like consumed auth_completions; after expires_at a state is refused before +-- any claim, so a row is never consulted again. +CREATE TABLE IF NOT EXISTS oauth_state_uses ( + jti TEXT NOT NULL, + phase TEXT NOT NULL, + app_slug TEXT NOT NULL, + used_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (jti, phase) +); + CREATE TABLE IF NOT EXISTS capability_grants ( id TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, diff --git a/src/store/types.ts b/src/store/types.ts index 5307e1f..d6a2f93 100644 --- a/src/store/types.ts +++ b/src/store/types.ts @@ -165,6 +165,14 @@ export interface StoredAuthCompletion { payloadJson: Record; } +export interface ClaimOAuthStateUseInput { + jti: string; + phase: "launch" | "callback"; + appSlug: AppSlug; + usedAt: string; + expiresAt: string; +} + export interface CreateAuthCompletionInput { /** * Correlation handle only (see StoredAuthCompletion.attemptId). The store @@ -272,5 +280,15 @@ export interface HeimdallStore { */ consumeAuthCompletionByAttempt(appSlug: AppSlug, attemptId: string, at: string): Promise; upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise; + /** + * Claim one use of a signed OAuth state: true only for the first claim of + * (jti, phase), false for every later one. Without it a state is a bearer + * token any number of browsers can complete, so an attacker who learns a + * victim's state completes it as themselves and hands the victim a code + * for the attacker's account. `expiresAt` is the state's own expiry; the + * state is refused at that time before any claim, so the record is dead + * after it and a store may drop it. + */ + claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise; createAuditEvent(input: CreateAuditEventInput): Promise; } diff --git a/tests/store.test.ts b/tests/store.test.ts index c94c521..60bd1f5 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -3,7 +3,7 @@ import { Pool } from "pg"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { newDb } from "pg-mem"; import { type HeimdallConfig } from "../src/config.js"; -import { createStore } from "../src/store/index.js"; +import { createStore, InMemoryStore } from "../src/store/index.js"; import { createPostgresStore, PostgresStore, @@ -159,18 +159,6 @@ describe("PostgresStore", () => { const consumedAgain = await store.consumeAuthCompletion("repixelizer", completion.code, "2026-04-26T12:02:00.000Z"); expect(consumedAgain).toBeNull(); - const stateUse = { - jti: "state-1", - phase: "launch" as const, - appSlug: "repixelizer" as const, - usedAt: now, - expiresAt: "2026-04-26T12:10:00.000Z", - }; - expect(await store.claimOAuthStateUse(stateUse)).toBe(true); - expect(await store.claimOAuthStateUse(stateUse)).toBe(false); - expect(await store.claimOAuthStateUse({ ...stateUse, phase: "callback" })).toBe(true); - expect(await store.claimOAuthStateUse({ ...stateUse, jti: "state-2" })).toBe(true); - const attempt = await store.createAuthAttempt({ handle: "attempt-123", appSlug: "ghostlight", @@ -210,6 +198,36 @@ describe("PostgresStore", () => { }); }); +describe("InMemoryStore.claimOAuthStateUse", () => { + const use = { + jti: "state-1", + phase: "launch" as const, + appSlug: "repixelizer" as const, + usedAt: "2026-04-26T12:00:00.000Z", + expiresAt: "2026-04-26T12:10:00.000Z", + }; + + it("is true once per (jti, phase)", async () => { + const store = new InMemoryStore(); + expect(await store.claimOAuthStateUse(use)).toBe(true); + expect(await store.claimOAuthStateUse(use)).toBe(false); + expect(await store.claimOAuthStateUse({ ...use, phase: "callback" })).toBe(true); + expect(await store.claimOAuthStateUse({ ...use, phase: "callback" })).toBe(false); + expect(await store.claimOAuthStateUse({ ...use, jti: "state-2" })).toBe(true); + }); + + it("drops a record once its state has expired, and keeps it until then", async () => { + const store = new InMemoryStore(); + await store.claimOAuthStateUse(use); + // Before expiry a later claim of another state leaves the record in force. + await store.claimOAuthStateUse({ ...use, jti: "state-2", usedAt: "2026-04-26T12:09:59.000Z" }); + expect(await store.claimOAuthStateUse(use)).toBe(false); + // At and after expiry the record is dead weight: the state is refused before any claim. + await store.claimOAuthStateUse({ ...use, jti: "state-3", usedAt: "2026-04-26T12:10:00.000Z" }); + expect(await store.claimOAuthStateUse(use)).toBe(true); + }); +}); + describe("createPostgresStore", () => { // pg emits an idle client's connection loss on the pool. With no listener // that event kills the process, and Node prints the pg Client with its @@ -245,11 +263,12 @@ describe("PostgresStore.checkSchema", () => { "auth_attempts", "private_command_receipts", "auth_completions", + "oauth_state_uses", "capability_grants", "entitlement_snapshots", "audit_events", ]); - expect(REQUIRED_COLUMNS).toHaveLength(85); + expect(REQUIRED_COLUMNS).toHaveLength(90); expect(REQUIRED_COLUMNS).toEqual( expect.arrayContaining([ { table: "auth_completions", column: "code", type: "TEXT", nullable: false }, @@ -260,11 +279,12 @@ describe("PostgresStore.checkSchema", () => { { table: "auth_completions", column: "attempt_id", type: "TEXT", nullable: true }, ]) ); - expect(REQUIRED_KEYS).toHaveLength(12); + expect(REQUIRED_KEYS).toHaveLength(13); expect(REQUIRED_KEYS).toEqual( expect.arrayContaining([ { table: "linked_identities", columns: "provider,provider_user_id", predicate: "" }, { table: "private_command_receipts", columns: "app_slug,idempotency_key", predicate: "" }, + { table: "oauth_state_uses", columns: "jti,phase", predicate: "" }, { table: "entitlement_snapshots", columns: "account_id,provider,scope", predicate: "" }, { table: "auth_completions", columns: "app_slug,attempt_id", predicate: "attempt_id IS NOT NULL AND consumed_at IS NULL" }, ])