Merge fix/session-subject-required: require readSubject on the external session owner

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
donghyeon-ka
2026-09-27 13:32:40 +09:00
co-authored by Claude Opus 5.5
10 changed files with 250 additions and 50 deletions
@@ -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<void>;
signOut(): Promise<void>;
@@ -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 () => {},
@@ -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<AuthSessionPort, "subscribe"> &
Partial<Pick<AuthSessionPort, "getState" | "getSubject">>;
queryInvalidation: Pick<QueryInvalidationCoordinator, "resetLocal">;
/** Hears about an authenticated session that could not name its subject. */
diagnostics?: DiagnosticsPort;
tokenFactory?: () => string;
participants?: readonly ScopeResetParticipant[];
activateNextGeneration?: () => void | Promise<void>;
@@ -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.
}
}
+10 -8
View File
@@ -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<void>;
signOut(): Promise<void>;
+2
View File
@@ -134,6 +134,7 @@ function toReleaseInfo(manifest: Readonly<ReleaseManifest>): ReleaseInfo {
const EXTERNAL_OWNER_METHODS = Object.freeze([
"readState",
"readSubject",
"subscribe",
"beginSignIn",
"signOut",
@@ -403,6 +404,7 @@ export async function createRuntimeAdapters(
});
const serverStateScope = createServerStateScopeRuntime({
session: authSession,
diagnostics,
queryInvalidation: {
resetLocal: () => serverStateGeneration.resetCurrent(),
},