@verax-ai/body 0.4.8 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/install.js CHANGED
@@ -1927,6 +1927,7 @@ export function windowsPowerShellScripts() {
1927
1927
  { id: "sddl-batch", script: windowsSddlBatchArgv(["C:\\ProgramData\\Verax"]).at(-1) ?? "" },
1928
1928
  { id: "acl-owner", script: aclOwnerCommand("C:\\ProgramData\\Verax") },
1929
1929
  { id: "directory-owner-sid", script: directoryOwnerSidCommand("C:\\ProgramData\\Verax") },
1930
+ { id: "file-owner", script: fileOwnerSidCommand("C:\\ProgramData\\Verax\\state\\keys\\record.private.pem") },
1930
1931
  { id: "service-sid", script: WINDOWS_SERVICE_SID_COMMAND },
1931
1932
  { id: "profile-image-path", script: profileImagePathCommand("S-1-5-21-1001") },
1932
1933
  { id: "account-create", script: powerShellScript(windowsAccountBody(true, temp)) },
@@ -4852,6 +4853,51 @@ function invokingSid(exec) {
4852
4853
  }
4853
4854
  return sid;
4854
4855
  }
4856
+ const OWNER_DENIED = "VERAX-OWNER-DENIED";
4857
+ /**
4858
+ * Prints the file's owner, then this token's user and the groups it holds
4859
+ * enabled. `WindowsIdentity.Groups` leaves out a group held for deny only,
4860
+ * which is what Administrators is in a session that is not elevated.
4861
+ */
4862
+ function fileOwnerSidCommand(file) {
4863
+ const literal = file.replaceAll("'", "''");
4864
+ return psPrefixed(["Microsoft.PowerShell.Security"], [
4865
+ `try { $owner = (Get-Acl -LiteralPath '${literal}' -ErrorAction Stop).GetOwner([System.Security.Principal.SecurityIdentifier]).Value }`,
4866
+ `catch [System.UnauthorizedAccessException] { '${OWNER_DENIED}'; exit 0 }`,
4867
+ "$id = [System.Security.Principal.WindowsIdentity]::GetCurrent()",
4868
+ "'owner ' + $owner",
4869
+ "'user ' + $id.User.Value",
4870
+ "$id.Groups | ForEach-Object { 'group ' + $_.Value }",
4871
+ ].join("\n"));
4872
+ }
4873
+ /**
4874
+ * Whether this process holds the owner's rights over `file`: the owner is its
4875
+ * user, or a group its token holds enabled. An owner reads the security
4876
+ * descriptor even under an entry that denies it the file, so a caller who is
4877
+ * refused the descriptor is not the owner. Output that names no owner or no
4878
+ * user is "unknown", never "other".
4879
+ */
4880
+ export function windowsFileOwner(file, exec = defaultExec) {
4881
+ let ran;
4882
+ try {
4883
+ ran = exec(toolArgv("powershell", ["-NoProfile", "-NonInteractive", "-Command", fileOwnerSidCommand(file)], "win32"));
4884
+ }
4885
+ catch {
4886
+ return "unknown";
4887
+ }
4888
+ if ((ran.status ?? 1) !== 0)
4889
+ return "unknown";
4890
+ const lines = `${ran.stdout ?? ""}`.split(/\r?\n/).map((line) => line.trim());
4891
+ if (lines.includes(OWNER_DENIED))
4892
+ return "other";
4893
+ const sidOf = (kind, line) => new RegExp(`^${kind} (S-1-[0-9-]+)$`, "i").exec(line)?.[1]?.toUpperCase();
4894
+ const owner = lines.map((line) => sidOf("owner", line)).find((sid) => sid !== undefined);
4895
+ const user = lines.map((line) => sidOf("user", line)).find((sid) => sid !== undefined);
4896
+ if (!owner || !user)
4897
+ return "unknown";
4898
+ const held = new Set([user, ...lines.map((line) => sidOf("group", line)).filter((sid) => sid !== undefined)]);
4899
+ return held.has(owner) ? "self" : "other";
4900
+ }
4855
4901
  /** The SID `whoami /user` names for this process. */
