From b69d3057a50ff0dbfcb2aa5f33391a01950d4547 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 00:01:59 +0200 Subject: [PATCH 01/14] cultcache-ts: the payload nesting bound (256) in the one document-payload owner, so every TS payload door shares it checkPayloadDepth is an iterative header walk run by decodeDocumentPayload before the formatter and by encodeDocumentPayload on the formatter's bytes; the two plain-decode inspection doors call it first. The plain formatter's encoder depth is set above the limit so the walk decides. Tests: the C# bounds vectors, the walk's header and scalar rules, the owner, the inspector, the legacy version inference, and the mesh network doors; test:pack:ts denies decoder-shaped exports by enumerating the packed entries. Builds and passes untested at this commit (verification runs on Yggdrasil next). Co-Authored-By: Claude Sonnet 5.5 --- .../cultcache-ts/src/cult-cache-inspector.ts | 2 + .../cultcache-ts/src/document-formatter.ts | 4 +- packages/cultcache-ts/src/document.ts | 11 +- packages/cultcache-ts/src/index.ts | 1 + packages/cultcache-ts/src/payload-depth.ts | 70 +++++++ .../single-file-messagepack-backing-store.ts | 2 + .../cultcache-ts/test/payload-depth.test.ts | 190 ++++++++++++++++++ .../cultcache-ts/test/union-parity.test.ts | 113 ++++++++++- .../cultmesh-ts/test/codec-documents.test.ts | 51 +++++ scripts/test-typescript-package-closure.mjs | 17 +- 10 files changed, 446 insertions(+), 15 deletions(-) create mode 100644 packages/cultcache-ts/src/payload-depth.ts create mode 100644 packages/cultcache-ts/test/payload-depth.test.ts diff --git a/packages/cultcache-ts/src/cult-cache-inspector.ts b/packages/cultcache-ts/src/cult-cache-inspector.ts index 54e75700..43fc41cd 100644 --- a/packages/cultcache-ts/src/cult-cache-inspector.ts +++ b/packages/cultcache-ts/src/cult-cache-inspector.ts @@ -1,5 +1,6 @@ import { decode } from "@msgpack/msgpack"; +import { checkPayloadDepth } from "./payload-depth"; import { STORE_FORMAT_VERSION, isV1Snapshot, requireV1RecordSlots } from "./store-format"; export interface CultCacheInspection { @@ -288,6 +289,7 @@ function decodeLegacyEnvelope(value: unknown): InspectedRecord { function previewPayload(payload: Uint8Array): Pick { try { + checkPayloadDepth(payload); return { payloadPreview: toJsonSafe(decode(payload)) }; } catch (error) { return { diff --git a/packages/cultcache-ts/src/document-formatter.ts b/packages/cultcache-ts/src/document-formatter.ts index 54dee1ed..799b2558 100644 --- a/packages/cultcache-ts/src/document-formatter.ts +++ b/packages/cultcache-ts/src/document-formatter.ts @@ -1,5 +1,6 @@ import { decode, encode } from "@msgpack/msgpack"; +import { MAX_PAYLOAD_DEPTH } from "./payload-depth"; import type { SlotsCodec } from "./codec"; import type { AnyCultCacheDocumentDefinition, CultCacheDocumentFormatter } from "./types"; import { readWire, writeWire } from "./wire"; @@ -16,7 +17,8 @@ export function resolveDocumentFormatter(definition: AnyCultCacheDocumentDefinit } const plainDocumentFormatter: CultCacheDocumentFormatter = { - encode: (value: unknown) => encode(value), + // The encoder's own depth refusal (100 by default) is set above the limit, so the payload walk decides. + encode: (value: unknown) => encode(value, { maxDepth: MAX_PAYLOAD_DEPTH * 2 }), decode: (payload: Uint8Array) => decode(payload), }; diff --git a/packages/cultcache-ts/src/document.ts b/packages/cultcache-ts/src/document.ts index 4c6ea040..03c2e4a0 100644 --- a/packages/cultcache-ts/src/document.ts +++ b/packages/cultcache-ts/src/document.ts @@ -1,4 +1,5 @@ import { resolveDocumentFormatter } from "./document-formatter"; +import { checkPayloadDepth } from "./payload-depth"; import type { AnyCultCacheDocumentDefinition, CultCacheSchemaCatalogMember, @@ -104,19 +105,25 @@ export function documentPayloadBytes(payload: DocumentPayload): Uint8Array { return payload as unknown as Uint8Array; } +export { CultCachePayloadDepthError, MAX_PAYLOAD_DEPTH } from "./payload-depth"; + // The one reader of a document payload: through the definition's formatter, codec or plain map, then its schema. A // reader holds the definition or it has no business reading the bytes, so there is no definition-less form. export function decodeDocumentPayload( definition: TDefinition, payload: DocumentPayload, ): CultCacheDocumentValue { - const decoded = resolveDocumentFormatter(definition).decode(documentPayloadBytes(payload)); + const bytes = documentPayloadBytes(payload); + checkPayloadDepth(bytes, `document type "${definition.type}" payload`); + const decoded = resolveDocumentFormatter(definition).decode(bytes); return definition.schema.parse(decoded) as CultCacheDocumentValue; } // The one writer: the definition's schema first, then its formatter, codec or plain map. export function encodeDocumentPayload(definition: AnyCultCacheDocumentDefinition, value: unknown): DocumentPayload { - return documentPayloadFromBytes(resolveDocumentFormatter(definition).encode(definition.schema.parse(value))); + const bytes = resolveDocumentFormatter(definition).encode(definition.schema.parse(value)); + checkPayloadDepth(bytes, `document type "${definition.type}" value`); + return documentPayloadFromBytes(bytes); } // The schema members of a document: the ones it declares, else those its codec derives, else none. diff --git a/packages/cultcache-ts/src/index.ts b/packages/cultcache-ts/src/index.ts index c5dfbff1..8646d12e 100644 --- a/packages/cultcache-ts/src/index.ts +++ b/packages/cultcache-ts/src/index.ts @@ -10,6 +10,7 @@ export { documentPayloadFromBytes, encodeDocumentPayload, } from "./document"; +export { CultCachePayloadDepthError, MAX_PAYLOAD_DEPTH } from "./payload-depth"; export type { DocumentPayload } from "./document"; export { SingleFileMessagePackBackingStore } from "./single-file-messagepack-backing-store"; export type { diff --git a/packages/cultcache-ts/src/payload-depth.ts b/packages/cultcache-ts/src/payload-depth.ts new file mode 100644 index 00000000..40ca7afe --- /dev/null +++ b/packages/cultcache-ts/src/payload-depth.ts @@ -0,0 +1,70 @@ +// The one payload nesting rule in TypeScript, the twin of the C# reference's CultPayloadDepth.Check: every MessagePack +// array and map counts, whether a reader reads it or skips past it, and the outermost array is depth 1. Depth +// MAX_PAYLOAD_DEPTH is accepted and one container deeper is refused, on read and on write. +export const MAX_PAYLOAD_DEPTH = 256; + +export class CultCachePayloadDepthError extends Error { + constructor(readonly depth: number, readonly limit: number, subject: string) { + super(`${subject} nests ${depth} MessagePack containers deep; the limit is ${limit}.`); + this.name = "CultCachePayloadDepthError"; + } +} + +// Walks the headers of one MessagePack value iteratively (a count stack bounded by the limit, scalars skipped by length, +// nothing read) and throws at the first container past the limit. The message names the subject, the depth and the limit, +// never payload bytes. A payload that ends early is the reader's to refuse. +export function checkPayloadDepth(bytes: Uint8Array, subject = "document payload"): void { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const remaining = new Float64Array(MAX_PAYLOAD_DEPTH); + let depth = 0; + let position = 0; + // The big-endian length that follows the code byte, when the payload is long enough to hold it. + const width = (size: 1 | 2 | 4): number | undefined => { + if (position + 1 + size > bytes.length) return undefined; + return size === 1 ? view.getUint8(position + 1) : size === 2 ? view.getUint16(position + 1) : view.getUint32(position + 1); + }; + while (position < bytes.length) { + const code = bytes[position]; + let header = 0; + let children = 0; + let skip = 0; + let container = false; + if (code <= 0x7f || code >= 0xe0 || code === 0xc0 || code === 0xc1 || code === 0xc2 || code === 0xc3) skip = 1; + else if (code <= 0x8f) { container = true; header = 1; children = 2 * (code & 0x0f); } + else if (code <= 0x9f) { container = true; header = 1; children = code & 0x0f; } + else if (code <= 0xbf) skip = 1 + (code & 0x1f); + else if (code === 0xc4 || code === 0xd9) { const n = width(1); if (n === undefined) return; skip = 2 + n; } + else if (code === 0xc5 || code === 0xda) { const n = width(2); if (n === undefined) return; skip = 3 + n; } + else if (code === 0xc6 || code === 0xdb) { const n = width(4); if (n === undefined) return; skip = 5 + n; } + else if (code === 0xc7) { const n = width(1); if (n === undefined) return; skip = 3 + n; } + else if (code === 0xc8) { const n = width(2); if (n === undefined) return; skip = 4 + n; } + else if (code === 0xc9) { const n = width(4); if (n === undefined) return; skip = 6 + n; } + else if (code === 0xca || code === 0xce || code === 0xd2) skip = 5; + else if (code === 0xcb || code === 0xcf || code === 0xd3) skip = 9; + else if (code === 0xcc || code === 0xd0) skip = 2; + else if (code === 0xcd || code === 0xd1 || code === 0xd4) skip = 3; + else if (code === 0xd5) skip = 4; + else if (code === 0xd6) skip = 6; + else if (code === 0xd7) skip = 10; + else if (code === 0xd8) skip = 18; + else if (code === 0xdc) { const n = width(2); if (n === undefined) return; container = true; header = 3; children = n; } + else if (code === 0xdd) { const n = width(4); if (n === undefined) return; container = true; header = 5; children = n; } + else if (code === 0xde) { const n = width(2); if (n === undefined) return; container = true; header = 3; children = 2 * n; } + else { const n = width(4); if (n === undefined) return; container = true; header = 5; children = 2 * n; } + + if (container) { + if (depth === MAX_PAYLOAD_DEPTH) throw new CultCachePayloadDepthError(MAX_PAYLOAD_DEPTH + 1, MAX_PAYLOAD_DEPTH, subject); + position += header; + if (children > 0) { + remaining[depth++] = children; + continue; + } + } else { + position += skip; + } + + // One element is complete; close every container it was the last element of. + while (depth > 0 && --remaining[depth - 1] === 0) depth--; + if (depth === 0) return; + } +} diff --git a/packages/cultcache-ts/src/single-file-messagepack-backing-store.ts b/packages/cultcache-ts/src/single-file-messagepack-backing-store.ts index cdc6cf9e..d0f295d5 100644 --- a/packages/cultcache-ts/src/single-file-messagepack-backing-store.ts +++ b/packages/cultcache-ts/src/single-file-messagepack-backing-store.ts @@ -5,6 +5,7 @@ import { decode, encode } from "@msgpack/msgpack"; import { z } from "zod"; import { documentPayloadBytes, documentPayloadFromBytes } from "./document"; +import { checkPayloadDepth } from "./payload-depth"; import { STORE_FORMAT_VERSION, isV1Snapshot, requireV1RecordSlots } from "./store-format"; import type { CacheBackingStore, @@ -355,6 +356,7 @@ function resolveCatalogEntryForRecord( function inferSchemaVersionFromPayload(payload: Uint8Array): string | undefined { try { + checkPayloadDepth(payload); const decoded = decode(payload); if (Array.isArray(decoded) && typeof decoded[0] === "string") { return decoded[0]; diff --git a/packages/cultcache-ts/test/payload-depth.test.ts b/packages/cultcache-ts/test/payload-depth.test.ts new file mode 100644 index 00000000..8392bfb7 --- /dev/null +++ b/packages/cultcache-ts/test/payload-depth.test.ts @@ -0,0 +1,190 @@ +import assert from "node:assert/strict"; +import { mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; + +import { encode } from "@msgpack/msgpack"; +import { z } from "zod"; + +import * as root from "../src"; +import { inspectCultCacheBytes } from "../src/cult-cache-inspector"; +import { + CultCachePayloadDepthError, + MAX_PAYLOAD_DEPTH, + decodeDocumentPayload, + defineDocumentType, + documentPayloadBytes, + documentPayloadFromBytes, + encodeDocumentPayload, +} from "../src/document"; +import { checkPayloadDepth } from "../src/payload-depth"; +import { SingleFileMessagePackBackingStore } from "../src/single-file-messagepack-backing-store"; + +const L = MAX_PAYLOAD_DEPTH; +const CANARY = "CANARY-payload-depth-91d3"; + +const cat = (...parts: Uint8Array[]) => Uint8Array.from(parts.flatMap((part) => [...part])); +const bytes = (...values: number[]) => Uint8Array.from(values); +const repeat = (unit: Uint8Array, times: number) => { + const out = new Uint8Array(unit.length * times); + for (let index = 0; index < times; index += 1) out.set(unit, index * unit.length); + return out; +}; +// n containers nested in one another around a leaf; `open` is one container's header with one child (two for a map). +const chain = (open: Uint8Array, n: number, leaf: Uint8Array = bytes(0xc0)) => cat(repeat(open, n), leaf); +const arrays = (n: number, leaf?: Uint8Array) => chain(bytes(0x91), n, leaf); + +const refused = (payload: Uint8Array, label: string) => + assert.throws(() => checkPayloadDepth(payload), (error: unknown) => + error instanceof CultCachePayloadDepthError && error.depth === L + 1 && error.limit === L, label); + +test("the limit is 256: depth 256 passes and 257 is refused, for every array and map header width", () => { + assert.equal(L, 256); + const kinds: [string, Uint8Array][] = [ + ["fixarray", bytes(0x91)], + ["array16", bytes(0xdc, 0, 1)], + ["array32", bytes(0xdd, 0, 0, 0, 1)], + ["fixmap", bytes(0x81, 0x00)], + ["map16", bytes(0xde, 0, 1, 0x00)], + ["map32", bytes(0xdf, 0, 0, 0, 1, 0x00)], + ]; + for (const [name, open] of kinds) { + assert.doesNotThrow(() => checkPayloadDepth(chain(open, L)), `${name} at the limit`); + refused(chain(open, L + 1), `${name} past the limit`); + } +}); + +test("an empty map or array as the innermost container counts like any other", () => { + for (const empty of [bytes(0x90), bytes(0x80), bytes(0xdc, 0, 0), bytes(0xdd, 0, 0, 0, 0), bytes(0xde, 0, 0), bytes(0xdf, 0, 0, 0, 0)]) { + assert.doesNotThrow(() => checkPayloadDepth(arrays(L - 1, empty))); + refused(arrays(L, empty), "empty innermost past the limit"); + } + // [a chain of 255, a chain of 255]: the first sibling closes before the second opens, so the depth is 256, not 511. + const sibling = arrays(L - 1); + assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x92), sibling, sibling))); + refused(cat(bytes(0x92), sibling, arrays(L)), "the second sibling is one deeper"); + // A map's key and value both count as elements: {key: chain, key: chain} closes after four elements. + assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x82, 0x00), sibling, bytes(0x01), sibling))); + refused(cat(bytes(0x82, 0x00), sibling, bytes(0x01), arrays(L)), "the second map value is one deeper"); + refused(cat(bytes(0x82), arrays(L), sibling, bytes(0x01), sibling), "a map key one deeper"); +}); + +test("every scalar is skipped by its length, whatever bytes it holds", () => { + const filler = (count: number) => repeat(bytes(0x91), count); + const scalars: [string, Uint8Array][] = [ + ["nil", bytes(0xc0)], ["false", bytes(0xc2)], ["true", bytes(0xc3)], ["positive fixint", bytes(0x7f)], ["negative fixint", bytes(0xe0)], + ["uint8", bytes(0xcc, 0x91)], ["uint16", cat(bytes(0xcd), filler(2))], ["uint32", cat(bytes(0xce), filler(4))], ["uint64", cat(bytes(0xcf), filler(8))], + ["int8", bytes(0xd0, 0x91)], ["int16", cat(bytes(0xd1), filler(2))], ["int32", cat(bytes(0xd2), filler(4))], ["int64", cat(bytes(0xd3), filler(8))], + ["float32", cat(bytes(0xca), filler(4))], ["float64", cat(bytes(0xcb), filler(8))], + ["fixext1", cat(bytes(0xd4), filler(2))], ["fixext2", cat(bytes(0xd5), filler(3))], ["fixext4", cat(bytes(0xd6), filler(5))], + ["fixext8", cat(bytes(0xd7), filler(9))], ["fixext16", cat(bytes(0xd8), filler(17))], + ["fixstr", cat(bytes(0xa3), filler(3))], ["str8", cat(bytes(0xd9, 3), filler(3))], ["str16", cat(bytes(0xda, 0, 3), filler(3))], + ["str32", cat(bytes(0xdb, 0, 0, 0, 3), filler(3))], + ["bin8", cat(bytes(0xc4, 3), filler(3))], ["bin16", cat(bytes(0xc5, 0, 3), filler(3))], ["bin32", cat(bytes(0xc6, 0, 0, 0, 3), filler(3))], + ["ext8", cat(bytes(0xc7, 3, 0x7f), filler(3))], ["ext16", cat(bytes(0xc8, 0, 3, 0x7f), filler(3))], + ["ext32", cat(bytes(0xc9, 0, 0, 0, 3, 0x7f), filler(3))], + ["str16 of 300 bytes", cat(bytes(0xda, 0x01, 0x2c), filler(300))], + ]; + for (const [name, scalar] of scalars) { + assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x92), scalar, arrays(L - 1))), `${name} then a chain at the limit`); + refused(cat(bytes(0x92), scalar, arrays(L)), `${name} then a chain past it`); + assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x92), arrays(L - 1), scalar)), `${name} after a chain at the limit`); + } +}); + +test("a payload that ends early, is empty or carries trailing bytes is the reader's business, not the walk's", () => { + for (const early of [[], [0xd9], [0xda, 0], [0xdb, 0, 0, 0], [0xc4], [0xc5, 0], [0xc6, 0, 0, 0], [0xc7], [0xc8, 0], [0xc9, 0, 0, 0], [0xdc, 0], [0xdd, 0, 0, 0], [0xde, 0], [0xdf, 0, 0, 0]]) { + assert.doesNotThrow(() => checkPayloadDepth(bytes(...early)), early.map((value) => value.toString(16)).join(" ")); + } + assert.doesNotThrow(() => checkPayloadDepth(arrays(L - 1, bytes(0x91))), "a chain cut off before its leaf"); + assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x90), arrays(L + 50))), "bytes after the first complete value are not walked"); + assert.doesNotThrow(() => checkPayloadDepth(bytes(0xc0))); +}); + +test("the walk is iterative: 100000 nested arrays are refused with the depth error, not a RangeError", () => { + refused(arrays(100_000), "100000 nested arrays"); + refused(chain(bytes(0x81, 0x00), 100_000), "100000 nested maps"); +}); + +test("a refusal names the subject, the depth and the limit and never a byte of the payload", () => { + const payload = chain(bytes(0x91), L + 1, cat(bytes(0xd9, CANARY.length), new TextEncoder().encode(CANARY))); + assert.throws( + () => checkPayloadDepth(payload, 'document type "t.note" payload'), + (error: unknown) => error instanceof CultCachePayloadDepthError + && error.name === "CultCachePayloadDepthError" + && error.message === 'document type "t.note" payload nests 257 MessagePack containers deep; the limit is 256.', + ); + const canaryPayload = payload; + assert.throws(() => checkPayloadDepth(canaryPayload), (error: Error) => !error.message.includes(CANARY) && !JSON.stringify(error).includes(CANARY)); +}); + +const note = z.object({ id: z.string(), count: z.number() }); +const formatterCalls: string[] = []; +const guarded = defineDocumentType({ + type: "t.guarded", + schemaId: "t.guarded.v0", + schema: note, + name: "id", + formatter: { + encode: () => (formatterCalls.push("encode"), arrays(L + 1)), + decode: () => (formatterCalls.push("decode"), { id: "a", count: 1 }), + }, +}); + +test("the owner refuses a payload past the limit before its formatter reads it, and a formatter's bytes before they are wrapped", () => { + assert.throws(() => decodeDocumentPayload(guarded, documentPayloadFromBytes(arrays(L + 1))), CultCachePayloadDepthError); + assert.deepEqual(formatterCalls, [], "the formatter never saw the deep payload"); + assert.deepEqual(decodeDocumentPayload(guarded, documentPayloadFromBytes(arrays(L))), { id: "a", count: 1 }); + + assert.throws(() => encodeDocumentPayload(guarded, { id: "a", count: 1 }), (error: Error) => + error instanceof CultCachePayloadDepthError && error.message === 'document type "t.guarded" value nests 257 MessagePack containers deep; the limit is 256.'); +}); + +test("a document without a codec or formatter writes a value L deep and refuses L+1 by the walk", () => { + const anything = defineDocumentType({ type: "t.any", schemaId: "t.any.v0", schema: z.any(), name: "id" }); + const nest = (n: number): unknown => (n === 1 ? [] : [nest(n - 1)]); + const atLimit = encodeDocumentPayload(anything, nest(L)); + assert.deepEqual(documentPayloadBytes(atLimit), encode(nest(L), { maxDepth: 1000 })); + assert.deepEqual(decodeDocumentPayload(anything, atLimit), nest(L)); + assert.throws(() => encodeDocumentPayload(anything, nest(L + 1)), (error: unknown) => + error instanceof CultCachePayloadDepthError && error.depth === L + 1 && error.limit === L); + assert.throws(() => decodeDocumentPayload(anything, documentPayloadFromBytes(arrays(L + 1))), CultCachePayloadDepthError); +}); + +test("the limit and its error are exported from the root, and the walk itself is not", () => { + assert.equal(root.MAX_PAYLOAD_DEPTH, 256); + assert.equal(root.CultCachePayloadDepthError, CultCachePayloadDepthError); + assert.equal("checkPayloadDepth" in root, false); +}); + +// A v1 store whose one record carries `payload` as bin and no catalog entry, so the record's schema is inferred from the +// payload's first element. +async function storeWith(payload: Uint8Array): Promise { + const file = join(await mkdtemp(join(tmpdir(), "cultcache-payload-depth-")), "deep.cc"); + await writeFile(file, encode(["cultcache.store.v1", [], [["record-1", "sha256:stale", "2026-06-25T12:00:00Z", payload]]])); + return file; +} +const stamped = (containersInsideTheStamp: number) => + cat(bytes(0x92), encode("tests.schema_stamped_entry.v1"), arrays(containersInsideTheStamp)); + +test("the inspector previews a payload at the limit and reports one past it, or 100000 deep, as a decode error", async () => { + const atLimit = await storeWith(stamped(L - 1)); + const previewed = inspectCultCacheBytes(atLimit, await readFile(atLimit)).records[0]!; + assert.equal(previewed.payloadDecodeError, undefined); + + for (const inside of [L, 100_000]) { + const file = await storeWith(stamped(inside)); + const record = inspectCultCacheBytes(file, await readFile(file)).records[0]!; + assert.equal(record.payloadDecodeError, "document payload nests 257 MessagePack containers deep; the limit is 256."); + } +}); + +test("the single-file store infers a legacy record's schema from a payload at the limit and from none past it", async () => { + const atLimit = await storeWith(stamped(L - 1)); + const [read] = await new SingleFileMessagePackBackingStore(atLimit).pullAll(); + assert.equal(read.catalogEntry?.schemaVersion, "tests.schema_stamped_entry.v1"); + + const past = await storeWith(stamped(L)); + await assert.rejects(() => new SingleFileMessagePackBackingStore(past).pullAll(), /missing schema id/u); +}); diff --git a/packages/cultcache-ts/test/union-parity.test.ts b/packages/cultcache-ts/test/union-parity.test.ts index b025f113..575da1d8 100644 --- a/packages/cultcache-ts/test/union-parity.test.ts +++ b/packages/cultcache-ts/test/union-parity.test.ts @@ -12,7 +12,15 @@ import { codecs } from "../src"; import { MAX_SLOT_KEY, type Codec } from "../src/codec"; import { CultCache } from "../src/cult-cache"; import { readWire, WireFloat, writeWire } from "../src/wire"; -import { defineDocumentType, documentPayloadBytes, documentPayloadFromBytes } from "../src/document"; +import { + CultCachePayloadDepthError, + MAX_PAYLOAD_DEPTH, + decodeDocumentPayload, + defineDocumentType, + documentPayloadBytes, + documentPayloadFromBytes, + encodeDocumentPayload, +} from "../src/document"; import { SingleFileMessagePackBackingStore } from "../src/single-file-messagepack-backing-store"; import type { AnyCultCacheDocumentDefinition, CacheBackingStore, CultCacheEnvelope } from "../src/types"; @@ -39,9 +47,10 @@ type Node = | { kind: "Box"; id: string; children: (Node | null)[] } | { kind: "Text"; id: string; content: string } | { kind: "Use"; id: string; composition: Composition; slots: (Node | null)[] } - | { kind: "Image"; id: string; uri: string; alt: string }; + | { kind: "Image"; id: string; uri: string; alt: string } + | { kind: "Wrap"; inner: Node | null }; interface Composition { name: string; body: Node | null } -type Outcome = { kind: "Pending"; message: string } | { kind: "Completed"; sourceVersion: number } | { kind: "Denied" }; +type Outcome = { kind: "Pending"; message: string } | { kind: "Completed"; sourceVersion: number } | { kind: "Denied" } | { kind: "Floor" } | { kind: "Ceiling" }; type Item = { kind: "Gem"; name: string } | { kind: "Tool"; name: string; uses: number } | { kind: "Part"; name: string; count: number }; type CraftedItem = { kind: "Tool"; name: string; uses: number } | { kind: "Part"; name: string; count: number }; interface Surface { @@ -62,11 +71,14 @@ const node: Codec = union("Node", { 0: ["id", string], 1: ["composition", composition], 2: ["slots", list(lazy(() => node))], })], 5: ["Image", slots<{ id: string; uri: string; alt: string }>({ 0: ["id", string], 1: ["uri", string], 3: ["alt", string] })], + 6: ["Wrap", slots<{ inner: Node | null }>({ 0: ["inner", lazy(() => node)] })], }, `${CS}Node`); const outcome = union("Outcome", { 0: ["Pending", slots<{ message: string }>({ 0: ["message", string] })], 1: ["Completed", slots<{ sourceVersion: number }>({ 0: ["sourceVersion", int32] })], 2: ["Denied", unit], + [-2147483648]: ["Floor", unit], + 2147483647: ["Ceiling", unit], }, `${CS}Outcome`); const toolArm = slots<{ name: string; uses: number }>({ 0: ["name", string], 1: ["uses", int32] }); const partArm = slots<{ name: string; count: number }>({ 0: ["name", string], 1: ["count", int32] }); @@ -99,6 +111,7 @@ const nodeSchema: z.ZodType = z.lazy(() => slots: z.array(nodeSchema), }), z.object({ kind: z.literal("Image"), id: z.string(), uri: z.string(), alt: z.string() }), + z.object({ kind: z.literal("Wrap"), inner: nodeSchema }), ]), ])); const surfaceSchema = z.object({ @@ -111,6 +124,8 @@ const surfaceSchema = z.object({ z.object({ kind: z.literal("Pending"), message: z.string() }), z.object({ kind: z.literal("Completed"), sourceVersion: z.number() }), z.object({ kind: z.literal("Denied") }), + z.object({ kind: z.literal("Floor") }), + z.object({ kind: z.literal("Ceiling") }), ]), ])), part: z.union([z.null(), z.discriminatedUnion("kind", [ @@ -273,7 +288,7 @@ test("an arm that is not [key, slots] is refused naming the union, and a non-int }); test("an arm key that is not a declared key is refused, with no fallback", () => { - assert.throws(() => node.decode([4, []]), /Union Node: unknown arm key 4 \(declared keys: 0, 1, 2, 5\)/u); + assert.throws(() => node.decode([4, []]), /Union Node: unknown arm key 4 \(declared keys: 0, 1, 2, 5, 6\)/u); assert.throws(() => outcome.decode([3, []]), /Union Outcome: unknown arm key 3/u); }); @@ -448,14 +463,14 @@ test("an arm key is an integer in any MessagePack integer encoding, and a float- assert.deepEqual(outcome.decode(readWire(fromHex(`92${key}9107`))), completed, key); } for (const key of ["ca3f800000", "cb3ff0000000000000"]) { - assert.throws(() => outcome.decode(readWire(fromHex(`92${key}9107`))), { message: "Union Outcome: the arm key is not an integer (declared keys: 0, 1, 2)." }, key); + assert.throws(() => outcome.decode(readWire(fromHex(`92${key}9107`))), { message: "Union Outcome: the arm key is not an integer (declared keys: -2147483648, 0, 1, 2, 2147483647)." }, key); } assert.throws(() => outcome.decode(readWire(fromHex("92cb800000000000000091a477616974"))), /^Error: Union Outcome: the arm key is not an integer/u, "-0.0 is a float, not key 0"); for (const key of ["ce80000000", "cf8000000000000000", "d30000000080000000"]) { - assert.throws(() => outcome.decode(readWire(fromHex(`92${key}9107`))), { message: "Union Outcome: the arm key is outside Int32 (declared keys: 0, 1, 2)." }, key); + assert.throws(() => outcome.decode(readWire(fromHex(`92${key}9107`))), { message: "Union Outcome: the arm key is outside Int32 (declared keys: -2147483648, 0, 1, 2, 2147483647)." }, key); } - assert.throws(() => outcome.decode(readWire(fromHex("92d2800000009107"))), { message: "Union Outcome: unknown arm key -2147483648 (declared keys: 0, 1, 2)." }); - assert.throws(() => outcome.decode(readWire(fromHex("92ff9107"))), { message: "Union Outcome: unknown arm key -1 (declared keys: 0, 1, 2)." }); + assert.throws(() => outcome.decode(readWire(fromHex("92d2800000019107"))), { message: "Union Outcome: unknown arm key -2147483647 (declared keys: -2147483648, 0, 1, 2, 2147483647)." }); + assert.throws(() => outcome.decode(readWire(fromHex("92ff9107"))), { message: "Union Outcome: unknown arm key -1 (declared keys: -2147483648, 0, 1, 2, 2147483647)." }); }); test("a union refuses a declared arm key outside Int32", () => { @@ -787,3 +802,85 @@ test("a bytes slot reads a MessagePack str as its bytes and writes bin, and refu assert.throws(() => record.decode(readWire(fromHex("91a2c328"))), { message: "b (slot 0): expected bytes, found a string that is not valid UTF-8" }); assert.throws(() => record.decode([5]), { message: "b (slot 0): expected bytes, found number" }); }); + +// ---- the bounds vectors: arm keys at the ends of the Int32 domain, nil arm slots, payload nesting ---- + +const wrapChain = (wraps: number, leaf: Node): Node => { + let node: Node = leaf; + for (let index = 0; index < wraps; index += 1) node = { kind: "Wrap", inner: node }; + return node; +}; +// A Wrap adds 2 containers, a Box with no children 3, a Text leaf 2, and the outermost array is 1 (the C# test's arithmetic). +const AT_LIMIT_WRAPS = (MAX_PAYLOAD_DEPTH - 1 - 3) / 2; +const PAST_LIMIT_WRAPS = (MAX_PAYLOAD_DEPTH + 1 - 1 - 2) / 2; +const atLimitValue: Surface = { ...golden, root: wrapChain(AT_LIMIT_WRAPS, { kind: "Box", id: "leaf", children: [] }) }; +const pastLimitValue: Surface = { ...golden, root: wrapChain(PAST_LIMIT_WRAPS, { kind: "Text", id: "leaf", content: CANARY }) }; + +async function boundsEntries() { + const raw = decode(await read("bounds-outcomes.msgpack")) as unknown[][]; + const [limit, ...rest] = raw; + return { limit, entries: rest.map(([file, outcome, unionName, key, detail]) => ({ file: file as string, outcome: outcome as string, unionName: unionName as string, key: key as number | null, detail: detail as string })) }; +} + +test("every bounds vector is listed and holds: accepted files decode and re-encode, refused files are refused naming the union or the depth", async () => { + const { limit, entries } = await boundsEntries(); + assert.deepEqual(limit, ["limit", MAX_PAYLOAD_DEPTH]); + assert.equal(entries.length, 12); + const document = surfaceDocument(); + const counts = { accepted: 0, refused: 0, readOnly: 0 }; + + for (const { file, outcome: expected, unionName, key, detail } of entries) { + const payload = documentPayloadFromBytes(await read(file)); + if (expected === "accepted") { + counts.accepted += 1; + const value = decodeDocumentPayload(document, payload); + assert.equal(hex(documentPayloadBytes(encodeDocumentPayload(document, value))), hex(await read(detail)), `${file}: re-encodes to ${detail}`); + } else if (expected === "read-only") { + counts.readOnly += 1; + assert.deepEqual(decodeDocumentPayload(document, payload), golden, `${file}: the extra slots are read past`); + } else { + counts.refused += 1; + assert.throws( + () => decodeDocumentPayload(document, payload), + (error: Error) => { + assert.ok(!error.message.includes(CANARY), `${file}: the refusal echoed the payload`); + if (detail === "depth") { + return error instanceof CultCachePayloadDepthError && error.depth === MAX_PAYLOAD_DEPTH + 1 && error.limit === MAX_PAYLOAD_DEPTH + && error.message.includes(`"${document.type}"`) && error.message.includes("257") && error.message.includes("256"); + } + assert.ok(!(error instanceof CultCachePayloadDepthError), file); + const said = detail === "key-out-of-range" ? "outside Int32" : detail === "key-not-integer" ? "not an integer" : "expected [key, slots]"; + return error.message.includes(`Union ${unionName}:`) && error.message.includes(said); + }, + file, + ); + } + } + assert.deepEqual(counts, { accepted: 3 + 1, refused: 4 + 1 + 2, readOnly: 1 }); +}); + +test("the constructed values write the committed at-limit payload byte for byte, and the past-limit value is refused and stored nowhere", async () => { + const document = surfaceDocument(); + assert.equal(hex(documentPayloadBytes(encodeDocumentPayload(document, atLimitValue))), hex(await read("depth-at-limit.msgpack"))); + assert.deepEqual(decodeDocumentPayload(document, documentPayloadFromBytes(await read("depth-at-limit.msgpack"))), atLimitValue); + + assert.throws( + () => encodeDocumentPayload(document, pastLimitValue), + (error: Error) => error instanceof CultCachePayloadDepthError && error.depth === 257 && !error.message.includes(CANARY), + ); + + const entries: CultCacheEnvelope[] = []; + const cache = CultCache.builder().withDocumentType(document).withGenericStore(memoryStore(entries)).build(); + await assert.rejects(() => cache.put(document, "past", pastLimitValue), CultCachePayloadDepthError); + assert.deepEqual(entries, [], "nothing reached the store"); + assert.equal(cache.get(document, "past"), undefined, "nothing is held in memory"); + await cache.put(document, "at", atLimitValue); + assert.equal(entries.length, 1); + assert.equal(hex(documentPayloadBytes(entries[0]!.payload)), hex(await read("depth-at-limit.msgpack"))); +}); + +test("a cache load refuses a store whose record is past the limit, naming the type and not the payload", async () => { + const document = surfaceDocument(); + const refusing = CultCache.builder().withDocumentType(document).withGenericStore(memoryStore([envelopeOf(await read("depth-past-limit.msgpack"))])).build(); + await assert.rejects(() => refusing.pullAllBackingStores(), (error: Error) => error instanceof CultCachePayloadDepthError && !error.message.includes(CANARY)); +}); diff --git a/packages/cultmesh-ts/test/codec-documents.test.ts b/packages/cultmesh-ts/test/codec-documents.test.ts index eec87133..4843c09b 100644 --- a/packages/cultmesh-ts/test/codec-documents.test.ts +++ b/packages/cultmesh-ts/test/codec-documents.test.ts @@ -5,10 +5,14 @@ import { join } from "node:path"; import test from "node:test"; import { z } from "zod"; import { + CultCachePayloadDepthError, + MAX_PAYLOAD_DEPTH, + SingleFileMessagePackBackingStore, codecs, decodeDocumentPayload, defineDocumentType, documentPayloadBytes, + documentPayloadFromBytes, encodeDocumentPayload, } from "@gamecult/cultcache-ts"; import type { CacheBackingStore, CultCacheEnvelope } from "@gamecult/cultcache-ts"; @@ -208,3 +212,50 @@ test("a store read takes the record the catalog matches to the schema and the de const store: CacheBackingStore = { pullAll: async () => records, push: async () => undefined, delete: async () => undefined }; assert.deepEqual(await cultMeshDocumentFromStore(store, target).latest(), { n: 2 }); }); + +// A payload nested past the limit: MAX_PAYLOAD_DEPTH + 1 one-element arrays around a nil. +const pastLimitPayload = () => documentPayloadFromBytes(Uint8Array.from([...new Array(MAX_PAYLOAD_DEPTH + 1).fill(0x91), 0xc0])); + +test("a payload past the nesting limit is refused at the network doors: a RUDP put and a single-file read", async () => { + const connectionId = 0x10203080; + const plainBinding = defineCultNetDocumentBinding({ definition: plainNote }); + const registry = new CultNetDocumentRegistry([plainBinding]); + const errors: unknown[] = []; + const puts: CultMeshRudpDocumentPut[] = []; + const server = CultMesh.createRudpDocumentServer("cultmesh-ts-depth-server", connectionId, { + documents: registry, + bindHost: "127.0.0.1", bindPort: 0, resendDelayMs: 25, resendPollMs: 5, + onError: (error) => errors.push(error), + onDocumentPutRaw: async (document) => { puts.push(document); }, + }); + let peer: CultNetPeer | undefined; + try { + await server.start(); + peer = await CultMesh.createRudpPeer("cultmesh-ts-depth-client", connectionId, `rudp://127.0.0.1:${server.bind.port}`, { + resendDelayMs: 25, resendPollMs: 5, connectTimeoutMs: 1_000, + }); + peer.send(registry.createRawDocumentPutMessageFromEnvelope("deep-1", { + key: "k", type: plainNote.type, schemaId: plainNote.schemaId, payload: pastLimitPayload(), storedAt: new Date().toISOString(), + })); + const startedAt = Date.now(); + while (errors.length === 0 && Date.now() - startedAt < 2_000) await new Promise((resolve) => setTimeout(resolve, 5)); + assert.equal(errors.length, 1); + assert.ok(errors[0] instanceof CultCachePayloadDepthError, "the put is refused by the payload owner"); + assert.deepEqual(puts, [], "the handler never saw the put"); + + // The server is still serving: an ordinary put goes through. + peer.send(registry.createRawDocumentPutMessage(plainBinding, "ok-1", "k2", { noteId: "k2", body: "fine" })); + while (puts.length === 0 && Date.now() - startedAt < 4_000) await new Promise((resolve) => setTimeout(resolve, 5)); + assert.equal(puts.length, 1); + } finally { + peer?.close(); + server.close(); + } + + const dir = await mkdtemp(join(tmpdir(), "cultmesh-ts-depth-store-")); + const path = join(dir, "deep.ccmp"); + await new SingleFileMessagePackBackingStore(path).push({ + key: "k", type: plainNote.type, schemaId: plainNote.schemaId, payload: pastLimitPayload(), storedAt: new Date().toISOString(), + }); + await assert.rejects(() => cultMeshDocumentFromSingleFile(path, plainNote).latest(), CultCachePayloadDepthError); +}); diff --git a/scripts/test-typescript-package-closure.mjs b/scripts/test-typescript-package-closure.mjs index 3eaf344a..58a40ae7 100644 --- a/scripts/test-typescript-package-closure.mjs +++ b/scripts/test-typescript-package-closure.mjs @@ -84,10 +84,19 @@ const mesh = require("cultmesh-ts"); assert.equal(typeof cache.defineDocumentType, "function"); // The document owner is also an entry of its own, which the browser client imports without the Node-only cache. assert.equal(documentEntry.decodeDocumentPayload, cache.decodeDocumentPayload); -assert.equal("resolveDocumentFormatter" in cache, false); -assert.equal("resolveDocumentFormatter" in documentEntry, false); -assert.equal("codecFormatter" in cache.codecs, false); -assert.equal("codecFormatter" in documentEntry, false); +// No entry exports a decoder or formatter that reads a payload around its schema: by shape, every packed export whose name +// says it decodes, reads a wire or formats is enumerated, and the only one allowed is the schema-checked owner. +const inspection = require("@gamecult/cultcache-ts/inspection"); +const decoderShaped = (entry) => Object.keys(entry).filter((name) => /decode|formatter|readwire/i.test(name)).sort(); +for (const [entryName, entry] of Object.entries({ root: cache, codecs: cache.codecs, document: documentEntry, inspection })) { + const found = decoderShaped(entry); + const allowed = entryName === "root" || entryName === "document" ? ["decodeDocumentPayload"] : []; + assert.deepEqual(found, allowed, "decoder-shaped exports of the " + entryName + " entry"); +} +assert.equal(typeof documentEntry.checkPayloadDepth, "undefined"); +assert.equal(documentEntry.MAX_PAYLOAD_DEPTH, 256); +assert.equal(cache.MAX_PAYLOAD_DEPTH, 256); +assert.equal(documentEntry.CultCachePayloadDepthError, cache.CultCachePayloadDepthError); assert.equal(typeof net.CultNetPeer, "function"); assert.equal(typeof mesh.CultMesh, "function"); assert.equal(typeof mesh.CultMeshProviderSession, "function"); From 8dfdcd8a533abf95a887d59e783d4766cf7e263b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 00:05:27 +0200 Subject: [PATCH 02/14] cultcache-ts test: the Node arm list names Wrap, and the put-refused assertion keeps the store's type Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-ts/test/union-parity.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/cultcache-ts/test/union-parity.test.ts b/packages/cultcache-ts/test/union-parity.test.ts index 575da1d8..da6d1e9e 100644 --- a/packages/cultcache-ts/test/union-parity.test.ts +++ b/packages/cultcache-ts/test/union-parity.test.ts @@ -384,7 +384,7 @@ test("a union names itself, its arm and the field when an arm's slots are refuse assert.equal(node.encode(undefined as unknown as null), null); assert.throws( () => node.encode({ kind: "Nope" } as unknown as Node), - /^Error: Union Node: the value's kind is not one of its arms \(Box, Text, Use, Image\)\.$/u, + /^Error: Union Node: the value's kind is not one of its arms \(Box, Text, Use, Image, Wrap\)\.$/u, ); }); @@ -872,7 +872,7 @@ test("the constructed values write the committed at-limit payload byte for byte, const entries: CultCacheEnvelope[] = []; const cache = CultCache.builder().withDocumentType(document).withGenericStore(memoryStore(entries)).build(); await assert.rejects(() => cache.put(document, "past", pastLimitValue), CultCachePayloadDepthError); - assert.deepEqual(entries, [], "nothing reached the store"); + assert.equal(entries.length, 0, "nothing reached the store"); assert.equal(cache.get(document, "past"), undefined, "nothing is held in memory"); await cache.put(document, "at", atLimitValue); assert.equal(entries.length, 1); From c114820c0c1a388e0010039c65f4e2a2dcffa37d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 00:08:23 +0200 Subject: [PATCH 03/14] Caching and cultcache-ts tests: slot-nil rows for a four-byte UTF-8 character in a string slot and in a byte[] slot The C# cases and the TS assertions are here; the vector file is written from the reference in the next commit, so the slot-nil tests of both runtimes fail at this commit. Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-ts/test/union-parity.test.ts | 11 +++++++++-- tests/GameCult.Caching.Tests/SlotNilVectorTests.cs | 2 ++ tests/vectors/slot-nil/README.md | 4 ++-- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/packages/cultcache-ts/test/union-parity.test.ts b/packages/cultcache-ts/test/union-parity.test.ts index da6d1e9e..f3e79b37 100644 --- a/packages/cultcache-ts/test/union-parity.test.ts +++ b/packages/cultcache-ts/test/union-parity.test.ts @@ -772,7 +772,7 @@ test("slots read and rewrite exactly what the C# reference does for nil, a str i 4: ["l", list(string), () => []], }); const rows = readWire(new Uint8Array(await readFile(join(vectors, "..", "slot-nil", "reads.msgpack")))) as [string, Uint8Array, boolean, Uint8Array][]; - assert.equal(rows.length, 15); + assert.equal(rows.length, 17); let accepted = 0; for (const [name, payload, wasAccepted, rewritten] of rows) { if (wasAccepted) { @@ -782,7 +782,14 @@ test("slots read and rewrite exactly what the C# reference does for nil, a str i assert.throws(() => probe.decode(readWire(payload)), (error: Error) => !error.message.includes(hex(payload).slice(2)), name); } } - assert.equal(accepted, 13); + assert.equal(accepted, 15); + // A character outside the BMP is four UTF-8 bytes (U+1F600 is f0 9f 98 80); a CESU-8 reader, or one with no four-byte + // branch, fails here against the bytes the C# reference wrote. + const astral = rows.find(([name]) => name === "string-astral")!; + assert.equal(probe.decode(readWire(astral[1])).s, "\u{1F600}"); + assert.equal(hex(writeWire(probe.encode(probe.decode(readWire(astral[1]))))), hex(astral[3])); + const astralInBytes = rows.find(([name]) => name === "bytes-str-astral")!; + assert.equal(hex(probe.decode(readWire(astralInBytes[1])).b), "f09f9880"); }); test("a nil reads as null and writes as nil in every reference slot, and a value slot refuses it", () => { diff --git a/tests/GameCult.Caching.Tests/SlotNilVectorTests.cs b/tests/GameCult.Caching.Tests/SlotNilVectorTests.cs index 5b1a637b..e3a24f76 100644 --- a/tests/GameCult.Caching.Tests/SlotNilVectorTests.cs +++ b/tests/GameCult.Caching.Tests/SlotNilVectorTests.cs @@ -44,6 +44,8 @@ namespace GameCult.Caching.Tests ("nil-int", "95a161c0c4026162c090"), ("bytes-str", "95a16107a3616263c090"), ("bytes-str-euro", "95a16107a3e282acc090"), + ("string-astral", "95a4f09f988007c4026162c090"), + ("bytes-str-astral", "95a16107a4f09f9880c090"), ("bytes-bin", "95a16107c403616263c090"), ("short-0", "90"), ("short-1", "91a161"), diff --git a/tests/vectors/slot-nil/README.md b/tests/vectors/slot-nil/README.md index f7ac1a2b..a74f6fdb 100644 --- a/tests/vectors/slot-nil/README.md +++ b/tests/vectors/slot-nil/README.md @@ -8,5 +8,5 @@ A record of five slots: `S` string, `I` int, `B` byte[], `R` a record of one str - `reads.msgpack`: an array of `[name, payload, accepted, rewritten]`. `payload` (bin) is the record fed to the reference; `accepted` is whether it read; `rewritten` (bin) is what the reference writes after reading it, and empty - when refused. It covers a nil in each kind of slot, a MessagePack str in the byte[] slot, and records short of their - last slots. + when refused. It covers a nil in each kind of slot, a MessagePack str in the byte[] slot, a four-byte UTF-8 character + (U+1F600) as the string slot and as a str in the byte[] slot, and records short of their last slots. From 85d8d575cff9ec9c1e29a511babd03df81047550 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 00:09:37 +0200 Subject: [PATCH 04/14] Caching tests: write slot-nil/reads.msgpack from the C# reference with the two four-byte UTF-8 rows (CULTCACHE_WRITE_VECTORS=1 on Yggdrasil) Co-Authored-By: Claude Sonnet 5.5 --- tests/vectors/slot-nil/reads.msgpack | Bin 490 -> 584 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/tests/vectors/slot-nil/reads.msgpack b/tests/vectors/slot-nil/reads.msgpack index fd972cb2904540ce78335d8d65aa41286470e765..fa104eab7692d17c2de43b4f0ec8c614bd8265e2 100644 GIT binary patch delta 106 zcmaFGe1e7f4ujxEMiIuywZ$bxnR)5Di9k9r=LqlAB_HO`Xkb6Wl$dm2!eKQ2lnqIh hC8@=_K(#Op+*21OvV--2l=FaiM_52cOcr9i0RX7XFmeC@ delta 14 VcmX@X@`{;p{zhgI#>vHuR{ Date: Mon, 12 Oct 2026 00:17:09 +0200 Subject: [PATCH 05/14] cultcache-ts test: the walk's header counts, the never-used 0xc1 and the longest fixstr, and a scalar that ends a full-depth chain Kills the survivors of the first mutation sweep (fixext2 skip, 0xc1, the fixarray/fixmap/fixstr upper bounds, map16 and map32 child counts). Co-Authored-By: Claude Sonnet 5.5 --- .../cultcache-ts/test/payload-depth.test.ts | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/packages/cultcache-ts/test/payload-depth.test.ts b/packages/cultcache-ts/test/payload-depth.test.ts index 8392bfb7..f75041d8 100644 --- a/packages/cultcache-ts/test/payload-depth.test.ts +++ b/packages/cultcache-ts/test/payload-depth.test.ts @@ -70,16 +70,32 @@ test("an empty map or array as the innermost container counts like any other", ( refused(cat(bytes(0x82), arrays(L), sibling, bytes(0x01), sibling), "a map key one deeper"); }); +test("a header counts every child it announces, up to the widest of each kind", () => { + const nils = (count: number) => repeat(bytes(0xc0), count); + const kinds: [string, Uint8Array, number][] = [ + ["the longest fixarray", bytes(0x9f), 15], + ["the longest fixmap", bytes(0x8f), 30], + ["array16 of two", bytes(0xdc, 0, 2), 2], + ["array32 of two", bytes(0xdd, 0, 0, 0, 2), 2], + ["map16 of two pairs", bytes(0xde, 0, 2), 4], + ["map32 of two pairs", bytes(0xdf, 0, 0, 0, 2), 4], + ]; + for (const [name, header, elements] of kinds) { + assert.doesNotThrow(() => checkPayloadDepth(cat(header, nils(elements - 1), arrays(L - 1))), `${name}: the last child at the limit`); + refused(cat(header, nils(elements - 1), arrays(L)), `${name}: the last child past it`); + } +}); + test("every scalar is skipped by its length, whatever bytes it holds", () => { const filler = (count: number) => repeat(bytes(0x91), count); const scalars: [string, Uint8Array][] = [ - ["nil", bytes(0xc0)], ["false", bytes(0xc2)], ["true", bytes(0xc3)], ["positive fixint", bytes(0x7f)], ["negative fixint", bytes(0xe0)], + ["nil", bytes(0xc0)], ["the never-used 0xc1", bytes(0xc1)], ["false", bytes(0xc2)], ["true", bytes(0xc3)], ["positive fixint", bytes(0x7f)], ["negative fixint", bytes(0xe0)], ["uint8", bytes(0xcc, 0x91)], ["uint16", cat(bytes(0xcd), filler(2))], ["uint32", cat(bytes(0xce), filler(4))], ["uint64", cat(bytes(0xcf), filler(8))], ["int8", bytes(0xd0, 0x91)], ["int16", cat(bytes(0xd1), filler(2))], ["int32", cat(bytes(0xd2), filler(4))], ["int64", cat(bytes(0xd3), filler(8))], ["float32", cat(bytes(0xca), filler(4))], ["float64", cat(bytes(0xcb), filler(8))], ["fixext1", cat(bytes(0xd4), filler(2))], ["fixext2", cat(bytes(0xd5), filler(3))], ["fixext4", cat(bytes(0xd6), filler(5))], ["fixext8", cat(bytes(0xd7), filler(9))], ["fixext16", cat(bytes(0xd8), filler(17))], - ["fixstr", cat(bytes(0xa3), filler(3))], ["str8", cat(bytes(0xd9, 3), filler(3))], ["str16", cat(bytes(0xda, 0, 3), filler(3))], + ["fixstr", cat(bytes(0xa3), filler(3))], ["the longest fixstr", cat(bytes(0xbf), filler(31))], ["str8", cat(bytes(0xd9, 3), filler(3))], ["str16", cat(bytes(0xda, 0, 3), filler(3))], ["str32", cat(bytes(0xdb, 0, 0, 0, 3), filler(3))], ["bin8", cat(bytes(0xc4, 3), filler(3))], ["bin16", cat(bytes(0xc5, 0, 3), filler(3))], ["bin32", cat(bytes(0xc6, 0, 0, 0, 3), filler(3))], ["ext8", cat(bytes(0xc7, 3, 0x7f), filler(3))], ["ext16", cat(bytes(0xc8, 0, 3, 0x7f), filler(3))], @@ -89,7 +105,8 @@ test("every scalar is skipped by its length, whatever bytes it holds", () => { for (const [name, scalar] of scalars) { assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x92), scalar, arrays(L - 1))), `${name} then a chain at the limit`); refused(cat(bytes(0x92), scalar, arrays(L)), `${name} then a chain past it`); - assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x92), arrays(L - 1), scalar)), `${name} after a chain at the limit`); + // As the leaf of a chain: a scalar read at the wrong length leaves containers open, and the sibling chain then reads one deeper. + assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x92), arrays(L - 1, scalar), arrays(L - 1))), `${name} closes the chain it ends`); } }); From ef682ad7b08774fe343e166e13c016fe6434493c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 01:04:26 +0200 Subject: [PATCH 06/14] cultcache-ts inspector: recoverCatalogEntry reads through the same bounded door as previewPayload Finding inspector-recover-unwalked: one decodeBoundedPayload (walk, then decode) serves both the stamp recovery and the preview, so a payload past the limit is never decoded by either. Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-ts/src/cult-cache-inspector.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/cultcache-ts/src/cult-cache-inspector.ts b/packages/cultcache-ts/src/cult-cache-inspector.ts index 43fc41cd..f1f13bbb 100644 --- a/packages/cultcache-ts/src/cult-cache-inspector.ts +++ b/packages/cultcache-ts/src/cult-cache-inspector.ts @@ -219,7 +219,7 @@ function decodeV1Record(value: unknown, catalogBySchemaId: Map { try { checkPayloadDepth(payload); From c40cc555e1a262ffc35cfa9b5af73c6c1f04267d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 01:04:27 +0200 Subject: [PATCH 07/14] cultcache-ts: the payload walk covers library-written MessagePack only; a user formatter's bytes are its own, and the 32-bit walk lengths are pinned Findings custom-formatter-bytes-walked (ruling depth-walk-covers-library-msgpack: the owner skips the walk when the definition carries a formatter; the grey 0x91 image round-trips, plain and codec stay bounded; README says so) and wide-length-unpinned (bin32/str32/ext32 of 65539 bytes and array32/map32 of more than 65535 children before a chain at and past the limit). The same tests pin the inspector refusing to recover a stamp from a past-limit payload. Not yet built. Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-ts/README.md | 4 + packages/cultcache-ts/src/document.ts | 10 ++- .../cultcache-ts/test/payload-depth.test.ts | 76 ++++++++++++++++--- 3 files changed, 78 insertions(+), 12 deletions(-) diff --git a/packages/cultcache-ts/README.md b/packages/cultcache-ts/README.md index 7fd0b0dd..9e208dfe 100644 --- a/packages/cultcache-ts/README.md +++ b/packages/cultcache-ts/README.md @@ -253,6 +253,10 @@ const combatLogDocument = defineDocumentType({ If you do not supply one, `CultCacheTS` uses MessagePack plus Zod validation by default. +The 256-container nesting bound (`MAX_PAYLOAD_DEPTH`, refused with `CultCachePayloadDepthError`) covers the MessagePack the +library itself writes: the default format and a codec. A payload your formatter writes is opaque bytes in any format, so the +library does not walk it as MessagePack; its format and its bounds are your formatter's. + Zod is no longer mandatory. Any schema object with a `parse(...)` function will do, which means generated Ajv-backed JSON-schema contracts can feed the cache directly as long as they expose the same parse surface. diff --git a/packages/cultcache-ts/src/document.ts b/packages/cultcache-ts/src/document.ts index 03c2e4a0..536e7709 100644 --- a/packages/cultcache-ts/src/document.ts +++ b/packages/cultcache-ts/src/document.ts @@ -107,6 +107,12 @@ export function documentPayloadBytes(payload: DocumentPayload): Uint8Array { export { CultCachePayloadDepthError, MAX_PAYLOAD_DEPTH } from "./payload-depth"; +// The payload nesting bound covers the MessagePack the library itself writes: the plain default formatter and a codec. A +// user formatter's bytes are opaque and in any format; its format and bounds are its own. +function writesLibraryMessagePack(definition: AnyCultCacheDocumentDefinition): boolean { + return !definition.formatter; +} + // The one reader of a document payload: through the definition's formatter, codec or plain map, then its schema. A // reader holds the definition or it has no business reading the bytes, so there is no definition-less form. export function decodeDocumentPayload( @@ -114,7 +120,7 @@ export function decodeDocumentPayload { const bytes = documentPayloadBytes(payload); - checkPayloadDepth(bytes, `document type "${definition.type}" payload`); + if (writesLibraryMessagePack(definition)) checkPayloadDepth(bytes, `document type "${definition.type}" payload`); const decoded = resolveDocumentFormatter(definition).decode(bytes); return definition.schema.parse(decoded) as CultCacheDocumentValue; } @@ -122,7 +128,7 @@ export function decodeDocumentPayload (slotCalls.push("decode"), codecs.string.decode(raw)), encode: (value: string) => (slotCalls.push("encode"), codecs.string.encode(value)) }; const guarded = defineDocumentType({ type: "t.guarded", schemaId: "t.guarded.v0", schema: note, name: "id", - formatter: { - encode: () => (formatterCalls.push("encode"), arrays(L + 1)), - decode: () => (formatterCalls.push("decode"), { id: "a", count: 1 }), - }, + codec: codecs.slots<{ id: string; count: number }>({ 0: ["id", watched], 1: ["count", codecs.int32] }, "T.Guarded"), }); -test("the owner refuses a payload past the limit before its formatter reads it, and a formatter's bytes before they are wrapped", () => { +test("the owner refuses a payload past the limit before a codec reads it, and a codec's bytes before they are wrapped", () => { assert.throws(() => decodeDocumentPayload(guarded, documentPayloadFromBytes(arrays(L + 1))), CultCachePayloadDepthError); - assert.deepEqual(formatterCalls, [], "the formatter never saw the deep payload"); - assert.deepEqual(decodeDocumentPayload(guarded, documentPayloadFromBytes(arrays(L))), { id: "a", count: 1 }); + assert.deepEqual(slotCalls, [], "the codec never saw the deep payload"); + assert.deepEqual(decodeDocumentPayload(guarded, documentPayloadFromBytes(encode(["a", 1]))), { id: "a", count: 1 }); - assert.throws(() => encodeDocumentPayload(guarded, { id: "a", count: 1 }), (error: Error) => - error instanceof CultCachePayloadDepthError && error.message === 'document type "t.guarded" value nests 257 MessagePack containers deep; the limit is 256.'); + const formatterBytes = (value: unknown) => documentPayloadBytes(encodeDocumentPayload(guarded, value)); + assert.deepEqual(formatterBytes({ id: "a", count: 1 }), encode(["a", 1])); }); test("a document without a codec or formatter writes a value L deep and refuses L+1 by the walk", () => { @@ -189,11 +188,13 @@ test("the inspector previews a payload at the limit and reports one past it, or const atLimit = await storeWith(stamped(L - 1)); const previewed = inspectCultCacheBytes(atLimit, await readFile(atLimit)).records[0]!; assert.equal(previewed.payloadDecodeError, undefined); + assert.equal(previewed.schemaName, "tests.schema_stamped_entry", "a payload the walk accepts yields its stamp"); for (const inside of [L, 100_000]) { const file = await storeWith(stamped(inside)); const record = inspectCultCacheBytes(file, await readFile(file)).records[0]!; assert.equal(record.payloadDecodeError, "document payload nests 257 MessagePack containers deep; the limit is 256."); + assert.equal(record.schemaName, "", "the stamp of a payload the walk refuses is not recovered"); } }); @@ -205,3 +206,58 @@ test("the single-file store infers a legacy record's schema from a payload at th const past = await storeWith(stamped(L)); await assert.rejects(() => new SingleFileMessagePackBackingStore(past).pullAll(), /missing schema id/u); }); + +// A header whose length or count needs all four bytes: the low sixteen bits of the length are small, the whole is not. +const be32 = (n: number) => bytes((n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff); + +test("a 32-bit length or count is read whole: the walk skips a 65539-byte scalar and counts 65540 children", () => { + const blob = repeat(bytes(0x91), 65539); + const scalars: [string, Uint8Array][] = [ + ["bin32", cat(bytes(0xc6), be32(65539), blob)], + ["str32", cat(bytes(0xdb), be32(65539), blob)], + ["ext32", cat(bytes(0xc9), be32(65539), bytes(0x7f), blob)], + ]; + for (const [name, scalar] of scalars) { + assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x92), scalar, arrays(L - 1))), `${name} of 65539 bytes then a chain at the limit`); + refused(cat(bytes(0x92), scalar, arrays(L)), `${name} of 65539 bytes then a chain past it`); + } + const nils = repeat(bytes(0xc0), 65540); + for (const [name, header] of [["array32", cat(bytes(0xdd), be32(65540))], ["map32", cat(bytes(0xdf), be32(32770))]] as const) { + refused(cat(bytes(0x92), header, nils, arrays(L)), `${name} announcing more than 65535: the sibling chain past the limit`); + assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x92), header, nils, arrays(L - 1))), `${name}: the sibling chain at the limit`); + } +}); + +test("a user formatter's bytes are its own: a 0x91 grey image round-trips, while plain and codec documents are still walked", () => { + const grey = defineDocumentType({ + type: "t.grey", + schemaId: "t.grey.v0", + schema: z.object({ pixels: z.instanceof(Uint8Array) }), + name: "pixels", + formatter: { encode: (value) => (value as { pixels: Uint8Array }).pixels, decode: (payload) => ({ pixels: payload }) }, + }); + for (const size of [300, 4096]) { + const pixels = new Uint8Array(size).fill(0x91); + const written = encodeDocumentPayload(grey, { pixels }); + assert.deepEqual(documentPayloadBytes(written), pixels, `${size} bytes written as the formatter made them`); + assert.deepEqual(decodeDocumentPayload(grey, written), { pixels }, `${size} bytes read back through the formatter`); + } + + const anything = defineDocumentType({ type: "t.any2", schemaId: "t.any2.v0", schema: z.any(), name: "id" }); + const nest = (n: number): unknown => (n === 1 ? [] : [nest(n - 1)]); + assert.throws(() => encodeDocumentPayload(anything, nest(L + 1)), CultCachePayloadDepthError); + assert.throws(() => decodeDocumentPayload(anything, documentPayloadFromBytes(arrays(L + 1))), CultCachePayloadDepthError); + + type Tree = unknown[]; + const tree: codecs.Codec = codecs.lazy(() => codecs.list(tree)); + const coded = defineDocumentType({ + type: "t.coded", + schemaId: "t.coded.v0", + schema: z.any(), + name: "id", + codec: codecs.slots<{ id: string; inner: Tree }>({ 0: ["id", codecs.string], 1: ["inner", tree] }, "T.Coded"), + }); + assert.doesNotThrow(() => encodeDocumentPayload(coded, { id: "a", inner: nest(L - 1) as Tree })); + assert.throws(() => encodeDocumentPayload(coded, { id: "a", inner: nest(L) as Tree }), CultCachePayloadDepthError); + assert.throws(() => decodeDocumentPayload(coded, documentPayloadFromBytes(arrays(L + 1))), CultCachePayloadDepthError); +}); From 27b9e2b31549fab4f1f603dfe1d52089d38fbeec Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 01:04:27 +0200 Subject: [PATCH 08/14] test:pack:ts denies payload readers by identity and behaviour, not by name Finding pack-denial-by-name: the package-internal readers (readWire, resolveDocumentFormatter, @msgpack decode) are loaded from the packed dist by path and searched by identity through every packed entry, including default and namespace members; every other exported function is shown a MessagePack map and must not return it decoded. Co-Authored-By: Claude Sonnet 5.5 --- scripts/test-typescript-package-closure.mjs | 51 ++++++++++++++++++--- 1 file changed, 44 insertions(+), 7 deletions(-) diff --git a/scripts/test-typescript-package-closure.mjs b/scripts/test-typescript-package-closure.mjs index 58a40ae7..914cf8cf 100644 --- a/scripts/test-typescript-package-closure.mjs +++ b/scripts/test-typescript-package-closure.mjs @@ -84,14 +84,51 @@ const mesh = require("cultmesh-ts"); assert.equal(typeof cache.defineDocumentType, "function"); // The document owner is also an entry of its own, which the browser client imports without the Node-only cache. assert.equal(documentEntry.decodeDocumentPayload, cache.decodeDocumentPayload); -// No entry exports a decoder or formatter that reads a payload around its schema: by shape, every packed export whose name -// says it decodes, reads a wire or formats is enumerated, and the only one allowed is the schema-checked owner. +// No entry exports a function that reads a payload around its schema, whatever it is called, wherever it is mounted: the +// package-internal readers are loaded from the packed dist files by path and looked for by identity in every packed +// entry (own names, 'default', and the members of any namespace or function export), and every exported function is +// shown a MessagePack map and must not hand it back decoded. The only reader allowed is the schema-checked owner. +const path = require("node:path"); +const msgpack = require("@msgpack/msgpack"); +const dist = path.dirname(require.resolve("@gamecult/cultcache-ts")); +const internalReaders = new Map([ + ["readWire", require(path.join(dist, "wire.js")).readWire], + ["resolveDocumentFormatter", require(path.join(dist, "document-formatter.js")).resolveDocumentFormatter], + ["@msgpack/msgpack decode", msgpack.decode], + ["@msgpack/msgpack decodeMulti", msgpack.decodeMulti], +]); +for (const [name, reader] of internalReaders) assert.equal(typeof reader, "function", name + " was found in the packed package"); const inspection = require("@gamecult/cultcache-ts/inspection"); -const decoderShaped = (entry) => Object.keys(entry).filter((name) => /decode|formatter|readwire/i.test(name)).sort(); -for (const [entryName, entry] of Object.entries({ root: cache, codecs: cache.codecs, document: documentEntry, inspection })) { - const found = decoderShaped(entry); - const allowed = entryName === "root" || entryName === "document" ? ["decodeDocumentPayload"] : []; - assert.deepEqual(found, allowed, "decoder-shaped exports of the " + entryName + " entry"); +const entries = { root: cache, codecs: cache.codecs, document: documentEntry, inspection }; +const probePayload = msgpack.encode({ probe: 7 }); +const exportsOf = (entry) => { + const found = []; + const seen = new Set(); + const visit = (value, where, depth) => { + if ((typeof value !== "function" && (typeof value !== "object" || value === null)) || seen.has(value) || depth > 4) return; + seen.add(value); + found.push([where, value]); + for (const key of Object.getOwnPropertyNames(value)) { + if (typeof value === "function" && ["length", "name", "prototype", "caller", "arguments"].includes(key)) continue; + let member; + try { member = value[key]; } catch { continue; } + visit(member, where + "." + key, depth + 1); + } + }; + for (const key of Object.getOwnPropertyNames(entry)) visit(entry[key], key, 0); + return found; +}; +for (const [entryName, entry] of Object.entries(entries)) { + for (const [where, value] of exportsOf(entry)) { + for (const [name, reader] of internalReaders) { + assert.notEqual(value, reader, entryName + " entry exports " + name + " as " + where); + } + if (typeof value !== "function" || value === cache.decodeDocumentPayload) continue; + let returned; + try { returned = value(probePayload); } catch { continue; } + assert.ok(!JSON.stringify(returned, (_key, member) => (member instanceof Map ? Object.fromEntries(member) : member))?.includes('"probe":7'), + entryName + " entry exports " + where + ", which reads a payload without its schema"); + } } assert.equal(typeof documentEntry.checkPayloadDepth, "undefined"); assert.equal(documentEntry.MAX_PAYLOAD_DEPTH, 256); From 05f9937bbc19092dba11d848fc647d2ad0be15d3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 01:07:51 +0200 Subject: [PATCH 09/14] wip --- packages/cultcache-ts/test/payload-depth.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/cultcache-ts/test/payload-depth.test.ts b/packages/cultcache-ts/test/payload-depth.test.ts index 7327d7a9..5572692e 100644 --- a/packages/cultcache-ts/test/payload-depth.test.ts +++ b/packages/cultcache-ts/test/payload-depth.test.ts @@ -232,7 +232,7 @@ test("a user formatter's bytes are its own: a 0x91 grey image round-trips, while const grey = defineDocumentType({ type: "t.grey", schemaId: "t.grey.v0", - schema: z.object({ pixels: z.instanceof(Uint8Array) }), + schema: z.object({ pixels: z.custom() }), name: "pixels", formatter: { encode: (value) => (value as { pixels: Uint8Array }).pixels, decode: (payload) => ({ pixels: payload }) }, }); From d64f688459e810c93c97deb11374d3ce38b8e4e1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 01:08:44 +0200 Subject: [PATCH 10/14] test fixes: the grey-image schema is a custom check, and the pack probe treats a throwing result as not a reader Fixes the previous commit (05f9937b, mislabelled wip): its test file did not compile (TS2322) and the pack probe threw on a lazy codec's getters. Co-Authored-By: Claude Sonnet 5.5 --- scripts/test-typescript-package-closure.mjs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/scripts/test-typescript-package-closure.mjs b/scripts/test-typescript-package-closure.mjs index 914cf8cf..c71101b5 100644 --- a/scripts/test-typescript-package-closure.mjs +++ b/scripts/test-typescript-package-closure.mjs @@ -124,10 +124,11 @@ for (const [entryName, entry] of Object.entries(entries)) { assert.notEqual(value, reader, entryName + " entry exports " + name + " as " + where); } if (typeof value !== "function" || value === cache.decodeDocumentPayload) continue; - let returned; - try { returned = value(probePayload); } catch { continue; } - assert.ok(!JSON.stringify(returned, (_key, member) => (member instanceof Map ? Object.fromEntries(member) : member))?.includes('"probe":7'), - entryName + " entry exports " + where + ", which reads a payload without its schema"); + let shown; + try { + shown = JSON.stringify(value(probePayload), (_key, member) => (member instanceof Map ? Object.fromEntries(member) : member)); + } catch { continue; } + assert.ok(!shown?.includes('"probe":7'), entryName + " entry exports " + where + ", which reads a payload without its schema"); } } assert.equal(typeof documentEntry.checkPayloadDepth, "undefined"); From 542a3d904eb6a9c9ddecd190d5cfa0cfac7abc49 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 01:11:18 +0200 Subject: [PATCH 11/14] cultcache-ts test: the deep codec document uses a slot codec that writes N nested arrays (a self-recursive list codec has no finite type name) Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-ts/test/payload-depth.test.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/cultcache-ts/test/payload-depth.test.ts b/packages/cultcache-ts/test/payload-depth.test.ts index 5572692e..7d8c1ca1 100644 --- a/packages/cultcache-ts/test/payload-depth.test.ts +++ b/packages/cultcache-ts/test/payload-depth.test.ts @@ -248,16 +248,20 @@ test("a user formatter's bytes are its own: a 0x91 grey image round-trips, while assert.throws(() => encodeDocumentPayload(anything, nest(L + 1)), CultCachePayloadDepthError); assert.throws(() => decodeDocumentPayload(anything, documentPayloadFromBytes(arrays(L + 1))), CultCachePayloadDepthError); - type Tree = unknown[]; - const tree: codecs.Codec = codecs.lazy(() => codecs.list(tree)); + // A slot that writes `depth` nested arrays, so a codec document can be made as deep as the test needs. + const nested: codecs.Codec = { + typeName: "System.Object", + encode: (depth) => nest(depth), + decode: (raw) => (raw as unknown[]).length, + }; const coded = defineDocumentType({ type: "t.coded", schemaId: "t.coded.v0", schema: z.any(), name: "id", - codec: codecs.slots<{ id: string; inner: Tree }>({ 0: ["id", codecs.string], 1: ["inner", tree] }, "T.Coded"), + codec: codecs.slots<{ id: string; depth: number }>({ 0: ["id", codecs.string], 1: ["depth", nested] }, "T.Coded"), }); - assert.doesNotThrow(() => encodeDocumentPayload(coded, { id: "a", inner: nest(L - 1) as Tree })); - assert.throws(() => encodeDocumentPayload(coded, { id: "a", inner: nest(L) as Tree }), CultCachePayloadDepthError); + assert.doesNotThrow(() => encodeDocumentPayload(coded, { id: "a", depth: L - 1 })); + assert.throws(() => encodeDocumentPayload(coded, { id: "a", depth: L }), CultCachePayloadDepthError); assert.throws(() => decodeDocumentPayload(coded, documentPayloadFromBytes(arrays(L + 1))), CultCachePayloadDepthError); }); From 986faf1f33fb198e6ec0717014b9f5b8c493aa7e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 01:22:47 +0200 Subject: [PATCH 12/14] test:pack:ts probe shows each exported function a map and a slot record (readWire refuses a map, so a wrapper of it passed the map-only probe) Co-Authored-By: Claude Sonnet 5.5 --- scripts/test-typescript-package-closure.mjs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/scripts/test-typescript-package-closure.mjs b/scripts/test-typescript-package-closure.mjs index c71101b5..5544af06 100644 --- a/scripts/test-typescript-package-closure.mjs +++ b/scripts/test-typescript-package-closure.mjs @@ -87,7 +87,7 @@ assert.equal(documentEntry.decodeDocumentPayload, cache.decodeDocumentPayload); // No entry exports a function that reads a payload around its schema, whatever it is called, wherever it is mounted: the // package-internal readers are loaded from the packed dist files by path and looked for by identity in every packed // entry (own names, 'default', and the members of any namespace or function export), and every exported function is -// shown a MessagePack map and must not hand it back decoded. The only reader allowed is the schema-checked owner. +// shown a MessagePack map and a slot record and must not hand either back decoded. The only reader allowed is the schema-checked owner. const path = require("node:path"); const msgpack = require("@msgpack/msgpack"); const dist = path.dirname(require.resolve("@gamecult/cultcache-ts")); @@ -100,7 +100,8 @@ const internalReaders = new Map([ for (const [name, reader] of internalReaders) assert.equal(typeof reader, "function", name + " was found in the packed package"); const inspection = require("@gamecult/cultcache-ts/inspection"); const entries = { root: cache, codecs: cache.codecs, document: documentEntry, inspection }; -const probePayload = msgpack.encode({ probe: 7 }); +// A map and a slot record (an array), each with the text its decoded form prints as: a reader of either shape gives itself away. +const probes = [{ probe: 7 }, ["probe", 7]].map((value) => [msgpack.encode(value), JSON.stringify(value)]); const exportsOf = (entry) => { const found = []; const seen = new Set(); @@ -124,11 +125,13 @@ for (const [entryName, entry] of Object.entries(entries)) { assert.notEqual(value, reader, entryName + " entry exports " + name + " as " + where); } if (typeof value !== "function" || value === cache.decodeDocumentPayload) continue; - let shown; - try { - shown = JSON.stringify(value(probePayload), (_key, member) => (member instanceof Map ? Object.fromEntries(member) : member)); - } catch { continue; } - assert.ok(!shown?.includes('"probe":7'), entryName + " entry exports " + where + ", which reads a payload without its schema"); + for (const [probePayload, decodedText] of probes) { + let shown; + try { + shown = JSON.stringify(value(probePayload), (_key, member) => (member instanceof Map ? Object.fromEntries(member) : member)); + } catch { continue; } + assert.ok(!shown?.includes(decodedText), entryName + " entry exports " + where + ", which reads a payload without its schema"); + } } } assert.equal(typeof documentEntry.checkPayloadDepth, "undefined"); From 0451e4afc1bda67e571724e616ed5779f3e0633e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 01:32:15 +0200 Subject: [PATCH 13/14] cultcache-ts test: the plain-document write refusal names its document type (kills the Stryker survivor on the encode subject) Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-ts/test/payload-depth.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/cultcache-ts/test/payload-depth.test.ts b/packages/cultcache-ts/test/payload-depth.test.ts index 7d8c1ca1..1a95924b 100644 --- a/packages/cultcache-ts/test/payload-depth.test.ts +++ b/packages/cultcache-ts/test/payload-depth.test.ts @@ -164,7 +164,8 @@ test("a document without a codec or formatter writes a value L deep and refuses assert.deepEqual(documentPayloadBytes(atLimit), encode(nest(L), { maxDepth: 1000 })); assert.deepEqual(decodeDocumentPayload(anything, atLimit), nest(L)); assert.throws(() => encodeDocumentPayload(anything, nest(L + 1)), (error: unknown) => - error instanceof CultCachePayloadDepthError && error.depth === L + 1 && error.limit === L); + error instanceof CultCachePayloadDepthError && error.depth === L + 1 && error.limit === L + && error.message === 'document type "t.any" value nests 257 MessagePack containers deep; the limit is 256.'); assert.throws(() => decodeDocumentPayload(anything, documentPayloadFromBytes(arrays(L + 1))), CultCachePayloadDepthError); }); From 3b2af2b232fa3e10402dee8f107604b410c4cc71 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 01:50:05 +0200 Subject: [PATCH 14/14] cultcache-ts: previewPayload reads through decodeBoundedPayload (the inspector's one walk site); the map32 and array32 counts are pinned above 65535 The wide-count test announced map32 as 32770 pairs, which fits in 16 bits, so a count read as its low 16 bits survived. map32 now announces 65537 pairs and array32 65540 children; both low halves close the container early. Builds: yes. Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-ts/src/cult-cache-inspector.ts | 3 +-- packages/cultcache-ts/test/payload-depth.test.ts | 9 +++++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/cultcache-ts/src/cult-cache-inspector.ts b/packages/cultcache-ts/src/cult-cache-inspector.ts index f1f13bbb..56a0f6e3 100644 --- a/packages/cultcache-ts/src/cult-cache-inspector.ts +++ b/packages/cultcache-ts/src/cult-cache-inspector.ts @@ -295,8 +295,7 @@ function decodeBoundedPayload(payload: Uint8Array): unknown { function previewPayload(payload: Uint8Array): Pick { try { - checkPayloadDepth(payload); - return { payloadPreview: toJsonSafe(decode(payload)) }; + return { payloadPreview: toJsonSafe(decodeBoundedPayload(payload)) }; } catch (error) { return { payloadPreview: { diff --git a/packages/cultcache-ts/test/payload-depth.test.ts b/packages/cultcache-ts/test/payload-depth.test.ts index 1a95924b..02e55ab3 100644 --- a/packages/cultcache-ts/test/payload-depth.test.ts +++ b/packages/cultcache-ts/test/payload-depth.test.ts @@ -222,8 +222,13 @@ test("a 32-bit length or count is read whole: the walk skips a 65539-byte scalar assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x92), scalar, arrays(L - 1))), `${name} of 65539 bytes then a chain at the limit`); refused(cat(bytes(0x92), scalar, arrays(L)), `${name} of 65539 bytes then a chain past it`); } - const nils = repeat(bytes(0xc0), 65540); - for (const [name, header] of [["array32", cat(bytes(0xdd), be32(65540))], ["map32", cat(bytes(0xdf), be32(32770))]] as const) { + // Both counts exceed 65535 and their low sixteen bits are small (4 children; 1 pair), so a count cut to 16 bits closes the container early. + const wide: [string, Uint8Array, number][] = [ + ["array32", cat(bytes(0xdd), be32(65540)), 65540], + ["map32", cat(bytes(0xdf), be32(65537)), 2 * 65537], + ]; + for (const [name, header, children] of wide) { + const nils = repeat(bytes(0xc0), children); refused(cat(bytes(0x92), header, nils, arrays(L)), `${name} announcing more than 65535: the sibling chain past the limit`); assert.doesNotThrow(() => checkPayloadDepth(cat(bytes(0x92), header, nils, arrays(L - 1))), `${name}: the sibling chain at the limit`); }