fix: harden bounded state sidecars

N-05: the conditional-validator key was a colon join over components that may
themselves contain colons, so two distinct valid bindings could collide and one
definition's ETag could be prepared for another. The key is now a validated,
byte-bounded fixed tuple encoded with JSON.stringify.

N-09: capture localStorage exactly once and compare StorageEvent.storageArea
against that object identity, so a pulse from sessionStorage or any other area
is rejected instead of matching on key and value alone. The pulse key is
registered in the storage registry as CACHE_INVALIDATION_PULSE.

N-10: race loadPage against the caller signal and re-check before observing a
page, so a non-cooperative loader can neither hold loadAll forever nor have a
post-abort completion accumulated into a successful result.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-08-13 23:35:48 +09:00
co-authored by Claude Opus 5
parent b893d95b36
commit 4fe924ee0f
9 changed files with 261 additions and 19 deletions
@@ -2,6 +2,7 @@ import {
isCacheInvalidationOpaqueIdentifier,
type CacheInvalidationTopicDefinition,
} from "../../contracts/cache-invalidation.ts";
import { STORAGE_REGISTRY } from "../../contracts/storage-keys.ts";
import {
createBrowserCrossContextInvalidation,
type BroadcastChannelFacade,
@@ -31,8 +32,9 @@ type NativeBroadcastChannel = Readonly<{
}>;
const CHANNEL_NAME = "ca-client-cache-invalidation-v1";
// N-09. The registry owns the physical-key policy for the pulse.
const STORAGE_PULSE_KEY =
"ca-frontend:cache-invalidation:v1:pulse";
STORAGE_REGISTRY.CACHE_INVALIDATION_PULSE.physicalKey;
/**
* Captures native capabilities without allowing a SecurityError getter or a
@@ -59,6 +61,8 @@ export function createBrowserCrossContextInvalidationFromHost(
const sourceEpoch = createOpaqueId("page");
if (!sourceId || !sourceEpoch) return undefined;
const capturedLocalStorage = captureLocalStorage(host);
return createBrowserCrossContextInvalidation({
channelName: CHANNEL_NAME,
storagePulseKey: STORAGE_PULSE_KEY,
@@ -72,8 +76,13 @@ export function createBrowserCrossContextInvalidationFromHost(
return eventId;
},
createBroadcastChannel: broadcastFactory(host),
storage: storageFacade(host),
storageEvents: storageEventTarget(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,
});
}
@@ -182,11 +191,16 @@ function isNativeBroadcastChannel(
);
}
function storageFacade(
function captureLocalStorage(
host: Record<string, unknown>,
): StoragePulseFacade | undefined {
): object | undefined {
const candidate = safeGet(host, "localStorage");
if (!candidate || typeof candidate !== "object") return undefined;
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");
@@ -205,6 +219,7 @@ function storageFacade(
function storageEventTarget(
host: Record<string, unknown>,
expectedLocalStorage: object | undefined,
): StorageEventTargetFacade | undefined {
const addEventListener = safeGet(host, "addEventListener");
const removeEventListener = safeGet(host, "removeEventListener");
@@ -222,15 +237,27 @@ function storageEventTarget(
addEventListener(_type: "storage", listener: StoragePulseListener) {
const bound = (event: unknown) => {
if (!event || typeof event !== "object") {
listener({ key: null, newValue: null });
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);
@@ -98,6 +98,13 @@ export type StoragePulseFacade = Readonly<{
export type StoragePulseEvent = Readonly<{
key: string | null;
newValue: string | null;
/**
* N-09. A `storage` event fires for every `Storage` area in the context.
* Matching only key and value cannot prove the write came from the
* localStorage this runtime actually captured, so the host classifies the
* native `storageArea` by object identity and the core admits one value.
*/
storageArea: "EXPECTED_LOCAL_STORAGE" | "OTHER_OR_UNKNOWN";
}>;
export type StoragePulseListener = (event: StoragePulseEvent) => void;
@@ -179,6 +186,7 @@ export function createBrowserCrossContextInvalidation(
const receiveStorage: StoragePulseListener = (event) => {
if (
closed ||
event.storageArea !== "EXPECTED_LOCAL_STORAGE" ||
event.key !== dependencies.storagePulseKey ||
typeof event.newValue !== "string"
) {
@@ -32,6 +32,26 @@ type ValidatorRow = {
generation: number;
};
type ConditionalValidatorKeyTuple = readonly [
scopeFingerprint: string,
definitionId: string,
identityToken: string,
representationVersion: number,
];
/** The store is a trust boundary, so key components are validated and bounded. */
const MAX_KEY_COMPONENT_BYTES = 512;
const KEY_COMPONENT_ENCODER = new TextEncoder();
function isBoundedKeyComponent(value: unknown): value is string {
return (
typeof value === "string" &&
value.length > 0 &&
KEY_COMPONENT_ENCODER.encode(value).byteLength <=
MAX_KEY_COMPONENT_BYTES
);
}
export function createConditionalValidatorStore(
maxEntries = 1_024,
): ConditionalValidatorStore {
@@ -40,22 +60,31 @@ export function createConditionalValidatorStore(
}
const rows = new Map<string, ValidatorRow>();
/**
* N-05. A delimiter join is not injective here: `definitionId`,
* `identityToken` and the scope fingerprint may all contain the delimiter, so
* two distinct valid bindings could encode to the same key and one
* definition's ETag could be sent for another. The key is a validated fixed
* tuple encoded with `JSON.stringify`, which escapes the separators.
*/
function key(binding: ConditionalValidatorBinding): string | null {
if (
!binding.scope.isCurrent() ||
!binding.definitionId ||
!isBoundedKeyComponent(binding.scope.fingerprint) ||
!isBoundedKeyComponent(binding.definitionId) ||
!/^[A-Za-z0-9._:-]{16,128}$/.test(binding.identityToken) ||
!Number.isSafeInteger(binding.representationVersion) ||
binding.representationVersion < 1
) {
return null;
}
return [
const tuple: ConditionalValidatorKeyTuple = [
binding.scope.fingerprint,
binding.definitionId,
binding.identityToken,
binding.representationVersion,
].join(":");
];
return JSON.stringify(tuple);
}
return Object.freeze({
@@ -6,6 +6,36 @@ import type {
} from "../../contracts/cursor-pagination.ts";
import { createFailure } from "../../contracts/errors.ts";
const ABORTED = Symbol("PAGINATION_ABORTED");
/**
* Resolves as soon as the operation settles or the signal aborts, whichever
* comes first. A late operation result is observed and discarded, never thrown
* as an unhandled rejection.
*/
async function raceAbort<Value>(
operation: Promise<Value>,
signal: AbortSignal | undefined,
): Promise<Value | typeof ABORTED> {
operation.catch(() => {});
if (!signal) return await operation;
if (signal.aborted) return ABORTED;
return await new Promise<Value | typeof ABORTED>((resolve) => {
const onAbort = () => resolve(ABORTED);
signal.addEventListener("abort", onAbort, { once: true });
operation.then(
(value) => {
signal.removeEventListener("abort", onAbort);
resolve(value);
},
() => {
signal.removeEventListener("abort", onAbort);
resolve(ABORTED);
},
);
});
}
export function createCursorPaginationRuntime<Value>(dependencies: Readonly<{
definitionId: string;
profile: CursorPaginationProfile;
@@ -29,9 +59,21 @@ export function createCursorPaginationRuntime<Value>(dependencies: Readonly<{
if (context.signal?.aborted) {
return failure("REQUEST_ABORTED", "PAGINATION_ABORTED");
}
const result = await dependencies.loadPage(cursor, context);
// N-10. A non-cooperative loader may never settle, or may settle after
// abort. Race the signal so `loadAll` is bounded, and re-check before
// observing the page so a late completion is ignored rather than
// accumulated into a successful result.
const raced: Result<CursorPage<Value>> | typeof ABORTED =
await raceAbort<Result<CursorPage<Value>>>(
dependencies.loadPage(cursor, context),
context.signal,
);
if (raced === ABORTED || context.signal?.aborted) {
return failure("REQUEST_ABORTED", "PAGINATION_ABORTED");
}
const result: Result<CursorPage<Value>> = raced;
if (!result.ok) return result;
const page = result.value;
const page: CursorPage<Value> = result.value;
if (!isValidPage(page, dependencies.profile)) {
return failure(
"PAGINATION_CONTRACT_VIOLATION",
@@ -57,7 +99,7 @@ export function createCursorPaginationRuntime<Value>(dependencies: Readonly<{
);
}
if (!page.hasMore) return { ok: true, value: Object.freeze(items) };
const nextCursor = page.nextCursor;
const nextCursor: string | null = page.nextCursor;
if (!nextCursor || cursors.has(nextCursor)) {
return failure(
"PAGINATION_CONTRACT_VIOLATION",
+12
View File
@@ -69,6 +69,18 @@ export const STORAGE_REGISTRY = Object.freeze({
migration: "discard",
quotaFallback: "feature-disable",
}),
CACHE_INVALIDATION_PULSE: defineStorageKey({
logicalName: "CACHE_INVALIDATION_PULSE",
scope: "cache-invalidation",
name: "pulse",
backend: "localStorage",
classification: "opaque-cache",
schemaVersion: 1,
valueCodec: "opaque-string-v1",
ttl: null,
migration: "discard",
quotaFallback: "no-persist",
}),
AUTH_TOKEN: defineStorageKey({
logicalName: "AUTH_TOKEN",
scope: "auth",