@verax-ai/body 0.4.3 → 0.4.5

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.
@@ -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)
@@ -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,10 +12,14 @@
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() {
@@ -39,6 +43,10 @@ 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",
@@ -69,11 +77,25 @@ const APPROVAL_NOT_CHECKED = {
69
77
  trustSource: "none",
70
78
  trustNote: "approval signatures were not checked",
71
79
  };
72
- 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) {
73
92
  const lines = [];
74
93
  lines.push(`ledger ${r.directory}`);
75
94
  lines.push(`decisions ${r.decisions}`);
76
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
+ }
77
99
  lines.push(`signatures ${r.signaturesValid} verify, ${r.signaturesInvalid} do not`);
78
100
  lines.push(`chain ${r.chainBreakAt === null ? "unbroken" : `breaks at record ${r.chainBreakAt}`}`);
79
101
  lines.push(`verified with ${r.trust.source === "pinned"
@@ -127,6 +149,8 @@ export function renderVerify(r, approval = APPROVAL_NOT_CHECKED) {
127
149
  lines.push(r.anchors.line);
128
150
  lines.push(approval.line);
129
151
  lines.push(` ${approval.trustNote}`);
152
+ // Halt and resume signatures are checked under the same operator key.
153
+ lines.push(control.line);
130
154
  if (r.problems.length > 0) {
131
155
  lines.push("");
132
156
  lines.push("problems:");
@@ -185,6 +209,14 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
185
209
  if (!witnessKey.ok)
186
210
  return EX_VERIFY_FAILED;
187
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
+ }
188
220
  const checkpointKey = readKeyFlag("--checkpoint-key");
189
221
  if (!checkpointKey.ok)
190
222
  return EX_VERIFY_FAILED;
@@ -227,6 +259,7 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
227
259
  let result;
228
260
  try {
229
261
  result = await verifyLedger(dir, {
262
+ thirdPartyPublicKeyPems,
230
263
  ...(publicKeyPem ? { publicKeyPem } : {}),
231
264
  ...(effectPublicKeyPem ? { effectPublicKeyPem } : {}),
232
265
  ...(witnessPublicKeyPem ? { witnessPublicKeyPem } : {}),
@@ -246,6 +279,7 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
246
279
  chainBreakAt: null,
247
280
  effectsBound: 0,
248
281
  effectsOrphaned: 0,
282
+ effectsDeferred: [],
249
283
  trust: { source: "none", publicKeyPem: null, note: problem },
250
284
  effectTrust: { source: "none", publicKeyPem: null, note: problem },
251
285
  witnessTrust: { source: "none", publicKeyPem: null, note: problem },
@@ -261,8 +295,8 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
261
295
  anchors: { line: "anchors: not checked", receipts: 0, verified: 0, checked: false },
262
296
  problems: [problem],
263
297
  };
264
- const failedReport = { ...failed, approvalSignatures: APPROVAL_NOT_CHECKED };
265
- 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));
266
300
  return EX_VERIFY_FAILED;
267
301
  }
268
302
  let approval;
@@ -281,7 +315,23 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
281
315
  problems: [...result.problems, `approval signatures: ${approval.signedFailed} did not verify`],
282
316
  };
283
317
  }
284
- const reported = { ...result, approvalSignatures: approval };
285
- 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));
286
336
  return reported.ok ? 0 : EX_VERIFY_FAILED;
287
337
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verax-ai/body",
3
- "version": "0.4.3",
3
+ "version": "0.4.5",
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.3",
30
- "@verax-ai/proxy": "^0.4.3",
29
+ "@verax-ai/inventory": "^0.4.5",
30
+ "@verax-ai/proxy": "^0.4.5",
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.",