cultmesh-ts: document server asks a write authority before applying a peer put or delete
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled

Deny by default with a grant-all opt-in; the gate runs before the put is sized,
resolved or decoded; refusal is the typed write_not_authorized. Adds
onDocumentDeleteRaw, refuses wrong-typed shard fields before the gate, grants
all writes in the existing server tests, and ports the cultmesh-py
remote-write-authority tests (no forwarding).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Libby 2026-11-07 19:52:42 +00:00
commit 1bc05d7b06
7 changed files with 357 additions and 14 deletions

View file

@ -10,6 +10,7 @@ All notable changes to `@gamecult/cultmesh-ts` are recorded here, following
- 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.
- `CultMeshDocumentCatalog` (`document`, `tryDocument`, `latest`, `replace`, `submitPrediction`, `authoritativeWriter`, `predictionWriter`, `watch`) and `CultMeshCollectionCatalog` (`collection`, `tryCollection`, `latest`, `watchChanges`) take `<TDocument = never, TSchema>` and yield `CultMeshCatalogValue<TDocument, TSchema>`: an explicit type argument wins, a CultCache document definition names its own value type, and a bare schema descriptor yields `unknown`. A value type is no longer inferred from a value or an expected result. The `parse` option is removed from these calls, and a lookup by type answers with that type's handle or none, not an alias of a compatible schema.
- `createRudpDocumentServer` refuses every peer put and delete unless it is given a `writeAuthority`. A refused write is answered with the typed `write_not_authorized` naming the record key (the bytes pinned in `error-vectors.json`), and `onDocumentPutRaw` is never called; pass `writeAuthority: new CultMeshGrantAllWrites()` to keep the old accept-everything behaviour. The authority is asked before the put is sized, resolved or decoded, with the canonical schema id and the peer's address; one that throws, rejects or answers anything but `granted: true` refuses. A put carrying a wrong-typed `shardId` or `shardEpoch` is refused before the authority is asked. A peer `document_delete` now reaches the new `onDocumentDeleteRaw` once granted (without it, a text refusal) instead of the unsupported-request error.
- Adding a document or collection to a catalog under a schema id or schema name another type already holds is refused with `SchemaConflictError`.
### Added

View file