4856
4902
  export function windowsInvokingSid(exec = defaultExec) {
4857
4903
  return invokingSid(exec);
@@ -15,7 +15,7 @@ export function persistPolicySnapshot(stateDir, hash, document) {
15
15
  const path = snapshotPath(stateDir, hash);
16
16
  if (existsSync(path)) {
17
17
  const existing = JSON.parse(readFileSync(path, "utf8"));
18
- if (loadPolicy(existing).hash !== hash) {
18
+ if (loadPolicy(existing, { unknownKeys: "ignore" }).hash !== hash) {
19
19
  throw new Error(`policy-snapshot-mismatch:${hash}`);
20
20
  }
21
21
  return;
@@ -32,7 +32,7 @@ export function readPolicySnapshots(stateDir, hashes) {
32
32
  continue;
33
33
  try {
34
34
  const document = JSON.parse(readFileSync(path, "utf8"));
35
- if (loadPolicy(document).hash !== hash)
35
+ if (loadPolicy(document, { unknownKeys: "ignore" }).hash !== hash)
36
36
  continue;
37
37
  out[hash] = document;
38
38
  }
@@ -2,22 +2,12 @@ import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { loadApprovalsFromDir, loadDecisionRefsFromDir, loadEffectsFromDir, loadPolicy, parseCardCsv, parseChannelJsonl, reconcile, } from "@verax-ai/proxy";
4
4
  const SNAPSHOT_NAME = /^[0-9a-f]{64}\.json$/;
5
- function descriptorsFromDoc(doc) {
5
+ // The descriptors come from the parsed policy, never from the stored document: a snapshot is
6
+ // read with unknown keys ignored, and a block the hash does not cover must not decide a match.
7
+ function descriptorsOf(policy) {
6
8
  const out = {};
7
- if (!Array.isArray(doc.rules))
8
- return out;
9
- for (const rule of doc.rules) {
10
- const spend = rule.spend;
11
- if (!spend || !Array.isArray(spend.payees) || !Array.isArray(spend.descriptors))
12
- continue;
13
- const stamps = spend.descriptors.filter((d) => typeof d === "string" && d !== "");
14
- if (stamps.length === 0)
15
- continue;
16
- for (const payee of spend.payees) {
17
- if (typeof payee === "string" && payee !== "")
18
- out[payee] = stamps;
19
- }
20
- }
9
+ for (const [payee, stamps] of Object.entries(policy.descriptorsByPayee ?? {}))
10
+ out[payee] = [...stamps];
21
11
  return out;
22
12
  }
23
13
  function loadDescriptorsFromDir(stateDir) {
@@ -47,10 +37,10 @@ function loadDescriptorsFromDir(stateDir) {
47
37
  const chosen = candidates[candidates.length - 1];
48
38
  const hash = chosen.name.slice(0, 64);
49
39
  try {
50
- const doc = JSON.parse(readFileSync(join(dir, chosen.name), "utf8"));
51
- if (loadPolicy(doc).hash !== hash)
40
+ const policy = loadPolicy(JSON.parse(readFileSync(join(dir, chosen.name), "utf8")), { unknownKeys: "ignore" });
41
+ if (policy.hash !== hash)
52
42
  return { descriptorsByPayee: {}, policyHash: null };
53
- return { descriptorsByPayee: descriptorsFromDoc(doc), policyHash: hash };
43
+ return { descriptorsByPayee: descriptorsOf(policy), policyHash: hash };
54
44
  }
55
45
  catch {
56
46
  return { descriptorsByPayee: {}, policyHash: null };
package/dist/server.js CHANGED
@@ -6,6 +6,7 @@ import { Server as McpServer } from "@modelcontextprotocol/sdk/server/index.js";
6
6
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
7
7
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
8
8
  import { decisionRecordHash } from "@cedulon/core";
9
+ import { bodyVersion } from "./body-version.js";
9
10
  import { isLoopbackHost } from "./config.js";
10
11
  import { approvalChallenge, gateApprovalSignature } from "./approval-signature.js";
11
12
  import { readCredentials } from "./operator-credentials.js";
@@ -289,6 +290,19 @@ function send(res, status, body, headers) {
289
290
  });
290
291
  res.end(text);
291
292
  }
293
+ /**
294
+ * The body has answered on a response the MCP transport also holds. The
295
+ * transport still writes its own answer when the handler throws; a second
296
+ * `writeHead` would throw, and its adapter would print the stack and destroy
297
+ * the socket under the answer already sent. After this, those writes go
298
+ * nowhere. The adapter's own already-sent header is read from the Response
299
+ * the transport builds, which the body does not hold.
300
+ */
301
+ function closeToTransport(res) {
302
+ res.writeHead = (() => res);
303
+ res.write = (() => true);
304
+ res.end = (() => res);
305
+ }
292
306
  /**
293
307
  * Republishes a child's own `tools/list` entry under its prefixed name. The
294
308
  * description is the child's; the sentence added here says what changes by
@@ -385,7 +399,7 @@ export async function listen(config) {
385
399
  }
386
400
  try {
387
401
  // This must precede syncControlRecords: those records pulse too.
388
- recordBodyStart(config.stateDir, services.ledger.startedAtMs);
402
+ recordBodyStart(config.stateDir, services.ledger.startedAtMs, signers.recordSigner);
389
403
  }
390
404
  catch (err) {
391
405
  services.ledger.close();
@@ -425,6 +439,7 @@ export async function listen(config) {
425
439
  const res = responseSlot.getStore();
426
440
  if (res && !res.headersSent) {
427
441
  send(res, 507, { error: "insufficient-storage" });
442
+ closeToTransport(res);
428
443
  }
429
444
  throw err;
430
445
  }
@@ -883,7 +898,7 @@ export async function listen(config) {
883
898
  res.end(JSON.stringify({ error: "method-not-allowed" }));
884
899
  return;
885
900
  }
886
- const mcp = new McpServer({ name: "verax-body", version: "0.0.0" }, { capabilities: { tools: {} } });
901
+ const mcp = new McpServer({ name: "verax-body", version: bodyVersion() }, { capabilities: { tools: {} } });
887
902
  attachHandlers(mcp);
888
903
  const transport = new StreamableHTTPServerTransport({
889
904
  sessionIdGenerator: undefined,
package/dist/unlock.d.ts CHANGED
@@ -3,6 +3,9 @@ export type LockRecord = {
3
3
  pid: number;
4
4
  startedAt: number;
5
5
  port?: number;
6
+ bootId?: string;
7
+ token?: string;
8
+ beatMs?: number;
6
9
  };
7
10
  /** A lock from before the body recorded its port has no `port`. That is still a lock. */
8
11
  export declare function readLockFile(path: string): LockRecord | null;
package/dist/unlock.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { appendFileSync, existsSync, readFileSync, unlinkSync } from "node:fs";
2
2
  import { userInfo } from "node:os";
3
3
  import { join } from "node:path";
4
+ import { lockBeatOf, lockState } from "@verax-ai/proxy";
4
5
  export function pidAlive(pid) {
5
6
  if (!Number.isInteger(pid) || pid <= 0)
6
7
  return false;
@@ -16,12 +17,19 @@ export function pidAlive(pid) {
16
17
  export function readLockFile(path) {
17
18
  try {
18
19
  const raw = JSON.parse(readFileSync(path, "utf8"));
19
- if (typeof raw.pid !== "number" || typeof raw.startedAt !== "number")
20
+ if (typeof raw.pid !== "number" || typeof raw.startedAt !== "number" || !Number.isFinite(raw.startedAt))
20
21
  return null;
21
22
  const record = { pid: raw.pid, startedAt: raw.startedAt };
22
23
  if (typeof raw.port === "number" && Number.isInteger(raw.port) && raw.port > 0 && raw.port < 65536) {
23
24
  record.port = raw.port;
24
25
  }
26
+ if (typeof raw.bootId === "string" && raw.bootId !== "")
27
+ record.bootId = raw.bootId;
28
+ if (typeof raw.token === "string")
29
+ record.token = raw.token;
30
+ const beatMs = lockBeatOf(raw.beatMs);
31
+ if (beatMs !== undefined)
32
+ record.beatMs = beatMs;
25
33
  return record;
26
34
  }
27
35
  catch {
@@ -52,15 +60,30 @@ export function runUnlock(stateDir, writeErr = (s) => process.stderr.write(s), o
52
60
  return 1;
53
61
  }
54
62
  const existing = readLockFile(lockPath);
63
+ let forcedQuiet = false;
55
64
  if (!existing) {
56
65
  if (!options.force) {
57
66
  writeErr("lock-unreadable\n");
58
67
  return 1;
59
68
  }
60
69
  }
61
- else if (pidAlive(existing.pid)) {
62
- writeErr(`still-running:${existing.pid}\n`);
63
- return 1;
70
+ else {
71
+ // A lock that beats is watched, so a body in another container that shares this pid is seen.
72
+ const state = lockState(lockPath, existing);
73
+ if (state === "gone") {
74
+ writeErr("no-lock\n");
75
+ return 1;
76
+ }
77
+ // A still lock under a live pid: a frozen body, or a dead one whose pid another
78
+ // process now has. Only the operator can say which, so it takes --force and a record.
79
+ forcedQuiet = state === "quiet" && options.force === true;
80
+ if (state === "held" || (state === "quiet" && !forcedQuiet)) {
81
+ writeErr(`still-running:${existing.pid}\n`);
82
+ if (state === "quiet") {
83
+ writeErr(`lock-not-beating: pid ${existing.pid} is alive but the lock has not moved; if no body is running, run verax unlock --force\n`);
84
+ }
85
+ return 1;
86
+ }
64
87
  }
65
88
  const operator = operatorName();
66
89
  const base = existing
@@ -68,6 +91,7 @@ export function runUnlock(stateDir, writeErr = (s) => process.stderr.write(s), o
68
91
  removedPid: existing.pid,
69
92
  startedAt: existing.startedAt,
70
93
  operator,
94
+ ...(forcedQuiet ? { reason: "not-beating" } : {}),
71
95
  }
72
96
  : {
73
97
  removedPid: null,
@@ -25,7 +25,7 @@ import { readStartSummary, renderStarts } from "./heartbeat.js";
25
25
  export const EX_VERIFY_FAILED = 1;
26
26
  function usage() {
27
27
  return [
28
- "usage: verax verify <stateDir> [--key <public.pem>] [--effect-key <public.pem>] [--witness-key <public.pem>] [--checkpoint-key <public.pem>] [--anchor-key <public.pem>] [--operator-credentials <file>] [--json]",
28
+ "usage: verax verify <stateDir> [--key <public.pem>] [--effect-key <public.pem>] [--witness-key <public.pem>] [--checkpoint-key <public.pem>] [--anchor-key <public.pem> [--require-anchored [--anchor-grace-ms <n>]]] [--require-signed-starts] [--operator-credentials <file>] [--json]",
29
29
  "",
30
30
  " <stateDir> the directory holding decisions.jsonl and effects.jsonl",
31
31
  " --key <file> verify decision records against a public key you hold,",
@@ -57,6 +57,23 @@ function usage() {
57
57
  " checkpoint-anchors.jsonl under this service key. A",
58
58
  " receipt names no key of its own, so without this flag",
59
59
  " the receipts are counted and not checked.",
60
+ " --require-anchored",
61
+ " every checkpoint whose window ended more than the",
62
+ " grace ago must have a receipt that verifies under",
63
+ " --anchor-key; one without is checkpoint-not-anchored.",
64
+ " A receipt deleted from the directory is named instead",
65
+ " of passing. Needs --anchor-key.",
66
+ " --anchor-grace-ms <n>",
67
+ " the grace for --require-anchored, in milliseconds",
68
+ " (default 600000, ten minutes).",
69
+ " --require-signed-starts",
70
+ " every row of starts.jsonl must be a signed start row.",
71
+ " An unsigned row is start-row-unsigned, a line that",
72
+ " cannot be read is start-row-unreadable, and a ledger",
73
+ " with no start row is start-rows-missing. For a ledger",
74
+ " you know was written by a body that signs its starts:",
75
+ " a signed row with its signature removed otherwise",
76
+ " reads as one written before signing.",
60
77
  " --operator-credentials <file>",
61
78
  " verify HTTP approval signatures against this operator",
62
79
  " credential file, instead of operator-credentials.json",
@@ -228,6 +245,33 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
228
245
  if (!anchorKey.ok)
229
246
  return EX_VERIFY_FAILED;
230
247
  const anchorPublicKeyPem = anchorKey.pem;
248
+ const requireAt = args.indexOf("--require-anchored");
249
+ const requireAnchored = requireAt !== -1;
250
+ if (requireAnchored)
251
+ args.splice(requireAt, 1);
252
+ let anchorGraceMs;
253
+ const graceAt = args.indexOf("--anchor-grace-ms");
254
+ if (graceAt !== -1) {
255
+ const raw = args[graceAt + 1] ?? "";
256
+ if (!/^[0-9]+$/.test(raw) || !Number.isSafeInteger(Number(raw))) {
257
+ out("verify: --anchor-grace-ms needs a whole number of milliseconds");
258
+ return EX_VERIFY_FAILED;
259
+ }
260
+ anchorGraceMs = Number(raw);
261
+ args.splice(graceAt, 2);
262
+ if (!requireAnchored) {
263
+ out("verify: --anchor-grace-ms is read only with --require-anchored");
264
+ return EX_VERIFY_FAILED;
265
+ }
266
+ }
267
+ if (requireAnchored && !anchorPublicKeyPem) {
268
+ out("verify: --require-anchored needs --anchor-key: a receipt is checked only under a key you supply");
269
+ return EX_VERIFY_FAILED;
270
+ }
271
+ const signedStartsAt = args.indexOf("--require-signed-starts");
272
+ const requireSignedStarts = signedStartsAt !== -1;
273
+ if (requireSignedStarts)
274
+ args.splice(signedStartsAt, 1);
231
275
  let credentialsFile;
232
276
  const credentialsAt = args.indexOf("--operator-credentials");
233
277
  if (credentialsAt !== -1) {
@@ -250,7 +294,20 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
250
294
  args.splice(credentialsAt, 2);
251
295
  credentialsFile = path;
252
296
  }
253
- const dir = args.find((a) => !a.startsWith("-"));
297
+ // Every flag this command knows has been taken out of args by now. What is left is one
298
+ // directory. A flag it does not know is refused, not dropped: `--require-anchord` used to
299
+ // print VERIFIED over a checkpoint with no receipt.
300
+ const rest = args.filter((a) => a !== "--json");
301
+ const unknown = rest.find((a) => a.startsWith("-"));
302
+ if (unknown !== undefined) {
303
+ out(`verify: unknown option ${unknown}`);
304
+ return EX_VERIFY_FAILED;
305
+ }
306
+ if (rest.length > 1) {
307
+ out(`verify: one ledger directory at a time, got ${rest.length}`);
308
+ return EX_VERIFY_FAILED;
309
+ }
310
+ const dir = rest[0];
254
311
  if (!dir) {
255
312
  out(usage());
256
313
  return EX_VERIFY_FAILED;
@@ -268,6 +325,8 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
268
325
  ...(witnessPublicKeyPem ? { witnessPublicKeyPem } : {}),
269
326
  ...(checkpointPublicKeyPem ? { checkpointPublicKeyPem } : {}),
270
327
  ...(anchorPublicKeyPem ? { anchorPublicKeyPem } : {}),
328
+ ...(requireAnchored ? { requireAnchored } : {}),
329
+ ...(anchorGraceMs !== undefined ? { anchorGraceMs } : {}),
271
330
  });
272
331
  }
273
332
  catch (err) {
@@ -298,7 +357,9 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
298
357
  anchors: { line: "anchors: not checked", receipts: 0, verified: 0, checked: false },
299
358
  problems: [problem],
300
359
  };
301
- const starts = readStartSummary(dir);
360
+ const starts = readStartSummary(dir, publicKeyPem ?? null, publicKeyPem ? "pinned" : "none", {
361
+ requireSigned: requireSignedStarts,
362
+ });
302
363
  const failedReport = { ...failed, approvalSignatures: APPROVAL_NOT_CHECKED, controlSignatures: CONTROL_NOT_CHECKED, starts };
303
364
  out(json ? JSON.stringify(failedReport, null, 2) : renderVerify(failed, APPROVAL_NOT_CHECKED, CONTROL_NOT_CHECKED, starts));
304
365
  return EX_VERIFY_FAILED;
@@ -335,7 +396,15 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
335
396
  problems: [...result.problems, `control signatures: ${control.signedFailed} did not verify`],
336
397
  };
337
398
  }
338
- const reported = { ...result, approvalSignatures: approval, controlSignatures: control, starts: readStartSummary(dir) };
399
+ // Start rows are signed by the record key: the pinned one, else the one the records carry.
400
+ const startKeyPem = publicKeyPem ?? result.trust.publicKeyPem ?? null;
401
+ const starts = readStartSummary(dir, startKeyPem, publicKeyPem ? "pinned" : "in-ledger", {
402
+ requireSigned: requireSignedStarts,
403
+ });
404
+ if (starts.problems.length > 0) {
405
+ result = { ...result, ok: false, problems: [...result.problems, ...starts.problems] };
406
+ }
407
+ const reported = { ...result, approvalSignatures: approval, controlSignatures: control, starts };
339
408
  out(json ? JSON.stringify(reported, null, 2) : renderVerify(reported, approval, control, reported.starts));
340
409
  return reported.ok ? 0 : EX_VERIFY_FAILED;
341
410
  }
package/dist/wiring.js CHANGED
@@ -34,6 +34,11 @@ export function createBodyServices(opts) {
34
34
  }
35
35
  extraNames.push(tool.name);
36
36
  }
37
+ // The policy is read before the ledger opens: opening takes the ledger lock,
38
+ // and a start the policy stops must not leave that lock for the next one.
39
+ const policyText = readFileSync(opts.policyFile, "utf8");
40
+ const policyDocument = JSON.parse(policyText);
41
+ const policy = loadPolicy(policyText);
37
42
  const ledger = new FileLedger(opts.stateDir);
38
43
  ledger.remoteWitness = (row, resultHash) => requestWitnessSign(opts.stateDir, row, resultHash);
39
44
  ledger.onPieceClose = async (window) => {
@@ -43,10 +48,13 @@ export function createBodyServices(opts) {
43
48
  endMs: window.endMs,
44
49
  });
45
50
  };
46
- const policyText = readFileSync(opts.policyFile, "utf8");
47
- const policyDocument = JSON.parse(policyText);
48
- const policy = loadPolicy(policyText);
49
- persistPolicySnapshot(opts.stateDir, policy.hash, policyDocument);
51
+ try {
52
+ persistPolicySnapshot(opts.stateDir, policy.hash, policyDocument);
53
+ }
54
+ catch (err) {
55
+ ledger.close();
56
+ throw err;
57
+ }
50
58
  const now = opts.now ?? (() => Date.now());
51
59
  const nonce = opts.nonce ?? (() => crypto.randomUUID());
52
60
  const registry = new Map();
package/dist/witness.d.ts CHANGED
@@ -7,7 +7,34 @@ export type WitnessListen = {
7
7
  token: string;
8
8
  publicKeyPem: string;
9
9
  startedAt: number;
10
+ /** The Transparency Service this witness registers each checkpoint with, or absent. */
11
+ anchorService?: string;
10
12
  };
13
+ /** Where `verax witness` sends each checkpoint it signs, read once at start. */
14
+ export type WitnessAnchor = {
15
+ serviceName: string;
16
+ serviceKey: string | null;
17
+ };
18
+ /**
19
+ * `VERAX_ANCHOR_SERVICE` names the service (https; http only on loopback) and
20
+ * `VERAX_ANCHOR_SERVICE_KEY` a file holding its public key. Neither set is no
21
+ * anchoring. A value that is set but unusable is an error, so a witness the
22
+ * operator meant to anchor does not start without anchoring.
23
+ */
24
+ export declare function witnessAnchorFromEnv(env?: NodeJS.ProcessEnv): {
25
+ ok: true;
26
+ anchor: WitnessAnchor | null;
27
+ } | {
28
+ ok: false;
29
+ reason: string;
30
+ };
31
+ /**
32
+ * Registers every checkpoint in `stateDir` not yet anchored at the service,
33
+ * so a failure is retried with the next checkpoint. A failure is a
34
+ * `witness-status.jsonl` row and nothing else: the checkpoint is already
35
+ * written and the body is not waiting for this.
36
+ */
37
+ export declare function anchorPendingCheckpoints(stateDir: string, anchor: WitnessAnchor, fetchImpl?: typeof fetch): Promise<void>;
11
38
  type EffectRowWire = {
12
39
  ref: string;
13
40
  effectHash: string;
@@ -29,5 +56,10 @@ export type CheckpointWindow = {
29
56
  };
30
57
  export declare function requestWitnessCheckpoint(stateDir: string, window: CheckpointWindow): Promise<SignedCheckpoint | null>;
31
58
  export declare function requestWitnessSign(stateDir: string, row: EffectRowWire, resultHash: string | undefined): Promise<Pick<LedgerEffect, "receipt" | "attestation" | "witnessClass"> | null>;
59
+ /**
60
+ * One registration run at a time: two checkpoints in quick succession must
61
+ * not send the same pending hash twice.
62
+ */
63
+ export declare function anchorInTurn(run: () => Promise<void>, onFailure: () => void): () => void;
32
64
  export declare function runWitness(stateDir: string): Promise<void>;
33
65
  export {};
package/dist/witness.js CHANGED
@@ -1,4 +1,4 @@
1
- import { randomBytes, generateKeyPairSync } from "node:crypto";
1
+ import { createPublicKey, randomBytes, generateKeyPairSync } from "node:crypto";
2
2
  import { appendFileSync, existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs";
3
3
  import { createServer } from "node:http";
4
4
  import { join } from "node:path";
@@ -7,10 +7,93 @@ import { buildCheckpointClaims, checkpointHash, signCheckpoint, totalsFromDecisi
7
7
  import { canonical, decisionRecordHash } from "@cedulon/core";
8
8
  import { coseFromHex, decodeCoseSign1, verifyCoseSign1 } from "@cedulon/cose";
9
9
  import { verifyEffectExtract } from "@cedulon/effect-extract";
10
- import { checkpointsPath, listPieceFiles, signEffectAttestation } from "@verax-ai/proxy";
10
+ import { appendAnchor, checkpointsPath, listPieceFiles, signEffectAttestation } from "@verax-ai/proxy";
11
+ import { pendingAnchors, registerCheckpoint, serviceNameOf, serviceUrl } from "./anchor-cli.js";
11
12
  import { assertEd25519PublicKey } from "./keys.js";
13
+ import { lockHolderAlive } from "@verax-ai/proxy";
12
14
  import { pidAlive } from "./unlock.js";
13
15
  const WITNESS_CLASS = "same-org";
16
+ /**
17
+ * `VERAX_ANCHOR_SERVICE` names the service (https; http only on loopback) and
18
+ * `VERAX_ANCHOR_SERVICE_KEY` a file holding its public key. Neither set is no
19
+ * anchoring. A value that is set but unusable is an error, so a witness the
20
+ * operator meant to anchor does not start without anchoring.
21
+ */
22
+ export function witnessAnchorFromEnv(env = process.env) {
23
+ const raw = env.VERAX_ANCHOR_SERVICE?.trim() ?? "";
24
+ const keyPath = env.VERAX_ANCHOR_SERVICE_KEY?.trim() ?? "";
25
+ if (raw === "") {
26
+ if (keyPath !== "")
27
+ return { ok: false, reason: "VERAX_ANCHOR_SERVICE_KEY is set without VERAX_ANCHOR_SERVICE" };
28
+ return { ok: true, anchor: null };
29
+ }
30
+ const url = serviceUrl(raw);
31
+ if (!url) {
32
+ return {
33
+ ok: false,
34
+ reason: "VERAX_ANCHOR_SERVICE must be an https URL with no credentials, query or fragment (http only on loopback)",
35
+ };
36
+ }
37
+ let serviceKey = null;
38
+ if (keyPath !== "") {
39
+ try {
40
+ serviceKey = readFileSync(keyPath, "utf8");
41
+ }
42
+ catch {
43
+ return { ok: false, reason: `cannot read VERAX_ANCHOR_SERVICE_KEY file ${keyPath}` };
44
+ }
45
+ if (serviceKey.trim() === "")
46
+ return { ok: false, reason: `VERAX_ANCHOR_SERVICE_KEY file ${keyPath} is empty` };
47
+ // A file that holds something else would start a witness that refuses
48
+ // every receipt it is sent.
49
+ try {
50
+ createPublicKey(serviceKey);
51
+ }
52
+ catch {
53
+ return { ok: false, reason: `VERAX_ANCHOR_SERVICE_KEY file ${keyPath} is not a public key` };
54
+ }
55
+ }
56
+ return { ok: true, anchor: { serviceName: serviceNameOf(url), serviceKey } };
57
+ }
58
+ /**
59
+ * Registers every checkpoint in `stateDir` not yet anchored at the service,
60
+ * so a failure is retried with the next checkpoint. A failure is a
61
+ * `witness-status.jsonl` row and nothing else: the checkpoint is already
62
+ * written and the body is not waiting for this.
63
+ */
64
+ export async function anchorPendingCheckpoints(stateDir, anchor, fetchImpl = fetch) {
65
+ const { pending, problems } = pendingAnchors(stateDir, anchor.serviceName);
66
+ if (problems.length > 0) {
67
+ appendStatus(stateDir, {
68
+ atMs: Date.now(),
69
+ result: "anchor-failed",
70
+ service: anchor.serviceName,
71
+ reason: "unreadable",
72
+ });
73
+ return;
74
+ }
75
+ for (const hash of pending) {
76
+ const got = await registerCheckpoint(anchor.serviceName, hash, anchor.serviceKey, fetchImpl);
77
+ if (!got.ok) {
78
+ appendStatus(stateDir, {
79
+ atMs: Date.now(),
80
+ result: "anchor-failed",
81
+ service: anchor.serviceName,
82
+ checkpointHash: hash,
83
+ reason: got.reason,
84
+ });
85
+ continue;
86
+ }
87
+ appendAnchor(stateDir, got.row);
88
+ appendStatus(stateDir, {
89
+ atMs: Date.now(),
90
+ result: "anchored",
91
+ service: anchor.serviceName,
92
+ checkpointHash: hash,
93
+ receipt: got.checked ? "verified" : "unchecked",
94
+ });
95
+ }
96
+ }
14
97
  function listenPath(stateDir) {
15
98
  return join(stateDir, "witness.listen.json");
16
99
  }
@@ -61,6 +144,7 @@ export function readWitnessListen(stateDir) {
61
144
  token: raw.token,
62
145
  publicKeyPem: raw.publicKeyPem,
63
146
  startedAt: typeof raw.startedAt === "number" ? raw.startedAt : 0,
147
+ ...(typeof raw.anchorService === "string" && raw.anchorService !== "" ? { anchorService: raw.anchorService } : {}),
64
148
  };
65
149
  }
66
150
  catch {
@@ -354,13 +438,67 @@ export async function requestWitnessSign(stateDir, row, resultHash) {
354
438
  return null;
355
439
  }
356
440
  }
441
+ /**
442
+ * One registration run at a time: two checkpoints in quick succession must
443
+ * not send the same pending hash twice.
444
+ */
445
+ export function anchorInTurn(run, onFailure) {
446
+ let running = false;
447
+ let again = false;
448
+ const drain = async () => {
449
+ do {
450
+ again = false;
451
+ try {
452
+ await run();
453
+ }
454
+ catch {
455
+ // Recording the failure can fail for the reason the run did (a full
456
+ // disk). Nothing may leave this function as a rejection: an unhandled
457
+ // one ends the witness process.
458
+ try {
459
+ onFailure();
460
+ }
461
+ catch {
462
+ /* the status file was the only place to say so */
463
+ }
464
+ }
465
+ } while (again);
466
+ running = false;
467
+ };
468
+ // A run retries everything still pending, so checkpoints that arrive while
469
+ // one is in flight need one more run after it, not one each.
470
+ return () => {
471
+ if (running) {
472
+ again = true;
473
+ return;
474
+ }
475
+ running = true;
476
+ void drain();
477
+ };
478
+ }
357
479
  export async function runWitness(stateDir) {
358
480
  mkdirSync(stateDir, { recursive: true, mode: 0o700 });
359
481
  const existing = readWitnessListen(stateDir);
360
- if (existing && pidAlive(existing.pid)) {
482
+ // A restarted container runs the witness under the same pid; a listen file
483
+ // written before this process started is not a running witness.
484
+ if (existing && lockHolderAlive({ pid: existing.pid, startedAt: existing.startedAt })) {
361
485
  process.stderr.write(`witness-already-running:${existing.pid}\n`);
362
486
  process.exit(1);
363
487
  }
488
+ const anchorConfig = witnessAnchorFromEnv();
489
+ if (!anchorConfig.ok) {
490
+ process.stderr.write(`witness-anchor-config: ${anchorConfig.reason}\n`);
491
+ process.exit(64);
492
+ }
493
+ const anchor = anchorConfig.anchor;
494
+ const anchorAfterCheckpoint = anchor
495
+ ? anchorInTurn(() => anchorPendingCheckpoints(stateDir, anchor), () => appendStatus(stateDir, {
496
+ atMs: Date.now(),
497
+ result: "anchor-failed",
498
+ service: anchor.serviceName,
499
+ reason: "exception",
500
+ }))
501
+ : () => undefined;
364
502
  const keys = loadOrCreateWitnessKeys(stateDir);
365
503
  const token = randomBytes(16).toString("hex");
366
504
  const server = createServer((req, res) => {
@@ -403,6 +541,8 @@ export async function runWitness(stateDir) {
403
541
  }
404
542
  const signed = signWindowCheckpoint(stateDir, { epoch: body.epoch, startMs: body.startMs, endMs: body.endMs }, keys);
405
543
  send(res, 200, signed);
544
+ // After the answer: the body waits 800 ms for it, a service up to 15 s.
545
+ anchorAfterCheckpoint();
406
546
  return;
407
547
  }
408
548
  send(res, 404, { error: "not-found" });
@@ -433,10 +573,13 @@ export async function runWitness(stateDir) {
433
573
  token,
434
574
  publicKeyPem: keys.publicKeyPem,
435
575
  startedAt: Date.now(),
576
+ ...(anchor ? { anchorService: anchor.serviceName } : {}),
436
577
  };
437
578
  writeFileAtomic(listenPath(stateDir), `${JSON.stringify(listen)}\n`);
438
579
  process.stderr.write(`witness-pid:${process.pid}\n`);
439
580
  process.stderr.write(`witness-port:${addr.port}\n`);
581
+ if (anchor)
582
+ process.stderr.write(`witness-anchor:${anchor.serviceName}\n`);
440
583
  await new Promise((resolve) => {
441
584
  const shutdown = () => {
442
585
  try {