@verax-ai/body 0.4.2 → 0.4.4

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
+ }
@@ -1,4 +1,5 @@
1
1
  import type { ApprovalSignature } from "@verax-ai/proxy";
2
+ import { type StoredCredential } from "./operator-credentials.ts";
2
3
  export declare function approvalChallenge(input: {
3
4
  ref: string;
4
5
  requestHash: string;
@@ -13,6 +14,18 @@ export type ApprovalGate = {
13
14
  error: "approve-signature-required" | "approve-signature-invalid" | "unknown-credential" | "cloned-authenticator" | "passkey-closed";
14
15
  reason?: string;
15
16
  };
17
+ export type PostedAssertion = {
18
+ id: string;
19
+ rawId: string;
20
+ type: "public-key";
21
+ response: {
22
+ clientDataJSON: string;
23
+ authenticatorData: string;
24
+ signature: string;
25
+ };
26
+ clientExtensionResults: Record<string, unknown>;
27
+ };
28
+ export declare function asAssertion(value: unknown): PostedAssertion | null;
16
29
  /**
17
30
  * When an operator is registered, the approval body must carry that
18
31
  * operator's assertion for this defer. No registered operator keeps today's
@@ -36,6 +49,10 @@ export type ApprovalSignatureReport = {
36
49
  trustSource: "pinned" | "in-ledger" | "none";
37
50
  trustNote: string;
38
51
  };
52
+ export declare function readLines(path: string): string[];
53
+ export declare function originInClientData(clientDataJSON: string): string | null;
54
+ export declare function assertionMatches(sig: Pick<ApprovalSignature, "clientDataJSON" | "authenticatorData" | "signature" | "rpId">, publicKey: string, challenge: string): boolean;
55
+ export declare function trustOf(pinned: boolean, credentials: StoredCredential[]): Pick<ApprovalSignatureReport, "trustSource" | "trustNote">;
39
56
  /**
40
57
  * Recount operator approvals without a body. A signature is checked against
41
58
  * the operator public key and the challenge rebuilt from the defer record.
@@ -20,7 +20,7 @@ export function approvalChallenge(input) {
20
20
  });
21
21
  return createHash("sha256").update(json).digest("base64url");
22
22
  }
23
- function asAssertion(value) {
23
+ export function asAssertion(value) {
24
24
  if (!value || typeof value !== "object")
25
25
  return null;
26
26
  const row = value;
@@ -94,7 +94,7 @@ export async function gateApprovalSignature(opts) {
94
94
  const PINNED_NOTE = "verified against a key the reader supplied, not one taken from these files";
95
95
  const FILE_NOTE = "verified against the key carried in operator-credentials.json: this shows the files are internally consistent, not that the key was ever trusted. Pin a key you hold to check that.";
96
96
  const NO_KEY_NOTE = "no operator key was found in these files";
97
- function readLines(path) {
97
+ export function readLines(path) {
98
98
  try {
99
99
  return readFileSync(path, "utf8")
100
100
  .split("\n")
@@ -126,7 +126,7 @@ function signatureOf(value) {
126
126
  return null;
127
127
  return row;
128
128
  }
129
- function originInClientData(clientDataJSON) {
129
+ export function originInClientData(clientDataJSON) {
130
130
  try {
131
131
  const parsed = JSON.parse(Buffer.from(clientDataJSON, "base64url").toString("utf8"));
132
132
  if (!parsed || typeof parsed !== "object")
@@ -146,7 +146,7 @@ function originOnSignature(value) {
146
146
  return null;
147
147
  return originInClientData(clientDataJSON);
148
148
  }
149
- function assertionMatches(sig, publicKey, challenge) {
149
+ export function assertionMatches(sig, publicKey, challenge) {
150
150
  // The origin stays in clientDataJSON and is reported on the verify line.
151
151
  // This re-read does not judge it: the allow-list is not in these files, so
152
152
  // handing the claimed origin back is not an allow-list decision. rpIdHash
@@ -168,7 +168,7 @@ function assertionMatches(sig, publicKey, challenge) {
168
168
  publicKeyCose: publicKey,
169
169
  }).ok;
170
170
  }
171
- function trustOf(pinned, credentials) {
171
+ export function trustOf(pinned, credentials) {
172
172
  if (pinned)
173
173
  return { trustSource: "pinned", trustNote: PINNED_NOTE };
174
174
  if (credentials.length > 0)
@@ -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;
@@ -0,0 +1,52 @@
1
+ import type { ControlSignature } from "@verax-ai/proxy";
2
+ export type ControlAction = "halt" | "resume";
3
+ export declare function controlChallenge(input: {
4
+ action: ControlAction;
5
+ prev: string | null;
6
+ }): string;
7
+ /** The challenge for the next line, from the history as it is now. */
8
+ export declare function nextControlChallenge(stateDir: string, action: ControlAction): {
9
+ challenge: string;
10
+ prev: string | null;
11
+ };
12
+ export type ControlGate = {
13
+ ok: true;
14
+ signature?: ControlSignature;
15
+ } | {
16
+ ok: false;
17
+ status: 403 | 503;
18
+ error: "resume-signature-required" | "control-signature-invalid" | "unknown-credential" | "cloned-authenticator" | "passkey-closed";
19
+ reason?: string;
20
+ };
21
+ /**
22
+ * Synchronous on purpose: the server reads the tail here and appends the line
23
+ * right after, with nothing awaited in between, so no other request of this
24
+ * body can append a line the assertion was not made for.
25
+ */
26
+ export declare function gateControlSignature(opts: {
27
+ stateDir: string;
28
+ env: NodeJS.ProcessEnv;
29
+ action: ControlAction;
30
+ assertion: unknown;
31
+ }): ControlGate;
32
+ export type ControlSignatureReport = {
33
+ ok: boolean;
34
+ signedVerified: number;
35
+ signedFailed: number;
36
+ unsignedHttp: number;
37
+ cli: number;
38
+ file: number;
39
+ line: string;
40
+ trustSource: "pinned" | "in-ledger" | "none";
41
+ trustNote: string;
42
+ };
43
+ /**
44
+ * Recount halt and resume signatures without a body. A signature must name,
45
+ * as `prev`, the line hash of the control record copied from the history line
46
+ * just before its own (`null` for line 0), and verify under the operator key
47
+ * over the challenge rebuilt from that and the record's subject. A challenge
48
+ * counts once. The authenticator counter is not consulted.
49
+ */
50
+ export declare function verifyControlSignatures(stateDir: string, opts?: {
51
+ credentialsFile?: string;
52
+ }): Promise<ControlSignatureReport>;
@@ -0,0 +1,184 @@
1
+ /**
2
+ * A halt or resume over HTTP can carry the operator's passkey assertion. The
3
+ * challenge names the action and the newest line of `halt-history.jsonl`, so
4
+ * one assertion fits the one line appended after that tail and no later one.
5
+ * The body rebuilds it from the file when the request arrives; `verax verify`
6
+ * rebuilds it from the previous control record. Nothing is remembered.
7
+ *
8
+ * A resume lets every held call through again, so once an operator is
9
+ * registered a resume over HTTP must be signed. A halt is never made to wait
10
+ * for a passkey: it may carry one, and one that is offered must verify.
11
+ */
12
+ import { createHash } from "node:crypto";
13
+ import { canonical } from "@cedulon/core";
14
+ import { listPieceFiles } from "@verax-ai/proxy";
15
+ import { asAssertion, assertionMatches, readLines, trustOf } from "./approval-signature.js";
16
+ import { historyTail } from "./halt.js";
17
+ import { credentialsPath, findCredential, hasRegisteredOperator, readCredentialsAt, updateCounter, } from "./operator-credentials.js";
18
+ import { readRpConfig } from "./rp-config.js";
19
+ import { verifyAssertion } from "./webauthn-verify.js";
20
+ export function controlChallenge(input) {
21
+ const json = canonical({ v: 1, purpose: `verax.${input.action}`, prev: input.prev });
22
+ return createHash("sha256").update(json).digest("base64url");
23
+ }
24
+ /** The challenge for the next line, from the history as it is now. */
25
+ export function nextControlChallenge(stateDir, action) {
26
+ const prev = historyTail(stateDir);
27
+ return { challenge: controlChallenge({ action, prev }), prev };
28
+ }
29
+ /**
30
+ * Synchronous on purpose: the server reads the tail here and appends the line
31
+ * right after, with nothing awaited in between, so no other request of this
32
+ * body can append a line the assertion was not made for.
33
+ */
34
+ export function gateControlSignature(opts) {
35
+ if (opts.assertion === undefined || opts.assertion === null) {
36
+ if (opts.action === "resume" && hasRegisteredOperator(opts.stateDir)) {
37
+ return { ok: false, status: 403, error: "resume-signature-required" };
38
+ }
39
+ return { ok: true };
40
+ }
41
+ const rp = readRpConfig(opts.env);
42
+ if (!rp.ok)
43
+ return { ok: false, status: 503, error: "passkey-closed", reason: rp.reason };
44
+ const assertion = asAssertion(opts.assertion);
45
+ if (!assertion)
46
+ return { ok: false, status: 403, error: "control-signature-invalid" };
47
+ const stored = findCredential(opts.stateDir, assertion.id);
48
+ if (!stored)
49
+ return { ok: false, status: 403, error: "unknown-credential" };
50
+ const { challenge, prev } = nextControlChallenge(opts.stateDir, opts.action);
51
+ const verified = verifyAssertion({
52
+ response: assertion,
53
+ expectedChallenge: challenge,
54
+ expectedOrigins: rp.config.origins,
55
+ rpId: rp.config.rpID,
56
+ publicKeyCose: stored.publicKey,
57
+ });
58
+ if (!verified.ok)
59
+ return { ok: false, status: 403, error: "control-signature-invalid" };
60
+ if (!updateCounter(opts.stateDir, stored.id, verified.counter)) {
61
+ return { ok: false, status: 403, error: "cloned-authenticator" };
62
+ }
63
+ return {
64
+ ok: true,
65
+ signature: {
66
+ credentialId: stored.id,
67
+ sub: stored.sub,
68
+ authenticatorData: assertion.response.authenticatorData,
69
+ clientDataJSON: assertion.response.clientDataJSON,
70
+ signature: assertion.response.signature,
71
+ rpId: rp.config.rpID,
72
+ prev,
73
+ },
74
+ };
75
+ }
76
+ function controlSignatureOf(value) {
77
+ if (!value || typeof value !== "object")
78
+ return null;
79
+ const row = value;
80
+ for (const field of ["credentialId", "sub", "authenticatorData", "clientDataJSON", "signature", "rpId"]) {
81
+ if (typeof row[field] !== "string" || row[field] === "")
82
+ return null;
83
+ }
84
+ if (row.prev !== null && (typeof row.prev !== "string" || row.prev === ""))
85
+ return null;
86
+ return row;
87
+ }
88
+ /**
89
+ * Recount halt and resume signatures without a body. A signature must name,
90
+ * as `prev`, the line hash of the control record copied from the history line
91
+ * just before its own (`null` for line 0), and verify under the operator key
92
+ * over the challenge rebuilt from that and the record's subject. A challenge
93
+ * counts once. The authenticator counter is not consulted.
94
+ */
95
+ export async function verifyControlSignatures(stateDir, opts = {}) {
96
+ const pinned = typeof opts.credentialsFile === "string";
97
+ const credentials = readCredentialsAt(pinned ? opts.credentialsFile : credentialsPath(stateDir));
98
+ const trust = trustOf(pinned, credentials);
99
+ const decisions = [];
100
+ const inputsByRef = new Map();
101
+ for (const piece of listPieceFiles(stateDir)) {
102
+ for (const line of readLines(piece.decisions)) {
103
+ try {
104
+ decisions.push(JSON.parse(line));
105
+ }
106
+ catch {
107
+ // The ledger statement names a line that does not parse.
108
+ }
109
+ }
110
+ for (const line of readLines(piece.inputs)) {
111
+ try {
112
+ const row = JSON.parse(line);
113
+ if (typeof row.ref !== "string" || row.inputs === undefined)
114
+ continue;
115
+ const hash = createHash("sha256").update(canonical(row.inputs), "utf8").digest("hex");
116
+ const byHash = inputsByRef.get(row.ref) ?? new Map();
117
+ byHash.set(hash, row.inputs?.control ?? null);
118
+ inputsByRef.set(row.ref, byHash);
119
+ }
120
+ catch {
121
+ // Same as a decision line.
122
+ }
123
+ }
124
+ }
125
+ let signedVerified = 0;
126
+ let signedFailed = 0;
127
+ let unsignedHttp = 0;
128
+ let cli = 0;
129
+ let file = 0;
130
+ const lineHashByLine = new Map();
131
+ const used = new Set();
132
+ for (const row of decisions) {
133
+ if (!row || typeof row !== "object" || !row.claims || typeof row.claims !== "object")
134
+ continue;
135
+ const claims = row.claims;
136
+ if (claims.effectClass !== "verax.control" || claims.decision !== "allow")
137
+ continue;
138
+ if (claims.subject !== "verax.halt" && claims.subject !== "verax.resume")
139
+ continue;
140
+ if (typeof claims.ref !== "string" || typeof claims.inputsHash !== "string")
141
+ continue;
142
+ const control = inputsByRef.get(claims.ref)?.get(claims.inputsHash);
143
+ if (!control)
144
+ continue;
145
+ const at = typeof control.line === "number" && Number.isInteger(control.line) ? control.line : -1;
146
+ if (control.signature === undefined) {
147
+ if (control.via === "http")
148
+ unsignedHttp += 1;
149
+ else if (control.via === "cli")
150
+ cli += 1;
151
+ else
152
+ file += 1;
153
+ }
154
+ else {
155
+ const sig = controlSignatureOf(control.signature);
156
+ const expectedPrev = at === 0 ? null : at > 0 ? lineHashByLine.get(at - 1) : undefined;
157
+ const action = claims.subject === "verax.halt" ? "halt" : "resume";
158
+ const challenge = sig && expectedPrev !== undefined && sig.prev === expectedPrev
159
+ ? controlChallenge({ action, prev: expectedPrev })
160
+ : null;
161
+ const firstUse = challenge !== null && !used.has(challenge);
162
+ if (challenge !== null)
163
+ used.add(challenge);
164
+ const cred = sig ? credentials.find((c) => c.id === sig.credentialId && c.sub === sig.sub) : undefined;
165
+ if (sig && cred && challenge && firstUse && assertionMatches(sig, cred.publicKey, challenge))
166
+ signedVerified += 1;
167
+ else
168
+ signedFailed += 1;
169
+ }
170
+ if (at >= 0 && typeof control.lineHash === "string")
171
+ lineHashByLine.set(at, control.lineHash);
172
+ }
173
+ return {
174
+ ok: signedFailed === 0,
175
+ signedVerified,
176
+ signedFailed,
177
+ unsignedHttp,
178
+ cli,
179
+ file,
180
+ line: `control signatures signed-verified ${signedVerified} · signed-failed ${signedFailed} · unsigned-http ${unsignedHttp} · cli ${cli} · file ${file}`,
181
+ trustSource: trust.trustSource,
182
+ trustNote: trust.trustNote,
183
+ };
184
+ }
@@ -8,6 +8,8 @@ export type DownstreamToolFn = (call: ToolCall, principal: Principal, ref?: stri
8
8
  */
9
9
  export type DownstreamSpec = {
10
10
  prefix: string;
11
+ /** Operator-pinned downstream Ed25519 SPKI public key. */
12
+ effectKeyPem?: string;
11
13
  /** stdio: the process to start. */
12
14
  command?: string;
13
15
  args?: string[];
@@ -45,11 +47,11 @@ export declare class DownstreamCallError extends Error {
45
47
  }
46
48
  export declare function prefixedName(prefix: string, childName: string): string;
47
49
  export declare function extraToolNameOk(name: string): boolean;
48
- export declare function parseDownstreamJson(raw: string): DownstreamSpec;
50
+ export declare function parseDownstreamJson(raw: string, bodyPublicKeyPems?: readonly string[]): DownstreamSpec;
49
51
  /**
50
52
  * The `VERAX_DOWNSTREAM` document: one child, or an array of them. An empty
51
53
  * array is a document that attaches nothing, which is not the same as no
52
54
  * document at all — the operator wrote it, so it is honoured.
53
55
  */
54
- export declare function parseDownstreamDocument(raw: string): DownstreamSpec[];
56
+ export declare function parseDownstreamDocument(raw: string, bodyPublicKeyPems?: readonly string[]): DownstreamSpec[];
55
57
  export declare function openDownstream(spec: DownstreamSpec): Promise<DownstreamSession>;
@@ -1,4 +1,6 @@
1
1
  import { Readable } from "node:stream";
2
+ import { createPublicKey } from "node:crypto";
3
+ import { effectDescriptor, samePublicKey, sha256Canonical, thirdPartyReceiptRejection } from "@verax-ai/proxy";
2
4
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
5
  import { getDefaultEnvironment, StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
4
6
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
@@ -10,6 +12,16 @@ const EXTRA_NAME_RE = /^[A-Za-z][A-Za-z0-9_-]{0,31}\.[A-Za-z][A-Za-z0-9._-]{0,63
10
12
  // hostile or broken; the body is not a registry for thousands of names.
11
13
  const MAX_CHILD_TOOLS = 256;
12
14
  const MAX_TOOL_BYTES = 64 * 1024;
15
+ function assertEffectKey(pem) {
16
+ try {
17
+ if (typeof pem !== "string" || !pem.trim().startsWith("-----BEGIN PUBLIC KEY-----") ||
18
+ createPublicKey(pem).asymmetricKeyType !== "ed25519")
19
+ throw new Error();
20
+ }
21
+ catch {
22
+ throw new Error("downstream-effect-key-invalid");
23
+ }
24
+ }
13
25
  export class DownstreamCallError extends Error {
14
26
  prefix;
15
27
  tool;
@@ -41,7 +53,7 @@ function assertStdioTrusted(spec) {
41
53
  throw new Error(`downstream-stdio-trust-required:${spec.prefix}`);
42
54
  }
43
55
  }
44
- export function parseDownstreamJson(raw) {
56
+ export function parseDownstreamJson(raw, bodyPublicKeyPems = []) {
45
57
  let parsed;
46
58
  try {
47
59
  parsed = JSON.parse(raw);
@@ -63,6 +75,13 @@ export function parseDownstreamJson(raw) {
63
75
  if (!cmdVar && !urlVar)
64
76
  throw new Error("downstream-transport-missing");
65
77
  const spec = { prefix: rec.prefix };
78
+ if (rec.effectKeyPem !== undefined) {
79
+ assertEffectKey(rec.effectKeyPem);
80
+ if (bodyPublicKeyPems.some(key => samePublicKey(key, rec.effectKeyPem))) {
81
+ throw new Error(`downstream-effect-key-not-independent:${spec.prefix}`);
82
+ }
83
+ spec.effectKeyPem = rec.effectKeyPem;
84
+ }
66
85
  if (cmdVar) {
67
86
  if (typeof rec.command !== "string" || rec.command.trim() === "") {
68
87
  throw new Error("downstream-command-invalid");
@@ -146,7 +165,7 @@ export function parseDownstreamJson(raw) {
146
165
  * array is a document that attaches nothing, which is not the same as no
147
166
  * document at all — the operator wrote it, so it is honoured.
148
167
  */
149
- export function parseDownstreamDocument(raw) {
168
+ export function parseDownstreamDocument(raw, bodyPublicKeyPems = []) {
150
169
  let parsed;
151
170
  try {
152
171
  parsed = JSON.parse(raw);
@@ -158,7 +177,7 @@ export function parseDownstreamDocument(raw) {
158
177
  const specs = [];
159
178
  const prefixes = new Set();
160
179
  for (const item of items) {
161
- const spec = parseDownstreamJson(JSON.stringify(item));
180
+ const spec = parseDownstreamJson(JSON.stringify(item), bodyPublicKeyPems);
162
181
  if (prefixes.has(spec.prefix)) {
163
182
  throw new Error(`downstream-prefix-duplicate:${spec.prefix}`);
164
183
  }
@@ -266,6 +285,8 @@ function attachTimeoutError(err, prefix) {
266
285
  return err instanceof Error ? err : new Error(msg);
267
286
  }
268
287
  export async function openDownstream(spec) {
288
+ if (spec.effectKeyPem !== undefined)
289
+ assertEffectKey(spec.effectKeyPem);
269
290
  if (!PREFIX_RE.test(spec.prefix)) {
270
291
  throw new Error("downstream-prefix-invalid");
271
292
  }
@@ -318,12 +339,14 @@ export async function openDownstream(spec) {
318
339
  name,
319
340
  ...(typeof tool.description === "string" ? { description: tool.description } : {}),
320
341
  ...(tool.inputSchema !== undefined ? { inputSchema: tool.inputSchema } : {}),
321
- fn: async (call) => {
342
+ fn: async (call, _principal, ref) => {
322
343
  let raw;
323
344
  try {
324
345
  // Mutation check: stub this call and the allow test expecting
325
346
  // "pong":true from the child goes red.
326
- raw = await client.callTool({ name: childName, arguments: call.arguments }, undefined, { timeout: timeoutMs });
347
+ raw = await client.callTool({ name: childName, arguments: call.arguments,
348
+ ...(spec.effectKeyPem ? { _meta: { "io.cedulon/decision": { ref, deciderId: "verax-proxy", prefix: spec.prefix } } } : {}),
349
+ }, undefined, { timeout: timeoutMs });
327
350
  }
328
351
  catch (err) {
329
352
  throw new DownstreamCallError(spec.prefix, childName, err);
@@ -332,6 +355,14 @@ export async function openDownstream(spec) {
332
355
  if (result.isError) {
333
356
  throw new DownstreamCallError(spec.prefix, childName, textOf(result) || "isError");
334
357
  }
358
+ if (spec.effectKeyPem) {
359
+ const receipt = raw._meta?.["io.cedulon/effect-extract"];
360
+ const reason = thirdPartyReceiptRejection(receipt, spec.effectKeyPem, ref, name, sha256Canonical(effectDescriptor(name, call.arguments)));
361
+ if (reason)
362
+ process.stderr.write(`verax-body: third-party receipt rejected: ${reason}\n`);
363
+ else
364
+ result.effectReceipt = receipt;
365
+ }
335
366
  return result;
336
367
  },
337
368
  });
package/dist/halt.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { ControlSignature } from "@verax-ai/proxy";
1
2
  /**
2
3
  * The proxy refuses every call while `<stateDir>/halted` exists; that file is
3
4
  * the switch and stays empty. Who flipped it and when goes to
@@ -11,26 +12,36 @@
11
12
  * and that delay is part of the record rather than something the file hides.
12
13
  * Calls refused while halted are signed deny records, and they come after
13
14
  * the halt control record in the chain.
15
+ *
16
+ * An HTTP halt or resume made with the operator's passkey carries that
17
+ * assertion on its line, and the control record carries it on from there.
14
18
  */
15
19
  export type HaltEvent = {
16
20
  action: "halt" | "resume";
17
21
  atMs: number;
18
22
  by: string;
19
23
  via: "cli" | "http";
24
+ signature?: ControlSignature;
20
25
  };
21
26
  export type HaltState = {
22
27
  halted: boolean;
23
28
  since?: HaltEvent;
24
29
  };
30
+ /**
31
+ * SHA-256 of the newest history line, as the control record names that line
32
+ * (`lineHash`), or `null` when there is none. A signed halt or resume binds
33
+ * this, so its assertion fits only the line it is appended after.
34
+ */
35
+ export declare function historyTail(stateDir: string): string | null;
25
36
  export declare function readHalt(stateDir: string): HaltState;
26
37
  /** Halting twice is one halt: the first line keeps saying who stopped it. */
27
- export declare function haltBody(stateDir: string, by: string, via: HaltEvent["via"], now?: number): HaltState;
38
+ export declare function haltBody(stateDir: string, by: string, via: HaltEvent["via"], now?: number, signature?: ControlSignature): HaltState;
28
39
  /**
29
40
  * Resuming a body that is not halted changes nothing and writes nothing.
30
41
  * The line goes to the history before the switch is removed: if it cannot be
31
42
  * written, the append throws and the body stays halted, rather than running
32
43
  * again with no record of who let it.
33
44
  */
34
- export declare function resumeBody(stateDir: string, by: string, via: HaltEvent["via"], now?: number): HaltState;
45
+ export declare function resumeBody(stateDir: string, by: string, via: HaltEvent["via"], now?: number, signature?: ControlSignature): HaltState;
35
46
  export declare function runHalt(stateDir: string, writeErr?: (s: string) => void): number;
36
47
  export declare function runResume(stateDir: string, writeErr?: (s: string) => void): number;
package/dist/halt.js CHANGED
@@ -1,6 +1,8 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
3
  import { userInfo } from "node:os";
3
4
  import { join } from "node:path";
5
+ import { canonical } from "@cedulon/core";
4
6
  const SWITCH = "halted";
5
7
  const HISTORY = "halt-history.jsonl";
6
8
  function cliUser() {
@@ -14,6 +16,30 @@ function cliUser() {
14
16
  function appendHistory(stateDir, event) {
15
17
  appendFileSync(join(stateDir, HISTORY), `${JSON.stringify(event)}\n`, { encoding: "utf8", mode: 0o600 });
16
18
  }
19
+ /**
20
+ * SHA-256 of the newest history line, as the control record names that line
21
+ * (`lineHash`), or `null` when there is none. A signed halt or resume binds
22
+ * this, so its assertion fits only the line it is appended after.
23
+ */
24
+ export function historyTail(stateDir) {
25
+ let raw;
26
+ try {
27
+ raw = readFileSync(join(stateDir, HISTORY), "utf8");
28
+ }
29
+ catch (err) {
30
+ if (err.code === "ENOENT")
31
+ return null;
32
+ throw err;
33
+ }
34
+ const lines = raw
35
+ .split("\n")
36
+ .map((line) => line.replace(/\r$/, ""))
37
+ .filter((line) => line.trim() !== "");
38
+ const last = lines[lines.length - 1];
39
+ if (last === undefined)
40
+ return null;
41
+ return createHash("sha256").update(canonical(last), "utf8").digest("hex");
42
+ }
17
43
  function lastHalt(stateDir) {
18
44
  let raw;
19
45
  try {
@@ -45,11 +71,11 @@ export function readHalt(stateDir) {
45
71
  return since ? { halted: true, since } : { halted: true };
46
72
  }
47
73
  /** Halting twice is one halt: the first line keeps saying who stopped it. */
48
- export function haltBody(stateDir, by, via, now = Date.now()) {
74
+ export function haltBody(stateDir, by, via, now = Date.now(), signature) {
49
75
  mkdirSync(stateDir, { recursive: true, mode: 0o700 });
50
76
  if (!existsSync(join(stateDir, SWITCH))) {
51
77
  writeFileSync(join(stateDir, SWITCH), "", { encoding: "utf8", mode: 0o600 });
52
- appendHistory(stateDir, { action: "halt", atMs: now, by, via });
78
+ appendHistory(stateDir, { action: "halt", atMs: now, by, via, ...(signature ? { signature } : {}) });
53
79
  }
54
80
  return readHalt(stateDir);
55
81
  }
@@ -59,9 +85,9 @@ export function haltBody(stateDir, by, via, now = Date.now()) {
59
85
  * written, the append throws and the body stays halted, rather than running
60
86
  * again with no record of who let it.
61
87
  */
62
- export function resumeBody(stateDir, by, via, now = Date.now()) {
88
+ export function resumeBody(stateDir, by, via, now = Date.now(), signature) {
63
89
  if (existsSync(join(stateDir, SWITCH))) {
64
- appendHistory(stateDir, { action: "resume", atMs: now, by, via });
90
+ appendHistory(stateDir, { action: "resume", atMs: now, by, via, ...(signature ? { signature } : {}) });
65
91
  rmSync(join(stateDir, SWITCH), { force: true });
66
92
  }
67
93
  return readHalt(stateDir);
package/dist/server.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
3
4
  import { createServer } from "node:http";
4
5
  import { Server as McpServer } from "@modelcontextprotocol/sdk/server/index.js";
5
6
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
@@ -18,6 +19,7 @@ import { matchingInputs } from "./inputs-read.js";
18
19
  import { readPolicySnapshots } from "./policy-store.js";
19
20
  import { readHeartbeat, readInstallHealthNonce, readWitnessPulse } from "./health-extras.js";
20
21
  import { agentsWindow } from "./agents.js";
22
+ import { gateControlSignature, nextControlChallenge } from "./control-signature.js";
21
23
  import { haltBody, readHalt, resumeBody } from "./halt.js";
22
24
  import { inventoryHealth, readInventoryFile } from "./inventory-file.js";
23
25
  import { createBodyServices, TOOL_NAMES } from "./wiring.js";
@@ -332,10 +334,10 @@ function downstreamPublic(sessions, specs) {
332
334
  * closes the ones already open and throws: a half-attached body would serve a
333
335
  * tool list its operator never wrote.
334
336
  */
335
- async function attachDownstream(file) {
337
+ async function attachDownstream(file, bodyPublicKeyPems) {
336
338
  if (file === null || file.trim() === "")
337
339
  return { sessions: [], specs: [] };
338
- const specs = parseDownstreamDocument(readFileSync(file, "utf8"));
340
+ const specs = parseDownstreamDocument(readFileSync(file, "utf8"), bodyPublicKeyPems);
339
341
  const sessions = [];
340
342
  for (const spec of specs) {
341
343
  try {
@@ -351,10 +353,20 @@ async function attachDownstream(file) {
351
353
  }
352
354
  export async function listen(config) {
353
355
  const signers = loadOrCreateSigners(config.stateDir);
356
+ const bodyPublicKeyPems = [signers.recordSigner.publicKeyPem, signers.effectSigner.publicKeyPem];
357
+ if (config.downstreamFile) {
358
+ try {
359
+ bodyPublicKeyPems.push(readFileSync(join(config.stateDir, "keys", "witness.public.pem"), "utf8"));
360
+ }
361
+ catch (err) {
362
+ if (err.code !== "ENOENT")
363
+ throw err;
364
+ }
365
+ }
354
366
  // The children are attached before the door opens. A named document the body
355
367
  // cannot honour stops the start: a body that serves six tools while its
356
368
  // operator wrote seven is answering for a gate it does not have.
357
- const { sessions, specs: downstreamSpecs } = await attachDownstream(config.downstreamFile ?? null);
369
+ const { sessions, specs: downstreamSpecs } = await attachDownstream(config.downstreamFile ?? null, bodyPublicKeyPems);
358
370
  const extraTools = sessions.flatMap((session) => session.tools);
359
371
  let services;
360
372
  try {
@@ -524,6 +536,7 @@ export async function listen(config) {
524
536
  const apiAgents = req.method === "GET" && url.pathname === "/api/agents";
525
537
  const apiHalt = url.pathname === "/api/halt" && (req.method === "GET" || req.method === "POST");
526
538
  const apiResume = req.method === "POST" && url.pathname === "/api/resume";
539
+ const apiControlChallenge = req.method === "GET" && (url.pathname === "/api/halt/challenge" || url.pathname === "/api/resume/challenge");
527
540
  if (url.pathname !== "/mcp" &&
528
541
  !apiLedger &&
529
542
  !apiInventory &&
@@ -532,7 +545,8 @@ export async function listen(config) {
532
545
  !apiApproveChallenge &&
533
546
  !apiAgents &&
534
547
  !apiHalt &&
535
- !apiResume) {
548
+ !apiResume &&
549
+ !apiControlChallenge) {
536
550
  send(res, 404, { error: "not-found" });
537
551
  return;
538
552
  }
@@ -573,25 +587,68 @@ export async function listen(config) {
573
587
  return;
574
588
  }
575
589
  try {
576
- if (apiHalt || apiResume) {
590
+ if (apiHalt || apiResume || apiControlChallenge) {
577
591
  if (await refuseStaleBearer())
578
592
  return;
579
593
  const scopes = verified.principal.scopes;
580
594
  const operator = scopes.has("verax:audit") || scopes.has("verax:approve");
595
+ const resuming = apiResume || url.pathname === "/api/resume/challenge";
581
596
  // Stopping is the safe direction, so any operator session may do it.
582
597
  // Lifting a halt lets everything through again: that is an approval of
583
598
  // everything at once and needs the approve scope. The agent token
584
599
  // carries neither, so an agent cannot stop itself being stopped.
585
- if (!operator || (apiResume && !scopes.has("verax:approve"))) {
600
+ if (!operator || (resuming && !scopes.has("verax:approve"))) {
586
601
  send(res, 403, { error: "scope-missing" });
587
602
  return;
588
603
  }
604
+ if (apiControlChallenge) {
605
+ const rp = readRpConfig(process.env);
606
+ if (!rp.ok) {
607
+ send(res, 503, { error: "passkey-closed", reason: rp.reason });
608
+ return;
609
+ }
610
+ send(res, 200, {
611
+ ...nextControlChallenge(config.stateDir, resuming ? "resume" : "halt"),
612
+ rpId: rp.config.rpID,
613
+ allowCredentials: readCredentials(config.stateDir).map((row) => ({ id: row.id, type: "public-key" })),
614
+ });
615
+ return;
616
+ }
589
617
  if (req.method === "GET") {
590
618
  send(res, 200, readHalt(config.stateDir));
591
619
  return;
592
620
  }
621
+ const parsed = await readJsonBody(req, MAX_BODY_BYTES);
622
+ if (await refuseStaleBearer())
623
+ return;
624
+ if (!parsed.ok && apiResume) {
625
+ send(res, 400, { error: "bad-body" });
626
+ return;
627
+ }
628
+ const asked = parsed.ok && parsed.value && typeof parsed.value === "object" ? parsed.value : {};
629
+ // The tail is read inside the gate and the line is appended right
630
+ // after it, with nothing awaited in between.
631
+ const gated = gateControlSignature({
632
+ stateDir: config.stateDir,
633
+ env: process.env,
634
+ action: apiResume ? "resume" : "halt",
635
+ assertion: asked.assertion,
636
+ });
637
+ // A refused resume writes nothing. A halt is never refused for its
638
+ // signature: it stops unsigned, and the answer says what was refused.
639
+ if (!gated.ok && apiResume) {
640
+ send(res, gated.status, { error: gated.error, ...(gated.reason ? { reason: gated.reason } : {}) });
641
+ return;
642
+ }
643
+ const signature = gated.ok ? gated.signature : undefined;
644
+ const refused = !parsed.ok ? "bad-body" : gated.ok ? undefined : gated.error;
593
645
  const by = verified.principal.brain;
594
- const state = apiResume ? resumeBody(config.stateDir, by, "http") : haltBody(config.stateDir, by, "http");
646
+ const state = apiResume
647
+ ? resumeBody(config.stateDir, by, "http", Date.now(), signature)
648
+ : {
649
+ ...haltBody(config.stateDir, by, "http", Date.now(), signature),
650
+ ...(refused ? { signatureRefused: refused } : {}),
651
+ };
595
652
  try {
596
653
  await services.proxy.syncControlRecords();
597
654
  }
@@ -1,5 +1,6 @@
1
1
  import { type VerifyResult } from "@verax-ai/proxy";
2
2
  import { type ApprovalSignatureReport } from "./approval-signature.ts";
3
+ import { type ControlSignatureReport } from "./control-signature.ts";
3
4
  export declare const EX_VERIFY_FAILED = 1;
4
- export declare function renderVerify(r: VerifyResult, approval?: ApprovalSignatureReport): string;
5
+ export declare function renderVerify(r: VerifyResult, approval?: ApprovalSignatureReport, control?: ControlSignatureReport): string;
5
6
  export declare function runVerify(argv: readonly string[], out?: (s: string) => void): Promise<number>;
@@ -12,15 +12,19 @@
12
12
  * the most — **which key** answered. Verifying against the key lying in the
13
13
  * same directory proves the files agree with each other and nothing else;
14
14
  * that line is printed every time, not buried in a flag.
15
+ * Third-party extracts require reader-held --third-party-key <file> pins
16
+ * (repeatable). Their signed row binds to its decision, but resultHash is
17
+ * unattested. A record, effect or witness key cannot be a third-party pin.
15
18
  */
16
19
  import { readFileSync } from "node:fs";
17
20
  import { verifyLedger } from "@verax-ai/proxy";
18
21
  import { verifyApprovalSignatures } from "./approval-signature.js";
22
+ import { verifyControlSignatures } from "./control-signature.js";
19
23
  import { directoryAccess, unreadableSentence } from "./install.js";
20
24
  export const EX_VERIFY_FAILED = 1;
21
25
  function usage() {
22
26
  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]",
27
+ "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
28
  "",
25
29
  " <stateDir> the directory holding decisions.jsonl and effects.jsonl",
26
30
  " --key <file> verify decision records against a public key you hold,",
@@ -39,10 +43,19 @@ function usage() {
39
43
  " row. Agreement is not trust, the same as --key. When",
40
44
  " this is set and the ledger has a self row, --effect-key",
41
45
  " is required too.",
46
+ " --third-party-key <file>",
47
+ " pin a downstream effect-extract signer (repeatable).",
48
+ " No key is taken from a third-party row. Its resultHash",
49
+ " is not attested. Body record/effect/witness keys refuse.",
42
50
  " --checkpoint-key <file>",
43
51
  " verify every checkpoint row against a public key you",
44
52
  " hold, instead of one key taken from the checkpoint",
45
53
  " file. Same distinction as --key, for the witness.",
54
+ " --anchor-key <file>",
55
+ " check the transparency-service receipts in",
56
+ " checkpoint-anchors.jsonl under this service key. A",
57
+ " receipt names no key of its own, so without this flag",
58
+ " the receipts are counted and not checked.",
46
59
  " --operator-credentials <file>",
47
60
  " verify HTTP approval signatures against this operator",
48
61
  " credential file, instead of operator-credentials.json",
@@ -64,11 +77,25 @@ const APPROVAL_NOT_CHECKED = {
64
77
  trustSource: "none",
65
78
  trustNote: "approval signatures were not checked",
66
79
  };
67
- export function renderVerify(r, approval = APPROVAL_NOT_CHECKED) {
80
+ const CONTROL_NOT_CHECKED = {
81
+ ok: true,
82
+ signedVerified: 0,
83
+ signedFailed: 0,
84
+ unsignedHttp: 0,
85
+ cli: 0,
86
+ file: 0,
87
+ line: "control signatures not checked",
88
+ trustSource: "none",
89
+ trustNote: "control signatures were not checked",
90
+ };
91
+ export function renderVerify(r, approval = APPROVAL_NOT_CHECKED, control = CONTROL_NOT_CHECKED) {
68
92
  const lines = [];
69
93
  lines.push(`ledger ${r.directory}`);
70
94
  lines.push(`decisions ${r.decisions}`);
71
95
  lines.push(`effects ${r.effects} (${r.effectsBound} bound to a decision, ${r.effectsOrphaned} with none)`);
96
+ if (r.effectsDeferred.length > 0) {
97
+ lines.push(`deferred ${r.effectsDeferred.length} allow(s) with no effect row yet, within the boundary allowance of the newest record (boundary-deferred, a warning): ${r.effectsDeferred.join(", ")}`);
98
+ }
72
99
  lines.push(`signatures ${r.signaturesValid} verify, ${r.signaturesInvalid} do not`);
73
100
  lines.push(`chain ${r.chainBreakAt === null ? "unbroken" : `breaks at record ${r.chainBreakAt}`}`);
74
101
  lines.push(`verified with ${r.trust.source === "pinned"
@@ -102,6 +129,7 @@ export function renderVerify(r, approval = APPROVAL_NOT_CHECKED) {
102
129
  lines.push(` ${r.checkpointTrust.note}`);
103
130
  lines.push(r.index.line);
104
131
  lines.push(r.effectCompleteness);
132
+ lines.push(r.inputs.line);
105
133
  if (r.tail.checkpoint) {
106
134
  const head = r.tail.checkpoint.chainHeadHash ?? "(no head hash)";
107
135
  const holds = r.tail.checkpoint.ledgerHoldsRecord === null
@@ -118,8 +146,11 @@ export function renderVerify(r, approval = APPROVAL_NOT_CHECKED) {
118
146
  lines.push(r.control.line);
119
147
  for (const warning of r.control.warnings)
120
148
  lines.push(`warning ${warning}`);
149
+ lines.push(r.anchors.line);
121
150
  lines.push(approval.line);
122
151
  lines.push(` ${approval.trustNote}`);
152
+ // Halt and resume signatures are checked under the same operator key.
153
+ lines.push(control.line);
123
154
  if (r.problems.length > 0) {
124
155
  lines.push("");
125
156
  lines.push("problems:");
@@ -178,10 +209,22 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
178
209
  if (!witnessKey.ok)
179
210
  return EX_VERIFY_FAILED;
180
211
  witnessPublicKeyPem = witnessKey.pem;
212
+ const thirdPartyPublicKeyPems = [];
213
+ while (args.includes("--third-party-key")) {
214
+ const key = readKeyFlag("--third-party-key");
215
+ if (!key.ok)
216
+ return EX_VERIFY_FAILED;
217
+ if (key.pem)
218
+ thirdPartyPublicKeyPems.push(key.pem);
219
+ }
181
220
  const checkpointKey = readKeyFlag("--checkpoint-key");
182
221
  if (!checkpointKey.ok)
183
222
  return EX_VERIFY_FAILED;
184
223
  checkpointPublicKeyPem = checkpointKey.pem;
224
+ const anchorKey = readKeyFlag("--anchor-key");
225
+ if (!anchorKey.ok)
226
+ return EX_VERIFY_FAILED;
227
+ const anchorPublicKeyPem = anchorKey.pem;
185
228
  let credentialsFile;
186
229
  const credentialsAt = args.indexOf("--operator-credentials");
187
230
  if (credentialsAt !== -1) {
@@ -216,10 +259,12 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
216
259
  let result;
217
260
  try {
218
261
  result = await verifyLedger(dir, {
262
+ thirdPartyPublicKeyPems,
219
263
  ...(publicKeyPem ? { publicKeyPem } : {}),
220
264
  ...(effectPublicKeyPem ? { effectPublicKeyPem } : {}),
221
265
  ...(witnessPublicKeyPem ? { witnessPublicKeyPem } : {}),
222
266
  ...(checkpointPublicKeyPem ? { checkpointPublicKeyPem } : {}),
267
+ ...(anchorPublicKeyPem ? { anchorPublicKeyPem } : {}),
223
268
  });
224
269
  }
225
270
  catch (err) {
@@ -234,6 +279,7 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
234
279
  chainBreakAt: null,
235
280
  effectsBound: 0,
236
281
  effectsOrphaned: 0,
282
+ effectsDeferred: [],
237
283
  trust: { source: "none", publicKeyPem: null, note: problem },
238
284
  effectTrust: { source: "none", publicKeyPem: null, note: problem },
239
285
  witnessTrust: { source: "none", publicKeyPem: null, note: problem },
@@ -245,10 +291,12 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
245
291
  checkpoint: null,
246
292
  },
247
293
  control: { line: "control: not checked", windows: 0, warnings: [] },
294
+ inputs: { line: "inputs: not checked", matched: 0, missing: 0, mismatched: 0 },
295
+ anchors: { line: "anchors: not checked", receipts: 0, verified: 0, checked: false },
248
296
  problems: [problem],
249
297
  };
250
- const failedReport = { ...failed, approvalSignatures: APPROVAL_NOT_CHECKED };
251
- out(json ? JSON.stringify(failedReport, null, 2) : renderVerify(failed, APPROVAL_NOT_CHECKED));
298
+ const failedReport = { ...failed, approvalSignatures: APPROVAL_NOT_CHECKED, controlSignatures: CONTROL_NOT_CHECKED };
299
+ out(json ? JSON.stringify(failedReport, null, 2) : renderVerify(failed, APPROVAL_NOT_CHECKED, CONTROL_NOT_CHECKED));
252
300
  return EX_VERIFY_FAILED;
253
301
  }
254
302
  let approval;
@@ -267,7 +315,23 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
267
315
  problems: [...result.problems, `approval signatures: ${approval.signedFailed} did not verify`],
268
316
  };
269
317
  }
270
- const reported = { ...result, approvalSignatures: approval };
271
- out(json ? JSON.stringify(reported, null, 2) : renderVerify(reported, approval));
318
+ let control;
319
+ try {
320
+ control = await verifyControlSignatures(dir, credentialsFile ? { credentialsFile } : {});
321
+ }
322
+ catch (err) {
323
+ const problem = err instanceof Error ? err.message : "control signatures could not be read";
324
+ control = { ...CONTROL_NOT_CHECKED, ok: false, trustNote: problem };
325
+ result = { ...result, ok: false, problems: [...result.problems, problem] };
326
+ }
327
+ if (control.signedFailed > 0) {
328
+ result = {
329
+ ...result,
330
+ ok: false,
331
+ problems: [...result.problems, `control signatures: ${control.signedFailed} did not verify`],
332
+ };
333
+ }
334
+ const reported = { ...result, approvalSignatures: approval, controlSignatures: control };
335
+ out(json ? JSON.stringify(reported, null, 2) : renderVerify(reported, approval, control));
272
336
  return reported.ok ? 0 : EX_VERIFY_FAILED;
273
337
  }
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.4",
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.4",
30
+ "@verax-ai/proxy": "^0.4.4",
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.",