Files
clean-architecture-frontend…/src/adapters/cross-context-invalidation/browser-cross-context-host.ts
T
DongHyeonkaandClaude Opus 5.5 63ce5f6486 fix(cross-context): report an inactive host and hash the release epoch (Q-6.2-9)
createBrowserCrossContextInvalidationFromHost returned undefined without any
diagnostic when the cache epoch was invalid or secure random was missing, and
bootstrap built the epoch as `release.${releaseId}`, so any release ID with
`+`, `/`, `@` or over the length limit silently turned cross-tab
invalidation off.

- The host factory now reports OPEN/FAILED/NONE with the new reasons
  INVALID_CACHE_EPOCH or SECURE_RANDOM_UNAVAILABLE before returning
  undefined (the zero-topic build still probes nothing and reports nothing).
- New crossContextCacheEpochForRelease() derives `release.<fnv1a-64 hex>`
  from the release ID; bootstrap uses it (one call-site change in
  src/bootstrap/runtime-adapters.ts).
- The observation reason union gains two members (additive); the ops runbook
  lists them.

Verified: two new unit tests failed before (no observation; missing epoch
helper) and pass now. Lane gates, reference-feature and V3 integration tests,
and check:diagnostics pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 13:39:59 +09:00

312 lines
9.8 KiB
TypeScript

