/** Genuine coordinator -> configured signed source -> actual registry SQL. * Disposable runner only. Live executor fencing remains an explicit synthetic * fixture; this is not proof of production quiescence or writer enrollment. */ import assert from "node:assert/strict" import { createHash, generateKeyPairSync, randomUUID, sign } from "node:crypto" import { mkdtemp, rm, stat } from "node:fs/promises" import { resolve, dirname, sep } from "node:path" import { assertOwnedBandwidthSql } from "./bandwidth-admission-process.sql-helper.js" import { canonicalBandwidthNodeValue } from "./bandwidth-node-bootstrap.js" import { createBandwidthOperatorEnrollmentPrerequisite, bandwidthOperatorEnrollmentGrantSchema } from "./bandwidth-operator-enrollment.js" import { createBandwidthOperatorRegistry, BandwidthOperatorRegistryUnknown } from "./bandwidth-operator-registry.js" import { BandwidthExternalNodeRegistryUnknown } from "./bandwidth-external-node-registry.js" import { bandwidthPeerRefKey, type BandwidthPeerRef } from "./bandwidth-peer-reference.js" import type { createOwnedExternalRegistryHarness } from "./bandwidth-external-node-registry.sql-helper.js" type Harness = Awaited> type Signed = Awaited> export async function acceptOwnedOperatorRegistry(f: Harness, signed: Signed): Promise { assertOwnedBandwidthSql(); assert.equal(process.env.MMAPP_OWN_BANDWIDTH_EXTERNAL_REGISTRY, "true") const state = resolve(process.env.MCP_STATE_DIR!), folder = await mkdtemp(resolve(state, "operator-registry-")) assert.equal(dirname(folder), state) const trustKeyFile = resolve(folder, "trust.pem"), grantFile = resolve(folder, "grant.json") const { publicKey, privateKey } = generateKeyPairSync("ed25519"), sha = (bytes: Buffer | string) => createHash("sha256").update(bytes).digest("hex") await import("node:fs/promises").then(({ writeFile }) => writeFile(trustKeyFile, publicKey.export({ type: "spki", format: "pem" }), { flag: "wx", mode: 0o600 })) const checks: string[] = [], claims = { "system-id": "OWNED-COORDINATOR-SHARED", "software-id": "OWNED-COORDINATOR-SOFTWARE" } let allowedPeer: BandwidthPeerRef | undefined, credentialReads = 0, quiescent = true, opens = 0, removeAfterCommit = false let diagnostic: { began: number; queryCount: number; commitAttempted: boolean; commitAcknowledged: boolean } | undefined const coordinator = createBandwidthOperatorEnrollmentPrerequisite({ trustKeyFile, trustKeySha256: sha(publicKey.export({ type: "spki", format: "der" })), grantFile, ...f.root }, { async read(peer, scope) { assert(allowedPeer); assert.equal(bandwidthPeerRefKey(peer), bandwidthPeerRefKey(allowedPeer)); assert(quiescent) credentialReads++; return f.readPeerSnapshot(peer, scope) }, }, { async verify(grant, scope) { assert(quiescent); scope.signal?.throwIfAborted(); assert(Date.now() < scope.deadlineAt) assert.equal(grant.executorInventorySha256, sha("OWNED SYNTHETIC QUIESCENCE FIXTURE")); assert.equal(grant.operatorId, "owned-coordinator-operator") } }) const registry = createBandwidthOperatorRegistry({ coordinator, source: { async open(scope, guard) { opens++; const session = await signed.node.open(scope, guard) return { ...session, connection: { release: session.connection.release.bind(session.connection), async query(text, values, options) { if (diagnostic) { diagnostic.queryCount++; if (text === "COMMIT") diagnostic.commitAttempted = true } const result = await session.connection.query(text, values, options) if (diagnostic && text === "COMMIT" && "command" in result && result.command === "COMMIT") diagnostic.commitAcknowledged = true if (text === "COMMIT" && removeAfterCommit) { removeAfterCommit = false; await rm(grantFile) } return result } } } } } }) async function publish(peer: BandwidthPeerRef, vector = claims) { const source = await f.readPeerSnapshot(peer, f.scope()); assert(source) const now = Date.now(), grant = bandwidthOperatorEnrollmentGrantSchema.parse({ format: "mmapp-bandwidth-operator-enrollment-v1", grantId: randomUUID(), operatorId: "owned-coordinator-operator", ...f.root, executorInventorySha256: sha("OWNED SYNTHETIC QUIESCENCE FIXTURE"), executorsStoppedAt: now - 1000, issuedAt: now - 1000, expiresAt: now + 120000, peerRef: peer, sourceProof: source.sourceProof, authorityGeneration: source.authorityGeneration, routingEndpointEpoch: source.endpoint.routingEndpointEpoch, claims: Object.entries(vector).map(([kind, value]) => ({ kind, value })) }) const bytes = Buffer.from(canonicalBandwidthNodeValue(grant)) const { writeFile } = await import("node:fs/promises") await writeFile(grantFile, JSON.stringify({ format: "mmapp-bandwidth-operator-enrollment-envelope-v1", payload: bytes.toString("base64url"), signature: sign(null, bytes, privateKey).toString("base64url") }), { mode: 0o600 }) allowedPeer = peer } const coreTables = ["bandwidth_attempts", "bandwidth_node_occupancy", "bandwidth_attempt_events"], beforeCore = await f.digest(coreTables) try { const sourceId = await f.managedEndpoint(claims), peer: BandwidthPeerRef = { kind: "server", serverId: sourceId } await publish(peer); const managed = await registry.register(await coordinator.acquire(peer, f.scope()), f.scope()) const enrollmentId = f.externalEndpoint(claims), external: BandwidthPeerRef = { kind: "external", enrollmentId } await publish(external); const destination = await registry.register(await coordinator.acquire(external, f.scope()), f.scope()) assert.equal(managed.canonicalNodeId, destination.canonicalNodeId) assert.equal((await f.owner.query("SELECT node_id::text FROM mmapp_control.bandwidth_node_aliases WHERE server_id=$1", [sourceId])).rows[0].node_id, managed.canonicalNodeId) assert.equal((await f.owner.query("SELECT node_id::text FROM mmapp_control.bandwidth_external_node_aliases WHERE enrollment_id=$1", [enrollmentId])).rows[0].node_id, managed.canonicalNodeId) checks.push("genuine Ed25519 operator grant, native managed/external license GET and branded coordinator compose with configured signed-v2 node source and actual PostgreSQL registry factories to reuse one canonical node") await publish(external); const revoked = await coordinator.acquire(external, f.scope()), beforeReads = credentialReads, beforeOpens = opens await rm(grantFile); await assert.rejects(registry.register(revoked, f.scope())); assert.equal(credentialReads, beforeReads); assert.equal(opens, beforeOpens) await publish(external); const fenced = await coordinator.acquire(external, f.scope()), fenceReads = credentialReads quiescent = false; await assert.rejects(registry.register(fenced, f.scope())); assert.equal(credentialReads, fenceReads); assert.equal(opens, beforeOpens); quiescent = true checks.push("deleted signed grant and revoked independent quiescence fixture reject genuine registration before credentials, source lease or registry SQL") const lostClaims = { "system-id": "OWNED-COORDINATOR-COMMIT", "software-id": "OWNED-COORDINATOR-COMMIT-SOFTWARE" }, lostId = f.externalEndpoint(lostClaims), lostPeer: BandwidthPeerRef = { kind: "external", enrollmentId: lostId } await publish(lostPeer, lostClaims); const lost = await coordinator.acquire(lostPeer, f.scope()); removeAfterCommit = true diagnostic = { began: Date.now(), queryCount: 0, commitAttempted: false, commitAcknowledged: false } await assert.rejects(registry.register(lost, f.scope()), error => { const accepted = (error instanceof BandwidthOperatorRegistryUnknown || error instanceof BandwidthExternalNodeRegistryUnknown) && error.automaticReplay === false if (removeAfterCommit || !accepted) console.error("Owned operator registry local diagnostic:", JSON.stringify({ elapsedMs: Date.now() - diagnostic!.began, queryCount: diagnostic!.queryCount, commitAttempted: diagnostic!.commitAttempted, commitAcknowledged: diagnostic!.commitAcknowledged, code: error && typeof error === "object" && "code" in error ? String(error.code).slice(0, 100) : "unclassified" })) return accepted }) assert.equal(removeAfterCommit, false, "The genuine source acknowledged COMMIT before the fixture revoked the grant") await assert.rejects(stat(grantFile), { code: "ENOENT" }) assert.equal(Number((await f.owner.query("SELECT count(*) AS n FROM mmapp_control.bandwidth_external_node_events WHERE enrollment_id=$1", [lostId])).rows[0].n), 1) const afterCommitReads = credentialReads; await assert.rejects(registry.register(lost, f.scope())); assert.equal(credentialReads, afterCommitReads) checks.push("real coordinator registration COMMIT persists exactly one enrollment before grant-file revocation: bridge returns Unknown with no automatic replay, and original capability cannot reopen credentials") assert.equal(await f.digest(coreTables), beforeCore) return checks } finally { coordinator.close() assert.equal(dirname(folder), state); assert(folder.startsWith(state + sep)) await rm(folder, { recursive: true, force: true }) } }