fix(contracts): return read-only indexes and frozen row snapshots (Q-6.7-7)

indexInvalidationRegistry and indexInvalidationTopicVersions froze only
the wrapper object, so `.clear()` on the returned Map emptied a
validated fan-out. validateWebWorkerContributions,
validateOfflineCommandContribution and validateRealtimeContributions
froze only the outer array and returned the caller's rows, so a later
write could raise a deadline, request byte bound or polling interval
that had already been checked.

read-only-registry.ts gains createReadOnlyMap (same private-store
facade, typed ReadonlyMap so the public index types do not change;
forEach now also passes the map argument). The three contribution
validators snapshot every row (exact keys, arrays by index) with
exact-snapshot.ts, validate the snapshot and return it frozen.

Behavior: contribution rows with extra keys, accessors or non-plain
prototypes are now rejected (template registries are empty today).

Verified: new tests/unit/contract-index-immutability.test.ts (5 cases,
all RED before); gates green except the known removal-fixture test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-24 13:45:37 +09:00
co-authored by Claude Opus 5.5
parent cb52c74710
commit abaaa9c773
6 changed files with 330 additions and 24 deletions
+39 -5
View File
@@ -7,6 +7,8 @@
* defines server idempotency or an inspect protocol of its own.
*/
import { exactOwnDataSnapshot, snapshotExactArray } from "./exact-snapshot.ts";
export const OFFLINE_COMMAND_BOUNDS = Object.freeze({
operations: 64,
defaultRequestBytes: 262_144,
@@ -118,20 +120,52 @@ export interface OfflineCommandSummary {
| "DISMISS";
}
const CONTRIBUTION_KEYS = Object.freeze(["datasetId", "operations"] as const);
const OPERATION_KEYS = Object.freeze([
"operationId",
"contractPackageId",
"maximumRequestBytes",
"retentionClass",
] as const);
function invalid(detail: string): never {
throw new TypeError(`Offline command contribution is not exact: ${detail}`);
}
/**
* Q-6.7-7. Validates and returns owned frozen snapshots, so a later write to
* the caller's operation row cannot raise a bound that was already checked.
*/
export function validateOfflineCommandContribution(
contribution: InstalledOfflineCommandContribution,
source: InstalledOfflineCommandContribution,
): InstalledOfflineCommandContribution {
const contribution = exactOwnDataSnapshot<InstalledOfflineCommandContribution>(
source,
CONTRIBUTION_KEYS,
CONTRIBUTION_KEYS,
invalid,
);
if (contribution.datasetId !== "OFFLINE_COMMANDS_V1") {
throw new TypeError("Offline command dataset identity is invalid.");
}
const rows = snapshotExactArray(contribution.operations);
if (
contribution.operations.length === 0 ||
contribution.operations.length > OFFLINE_COMMAND_BOUNDS.operations
!rows ||
rows.length === 0 ||
rows.length > OFFLINE_COMMAND_BOUNDS.operations
) {
throw new TypeError("Offline command operation count is out of range.");
}
const operations = rows.map((row) =>
exactOwnDataSnapshot<InstalledOfflineOperation>(
row,
OPERATION_KEYS,
OPERATION_KEYS,
invalid,
),
);
const seen = new Set<string>();
for (const operation of contribution.operations) {
for (const operation of operations) {
if (!operation.operationId || seen.has(operation.operationId)) {
throw new TypeError("Duplicate offline command operation.");
}
@@ -149,6 +183,6 @@ export function validateOfflineCommandContribution(
}
return Object.freeze({
datasetId: contribution.datasetId,
operations: Object.freeze([...contribution.operations]),
operations: Object.freeze(operations),
});
}
+6 -3
View File
@@ -4,6 +4,7 @@ import {
queryNamespaceIdentityKey,
type QueryNamespaceIdentity,
} from "./query-keys.ts";
import { createReadOnlyMap } from "./read-only-registry.ts";
declare const queryInvalidationTopicBrand: unique symbol;
@@ -181,14 +182,16 @@ export function indexInvalidationRegistry(
}
}
// Q-6.7-7. Read facades, not `Map`s: freezing the wrapper object would
// leave `clear()` able to empty the validated fan-out.
return Object.freeze({
namespacesForTopic: new Map(
namespacesForTopic: createReadOnlyMap(
[...namespacesForTopic].map(([key, value]) => [
key,
Object.freeze([...value]) as readonly QueryNamespaceIdentity[],
]),
),
topicsForNamespace: new Map(
topicsForNamespace: createReadOnlyMap(
[...topicsForNamespace].map(([key, value]) => [
key,
Object.freeze([...value]) as readonly string[],
@@ -229,7 +232,7 @@ export function indexInvalidationTopicVersions(
}
versions.set(definition.topicId, definition.topicVersion);
}
return versions;
return createReadOnlyMap(versions);
}
export type QueryMutationLease = Readonly<{
+23 -5
View File
@@ -22,9 +22,9 @@ export type ReadOnlyRegistry<Key, Value> = Readonly<{
[Symbol.iterator](): IterableIterator<readonly [Key, Value]>;
}>;
export function createReadOnlyRegistry<Key, Value>(
function readOnlyFacade<Key, Value>(
entries: Iterable<readonly [Key, Value]>,
): ReadOnlyRegistry<Key, Value> {
) {
const store = new Map<Key, Value>(entries as Iterable<[Key, Value]>);
const facade = {
get: (key: Key) => store.get(key),
@@ -32,15 +32,33 @@ export function createReadOnlyRegistry<Key, Value>(
keys: () => store.keys(),
values: () => store.values(),
entries: () => store.entries(),
forEach: (visit: (value: Value, key: Key) => void) => {
for (const [key, value] of store) visit(value, key);
forEach: (
visit: (value: Value, key: Key, map: ReadonlyMap<Key, Value>) => void,
): void => {
for (const [key, value] of store) visit(value, key, facade);
},
get size() {
return store.size;
},
[Symbol.iterator]: () => store.entries(),
};
return Object.freeze(facade) as ReadOnlyRegistry<Key, Value>;
return Object.freeze(facade);
}
export function createReadOnlyRegistry<Key, Value>(
entries: Iterable<readonly [Key, Value]>,
): ReadOnlyRegistry<Key, Value> {
return readOnlyFacade(entries);
}
/**
* Q-6.7-7. The same facade for an index already published as a `ReadonlyMap`,
* so the public type stays put while `set`/`delete`/`clear` stop existing.
*/
export function createReadOnlyMap<Key, Value>(
entries: Iterable<readonly [Key, Value]>,
): ReadonlyMap<Key, Value> {
return readOnlyFacade(entries);
}
/** Kept here for existing importers; the implementation lives in `exact-snapshot.ts`. */
+87 -4
View File
@@ -1,6 +1,11 @@
import type { InstalledOfflineCommandContribution } from "./offline-command.ts";
import type { InstalledServiceWorkerSelection } from "./service-worker.ts";
import type { InstalledWebWorkerContribution } from "./web-worker.ts";
import {
exactOwnDataSnapshot,
ownDataValue,
snapshotExactArray,
} from "./exact-snapshot.ts";
/**
* §3.4–§3.6. Optional runtime capability selection and hosting.
@@ -129,18 +134,95 @@ export function resolveRuntimeCapabilities(
});
}
const REALTIME_CONTRIBUTION_KEYS = Object.freeze([
"contributionId",
"featureId",
"contractSourcePackageId",
"streamId",
"recoveryMode",
"eventEffects",
"transport",
] as const);
const EVENT_EFFECT_KEYS = Object.freeze([
"eventType",
"mapperId",
"effect",
"invalidationTopics",
] as const);
const ENDPOINT_TRANSPORT_KEYS = Object.freeze(["kind", "endpointId"] as const);
const POLLING_TRANSPORT_KEYS = Object.freeze([
"kind",
"operationId",
"intervalMs",
] as const);
function invalidRealtime(detail: string): never {
throw new TypeError(`Realtime contribution is not exact: ${detail}`);
}
function snapshotTransport(source: unknown): InstalledRealtimeTransport {
const polling = ownDataValue(source, "kind") === "POLLING";
const keys = polling ? POLLING_TRANSPORT_KEYS : ENDPOINT_TRANSPORT_KEYS;
const transport = exactOwnDataSnapshot<Record<string, unknown>>(
source,
keys,
keys,
invalidRealtime,
) as InstalledRealtimeTransport;
// The key set was chosen by one read; the snapshot must agree with it.
if ((transport.kind === "POLLING") !== polling) invalidRealtime("transport");
return transport;
}
function snapshotEventEffect(source: unknown): InstalledRealtimeEventEffect {
const effect = exactOwnDataSnapshot<InstalledRealtimeEventEffect>(
source,
EVENT_EFFECT_KEYS,
EVENT_EFFECT_KEYS,
invalidRealtime,
);
const topics =
snapshotExactArray(effect.invalidationTopics) ??
invalidRealtime("invalidationTopics");
return Object.freeze({
...effect,
invalidationTopics: topics as readonly string[],
});
}
/**
* Q-6.7-7. Validates and returns owned frozen snapshots, so a later write to
* the caller's row cannot change a polling interval or topic list that was
* already checked.
*/
export function validateRealtimeContributions(
contributions: readonly InstalledRealtimeContribution[],
source: readonly InstalledRealtimeContribution[],
): readonly InstalledRealtimeContribution[] {
const bounds = REALTIME_CONTRIBUTION_BOUNDS;
if (contributions.length > bounds.contributions) {
const rows = snapshotExactArray(source) ?? invalidRealtime("array required");
if (rows.length > bounds.contributions) {
throw new TypeError("Realtime contributions exceed their bound.");
}
const contributionIds = new Set<string>();
const streamIds = new Set<string>();
let eventTypeCount = 0;
const installed: InstalledRealtimeContribution[] = [];
for (const contribution of contributions) {
for (const row of rows) {
const outer = exactOwnDataSnapshot<InstalledRealtimeContribution>(
row,
REALTIME_CONTRIBUTION_KEYS,
REALTIME_CONTRIBUTION_KEYS,
invalidRealtime,
);
const effectRows =
snapshotExactArray(outer.eventEffects) ??
invalidRealtime("eventEffects");
const contribution: InstalledRealtimeContribution = Object.freeze({
...outer,
eventEffects: Object.freeze(effectRows.map(snapshotEventEffect)),
transport: snapshotTransport(outer.transport),
});
if (
!contribution.contributionId ||
contributionIds.has(contribution.contributionId)
@@ -195,8 +277,9 @@ export function validateRealtimeContributions(
);
}
}
installed.push(contribution);
}
return Object.freeze([...contributions]);
return Object.freeze(installed);
}
export type RuntimeCapabilityId =
+51 -7
View File
@@ -7,6 +7,8 @@
* runtime is separate from the OPFS dedicated worker and the Service Worker.
*/
import { exactOwnDataSnapshot, snapshotExactArray } from "./exact-snapshot.ts";
export const WEB_WORKER_PROTOCOL = "CA_WEB_WORKER_V1" as const;
export const WEB_WORKER_BOUNDS = Object.freeze({
@@ -93,27 +95,66 @@ export type WorkerResponseMessage =
code: WorkerFailureCode;
}>;
const CONTRIBUTION_KEYS = Object.freeze([
"taskGroupId",
"tasks",
"fallback",
] as const);
const TASK_KEYS = Object.freeze([
"taskId",
"taskVersion",
"maximumInputBytes",
"maximumOutputBytes",
"deadlineMs",
] as const);
function invalid(detail: string): never {
throw new TypeError(`Web Worker contribution is not exact: ${detail}`);
}
/**
* Q-6.7-7. Validates and returns owned frozen snapshots, so a later write to
* the caller's task row cannot raise a bound that was already checked.
*/
export function validateWebWorkerContributions(
contributions: readonly InstalledWebWorkerContribution[],
source: readonly InstalledWebWorkerContribution[],
): readonly InstalledWebWorkerContribution[] {
const bounds = WEB_WORKER_BOUNDS;
if (contributions.length > bounds.taskGroups) {
const rows = snapshotExactArray(source) ?? invalid("array required");
if (rows.length > bounds.taskGroups) {
throw new TypeError("Web Worker task groups exceed their bound.");
}
const groupIds = new Set<string>();
const taskIds = new Set<string>();
for (const contribution of contributions) {
const installed: InstalledWebWorkerContribution[] = [];
for (const row of rows) {
const contribution = exactOwnDataSnapshot<InstalledWebWorkerContribution>(
row,
CONTRIBUTION_KEYS,
CONTRIBUTION_KEYS,
invalid,
);
if (!contribution.taskGroupId || groupIds.has(contribution.taskGroupId)) {
throw new TypeError("Web Worker task group identity is invalid.");
}
groupIds.add(contribution.taskGroupId);
const taskRows = snapshotExactArray(contribution.tasks);
if (
contribution.tasks.length === 0 ||
contribution.tasks.length > bounds.tasksPerGroup
!taskRows ||
taskRows.length === 0 ||
taskRows.length > bounds.tasksPerGroup
) {
throw new TypeError("Web Worker task count is out of range.");
}
for (const task of contribution.tasks) {
const tasks = taskRows.map((taskRow) =>
exactOwnDataSnapshot<InstalledWorkerTask>(
taskRow,
TASK_KEYS,
TASK_KEYS,
invalid,
),
);
for (const task of tasks) {
const qualified = `${contribution.taskGroupId}/${task.taskId}`;
if (!task.taskId || taskIds.has(qualified)) {
throw new TypeError("Duplicate Web Worker task.");
@@ -134,6 +175,9 @@ export function validateWebWorkerContributions(
throw new TypeError(`Web Worker task bounds invalid: ${qualified}`);
}
}
installed.push(
Object.freeze({ ...contribution, tasks: Object.freeze(tasks) }),
);
}
return Object.freeze([...contributions]);
return Object.freeze(installed);
}
@@ -0,0 +1,124 @@
import { describe, expect, it } from "vitest";
import { validateOfflineCommandContribution } from "../../src/contracts/offline-command.ts";
import {
defineQueryInvalidationTopic,
indexInvalidationRegistry,
indexInvalidationTopicVersions,
} from "../../src/contracts/query-invalidation.ts";
import { defineQueryNamespaceIdentity } from "../../src/contracts/query-keys.ts";
import { validateRealtimeContributions } from "../../src/contracts/runtime-capabilities.ts";
import { validateWebWorkerContributions } from "../../src/contracts/web-worker.ts";
/**
* Q-6.7-7. A validated index or registry is authority. `Object.freeze` on the
* outer wrapper leaves a returned `Map` clearable and leaves every row the
* caller's still-mutable object, so a later write changes what was validated.
*/
function tryClear(map: unknown): void {
try {
(map as Map<unknown, unknown>).clear();
} catch {
// A read facade has no `clear`; that is the expected outcome.
}
try {
Map.prototype.clear.call(map as Map<unknown, unknown>);
} catch {
// Borrowing the mutator must fail on the missing internal slot.
}
}
describe("query invalidation index", () => {
const topic = defineQueryInvalidationTopic("qinv.orders.changed");
const orders = defineQueryNamespaceIdentity("orders", 1);
const registry = {
topics: [topic],
namespaces: [orders],
edges: [{ topicId: topic, namespace: orders }],
};
it("cannot be cleared after indexing", () => {
const index = indexInvalidationRegistry(registry);
tryClear(index.namespacesForTopic);
tryClear(index.topicsForNamespace);
expect(index.namespacesForTopic.get(topic)).toEqual([orders]);
expect(index.topicsForNamespace.get('["orders",1]')).toEqual([topic]);
});
it("returns topic versions that cannot be cleared", () => {
const versions = indexInvalidationTopicVersions(registry, [
{ topicId: topic, topicVersion: 1 },
]);
tryClear(versions);
expect(versions.get(topic)).toBe(1);
});
});
describe("runtime capability contributions", () => {
it("snapshots web worker task bounds", () => {
const task = {
taskId: "hash",
taskVersion: 1 as const,
maximumInputBytes: 1_024,
maximumOutputBytes: 1_024,
deadlineMs: 1_000,
};
const [installed] = validateWebWorkerContributions([
{ taskGroupId: "crypto", tasks: [task], fallback: "UNSUPPORTED" },
]);
task.deadlineMs = 999_999;
expect(installed?.tasks[0]?.deadlineMs).toBe(1_000);
expect(Object.isFrozen(installed?.tasks[0])).toBe(true);
});
it("snapshots offline command operation bounds", () => {
const operation = {
operationId: "CREATE_ORDER",
contractPackageId: "@test/contracts",
maximumRequestBytes: 1_024,
retentionClass: "STANDARD_7D" as const,
};
const installed = validateOfflineCommandContribution({
datasetId: "OFFLINE_COMMANDS_V1",
operations: [operation],
});
operation.maximumRequestBytes = 999_999_999;
expect(installed.operations[0]?.maximumRequestBytes).toBe(1_024);
expect(Object.isFrozen(installed.operations[0])).toBe(true);
});
it("snapshots realtime transport and effect rows", () => {
const transport = {
kind: "POLLING" as const,
operationId: "LIST_ORDERS",
intervalMs: 5_000,
};
const topics = ["qinv.orders.changed"];
const [installed] = validateRealtimeContributions([
{
contributionId: "orders-realtime",
featureId: "orders",
contractSourcePackageId: "@test/contracts",
streamId: "ORDERS",
recoveryMode: "SESSION_REBUILD",
eventEffects: [
{
eventType: "orders.changed",
mapperId: "OrdersChanged",
effect: "INVALIDATE_TOPICS",
invalidationTopics: topics,
},
],
transport,
},
]);
transport.intervalMs = 1;
topics.length = 0;
const effect = installed?.eventEffects[0];
expect(installed?.transport).toMatchObject({ intervalMs: 5_000 });
expect(effect?.invalidationTopics).toEqual(["qinv.orders.changed"]);
expect(Object.isFrozen(installed?.transport)).toBe(true);
expect(Object.isFrozen(effect?.invalidationTopics)).toBe(true);
});
});