@verax-ai/body 0.4.7 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -38,6 +38,12 @@ Bearer token the configured issuer did not sign.
38
38
  | `VERAX_INVENTORY_FILE` | no | Roster document the body serves. The format is `@verax-ai/inventory`. |
39
39
  | `VERAX_DOWNSTREAM` | no | Path to a JSON document naming MCP servers to put behind this gate: one `{ prefix, command?, args?, cwd?, env?, url?, headers?, timeoutMs?, trust? }` or an array of them. Each child names exactly one way in — `command` to spawn it over stdio, or `url` to reach one already running over Streamable HTTP, with `headers` for its own bearer. A stdio child requires `"trust": "same-user"` (it runs as the same user as the body and can read the signing keys); an HTTP child does not ask for that field and must not carry it. This is a breaking change: existing stdio documents do not open until the field is added. A path and not the JSON itself, because the document may name a key in `env` or `headers`. Their tools are served as `prefix.childName` and need an exact policy rule under that name; a named child that cannot be opened stops the body. |
40
40
 
41
+ The agent's token is a JWT signed with ES256 or EdDSA by a key in that JWKS.
42
+ It must carry `iss` (`VERAX_ISSUER`), `aud` (`VERAX_AUDIENCE`), `sub`, `iat`,
43
+ `exp` and `jti`; `scope` is a space-separated list the policy reads. A token
44
+ without `jti` is refused with 401, because a revocation names a token by its
45
+ `jti`. Check that your issuer sets it on the tokens it gives agents.
46
+
41
47
  `verax doctor` names what is missing. A misconfigured body exits with code 78
42
48
  before it listens.
43
49
 
@@ -1,2 +1,27 @@
1
+ import { type AnchorRow } from "@verax-ai/proxy";
1
2
  export declare const EX_ANCHOR_FAILED = 1;
3
+ /** https only; http is accepted for a loopback address. No credentials, query or fragment. */
4
+ export declare function serviceUrl(raw: string): URL | null;
5
+ /** The name a service's rows are kept under: origin and path, no trailing slash. */
6
+ export declare function serviceNameOf(service: URL): string;
7
+ export type Registered = {
8
+ ok: true;
9
+ row: AnchorRow;
10
+ checked: boolean;
11
+ } | {
12
+ ok: false;
13
+ reason: "unreachable" | "wrong-receipt" | "receipt-unverified";
14
+ message: string;
15
+ };
16
+ /**
17
+ * Registers one checkpoint hash at `serviceName` and returns the row to keep.
18
+ * Nothing is written here; the caller appends the row. With `serviceKey` the
19
+ * receipt must verify under it, at the tree size and leaf the service named.
20
+ */
21
+ export declare function registerCheckpoint(serviceName: string, hash: string, serviceKey: string | null, fetchImpl?: typeof fetch, now?: () => number): Promise<Registered>;
22
+ /** Checkpoint hashes in this directory with no row at `serviceName`, in file order. */
23
+ export declare function pendingAnchors(dir: string, serviceName: string): {
24
+ pending: string[];
25
+ problems: string[];
26
+ };
2
27
  export declare function runAnchor(argv: readonly string[], out?: (s: string) => void, fetchImpl?: typeof fetch, now?: () => number): Promise<number>;
@@ -29,7 +29,8 @@ function usage() {
29
29
  "Sends the SHA-256 of each checkpoint not yet anchored at that service, and nothing else.",
30
30
  ].join("\n");
31
31
  }
