@verax-ai/body 0.4.2 → 0.4.3

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.
@@ -0,0 +1,2 @@
1
+ export declare const EX_ANCHOR_FAILED = 1;
2
+ export declare function runAnchor(argv: readonly string[], out?: (s: string) => void, fetchImpl?: typeof fetch, now?: () => number): Promise<number>;
@@ -0,0 +1,203 @@
1
+ /**
2
+ * `verax anchor <stateDir> --service <url>` registers each checkpoint this
3
+ * ledger holds with a SCITT Transparency Service that someone else runs, and
4
+ * keeps the COSE Receipt it returns in `checkpoint-anchors.jsonl`.
5
+ *
6
+ * Only the checkpoint hash leaves the machine: `POST <service>/register` with
7
+ * `{"capsule_id": <SHA-256 of the checkpoint's COSE octets>}`. The window, the
8
+ * counts and the head stay here. A checkpoint already anchored at that service
9
+ * is not sent again.
10
+ *
11
+ * `--service-key <pem>` checks each receipt as it arrives and refuses to keep
12
+ * one that does not verify. Without it the receipt is kept and `verax verify
13
+ * --anchor-key` is where it is first checked.
14
+ */
15
+ import { readFileSync } from "node:fs";
16
+ import { anchorEntryHash, appendAnchor, readAnchors, readCheckpointFile, verifyReceipt, } from "@verax-ai/proxy";
17
+ import { checkpointHash } from "@cedulon/checkpoint";
18
+ export const EX_ANCHOR_FAILED = 1;
19
+ const EX_USAGE = 64;
20
+ function usage() {
21
+ return [
22
+ "usage: verax anchor <stateDir> --service <url> [--service-key <public.pem>] [--json]",
23
+ "",
24
+ " --service <url> the Transparency Service, for example https://witness.agentactioncapsule.org.",
25
+ " https only; http is accepted for a loopback address.",
26
+ " --service-key <file> the service's public key; each receipt must verify under it before it is kept",
27
+ " --json one JSON object per anchored checkpoint",
28
+ "",
29
+ "Sends the SHA-256 of each checkpoint not yet anchored at that service, and nothing else.",
30
+ ].join("\n");
31
+ }
32
+ function serviceUrl(raw) {
33
+ let url;
34
+ try {
35
+ url = new URL(raw);
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "")
41
+ return null;
42
+ const loopback = url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "[::1]";
43
+ if (url.protocol === "https:")
44
+ return url;
45
+ if (url.protocol === "http:" && loopback)
46
+ return url;
47
+ return null;
48
+ }
49
+ // A receipt is a few hundred bytes; the reader refuses CBOR over 64 KiB.
50
+ const MAX_ANSWER_BYTES = 256 * 1024;
51
+ const MAX_RECEIPT_BYTES = 64 * 1024;
52
+ const MAX_RECEIPT_B64 = Math.ceil(MAX_RECEIPT_BYTES / 3) * 4;
53
+ /** The body as text, refused once it passes MAX_ANSWER_BYTES rather than held in full. */
54
+ async function boundedText(res) {
55
+ const declared = Number(res.headers.get("content-length") ?? "0");
56
+ if (declared > MAX_ANSWER_BYTES)
57
+ throw new Error("answer too large");
58
+ if (!res.body)
59
+ return "";
60
+ const reader = res.body.getReader();
61
+ const chunks = [];
62
+ let size = 0;
63
+ for (;;) {
64
+ const { done, value } = await reader.read();
65
+ if (done)
66
+ break;
67
+ size += value.length;
68
+ if (size > MAX_ANSWER_BYTES) {
69
+ await reader.cancel();
70
+ throw new Error("answer too large");
71
+ }
72
+ chunks.push(value);
73
+ }
74
+ return Buffer.concat(chunks).toString("utf8");
75
+ }
76
+ export async function runAnchor(argv, out = (s) => process.stdout.write(`${s}\n`), fetchImpl = fetch, now = Date.now) {
77
+ const args = [...argv];
78
+ if (args.length === 0 || args.includes("--help") || args.includes("-h")) {
79
+ out(usage());
80
+ return args.length === 0 ? EX_USAGE : 0;
81
+ }
82
+ const json = args.includes("--json");
83
+ const take = (flag) => {
84
+ const at = args.indexOf(flag);
85
+ if (at === -1)
86
+ return undefined;
87
+ const value = args[at + 1];
88
+ if (!value || value.startsWith("-"))
89
+ return null;
90
+ args.splice(at, 2);
91
+ return value;
92
+ };
93
+ const rawService = take("--service");
94
+ if (!rawService) {
95
+ out("anchor: --service <url> is required");
96
+ return EX_USAGE;
97
+ }
98
+ const service = serviceUrl(rawService);
99
+ if (!service) {
100
+ out("anchor: --service must be an https URL with no credentials, query or fragment (http only on loopback)");
101
+ return EX_USAGE;
102
+ }
103
+ const keyPath = take("--service-key");
104
+ if (keyPath === null) {
105
+ out("anchor: --service-key needs a file path");
106
+ return EX_USAGE;
107
+ }
108
+ let serviceKey = null;
109
+ if (keyPath) {
110
+ try {
111
+ serviceKey = readFileSync(keyPath, "utf8");
112
+ }
113
+ catch {
114
+ out(`anchor: cannot read key file ${keyPath}`);
115
+ return EX_USAGE;
116
+ }
117
+ if (serviceKey.trim() === "") {
118
+ out(`anchor: key file ${keyPath} is empty`);
119
+ return EX_USAGE;
120
+ }
121
+ }
122
+ const dir = args.find((a) => !a.startsWith("-"));
123
+ if (!dir) {
124
+ out(usage());
125
+ return EX_USAGE;
126
+ }
127
+ const serviceName = service.origin + service.pathname.replace(/\/+$/, "");
128
+ const loaded = readCheckpointFile(dir);
129
+ if (loaded.problems.length > 0) {
130
+ for (const p of loaded.problems)
131
+ out(`anchor: ${p}`);
132
+ return EX_ANCHOR_FAILED;
133
+ }
134
+ const existing = readAnchors(dir);
135
+ if (existing.problems.length > 0) {
136
+ for (const p of existing.problems)
137
+ out(`anchor: ${p}`);
138
+ return EX_ANCHOR_FAILED;
139
+ }
140
+ const done = new Set(existing.rows.filter((r) => r.service === serviceName).map((r) => r.checkpointHash));
141
+ const pending = loaded.rows.map((row) => checkpointHash(row)).filter((hash) => !done.has(hash));
142
+ if (pending.length === 0) {
143
+ out(json ? JSON.stringify({ anchored: 0, service: serviceName }) : `nothing to anchor at ${serviceName}`);
144
+ return 0;
145
+ }
146
+ let failed = 0;
147
+ for (const hash of pending) {
148
+ const entryHash = anchorEntryHash(hash, "register");
149
+ let answer;
150
+ try {
151
+ const res = await fetchImpl(`${serviceName}/register`, {
152
+ method: "POST",
153
+ headers: { "content-type": "application/json", accept: "application/json" },
154
+ body: JSON.stringify({ capsule_id: hash }),
155
+ signal: AbortSignal.timeout(15_000),
156
+ redirect: "error",
157
+ });
158
+ if (!res.ok)
159
+ throw new Error(`HTTP ${res.status}`);
160
+ answer = JSON.parse(await boundedText(res));
161
+ }
162
+ catch (err) {
163
+ failed += 1;
164
+ out(`anchor: ${hash.slice(0, 12)} not registered: ${err instanceof Error ? err.message : String(err)}`);
165
+ continue;
166
+ }
167
+ const { receipt_b64, entry_hash, leaf_index, tree_size } = answer;
168
+ if (typeof receipt_b64 !== "string" ||
169
+ receipt_b64.length > MAX_RECEIPT_B64 ||
170
+ Buffer.from(receipt_b64, "base64").length > MAX_RECEIPT_BYTES ||
171
+ entry_hash !== entryHash ||
172
+ !Number.isSafeInteger(leaf_index) ||
173
+ !Number.isSafeInteger(tree_size)) {
174
+ failed += 1;
175
+ out(`anchor: ${hash.slice(0, 12)} the service answered with a receipt for another entry, or no receipt`);
176
+ continue;
177
+ }
178
+ if (serviceKey) {
179
+ const check = verifyReceipt(Buffer.from(receipt_b64, "base64"), Buffer.from(entryHash, "hex"), serviceKey);
180
+ if (!check.ok || check.treeSize !== tree_size || check.leafIndex !== leaf_index) {
181
+ failed += 1;
182
+ out(`anchor: ${hash.slice(0, 12)} receipt does not verify under --service-key; not kept`);
183
+ continue;
184
+ }
185
+ }
186
+ const row = {
187
+ v: 1,
188
+ checkpointHash: hash,
189
+ service: serviceName,
190
+ route: "register",
191
+ entryHash,
192
+ leafIndex: leaf_index,
193
+ treeSize: tree_size,
194
+ receiptB64: receipt_b64,
195
+ atMs: now(),
196
+ };
197
+ appendAnchor(dir, row);
198
+ out(json
199
+ ? JSON.stringify(row)
200
+ : `anchored ${hash.slice(0, 12)} at ${serviceName}: leaf ${row.leafIndex} of ${row.treeSize}${serviceKey ? ", receipt verified" : ", receipt not yet checked"}`);
201
+ }
202
+ return failed === 0 ? 0 : EX_ANCHOR_FAILED;
203
+ }
@@ -186,7 +186,10 @@ export async function verifyApprovalSignatures(stateDir, opts = {}) {
186
186
  const credentials = readCredentialsAt(pinned ? opts.credentialsFile : credentialsPath(stateDir));
187
187
  const trust = trustOf(pinned, credentials);
188
188
  const decisions = [];
189
- const approverByAllow = new Map();
189
+ // Every inputs row under a ref, by the hash of its inputs document. A ref can
190
+ // hold rows with no record (a crash, a retry, or a row appended by hand);
191
+ // only the row the allow's signed inputsHash names speaks for that allow.
192
+ const inputsByRef = new Map();
190
193
  for (const piece of listPieceFiles(stateDir)) {
191
194
  for (const line of readLines(piece.decisions)) {
192
195
  try {
@@ -199,9 +202,12 @@ export async function verifyApprovalSignatures(stateDir, opts = {}) {
199
202
  for (const line of readLines(piece.inputs)) {
200
203
  try {
201
204
  const row = JSON.parse(line);
202
- if (typeof row.ref !== "string" || !row.inputs?.approver)
205
+ if (typeof row.ref !== "string" || row.inputs === undefined)
203
206
  continue;
204
- approverByAllow.set(row.ref, row.inputs.approver);
207
+ const hash = createHash("sha256").update(canonical(row.inputs), "utf8").digest("hex");
208
+ const byHash = inputsByRef.get(row.ref) ?? new Map();
209
+ byHash.set(hash, row.inputs?.approver ?? null);
210
+ inputsByRef.set(row.ref, byHash);
205
211
  }
206
212
  catch {
207
213
  // Same as a decision line: skip, do not invent a failure from a torn line.
@@ -223,7 +229,10 @@ export async function verifyApprovalSignatures(stateDir, opts = {}) {
223
229
  continue;
224
230
  if (row.claims.decision !== "allow" || typeof row.claims.ref !== "string")
225
231
  continue;
226
- const approver = approverByAllow.get(row.claims.ref);
232
+ // No row hashes to the signed inputsHash: the ledger statement names that
233
+ // record, and no other row is read in its place.
234
+ const signedInputs = typeof row.claims.inputsHash === "string" ? row.claims.inputsHash : null;
235
+ const approver = signedInputs === null ? null : inputsByRef.get(row.claims.ref)?.get(signedInputs);
227
236
  if (!approver)
228
237
  continue;
229
238
  if (approver.signature === undefined) {
package/dist/cli.js CHANGED
@@ -11,6 +11,7 @@ import { clearCliCodeCheckPassed, defaultElevated, directoryAccess, doctorStateT
11
11
  import { runHalt, runResume } from "./halt.js";
12
12
  import { main } from "./main.js";
13
13
  import { runOperator } from "./operator-cli.js";
14
+ import { runAnchor } from "./anchor-cli.js";
14
15
  import { runReconcile } from "./reconcile-cli.js";
15
16
  import { runVerify } from "./verify-cli.js";
16
17
  import { runUnlock } from "./unlock.js";
@@ -49,6 +50,9 @@ Usage: verax <command> [options]
49
50
  reconcile <args> compare the ledger against a statement
50
51
  verify <stateDir> read a ledger back without a body: signatures, chain,
51
52
  effect binding, which key answered, and approval signatures
53
+ anchor <stateDir> --service <url>
54
+ register each checkpoint's hash with a transparency service
55
+ someone else runs and keep its receipt for verify --anchor-key
52
56
  witness <stateDir> run the witness alongside a body
53
57
  halt <stateDir> stop the body from allowing anything further
54
58
  resume <stateDir> lift a halt; who and when go to halt-history.jsonl
@@ -262,6 +266,9 @@ async function dispatchCli(argv, stdout, stderr, env) {
262
266
  if (argv[0] === "verify") {
263
267
  return runVerify(argv.slice(1), (s) => stdout.write(`${s}\n`));
264
268
  }
269
+ if (argv[0] === "anchor") {
270
+ return runAnchor(argv.slice(1), (s) => stdout.write(`${s}\n`));
271
+ }
265
272
  if (argv[0] === "desktop") {
266
273
  stderr.write("desktop-not-released: the desktop panel is not in this release\n");
267
274
  return 64;
@@ -20,7 +20,7 @@ import { directoryAccess, unreadableSentence } from "./install.js";
20
20
  export const EX_VERIFY_FAILED = 1;
21
21
  function usage() {
22
22
  return [
23
- "usage: verax verify <stateDir> [--key <public.pem>] [--effect-key <public.pem>] [--witness-key <public.pem>] [--checkpoint-key <public.pem>] [--operator-credentials <file>] [--json]",
23
+ "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]",
24
24
  "",
25
25
  " <stateDir> the directory holding decisions.jsonl and effects.jsonl",
26
26
  " --key <file> verify decision records against a public key you hold,",
@@ -43,6 +43,11 @@ function usage() {
43
43
  " verify every checkpoint row against a public key you",
44
44
  " hold, instead of one key taken from the checkpoint",
45
45
  " file. Same distinction as --key, for the witness.",
46
+ " --anchor-key <file>",
47
+ " check the transparency-service receipts in",
48
+ " checkpoint-anchors.jsonl under this service key. A",
49
+ " receipt names no key of its own, so without this flag",
50
+ " the receipts are counted and not checked.",
46
51
  " --operator-credentials <file>",
47
52
  " verify HTTP approval signatures against this operator",
48
53
  " credential file, instead of operator-credentials.json",
@@ -102,6 +107,7 @@ export function renderVerify(r, approval = APPROVAL_NOT_CHECKED) {
102
107
  lines.push(` ${r.checkpointTrust.note}`);
103
108
  lines.push(r.index.line);
104
109
  lines.push(r.effectCompleteness);
110
+ lines.push(r.inputs.line);
105
111
  if (r.tail.checkpoint) {
106
112
  const head = r.tail.checkpoint.chainHeadHash ?? "(no head hash)";
107
113
  const holds = r.tail.checkpoint.ledgerHoldsRecord === null
@@ -118,6 +124,7 @@ export function renderVerify(r, approval = APPROVAL_NOT_CHECKED) {
118
124
  lines.push(r.control.line);
119
125
  for (const warning of r.control.warnings)
120
126
  lines.push(`warning ${warning}`);
127
+ lines.push(r.anchors.line);
121
128
  lines.push(approval.line);
122
129
  lines.push(` ${approval.trustNote}`);
123
130
  if (r.problems.length > 0) {
@@ -182,6 +189,10 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
182
189
  if (!checkpointKey.ok)
183
190
  return EX_VERIFY_FAILED;
184
191
  checkpointPublicKeyPem = checkpointKey.pem;
192
+ const anchorKey = readKeyFlag("--anchor-key");
193
+ if (!anchorKey.ok)
194
+ return EX_VERIFY_FAILED;
195
+ const anchorPublicKeyPem = anchorKey.pem;
185
196
  let credentialsFile;
186
197
  const credentialsAt = args.indexOf("--operator-credentials");
187
198
  if (credentialsAt !== -1) {
@@ -220,6 +231,7 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
220
231
  ...(effectPublicKeyPem ? { effectPublicKeyPem } : {}),
221
232
  ...(witnessPublicKeyPem ? { witnessPublicKeyPem } : {}),
222
233
  ...(checkpointPublicKeyPem ? { checkpointPublicKeyPem } : {}),
234
+ ...(anchorPublicKeyPem ? { anchorPublicKeyPem } : {}),
223
235
  });
224
236
  }
225
237
  catch (err) {
@@ -245,6 +257,8 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
245
257
  checkpoint: null,
246
258
  },
247
259
  control: { line: "control: not checked", windows: 0, warnings: [] },
260
+ inputs: { line: "inputs: not checked", matched: 0, missing: 0, mismatched: 0 },
261
+ anchors: { line: "anchors: not checked", receipts: 0, verified: 0, checked: false },
248
262
  problems: [problem],
249
263
  };
250
264
  const failedReport = { ...failed, approvalSignatures: APPROVAL_NOT_CHECKED };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verax-ai/body",
3
- "version": "0.4.2",
3
+ "version": "0.4.3",
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.2",
30
- "@verax-ai/proxy": "^0.4.2",
29
+ "@verax-ai/inventory": "^0.4.3",
30
+ "@verax-ai/proxy": "^0.4.3",
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.",