From 0bedcdeb370ef1970bdaf2abe482c549e537c170 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 27 Sep 2026 20:55:49 +0200 Subject: [PATCH 01/14] Add TypeScript Idunn runtime presence publisher --- .../cultnet-ts/src/idunn-runtime-authority.ts | 717 ++++++++++++++++++ packages/cultnet-ts/src/index.ts | 14 + .../test/idunn-runtime-authority.test.ts | 140 ++++ 3 files changed, 871 insertions(+) create mode 100644 packages/cultnet-ts/src/idunn-runtime-authority.ts create mode 100644 packages/cultnet-ts/test/idunn-runtime-authority.test.ts diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts new file mode 100644 index 00000000..28e61e97 --- /dev/null +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -0,0 +1,717 @@ +import crypto from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { decode, encode } from "@msgpack/msgpack"; + +import { + GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, + GAMECULT_RUNTIME_PRESENCE_IDENTITY_NAME, + IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME, + runtimePresenceActivationSigningMessage, + runtimePresenceProofPayload, + runtimePresenceProviderSigningMessage, + encodeRuntimePresenceHealth, + type RuntimePresenceHealth, +} from "./runtime-presence-health"; +import { encodeCultNetMessageForWire } from "./contracts"; +import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp"; +import type { CultNetRudpPacket } from "./rudp"; +import dgram from "node:dgram"; + +export const IDUNN_EXPECTED_INCARNATION_SCHEMA = "idunn.expected_incarnation.v2"; +export const IDUNN_RUNTIME_ACTIVATION_SCHEMA = "idunn.runtime_activation.v2"; +export const IDUNN_PROCESS_WRITE_LEASE_SCHEMA = "idunn.process_write_lease.v1"; +export const IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT = "GAMECULT_IDUNN_PROCESS_WRITE_LEASE"; +export const IDUNN_RUNTIME_BUNDLE_ENVIRONMENT = "GAMECULT_IDUNN_RUNTIME_BUNDLE"; +export const IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT = "GAMECULT_IDUNN_CANDIDATE_BIND"; + +const PROVIDER_ID_DOMAIN = Buffer.from("gamecult.provider-health.identity.v1\0", "utf8"); +const PROVIDER_PROTECTOR_CONTEXT = "gamecult-provider-health-identity-v1"; +const ACTIVATION_ID_DOMAIN = Buffer.from("idunn.runtime-activation.id.v1\0", "utf8"); +const CULTCACHE_STORE_FORMAT = "cultcache.store.v1"; +const ED25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex"); +const MAX_RECENT_WARMING_PROOFS = 64; +const authorityKeys = new WeakMap(); + +type ExpectedIncarnation = { + schemaVersion: string; + target: string; + planId: string; + incarnationId: string; + sealedReleaseId: string; + sourceRepository: string; + sourceRevision: string; + recipeSha256: string; + runtimeId: string; + expectedSignerIdentityId: string; + healthContract: string; + artifactSha256: string; + stateSchemaGeneration: string | null; + stateContractSha256: string | null; + writeLeaseRequired: boolean; + route: { routeId: string; transport: string; stableEndpoint: string; candidateEndpoint: string } | null; + capabilities: Array<{ capability: string; schema: string; compatibility: string; minimumCapacity: number }>; + dependencies: Array<{ kind: string; capability: string; schema: string; compatibility: string; providerEndpoint: string | null }>; + canonicalBytes: Buffer; + canonicalSha256: string; +}; + +type RuntimeActivation = { + schemaVersion: string; + expectedProjectionSha256: string; + runtimeId: string; + runtimeInstanceId: string; + activationSignerIdentityId: string; + activationSignerPublicKey: Buffer; + canonicalSha256: string; +}; + +export type IdunnRuntimeAuthority = { + expected: ExpectedIncarnation; + activation: RuntimeActivation; + providerSignerIdentityId: string; + activationSignerIdentityId: string; + boundEndpoint: string; + processWriteLeasePath?: string; +}; + +export type IdunnRuntimePresencePublisher = { + readonly runtimeId: string; + readonly runtimeInstanceId: string; + readonly requiresWriteLease: boolean; + publish(state: RuntimePresenceHealth["state"], detail: string): Promise; + waitForWriteLease(options?: { pollIntervalMs?: number; signal?: AbortSignal }): Promise; + assertWriteLease(): Promise; +}; + +export type IdunnRuntimePresencePublisherOptions = { + authority: IdunnRuntimeAuthority; + endpoint: string; + healthContract: string; + capabilities: RuntimePresenceHealth["capabilities"]; +}; + +/** + * Loads the root-provisioned Idunn bundle and parent-only signing descriptors. + * The expected record and activation witness are accepted only when their + * exact positional contracts and mutual incarnation binding agree. + */ +export function loadIdunnRuntimeAuthorityFromEnvironment( + target: string, + healthContract: string, + odinEndpoint: string, +): IdunnRuntimeAuthority { + const bundle = requiredEnvironment(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT); + const expected = readAuthorityRecord(path.join(bundle, "expected.cc"), "idunn.expected_incarnation", IDUNN_EXPECTED_INCARNATION_SCHEMA); + const activation = readAuthorityRecord(path.join(bundle, "activation.cc"), "idunn.runtime_activation", IDUNN_RUNTIME_ACTIVATION_SCHEMA); + const expectedValue = decodeExpected(expected.payload); + const activationValue = decodeActivation(activation.payload); + if (expectedValue.target !== target || expectedValue.healthContract !== healthContract) { + throw new Error("Idunn Expected target or health contract does not match this runtime."); + } + const odinDependency = expectedValue.dependencies.find((dependency) => dependency.kind === "shared-infrastructure" + && dependency.capability === "odin.verse-rendezvous"); + if (!odinDependency || normalizeRudpEndpoint(odinDependency.providerEndpoint ?? "") !== normalizeRudpEndpoint(odinEndpoint)) { + throw new Error("Configured Odin endpoint does not match Idunn Expected dependency authority."); + } + if (activationValue.expectedProjectionSha256 !== expectedValue.canonicalSha256 + || activationValue.runtimeId !== expectedValue.runtimeId) { + throw new Error("Idunn Activation does not bind this exact Expected incarnation."); + } + + const descriptors = inheritedDescriptorMap(); + const providerCredential = descriptors.get(GAMECULT_RUNTIME_PRESENCE_IDENTITY_NAME); + const activationCredential = descriptors.get(IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME); + if (providerCredential === undefined || activationCredential === undefined) { + throw new Error("Idunn runtime-presence signing descriptors are missing."); + } + + const providerPrivateKey = openProviderHealthIdentity(readDescriptor(providerCredential)); + const activationSeed = readDescriptor(activationCredential); + if (activationSeed.length !== 32) throw new Error("Idunn activation credential must be exactly 32 bytes."); + const activationPrivateKey = privateKeyFromSeed(activationSeed); + activationSeed.fill(0); + const activationPublicKey = rawEd25519PublicKey(crypto.createPublicKey(activationPrivateKey)); + const activationSignerIdentityId = sha256Hex(Buffer.concat([ACTIVATION_ID_DOMAIN, activationPublicKey])); + if (activationSignerIdentityId !== activationValue.activationSignerIdentityId + || !activationPublicKey.equals(activationValue.activationSignerPublicKey)) { + throw new Error("Idunn activation credential does not match the root-provisioned Activation witness."); + } + + if (expectedValue.writeLeaseRequired !== (process.env[IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT] !== undefined)) { + throw new Error("Idunn process write-lease environment does not match Expected."); + } + const boundEndpoint = requiredEnvironment(IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT); + if (!expectedValue.route || expectedValue.route.candidateEndpoint !== boundEndpoint) { + throw new Error("Idunn candidate bind differs from the Expected route."); + } + if (expectedValue.expectedSignerIdentityId !== providerSignerIdentityId(providerPrivateKey)) { + throw new Error("Provider identity does not match Idunn Expected."); + } + + const authority: IdunnRuntimeAuthority = { + expected: expectedValue, + activation: activationValue, + providerSignerIdentityId: expectedValue.expectedSignerIdentityId, + activationSignerIdentityId, + boundEndpoint, + ...(process.env[IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT] + ? { processWriteLeasePath: process.env[IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT] } + : {}), + }; + authorityKeys.set(authority, { providerPrivateKey, activationPrivateKey }); + return authority; +} + +/** + * Signs the fixed Idunn v2 positional runtime-presence contract with the + * provider identity and this launch's Idunn-issued activation key. + */ +export function signIdunnRuntimePresence( + authority: IdunnRuntimeAuthority, + fields: Omit, +): { presence: RuntimePresenceHealth; payload: Uint8Array; canonicalSha256: string } { + const presence: RuntimePresenceHealth = { + ...fields, + target: authority.expected.target, + expectedProjectionSha256: authority.expected.canonicalSha256, + planId: authority.expected.planId, + incarnationId: authority.expected.incarnationId, + sealedReleaseId: authority.expected.sealedReleaseId, + activationWitnessSha256: authority.activation.canonicalSha256, + stateSchemaGeneration: authority.expected.stateSchemaGeneration, + stateContractSha256: authority.expected.stateContractSha256, + runtimeId: authority.expected.runtimeId, + runtimeInstanceId: authority.activation.runtimeInstanceId, + boundEndpoint: authority.boundEndpoint, + healthContract: authority.expected.healthContract, + signerIdentityId: authority.providerSignerIdentityId, + activationSignerIdentityId: authority.activationSignerIdentityId, + }; + const keys = authorityKeys.get(authority); + if (!keys) throw new Error("Idunn runtime authority was not opened by the CultNet credential reader."); + const proofPayload = runtimePresenceProofPayload(presence); + const providerSignature = crypto.sign(null, runtimePresenceProviderSigningMessage(proofPayload), keys.providerPrivateKey); + const activationSignature = crypto.sign(null, runtimePresenceActivationSigningMessage(proofPayload), keys.activationPrivateKey); + const payload = encodeRuntimePresenceHealth(presence, providerSignature, activationSignature); + return { + presence, + payload, + canonicalSha256: prefixedSha256(Buffer.from(payload)), + }; +} + +export function createIdunnRuntimePresencePublisher( + options: IdunnRuntimePresencePublisherOptions, +): IdunnRuntimePresencePublisher { + const endpoint = parseRudpEndpoint(options.endpoint); + const expected = options.authority.expected; + if (options.healthContract !== expected.healthContract) throw new Error("Runtime presence contract differs from Expected."); + if (options.authority.boundEndpoint !== expected.route?.candidateEndpoint) throw new Error("Runtime presence bind differs from Expected."); + for (const required of expected.capabilities) { + if (!options.capabilities.some((actual) => actual.capability === required.capability + && actual.schema === required.schema + && actual.compatibility === required.compatibility + && actual.capacity >= required.minimumCapacity)) { + throw new Error(`Runtime does not provide Expected capability ${required.capability}/${required.schema}.`); + } + } + const connectionId = 0x0d1d0002; + let sequence = 0; + let latestLeaseSha256: string | null = null; + const recentWarmingProofs: string[] = []; + + const assertWriteLease = async () => { + if (!expected.writeLeaseRequired) return ""; + const leasePath = options.authority.processWriteLeasePath; + if (!leasePath) throw new Error("Idunn process write lease is required but no lease path is configured."); + const record = readAuthorityRecord(leasePath, "idunn.process_write_lease", IDUNN_PROCESS_WRITE_LEASE_SCHEMA); + const lease = decodeArray(record.payload, 14, "Idunn process write lease"); + assertLeaseMatches(lease, options.authority, recentWarmingProofs); + latestLeaseSha256 = prefixedSha256(Buffer.from(encode(lease))); + return latestLeaseSha256; + }; + + const publish = async (state: RuntimePresenceHealth["state"], detail: string) => { + const writeLeaseSha256 = state === "warming" || !expected.writeLeaseRequired ? null : await assertWriteLease(); + sequence += 1; + const signed = signIdunnRuntimePresence(options.authority, { + capabilities: options.capabilities, + state, + detail: detail.slice(0, 512), + writeLeaseSha256, + publisherSequence: sequence, + observedAtUnixMillis: Date.now(), + }); + await publishDocument(endpoint, connectionId, { + schemaVersion: "cultnet.document_put_raw.v0", + messageId: `runtime-presence:${expected.target}:${options.authority.activation.runtimeInstanceId}:${sequence}`, + document: { + schemaId: GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, + recordKey: expected.target, + storedAt: new Date().toISOString(), + payloadEncoding: "messagepack", + payload: signed.payload, + sourceRuntimeId: expected.runtimeId, + sourceRole: "runtime-presence-health-publisher", + tags: ["cultnet.transport.rudp.v0", "runtime-presence"], + }, + }); + if (state === "warming") { + recentWarmingProofs.push(signed.canonicalSha256); + if (recentWarmingProofs.length > MAX_RECENT_WARMING_PROOFS) recentWarmingProofs.shift(); + } + return signed.canonicalSha256; + }; + + return { + runtimeId: expected.runtimeId, + runtimeInstanceId: options.authority.activation.runtimeInstanceId, + requiresWriteLease: expected.writeLeaseRequired, + publish, + async waitForWriteLease({ pollIntervalMs = 5000, signal } = {}) { + if (!expected.writeLeaseRequired) return ""; + let warmingSequence = 0; + while (!signal?.aborted) { + await publish("warming", "waiting-for-process-write-lease"); + warmingSequence += 1; + try { + return await assertWriteLease(); + } catch (error) { + if (warmingSequence > 720) throw new Error("Timed out waiting for Idunn process write lease.", { cause: error }); + } + await abortableDelay(pollIntervalMs, signal); + } + throw signal?.reason ?? new Error("Aborted while waiting for Idunn process write lease."); + }, + assertWriteLease, + }; +} + +async function publishDocument( + endpoint: { host: string; port: number }, + connectionId: number, + message: Record, +): Promise { + const socket = dgram.createSocket(endpoint.host.includes(":") ? "udp6" : "udp4"); + await new Promise((resolve, reject) => { + socket.once("error", reject); + socket.bind(0, endpoint.host.includes(":") ? "::" : "0.0.0.0", () => { + socket.off("error", reject); + resolve(); + }); + }); + const receiver = receivePackets(socket); + const session = new CultNetRudpSession({ connectionId, initialSequence: 1, resendDelayMs: 100 }); + try { + await sendPacket(socket, endpoint, session.createConnect(Date.now(), new Uint8Array())); + await receiveUntil(receiver, session, endpoint, (packet) => packet.packetType === "accept", 5000); + const wirePayload = Uint8Array.from(encodeCultNetMessageForWire(message as never, "cultnet.schema.v0") as Uint8Array); + const packets = session.sendMany("schema", wirePayload, { reliable: true, ordered: true, nowMs: Date.now() }); + const ack = receiveUntil(receiver, session, endpoint, (packet) => packet.packetType === "ack", 2000); + for (const packet of packets) await sendPacket(socket, endpoint, packet); + await ack; + } finally { + receiver.close(); + socket.close(); + } +} + +type PacketReceiver = { + socket: dgram.Socket; + next(timeoutMs: number): Promise; + close(): void; +}; + +function receivePackets(socket: dgram.Socket): PacketReceiver { + const packets: CultNetRudpPacket[] = []; + const waiters: Array<{ resolve: (packet: CultNetRudpPacket) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }> = []; + const errors: Error[] = []; + const drain = () => { + while (waiters.length && (packets.length || errors.length)) { + const waiter = waiters.shift()!; + clearTimeout(waiter.timer); + if (errors.length) waiter.reject(errors.shift()!); + else waiter.resolve(packets.shift()!); + } + }; + const onMessage = (wire: Buffer) => { + try { packets.push(decodeRudpPacket(wire)); } catch (error) { errors.push(error as Error); } + drain(); + }; + const onError = (error: Error) => { errors.push(error); drain(); }; + socket.on("message", onMessage); + socket.on("error", onError); + return { + socket, + next(timeoutMs) { + if (packets.length) return Promise.resolve(packets.shift()!); + if (errors.length) return Promise.reject(errors.shift()!); + return new Promise((resolve, reject) => { + const waiter = { + resolve, + reject, + timer: setTimeout(() => { + const index = waiters.indexOf(waiter); + if (index >= 0) waiters.splice(index, 1); + const error = new Error("Timed out waiting for CultNet RUDP packet.") as NodeJS.ErrnoException; + error.code = "ETIMEDOUT"; + reject(error); + }, Math.max(1, timeoutMs)), + }; + waiters.push(waiter); + }); + }, + close() { + socket.off("message", onMessage); + socket.off("error", onError); + for (const waiter of waiters.splice(0)) { + clearTimeout(waiter.timer); + waiter.reject(new Error("CultNet RUDP publisher closed.")); + } + }, + }; +} + +async function receiveUntil( + receiver: PacketReceiver, + session: CultNetRudpSession, + endpoint: { host: string; port: number }, + predicate: (packet: CultNetRudpPacket) => boolean, + timeoutMs: number, +): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + try { + const packet = await receiver.next(Math.min(100, deadline - Date.now())); + const received = session.receive(packet, Date.now()); + if (received.reply) throw new Error("Runtime presence received an unexpected reply-required packet."); + if (predicate(packet)) return; + } catch (error) { + if ((error as NodeJS.ErrnoException)?.code !== "ETIMEDOUT") throw error; + } + for (const packet of session.dueResends(Date.now())) await sendPacket(receiver.socket, endpoint, packet); + } + throw new Error(`Timed out waiting for CultNet RUDP response after ${timeoutMs} ms.`); +} + +async function sendPacket(socket: dgram.Socket, endpoint: { host: string; port: number }, packet: CultNetRudpPacket): Promise { + const wire = encodeRudpPacket(packet); + await new Promise((resolve, reject) => { + socket.send(wire, endpoint.port, endpoint.host, (error) => error ? reject(error) : resolve()); + }); +} + +function readAuthorityRecord(filePath: string, type: string, schemaId: string): { payload: Uint8Array } { + const decoded = decode(fs.readFileSync(filePath)); + if (!Array.isArray(decoded) || decoded[0] !== CULTCACHE_STORE_FORMAT || !Array.isArray(decoded[1]) || !Array.isArray(decoded[2])) { + throw new Error(`Idunn authority file ${filePath} is not a CultCache v1 store.`); + } + if (decoded[2].length !== 1) throw new Error(`Idunn authority file ${filePath} must contain exactly one record.`); + const matchingRecords = (decoded[2] as unknown[]).filter((raw) => { + const row = array(raw, 4, "CultCache record"); + return row[1] === schemaId; + }); + if (matchingRecords.length !== 1) throw new Error(`Idunn authority file must contain exactly one ${schemaId} record.`); + const row = array(matchingRecords[0], 4, "CultCache record"); + const catalog = (decoded[1] as unknown[]).find((raw) => { + const entry = Array.isArray(raw) ? raw : []; + return entry[0] === schemaId; + }); + const catalogEntry = array(catalog, 7, "CultCache schema catalog entry"); + if (catalogEntry[1] !== type) throw new Error(`Idunn authority record has unexpected CultCache type ${String(catalogEntry[1])}.`); + if (!(row[3] instanceof Uint8Array)) throw new Error("Idunn authority payload is not MessagePack bytes."); + return { payload: row[3] }; +} + +function decodeExpected(payload: Uint8Array): ExpectedIncarnation { + const values = decodeArray(payload, 18, "Idunn Expected"); + if (values[0] !== IDUNN_EXPECTED_INCARNATION_SCHEMA) throw new Error("Idunn Expected schema is unsupported."); + const canonicalBytes = Buffer.from(encode(values)); + if (!canonicalBytes.equals(Buffer.from(payload))) throw new Error("Idunn Expected is not canonical MessagePack."); + const stateSchemaGeneration = nullableString(values[12], "Expected state generation"); + const stateContractSha256 = nullableString(values[13], "Expected state contract"); + if ((stateSchemaGeneration === null) !== (stateContractSha256 === null)) throw new Error("Idunn Expected state lineage is partial."); + if (typeof values[14] !== "boolean") throw new Error("Idunn Expected write-lease flag is not boolean."); + const route = decodeRoute(values[15]); + const writeLeaseRequired = values[14]; + if (writeLeaseRequired && stateSchemaGeneration === null) throw new Error("Stateless Idunn Expected cannot require a write lease."); + const target = string(values[1], "Expected target"); + const planId = string(values[2], "Expected plan id"); + const incarnationId = string(values[3], "Expected incarnation id"); + const sealedReleaseId = string(values[4], "Expected sealed release"); + const sourceRepository = string(values[5], "Expected source repository"); + const sourceRevision = string(values[6], "Expected source revision"); + const recipeSha256 = string(values[7], "Expected recipe hash"); + const runtimeId = string(values[8], "Expected runtime id"); + const expectedSignerIdentityId = string(values[9], "Expected signer identity"); + const healthContract = string(values[10], "Expected health contract"); + const artifactSha256 = string(values[11], "Expected artifact hash"); + for (const [name, hash] of [["plan", planId], ["release", sealedReleaseId], ["recipe", recipeSha256], ["artifact", artifactSha256]] as const) { + if (!/^sha256-[0-9a-f]{64}$/u.test(hash)) throw new Error(`Expected ${name} hash is malformed.`); + } + if (!/^[0-9a-f]{40}$/u.test(sourceRevision)) throw new Error("Expected source revision is malformed."); + if (!route || route.transport !== "http" || !route.candidateEndpoint.startsWith("http://")) { + throw new Error("Idunn Expected must include an HTTP candidate route."); + } + return { + schemaVersion: string(values[0], "Expected schema"), + target, + planId, + incarnationId, + sealedReleaseId, + sourceRepository, + sourceRevision, + recipeSha256, + runtimeId, + expectedSignerIdentityId, + healthContract, + artifactSha256, + stateSchemaGeneration, + stateContractSha256, + writeLeaseRequired, + route, + capabilities: decodeExpectedCapabilities(values[16]), + dependencies: decodeExpectedDependencies(values[17]), + canonicalBytes, + canonicalSha256: prefixedSha256(canonicalBytes), + }; +} + +function decodeActivation(payload: Uint8Array): RuntimeActivation { + const values = decodeArray(payload, 10, "Idunn Activation"); + if (values[0] !== IDUNN_RUNTIME_ACTIVATION_SCHEMA) throw new Error("Idunn Activation schema is unsupported."); + const canonicalBytes = Buffer.from(encode(values)); + if (!canonicalBytes.equals(Buffer.from(payload))) throw new Error("Idunn Activation is not canonical MessagePack."); + const publicKey = bytes(values[5], "Activation signer public key"); + if (publicKey.length !== 32) throw new Error("Activation signer public key is not Ed25519."); + const activationSignerIdentityId = string(values[4], "Activation signer identity"); + if (number(values[6], "Activation issue time") <= 0 + || !/^[0-9a-f]{64}$/u.test(string(values[7], "Idunn signer identity")) + || values[8] !== "ed25519" + || bytes(values[9], "Activation signature").length !== 64) { + throw new Error("Idunn Activation signature contract is malformed."); + } + if (sha256Hex(Buffer.concat([ACTIVATION_ID_DOMAIN, publicKey])) !== activationSignerIdentityId) { + throw new Error("Activation signer identity does not match its public key."); + } + return { + schemaVersion: string(values[0], "Activation schema"), + expectedProjectionSha256: string(values[1], "Activation Expected hash"), + runtimeId: string(values[2], "Activation runtime id"), + runtimeInstanceId: string(values[3], "Activation instance id"), + activationSignerIdentityId, + activationSignerPublicKey: Buffer.from(publicKey), + canonicalSha256: prefixedSha256(canonicalBytes), + }; +} + +function decodeExpectedCapabilities(value: unknown): ExpectedIncarnation["capabilities"] { + return arrayOf(value, "Expected capabilities").map((raw) => { + const item = array(raw, 4, "Expected capability"); + return { + capability: string(item[0], "Capability id"), + schema: string(item[1], "Capability schema"), + compatibility: string(item[2], "Capability compatibility"), + minimumCapacity: number(item[3], "Capability capacity"), + }; + }); +} + +function decodeExpectedDependencies(value: unknown): ExpectedIncarnation["dependencies"] { + return arrayOf(value, "Expected dependencies").map((raw) => { + const item = array(raw, 10, "Expected dependency"); + return { + kind: string(item[0], "Dependency kind"), + capability: string(item[1], "Dependency capability"), + schema: string(item[2], "Dependency schema"), + compatibility: string(item[3], "Dependency compatibility"), + providerEndpoint: nullableString(item[9], "Dependency provider endpoint"), + }; + }); +} + +function decodeRoute(value: unknown): ExpectedIncarnation["route"] { + if (value === null) return null; + const route = array(value, 4, "Expected route"); + return { + routeId: string(route[0], "Route id"), + transport: string(route[1], "Route transport"), + stableEndpoint: string(route[2], "Stable route endpoint"), + candidateEndpoint: string(route[3], "Candidate route endpoint"), + }; +} + +function openProviderHealthIdentity(credentialBytes: Buffer): crypto.KeyObject { + const record = readAuthorityRecordBytes(credentialBytes, "gamecult.provider_health_identity", "gamecult.provider_health_identity.private.v1"); + const fields = decodeArray(record, 10, "provider-health identity"); + const [schema, identityId, publicKeyValue, protectedSeedValue, protectorKind, binding, version, assurance, createdAt, enrollmentNonceValue] = fields; + if (schema !== "gamecult.provider_health_identity.private.v1" || version !== "v1") throw new Error("Provider-health identity schema is unsupported."); + string(createdAt, "Provider-health identity creation time"); + const enrollmentNonce = bytes(enrollmentNonceValue, "Provider-health enrollment nonce"); + if (enrollmentNonce.length !== 32) throw new Error("Provider-health enrollment nonce has an invalid length."); + const publicKey = bytesValue(publicKeyValue, "Provider-health public key"); + const protectedSeed = bytesValue(protectedSeedValue, "Provider-health protected seed"); + const machineId = fs.readFileSync("/etc/machine-id", "utf8").trim(); + if (!machineId) throw new Error("Linux machine-id is unavailable for provider-health identity."); + const expectedBinding = `${PROVIDER_PROTECTOR_CONTEXT}:machine-id-sha256:${sha256Hex(Buffer.from(machineId))}`; + if (protectorKind !== "linux_file_mode_machine_id_binding" || binding !== expectedBinding || assurance !== "os_installation_file_bound_cloneable_baseline") { + throw new Error("Provider-health identity protector does not match this Linux installation."); + } + if (publicKey.length !== 32 || protectedSeed.length !== 32) throw new Error("Provider-health identity key material has an invalid length."); + const mask = crypto.createHash("sha256").update(Buffer.concat([ + Buffer.from("gamecult-linux-service-seed-v1\0", "utf8"), + Buffer.from(PROVIDER_PROTECTOR_CONTEXT, "utf8"), + Buffer.from(expectedBinding, "utf8"), + ])).digest(); + const seed = Buffer.from(protectedSeed.map((value, index) => value ^ mask[index]!)); + const key = privateKeyFromSeed(seed); + seed.fill(0); + const derivedPublicKey = rawEd25519PublicKey(crypto.createPublicKey(key)); + const derivedId = sha256Hex(Buffer.concat([PROVIDER_ID_DOMAIN, derivedPublicKey])); + if (!derivedPublicKey.equals(publicKey) || identityId !== derivedId) throw new Error("Provider-health private key differs from its enrolled identity."); + return key; +} + +function readAuthorityRecordBytes(bytes: Buffer, type: string, schemaId: string): Uint8Array { + const decoded = decode(bytes); + if (!Array.isArray(decoded) || decoded[0] !== CULTCACHE_STORE_FORMAT || !Array.isArray(decoded[1]) || !Array.isArray(decoded[2])) { + throw new Error("Runtime credential is not a CultCache v1 store."); + } + if (decoded[2].length !== 1) throw new Error("Runtime credential must contain exactly one record."); + const rows = (decoded[2] as unknown[]).filter((raw) => Array.isArray(raw) && raw[1] === schemaId); + if (rows.length !== 1) throw new Error(`Runtime credential must contain exactly one ${schemaId} record.`); + const catalog = (decoded[1] as unknown[]).find((raw) => Array.isArray(raw) && raw[0] === schemaId); + if (!Array.isArray(catalog) || catalog[1] !== type) throw new Error("Runtime credential has an unexpected CultCache type."); + const row = array(rows[0], 4, "Runtime credential record"); + return bytesValue(row[3], "Runtime credential payload"); +} + +function inheritedDescriptorMap(): Map { + if (process.env.LISTEN_PID !== String(process.pid)) throw new Error("Inherited Idunn descriptors do not belong to this process."); + const count = Number(process.env.LISTEN_FDS); + const names = process.env.LISTEN_FDNAMES?.split(":") ?? []; + if (!Number.isInteger(count) || count < 1 || names.length !== count) throw new Error("Inherited Idunn descriptor list is malformed."); + return new Map(names.map((name, index) => [name, index + 3])); +} + +function readDescriptor(descriptor: number): Buffer { + const fdPath = `/proc/self/fd/${descriptor}`; + return fs.readFileSync(fdPath); +} + +function privateKeyFromSeed(seed: Uint8Array): crypto.KeyObject { + return crypto.createPrivateKey({ key: Buffer.concat([ED25519_PKCS8_PREFIX, Buffer.from(seed)]), format: "der", type: "pkcs8" }); +} + +function rawEd25519PublicKey(publicKey: crypto.KeyObject): Buffer { + const der = publicKey.export({ type: "spki", format: "der" }) as Buffer; + return Buffer.from(der.subarray(der.length - 32)); +} + +function providerSignerIdentityId(privateKey: crypto.KeyObject): string { + return sha256Hex(Buffer.concat([PROVIDER_ID_DOMAIN, rawEd25519PublicKey(crypto.createPublicKey(privateKey))])); +} + +function assertLeaseMatches(values: unknown[], authority: IdunnRuntimeAuthority, recentWarmingProofs: string[]): void { + const expected = authority.expected; + const activation = authority.activation; + const matches = values[0] === IDUNN_PROCESS_WRITE_LEASE_SCHEMA + && values[1] === expected.target + && values[2] === expected.canonicalSha256 + && values[3] === expected.planId + && values[4] === expected.incarnationId + && values[5] === expected.sealedReleaseId + && values[6] === activation.canonicalSha256 + && values[7] === expected.stateSchemaGeneration + && values[8] === expected.stateContractSha256 + && values[9] === expected.runtimeId + && values[10] === activation.runtimeInstanceId + && typeof values[11] === "string" + && recentWarmingProofs.includes(values[11]) + && Number.isSafeInteger(values[12]) && Number(values[12]) > 0 + && Number.isSafeInteger(values[13]) && Number(values[13]) > 0; + if (!matches) throw new Error("Idunn process write lease does not match the current Expected incarnation."); +} + +function parseRudpEndpoint(value: string): { host: string; port: number } { + const text = value.replace(/^rudp:\/\//i, ""); + const match = text.match(/^\[([^\]]+)\]:(\d+)$/) ?? text.match(/^([^:]+):(\d+)$/); + if (!match) throw new Error(`Invalid Odin RUDP endpoint: ${value}`); + const port = Number(match[2]); + if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`Invalid Odin RUDP port: ${match[2]}`); + return { host: match[1]!, port }; +} + +function normalizeRudpEndpoint(value: string): string { + const normalized = value.trim().toLowerCase().replace(/^rudp:\/\//, ""); + const parsed = parseRudpEndpoint(normalized); + return `${parsed.host.toLowerCase()}:${parsed.port}`; +} + +function requiredEnvironment(name: string): string { + const value = process.env[name]?.trim(); + if (!value) throw new Error(`${name} is required for Idunn runtime presence.`); + return value; +} + +function abortableDelay(milliseconds: number, signal?: AbortSignal): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, milliseconds); + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason ?? new Error("Aborted.")); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +function array(value: unknown, length: number, label: string): unknown[] { + if (!Array.isArray(value) || value.length !== length) throw new Error(`${label} is not a ${length}-field positional contract.`); + return value; +} + +function decodeArray(payload: Uint8Array, length: number, label: string): unknown[] { + return array(decode(payload), length, label); +} + +function arrayOf(value: unknown, label: string): unknown[] { + if (!Array.isArray(value)) throw new Error(`${label} is not an array.`); + return value; +} + +function string(value: unknown, label: string): string { + if (typeof value !== "string" || !value.trim() || value.trim() !== value || /[\u0000-\u001f\u007f]/u.test(value)) { + throw new Error(`${label} is not a valid authority string.`); + } + return value; +} + +function nullableString(value: unknown, label: string): string | null { + return value === null ? null : string(value, label); +} + +function number(value: unknown, label: string): number { + if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error(`${label} is not a non-negative integer.`); + return value; +} + +function bytes(value: unknown, label: string): Uint8Array { + if (!(value instanceof Uint8Array)) throw new Error(`${label} is not bytes.`); + return value; +} + +function bytesValue(value: unknown, label: string): Buffer { + return Buffer.from(bytes(value, label)); +} + +function prefixedSha256(bytes: Uint8Array): string { + return `sha256-${sha256Hex(bytes)}`; +} + +function sha256Hex(bytes: Uint8Array): string { + return crypto.createHash("sha256").update(bytes).digest("hex"); +} diff --git a/packages/cultnet-ts/src/index.ts b/packages/cultnet-ts/src/index.ts index 84bef769..3db890ef 100644 --- a/packages/cultnet-ts/src/index.ts +++ b/packages/cultnet-ts/src/index.ts @@ -197,3 +197,17 @@ export { type RuntimePresenceHealth, type RuntimePresenceState, } from "./runtime-presence-health"; + +export { + IDUNN_EXPECTED_INCARNATION_SCHEMA, + IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT, + IDUNN_PROCESS_WRITE_LEASE_SCHEMA, + IDUNN_RUNTIME_BUNDLE_ENVIRONMENT, + IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT, + IDUNN_RUNTIME_ACTIVATION_SCHEMA, + createIdunnRuntimePresencePublisher, + loadIdunnRuntimeAuthorityFromEnvironment, + type IdunnRuntimeAuthority, + type IdunnRuntimePresencePublisher, + type IdunnRuntimePresencePublisherOptions, +} from "./idunn-runtime-authority"; diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts new file mode 100644 index 00000000..dd079c91 --- /dev/null +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -0,0 +1,140 @@ +import { mock, test } from "node:test"; +import assert from "node:assert/strict"; +import crypto from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { decode, encode } from "@msgpack/msgpack"; + +import { + loadIdunnRuntimeAuthorityFromEnvironment, + signIdunnRuntimePresence, +} from "../src/idunn-runtime-authority"; +import { + runtimePresenceActivationSigningMessage, + runtimePresenceProofPayload, + runtimePresenceProviderSigningMessage, +} from "../src/runtime-presence-health"; + +const providerIdentityContext = "gamecult-provider-health-identity-v1"; +const providerIdDomain = Buffer.from("gamecult.provider-health.identity.v1\0", "utf8"); +const activationIdDomain = Buffer.from("idunn.runtime-activation.id.v1\0", "utf8"); + +test("opens Idunn's machine-bound identity and signs the exact Expected incarnation twice", (context) => { + const directory = mkdtempSync(path.join(os.tmpdir(), "cultnet-runtime-authority-")); + context.after(() => rmSync(directory, { recursive: true, force: true })); + + const machineId = "1234567890abcdef1234567890abcdef"; + const providerSeed = Buffer.alloc(32, 0x31); + const activationSeed = Buffer.alloc(32, 0x72); + const providerKey = privateKeyFromSeed(providerSeed); + const activationKey = privateKeyFromSeed(activationSeed); + const providerPublic = rawPublic(crypto.createPublicKey(providerKey)); + const activationPublic = rawPublic(crypto.createPublicKey(activationKey)); + const providerIdentity = sha256Hex(Buffer.concat([providerIdDomain, providerPublic])); + const activationIdentity = sha256Hex(Buffer.concat([activationIdDomain, activationPublic])); + const target = "streampixels-service"; + const contract = "streampixels-service.cultnet-rudp-service-health"; + const candidate = "http://127.0.0.1:18831"; + const expectedValues = [ + "idunn.expected_incarnation.v2", target, `sha256-${"1".repeat(64)}`, "incarnation-1", + `sha256-${"2".repeat(64)}`, "https://github.com/GameCult/StreamPixels.git", "a".repeat(40), + `sha256-${"3".repeat(64)}`, "streampixels-service-yggdrasil", providerIdentity, contract, + `sha256-${"4".repeat(64)}`, "service-boundary-v1", `sha256-${"5".repeat(64)}`, true, + ["streampixels-service-http", "http", "http://127.0.0.1:8831", candidate], + [["streampixels.service.api", "streampixels.api.v1", "v1", 1]], + [["shared-infrastructure", "odin.verse-rendezvous", "odin.verse-topology.v1", "v1", 1, "before-promotion", null, null, null, "rudp://127.0.0.1:17871"]], + ]; + const expectedBytes = Buffer.from(encode(expectedValues)); + const expectedSha = `sha256-${sha256Hex(expectedBytes)}`; + const activationValues = [ + "idunn.runtime_activation.v2", expectedSha, "streampixels-service-yggdrasil", + `sha256-${"6".repeat(64)}`, activationIdentity, activationPublic, Date.now(), + "7".repeat(64), "ed25519", new Uint8Array(64).fill(0x17), + ]; + const bundle = path.join(directory, "bundle"); + fs.mkdirSync(bundle); + writeFileSync(path.join(bundle, "expected.cc"), cultCacheStore( + "idunn.expected_incarnation", "idunn.expected_incarnation.v2", "expected", expectedBytes, + )); + writeFileSync(path.join(bundle, "activation.cc"), cultCacheStore( + "idunn.runtime_activation", "idunn.runtime_activation.v2", "activation", Buffer.from(encode(activationValues)), + )); + + const binding = `${providerIdentityContext}:machine-id-sha256:${sha256Hex(Buffer.from(machineId))}`; + const mask = crypto.createHash("sha256").update(Buffer.concat([ + Buffer.from("gamecult-linux-service-seed-v1\0", "utf8"), + Buffer.from(providerIdentityContext, "utf8"), + Buffer.from(binding, "utf8"), + ])).digest(); + const protectedSeed = Buffer.from(providerSeed.map((value, index) => value ^ mask[index]!)); + const providerCredential = cultCacheStore( + "gamecult.provider_health_identity", "gamecult.provider_health_identity.private.v1", + "gamecult-provider-health-identity", Buffer.from(encode([ + "gamecult.provider_health_identity.private.v1", providerIdentity, providerPublic, protectedSeed, + "linux_file_mode_machine_id_binding", binding, "v1", "os_installation_file_bound_cloneable_baseline", + "2026-01-01T00:00:00Z", new Uint8Array(32).fill(0x2a), + ])), + ); + + const originalEnvironment = { ...process.env }; + context.after(() => { + for (const key of Object.keys(process.env)) if (!(key in originalEnvironment)) delete process.env[key]; + Object.assign(process.env, originalEnvironment); + }); + process.env.GAMECULT_IDUNN_RUNTIME_BUNDLE = bundle; + process.env.GAMECULT_IDUNN_CANDIDATE_BIND = candidate; + process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE = path.join(directory, "lease.cc"); + process.env.LISTEN_PID = String(process.pid); + process.env.LISTEN_FDS = "2"; + process.env.LISTEN_FDNAMES = "gamecult-idunn-runtime-activation-key:gamecult-runtime-presence-identity"; + const realReadFileSync = fs.readFileSync.bind(fs); + mock.method(fs, "readFileSync", (filePath: fs.PathOrFileDescriptor, ...args: unknown[]) => { + if (filePath === "/proc/self/fd/3") return activationSeed; + if (filePath === "/proc/self/fd/4") return providerCredential; + if (filePath === "/etc/machine-id") return machineId; + return realReadFileSync(filePath as never, ...args as never[]); + }); + + const authority = loadIdunnRuntimeAuthorityFromEnvironment(target, contract, "127.0.0.1:17871"); + const signed = signIdunnRuntimePresence(authority, { + capabilities: [{ capability: "streampixels.service.api", schema: "streampixels.api.v1", compatibility: "v1", capacity: 1 }], + state: "warming", + detail: "starting", + writeLeaseSha256: null, + publisherSequence: 1, + observedAtUnixMillis: Date.now(), + }); + const proof = runtimePresenceProofPayload(signed.presence); + assert.equal((decode(expectedBytes) as unknown[]).length, 18); + assert.equal(signed.presence.expectedProjectionSha256, expectedSha); + const signedRecord = decode(signed.payload) as unknown[]; + assert.equal(crypto.verify(null, runtimePresenceProviderSigningMessage(proof), crypto.createPublicKey(providerKey), Buffer.from(signedRecord[21] as Uint8Array)), true); + assert.equal(crypto.verify(null, runtimePresenceActivationSigningMessage(proof), crypto.createPublicKey(activationKey), Buffer.from(signedRecord[23] as Uint8Array)), true); +}); + +function cultCacheStore(type: string, schemaId: string, key: string, payload: Uint8Array): Buffer { + return Buffer.from(encode([ + "cultcache.store.v1", + [[schemaId, type, `${schemaId}.v1`, schemaId, "{}", [schemaId], []]], + [[key, schemaId, "2026-01-01T00:00:00Z", payload]], + ])); +} + +function privateKeyFromSeed(seed: Uint8Array): crypto.KeyObject { + return crypto.createPrivateKey({ + key: Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), Buffer.from(seed)]), + format: "der", + type: "pkcs8", + }); +} + +function rawPublic(key: crypto.KeyObject): Buffer { + const der = key.export({ type: "spki", format: "der" }) as Buffer; + return Buffer.from(der.subarray(der.length - 32)); +} + +function sha256Hex(bytes: Uint8Array): string { + return crypto.createHash("sha256").update(bytes).digest("hex"); +} From 21dfd83211dba864d39b1252eb43078ba1778740 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 00:10:26 +0200 Subject: [PATCH 02/14] Validate systemd descriptor PID across namespaces --- .../cultnet-ts/src/idunn-runtime-authority.ts | 16 +++++++++++++++- .../test/idunn-runtime-authority.test.ts | 5 ++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index 28e61e97..00f35c2f 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -588,13 +588,27 @@ function readAuthorityRecordBytes(bytes: Buffer, type: string, schemaId: string) } function inheritedDescriptorMap(): Map { - if (process.env.LISTEN_PID !== String(process.pid)) throw new Error("Inherited Idunn descriptors do not belong to this process."); + if (process.env.LISTEN_PID !== currentSystemdListenPid()) throw new Error("Inherited Idunn descriptors do not belong to this process."); const count = Number(process.env.LISTEN_FDS); const names = process.env.LISTEN_FDNAMES?.split(":") ?? []; if (!Number.isInteger(count) || count < 1 || names.length !== count) throw new Error("Inherited Idunn descriptor list is malformed."); return new Map(names.map((name, index) => [name, index + 3])); } +function currentSystemdListenPid(): string { + try { + const status = fs.readFileSync("/proc/self/status", "utf8"); + const namespacePids = /^NSpid:\s+([0-9]+)(?:\s|$)/mu.exec(status); + // systemd records LISTEN_PID in its PID namespace. In a PrivatePIDs + // service, Node's process.pid is namespace-local, while the first NSpid + // value is the same host PID systemd used for LISTEN_PID. + return namespacePids?.[1] ?? String(process.pid); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return String(process.pid); + throw error; + } +} + function readDescriptor(descriptor: number): Buffer { const fdPath = `/proc/self/fd/${descriptor}`; return fs.readFileSync(fdPath); diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index dd079c91..d1b4dcdb 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -86,11 +86,14 @@ test("opens Idunn's machine-bound identity and signs the exact Expected incarnat process.env.GAMECULT_IDUNN_RUNTIME_BUNDLE = bundle; process.env.GAMECULT_IDUNN_CANDIDATE_BIND = candidate; process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE = path.join(directory, "lease.cc"); - process.env.LISTEN_PID = String(process.pid); + // systemd reports the host PID while Node inside PrivatePIDs sees PID 1. + const listenPid = String(process.pid + 1000); + process.env.LISTEN_PID = listenPid; process.env.LISTEN_FDS = "2"; process.env.LISTEN_FDNAMES = "gamecult-idunn-runtime-activation-key:gamecult-runtime-presence-identity"; const realReadFileSync = fs.readFileSync.bind(fs); mock.method(fs, "readFileSync", (filePath: fs.PathOrFileDescriptor, ...args: unknown[]) => { + if (filePath === "/proc/self/status") return `Name:\tnode\nNSpid:\t${listenPid}\t1\n`; if (filePath === "/proc/self/fd/3") return activationSeed; if (filePath === "/proc/self/fd/4") return providerCredential; if (filePath === "/etc/machine-id") return machineId; From 71aa615d93973680386d6ff256a86ab156bc107d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 00:24:02 +0200 Subject: [PATCH 03/14] Allow systemd descriptors in PID namespace init --- .../cultnet-ts/src/idunn-runtime-authority.ts | 21 +++++++------------ .../test/idunn-runtime-authority.test.ts | 14 +++++++++---- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index 00f35c2f..de4f3579 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -588,25 +588,20 @@ function readAuthorityRecordBytes(bytes: Buffer, type: string, schemaId: string) } function inheritedDescriptorMap(): Map { - if (process.env.LISTEN_PID !== currentSystemdListenPid()) throw new Error("Inherited Idunn descriptors do not belong to this process."); + if (!systemdListenPidMatches(process.env.LISTEN_PID, process.pid)) throw new Error("Inherited Idunn descriptors do not belong to this process."); const count = Number(process.env.LISTEN_FDS); const names = process.env.LISTEN_FDNAMES?.split(":") ?? []; if (!Number.isInteger(count) || count < 1 || names.length !== count) throw new Error("Inherited Idunn descriptor list is malformed."); return new Map(names.map((name, index) => [name, index + 3])); } -function currentSystemdListenPid(): string { - try { - const status = fs.readFileSync("/proc/self/status", "utf8"); - const namespacePids = /^NSpid:\s+([0-9]+)(?:\s|$)/mu.exec(status); - // systemd records LISTEN_PID in its PID namespace. In a PrivatePIDs - // service, Node's process.pid is namespace-local, while the first NSpid - // value is the same host PID systemd used for LISTEN_PID. - return namespacePids?.[1] ?? String(process.pid); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") return String(process.pid); - throw error; - } +export function systemdListenPidMatches(listenPid: string | undefined, processPid: number): boolean { + if (listenPid === String(processPid)) return true; + // systemd sets LISTEN_PID in the host PID namespace. With PrivatePIDs=yes, + // the service's main process is namespace PID 1 and cannot read that host + // PID through its private /proc mount. A descendant has a PID greater than + // 1 and must not reuse the inherited descriptor set. + return processPid === 1 && /^\d+$/u.test(listenPid ?? "") && Number(listenPid) > 1; } function readDescriptor(descriptor: number): Buffer { diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index d1b4dcdb..cfd2b5a4 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -10,6 +10,7 @@ import { decode, encode } from "@msgpack/msgpack"; import { loadIdunnRuntimeAuthorityFromEnvironment, signIdunnRuntimePresence, + systemdListenPidMatches, } from "../src/idunn-runtime-authority"; import { runtimePresenceActivationSigningMessage, @@ -21,6 +22,14 @@ const providerIdentityContext = "gamecult-provider-health-identity-v1"; const providerIdDomain = Buffer.from("gamecult.provider-health.identity.v1\0", "utf8"); const activationIdDomain = Buffer.from("idunn.runtime-activation.id.v1\0", "utf8"); +test("matches systemd's host PID for the private PID namespace init only", () => { + assert.equal(systemdListenPidMatches(String(process.pid), process.pid), true); + assert.equal(systemdListenPidMatches("1725346", 1), true); + assert.equal(systemdListenPidMatches("1725346", 2), false); + assert.equal(systemdListenPidMatches("not-a-pid", 1), false); + assert.equal(systemdListenPidMatches(undefined, 1), false); +}); + test("opens Idunn's machine-bound identity and signs the exact Expected incarnation twice", (context) => { const directory = mkdtempSync(path.join(os.tmpdir(), "cultnet-runtime-authority-")); context.after(() => rmSync(directory, { recursive: true, force: true })); @@ -86,14 +95,11 @@ test("opens Idunn's machine-bound identity and signs the exact Expected incarnat process.env.GAMECULT_IDUNN_RUNTIME_BUNDLE = bundle; process.env.GAMECULT_IDUNN_CANDIDATE_BIND = candidate; process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE = path.join(directory, "lease.cc"); - // systemd reports the host PID while Node inside PrivatePIDs sees PID 1. - const listenPid = String(process.pid + 1000); - process.env.LISTEN_PID = listenPid; + process.env.LISTEN_PID = String(process.pid); process.env.LISTEN_FDS = "2"; process.env.LISTEN_FDNAMES = "gamecult-idunn-runtime-activation-key:gamecult-runtime-presence-identity"; const realReadFileSync = fs.readFileSync.bind(fs); mock.method(fs, "readFileSync", (filePath: fs.PathOrFileDescriptor, ...args: unknown[]) => { - if (filePath === "/proc/self/status") return `Name:\tnode\nNSpid:\t${listenPid}\t1\n`; if (filePath === "/proc/self/fd/3") return activationSeed; if (filePath === "/proc/self/fd/4") return providerCredential; if (filePath === "/etc/machine-id") return machineId; From 5697802dbf86bc9249df21dd208ab332a649704e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 00:35:15 +0200 Subject: [PATCH 04/14] Read inherited Idunn descriptors directly --- packages/cultnet-ts/src/idunn-runtime-authority.ts | 3 +-- packages/cultnet-ts/test/idunn-runtime-authority.test.ts | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index de4f3579..ea07ba27 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -605,8 +605,7 @@ export function systemdListenPidMatches(listenPid: string | undefined, processPi } function readDescriptor(descriptor: number): Buffer { - const fdPath = `/proc/self/fd/${descriptor}`; - return fs.readFileSync(fdPath); + return fs.readFileSync(descriptor); } function privateKeyFromSeed(seed: Uint8Array): crypto.KeyObject { diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index cfd2b5a4..a2277c92 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -100,8 +100,8 @@ test("opens Idunn's machine-bound identity and signs the exact Expected incarnat process.env.LISTEN_FDNAMES = "gamecult-idunn-runtime-activation-key:gamecult-runtime-presence-identity"; const realReadFileSync = fs.readFileSync.bind(fs); mock.method(fs, "readFileSync", (filePath: fs.PathOrFileDescriptor, ...args: unknown[]) => { - if (filePath === "/proc/self/fd/3") return activationSeed; - if (filePath === "/proc/self/fd/4") return providerCredential; + if (filePath === 3) return activationSeed; + if (filePath === 4) return providerCredential; if (filePath === "/etc/machine-id") return machineId; return realReadFileSync(filePath as never, ...args as never[]); }); From 5dd25718af6c32ce8f9881676fed3a0c5c4e15a5 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 00:52:03 +0200 Subject: [PATCH 05/14] Read Idunn identity envelope format --- .../cultnet-ts/src/idunn-runtime-authority.ts | 18 +++++++++++++-- .../test/idunn-runtime-authority.test.ts | 23 +++++++++++++++---- 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index ea07ba27..c6f82c27 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -543,8 +543,7 @@ function decodeRoute(value: unknown): ExpectedIncarnation["route"] { } function openProviderHealthIdentity(credentialBytes: Buffer): crypto.KeyObject { - const record = readAuthorityRecordBytes(credentialBytes, "gamecult.provider_health_identity", "gamecult.provider_health_identity.private.v1"); - const fields = decodeArray(record, 10, "provider-health identity"); + const fields = decodeArray(readProviderHealthIdentityCredential(credentialBytes), 10, "provider-health identity"); const [schema, identityId, publicKeyValue, protectedSeedValue, protectorKind, binding, version, assurance, createdAt, enrollmentNonceValue] = fields; if (schema !== "gamecult.provider_health_identity.private.v1" || version !== "v1") throw new Error("Provider-health identity schema is unsupported."); string(createdAt, "Provider-health identity creation time"); @@ -573,6 +572,21 @@ function openProviderHealthIdentity(credentialBytes: Buffer): crypto.KeyObject { return key; } +function readProviderHealthIdentityCredential(bytes: Buffer): Uint8Array { + const decoded = decode(bytes); + if (!Array.isArray(decoded) || decoded.length !== 1) { + throw new Error("Provider-health identity credential must contain exactly one envelope."); + } + const envelope = array(decoded[0], 5, "Provider-health identity envelope"); + if (envelope[0] !== "gamecult-provider-health-identity" + || envelope[1] !== "gamecult.provider_health_identity.private.v1" + || envelope[4] !== "gamecult.provider_health_identity.private.v1") { + throw new Error("Provider-health identity credential belongs to a different profile or schema."); + } + string(envelope[3], "Provider-health identity stored-at time"); + return bytesValue(envelope[2], "Provider-health identity payload"); +} + function readAuthorityRecordBytes(bytes: Buffer, type: string, schemaId: string): Uint8Array { const decoded = decode(bytes); if (!Array.isArray(decoded) || decoded[0] !== CULTCACHE_STORE_FORMAT || !Array.isArray(decoded[1]) || !Array.isArray(decoded[2])) { diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index a2277c92..1ffeb2ba 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -78,14 +78,18 @@ test("opens Idunn's machine-bound identity and signs the exact Expected incarnat Buffer.from(binding, "utf8"), ])).digest(); const protectedSeed = Buffer.from(providerSeed.map((value, index) => value ^ mask[index]!)); - const providerCredential = cultCacheStore( - "gamecult.provider_health_identity", "gamecult.provider_health_identity.private.v1", - "gamecult-provider-health-identity", Buffer.from(encode([ + const providerCredential = Buffer.from(encode([[ + "gamecult-provider-health-identity", + "gamecult.provider_health_identity.private.v1", + Buffer.from(encode([ "gamecult.provider_health_identity.private.v1", providerIdentity, providerPublic, protectedSeed, "linux_file_mode_machine_id_binding", binding, "v1", "os_installation_file_bound_cloneable_baseline", "2026-01-01T00:00:00Z", new Uint8Array(32).fill(0x2a), ])), - ); + "2026-01-01T00:00:00Z", + "gamecult.provider_health_identity.private.v1", + ]])); + let descriptorProviderCredential = providerCredential; const originalEnvironment = { ...process.env }; context.after(() => { @@ -101,7 +105,7 @@ test("opens Idunn's machine-bound identity and signs the exact Expected incarnat const realReadFileSync = fs.readFileSync.bind(fs); mock.method(fs, "readFileSync", (filePath: fs.PathOrFileDescriptor, ...args: unknown[]) => { if (filePath === 3) return activationSeed; - if (filePath === 4) return providerCredential; + if (filePath === 4) return descriptorProviderCredential; if (filePath === "/etc/machine-id") return machineId; return realReadFileSync(filePath as never, ...args as never[]); }); @@ -121,6 +125,15 @@ test("opens Idunn's machine-bound identity and signs the exact Expected incarnat const signedRecord = decode(signed.payload) as unknown[]; assert.equal(crypto.verify(null, runtimePresenceProviderSigningMessage(proof), crypto.createPublicKey(providerKey), Buffer.from(signedRecord[21] as Uint8Array)), true); assert.equal(crypto.verify(null, runtimePresenceActivationSigningMessage(proof), crypto.createPublicKey(activationKey), Buffer.from(signedRecord[23] as Uint8Array)), true); + + descriptorProviderCredential = Buffer.from(encode([ + ...(decode(providerCredential) as unknown[][]), + ...(decode(providerCredential) as unknown[][]), + ])); + assert.throws( + () => loadIdunnRuntimeAuthorityFromEnvironment(target, contract, "127.0.0.1:17871"), + /exactly one envelope/, + ); }); function cultCacheStore(type: string, schemaId: string, key: string, payload: Uint8Array): Buffer { From 2c5dc3e27833050f667053b6a8a6c2428672cd11 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 01:00:52 +0200 Subject: [PATCH 06/14] Decode Idunn identity byte vectors --- packages/cultnet-ts/src/idunn-runtime-authority.ts | 13 ++++++++++--- .../cultnet-ts/test/idunn-runtime-authority.test.ts | 4 ++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index c6f82c27..e01be597 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -547,10 +547,10 @@ function openProviderHealthIdentity(credentialBytes: Buffer): crypto.KeyObject { const [schema, identityId, publicKeyValue, protectedSeedValue, protectorKind, binding, version, assurance, createdAt, enrollmentNonceValue] = fields; if (schema !== "gamecult.provider_health_identity.private.v1" || version !== "v1") throw new Error("Provider-health identity schema is unsupported."); string(createdAt, "Provider-health identity creation time"); - const enrollmentNonce = bytes(enrollmentNonceValue, "Provider-health enrollment nonce"); + const enrollmentNonce = providerIdentityByteVector(enrollmentNonceValue, "Provider-health enrollment nonce"); if (enrollmentNonce.length !== 32) throw new Error("Provider-health enrollment nonce has an invalid length."); - const publicKey = bytesValue(publicKeyValue, "Provider-health public key"); - const protectedSeed = bytesValue(protectedSeedValue, "Provider-health protected seed"); + const publicKey = Buffer.from(providerIdentityByteVector(publicKeyValue, "Provider-health public key")); + const protectedSeed = Buffer.from(providerIdentityByteVector(protectedSeedValue, "Provider-health protected seed")); const machineId = fs.readFileSync("/etc/machine-id", "utf8").trim(); if (!machineId) throw new Error("Linux machine-id is unavailable for provider-health identity."); const expectedBinding = `${PROVIDER_PROTECTOR_CONTEXT}:machine-id-sha256:${sha256Hex(Buffer.from(machineId))}`; @@ -587,6 +587,13 @@ function readProviderHealthIdentityCredential(bytes: Buffer): Uint8Array { return bytesValue(envelope[2], "Provider-health identity payload"); } +function providerIdentityByteVector(value: unknown, label: string): Uint8Array { + if (!Array.isArray(value) || value.some((byte) => typeof byte !== "number" || !Number.isInteger(byte) || byte < 0 || byte > 255)) { + throw new Error(`${label} is not a byte vector.`); + } + return Uint8Array.from(value as number[]); +} + function readAuthorityRecordBytes(bytes: Buffer, type: string, schemaId: string): Uint8Array { const decoded = decode(bytes); if (!Array.isArray(decoded) || decoded[0] !== CULTCACHE_STORE_FORMAT || !Array.isArray(decoded[1]) || !Array.isArray(decoded[2])) { diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index 1ffeb2ba..4b7b4865 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -82,9 +82,9 @@ test("opens Idunn's machine-bound identity and signs the exact Expected incarnat "gamecult-provider-health-identity", "gamecult.provider_health_identity.private.v1", Buffer.from(encode([ - "gamecult.provider_health_identity.private.v1", providerIdentity, providerPublic, protectedSeed, + "gamecult.provider_health_identity.private.v1", providerIdentity, Array.from(providerPublic), Array.from(protectedSeed), "linux_file_mode_machine_id_binding", binding, "v1", "os_installation_file_bound_cloneable_baseline", - "2026-01-01T00:00:00Z", new Uint8Array(32).fill(0x2a), + "2026-01-01T00:00:00Z", Array(32).fill(0x2a), ])), "2026-01-01T00:00:00Z", "gamecult.provider_health_identity.private.v1", From 564d5bf732f263ff23f3c58e3d98ffec9bb23564 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 02:11:12 +0200 Subject: [PATCH 07/14] Fix Idunn runtime presence RUDP publication --- .../cultnet-ts/src/idunn-runtime-authority.ts | 22 +++++-- .../test/idunn-runtime-authority.test.ts | 63 ++++++++++++++++++- 2 files changed, 80 insertions(+), 5 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index e01be597..2956cc2f 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -13,7 +13,7 @@ import { encodeRuntimePresenceHealth, type RuntimePresenceHealth, } from "./runtime-presence-health"; -import { encodeCultNetMessageForWire } from "./contracts"; +import { encodeCultNetMessageForWire, parseCultNetMessage } from "./contracts"; import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp"; import type { CultNetRudpPacket } from "./rudp"; import dgram from "node:dgram"; @@ -306,11 +306,23 @@ async function publishDocument( try { await sendPacket(socket, endpoint, session.createConnect(Date.now(), new Uint8Array())); await receiveUntil(receiver, session, endpoint, (packet) => packet.packetType === "accept", 5000); - const wirePayload = Uint8Array.from(encodeCultNetMessageForWire(message as never, "cultnet.schema.v0") as Uint8Array); + const wirePayload = encode(encodeCultNetMessageForWire(message as never, "cultnet.schema.v0")); const packets = session.sendMany("schema", wirePayload, { reliable: true, ordered: true, nowMs: Date.now() }); - const ack = receiveUntil(receiver, session, endpoint, (packet) => packet.packetType === "ack", 2000); for (const packet of packets) await sendPacket(socket, endpoint, packet); - await ack; + await receiveUntil( + receiver, + session, + endpoint, + () => session.outstandingReliablePacketCount === 0, + 2000, + (frame) => { + if (frame.channelId !== "schema") return; + const response = parseCultNetMessage(decode(frame.payload)); + if (response.schemaVersion === "cultnet.error.v0") { + throw new Error(`Odin rejected runtime presence: ${response.error}`); + } + }, + ); } finally { receiver.close(); socket.close(); @@ -379,6 +391,7 @@ async function receiveUntil( endpoint: { host: string; port: number }, predicate: (packet: CultNetRudpPacket) => boolean, timeoutMs: number, + onDelivered?: (frame: { channelId: string; payload: Uint8Array; sequence: number }) => void, ): Promise { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { @@ -386,6 +399,7 @@ async function receiveUntil( const packet = await receiver.next(Math.min(100, deadline - Date.now())); const received = session.receive(packet, Date.now()); if (received.reply) throw new Error("Runtime presence received an unexpected reply-required packet."); + for (const frame of received.delivered) onDelivered?.(frame); if (predicate(packet)) return; } catch (error) { if ((error as NodeJS.ErrnoException)?.code !== "ETIMEDOUT") throw error; diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index 4b7b4865..a27499cf 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -1,6 +1,7 @@ import { mock, test } from "node:test"; import assert from "node:assert/strict"; import crypto from "node:crypto"; +import dgram from "node:dgram"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -8,10 +9,12 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { decode, encode } from "@msgpack/msgpack"; import { + createIdunnRuntimePresencePublisher, loadIdunnRuntimeAuthorityFromEnvironment, signIdunnRuntimePresence, systemdListenPidMatches, } from "../src/idunn-runtime-authority"; +import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "../src/rudp"; import { runtimePresenceActivationSigningMessage, runtimePresenceProofPayload, @@ -30,7 +33,7 @@ test("matches systemd's host PID for the private PID namespace init only", () => assert.equal(systemdListenPidMatches(undefined, 1), false); }); -test("opens Idunn's machine-bound identity and signs the exact Expected incarnation twice", (context) => { +test("opens Idunn identity and publishes valid CultNet data while surfacing piggybacked application errors", async (context) => { const directory = mkdtempSync(path.join(os.tmpdir(), "cultnet-runtime-authority-")); context.after(() => rmSync(directory, { recursive: true, force: true })); @@ -126,6 +129,64 @@ test("opens Idunn's machine-bound identity and signs the exact Expected incarnat assert.equal(crypto.verify(null, runtimePresenceProviderSigningMessage(proof), crypto.createPublicKey(providerKey), Buffer.from(signedRecord[21] as Uint8Array)), true); assert.equal(crypto.verify(null, runtimePresenceActivationSigningMessage(proof), crypto.createPublicKey(activationKey), Buffer.from(signedRecord[23] as Uint8Array)), true); + const peer = dgram.createSocket("udp4"); + await new Promise((resolve, reject) => { + peer.once("error", reject); + peer.bind(0, "127.0.0.1", resolve); + }); + context.after(() => peer.close()); + const address = peer.address(); + assert.equal(typeof address, "object"); + const peerPort = (address as { port: number }).port; + let serverSession: CultNetRudpSession | undefined; + let receivedMessage: unknown; + let responseAck: number | undefined; + let peerFailure: Error | undefined; + peer.on("message", (wire, remote) => { + try { + const packet = decodeRudpPacket(wire); + if (packet.packetType === "connect") { + serverSession = new CultNetRudpSession({ connectionId: packet.connectionId, initialSequence: 100 }); + const accept = serverSession.acceptConnect(packet, Date.now()); + peer.send(encodeRudpPacket(accept), remote.port, remote.address); + return; + } + if (!serverSession) throw new Error("Publisher sent data before establishing RUDP."); + const result = serverSession.receive(packet, Date.now()); + const frame = result.delivered.find((candidate) => candidate.channelId === "schema"); + if (!frame) return; + receivedMessage = decode(frame.payload); + const errorPayload = encode({ + schemaVersion: "cultnet.error.v0", + error: "test admission denied", + routingHint: null, + code: null, + details: null, + }); + const [response] = serverSession.sendMany("schema", errorPayload, { + reliable: true, + ordered: true, + nowMs: Date.now(), + }); + assert.ok(response); + responseAck = response.ack; + peer.send(encodeRudpPacket(response), remote.port, remote.address); + } catch (error) { + peerFailure = error as Error; + } + }); + const publisher = createIdunnRuntimePresencePublisher({ + authority, + endpoint: `rudp://127.0.0.1:${peerPort}`, + healthContract: contract, + capabilities: [{ capability: "streampixels.service.api", schema: "streampixels.api.v1", compatibility: "v1", capacity: 1 }], + }); + await assert.rejects(publisher.publish("warming", "local RUDP integration"), /Odin rejected runtime presence: test admission denied/); + assert.deepEqual(receivedMessage && (receivedMessage as { schemaVersion?: string }).schemaVersion, "cultnet.document_put_raw.v0"); + assert.ok(Buffer.from(encode(receivedMessage)).byteLength > 0); + assert.equal(responseAck, 2, "the response data packet must acknowledge the publisher's reliable schema packet"); + assert.equal(peerFailure, undefined, peerFailure?.message); + descriptorProviderCredential = Buffer.from(encode([ ...(decode(providerCredential) as unknown[][]), ...(decode(providerCredential) as unknown[][]), From 02f13527eb091b74e7fb617fa4570e8891cda4e9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 02:51:12 +0200 Subject: [PATCH 08/14] Use explicit Ajv ESM entrypoint --- packages/cultnet-ts/src/contracts.ts | 2 +- packages/cultnet-ts/src/json-schema-contract.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/cultnet-ts/src/contracts.ts b/packages/cultnet-ts/src/contracts.ts index d90af381..4bfdafad 100644 --- a/packages/cultnet-ts/src/contracts.ts +++ b/packages/cultnet-ts/src/contracts.ts @@ -1,4 +1,4 @@ -import Ajv2020, { type ValidateFunction } from "ajv/dist/2020"; +import Ajv2020, { type ValidateFunction } from "ajv/dist/2020.js"; import documentRecordSchema from "../contracts/cultnet/cultnet.document-record.schema.json"; import helloSchema from "../contracts/cultnet/cultnet.hello.schema.json"; diff --git a/packages/cultnet-ts/src/json-schema-contract.ts b/packages/cultnet-ts/src/json-schema-contract.ts index 4d8fb85d..399290ef 100644 --- a/packages/cultnet-ts/src/json-schema-contract.ts +++ b/packages/cultnet-ts/src/json-schema-contract.ts @@ -1,4 +1,4 @@ -import Ajv2020, { type ErrorObject, type ValidateFunction } from "ajv/dist/2020"; +import Ajv2020, { type ErrorObject, type ValidateFunction } from "ajv/dist/2020.js"; import type { CultCacheSchema } from "@gamecult/cultcache-ts"; export interface JsonSchemaContract extends CultCacheSchema { From 265f716391c3183d2ebb4e2812c1e26e69ea529a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 03:29:01 +0200 Subject: [PATCH 09/14] Expose published Idunn presence snapshots --- .../cultnet-ts/src/idunn-runtime-authority.ts | 34 +++++++++++++------ .../test/idunn-runtime-authority.test.ts | 21 ++++++++++-- 2 files changed, 42 insertions(+), 13 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index 2956cc2f..af294c3f 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -13,7 +13,7 @@ import { encodeRuntimePresenceHealth, type RuntimePresenceHealth, } from "./runtime-presence-health"; -import { encodeCultNetMessageForWire, parseCultNetMessage } from "./contracts"; +import { encodeCultNetMessageForWire, parseCultNetMessage, type CultNetRawDocumentRecord } from "./contracts"; import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp"; import type { CultNetRudpPacket } from "./rudp"; import dgram from "node:dgram"; @@ -79,6 +79,7 @@ export type IdunnRuntimePresencePublisher = { readonly runtimeId: string; readonly runtimeInstanceId: string; readonly requiresWriteLease: boolean; + latestPresenceDocument(): CultNetRawDocumentRecord | null; publish(state: RuntimePresenceHealth["state"], detail: string): Promise; waitForWriteLease(options?: { pollIntervalMs?: number; signal?: AbortSignal }): Promise; assertWriteLease(): Promise; @@ -219,6 +220,7 @@ export function createIdunnRuntimePresencePublisher( const connectionId = 0x0d1d0002; let sequence = 0; let latestLeaseSha256: string | null = null; + let latestPresenceDocument: CultNetRawDocumentRecord | null = null; const recentWarmingProofs: string[] = []; const assertWriteLease = async () => { @@ -243,20 +245,22 @@ export function createIdunnRuntimePresencePublisher( publisherSequence: sequence, observedAtUnixMillis: Date.now(), }); + const document: CultNetRawDocumentRecord = { + schemaId: GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, + recordKey: expected.target, + storedAt: new Date().toISOString(), + payloadEncoding: "messagepack", + payload: new Uint8Array(signed.payload), + sourceRuntimeId: expected.runtimeId, + sourceRole: "runtime-presence-health-publisher", + tags: ["cultnet.transport.rudp.v0", "runtime-presence"], + }; await publishDocument(endpoint, connectionId, { schemaVersion: "cultnet.document_put_raw.v0", messageId: `runtime-presence:${expected.target}:${options.authority.activation.runtimeInstanceId}:${sequence}`, - document: { - schemaId: GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, - recordKey: expected.target, - storedAt: new Date().toISOString(), - payloadEncoding: "messagepack", - payload: signed.payload, - sourceRuntimeId: expected.runtimeId, - sourceRole: "runtime-presence-health-publisher", - tags: ["cultnet.transport.rudp.v0", "runtime-presence"], - }, + document, }); + latestPresenceDocument = document; if (state === "warming") { recentWarmingProofs.push(signed.canonicalSha256); if (recentWarmingProofs.length > MAX_RECENT_WARMING_PROOFS) recentWarmingProofs.shift(); @@ -268,6 +272,14 @@ export function createIdunnRuntimePresencePublisher( runtimeId: expected.runtimeId, runtimeInstanceId: options.authority.activation.runtimeInstanceId, requiresWriteLease: expected.writeLeaseRequired, + latestPresenceDocument() { + if (!latestPresenceDocument) return null; + return { + ...latestPresenceDocument, + payload: new Uint8Array(latestPresenceDocument.payload), + ...(latestPresenceDocument.tags ? { tags: [...latestPresenceDocument.tags] } : {}), + }; + }, publish, async waitForWriteLease({ pollIntervalMs = 5000, signal } = {}) { if (!expected.writeLeaseRequired) return ""; diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index a27499cf..6dcdc956 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -142,6 +142,7 @@ test("opens Idunn identity and publishes valid CultNet data while surfacing pigg let receivedMessage: unknown; let responseAck: number | undefined; let peerFailure: Error | undefined; + let rejectOdinAdmission = true; peer.on("message", (wire, remote) => { try { const packet = decodeRudpPacket(wire); @@ -156,14 +157,18 @@ test("opens Idunn identity and publishes valid CultNet data while surfacing pigg const frame = result.delivered.find((candidate) => candidate.channelId === "schema"); if (!frame) return; receivedMessage = decode(frame.payload); - const errorPayload = encode({ + const responsePayload = encode(rejectOdinAdmission ? { schemaVersion: "cultnet.error.v0", error: "test admission denied", routingHint: null, code: null, details: null, + } : { + schemaVersion: "cultnet.snapshot_response.v0", + messageId: "ack", + documents: [], }); - const [response] = serverSession.sendMany("schema", errorPayload, { + const [response] = serverSession.sendMany("schema", responsePayload, { reliable: true, ordered: true, nowMs: Date.now(), @@ -186,6 +191,18 @@ test("opens Idunn identity and publishes valid CultNet data while surfacing pigg assert.ok(Buffer.from(encode(receivedMessage)).byteLength > 0); assert.equal(responseAck, 2, "the response data packet must acknowledge the publisher's reliable schema packet"); assert.equal(peerFailure, undefined, peerFailure?.message); + assert.equal(publisher.latestPresenceDocument(), null, "a rejected publication must not become the snapshot source"); + + rejectOdinAdmission = false; + await publisher.publish("warming", "accepted presence"); + const publishedDocument = (receivedMessage as { document: { payload: Uint8Array; schemaId: string; recordKey: string } }).document; + const snapshotDocument = publisher.latestPresenceDocument(); + assert.ok(snapshotDocument); + assert.equal(snapshotDocument.schemaId, publishedDocument.schemaId); + assert.equal(snapshotDocument.recordKey, publishedDocument.recordKey); + assert.deepEqual(Buffer.from(snapshotDocument.payload), Buffer.from(publishedDocument.payload)); + snapshotDocument.payload[0] = snapshotDocument.payload[0]! ^ 0xff; + assert.deepEqual(Buffer.from(publisher.latestPresenceDocument()?.payload ?? []), Buffer.from(publishedDocument.payload), "snapshot readers cannot mutate publisher state"); descriptorProviderCredential = Buffer.from(encode([ ...(decode(providerCredential) as unknown[][]), From 542ddd3e5830ad7dc44e69298e5469f97f992422 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 28 Sep 2026 03:54:21 +0200 Subject: [PATCH 10/14] Bind runtime presence to route challenges --- .../cultnet-ts/src/idunn-runtime-authority.ts | 32 ++++++++++++++----- .../test/idunn-runtime-authority.test.ts | 15 +++++++-- 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index af294c3f..b675d5c3 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -13,7 +13,7 @@ import { encodeRuntimePresenceHealth, type RuntimePresenceHealth, } from "./runtime-presence-health"; -import { encodeCultNetMessageForWire, parseCultNetMessage, type CultNetRawDocumentRecord } from "./contracts"; +import { encodeCultNetMessageForWire, parseCultNetMessage, type CultNetRawDocumentRecord, type CultNetSnapshotRequestMessage } from "./contracts"; import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp"; import type { CultNetRudpPacket } from "./rudp"; import dgram from "node:dgram"; @@ -80,6 +80,7 @@ export type IdunnRuntimePresencePublisher = { readonly runtimeInstanceId: string; readonly requiresWriteLease: boolean; latestPresenceDocument(): CultNetRawDocumentRecord | null; + publishRouteObservation(request: CultNetSnapshotRequestMessage): Promise; publish(state: RuntimePresenceHealth["state"], detail: string): Promise; waitForWriteLease(options?: { pollIntervalMs?: number; signal?: AbortSignal }): Promise; assertWriteLease(): Promise; @@ -268,17 +269,32 @@ export function createIdunnRuntimePresencePublisher( return signed.canonicalSha256; }; + const copyLatestPresenceDocument = (): CultNetRawDocumentRecord | null => { + if (!latestPresenceDocument) return null; + return { + ...latestPresenceDocument, + payload: new Uint8Array(latestPresenceDocument.payload), + ...(latestPresenceDocument.tags ? { tags: [...latestPresenceDocument.tags] } : {}), + }; + }; + return { runtimeId: expected.runtimeId, runtimeInstanceId: options.authority.activation.runtimeInstanceId, requiresWriteLease: expected.writeLeaseRequired, - latestPresenceDocument() { - if (!latestPresenceDocument) return null; - return { - ...latestPresenceDocument, - payload: new Uint8Array(latestPresenceDocument.payload), - ...(latestPresenceDocument.tags ? { tags: [...latestPresenceDocument.tags] } : {}), - }; + latestPresenceDocument: copyLatestPresenceDocument, + async publishRouteObservation(request) { + if (!request.messageId || request.messageId.trim() !== request.messageId) throw new Error("Idunn route observation requires a message id."); + if ((request.schemaIds && !request.schemaIds.includes(GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA)) + || (request.recordKeys && !request.recordKeys.includes(expected.target)) + || request.shardId !== undefined + || request.shardEpoch !== undefined) { + throw new Error("Idunn route observation does not request this runtime presence document."); + } + await publish("active", `route-observation:${request.messageId}`); + const document = copyLatestPresenceDocument(); + if (!document) throw new Error("Idunn route observation was published without a presence document."); + return document; }, publish, async waitForWriteLease({ pollIntervalMs = 5000, signal } = {}) { diff --git a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts index 6dcdc956..7969fde2 100644 --- a/packages/cultnet-ts/test/idunn-runtime-authority.test.ts +++ b/packages/cultnet-ts/test/idunn-runtime-authority.test.ts @@ -19,6 +19,7 @@ import { runtimePresenceActivationSigningMessage, runtimePresenceProofPayload, runtimePresenceProviderSigningMessage, + RUNTIME_PRESENCE_SLOT, } from "../src/runtime-presence-health"; const providerIdentityContext = "gamecult-provider-health-identity-v1"; @@ -53,7 +54,7 @@ test("opens Idunn identity and publishes valid CultNet data while surfacing pigg "idunn.expected_incarnation.v2", target, `sha256-${"1".repeat(64)}`, "incarnation-1", `sha256-${"2".repeat(64)}`, "https://github.com/GameCult/StreamPixels.git", "a".repeat(40), `sha256-${"3".repeat(64)}`, "streampixels-service-yggdrasil", providerIdentity, contract, - `sha256-${"4".repeat(64)}`, "service-boundary-v1", `sha256-${"5".repeat(64)}`, true, + `sha256-${"4".repeat(64)}`, "service-boundary-v1", `sha256-${"5".repeat(64)}`, false, ["streampixels-service-http", "http", "http://127.0.0.1:8831", candidate], [["streampixels.service.api", "streampixels.api.v1", "v1", 1]], [["shared-infrastructure", "odin.verse-rendezvous", "odin.verse-topology.v1", "v1", 1, "before-promotion", null, null, null, "rudp://127.0.0.1:17871"]], @@ -101,7 +102,7 @@ test("opens Idunn identity and publishes valid CultNet data while surfacing pigg }); process.env.GAMECULT_IDUNN_RUNTIME_BUNDLE = bundle; process.env.GAMECULT_IDUNN_CANDIDATE_BIND = candidate; - process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE = path.join(directory, "lease.cc"); + delete process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE; process.env.LISTEN_PID = String(process.pid); process.env.LISTEN_FDS = "2"; process.env.LISTEN_FDNAMES = "gamecult-idunn-runtime-activation-key:gamecult-runtime-presence-identity"; @@ -195,12 +196,20 @@ test("opens Idunn identity and publishes valid CultNet data while surfacing pigg rejectOdinAdmission = false; await publisher.publish("warming", "accepted presence"); + const snapshotDocument = await publisher.publishRouteObservation({ + schemaVersion: "cultnet.snapshot_request.v0", + messageId: "route-challenge-1", + schemaIds: ["gamecult.runtime_presence_health.v2"], + recordKeys: [target], + }); const publishedDocument = (receivedMessage as { document: { payload: Uint8Array; schemaId: string; recordKey: string } }).document; - const snapshotDocument = publisher.latestPresenceDocument(); assert.ok(snapshotDocument); assert.equal(snapshotDocument.schemaId, publishedDocument.schemaId); assert.equal(snapshotDocument.recordKey, publishedDocument.recordKey); assert.deepEqual(Buffer.from(snapshotDocument.payload), Buffer.from(publishedDocument.payload)); + const routePresence = decode(snapshotDocument.payload) as unknown[]; + assert.equal(routePresence[RUNTIME_PRESENCE_SLOT.state], "active"); + assert.equal(routePresence[RUNTIME_PRESENCE_SLOT.detail], "route-observation:route-challenge-1"); snapshotDocument.payload[0] = snapshotDocument.payload[0]! ^ 0xff; assert.deepEqual(Buffer.from(publisher.latestPresenceDocument()?.payload ?? []), Buffer.from(publishedDocument.payload), "snapshot readers cannot mutate publisher state"); From 8b8650221bba433e9eb758c0c14ef131fa961cc4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 01:12:15 +0200 Subject: [PATCH 11/14] cultnet-ts: bound runtime presence detail by UTF-8 bytes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Rust owner refuses detail over 512 UTF-8 bytes; TypeScript counted UTF-16 units, so 300 x "é" was signed and then refused, and a slice inside a surrogate pair produced invalid UTF-8. One helper, truncateRuntimePresenceDetail, now cuts on a code point boundary at 512 bytes and serves both the publisher and validateRuntimePresence. Co-Authored-By: Claude Sonnet 5 --- .../cultnet-ts/src/idunn-runtime-authority.ts | 3 +- .../cultnet-ts/src/runtime-presence-health.ts | 21 ++++++++++++- .../test/runtime-presence-health.test.ts | 30 +++++++++++++++++++ 3 files changed, 52 insertions(+), 2 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index b675d5c3..d55c4dc4 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -9,6 +9,7 @@ import { IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME, runtimePresenceActivationSigningMessage, runtimePresenceProofPayload, + truncateRuntimePresenceDetail, runtimePresenceProviderSigningMessage, encodeRuntimePresenceHealth, type RuntimePresenceHealth, @@ -241,7 +242,7 @@ export function createIdunnRuntimePresencePublisher( const signed = signIdunnRuntimePresence(options.authority, { capabilities: options.capabilities, state, - detail: detail.slice(0, 512), + detail: truncateRuntimePresenceDetail(detail), writeLeaseSha256, publisherSequence: sequence, observedAtUnixMillis: Date.now(), diff --git a/packages/cultnet-ts/src/runtime-presence-health.ts b/packages/cultnet-ts/src/runtime-presence-health.ts index 8d70da8e..4cdccd1e 100644 --- a/packages/cultnet-ts/src/runtime-presence-health.ts +++ b/packages/cultnet-ts/src/runtime-presence-health.ts @@ -171,6 +171,25 @@ function presenceTuple( return fields; } +/** The Rust owner (`cultnet-rs`) bounds presence detail by UTF-8 bytes, not UTF-16 units. */ +export const RUNTIME_PRESENCE_DETAIL_MAX_BYTES = 512; + +/** + * Longest prefix of `detail` within the UTF-8 byte limit, cut on a code point + * boundary. The single rule for both signing and validation: a detail is valid + * exactly when this returns it unchanged. + */ +export function truncateRuntimePresenceDetail(detail: string): string { + let bytes = 0; + let end = 0; + for (const char of detail) { + bytes += Buffer.byteLength(char, "utf8"); + if (bytes > RUNTIME_PRESENCE_DETAIL_MAX_BYTES) break; + end += char.length; + } + return detail.slice(0, end); +} + /** * Reject statements the contract forbids, before they are signed. * @@ -185,7 +204,7 @@ export function validateRuntimePresence(presence: RuntimePresenceHealth): void { if (presence.observedAtUnixMillis <= 0 || !Number.isSafeInteger(presence.observedAtUnixMillis)) { throw new Error("runtime presence observation time must be a positive integer"); } - if (presence.detail.length > 512 || /\p{Cc}/u.test(presence.detail)) { + if (truncateRuntimePresenceDetail(presence.detail) !== presence.detail || /\p{Cc}/u.test(presence.detail)) { throw new Error("runtime presence detail is too long or carries control characters"); } if (presence.state === "warming" && presence.writeLeaseSha256 !== null) { diff --git a/packages/cultnet-ts/test/runtime-presence-health.test.ts b/packages/cultnet-ts/test/runtime-presence-health.test.ts index fa21aeaa..5a4de05f 100644 --- a/packages/cultnet-ts/test/runtime-presence-health.test.ts +++ b/packages/cultnet-ts/test/runtime-presence-health.test.ts @@ -18,6 +18,7 @@ import { RUNTIME_PRESENCE_FIELD_COUNT, encodeRuntimePresenceHealth, runtimePresenceProofPayload, + truncateRuntimePresenceDetail, validateRuntimePresence, type RuntimePresenceHealth, } from "../src/runtime-presence-health"; @@ -121,3 +122,32 @@ test("statements the contract forbids are refused before they are signed", () => const partialLineage = { ...referencePresence(), stateContractSha256: null }; assert.throws(() => validateRuntimePresence(partialLineage), /state lineage is partial/); }); + +const utf8Bytes = (text: string) => Buffer.byteLength(text, "utf8"); +const isValidUtf8 = (text: string) => !Buffer.from(text, "utf8").toString("utf8").includes("\uFFFD") && !text.includes("\uFFFD"); + +test("presence detail is truncated to 512 UTF-8 bytes, not UTF-16 units", () => { + const truncated = truncateRuntimePresenceDetail("é".repeat(300)); + assert.ok(utf8Bytes(truncated) <= 512); + assert.equal(truncated, "é".repeat(256)); + assert.ok(isValidUtf8(truncated)); +}); + +test("presence detail drops a 4-byte character straddling the boundary whole", () => { + const truncated = truncateRuntimePresenceDetail("a".repeat(510) + "😀"); + assert.equal(truncated, "a".repeat(510)); + assert.ok(isValidUtf8(truncated)); + assert.equal(truncateRuntimePresenceDetail("a".repeat(508) + "😀"), "a".repeat(508) + "😀"); +}); + +test("presence detail of exactly 512 ASCII bytes passes unchanged and 513 is cut", () => { + const exact = "a".repeat(512); + assert.equal(truncateRuntimePresenceDetail(exact), exact); + assert.doesNotThrow(() => validateRuntimePresence({ ...referencePresence(), detail: exact })); + assert.equal(truncateRuntimePresenceDetail(exact + "a"), exact); + assert.throws(() => validateRuntimePresence({ ...referencePresence(), detail: exact + "a" }), /too long/); +}); + +test("validation refuses a detail that is short in UTF-16 units but over 512 UTF-8 bytes", () => { + assert.throws(() => validateRuntimePresence({ ...referencePresence(), detail: "é".repeat(300) }), /too long/); +}); From 8e578ea2ab27b7e2f37415b05967ba10a94ce683 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 01:12:15 +0200 Subject: [PATCH 12/14] cultnet-ts: delete unused readAuthorityRecordBytes Never called; removed with nothing else depending on it. Co-Authored-By: Claude Sonnet 5 --- packages/cultnet-ts/src/idunn-runtime-authority.ts | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index d55c4dc4..d96c892b 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -637,20 +637,6 @@ function providerIdentityByteVector(value: unknown, label: string): Uint8Array { return Uint8Array.from(value as number[]); } -function readAuthorityRecordBytes(bytes: Buffer, type: string, schemaId: string): Uint8Array { - const decoded = decode(bytes); - if (!Array.isArray(decoded) || decoded[0] !== CULTCACHE_STORE_FORMAT || !Array.isArray(decoded[1]) || !Array.isArray(decoded[2])) { - throw new Error("Runtime credential is not a CultCache v1 store."); - } - if (decoded[2].length !== 1) throw new Error("Runtime credential must contain exactly one record."); - const rows = (decoded[2] as unknown[]).filter((raw) => Array.isArray(raw) && raw[1] === schemaId); - if (rows.length !== 1) throw new Error(`Runtime credential must contain exactly one ${schemaId} record.`); - const catalog = (decoded[1] as unknown[]).find((raw) => Array.isArray(raw) && raw[0] === schemaId); - if (!Array.isArray(catalog) || catalog[1] !== type) throw new Error("Runtime credential has an unexpected CultCache type."); - const row = array(rows[0], 4, "Runtime credential record"); - return bytesValue(row[3], "Runtime credential payload"); -} - function inheritedDescriptorMap(): Map { if (!systemdListenPidMatches(process.env.LISTEN_PID, process.pid)) throw new Error("Inherited Idunn descriptors do not belong to this process."); const count = Number(process.env.LISTEN_FDS); From a957f07539055fff91e3f660cc48d22a543578d1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 01:19:41 +0200 Subject: [PATCH 13/14] cultnet-ts: one UTF-8 byte bound for presence and daemon health detail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit signed-daemon-health sliced detail at 512 UTF-16 units while the Rust owner counts bytes, so 300 x "é" failed shape validation. truncateUtf8Bytes now serves runtime presence and both daemon-health sites, replacing truncateRuntimePresenceDetail. It makes the string well formed first, so a lone surrogate becomes U+FFFD instead of invalid UTF-8 in msgpack. The unsigned payload is extracted as unsignedDaemonHealthPayload so it can be tested without a socket. Co-Authored-By: Claude Sonnet 5 --- .../cultnet-ts/src/idunn-runtime-authority.ts | 5 +- .../cultnet-ts/src/runtime-presence-health.ts | 20 ++------ .../cultnet-ts/src/signed-daemon-health.ts | 32 +++++++++---- packages/cultnet-ts/src/utf8-bound.ts | 20 ++++++++ .../test/runtime-presence-health.test.ts | 24 +++++++--- .../test/signed-daemon-health.test.ts | 48 +++++++++++++++++++ 6 files changed, 114 insertions(+), 35 deletions(-) create mode 100644 packages/cultnet-ts/src/utf8-bound.ts create mode 100644 packages/cultnet-ts/test/signed-daemon-health.test.ts diff --git a/packages/cultnet-ts/src/idunn-runtime-authority.ts b/packages/cultnet-ts/src/idunn-runtime-authority.ts index d96c892b..5ea30fff 100644 --- a/packages/cultnet-ts/src/idunn-runtime-authority.ts +++ b/packages/cultnet-ts/src/idunn-runtime-authority.ts @@ -6,14 +6,15 @@ import { decode, encode } from "@msgpack/msgpack"; import { GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, GAMECULT_RUNTIME_PRESENCE_IDENTITY_NAME, + RUNTIME_PRESENCE_DETAIL_MAX_BYTES, IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME, runtimePresenceActivationSigningMessage, runtimePresenceProofPayload, - truncateRuntimePresenceDetail, runtimePresenceProviderSigningMessage, encodeRuntimePresenceHealth, type RuntimePresenceHealth, } from "./runtime-presence-health"; +import { truncateUtf8Bytes } from "./utf8-bound"; import { encodeCultNetMessageForWire, parseCultNetMessage, type CultNetRawDocumentRecord, type CultNetSnapshotRequestMessage } from "./contracts"; import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp"; import type { CultNetRudpPacket } from "./rudp"; @@ -242,7 +243,7 @@ export function createIdunnRuntimePresencePublisher( const signed = signIdunnRuntimePresence(options.authority, { capabilities: options.capabilities, state, - detail: truncateRuntimePresenceDetail(detail), + detail: truncateUtf8Bytes(detail, RUNTIME_PRESENCE_DETAIL_MAX_BYTES), writeLeaseSha256, publisherSequence: sequence, observedAtUnixMillis: Date.now(), diff --git a/packages/cultnet-ts/src/runtime-presence-health.ts b/packages/cultnet-ts/src/runtime-presence-health.ts index 4cdccd1e..7f38fa6f 100644 --- a/packages/cultnet-ts/src/runtime-presence-health.ts +++ b/packages/cultnet-ts/src/runtime-presence-health.ts @@ -20,6 +20,8 @@ import { encode } from "@msgpack/msgpack"; +import { truncateUtf8Bytes } from "./utf8-bound"; + export const GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA = "gamecult.runtime_presence_health.v2"; /** Purpose for the stable provider-health signature over the proof payload. */ @@ -174,22 +176,6 @@ function presenceTuple( /** The Rust owner (`cultnet-rs`) bounds presence detail by UTF-8 bytes, not UTF-16 units. */ export const RUNTIME_PRESENCE_DETAIL_MAX_BYTES = 512; -/** - * Longest prefix of `detail` within the UTF-8 byte limit, cut on a code point - * boundary. The single rule for both signing and validation: a detail is valid - * exactly when this returns it unchanged. - */ -export function truncateRuntimePresenceDetail(detail: string): string { - let bytes = 0; - let end = 0; - for (const char of detail) { - bytes += Buffer.byteLength(char, "utf8"); - if (bytes > RUNTIME_PRESENCE_DETAIL_MAX_BYTES) break; - end += char.length; - } - return detail.slice(0, end); -} - /** * Reject statements the contract forbids, before they are signed. * @@ -204,7 +190,7 @@ export function validateRuntimePresence(presence: RuntimePresenceHealth): void { if (presence.observedAtUnixMillis <= 0 || !Number.isSafeInteger(presence.observedAtUnixMillis)) { throw new Error("runtime presence observation time must be a positive integer"); } - if (truncateRuntimePresenceDetail(presence.detail) !== presence.detail || /\p{Cc}/u.test(presence.detail)) { + if (truncateUtf8Bytes(presence.detail, RUNTIME_PRESENCE_DETAIL_MAX_BYTES) !== presence.detail || /\p{Cc}/u.test(presence.detail)) { throw new Error("runtime presence detail is too long or carries control characters"); } if (presence.state === "warming" && presence.writeLeaseSha256 !== null) { diff --git a/packages/cultnet-ts/src/signed-daemon-health.ts b/packages/cultnet-ts/src/signed-daemon-health.ts index d4f0f0ce..db800181 100644 --- a/packages/cultnet-ts/src/signed-daemon-health.ts +++ b/packages/cultnet-ts/src/signed-daemon-health.ts @@ -19,6 +19,10 @@ import { encode } from "@msgpack/msgpack"; import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp"; import type { CultNetRudpPacket } from "./rudp"; import { encodeCultNetMessageForWire } from "./contracts"; +import { truncateUtf8Bytes } from "./utf8-bound"; + +/** The Rust owner (`cultnet-rs`) bounds daemon health detail by UTF-8 bytes. */ +export const DAEMON_HEALTH_DETAIL_MAX_BYTES = 512; export const CULTNET_RUDP_PROTOCOL_ID = "cultnet.transport.rudp.v0"; @@ -120,15 +124,7 @@ export async function publishSignedDaemonHealth( const observedAt = health.observedAt || new Date().toISOString(); const signed = publisher.privateKey ? signedDaemonHealthPayload(publisher, health, observedAt) : null; - const payload = signed?.payload || encode([ - publisher.daemonId, - health.state, - String(health.detail || "").slice(0, 512), - observedAt, - publisher.healthContract, - "daemon-published", - CULTNET_RUDP_PROTOCOL_ID, - ]); + const payload = signed?.payload || unsignedDaemonHealthPayload(publisher, health, observedAt); const message = { schemaVersion: "cultnet.document_put_raw.v0", @@ -165,6 +161,22 @@ export async function publishSignedDaemonHealth( } } +export function unsignedDaemonHealthPayload( + publisher: SignedDaemonHealthPublisher, + health: DaemonHealth, + observedAt: string, +): Uint8Array { + return encode([ + publisher.daemonId, + health.state, + truncateUtf8Bytes(String(health.detail || ""), DAEMON_HEALTH_DETAIL_MAX_BYTES), + observedAt, + publisher.healthContract, + "daemon-published", + CULTNET_RUDP_PROTOCOL_ID, + ]); +} + export function signedDaemonHealthPayload( publisher: SignedDaemonHealthPublisher, health: DaemonHealth, @@ -185,7 +197,7 @@ export function signedDaemonHealthPayload( publisher.healthContract, publisher.sourceRuntimeId, health.state, - String(health.detail || "").slice(0, 512), + truncateUtf8Bytes(String(health.detail || ""), DAEMON_HEALTH_DETAIL_MAX_BYTES), publisher.signerIdentityId, publisher.publisherIncarnationId, publisher.publisherSequence, diff --git a/packages/cultnet-ts/src/utf8-bound.ts b/packages/cultnet-ts/src/utf8-bound.ts new file mode 100644 index 00000000..d21ee849 --- /dev/null +++ b/packages/cultnet-ts/src/utf8-bound.ts @@ -0,0 +1,20 @@ +/** + * Longest prefix of `value` whose UTF-8 encoding fits in `maxBytes`, cut on a + * code point boundary. Rust owners (`cultnet-rs`) bound strings by UTF-8 bytes, + * not UTF-16 units, so every TypeScript publisher bounds through this one path. + * + * Lone surrogates are replaced with U+FFFD first: they have no UTF-8 encoding, + * and a msgpack writer would otherwise emit invalid bytes that Rust refuses. + * A value is therefore in bounds exactly when this returns it unchanged. + */ +export function truncateUtf8Bytes(value: string, maxBytes: number): string { + const wellFormed = (value as string & { toWellFormed(): string }).toWellFormed(); + let bytes = 0; + let end = 0; + for (const char of wellFormed) { + bytes += Buffer.byteLength(char, "utf8"); + if (bytes > maxBytes) break; + end += char.length; + } + return wellFormed.slice(0, end); +} diff --git a/packages/cultnet-ts/test/runtime-presence-health.test.ts b/packages/cultnet-ts/test/runtime-presence-health.test.ts index 5a4de05f..2dc4a845 100644 --- a/packages/cultnet-ts/test/runtime-presence-health.test.ts +++ b/packages/cultnet-ts/test/runtime-presence-health.test.ts @@ -18,10 +18,10 @@ import { RUNTIME_PRESENCE_FIELD_COUNT, encodeRuntimePresenceHealth, runtimePresenceProofPayload, - truncateRuntimePresenceDetail, validateRuntimePresence, type RuntimePresenceHealth, } from "../src/runtime-presence-health"; +import { truncateUtf8Bytes } from "../src/utf8-bound"; // Read from the source tree, not a copy beside the compiled test: the vectors // are generated output and must have exactly one home. @@ -127,27 +127,39 @@ const utf8Bytes = (text: string) => Buffer.byteLength(text, "utf8"); const isValidUtf8 = (text: string) => !Buffer.from(text, "utf8").toString("utf8").includes("\uFFFD") && !text.includes("\uFFFD"); test("presence detail is truncated to 512 UTF-8 bytes, not UTF-16 units", () => { - const truncated = truncateRuntimePresenceDetail("é".repeat(300)); + const truncated = truncateUtf8Bytes("é".repeat(300), 512); assert.ok(utf8Bytes(truncated) <= 512); assert.equal(truncated, "é".repeat(256)); assert.ok(isValidUtf8(truncated)); }); test("presence detail drops a 4-byte character straddling the boundary whole", () => { - const truncated = truncateRuntimePresenceDetail("a".repeat(510) + "😀"); + const truncated = truncateUtf8Bytes("a".repeat(510) + "😀", 512); assert.equal(truncated, "a".repeat(510)); assert.ok(isValidUtf8(truncated)); - assert.equal(truncateRuntimePresenceDetail("a".repeat(508) + "😀"), "a".repeat(508) + "😀"); + assert.equal(truncateUtf8Bytes("a".repeat(508) + "😀", 512), "a".repeat(508) + "😀"); }); test("presence detail of exactly 512 ASCII bytes passes unchanged and 513 is cut", () => { const exact = "a".repeat(512); - assert.equal(truncateRuntimePresenceDetail(exact), exact); + assert.equal(truncateUtf8Bytes(exact, 512), exact); assert.doesNotThrow(() => validateRuntimePresence({ ...referencePresence(), detail: exact })); - assert.equal(truncateRuntimePresenceDetail(exact + "a"), exact); + assert.equal(truncateUtf8Bytes(exact + "a", 512), exact); assert.throws(() => validateRuntimePresence({ ...referencePresence(), detail: exact + "a" }), /too long/); }); test("validation refuses a detail that is short in UTF-16 units but over 512 UTF-8 bytes", () => { assert.throws(() => validateRuntimePresence({ ...referencePresence(), detail: "é".repeat(300) }), /too long/); }); + +test("a lone high surrogate at the end becomes U+FFFD and the result is valid UTF-8", () => { + const truncated = truncateUtf8Bytes("abc\uD83D", 512); + assert.equal(truncated, "abc\uFFFD"); + assert.equal(Buffer.from(truncated, "utf8").toString("utf8"), truncated); +}); + +test("a lone low surrogate in the middle becomes U+FFFD and the result is valid UTF-8", () => { + const truncated = truncateUtf8Bytes("ab\uDE00cd", 512); + assert.equal(truncated, "ab\uFFFDcd"); + assert.equal(Buffer.from(truncated, "utf8").toString("utf8"), truncated); +}); diff --git a/packages/cultnet-ts/test/signed-daemon-health.test.ts b/packages/cultnet-ts/test/signed-daemon-health.test.ts new file mode 100644 index 00000000..1c433b04 --- /dev/null +++ b/packages/cultnet-ts/test/signed-daemon-health.test.ts @@ -0,0 +1,48 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import crypto from "node:crypto"; +import { decode } from "@msgpack/msgpack"; + +import { + signedDaemonHealthPayload, + unsignedDaemonHealthPayload, + type SignedDaemonHealthPublisher, +} from "../src/signed-daemon-health"; + +function publisher(): SignedDaemonHealthPublisher { + return { + daemonId: "heimdall", + endpoint: { host: "127.0.0.1", port: 1 }, + healthContract: "contract", + publisherIncarnationId: "incarnation", + publisherSequence: 0, + sourceRuntimeId: "runtime", + contract: { + connectionId: 1, + signedSchemaId: "signed.schema", + unsignedSchemaId: "unsigned.schema", + } as SignedDaemonHealthPublisher["contract"], + privateKey: crypto.generateKeyPairSync("ed25519").privateKey, + signerIdentityId: "signer", + }; +} + +const observedAt = "2026-01-01T00:00:00.000Z"; +const detail = "é".repeat(300); + +function assertBounded(text: unknown) { + assert.equal(typeof text, "string"); + const bytes = Buffer.from(text as string, "utf8"); + assert.ok(bytes.length <= 512, `detail is ${bytes.length} bytes`); + assert.equal(bytes.toString("utf8"), text); +} + +test("unsigned daemon health detail is bounded by UTF-8 bytes", () => { + const fields = decode(unsignedDaemonHealthPayload(publisher(), { state: "ok", detail }, observedAt)) as unknown[]; + assertBounded(fields[2]); +}); + +test("signed daemon health detail is bounded by UTF-8 bytes", () => { + const { statement } = signedDaemonHealthPayload(publisher(), { state: "ok", detail }, observedAt); + assertBounded(statement[5]); +}); From 0791e1b7d0c1a97691819203a41c8f33a2e53015 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 01:21:18 +0200 Subject: [PATCH 14/14] Raise the TypeScript packages' Node floor to 20 The UTF-8 detail bound calls String.prototype.toWellFormed, which Node 20 introduced. Node 18 reached end of life in April 2025, and CI runs Node 24. All four TypeScript packages move together so the family keeps one floor. Co-Authored-By: Claude Opus 5.5 --- packages/cultcache-ts/package.json | 2 +- packages/cultmesh-browser/package.json | 2 +- packages/cultmesh-ts/package.json | 2 +- packages/cultnet-ts/package.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/cultcache-ts/package.json b/packages/cultcache-ts/package.json index 67f8d5ed..c708bfc9 100644 --- a/packages/cultcache-ts/package.json +++ b/packages/cultcache-ts/package.json @@ -45,7 +45,7 @@ }, "homepage": "https://github.com/GameCult/CultLib/tree/main/packages/cultcache-ts#readme", "engines": { - "node": ">=18" + "node": ">=20" }, "dependencies": { "@msgpack/msgpack": "^3.1.3", diff --git a/packages/cultmesh-browser/package.json b/packages/cultmesh-browser/package.json index c49062b0..186ab630 100644 --- a/packages/cultmesh-browser/package.json +++ b/packages/cultmesh-browser/package.json @@ -37,7 +37,7 @@ "directory": "packages/cultmesh-browser" }, "engines": { - "node": ">=18" + "node": ">=20" }, "dependencies": { "@msgpack/msgpack": "^3.1.3", diff --git a/packages/cultmesh-ts/package.json b/packages/cultmesh-ts/package.json index 65a32110..4d59133a 100644 --- a/packages/cultmesh-ts/package.json +++ b/packages/cultmesh-ts/package.json @@ -40,7 +40,7 @@ }, "homepage": "https://github.com/GameCult/CultLib/tree/main/packages/cultmesh-ts#readme", "engines": { - "node": ">=18" + "node": ">=20" }, "dependencies": { "@msgpack/msgpack": "^3.1.2", diff --git a/packages/cultnet-ts/package.json b/packages/cultnet-ts/package.json index d34278f5..f33b8f83 100644 --- a/packages/cultnet-ts/package.json +++ b/packages/cultnet-ts/package.json @@ -53,7 +53,7 @@ }, "homepage": "https://github.com/GameCult/CultLib/tree/main/packages/cultnet-ts#readme", "engines": { - "node": ">=18" + "node": ">=20" }, "dependencies": { "@msgpack/msgpack": "^3.1.3",