diff --git a/src/adapters/auth/external-session-adapter.ts b/src/adapters/auth/external-session-adapter.ts index 34e519ee..92774f93 100644 --- a/src/adapters/auth/external-session-adapter.ts +++ b/src/adapters/auth/external-session-adapter.ts @@ -112,6 +112,9 @@ export function createDemoSessionAdapter( let state = initialState; const listeners = new Set<() => void>(); const setState = (next: SessionState) => { + // A notification means "the session changed"; repeating the same value + // would make every subscriber redo its work for nothing. + if (next === state) return; state = next; for (const listener of listeners) listener(); }; diff --git a/src/adapters/http/http-execution-v3.ts b/src/adapters/http/http-execution-v3.ts index f8033c70..08f82fec 100644 --- a/src/adapters/http/http-execution-v3.ts +++ b/src/adapters/http/http-execution-v3.ts @@ -134,6 +134,11 @@ export type HttpExecutionOutcome = }> | Readonly<{ kind: "UNAUTHENTICATED"; + /** + * Present only when the server answered 401. Absent means no credential + * existed and nothing was sent; that is not a session verdict. + */ + metadata?: SafeResponseMetadata; effect: "NOT_APPLICABLE" | "NOT_APPLIED" | "MAYBE_APPLIED"; }> | Readonly<{ @@ -1158,6 +1163,7 @@ async function admitResponse( unauthenticated( certaintyForAbandonedAttempt(attemptState, isCommand), isCommand, + metadata, ), "UNAUTHENTICATED", ); @@ -1652,9 +1658,11 @@ function postDispatchEffect(isCommand: boolean): HttpEffectCertainty { function unauthenticated( effect: string, isCommand: boolean, + metadata?: SafeResponseMetadata, ): HttpExecutionOutcome { return Object.freeze({ kind: "UNAUTHENTICATED" as const, + ...(metadata === undefined ? {} : { metadata }), effect: normalizeOptionalEffect(effect, isCommand), }); } diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 83703530..dfa1e1da 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -517,7 +517,10 @@ export async function createRuntimeAdapters( ? {} : { execution: executionContext.execution }), }); - if (outcome.kind === "UNAUTHENTICATED") { + // R-3.2. Only a server 401 is a session verdict. A request refused before + // dispatch for lack of a credential carries no response metadata; telling + // the owner would overwrite a recovering session and re-fence the scope. + if (outcome.kind === "UNAUTHENTICATED" && outcome.metadata !== undefined) { authSession.onUnauthenticated(); } return outcome; diff --git a/tests/features/reference-feature/reference-runtime-composition.test.ts b/tests/features/reference-feature/reference-runtime-composition.test.ts index c71459ce..6f3a2a6a 100644 --- a/tests/features/reference-feature/reference-runtime-composition.test.ts +++ b/tests/features/reference-feature/reference-runtime-composition.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from "vitest"; +import type { DemoSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.ts"; import { createRuntimeAdapters } from "../../../src/bootstrap/runtime-adapters.ts"; import { createRuntimeIdentityRegistry } from "../../../src/contracts/query-keys.ts"; import { bindQuery } from "../../../src/contracts/server-state.ts"; @@ -210,4 +211,59 @@ describe("reference feature runtime composition", () => { expect(safeEvidence).not.toContain("private-idempotency-key"); adapters.infrastructure.dispose(); }); + + /** + * R-3.2. A request refused before dispatch because no credential exists is + * not a session verdict. Reporting it to the owner overwrote a recovering + * session and could loop through the scope fence; only a server 401 may. + */ + it("does not report a request refused before dispatch as a sign-out", async () => { + const fetcher = vi.fn(async () => Response.json([])); + const adapters = await createRuntimeAdapters({ + runtime, + release, + host: {}, + fetcher, + }); + const session = adapters.outputPorts.session as DemoSessionAdapter; + session.setState("recovery-pending"); + await vi.waitFor(() => + expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), + ); + const notifications = vi.fn(); + session.subscribe(notifications); + + await expect( + referenceInput(adapters).listResources({ limit: 20 }), + ).resolves.toMatchObject({ ok: false }); + + expect(fetcher).not.toHaveBeenCalled(); + expect(session.getState()).toBe("recovery-pending"); + expect(notifications).not.toHaveBeenCalled(); + adapters.infrastructure.dispose(); + }); + + it("still signs out when the server answers 401", async () => { + const fetcher = vi.fn( + async () => new Response(null, { status: 401 }), + ); + const adapters = await createRuntimeAdapters({ + runtime, + release, + host: {}, + fetcher, + }); + await adapters.outputPorts.session.beginSignIn(); + await vi.waitFor(() => + expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"), + ); + + await expect( + referenceInput(adapters).listResources({ limit: 20 }), + ).resolves.toMatchObject({ ok: false }); + + expect(fetcher).toHaveBeenCalledOnce(); + expect(adapters.outputPorts.session.getState()).toBe("unauthenticated"); + adapters.infrastructure.dispose(); + }); }); diff --git a/tests/unit/auth-session-adapter.test.ts b/tests/unit/auth-session-adapter.test.ts index 9895aff4..9832825d 100644 --- a/tests/unit/auth-session-adapter.test.ts +++ b/tests/unit/auth-session-adapter.test.ts @@ -89,4 +89,25 @@ describe("external AuthSessionPort adapter", () => { expect(notifications).toBe(2); unsubscribe(); }); + + it("does not notify when the demo state is set to its current value", async () => { + const adapter = createDemoSessionAdapter("recovery-pending"); + let notifications = 0; + adapter.subscribe(() => { + notifications += 1; + }); + + adapter.setState("recovery-pending"); + expect(notifications).toBe(0); + + adapter.setState("authenticated"); + await adapter.beginSignIn(); + expect(notifications).toBe(1); + + adapter.onUnauthenticated(); + adapter.onUnauthenticated(); + await adapter.signOut(); + expect(adapter.getState()).toBe("unauthenticated"); + expect(notifications).toBe(2); + }); }); diff --git a/tests/unit/http-execution-v3.test.ts b/tests/unit/http-execution-v3.test.ts index 8d4b5852..fbc5f5aa 100644 --- a/tests/unit/http-execution-v3.test.ts +++ b/tests/unit/http-execution-v3.test.ts @@ -137,6 +137,32 @@ describe("runtime request deadline ceiling", () => { }); describe("descriptor-driven HTTP execution lifetime", () => { + it("tells a missing credential apart from a server 401", async () => { + const refusedFetcher = vi.fn(); + const refused = await createContractHttpExecutor({ + baseUrl: "https://api.example/", + maxRetryAttempts: 0, + attachCredentials: () => ({ kind: "UNAUTHENTICATED" }), + fetcher: refusedFetcher, + }).execute(installed, { limit: 20 }, { routeId: ROUTE_ID, scope }); + const rejected = await createContractHttpExecutor({ + baseUrl: "https://api.example/", + maxRetryAttempts: 0, + attachCredentials: () => ({ kind: "READY", headers: {} }), + fetcher: async () => new Response(null, { status: 401 }), + }).execute(installed, { limit: 20 }, { routeId: ROUTE_ID, scope }); + + // Only the server's answer carries response metadata; the composition + // root reports just that one to the session owner. + expect(refusedFetcher).not.toHaveBeenCalled(); + expect(refused).toEqual({ kind: "UNAUTHENTICATED", effect: "NOT_APPLICABLE" }); + expect(rejected).toMatchObject({ + kind: "UNAUTHENTICATED", + effect: "NOT_APPLICABLE", + metadata: { status: 401 }, + }); + }); + it("normalizes a read-side 429 to the non-applicable effect vocabulary", async () => { const executor = createContractHttpExecutor({ baseUrl: "https://api.example/",