32
- function serviceUrl(raw) {
32
+ /** https only; http is accepted for a loopback address. No credentials, query or fragment. */
33
+ export function serviceUrl(raw) {
33
34
  let url;
34
35
  try {
35
36
  url = new URL(raw);
@@ -73,6 +74,81 @@ async function boundedText(res) {
73
74
  }
74
75
  return Buffer.concat(chunks).toString("utf8");
75
76
  }
77
+ /** The name a service's rows are kept under: origin and path, no trailing slash. */
78
+ export function serviceNameOf(service) {
79
+ return service.origin + service.pathname.replace(/\/+$/, "");
80
+ }
81
+ /**
82
+ * Registers one checkpoint hash at `serviceName` and returns the row to keep.
83
+ * Nothing is written here; the caller appends the row. With `serviceKey` the
84
+ * receipt must verify under it, at the tree size and leaf the service named.
85
+ */
86
+ export async function registerCheckpoint(serviceName, hash, serviceKey, fetchImpl = fetch, now = Date.now) {
87
+ const entryHash = anchorEntryHash(hash, "register");
88
+ let answer;
89
+ try {
90
+ const res = await fetchImpl(`${serviceName}/register`, {
91
+ method: "POST",
92
+ headers: { "content-type": "application/json", accept: "application/json" },
93
+ body: JSON.stringify({ capsule_id: hash }),
94
+ signal: AbortSignal.timeout(15_000),
95
+ redirect: "error",
96
+ });
97
+ if (!res.ok)
98
+ throw new Error(`HTTP ${res.status}`);
99
+ answer = JSON.parse(await boundedText(res));
100
+ }
101
+ catch (err) {
102
+ return { ok: false, reason: "unreachable", message: err instanceof Error ? err.message : String(err) };
103
+ }
104
+ // JSON `null` parses and is not an object: read through `?? {}` so it is refused below
105
+ // like `[]` and `{}`, not thrown as a TypeError the caller has no row for.
106
+ const { receipt_b64, entry_hash, leaf_index, tree_size } = (answer ?? {});
107
+ if (typeof receipt_b64 !== "string" ||
108
+ receipt_b64.length > MAX_RECEIPT_B64 ||
109
+ Buffer.from(receipt_b64, "base64").length > MAX_RECEIPT_BYTES ||
110
+ entry_hash !== entryHash ||
111
+ !Number.isSafeInteger(leaf_index) ||
112
+ !Number.isSafeInteger(tree_size)) {
113
+ return {
114
+ ok: false,
115
+ reason: "wrong-receipt",
116
+ message: "the service answered with a receipt for another entry, or no receipt",
117
+ };
118
+ }
119
+ if (serviceKey) {
120
+ const check = verifyReceipt(Buffer.from(receipt_b64, "base64"), Buffer.from(entryHash, "hex"), serviceKey);
121
+ if (!check.ok || check.treeSize !== tree_size || check.leafIndex !== leaf_index) {
122
+ return { ok: false, reason: "receipt-unverified", message: "receipt does not verify under the service key" };
123
+ }
124
+ }
125
+ return {
126
+ ok: true,
127
+ checked: serviceKey !== null,
128
+ row: {
129
+ v: 1,
130
+ checkpointHash: hash,
131
+ service: serviceName,
132
+ route: "register",
133
+ entryHash,
134
+ leafIndex: leaf_index,
135
+ treeSize: tree_size,
136
+ receiptB64: receipt_b64,
137
+ atMs: now(),
138
+ },
139
+ };
140
+ }
141
+ /** Checkpoint hashes in this directory with no row at `serviceName`, in file order. */
142
+ export function pendingAnchors(dir, serviceName) {
143
+ const loaded = readCheckpointFile(dir);
144
+ if (loaded.problems.length > 0)
145
+ return { pending: [], problems: loaded.problems };
146
+ const existing = readAnchors(dir);
147
+ if (existing.problems.length > 0)
148
+ return { pending: [], problems: existing.problems };
149
+ const done = new Set(existing.rows.filter((r) => r.service === serviceName).map((r) => r.checkpointHash));
150
+ return { pending: loaded.rows.map((row) => checkpointHash(row)).filter((hash) => !done.has(hash)), problems: [] };
151
+ }
76
152
  export async function runAnchor(argv, out = (s) => process.stdout.write(`${s}\n`), fetchImpl = fetch, now = Date.now) {
77
153
  const args = [...argv];
78
154
  if (args.length === 0 || args.includes("--help") || args.includes("-h")) {
@@ -124,80 +200,35 @@ export async function runAnchor(argv, out = (s) => process.stdout.write(`${s}\n`
124
200
  out(usage());
125
201
  return EX_USAGE;
126
202
  }
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)
203
+ const serviceName = serviceNameOf(service);
204
+ const { pending, problems } = pendingAnchors(dir, serviceName);
205
+ if (problems.length > 0) {
206
+ for (const p of problems)
137
207
  out(`anchor: ${p}`);
138
208
  return EX_ANCHOR_FAILED;
139
209
  }
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
210
  if (pending.length === 0) {
143
211
  out(json ? JSON.stringify({ anchored: 0, service: serviceName }) : `nothing to anchor at ${serviceName}`);
144
212
  return 0;
145
213
  }
146
214
  let failed = 0;
147
215
  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)) {
216
+ const got = await registerCheckpoint(serviceName, hash, serviceKey, fetchImpl, now);
217
+ if (!got.ok) {
174
218
  failed += 1;
175
- out(`anchor: ${hash.slice(0, 12)} the service answered with a receipt for another entry, or no receipt`);
219
+ const short = hash.slice(0, 12);
220
+ out(got.reason === "unreachable"
221
+ ? `anchor: ${short} not registered: ${got.message}`
222
+ : got.reason === "wrong-receipt"
223
+ ? `anchor: ${short} ${got.message}`
224
+ : `anchor: ${short} receipt does not verify under --service-key; not kept`);
176
225
  continue;
177
226
  }
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
- };
227
+ const row = got.row;
197
228
  appendAnchor(dir, row);
198
229
  out(json
199
230
  ? JSON.stringify(row)
200
- : `anchored ${hash.slice(0, 12)} at ${serviceName}: leaf ${row.leafIndex} of ${row.treeSize}${serviceKey ? ", receipt verified" : ", receipt not yet checked"}`);
231
+ : `anchored ${hash.slice(0, 12)} at ${serviceName}: leaf ${row.leafIndex} of ${row.treeSize}${got.checked ? ", receipt verified" : ", receipt not yet checked"}`);
201
232
  }