import {
isCacheInvalidationOpaqueIdentifier,
type CacheInvalidationTopicDefinition,
} from "../../contracts/cache-invalidation.ts";
import { STORAGE_REGISTRY } from "../../contracts/storage-keys.ts";
import {
createBrowserCrossContextInvalidation,
type BroadcastChannelFacade,
type BroadcastMessageListener,
type BrowserCrossContextInvalidation,
type CrossContextInvalidationObservation,
type StorageEventTargetFacade,
type StoragePulseFacade,
type StoragePulseListener,
} from "./browser-cross-context-invalidation.ts";
export type BrowserCrossContextHostDependencies = Readonly<{
host?: Record<string, unknown>;
cacheEpoch: string;
topics: readonly CacheInvalidationTopicDefinition[];
observe?: (observation: CrossContextInvalidationObservation) => void;
}>;
type NativeBroadcastChannel = Readonly<{
postMessage(value: unknown): void;
addEventListener(type: string, listener: (event: unknown) => void): void;
removeEventListener(
type: string,
listener: (event: unknown) => void,
): void;
close(): void;
}>;
const CHANNEL_NAME = "ca-client-cache-invalidation-v1";
// N-09. The registry owns the physical-key policy for the pulse.
const STORAGE_PULSE_KEY =
STORAGE_REGISTRY.CACHE_INVALIDATION_PULSE.physicalKey;
/**
* Q-6.2-9. A release ID may hold any character (`1.2.3+sha.abc`, `feature/x`,
* `app@1.2.3`) and any length, but a cache epoch is an opaque identifier. The
* epoch is a stable 64-bit FNV-1a digest of the ID, so every tab of one release
* agrees on it and it always passes the wire rule.
*/
export function crossContextCacheEpochForRelease(releaseId: string): string {
let hash = 0xcbf29ce484222325n;
for (const byte of new TextEncoder().encode(releaseId)) {
hash = ((hash ^ BigInt(byte)) * 0x100000001b3n) & 0xffffffffffffffffn;
}
return `release.${hash.toString(16).padStart(16, "0")}`;
}
/**
* Captures native capabilities without allowing a SecurityError getter or a
* missing random source to fail application boot.
*/
export function createBrowserCrossContextInvalidationFromHost(
dependencies: BrowserCrossContextHostDependencies,
): BrowserCrossContextInvalidation | undefined {
// A zero-feature build owns no cross-context invalidation runtime. Preserve
// that property strictly: do not even probe browser capability getters.
if (dependencies.topics.length === 0) return undefined;
const host =
dependencies.host ??
(globalThis as unknown as Record<string, unknown>);
// Q-6.2-9. Ending inactive is reported, so cross-tab invalidation is never
// switched off without a diagnostic.
const inactive = (
reason: "INVALID_CACHE_EPOCH" | "SECURE_RANDOM_UNAVAILABLE",
): undefined => {
try {
dependencies.observe?.(
Object.freeze({
operation: "OPEN" as const,
outcome: "FAILED" as const,
transport: "NONE" as const,
reason,
}),
);
} catch {
// Diagnostics cannot change the capability decision.
}
return undefined;
};
if (
!isCacheInvalidationOpaqueIdentifier(dependencies.cacheEpoch)
) {
return inactive("INVALID_CACHE_EPOCH");
}
const createOpaqueId = randomIdFactory(host);
if (!createOpaqueId) return inactive("SECURE_RANDOM_UNAVAILABLE");
const sourceId = createOpaqueId("tab");
const sourceEpoch = createOpaqueId("page");
if (!sourceId || !sourceEpoch) {
return inactive("SECURE_RANDOM_UNAVAILABLE");
}
const capturedLocalStorage = captureLocalStorage(host);
return createBrowserCrossContextInvalidation({
channelName: CHANNEL_NAME,
storagePulseKey: STORAGE_PULSE_KEY,
sourceId,
sourceEpoch,
cacheEpoch: dependencies.cacheEpoch,
topics: dependencies.topics,
createEventId: () => {
const eventId = createOpaqueId("event");
if (!eventId) throw new TypeError("Secure random is unavailable.");
return eventId;
},
createBroadcastChannel: broadcastFactory(host),
// N-09. One capture, one identity: the write facade and the event
// validator must agree about which Storage object they trust. Reading the
// getter twice would let a hostile host return a different object.
storage: capturedLocalStorage
? storageFacade(capturedLocalStorage)
: undefined,
storageEvents: storageEventTarget(host, capturedLocalStorage),
observe: dependencies.observe,
});
}
function safeGet(
target: Record<string, unknown>,
property: string,
): unknown {
try {
return Reflect.get(target, property);
} catch {
return undefined;
}
}
function randomIdFactory(
host: Record<string, unknown>,
): ((prefix: string) => string | null) | undefined {
const cryptoCandidate = safeGet(host, "crypto");
if (!cryptoCandidate || typeof cryptoCandidate !== "object") {
return undefined;
}
const randomUuid = safeGet(
cryptoCandidate as Record<string, unknown>,
"randomUUID",
);
if (typeof randomUuid !== "function") return undefined;
return (prefix) => {
try {
const value = Reflect.apply(randomUuid, cryptoCandidate, []);
if (typeof value !== "string") return null;
const candidate = `${prefix}.${value}`;
return isCacheInvalidationOpaqueIdentifier(candidate)
? candidate
: null;
} catch {
return null;
}
};
}
function broadcastFactory(
host: Record<string, unknown>,
):
| ((name: string) => BroadcastChannelFacade)
| undefined {
const Constructor = safeGet(host, "BroadcastChannel");
if (typeof Constructor !== "function") return undefined;
return (name) => {
const candidate = Reflect.construct(Constructor, [name]) as unknown;
if (!isNativeBroadcastChannel(candidate)) {
throw new TypeError("BroadcastChannel is incompatible.");
}
const listenerBindings = new Map<
BroadcastMessageListener,
(event: unknown) => void
>();
return Object.freeze({
postMessage(value: unknown) {
candidate.postMessage(value);
},
addEventListener(
_type: "message",
listener: BroadcastMessageListener,
) {
const bound = (event: unknown) => {
listener({
data:
event && typeof event === "object"
? safeGet(
event as Record<string, unknown>,
"data",
)
: undefined,
});
};
listenerBindings.set(listener, bound);
candidate.addEventListener("message", bound);
},
removeEventListener(
_type: "message",
listener: BroadcastMessageListener,
) {
const bound = listenerBindings.get(listener);
if (!bound) return;
listenerBindings.delete(listener);
candidate.removeEventListener("message", bound);
},
close() {
listenerBindings.clear();
candidate.close();
},
});
};
}
function isNativeBroadcastChannel(
value: unknown,
): value is NativeBroadcastChannel {
if (!value || typeof value !== "object") return false;
const candidate = value as Record<string, unknown>;
return ["postMessage", "addEventListener", "removeEventListener", "close"].every(
(method) => typeof safeGet(candidate, method) === "function",
);
}
function captureLocalStorage(
host: Record<string, unknown>,
): object | undefined {
const candidate = safeGet(host, "localStorage");
return candidate && typeof candidate === "object" ? candidate : undefined;
}
function storageFacade(
candidate: object,
): StoragePulseFacade | undefined {
const record = candidate as Record<string, unknown>;
const setItem = safeGet(record, "setItem");
const removeItem = safeGet(record, "removeItem");
if (typeof setItem !== "function" || typeof removeItem !== "function") {
return undefined;
}
return Object.freeze({
setItem(key, value) {
Reflect.apply(setItem, candidate, [key, value]);
},
removeItem(key) {
Reflect.apply(removeItem, candidate, [key]);
},
});
}
function storageEventTarget(
host: Record<string, unknown>,
expectedLocalStorage: object | undefined,
): StorageEventTargetFacade | undefined {
const addEventListener = safeGet(host, "addEventListener");
const removeEventListener = safeGet(host, "removeEventListener");
if (
typeof addEventListener !== "function" ||
typeof removeEventListener !== "function"
) {
return undefined;
}
const bindings = new Map<
StoragePulseListener,
(event: unknown) => void
>();
return Object.freeze({
addEventListener(_type: "storage", listener: StoragePulseListener) {
const bound = (event: unknown) => {
if (!event || typeof event !== "object") {
listener({
key: null,
newValue: null,
storageArea: "OTHER_OR_UNKNOWN",
});
return;
}
const record = event as Record<string, unknown>;
const key = safeGet(record, "key");
const newValue = safeGet(record, "newValue");
const storageArea = safeGet(record, "storageArea");
listener({
key: typeof key === "string" ? key : null,
newValue: typeof newValue === "string" ? newValue : null,
// Compared by object identity against the captured area, never by
// shape or by re-reading `host.localStorage`.
storageArea:
expectedLocalStorage !== undefined &&
storageArea === expectedLocalStorage
? "EXPECTED_LOCAL_STORAGE"
: "OTHER_OR_UNKNOWN",
});
};
bindings.set(listener, bound);
Reflect.apply(addEventListener, host, ["storage", bound]);
},
removeEventListener(
_type: "storage",
listener: StoragePulseListener,
) {
const bound = bindings.get(listener);
if (!bound) return;
bindings.delete(listener);
Reflect.apply(removeEventListener, host, ["storage", bound]);
},
});
}