@ -4006,8 +4006,8 @@ export type CultMeshRemoteWriteOperation = "put" | "delete";
/**
* One peer write as the authority sees it. `schemaId` is the canonical id the registry resolved for the write (the id
* as sent when no binding takes it), never an alias the peer used when a binding resolves it. `shardId` and
* `shardEpoch` are as the peer sent them, `null` when it sent none; a message carrying either with the wrong type
* is refused when it is read, before any authority is asked.
* `shardEpoch` are as a put carried them, `null` when it sent none (always `null` for a delete, which has none); a
* put carrying either with the wrong type is refused before any authority is asked.
*/
export interface CultMeshRemoteWriteRequest {
peer: CultMeshRemoteWritePeer;
@ -4048,8 +4048,6 @@ export interface CultMeshRudpDocumentDelete {
messageId: string;
schemaId: string;
recordKey: string;
shardId: string | null;
shardEpoch: number | null;
remote: CultMeshRemoteWritePeer;
}
@ -5676,7 +5674,18 @@ export class CultMesh {
sendSchemaMessage(record, cultNetBuiltinSchemaRegistry.createCatalogResponse(message));
return;
case "cultnet.document_put_raw.v0":
if (await writeRefused(record, "put", message.document.schemaId, message.document.recordKey, message)) return;
{
// The parser passes shard fields of any type through a put; a wrong-typed one is refused before the authority.
const { shardId, shardEpoch } = message as { shardId?: unknown; shardEpoch?: unknown };
if (
(shardId !== undefined && typeof shardId !== "string") ||
(shardEpoch !== undefined && !Number.isSafeInteger(shardEpoch))
) {
sendSchemaMessage(record, cultNetTextError("CultMesh RUDP document put carries malformed shard fields."));
return;
}
if (await writeRefused(record, "put", message.document.schemaId, message.document.recordKey, (shardId as string | undefined) ?? null, (shardEpoch as number | undefined) ?? null)) return;
}
if (options.onDocumentPutRaw) {
const unservable = unservablePut(message);
if (unservable) {
@ -5697,7 +5706,7 @@ export class CultMesh {
}
return;
case "cultnet.document_delete.v0": {
if (await writeRefused(record, "delete", message.schemaId, message.recordKey, message)) return;
if (await writeRefused(record, "delete", message.schemaId, message.recordKey, null, null)) return;
if (!options.onDocumentDeleteRaw) {
sendSchemaMessage(record, cultNetTextError("CultMesh RUDP document server has no delete handler."));
return;
@ -5706,8 +5715,6 @@ export class CultMesh {
messageId: message.messageId,
schemaId: message.schemaId,
recordKey: message.recordKey,
shardId: message.shardId ?? null,
shardEpoch: message.shardEpoch ?? null,
remote: { ...record.remote },
});
return;
@ -5735,7 +5742,8 @@ export class CultMesh {
operation: CultMeshRemoteWriteOperation,
schemaId: string,
recordKey: string,
message: { shardId?: string; shardEpoch?: number },
shardId: string | null,
shardEpoch: number | null,
): Promise<boolean> {
let reason: string | undefined;
const authority = options.writeAuthority;
@ -5748,8 +5756,8 @@ export class CultMesh {
operation,
schemaId: options.documents.canonicalSchemaId(schemaId) ?? schemaId,
recordKey,
shardId: message.shardId ?? null,
shardEpoch: message.shardEpoch ?? null,
shardId,
shardEpoch,
});
if (decision?.granted === true) return false;
reason = typeof decision?.reason === "string" ? decision.reason : undefined;

View file

@ -20,7 +20,7 @@ import {
defineCultNetDocumentBinding,
type CultNetPeer,
} from "@gamecult/cultnet-ts";
import { CultMesh, cultMeshDocumentFromSingleFile, type CultMeshRudpDocumentPut } from "../src/index";
import { CultMesh, CultMeshGrantAllWrites, cultMeshDocumentFromSingleFile, type CultMeshRudpDocumentPut } from "../src/index";
// A document written in the reference's positional shape, and a plain map document beside it. Every mesh reader of a
// payload reads it the way the cache does, so both read through the mesh.
@ -77,6 +77,7 @@ test("the mesh syncs a codec document from a peer snapshot and returns a codec r
const receiptBinding = defineCultNetDocumentBinding({ definition: codecReceipt });
const puts: unknown[] = [];
const server = CultMesh.createRudpDocumentServer("cultmesh-ts-codec-server", connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry([commandBinding, plainBinding, receiptBinding]),
getCache: () => source.cache,
bindHost: "127.0.0.1", bindPort: 0, resendDelayMs: 25, resendPollMs: 5,
@ -131,6 +132,7 @@ test("a RUDP put naming a schema the server has no definition for reaches the ha
const errors: Error[] = [];
const puts: CultMeshRudpDocumentPut[] = [];
const server = CultMesh.createRudpDocumentServer("cultmesh-ts-unregistered-server", connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry([known]),
bindHost: "127.0.0.1", bindPort: 0, resendDelayMs: 25, resendPollMs: 5,
onError: (error) => errors.push(error),
@ -171,6 +173,7 @@ test("a payload past the nesting limit is refused at the network doors: a RUDP p
const errors: unknown[] = [];
const puts: CultMeshRudpDocumentPut[] = [];
const server = CultMesh.createRudpDocumentServer("cultmesh-ts-depth-server", connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
documents: registry,
bindHost: "127.0.0.1", bindPort: 0, resendDelayMs: 25, resendPollMs: 5,
onError: (error) => errors.push(error),

View file

@ -21,7 +21,7 @@ import {
type CultNetMessage,
type CultNetSnapshotResponseRawMessage,
} from "@gamecult/cultnet-ts";
import { CultMesh, CultMeshRudpUnservableDocumentError } from "../src/index";
import { CultMesh, CultMeshGrantAllWrites, CultMeshRudpUnservableDocumentError } from "../src/index";
// A record's payload as the bytes a peer would put on the wire.
const payloadOf = (value: unknown) => documentPayloadFromBytes(encodeWireValue(value));
@ -2857,6 +2857,7 @@ test("CultMesh TS RUDP document server accepts raw document puts from multiple p
"cultmesh-ts-document-server",
connectionId,
{
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry(),
bindHost: "127.0.0.1",
bindPort: 0,
@ -2945,6 +2946,7 @@ test("CultMesh TS publishes one registered document to a RUDP catalog", async ()
"cultmesh-ts-odin-catalog",
connectionId,
{
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry(),
bindHost: "127.0.0.1",
bindPort: 0,
@ -3020,6 +3022,7 @@ test("CultMesh TS returns a correlated provider receipt after a RUDP document mu
const commandBinding = defineCultNetDocumentBinding({ definition: noteDocument });
const receiptBinding = defineCultNetDocumentBinding({ definition: noteReceiptDocument });
const server = CultMesh.createRudpDocumentServer("cultmesh-ts-receipt-server", connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry([commandBinding, receiptBinding]), bindHost: "127.0.0.1", bindPort: 0,
resendDelayMs: 25, resendPollMs: 5,
onDocumentPutRaw: async (document) => ({
@ -3055,6 +3058,7 @@ test("CultMesh TS reads remote RUDP snapshots through document handles", async (
"cultmesh-ts-rudp-snapshot-server",
connectionId,
{
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry([
defineCultNetDocumentBinding({ definition: noteDocument }),
]),
@ -3152,6 +3156,7 @@ test("CultMesh TS syncs remote RUDP snapshots into a local node", async () => {
"cultmesh-ts-rudp-sync-server",
connectionId,
{
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry([
defineCultNetDocumentBinding({ definition: noteDocument }),
]),
@ -3233,6 +3238,7 @@ test("CultMesh TS peer snapshots never take another type's record at the key", a
"cultmesh-ts-rudp-foreign-snapshot-server",
connectionId,
{
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry([
defineCultNetDocumentBinding({ definition: incompatibleNoteDocument }),
defineCultNetDocumentBinding({ definition: foreignNoteDocument }),
@ -3474,6 +3480,7 @@ async function withServedBoundRig(
const messages: CultNetMessage[] = [];
const unparsed: Error[] = [];
const server = CultMesh.createRudpDocumentServer(SERVED_BOUND_SERVER, connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
documents: registry,
getCache: () => node.cache,
bindHost: "127.0.0.1",
@ -3635,6 +3642,7 @@ async function withRawPeerRig(
for (const put of stored) await registry.applyRawDocumentPutMessage(node.cache, put);
const errors: Error[] = [];
const server = CultMesh.createRudpDocumentServer(SERVED_BOUND_SERVER, connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
documents: registry,
getCache: () => (getCache ? getCache(node.cache) : node.cache) as typeof node.cache,
bindHost: "127.0.0.1",

View file

@ -14,6 +14,7 @@ import {
import {
CultMesh,
CultMeshGrantAllWrites,
CultMeshProviderRudpTransport,
CultMeshProviderSessionBroker,
CULTMESH_PROVIDER_SESSION_SERVICE_ID,
@ -64,6 +65,7 @@ test("RUDP provider transport requires broker acceptance for the full lifecycle"
},
});
const server = CultMesh.createRudpDocumentServer("odin-test", 0x43554c54, {
writeAuthority: new CultMeshGrantAllWrites(),
bindPort: 0,
documents: new CultNetDocumentRegistry(),
onOperationRequest: (request, session) => broker.handle(request, session),
@ -256,6 +258,7 @@ test("a replaced RUDP generation drops operations queued behind an active handle
let handlerCalls = 0;
let closedSessions = 0;
const server = CultMesh.createRudpDocumentServer("odin-queue-test", connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
bindPort: 0,
documents: new CultNetDocumentRegistry(),
onOperationRequest: async request => {
@ -326,6 +329,7 @@ test("a client restarted on the same address with the same Connect payload repla
const connectionId = 0x43554c54;
let closedSessions = 0;
const server = CultMesh.createRudpDocumentServer("odin-restart-test", connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
bindPort: 0,
documents: new CultNetDocumentRegistry(),
onSessionClosed: () => { closedSessions += 1; },
@ -364,6 +368,7 @@ test("a client restarted on the same address with the same Connect payload repla
test("the RUDP document server does not acknowledge by name a reliable packet its session did not receive", async () => {
const connectionId = 0x43554c55;
const server = CultMesh.createRudpDocumentServer("odin-ack-test", connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
bindPort: 0,
documents: new CultNetDocumentRegistry(),
onError: () => undefined,

View file

@ -0,0 +1,317 @@
// A peer's put or delete is applied only when the server's write authority grants it. Ports the behaviours of
// cultmesh-py test_remote_write_authority.py (no forwarding: this server does not forward non-primary writes).
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import test from "node:test";
import { z } from "zod";
import { documentPayloadFromBytes, defineDocumentType } from "@gamecult/cultcache-ts";
import { encodeWireValue } from "@gamecult/cultnet-ts/wire";
import {
CultNetDocumentRegistry,
cultNetWriteNotAuthorizedError,
defineCultNetDocumentBinding,
type CultNetMessage,
type CultNetPeer,
} from "@gamecult/cultnet-ts";
import {
CultMesh,
CultMeshGrantAllWrites,
type CultMeshRemoteWriteAuthority,
type CultMeshRemoteWriteDecision,
type CultMeshRemoteWriteRequest,
type CultMeshRudpDocumentDelete,
type CultMeshRudpDocumentPut,
} from "../src/index";
const SCHEMA_ID = "cultmesh.authority_note.v0";
const ALIAS = "runtime.generated.authority-note.ui.42";
const KEY_A = "tests:authority:a";
const KEY_B = "tests:authority:b";
const note = defineDocumentType({
type: "cultmesh.authority_note",
schemaId: SCHEMA_ID,
compatibleSchemaIds: [ALIAS],
schema: z.object({ noteId: z.string(), text: z.string() }),
name: "noteId",
});
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
function put(recordKey: string, extra: Record<string, unknown> = {}, schemaId = SCHEMA_ID, payload?: Uint8Array) {
return {
schemaVersion: "cultnet.document_put_raw.v0" as const,
messageId: `put-${recordKey}`,
document: {
schemaId,
recordKey,
storedAt: "2026-11-07T00:00:00Z",
payloadEncoding: "messagepack" as const,
payload: documentPayloadFromBytes(payload ?? encodeWireValue({ noteId: recordKey, text: "peer" })),
},
...extra,
} as CultNetMessage;
}
function del(recordKey: string, schemaId = SCHEMA_ID): CultNetMessage {
return { schemaVersion: "cultnet.document_delete.v0", messageId: `delete-${recordKey}`, schemaId, recordKey };
}
class Recording implements CultMeshRemoteWriteAuthority {
readonly requests: CultMeshRemoteWriteRequest[] = [];
constructor(private readonly answer: (request: CultMeshRemoteWriteRequest) => unknown) {}
decide(request: CultMeshRemoteWriteRequest): CultMeshRemoteWriteDecision | Promise<CultMeshRemoteWriteDecision> {
this.requests.push(request);
return this.answer(request) as CultMeshRemoteWriteDecision | Promise<CultMeshRemoteWriteDecision>;
}
}
const grant = () => ({ granted: true });
interface Rig {
puts: CultMeshRudpDocumentPut[];
deletes: CultMeshRudpDocumentDelete[];
errors: Error[];
replies: CultNetMessage[];
peer: CultNetPeer;
settle(): Promise<unknown>;
close(): void;
}
let nextConnection = 0x10204000;
async function rig(writeAuthority?: CultMeshRemoteWriteAuthority, extra: { maxPayloadBytes?: number } = {}): Promise<Rig> {
const connectionId = nextConnection++;
const puts: CultMeshRudpDocumentPut[] = [];
const deletes: CultMeshRudpDocumentDelete[] = [];
const errors: Error[] = [];
const server = CultMesh.createRudpDocumentServer("authority-server", connectionId, {
documents: new CultNetDocumentRegistry([defineCultNetDocumentBinding({ definition: note })]),
writeAuthority,
bindHost: "127.0.0.1",
bindPort: 0,
resendDelayMs: 25,
resendPollMs: 5,
onDocumentPutRaw: (document) => { puts.push(document); },
onDocumentDeleteRaw: (request) => { deletes.push(request); },
onError: (error) => errors.push(error),
...extra,
});
await server.start();
const peer = await CultMesh.createRudpPeer("authority-peer", connectionId, `rudp://127.0.0.1:${server.bind.port}`, {
resendDelayMs: 25,
resendPollMs: 5,
connectTimeoutMs: 2_000,
});
const replies: CultNetMessage[] = [];
peer.on("message", (message) => replies.push(message));
return {
puts, deletes, errors, replies, peer,
// A refusal is a reply; a grant sends none, so settle on a quiet period after the last send.
settle: () => sleep(250),
close: () => { peer.close(); server.close(); },
};
}
async function using(r: Rig, body: (r: Rig) => Promise<unknown>): Promise<void> {
try { await body(r); } finally { r.close(); }
}
function assertRefused(reply: CultNetMessage | undefined, key: string, error?: string): void {
assert.ok(reply && reply.schemaVersion === "cultnet.error.v0");
assert.equal(reply.code, "write_not_authorized");
assert.ok(reply.error.startsWith("write_not_authorized"));
assert.deepEqual(reply.details, { field: "recordKey", value: key, asOf: null, current: null });
if (error !== undefined) assert.equal(reply.error, error);
}
test("with no authority a peer's put and delete are refused and the handlers never run", async () => {
await using(await rig(undefined), async (r) => {
r.peer.send(put(KEY_A));
r.peer.send(del(KEY_A));
r.peer.send(put(KEY_B));
await r.settle();
assert.equal(r.replies.length, 3);
assertRefused(r.replies[0], KEY_A);
assertRefused(r.replies[1], KEY_A);
assertRefused(r.replies[2], KEY_B);
assert.deepEqual([r.puts.length, r.deletes.length], [0, 0]);
assert.deepEqual(r.errors, []);
});
});
test("a granted put and delete reach their handlers, send nothing back, and the authority saw this peer", async () => {
const authority = new Recording(grant);
await using(await rig(authority), async (r) => {
r.peer.send(put(KEY_A));
r.peer.send(del(KEY_A));
await r.settle();
assert.deepEqual(r.replies, []);
assert.deepEqual(r.puts.map((p) => p.recordKey), [KEY_A]);
assert.deepEqual(r.deletes.map((d) => d.recordKey), [KEY_A]);
assert.equal(authority.requests.length, 2);
for (const request of authority.requests) {
assert.equal(request.peer.address, "127.0.0.1");
assert.ok(request.peer.port > 0);
}
assert.deepEqual(authority.requests[1]!.peer, r.deletes[0]!.remote, "the delete handler sees the peer the authority was asked about");
});
});
test("the request carries the resolved write, and scoped grants refuse their neighbours", async () => {
const authority = new Recording((request) =>
request.operation === "put" && request.recordKey === KEY_A ? { granted: true } : { granted: false, reason: "scoped" });
await using(await rig(authority), async (r) => {
r.peer.send(put(KEY_A, { shardId: "authority-shard", shardEpoch: 1 }, ALIAS));
await r.settle();
const request = authority.requests[0]!;
assert.equal(request.schemaId, SCHEMA_ID, "the authority sees the canonical id, not the alias as sent");
assert.equal(request.operation, "put");
assert.equal(request.recordKey, KEY_A);
assert.equal(request.shardId, "authority-shard");
assert.equal(request.shardEpoch, 1);
assert.deepEqual(r.puts.map((p) => p.recordKey), [KEY_A]);
r.peer.send(put(KEY_B));
r.peer.send(del(KEY_A));
await r.settle();
assertRefused(r.replies[0], KEY_B, "write_not_authorized: scoped");
assertRefused(r.replies[1], KEY_A, "write_not_authorized: scoped");
assert.deepEqual(r.puts.map((p) => p.recordKey), [KEY_A], "a grant scoped to key a refuses key b");
assert.deepEqual(r.deletes, [], "a grant scoped to put refuses delete");
assert.equal(authority.requests.at(-1)!.operation, "delete");
assert.equal(authority.requests.at(-1)!.schemaId, SCHEMA_ID);
assert.equal(authority.requests.at(-1)!.shardId, null);
});
});
test("a delete sent under a schema alias asks the authority with the canonical id", async () => {
const authority = new Recording(grant);
await using(await rig(authority), async (r) => {
r.peer.send(del(KEY_A, ALIAS));
await r.settle();
assert.equal(authority.requests[0]!.schemaId, SCHEMA_ID);
assert.equal(r.deletes.length, 1);
});
});
test("refusal precedes every other judgment of the put", async () => {
await using(await rig(undefined, { maxPayloadBytes: 256 }), async (r) => {
r.peer.send(put("unrelated:authority", {}, "sha256:nobody-owns-this"));
r.peer.send(put(KEY_A, {}, SCHEMA_ID, new Uint8Array(20_000)));
await r.settle();
assertRefused(r.replies[0], "unrelated:authority");
assertRefused(r.replies[1], KEY_A);
assert.deepEqual(r.errors, [], "the gate ran before the put was sized or resolved");
assert.equal(r.puts.length, 0);
});
const granting = new Recording(grant);
await using(await rig(granting, { maxPayloadBytes: 256 }), async (r) => {
r.peer.send(put(KEY_A, {}, SCHEMA_ID, new Uint8Array(20_000)));
await r.settle();
assert.equal(r.replies[0]?.schemaVersion, "cultnet.error.v0");
assert.notEqual((r.replies[0] as { code?: string }).code, "write_not_authorized", "a granted put still meets the size judgment");
assert.equal(r.errors.length, 1);
});
});
test("an authority that throws or rejects refuses, fails closed, and is reported without being quoted", async () => {
for (const decide of [
() => { throw new Error("authority exploded"); },
() => Promise.reject(new Error("authority exploded")),
]) {
await using(await rig(new Recording(decide)), async (r) => {
r.peer.send(put(KEY_A));
r.peer.send(del(KEY_A));
await r.settle();
assertRefused(r.replies[0], KEY_A);
assertRefused(r.replies[1], KEY_A);
assert.deepEqual([r.puts.length, r.deletes.length], [0, 0]);
assert.equal(r.errors.length, 2);
assert.ok(r.errors.every((e) => e.message.includes("Error") && !e.message.includes("exploded")));
});
}
});
test("a refusal with no reason still says why, and a missing decision refuses", async () => {
await using(await rig(new Recording(() => ({ granted: false }))), async (r) => {
r.peer.send(put(KEY_A));
await r.settle();
assertRefused(r.replies[0], KEY_A, "write_not_authorized");
});
for (const answer of [null, undefined, {}, { granted: "yes" }, { granted: 1 }]) {
await using(await rig(new Recording(() => answer)), async (r) => {
r.peer.send(put(KEY_A));
r.peer.send(del(KEY_A));
await r.settle();
assertRefused(r.replies[0], KEY_A);
assertRefused(r.replies[1], KEY_A);
assert.deepEqual([r.puts.length, r.deletes.length], [0, 0]);
});
}
});
test("the refusal on the wire is the pinned error-vectors bytes", async () => {
const vectors = JSON.parse(readFileSync(join(__dirname, "../../../../contracts/cultnet/interop/error-vectors.json"), "utf8")).vectors;
const vector = vectors.find((v: { name: string }) => v.name === "write_not_authorized");
const expected = Buffer.from(vector.messagePackHex, "hex");
assert.deepEqual(Buffer.from(encodeWireValue(cultNetWriteNotAuthorizedError("some:key", "not granted"))), expected);
await using(await rig(new Recording(() => ({ granted: false, reason: "not granted" }))), async (r) => {
r.peer.send(put("some:key"));
await r.settle();
assert.deepEqual(Buffer.from(encodeWireValue(r.replies[0])), expected);
});
});
test("wrong-typed shard fields on a put are refused before the authority and reach no handler", async () => {
const authority = new Recording(grant);
await using(await rig(authority), async (r) => {
const bad: Record<string, unknown>[] = [
{ shardId: { not: "a string" } }, { shardId: 5 }, { shardEpoch: "7" }, { shardEpoch: true }, { shardEpoch: 1.5 },
];
for (const fields of bad) r.peer.send(put(KEY_A, fields));
await r.settle();
assert.equal(r.replies.length, bad.length);
assert.ok(r.replies.every((reply) => reply.schemaVersion === "cultnet.error.v0"));
assert.deepEqual(authority.requests, [], "the authority was never asked");
assert.equal(r.puts.length, 0);
});
});
test("well-typed shard fields reach the authority as sent", async () => {
const authority = new Recording(grant);
await using(await rig(authority), async (r) => {
r.peer.send(put(KEY_A, { shardId: "authority-shard", shardEpoch: 1 }));
await r.settle();
assert.deepEqual([authority.requests[0]!.shardId, authority.requests[0]!.shardEpoch], ["authority-shard", 1]);
});
});
test("grant-all is an explicit choice that grants every write", async () => {
await using(await rig(new CultMeshGrantAllWrites()), async (r) => {
r.peer.send(put(KEY_A));
r.peer.send(del(KEY_A));
await r.settle();
assert.deepEqual([r.puts.length, r.deletes.length, r.replies.length], [1, 1, 0]);
});
});
test("a granted delete with no delete handler is answered with a text refusal", async () => {
const connectionId = nextConnection++;
const server = CultMesh.createRudpDocumentServer("no-delete", connectionId, {
documents: new CultNetDocumentRegistry([defineCultNetDocumentBinding({ definition: note })]),
writeAuthority: new CultMeshGrantAllWrites(),
bindHost: "127.0.0.1", bindPort: 0, resendDelayMs: 25, resendPollMs: 5,
});
await server.start();
const peer = await CultMesh.createRudpPeer("p", connectionId, `rudp://127.0.0.1:${server.bind.port}`, { resendDelayMs: 25, resendPollMs: 5, connectTimeoutMs: 2_000 });
const replies: CultNetMessage[] = [];
peer.on("message", (m) => replies.push(m));
try {
peer.send(del(KEY_A));
await sleep(250);
assert.equal(replies.length, 1);
assert.notEqual((replies[0] as { code?: string }).code, "write_not_authorized");
} finally { peer.close(); server.close(); }
});

View file

@ -14,7 +14,7 @@ import {
encodeRudpPacket,
type CultNetPeer,
} from "@gamecult/cultnet-ts";
import { CultMesh } from "../src/index";
import { CultMesh, CultMeshGrantAllWrites } from "../src/index";
async function waitFor(predicate: () => boolean, description: string): Promise<void> {
const startedAt = Date.now();
@ -64,6 +64,7 @@ async function startServer(connectionId: number, socket: Socket): Promise<Server
const closed: number[] = [];
const errors: Error[] = [];
const server = CultMesh.createRudpDocumentServer("send-failure-server", connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry(),
socket,
bindHost: "127.0.0.1",