202
233
  return failed === 0 ? 0 : EX_ANCHOR_FAILED;
203
234
  }
@@ -11,7 +11,7 @@ function policyFromSnapshot(stateDir, policyHash) {
11
11
  if (!existsSync(snap))
12
12
  return null;
13
13
  try {
14
- const loaded = loadPolicy(JSON.parse(readFileSync(snap, "utf8")));
14
+ const loaded = loadPolicy(JSON.parse(readFileSync(snap, "utf8")), { unknownKeys: "ignore" });
15
15
  if (loaded.hash !== policyHash)
16
16
  return null;
17
17
  return loaded;
@@ -0,0 +1,2 @@
1
+ /** The published package answers with its own version, not a copy of it. Read once. */
2
+ export declare function bodyVersion(): string;
@@ -0,0 +1,23 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ let cached;
5
+ /** The published package answers with its own version, not a copy of it. Read once. */
6
+ export function bodyVersion() {
7
+ cached ??= readVersion();
8
+ return cached;
9
+ }
10
+ function readVersion() {
11
+ const here = dirname(fileURLToPath(import.meta.url));
12
+ for (const path of [join(here, "..", "package.json"), join(here, "..", "..", "package.json")]) {
13
+ try {
14
+ const raw = JSON.parse(readFileSync(path, "utf8"));
15
+ if (raw.name === "@verax-ai/body" && typeof raw.version === "string")
16
+ return raw.version;
17
+ }
18
+ catch {
19
+ // try the next candidate: the file layout differs between src and dist.
20
+ }
21
+ }
22
+ return "unknown";
23
+ }
package/dist/cli.js CHANGED
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync, realpathSync } from "node:fs";
3
- import path, { dirname, join } from "node:path";
2
+ import { realpathSync } from "node:fs";
3
+ import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { runApprove } from "./approve-cli.js";
6
6
  import { attachBodyLog } from "./body-log.js";
7
+ import { bodyVersion } from "./body-version.js";
7
8
  import { runDemo } from "./demo.js";
8
9
  import { doctorBodyLog, doctorExit, runDoctor } from "./doctor.js";
9
10
  import { clearVeraxEnv, envFileJwksMissing, loadEnvFile, runInitLocal } from "./init-local.js";
@@ -69,21 +70,7 @@ Serving needs VERAX_ISSUER, one of VERAX_JWKS_URL or VERAX_JWKS_FILE, VERAX_AUDI
69
70
  VERAX_STATE_DIR and VERAX_POLICY_FILE; \`verax doctor\` names what is missing.
70
71
  Records stay on this machine, under VERAX_STATE_DIR.
71
72
  `;
72
- function version() {
73
- // The published package answers with its own version, not a copy of it.
74
- const here = dirname(fileURLToPath(import.meta.url));
75
- for (const path of [join(here, "..", "package.json"), join(here, "..", "..", "package.json")]) {
76
- try {
77
- const raw = JSON.parse(readFileSync(path, "utf8"));
78
- if (raw.name === "@verax-ai/body" && typeof raw.version === "string")
79
- return raw.version;
80
- }
81
- catch {
82
- // try the next candidate: the file layout differs between src and dist.
83
- }
84
- }
85
- return "unknown";
86
- }
73
+ const version = bodyVersion;
87
74
  function isCliEntry() {
88
75
  const entry = process.argv[1];
89
76
  if (!entry)
package/dist/demo.js CHANGED
@@ -1,15 +1,15 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { createServer } from "node:http";
4
4
  import { tmpdir } from "node:os";
5
- import { dirname, join } from "node:path";
6
- import { fileURLToPath } from "node:url";
5
+ import { join } from "node:path";
7
6
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
8
7
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
9
8
  import { exportJWK, generateKeyPair, SignJWT } from "jose";
10
9
  import { verifyLedger } from "@verax-ai/proxy";
11
10
  import { runApprove } from "./approve-cli.js";
12
11
  import { listen } from "./server.js";
12
+ import { shippedPolicyPath } from "./shipped-policy.js";
13
13
  const NOT_SHOWN = "Not shown here: data masking arrives with a downstream server such as Conarium; statement reconciliation needs a real statement (verax reconcile).";
14
14
  const NOT_SHOWN_WITH_CONARIUM = "Not shown here: a real database (these are Conarium's sample rows); statement reconciliation needs a real statement (verax reconcile).";
15
15
  const NPX_DOWNLOAD_LINE = "npx will download @conarium-ai/core from npm and run it as a child process; a cold download takes longer.\n";
@@ -37,29 +37,15 @@ function redact(text, token) {
37
37
  return text;
38
38
  return text.split(token).join("[token]");
39
39
  }
40
- function shippedPolicyPath() {
41
- const here = dirname(fileURLToPath(import.meta.url));
42
- let resolved = null;
43
- try {
44
- resolved = join(dirname(fileURLToPath(import.meta.resolve("@verax-ai/proxy/package.json"))), "policy", "default.json");
45
- }
46
- catch {
47
- resolved = null;
48
- }
49
- const candidates = [
50
- resolved,
51
- join(here, "..", "..", "proxy", "policy", "default.json"),
52
- join(here, "..", "..", "@verax-ai", "proxy", "policy", "default.json"),
53
- ];
54
- for (const path of candidates) {
55
- if (path && existsSync(path))
56
- return path;
57
- }
58
- throw new Error("demo: shipped policy file not found");
40
+ function demoPolicyPath() {
41
+ const path = shippedPolicyPath();
42
+ if (path === null)
43
+ throw new Error("demo: shipped policy file not found");
44
+ return path;
59
45
  }
60
46
  /** Shipped default plus message.send egress and a spend rule, written under the temp dir. */
61
47
  function writeDemoPolicy(stateDir, withConarium) {
62
- const shipped = JSON.parse(readFileSync(shippedPolicyPath(), "utf8"));
48
+ const shipped = JSON.parse(readFileSync(demoPolicyPath(), "utf8"));
63
49
  const document = {
64
50
  ...shipped,
65
51
  egress: [EGRESS_HOST],
package/dist/desktop.js CHANGED
@@ -7,7 +7,8 @@ import { fileURLToPath } from "node:url";
7
7
  import { DESKTOP_PARENT_PID } from "./desktop-parent.js";
8
8
  import { defaultExec, foreignAclPrincipals, moduleSearchDirs, posixAclWriterDetail, posixAclWriters, posixOthersCanReplace, readSddlBatch, restrictToOwnerWin32, sddlOwner, systemToolEnv, systemToolPath, toolArgv, trustTargets, windowsDirectorySids, windowsInvokingSid, windowsUserCanWrite, } from "./install.js";
9
9
  import { hasRegisteredOperator } from "./operator-credentials.js";
10
- import { pidAlive, readLockFile } from "./unlock.js";
10
+ import { lockHolderAlive } from "@verax-ai/proxy";
11
+ import { readLockFile } from "./unlock.js";
11
12
  // With VERAX_DESKTOP_TRACE=1 each startup step writes one stderr line with the
12
13
  // milliseconds since this module loaded. Windows CI has waited ~87 s before the
13
14
  // issuer port opened; these lines say which step held it.
@@ -401,7 +402,7 @@ export async function desktopMode(stateDir, bodyPort, listenerPid = loopbackList
401
402
  if (!existsSync(lockPath))
402
403
  return { mode: "spawn" };
403
404
  const lock = readLockFile(lockPath);
404
- if (!lock || !pidAlive(lock.pid))
405
+ if (!lock || !lockHolderAlive(lock))
405
406
  return { mode: "spawn" };
406
407
  const lockPort = lock.port ?? null;
407
408
  if (lockPort === null || lockPort !== bodyPort) {
package/dist/doctor.d.ts CHANGED
@@ -4,7 +4,20 @@ export type DoctorCheck = {
4
4
  level: DoctorLevel;
5
5
  detail: string;
6
6
  };
7
- export declare function runDoctor(env: NodeJS.ProcessEnv, argv: readonly string[]): DoctorCheck[];
7
+ export type DoctorOptions = {
8
+ /** Whether this process is elevated. Asked only when the record key is readable. */
9
+ elevated?: () => boolean;
10
+ /** Whether this user owns the record key. Asked only when the key cannot be opened. */
11
+ keyOwner?: (path: string) => "self" | "other" | "unknown";
12
+ };
13
+ export declare function runDoctor(env: NodeJS.ProcessEnv, argv: readonly string[], opts?: DoctorOptions): DoctorCheck[];
8
14
  /** Last 20 lines of `<stateDir>/body.log`, or a missing-file sentence. */
9
15
  export declare function doctorBodyLog(stateDir: string): string;
16
+ /**
17
+ * The record key signs every decision. If the user running doctor can open
18
+ * it, an agent running as that user can too, and can sign records the body
19
+ * never made. Opening the file is the test, because on Windows only an open
20
+ * reads the ACL. An elevated session is outside the model either way.
21
+ */
22
+ export type KeyOwner = "self" | "other" | "unknown";
10
23
  export declare function doctorExit(checks: readonly DoctorCheck[]): number;
package/dist/doctor.js CHANGED
@@ -1,15 +1,24 @@
1
- import { existsSync, readFileSync, statSync } from "node:fs";
1
+ import { closeSync, existsSync, openSync, readFileSync, statSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
- import { readWindowsMachineRoots, SystemToolError, windowsAgentTokenPath } from "./install.js";
4
+ import { defaultElevated, readWindowsMachineRoots, SystemToolError, windowsAgentTokenPath, windowsFileOwner } from "./install.js";
5
5
  import { readLogTail } from "./body-log.js";
6
6
  import { indexCoverage, listPieceFiles } from "@verax-ai/proxy";
7
7
  import { loadConfig, isLoopbackHost } from "./config.js";
8
8
  import { parseDownstreamDocument } from "./downstream.js";
9
- import { pidAlive, readLockFile } from "./unlock.js";
9
+ import { lockHolderAlive, lockState } from "@verax-ai/proxy";
10
+ import { readLockFile } from "./unlock.js";
11
+ import { pendingAnchors } from "./anchor-cli.js";
12
+ import { readWitnessListen } from "./witness.js";
10
13
  const SECRET_RE = /sk-|-----BEGIN|Bearer |eyJ[A-Za-z0-9_-]{10,}\./;
11
14
  const SECRET_NAME = /^(VERAX_DEV_TOKEN|.*_(TOKEN|SECRET|KEY))$/;
12
- export function runDoctor(env, argv) {
15
+ /**
16
+ * Variables whose name ends like a secret's and whose value is a path to a
17
+ * file holding a public key. The value is still held to SECRET_RE, so key
18
+ * text written there instead of a path is named.
19
+ */
20
+ const PUBLIC_KEY_PATH_NAMES = new Set(["VERAX_ANCHOR_SERVICE_KEY"]);
21
+ export function runDoctor(env, argv, opts = {}) {
13
22
  const checks = [];
14
23
  const issuer = Boolean(env.VERAX_ISSUER?.trim());
15
24
  const jwksUrl = Boolean(env.VERAX_JWKS_URL?.trim());
@@ -93,14 +102,23 @@ export function runDoctor(env, argv) {
93
102
  const lockPath = join(stateDir, "ledger.lock");
94
103
  if (existsSync(lockPath)) {
95
104
  const existing = readLockFile(lockPath);
105
+ // Watched once: a still lock takes five beats to read.
106
+ const state = existing ? lockState(lockPath, existing) : null;
96
107
  if (!existing) {
97
108
  checks.push({ id: "ledger-lock", level: "fail", detail: "ledger.lock is unreadable" });
98
109
  }
99
- else if (existing.pid === process.pid) {
100
- checks.push({ id: "ledger-lock", level: "ok", detail: `ledger.lock is this process (${existing.pid})` });
110
+ else if (state === "quiet") {
111
+ checks.push({
112
+ id: "ledger-lock",
113
+ level: "warn",
114
+ detail: `ledger.lock names live pid ${existing.pid} but has not moved; if no body is running: verax unlock --force ${stateDir}`,
115
+ });
101
116
  }
102
- else if (pidAlive(existing.pid)) {
103
- checks.push({ id: "ledger-lock", level: "warn", detail: `ledger.lock is held by live pid ${existing.pid}` });
117
+ else if (state !== "stale") {
118
+ const own = existing.pid === process.pid;
119
+ checks.push(own
120
+ ? { id: "ledger-lock", level: "ok", detail: `ledger.lock is this process (${existing.pid})` }
121
+ : { id: "ledger-lock", level: "warn", detail: `ledger.lock is held by live pid ${existing.pid}` });
104
122
  }
105
123
  else {
106
124
  checks.push({
@@ -111,9 +129,13 @@ export function runDoctor(env, argv) {
111
129
  }
112
130
  }
113
131
  checks.push(...evidenceChecks(stateDir, env));
132
+ checks.push(...anchorChecks(stateDir, env));
133
+ const custody = keyCustodyCheck(stateDir, env, opts.elevated ?? (() => defaultElevated()), opts.keyOwner ?? defaultKeyOwner);
134
+ if (custody)
135
+ checks.push(custody);
114
136
  }
115
137
  const secretNames = Object.entries(env)
116
- .filter(([k, v]) => Boolean(v) && (SECRET_NAME.test(k) || SECRET_RE.test(String(v))))
138
+ .filter(([k, v]) => Boolean(v) && ((SECRET_NAME.test(k) && !PUBLIC_KEY_PATH_NAMES.has(k)) || SECRET_RE.test(String(v))))
117
139
  .map(([k]) => k);
118
140
  const secretInArgv = argv.some((a) => SECRET_RE.test(a));
119
141
  if (secretInArgv) {
@@ -358,6 +380,67 @@ export function doctorBodyLog(stateDir) {
358
380
  return `body.log missing: ${file}\n`;
359
381
  return tail;
360
382
  }
383
+ /** Whether the user running doctor owns the key file. */
384
+ function defaultKeyOwner(path) {
385
+ if (process.platform === "win32")
386
+ return windowsFileOwner(path);
387
+ try {
388
+ // The effective uid is the one the refused open ran under, and the one a chmod would.
389
+ const uid = process.geteuid?.();
390
+ if (uid === undefined)
391
+ return "unknown";
392
+ return statSync(path).uid === uid ? "self" : "other";
393
+ }
394
+ catch {
395
+ return "unknown";
396
+ }
397
+ }
398
+ function keyCustodyCheck(stateDir, env, elevated, keyOwner) {
399
+ const path = join(stateDir, "keys", "record.private.pem");
400
+ if (!existsSync(path))
401
+ return null;
402
+ try {
403
+ closeSync(openSync(path, "r"));
404
+ }
405
+ catch (err) {
406
+ const code = err.code;
407
+ if (code === "EACCES" || code === "EPERM") {
408
+ // An owner that has shut itself out rewrites the mode or the ACL with one command.
409
+ const owner = keyOwner(path);
410
+ if (owner === "self") {
411
+ return {
412
+ id: "key-custody",
413
+ level: "fail",
414
+ detail: "this user cannot read keys/record.private.pem now but owns it, so an agent running as this user can give itself read again and sign records as the body. " +
415
+ "verax install runs the body under its own account.",
416
+ };
417
+ }
418
+ if (owner === "unknown") {
419
+ return {
420
+ id: "key-custody",
421
+ level: "warn",
422
+ detail: "this user cannot read the body's record key; who owns the file could not be read",
423
+ };
424
+ }
425
+ return { id: "key-custody", level: "ok", detail: "this user cannot read the body's record key" };
426
+ }
427
+ return { id: "key-custody", level: "warn", detail: `record key could not be checked: ${code ?? "error"}` };
428
+ }
429
+ if (elevated()) {
430
+ return {
431
+ id: "key-custody",
432
+ level: "warn",
433
+ detail: "this elevated session can read the body's record key; an administrator is outside the model",
434
+ };
435
+ }
436
+ const local = Boolean(env.VERAX_JWKS_FILE?.trim());
437
+ return {
438
+ id: "key-custody",
439
+ level: "fail",
440
+ detail: `${local ? "local mode: " : ""}this user can read keys/record.private.pem, so an agent running as this user can sign records as the body. ` +
441
+ "That is a way to try Verax, not a boundary; verax install runs the body under its own account.",
442
+ };
443
+ }
361
444
  export function doctorExit(checks) {
362
445
  return checks.some((c) => c.level === "fail") ? 1 : 0;
363
446
  }
@@ -390,6 +473,74 @@ function heartbeatMaxMs(env) {
390
473
  }
391
474
  /** A pulse this far ahead of the clock is still treated as now. */
392
475
  const HEARTBEAT_FUTURE_SKEW_MS = 60_000;
476
+ /**
477
+ * What the running witness was started with, read from its listen file rather
478
+ * than from this shell's environment, which can differ. Checkpoints held only
479
+ * on this host can be removed with the ledger; that is what anchoring is for.
480
+ */
481
+ function anchorChecks(stateDir, env) {
482
+ const listen = readWitnessListen(stateDir);
483
+ const running = listen !== null && lockHolderAlive({ pid: listen.pid, startedAt: listen.startedAt });
484
+ const service = running ? listen.anchorService : undefined;
485
+ if (!running) {
486
+ if (env.VERAX_ANCHOR_SERVICE?.trim()) {
487
+ return [
488
+ {
489
+ id: "anchor",
490
+ level: "warn",
491
+ detail: "VERAX_ANCHOR_SERVICE is set here but no witness is running; only verax witness anchors checkpoints",
492
+ },
493
+ ];
494
+ }
495
+ return [];
496
+ }
497
+ if (!service) {
498
+ return [
499
+ {
500
+ id: "anchor",
501
+ level: "warn",
502
+ detail: "the witness runs without VERAX_ANCHOR_SERVICE; checkpoints stay on this host and can be removed with the ledger",
503
+ },
504
+ ];
505
+ }
506
+ const { pending, problems } = pendingAnchors(stateDir, service);
507
+ if (problems.length > 0) {
508
+ return [{ id: "anchor", level: "fail", detail: `anchors at ${service} cannot be read: ${problems[0]}` }];
509
+ }
510
+ if (pending.length > 0) {
511
+ return [
512
+ {
513
+ id: "anchor",
514
+ level: "warn",
515
+ detail: `${pending.length} checkpoint(s) not yet anchored at ${service}${lastAnchorFailure(stateDir)}`,
516
+ },
517
+ ];
518
+ }
519
+ return [{ id: "anchor", level: "ok", detail: `the witness anchors each checkpoint at ${service}` }];
520
+ }
521
+ function lastAnchorFailure(stateDir) {
522
+ try {
523
+ const lines = readFileSync(join(stateDir, "witness-status.jsonl"), "utf8").split("\n");
524
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
525
+ if (lines[i].trim() === "")
526
+ continue;
527
+ try {
528
+ const row = JSON.parse(lines[i]);
529
+ if (row.result === "anchored")
530
+ return "";
531
+ if (row.result === "anchor-failed")
532
+ return `; last attempt failed: ${String(row.reason ?? "unknown")}`;
533
+ }
534
+ catch {
535
+ // A torn line names nothing.
536
+ }
537
+ }
538
+ }
539
+ catch {
540
+ // No status file: no attempt yet.
541
+ }
542
+ return "";
543
+ }
393
544
  function evidenceChecks(stateDir, env) {
394
545
  const checks = [];
395
546
  let pieces;
@@ -26,6 +26,12 @@ export type DownstreamSpec = {
26
26
  * forbidden on HTTP.
27
27
  */
28
28
  trust?: "same-user";
29
+ /**
30
+ * Child tool names to attach, unprefixed. Only these enter the registry
31
+ * and only these are held to the bounds; a name the child does not offer
32
+ * stops the attach. Absent means every tool the child lists.
33
+ */
34
+ tools?: string[];
29
35
  };
30
36
  export type DownstreamTool = {
31
37
  name: string;