@verax-ai/body 0.4.7 → 0.5.0

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/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 {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verax-ai/body",
3
- "version": "0.4.7",
3
+ "version": "0.5.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "engines": {
@@ -26,8 +26,8 @@
26
26
  "@cedulon/cose": "0.13.1",
27
27
  "@cedulon/effect-extract": "0.13.1",
28
28
  "@modelcontextprotocol/sdk": "^1.30.0",
29
- "@verax-ai/inventory": "^0.4.7",
30
- "@verax-ai/proxy": "^0.4.7",
29
+ "@verax-ai/inventory": "^0.5.0",
30
+ "@verax-ai/proxy": "^0.5.0",
31
31
  "jose": "^6.2.11"
32
32
  },
33
33
  "description": "VERAX body: an MCP server that decides, records and proves what an agent did.",