cultnet-ts, cultmesh-ts: refuse a peer raw put with no stamp (raw-put-refuse-ts)

One judgment, isStoredAtStamp (cultcache-ts, the stored-at-stamp vector's shape), used by the RUDP document server (message_invalid, field document,
after the authority, before sizing) and by the registry that stores a put (throws, nothing stored). The put parser leaves storedAt to them.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Libby 2026-11-14 04:53:55 +00:00
commit 408a5ae571
12 changed files with 193 additions and 6 deletions

View file

@ -7,6 +7,7 @@ All notable changes to `@gamecult/cultcache-ts` are recorded here, following
### Added
- `isStoredAtStamp(text)` (package and browser entries): whether a `storedAt` is a stamp, the one shape pinned in `tests/vectors/stored-at-stamp/` (an RFC 3339 date-time with `T`, an optional 1 to 9 digit fraction, `Z` or `+hh:mm`/`-hh:mm`, a real calendar date, seconds 00-59, years 0001-9999). cultnet-ts and cultmesh-ts judge a peer's put by it (variants:ruling:raw-put-without-stamp-refused).
- `CacheBackingStore` gains the optional `read(key)` (the record at the key with its content version, from one read) and `commitIf(entry, expectedVersion)` (write only if the version still holds, under the store's write lock; returns the storedAt written). The single-file store implements both. The content version is the lowercase hex SHA-256 of the record's persisted encoding `[key, schemaId, storedAt, payload]`, equal to the C# reference's on `tests/vectors/content-version`. A store without them still works for everything except `update`.
- `CultCacheUpdateResult` and `CultCacheUpdateOptions` (`maxAttempts`, default 5), exported from the package entry and the browser entry.

View file

@ -16,6 +16,7 @@ export {
} from "./document";
export { CultCachePayloadDepthError, MAX_PAYLOAD_DEPTH } from "./payload-depth";
export type { DocumentPayload } from "./document";
export { isStoredAtStamp } from "./stored-at";
export { SchemaConflictError, StoreUnreadableError } from "./store-format";
export type {
AnyCultCacheDocumentDefinition,

View file

@ -0,0 +1,33 @@
// The one shape a `storedAt` stamp has (tests/vectors/stored-at-stamp/README.md; reference `parse_stored_at` in cultcache-py): an
// RFC 3339 date-time `YYYY-MM-DDThh:mm:ss`, an optional fraction of 1 to 9 digits, and `Z` or `+hh:mm` / `-hh:mm` (hours 00-23,
// minutes 00-59). A real calendar date, seconds 00-59, and an instant within years 0001-9999. Checked here, not left to
// `Date.parse`, which accepts shapes this one does not and whose accepted set differs by engine.
const STAMP = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.[0-9]{1,9})?(?:Z|([+-])([01][0-9]|2[0-3]):([0-5][0-9]))$/;
const MS_PER_MINUTE = 60_000;
/** True when `text` is a string that is a stamp. Anything else (missing, empty, wrong type, other shapes) is not. */
export function isStoredAtStamp(text: unknown): text is string {
if (typeof text !== "string") return false;
const shape = STAMP.exec(text);
if (shape === null) return false;
const [year, month, day, hour, minute, second] = shape.slice(1, 7).map(Number) as [number, number, number, number, number, number];
const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
const daysInMonth = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
if (year < 1 || month < 1 || month > 12 || day < 1 || day > (daysInMonth as number) || hour > 23 || minute > 59 || second > 59) {
return false;
}
// The UTC instant must stay within years 0001-9999, so an offset can push a boundary date out of range.
const local = new Date(0);
local.setUTCFullYear(year, month - 1, day);
local.setUTCHours(hour, minute, second, 0);
const offsetMinutes = shape[7] === undefined ? 0 : (shape[7] === "-" ? -1 : 1) * (Number(shape[8]) * 60 + Number(shape[9]));
const utcMs = local.getTime() - offsetMinutes * MS_PER_MINUTE;
const first = new Date(0);
first.setUTCFullYear(1, 0, 1);
first.setUTCHours(0, 0, 0, 0);
const last = new Date(0);
last.setUTCFullYear(9999, 11, 31);
last.setUTCHours(23, 59, 59, 999);
return utcMs >= first.getTime() && utcMs <= last.getTime();
}

View file

@ -0,0 +1,20 @@
// isStoredAtStamp agrees with every row of tests/vectors/stored-at-stamp/stamps.msgpack, the one shape a peer's storedAt must parse as.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import test from "node:test";
import { decode } from "@msgpack/msgpack";
import { isStoredAtStamp } from "../src";
// dist-test/test -> the repository root.
export const STAMP_VECTOR = join(__dirname, "..", "..", "..", "..", "tests", "vectors", "stored-at-stamp", "stamps.msgpack");
test("isStoredAtStamp answers every row of the stored-at-stamp vector", () => {
const rows = decode(readFileSync(STAMP_VECTOR)) as [string, boolean][];
assert.ok(rows.length > 20, "the vector was read");
for (const [text, parses] of rows) assert.equal(isStoredAtStamp(text), parses, JSON.stringify(text));
});
test("a stamp is a string: anything else is not one", () => {
for (const value of [undefined, null, 0, 1_700_000_000_000, true, {}, [], new Date()]) assert.equal(isStoredAtStamp(value), false);
});

View file

@ -11,6 +11,7 @@ All notable changes to `@gamecult/cultmesh-ts` are recorded here, following
### Breaking
- `createRudpDocumentServer` refuses a peer put whose `storedAt` is missing, empty or not a stamp (`isStoredAtStamp`, the shape pinned in `tests/vectors/stored-at-stamp/`) with `message_invalid` naming `document`, after the write authority has been asked and before the put is sized; `onDocumentPutRaw` is not called, so nothing is stored and no stamp is minted (variants:ruling:raw-put-without-stamp-refused). `CultMeshRudpDocumentPut.storedAt` is the stamp the peer sent, never a server clock; a document synced from a peer with a stampless record is refused by the registry.
- `publishRudpDocumentOnce` no longer treats a window with no refusal as published: a put nothing settled in its result window (500 ms, or 5000 ms against a receipt-capable server) rejects `CultMeshRudpWriteUnconfirmedError`, and a legacy server's echo of the put's id is not admission. It now resolves `"admitted"` (only on a `write_admitted`) or `"sent"`. **Migration:** a caller whose server cannot answer a write yet (for example Odin, until it is receipt-capable) passes `sendOnly: true` per call and treats `"sent"` as "sent", never as admitted. Receipts stay opt-in (`writeReceipts: true`); neither mode is the default.
- The package is renamed `cultmesh-ts` to `@gamecult/cultmesh-ts` (the repo already scopes `@gamecult/cultcache-ts`), so the unscoped name cannot be claimed by someone else. Import from `@gamecult/cultmesh-ts` and its subpaths; the API is unchanged. Depends on `@gamecult/cultnet-ts`.
- `asSchemaAlias` is removed from `CultMeshDocumentHandle`, `CultMeshCollectionHandle` and their bound forms. Read the handle by the schema you mean.

View file

@ -5,6 +5,7 @@ import {
CultCache,
SchemaConflictError,
SingleFileMessagePackBackingStore,
isStoredAtStamp,
schemaIdentityOf,
type AnyCultCacheDocumentDefinition,
type CacheBackingStore,
@ -5813,6 +5814,12 @@ export class CultMesh {
));
return;
}
// A peer's put is stored under the stamp it carries: one that is no stamp is refused, after the authority
// has spoken and before the put is sized, so the size-limited path never measures it. Nothing is minted.
if (!isStoredAtStamp(message.document.storedAt)) {
sendSchemaMessage(record, cultNetMessageInvalidError("document", "Raw put documents must carry a storedAt stamp."));
return;
}
}
if (options.onDocumentPutRaw) {
const unservable = unservablePut(message);
@ -6635,7 +6642,7 @@ function normalizeRudpDocumentPut(
return {
schemaId: document.schemaId,
recordKey: document.recordKey,
storedAt: document.storedAt ?? new Date().toISOString(),
storedAt: document.storedAt,
sourceRuntimeId: document.sourceRuntimeId ?? null,
sourceAgentId: document.sourceAgentId ?? null,
sourceRole: document.sourceRole ?? null,

View file

@ -3423,11 +3423,12 @@ const servedBoundRegistry = () =>
/**
* A put's own storedAt, kept by the served record and replaced in the receipt by the server's
* 24-character clock. `SERVED_STORED_AT` is long, so an echoed receipt is smaller than the served
* reply; `RECEIPT_STORED_AT` is short, so an echoed receipt is the larger reply, which shows that
* 24-character clock. `SERVED_STORED_AT` is as long as a stamp can be (a stamp is judged before a put is
* sized, so padding one is refused), so an echoed receipt is smaller than the served reply;
* `RECEIPT_STORED_AT` is short, so an echoed receipt is the larger reply, which shows that
* admission sizes only the served reply.
*/
const SERVED_STORED_AT = `2026-09-30T00:00:00.000Z${"~".repeat(200)}`;
const SERVED_STORED_AT = "2026-09-30T00:00:00.123456789+00:00"; // the longest a stamp can be, 35 characters
const RECEIPT_STORED_AT = "2026-09-30T00:00:00.000Z";
const SERVED_BOUND_SERVER = "cultmesh-ts-served-bound-server";

View file

@ -7,6 +7,7 @@ import { join } from "node:path";
import test from "node:test";
import { z } from "zod";
import { documentPayloadFromBytes, defineDocumentType } from "@gamecult/cultcache-ts";
import { decode } from "@msgpack/msgpack";
import { decodeRudpPacket } from "@gamecult/cultnet-ts";
import { encodeWireValue } from "@gamecult/cultnet-ts/wire";
import {
@ -310,6 +311,64 @@ test("the refusal on the wire is the pinned error-vectors bytes", async () => {
});
});
// A peer's put is stored under the stamp it carries: every row of the shared vector goes through the real handler. A row that
// is no stamp is refused message_invalid naming `document`, on the plain, the size-limited and (RUDP is this server's only
// transport) the capped path; the handler never runs, so nothing is stored or minted, and a stamped put after it still lands.
const STAMP_VECTOR = join(__dirname, "..", "..", "..", "..", "tests", "vectors", "stored-at-stamp", "stamps.msgpack");
test("a put whose storedAt is no stamp is refused message_invalid (document), for every row of the stamp vector", async () => {
const rows = decode(readFileSync(STAMP_VECTOR)) as [string, boolean][];
const cases: [string, unknown, boolean][] = [...rows.map(([text, parses]): [string, unknown, boolean] => [JSON.stringify(text), text, parses]),
["missing", undefined, false], ["number", 1_700_000_000_000, false]];
for (const extra of [{}, { maxPayloadBytes: 4096 }]) {
await using(await rig(new CultMeshGrantAllWrites(), extra), async (r) => {
let accepted = 0;
for (const [label, storedAt, parses] of cases) {
const message = put(KEY_A) as unknown as { document: Record<string, unknown> };
if (storedAt === undefined) delete message.document.storedAt; else message.document.storedAt = storedAt;
const seen = r.replies.length;
const handled = r.puts.length;
r.peer.send(message as unknown as CultNetMessage);
await sleep(40);
if (parses) {
accepted += 1;
assert.equal(r.puts.length, handled + 1, `${label}: a stamp reaches the handler`);
assert.equal(r.replies.length, seen, label);
} else {
assert.equal(r.puts.length, handled, `${label}: nothing handled, so nothing minted or stored`);
const reply = r.replies[seen] as { schemaVersion?: string; code?: string; details?: { field?: string } } | undefined;
assert.equal(reply?.schemaVersion, "cultnet.error.v0", label);
assert.equal(reply?.code, "message_invalid", label);
assert.equal(reply?.details?.field, "document", label);
}
}
assert.ok(accepted > 0);
assert.deepEqual(r.errors, []);
// The large put under a garbage stamp is refused for its stamp, before it is measured.
const large = put(KEY_A, {}, SCHEMA_ID, new Uint8Array(20_000)) as unknown as { document: Record<string, unknown> };
large.document.storedAt = "yesterday";
r.peer.send(large as unknown as CultNetMessage);
await sleep(60);
const last = r.replies[r.replies.length - 1] as { code?: string; details?: { field?: string } };
assert.equal(last.code, "message_invalid");
assert.equal(last.details?.field, "document");
});
}
// The stamp is judged after the authority: an ungranted peer hears write_not_authorized, aliased or not.
const refusing = new Recording(() => ({ granted: false, reason: "no" }));
await using(await rig(refusing), async (r) => {
const aliased = put(KEY_A, {}, ALIAS) as unknown as { document: Record<string, unknown> };
aliased.document.storedAt = "yesterday";
r.peer.send(aliased as unknown as CultNetMessage);
r.peer.send(put(KEY_B));
await r.settle();
assertRefused(r.replies[0], KEY_A);
assertRefused(r.replies[1], KEY_B);
assert.equal(refusing.requests[0]?.schemaId, SCHEMA_ID, "an aliased put asks under the canonical id");
assert.equal(r.puts.length, 0);
});
});
test("wrong-typed shard fields on a put are judged with null shard fields, then refused as malformed once granted", async () => {
const authority = new Recording(grant);
await using(await rig(authority), async (r) => {

View file

@ -7,6 +7,7 @@ All notable changes to `@gamecult/cultnet-ts` are recorded here, following
### Breaking
- `CultNetDocumentRegistry.applyRawDocumentPutMessage` and `createRawSnapshotResponseForPut` throw `A raw put must carry a storedAt stamp.` when the put's `storedAt` is missing, empty or not a stamp (`isStoredAtStamp` of cultcache-ts), and nothing is stored. The parser no longer refuses a `cultnet.document_put_raw.v0` for its `storedAt`: the server and the node judge it, so a refusal can name `document` (snapshot records and database changes are still read strictly as non-empty).
- `decodeManifest` refuses a manifest with bytes after its first MessagePack value (`CDN artifact manifest has N bytes after its first MessagePack value.`), as the C# reference does; before, the tail was ignored. `contracts/cultmesh/content-acceptance-vectors.json` now holds `trailing_nil`, `trailing_reserved_code` and `trailing_truncated_array` as refused.
### Added

View file

@ -1289,7 +1289,9 @@ function validateDocumentPutRawMessage(input: unknown): asserts input is CultNet
throw new Error("Validation failed for cultnet.document_put_raw.v0: /document: is required");
}
validateRawDocumentRecord(candidate.document, "/document");
// A peer's put is judged for its stamp by the server and the node (isStoredAtStamp), which answer message_invalid naming
// `document` after the write authority has spoken; the parser must let such a put through to them.
validateRawDocumentRecord(candidate.document, "/document", { judgesStoredAt: false });
}
function validateSnapshotResponseRawMessage(
@ -1450,6 +1452,7 @@ function validateBinaryMessageRoot(
function validateRawDocumentRecord(
input: unknown,
instancePath: string,
{ judgesStoredAt = true }: { judgesStoredAt?: boolean } = {},
): asserts input is CultNetRawDocumentRecord {
if (!input || typeof input !== "object") {
throw new Error(`Validation failed for raw CultNet document record: ${instancePath}: must be an object`);
@ -1461,7 +1464,9 @@ function validateRawDocumentRecord(
requireOptionalNonEmptyString(candidate.schemaVersion, `${instancePath}/schemaVersion`);
requireOptionalNonEmptyString(candidate.schemaContentHash, `${instancePath}/schemaContentHash`);
requireNonEmptyString(candidate.recordKey, `${instancePath}/recordKey`);
requireNonEmptyString(candidate.storedAt, `${instancePath}/storedAt`);
if (judgesStoredAt) {
requireNonEmptyString(candidate.storedAt, `${instancePath}/storedAt`);
}
if (candidate.payloadEncoding !== "messagepack") {
throw new Error(
`Validation failed for raw CultNet document record: ${instancePath}/payloadEncoding: must equal messagepack`,

View file

@ -6,6 +6,7 @@ import type {
} from "@gamecult/cultcache-ts";
import {
SchemaConflictError,
isStoredAtStamp,
decodeDocumentPayload,
documentPayloadBytes,
documentPayloadFromBytes,
@ -323,6 +324,10 @@ export class CultNetDocumentRegistry {
envelope: CultCacheEnvelope;
} {
const binding = this.#requireSchemaBinding(message.document.schemaId);
// A put is stored under the stamp it carries; one that is no stamp is refused, and nothing is minted for it.
if (!isStoredAtStamp(message.document.storedAt)) {
throw new Error("A raw put must carry a storedAt stamp.");
}
return {
binding,
envelope: {

View file

@ -0,0 +1,53 @@
// A peer's raw put is stored under the stamp it carries; one that is no stamp is refused and nothing is minted or stored
// (variants:ruling:raw-put-without-stamp-refused). The registry is the node-level owner: every row of the shared vector.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import test from "node:test";
import { decode } from "@msgpack/msgpack";
import { z } from "zod";
import { CultCache, defineDocumentType, encodeDocumentPayload } from "@gamecult/cultcache-ts";
import { CultNetDocumentRegistry, defineCultNetDocumentBinding, parseCultNetMessage, type CultNetMessage } from "../src";
const VECTOR = join(__dirname, "..", "..", "..", "..", "tests", "vectors", "stored-at-stamp", "stamps.msgpack");
const note = defineDocumentType({
type: "tests.stamped_note",
schemaId: "tests.stamped_note.v0",
schema: z.object({ noteId: z.string(), text: z.string() }),
name: "noteId",
});
const registry = new CultNetDocumentRegistry([defineCultNetDocumentBinding({ definition: note })]);
function putOf(key: string, storedAt: unknown): CultNetMessage {
const payload = encodeDocumentPayload(note, { noteId: key, text: "peer" });
const document: Record<string, unknown> = { schemaId: note.schemaId, recordKey: key, payloadEncoding: "messagepack", payload };
if (storedAt !== undefined) document.storedAt = storedAt;
return { schemaVersion: "cultnet.document_put_raw.v0", messageId: `put-${key}`, document } as unknown as CultNetMessage;
}
test("the registry stores a raw put only under a stamp, for every row of the vector and for a missing or mistyped one", async () => {
const rows = decode(readFileSync(VECTOR)) as [string, boolean][];
const cases: [string, unknown, boolean][] = [...rows.map(([text, parses]): [string, unknown, boolean] => [JSON.stringify(text), text, parses]),
["missing", undefined, false], ["number", 1_700_000_000_000, false], ["null", null, false]];
const cache = CultCache.builder().withDocumentType(note).build();
for (const [label, storedAt, parses] of cases) {
const message = putOf("k", storedAt);
// The parser lets a put through to its judges: the server and the registry refuse it, naming the document.
parseCultNetMessage(message, "cultnet.schema.v0");
const before = cache.getEnvelope(note, "k");
if (parses) {
await registry.applyRawDocumentPutMessage(cache, message as never);
assert.equal(cache.getRequiredEnvelope(note, "k").storedAt.length > 0, true, label);
} else {
await assert.rejects(registry.applyRawDocumentPutMessage(cache, message as never), /storedAt stamp/, label);
assert.deepEqual(cache.getEnvelope(note, "k"), before, `${label}: nothing minted or stored`);
}
}
// The refused puts left the store writable.
await registry.applyRawDocumentPutMessage(cache, putOf("after", "2026-11-07T00:00:00Z") as never);
assert.equal(cache.getRequired(note, "after").text, "peer");
});
test("a refused put does not serve either: createRawSnapshotResponseForPut refuses it too", () => {
assert.throws(() => registry.createRawSnapshotResponseForPut(putOf("k", "yesterday") as never, "m"), /storedAt stamp/);
});