From c6300e9d40217e824839e6490ce5898d7583d6cb Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 24 Sep 2026 16:25:22 +0900 Subject: [PATCH] feat(auth): require readSubject so a token refresh keeps server state An external owner without readSubject made every authenticated notification (every token refresh) abort requests and clear the server-state cache. readSubject is now a required owner method and getSubject a required SessionGateway method. - ExternalSessionOwner.readSubject(): required; the host owner check (EXTERNAL_OWNER_METHODS) rejects an owner without it, so the session fails closed as integration-failed like any other missing method. - SessionGateway.getSubject(): required. Anonymous and unavailable adapters return null; demo already returned its fixed user. - Scope runtime: same (state, subject) still skips the fence; a state or subject change still fences. An authenticated session with a null/empty subject still fences (fail closed) and now records cache.operation.failed {operation: SCOPE_FENCE, reason: SUBJECT_MISSING} once per fence. Bootstrap passes diagnostics in. - Docs: starter-experience external owner section and port comments describe what readSubject returns, the fail-closed diagnostic and a migration note. RED before the change (vitest tests/unit/server-state-scope-runtime.test.ts tests/unit/runtime-adapters.test.ts): 4 failed | 31 passed - fails closed when the owner lacks readSubject: expected 'authenticated' to be 'integration-failed' - fences and reports SUBJECT_MISSING ... null / empty subject, and the external owner whose readSubject returns null: expected [] to deeply equal [[{ level: 'warn', ... }]] - type level: an owner literal without readSubject compiled (tsc exit 0). The new @ts-expect-error pin fails check:types:test with TS2578 if readSubject becomes optional again. Pins that stayed green: same-subject token refresh keeps the cache, subject change fences, sign-out fences, owner missing readState is rejected. GREEN: check:architecture, check:types:app, check:types:test, lint, test:unit (2084), test:component (182), test:reference-feature (59), test:integration (151), verify:documentation, check:diagnostics, check:ci all pass. BREAKING: external auth owners must implement readSubject(); code that implements AuthSessionPort/SessionGateway directly must implement getSubject(). Co-Authored-By: Claude Opus 5.5 --- docs/architecture/starter-experience.md | 34 ++++-- src/adapters/auth/external-session-adapter.ts | 11 +- .../query-cache/server-state-scope-runtime.ts | 51 +++++--- src/application/ports/auth-session-port.ts | 18 +-- src/bootstrap/runtime-adapters.ts | 2 + tests/integration/auth-recovery.test.ts | 1 + tests/integration/http-client.test.ts | 2 + tests/unit/auth-session-adapter.test.ts | 23 ++++ tests/unit/runtime-adapters.test.ts | 45 +++++++ tests/unit/server-state-scope-runtime.test.ts | 113 ++++++++++++++++-- 10 files changed, 250 insertions(+), 50 deletions(-) diff --git a/docs/architecture/starter-experience.md b/docs/architecture/starter-experience.md index ab757891..34bdff73 100644 --- a/docs/architecture/starter-experience.md +++ b/docs/architecture/starter-experience.md @@ -49,23 +49,35 @@ remain opaque to the application and presentation layers. - `external`: delegates to `globalThis.__CA_FRONTEND_AUTH_OWNER__` - missing/invalid external owner: fails closed as `integration-failed` -An external owner implements `readState`, `subscribe`, `beginSignIn`, -`signOut`, `attachCredential`, `recoverSession`, and -`notifyUnauthenticated`. It owns token acquisition and storage. +An external owner implements `readState`, `readSubject`, `subscribe`, +`beginSignIn`, `signOut`, `attachCredential`, `recoverSession`, and +`notifyUnauthenticated`. It owns token acquisition and storage. An owner that +lacks any of these methods is rejected, and the session fails closed as +`integration-failed`. -The owner may also implement `readSubject()`. The server-state cache is cleared -only when the session state or the subject changes, so a token refresh for the -same user keeps cached data. `readSubject()` must return: +`readSubject()` is required. The server-state cache is cleared only when the +session state or the subject changes, so a token refresh for the same user +keeps cached data. `readSubject()` must return: - an opaque, non-empty string that stays the same for one user across token - refreshes and differs between users, such as a hashed account id + refreshes and differs between users: the OIDC `sub` claim, Supabase + `session.user.id`, or Firebase `user.uid` - `null` when nobody is signed in - never an access token, refresh token, or any other credential -Without `readSubject()` (or when it returns `null` or `""` while -authenticated), the runtime cannot tell a refresh from an account switch, so -every notification from an authenticated owner clears server state. This is the -safe default. The `demo` adapter reports one fixed demo user as its subject. +If `readSubject()` returns `null` or `""` while the owner reports +`authenticated`, the runtime cannot tell a refresh from an account switch. It +fails closed: every such notification clears server state, and each one records +the `cache.operation.failed` diagnostic with `operation: SCOPE_FENCE` and +`reason: SUBJECT_MISSING`. Seeing that diagnostic means the owner is not +reporting its subject. The `demo` adapter reports one fixed demo user as its +subject. + +Migration: `readSubject()` used to be optional. An owner written for an earlier +release must add it; without it the owner is rejected at startup (the session +becomes `integration-failed`) and a TypeScript owner no longer compiles +against `ExternalSessionOwner`. A code path that implements `AuthSessionPort` +or `SessionGateway` directly must add `getSubject()` the same way. ## Extending the starter diff --git a/src/adapters/auth/external-session-adapter.ts b/src/adapters/auth/external-session-adapter.ts index c50afe93..67adb93b 100644 --- a/src/adapters/auth/external-session-adapter.ts +++ b/src/adapters/auth/external-session-adapter.ts @@ -10,10 +10,11 @@ import { CREDENTIAL_HEADER_NAMES } from "../../contracts/rest-profiles.ts"; export type ExternalSessionOwner = Readonly<{ readState(): SessionState; /** - * Opaque, stable per-user id, never a token; see `SessionGateway.getSubject`. - * Without it every authenticated notification clears server state. + * Required. Opaque, stable per-user id, never a token (OIDC `sub`, Supabase + * `session.user.id`, Firebase `user.uid`); `null` when nobody is signed in. + * See `SessionGateway.getSubject` for what a missing subject costs. */ - readSubject?(): string | null; + readSubject(): string | null; subscribe(listener: () => void): () => void; beginSignIn(returnTo?: string): Promise; signOut(): Promise; @@ -60,7 +61,7 @@ export function createExternalAuthSessionAdapter( ): AuthSessionPort { return Object.freeze({ getState: () => owner.readState(), - getSubject: () => owner.readSubject?.() ?? null, + getSubject: () => owner.readSubject(), subscribe: (listener) => owner.subscribe(listener), beginSignIn: (returnTo) => owner.beginSignIn(returnTo), signOut: () => owner.signOut(), @@ -85,6 +86,7 @@ const EMPTY_PATCH = Object.freeze({ headers: Object.freeze({}) }); export function createAnonymousSessionAdapter(): AuthSessionPort { return createExternalAuthSessionAdapter({ readState: () => "unauthenticated", + readSubject: () => null, subscribe: () => () => {}, beginSignIn: async () => {}, signOut: async () => {}, @@ -155,6 +157,7 @@ export function createDemoSessionAdapter( export function createUnavailableSessionAdapter(): AuthSessionPort { return Object.freeze({ getState: () => "integration-failed", + getSubject: () => null, subscribe: () => () => {}, beginSignIn: async () => {}, signOut: async () => {}, diff --git a/src/adapters/query-cache/server-state-scope-runtime.ts b/src/adapters/query-cache/server-state-scope-runtime.ts index 208de0b9..947355c7 100644 --- a/src/adapters/query-cache/server-state-scope-runtime.ts +++ b/src/adapters/query-cache/server-state-scope-runtime.ts @@ -1,4 +1,5 @@ import type { AuthSessionPort } from "../../application/ports/auth-session-port.ts"; +import type { DiagnosticsPort } from "../../application/ports/diagnostics-port.ts"; import type { QueryInvalidationCoordinator } from "../../contracts/query-invalidation.ts"; import { createRuntimeIdentityRegistry, @@ -31,6 +32,8 @@ export type ServerStateScopeDependencies = Readonly<{ session: Pick & Partial>; queryInvalidation: Pick; + /** Hears about an authenticated session that could not name its subject. */ + diagnostics?: DiagnosticsPort; tokenFactory?: () => string; participants?: readonly ScopeResetParticipant[]; activateNextGeneration?: () => void | Promise; @@ -54,7 +57,7 @@ export function createServerStateScopeRuntime( let phase: ClientScopePhase = "READY"; let disposed = false; let resetChain = Promise.resolve(); - let sessionIdentity = readSessionIdentity(dependencies.session); + let sessionIdentity = readSessionIdentity(dependencies.session).identity; function createSnapshot(): CacheScopeSnapshot { const capturedGeneration = generation; @@ -98,15 +101,18 @@ export function createServerStateScopeRuntime( // §10.6 is for identity-affecting changes only. A notification that keeps // (state, subject) — a token refresh, a repeated sign-out — must not abort // requests and clear the cache. A FAILED scope still retries its reset. - const nextSessionIdentity = readSessionIdentity(dependencies.session); + const next = readSessionIdentity(dependencies.session); if ( - nextSessionIdentity !== null && - nextSessionIdentity === sessionIdentity && + next.identity !== null && + next.identity === sessionIdentity && phase !== "FAILED" ) { return; } - sessionIdentity = nextSessionIdentity; + // The fence below is correct but costly: an owner that cannot name its + // subject clears the cache on every token refresh. Make that visible. + if (next.subjectMissing) reportSubjectMissing(dependencies.diagnostics); + sessionIdentity = next.identity; const previousIdentities = identities; const previousGeneration = generation; @@ -204,24 +210,41 @@ export function createServerStateScopeRuntime( } /** - * `null` means the identity cannot be proven unchanged: no `getState`, a - * throwing owner, or an authenticated session without a non-empty subject. - * Those always fence, which keeps an account switch from reusing the previous - * cache. + * A `null` identity cannot be proven unchanged: no `getState`, a throwing + * owner, or an authenticated session without a non-empty subject (the last one + * is flagged `subjectMissing`). Those always fence, which keeps an account + * switch from reusing the previous cache. */ function readSessionIdentity( session: ServerStateScopeDependencies["session"], -): string | null { +): Readonly<{ identity: string | null; subjectMissing: boolean }> { try { const state = session.getState?.(); - if (state === undefined) return null; + if (state === undefined) return { identity: null, subjectMissing: false }; const subject = session.getSubject?.(); const knownSubject = typeof subject === "string" && subject !== "" ? subject : null; - if (state === "authenticated" && knownSubject === null) return null; - return JSON.stringify([state, knownSubject]); + if (state === "authenticated" && knownSubject === null) { + return { identity: null, subjectMissing: true }; + } + return { + identity: JSON.stringify([state, knownSubject]), + subjectMissing: false, + }; } catch { - return null; + return { identity: null, subjectMissing: false }; + } +} + +function reportSubjectMissing(diagnostics: DiagnosticsPort | undefined): void { + try { + diagnostics?.record({ + level: "warn", + eventId: "cache.operation.failed", + context: { operation: "SCOPE_FENCE", reason: "SUBJECT_MISSING" }, + }); + } catch { + // The fence must run whether or not diagnostics works. } } diff --git a/src/application/ports/auth-session-port.ts b/src/application/ports/auth-session-port.ts index f3ae46f5..e2f56f78 100644 --- a/src/application/ports/auth-session-port.ts +++ b/src/application/ports/auth-session-port.ts @@ -7,15 +7,17 @@ export type SessionState = export type SessionGateway = Readonly<{ getState(): SessionState; /** - * Optional opaque identifier of the signed-in subject. The server-state scope - * fences only when (state, subject) changes, so a token refresh does not clear - * the cache. Return a non-empty string that is stable for one user across - * refreshes and differs between users (for example a hashed account id), or - * `null` when nobody is signed in. Never return a token or other credential. - * An authenticated session that returns `null`, `""` or omits this is treated - * as possibly switched: every notification fences and clears server state. + * Opaque identifier of the signed-in subject. The server-state scope fences + * only when (state, subject) changes, so a token refresh does not clear the + * cache. Return a non-empty string that is stable for one user across + * refreshes and differs between users (OIDC `sub`, Supabase + * `session.user.id`, Firebase `user.uid`), or `null` when nobody is signed + * in. Never return a token or other credential. An authenticated session that + * returns `null` or `""` is treated as possibly switched: every notification + * fences, clears server state and records `cache.operation.failed` with + * reason `SUBJECT_MISSING`. */ - getSubject?(): string | null; + getSubject(): string | null; subscribe(listener: () => void): () => void; beginSignIn(returnTo?: string): Promise; signOut(): Promise; diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 2025e0ed..48d70cb3 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -134,6 +134,7 @@ function toReleaseInfo(manifest: Readonly): ReleaseInfo { const EXTERNAL_OWNER_METHODS = Object.freeze([ "readState", + "readSubject", "subscribe", "beginSignIn", "signOut", @@ -388,6 +389,7 @@ export async function createRuntimeAdapters( }); const serverStateScope = createServerStateScopeRuntime({ session: authSession, + diagnostics, queryInvalidation: { resetLocal: () => serverStateGeneration.resetCurrent(), }, diff --git a/tests/integration/auth-recovery.test.ts b/tests/integration/auth-recovery.test.ts index 05f66299..28392f86 100644 --- a/tests/integration/auth-recovery.test.ts +++ b/tests/integration/auth-recovery.test.ts @@ -52,6 +52,7 @@ function createOwner( ): ExternalSessionOwner { return { readState: () => "authenticated", + readSubject: () => "user-a", subscribe: () => () => {}, beginSignIn: async () => {}, signOut: async () => {}, diff --git a/tests/integration/http-client.test.ts b/tests/integration/http-client.test.ts index 06ef88b7..bb8eb096 100644 --- a/tests/integration/http-client.test.ts +++ b/tests/integration/http-client.test.ts @@ -78,6 +78,7 @@ describe("shared HTTP client", () => { clock, authSession: { getState: () => "authenticated", + getSubject: () => "user-a", subscribe: () => () => {}, beginSignIn: async () => {}, signOut: async () => {}, @@ -125,6 +126,7 @@ describe("shared HTTP client", () => { clock: { now: () => 0, sleep: async () => {} }, authSession: { getState: () => "authenticated", + getSubject: () => "user-a", subscribe: () => () => {}, beginSignIn: async () => {}, signOut: async () => {}, diff --git a/tests/unit/auth-session-adapter.test.ts b/tests/unit/auth-session-adapter.test.ts index bb600de7..0078c558 100644 --- a/tests/unit/auth-session-adapter.test.ts +++ b/tests/unit/auth-session-adapter.test.ts @@ -4,12 +4,14 @@ import { createAnonymousSessionAdapter, createDemoSessionAdapter, createExternalAuthSessionAdapter, + type ExternalSessionOwner, } from "../../src/adapters/auth/external-session-adapter.ts"; describe("external AuthSessionPort adapter", () => { it("attaches opaque credentials without exposing a token-shaped session", async () => { const adapter = createExternalAuthSessionAdapter({ readState: () => "authenticated", + readSubject: () => "user-a", subscribe: () => () => {}, beginSignIn: async () => {}, signOut: async () => {}, @@ -27,6 +29,7 @@ describe("external AuthSessionPort adapter", () => { }); expect(patch.headers.authorization).toBe("Bearer opaque"); expect(adapter.getState()).toBe("authenticated"); + expect(adapter.getSubject()).toBe("user-a"); expect(adapter).not.toHaveProperty("accessToken"); expect(adapter).not.toHaveProperty("refreshToken"); }); @@ -34,6 +37,7 @@ describe("external AuthSessionPort adapter", () => { it("fails invalid recovery states closed", async () => { const adapter = createExternalAuthSessionAdapter({ readState: () => "authenticated", + readSubject: () => "user-a", subscribe: () => () => {}, beginSignIn: async () => {}, signOut: async () => {}, @@ -49,6 +53,7 @@ describe("external AuthSessionPort adapter", () => { it("rejects credential patches that can alter transport-owned headers", async () => { const adapter = createExternalAuthSessionAdapter({ readState: () => "authenticated", + readSubject: () => "user-a", subscribe: () => () => {}, beginSignIn: async () => {}, signOut: async () => {}, @@ -71,6 +76,7 @@ describe("external AuthSessionPort adapter", () => { it("rejects credential headers that differ only in case instead of merging them", async () => { const adapter = createExternalAuthSessionAdapter({ readState: () => "authenticated", + readSubject: () => "user-a", subscribe: () => () => {}, beginSignIn: async () => {}, signOut: async () => {}, @@ -90,8 +96,25 @@ describe("external AuthSessionPort adapter", () => { ).rejects.toThrow("forbidden credential patch"); }); + it("requires the owner to name its subject", () => { + // An owner without readSubject would clear server state on every token + // refresh; check:types:test fails if this ever compiles again. + // @ts-expect-error readSubject is a required owner method. + const owner: ExternalSessionOwner = { + readState: () => "authenticated", + subscribe: () => () => {}, + beginSignIn: async () => {}, + signOut: async () => {}, + attachCredential: async () => ({ headers: {} }), + recoverSession: async () => "restored", + notifyUnauthenticated: () => {}, + }; + expect(owner).not.toHaveProperty("readSubject"); + }); + it("provides a safe anonymous adapter", async () => { const adapter = createAnonymousSessionAdapter(); + expect(adapter.getSubject()).toBeNull(); expect(adapter.getState()).toBe("unauthenticated"); await expect(adapter.recover()).resolves.toBe("no-session"); }); diff --git a/tests/unit/runtime-adapters.test.ts b/tests/unit/runtime-adapters.test.ts index 2553a34c..7014de97 100644 --- a/tests/unit/runtime-adapters.test.ts +++ b/tests/unit/runtime-adapters.test.ts @@ -242,6 +242,51 @@ describe("runtime adapter composition", () => { expect(adapters.outputPorts.session.getState()).toBe("integration-failed"); }); + describe("installed external auth owner shape", () => { + const externalRuntime: Runtime = { + ...runtime, + config: { ...runtime.config, AUTH_MODE: "external" }, + }; + const completeOwner = () => ({ + readState: () => "authenticated", + readSubject: () => "user-a", + subscribe: () => () => {}, + beginSignIn: async () => {}, + signOut: async () => {}, + attachCredential: async () => ({ headers: {} }), + recoverSession: async () => "no-session", + notifyUnauthenticated: () => {}, + }); + + it("uses an owner that implements every method", async () => { + const adapters = await createRuntimeAdapters({ + runtime: externalRuntime, + release, + host: { __CA_FRONTEND_AUTH_OWNER__: completeOwner() }, + }); + expect(adapters.outputPorts.session.getState()).toBe("authenticated"); + expect(adapters.outputPorts.session.getSubject()).toBe("user-a"); + adapters.infrastructure.dispose(); + }); + + it.each(["readSubject", "readState"])( + "fails closed when the owner lacks %s", + async (method) => { + const owner: Record = completeOwner(); + delete owner[method]; + const adapters = await createRuntimeAdapters({ + runtime: externalRuntime, + release, + host: { __CA_FRONTEND_AUTH_OWNER__: owner }, + }); + expect(adapters.outputPorts.session.getState()).toBe( + "integration-failed", + ); + adapters.infrastructure.dispose(); + }, + ); + }); + it("reports the static selection when no capability override disables it", async () => { const adapters = await createRuntimeAdapters({ runtime, release, host: {} }); diff --git a/tests/unit/server-state-scope-runtime.test.ts b/tests/unit/server-state-scope-runtime.test.ts index 8f3bcd5b..94c0375e 100644 --- a/tests/unit/server-state-scope-runtime.test.ts +++ b/tests/unit/server-state-scope-runtime.test.ts @@ -9,6 +9,7 @@ import { type ServerStateScopeDependencies, } from "../../src/adapters/query-cache/server-state-scope-runtime.ts"; import type { SessionState } from "../../src/application/ports/auth-session-port.ts"; +import type { DiagnosticRecordInput } from "../../src/contracts/diagnostics.ts"; import type { ClientScopeLifecycleEvent } from "../../src/contracts/server-state-scope.ts"; describe("server-state session generation runtime", () => { @@ -228,18 +229,26 @@ describe("identity-affecting session changes only", () => { function scopeFor(session: ServerStateScopeDependencies["session"]) { const resetLocal = vi.fn(async () => {}); + const record = vi.fn<(input: DiagnosticRecordInput) => void>(); const lifecycle: ClientScopeLifecycleEvent[] = []; let tokenSequence = 0; const runtime = createServerStateScopeRuntime({ session, queryInvalidation: { resetLocal }, + diagnostics: { record }, tokenFactory: () => `scope-identity-token-${String(tokenSequence++).padStart(6, "0")}`, }); runtime.subscribeLifecycle((event) => lifecycle.push(event)); - return { runtime, resetLocal, lifecycle }; + return { runtime, resetLocal, record, lifecycle }; } + const SUBJECT_MISSING_RECORD = { + level: "warn", + eventId: "cache.operation.failed", + context: { operation: "SCOPE_FENCE", reason: "SUBJECT_MISSING" }, + }; + it.each([ ["a repeated sign-out", { state: "unauthenticated" as const }], [ @@ -248,7 +257,7 @@ describe("identity-affecting session changes only", () => { ], ])("does not fence, abort or clear on %s", async (_label, identity) => { const fake = fakeSession(identity); - const { runtime, resetLocal, lifecycle } = scopeFor(fake.session); + const { runtime, resetLocal, record, lifecycle } = scopeFor(fake.session); const before = runtime.getSnapshot(); fake.notify(identity); @@ -259,6 +268,7 @@ describe("identity-affecting session changes only", () => { expect(before.isCurrent()).toBe(true); expect(before.signal.aborted).toBe(false); expect(resetLocal).not.toHaveBeenCalled(); + expect(record).not.toHaveBeenCalled(); expect(runtime.getPhase()).toBe("READY"); }); @@ -274,18 +284,13 @@ describe("identity-affecting session changes only", () => { { state: "authenticated" as const, subject: "user-b" }, ], [ - "an authenticated session cannot name its subject", - { state: "authenticated" as const }, - { state: "authenticated" as const }, - ], - [ - "an authenticated session names an empty subject", - { state: "authenticated" as const, subject: "" }, - { state: "authenticated" as const, subject: "" }, + "the user signs out", + { state: "authenticated" as const, subject: "user-a" }, + { state: "unauthenticated" as const }, ], ])("still fences when %s", async (_label, initial, next) => { const fake = fakeSession(initial); - const { runtime, resetLocal, lifecycle } = scopeFor(fake.session); + const { runtime, resetLocal, record, lifecycle } = scopeFor(fake.session); const before = runtime.getSnapshot(); fake.notify(next); @@ -295,6 +300,59 @@ describe("identity-affecting session changes only", () => { expect(lifecycle[0]).toEqual({ kind: "FENCED", previousGeneration: 1 }); await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY")); expect(resetLocal).toHaveBeenCalledOnce(); + expect(record).not.toHaveBeenCalled(); + }); + + it.each([ + ["cannot name its subject", null], + ["names an empty subject", ""], + ])( + "fences and reports SUBJECT_MISSING on every notification when an authenticated session %s", + async (_label, subject) => { + const fake = fakeSession({ state: "authenticated", subject }); + const { runtime, resetLocal, record, lifecycle } = scopeFor(fake.session); + const before = runtime.getSnapshot(); + + fake.notify({ state: "authenticated", subject }); + + expect(before.isCurrent()).toBe(false); + expect(before.signal.aborted).toBe(true); + expect(lifecycle[0]).toEqual({ kind: "FENCED", previousGeneration: 1 }); + await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY")); + expect(record.mock.calls).toEqual([[SUBJECT_MISSING_RECORD]]); + + fake.notify({ state: "authenticated", subject }); + await vi.waitFor(() => expect(resetLocal).toHaveBeenCalledTimes(2)); + expect(record.mock.calls).toEqual([ + [SUBJECT_MISSING_RECORD], + [SUBJECT_MISSING_RECORD], + ]); + + // Signing out is an ordinary fence, not a misbehaving owner. + fake.notify({ state: "unauthenticated" }); + await vi.waitFor(() => expect(resetLocal).toHaveBeenCalledTimes(3)); + expect(record).toHaveBeenCalledTimes(2); + }, + ); + + it("keeps fencing if diagnostics throws while reporting SUBJECT_MISSING", async () => { + const fake = fakeSession({ state: "authenticated", subject: null }); + const runtime = createServerStateScopeRuntime({ + session: fake.session, + queryInvalidation: { resetLocal: async () => {} }, + diagnostics: { + record() { + throw new Error("diagnostics down"); + }, + }, + tokenFactory: () => "scope-diagnostics-token-001", + }); + const before = runtime.getSnapshot(); + + fake.notify({ state: "authenticated", subject: null }); + + expect(before.isCurrent()).toBe(false); + expect(runtime.getPhase()).toBe("FENCED"); }); it("does not fence when the demo session re-announces the same user", async () => { @@ -323,10 +381,11 @@ describe("identity-affecting session changes only", () => { await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY")); }); - it("fences every authenticated notification from an external owner without readSubject", async () => { + it("fences and reports every authenticated notification from an external owner whose readSubject returns null", async () => { let notify: () => void = () => {}; const session = createExternalAuthSessionAdapter({ readState: () => "authenticated", + readSubject: () => null, subscribe(listener) { notify = listener; return () => {}; @@ -337,7 +396,7 @@ describe("identity-affecting session changes only", () => { recoverSession: async () => "no-session", notifyUnauthenticated: () => {}, }); - const { runtime, resetLocal, lifecycle } = scopeFor(session); + const { runtime, resetLocal, record, lifecycle } = scopeFor(session); const before = runtime.getSnapshot(); notify(); @@ -346,6 +405,34 @@ describe("identity-affecting session changes only", () => { expect(lifecycle[0]).toEqual({ kind: "FENCED", previousGeneration: 1 }); await vi.waitFor(() => expect(runtime.getPhase()).toBe("READY")); expect(resetLocal).toHaveBeenCalledOnce(); + expect(record.mock.calls).toEqual([[SUBJECT_MISSING_RECORD]]); + }); + + it("keeps the cache when an external owner refreshes a token for the same subject", async () => { + let notify: () => void = () => {}; + const session = createExternalAuthSessionAdapter({ + readState: () => "authenticated", + readSubject: () => "user-a", + subscribe(listener) { + notify = listener; + return () => {}; + }, + beginSignIn: async () => {}, + signOut: async () => {}, + attachCredential: async () => ({ headers: {} }), + recoverSession: async () => "no-session", + notifyUnauthenticated: () => {}, + }); + const { runtime, resetLocal, record, lifecycle } = scopeFor(session); + const before = runtime.getSnapshot(); + + notify(); + await Promise.resolve(); + + expect(lifecycle).toEqual([]); + expect(before.isCurrent()).toBe(true); + expect(resetLocal).not.toHaveBeenCalled(); + expect(record).not.toHaveBeenCalled(); }); it("retries a failed reset on a notification with the same identity", async () => {