@verax-ai/body 0.8.2 → 0.10.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.
@@ -0,0 +1,213 @@
1
+ import { chmodSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { CANARY_FILE, CANARY_SHAPES, FileLedger, activeCanaryValue, addCanary, CanaryStoreError, listCanaries, retireCanary, tenantKey, } from "@verax-ai/proxy";
4
+ import { memoryQuotaBytes } from "./config.js";
5
+ import { restrictToOwnerWin32 } from "./install.js";
6
+ import { loadOrCreateSigners } from "./keys.js";
7
+ import { memoryStoreFor } from "./memory-store.js";
8
+ const USAGE = `verax canary add [--state <dir>] [--label <text>] [--shape api-key|bearer|password|card]
9
+ verax canary list [--state <dir>]
10
+ verax canary remove [--state <dir>] <id>
11
+ verax canary plant memory [--state <dir>] [--iss <iss>] [--sub <sub>] <id>
12
+ `;
13
+ function parseFlags(argv) {
14
+ const out = { state: null, label: null, shape: null, iss: null, sub: null, rest: [] };
15
+ for (let i = 0; i < argv.length; i += 1) {
16
+ const arg = argv[i];
17
+ if (arg === "--state" || arg === "--label" || arg === "--shape" || arg === "--iss" || arg === "--sub") {
18
+ const value = argv[i + 1];
19
+ if (value === undefined || value.startsWith("-"))
20
+ return { error: `missing value for ${arg}` };
21
+ const key = arg.slice(2);
22
+ if (out[key] !== null)
23
+ return { error: `duplicate ${arg}` };
24
+ out[key] = value;
25
+ i += 1;
26
+ continue;
27
+ }
28
+ if (arg.startsWith("-"))
29
+ return { error: `unknown option: ${arg}` };
30
+ out.rest.push(arg);
31
+ }
32
+ return out;
33
+ }
34
+ function resolveState(flags, env) {
35
+ const dir = (flags.state ?? env.VERAX_STATE_DIR ?? "").trim();
36
+ if (dir === "")
37
+ return { error: "canary: set --state or VERAX_STATE_DIR", code: 78 };
38
+ try {
39
+ if (!statSync(dir).isDirectory())
40
+ return { error: "canary: state path is not a directory", code: 78 };
41
+ }
42
+ catch {
43
+ return { error: "canary: state directory is missing", code: 78 };
44
+ }
45
+ return dir;
46
+ }
47
+ /** POSIX mode 0600. Windows: the current user, Administrators and SYSTEM, as init --local does. */
48
+ function ownerOnly(path) {
49
+ if (process.platform === "win32") {
50
+ restrictToOwnerWin32(path);
51
+ return;
52
+ }
53
+ chmodSync(path, 0o600);
54
+ }
55
+ function asShape(raw) {
56
+ if (raw === null)
57
+ return undefined;
58
+ if (CANARY_SHAPES.includes(raw))
59
+ return raw;
60
+ return "bad";
61
+ }
62
+ function storeForPlant(stateDir) {
63
+ try {
64
+ return memoryStoreFor(stateDir);
65
+ }
66
+ catch (err) {
67
+ if (!(err instanceof Error) || err.message !== "memory-store-unopened")
68
+ throw err;
69
+ const keys = loadOrCreateSigners(stateDir);
70
+ return memoryStoreFor(stateDir, {
71
+ publicKeyPem: keys.recordSigner.publicKeyPem,
72
+ privateKeyPem: keys.recordSigner.privateKeyPem,
73
+ });
74
+ }
75
+ }
76
+ export async function runCanary(argv, stdout, stderr, env) {
77
+ const command = argv[0];
78
+ if (command !== "add" && command !== "list" && command !== "remove" && command !== "plant") {
79
+ stderr.write(USAGE);
80
+ return 64;
81
+ }
82
+ const parsed = parseFlags(argv.slice(1));
83
+ if ("error" in parsed) {
84
+ stderr.write(`${parsed.error}\n`);
85
+ stderr.write(USAGE);
86
+ return 64;
87
+ }
88
+ const state = resolveState(parsed, env);
89
+ if (typeof state !== "string") {
90
+ stderr.write(`${state.error}\n`);
91
+ return state.code;
92
+ }
93
+ try {
94
+ if (command === "add") {
95
+ if (parsed.rest.length !== 0 || parsed.iss !== null || parsed.sub !== null) {
96
+ stderr.write(USAGE);
97
+ return 64;
98
+ }
99
+ const shape = asShape(parsed.shape);
100
+ if (shape === "bad") {
101
+ stderr.write("canary: shape must be api-key, bearer, password or card\n");
102
+ return 64;
103
+ }
104
+ const created = addCanary(state, {
105
+ ...(parsed.label !== null ? { label: parsed.label } : {}),
106
+ ...(shape !== undefined ? { shape } : {}),
107
+ });
108
+ try {
109
+ ownerOnly(join(state, CANARY_FILE));
110
+ }
111
+ catch {
112
+ try {
113
+ retireCanary(state, created.id);
114
+ }
115
+ catch {
116
+ // The value stays in the file. It is not printed.
117
+ }
118
+ stderr.write("canary: owner-only failed\n");
119
+ return 1;
120
+ }
121
+ stdout.write(`${created.id}\n${created.value}\n`);
122
+ return 0;
123
+ }
124
+ if (command === "list") {
125
+ if (parsed.rest.length !== 0 || parsed.label !== null || parsed.shape !== null || parsed.iss !== null || parsed.sub !== null) {
126
+ stderr.write(USAGE);
127
+ return 64;
128
+ }
129
+ stdout.write("id\tlabel\tcreatedAt\tstatus\n");
130
+ for (const row of listCanaries(state)) {
131
+ stdout.write(`${row.id}\t${row.label.replace(/\t/g, " ")}\t${row.createdAt}\t${row.status}\n`);
132
+ }
133
+ return 0;
134
+ }
135
+ if (command === "remove") {
136
+ if (parsed.rest.length !== 1 || parsed.label !== null || parsed.shape !== null || parsed.iss !== null || parsed.sub !== null) {
137
+ stderr.write(USAGE);
138
+ return 64;
139
+ }
140
+ const result = retireCanary(state, parsed.rest[0]);
141
+ if (result === "missing") {
142
+ stderr.write("canary-not-found\n");
143
+ return 1;
144
+ }
145
+ try {
146
+ ownerOnly(join(state, CANARY_FILE));
147
+ }
148
+ catch {
149
+ stderr.write("canary: owner-only failed\n");
150
+ return 1;
151
+ }
152
+ stdout.write(`retired ${parsed.rest[0]}\n`);
153
+ return 0;
154
+ }
155
+ if (parsed.rest.length !== 2 || parsed.rest[0] !== "memory" || parsed.label !== null || parsed.shape !== null) {
156
+ stderr.write(USAGE);
157
+ return 64;
158
+ }
159
+ const id = parsed.rest[1];
160
+ const value = activeCanaryValue(state, id);
161
+ if (value === null) {
162
+ stderr.write("canary-not-found\n");
163
+ return 1;
164
+ }
165
+ let held;
166
+ try {
167
+ held = new FileLedger(state);
168
+ }
169
+ catch (err) {
170
+ const msg = err instanceof Error ? err.message : "";
171
+ if (msg.startsWith("ledger-locked")) {
172
+ stderr.write("canary-plant-body-running\n");
173
+ return 1;
174
+ }
175
+ throw err;
176
+ }
177
+ try {
178
+ const memoryId = `note-${id}`;
179
+ const principal = {
180
+ brain: parsed.sub ?? "local-agent",
181
+ iss: parsed.iss ?? "verax-local",
182
+ scopes: new Set(["verax:read", "verax:memory", "verax:act"]),
183
+ };
184
+ const store = storeForPlant(state);
185
+ const written = await store.put({
186
+ tenantKey: tenantKey(principal),
187
+ id: memoryId,
188
+ body: { title: "staging access", secret: value },
189
+ source: { uri: "note://staging-access", retrievedAtMs: 0 },
190
+ validFromMs: 0,
191
+ validUntilMs: 4_102_444_800_000,
192
+ putRef: `plant-${id}`,
193
+ quotaBytes: memoryQuotaBytes(),
194
+ });
195
+ if (!written.ok) {
196
+ stderr.write(`canary-plant-failed: ${written.error}\n`);
197
+ return 1;
198
+ }
199
+ stdout.write(`planted ${memoryId}\n`);
200
+ return 0;
201
+ }
202
+ finally {
203
+ held.close();
204
+ }
205
+ }
206
+ catch (err) {
207
+ if (err instanceof CanaryStoreError) {
208
+ stderr.write(`${err.message}\n`);
209
+ return 1;
210
+ }
211
+ throw err;
212
+ }
213
+ }
package/dist/cli.js CHANGED
@@ -8,21 +8,26 @@ import { runApprove } from "./approve-cli.js";
8
8
  import { attachBodyLog } from "./body-log.js";
9
9
  import { bodyVersion } from "./body-version.js";
10
10
  import { runDemo } from "./demo.js";
11
- import { doctorBodyLog, doctorExit, runDoctor } from "./doctor.js";
11
+ import { doctorBodyLog, doctorExit, downstreamCredentialChecks, runDoctor } from "./doctor.js";
12
12
  import { runDownstreamPin } from "./downstream-pin.js";
13
13
  import { clearVeraxEnv, envFileJwksMissing, loadEnvFile, runInitLocal } from "./init-local.js";
14
14
  import { clearCliCodeCheckPassed, defaultElevated, directoryAccess, doctorStateTarget, elevatedCommandCodeRefusal, linuxNodeLabelCheck, linuxSelinuxCheck, liveInstalledChecks, markCliCodeCheckPassed, runInstall, runUninstall, SystemToolError, unreadableSentence } from "./install.js";
15
+ import { runExplain } from "./explain-cli.js";
15
16
  import { runHalt, runResume } from "./halt.js";
16
- import { endProcess, main } from "./main.js";
17
+ import { runTaint } from "./taint-cli.js";
18
+ import { main } from "./main.js";
17
19
  import { runOperator } from "./operator-cli.js";
18
20
  import { runAnchor } from "./anchor-cli.js";
19
21
  import { runReconcile } from "./reconcile-cli.js";
22
+ import { runReport } from "./report-cli.js";
20
23
  import { runVerify } from "./verify-cli.js";
21
24
  import { clearStaleLockAtStart, runUnlock } from "./unlock.js";
22
25
  import { runWitness } from "./witness.js";
23
26
  import { runWatch } from "./watch.js";
27
+ import { runCanary } from "./canary-cli.js";
24
28
  import { runMemoryRehead } from "./memory-rehead-cli.js";
25
29
  import { runMemoryReattest } from "./memory-reattest-cli.js";
30
+ import { runPolicy } from "./policy-cli.js";
26
31
  const HELP = `verax - the body an agent asks before it acts, and the ledger it answers from.
27
32
 
28
33
  Usage: verax <command> [options]
@@ -43,7 +48,11 @@ Usage: verax <command> [options]
43
48
  uninstall [--keep-state]
44
49
  stop that body and remove its code. Needs an elevated shell
45
50
  and the same administrator-owned copy.
46
- doctor [--json] check the configuration this process would run with
51
+ doctor [--json] [--env-file <file>]
52
+ check the configuration this process would run with.
53
+ --env-file loads that file the way serve does. An install
54
+ keeps VERAX_DOWNSTREAM in verax.env; doctor does not open
55
+ that file unless this flag names it.
47
56
  downstream pin --file <file> --prefix <prefix>
48
57
  list that child's tools once and, after a typed yes,
49
58
  write a manifest beside the document. The document is not edited.
@@ -62,6 +71,14 @@ Usage: verax <command> [options]
62
71
  reconcile <args> compare the ledger against a statement
63
72
  verify <stateDir> read a ledger back without a body: signatures, chain,
64
73
  effect binding, which key answered, and approval signatures
74
+ report <stateDir> --from <YYYY-MM-DD> --to <YYYY-MM-DD> [--out <file.html>] [--json]
75
+ period counts from the ledger offline: decisions, approvals,
76
+ checkpoints, and the same verification verdict as verify
77
+ policy rehearse --policy <file> [--since <duration>] [--brain <id>] [--json] <stateDir>
78
+ re-evaluate recorded decisions under a policy that is not
79
+ switched on. Writes nothing and runs no tool.
80
+ Exit 0 when no rehearsed decision changes, 1 when a decision changes,
81
+ 2 on usage or a read error.
65
82
  anchor <stateDir> --service <url>
66
83
  register each checkpoint's hash with a transparency service
67
84
  someone else runs and keep its receipt for verify --anchor-key
@@ -69,6 +86,12 @@ Usage: verax <command> [options]
69
86
  watch <stateDir> [--max-silence 30s] [--once] [--on-silence halt|exec] [--exec <command>]
70
87
  halt on silence; --url <https://host/healthz> --token-file <path>
71
88
  reports remotely (remote halt is out of scope)
89
+ explain <stateDir> <ref>
90
+ prints the decision and the reason. When the inputs name
91
+ a taint source, also the source and the rule
92
+ taint clear <stateDir> --session <jti>
93
+ clear that token's session taint. The body signs the
94
+ clear the next time it syncs. A tool call cannot do this.
72
95
  halt <stateDir> stop the body from allowing anything further
73
96
  resume <stateDir> lift a halt; who and when go to halt-history.jsonl
74
97
  unlock [--force] <stateDir> clear a stale ledger lock
@@ -78,6 +101,14 @@ Usage: verax <command> [options]
78
101
  memory rehead <stateDir>
79
102
  write a signed head from the current commit chain.
80
103
  The body must be stopped.
104
+ canary add [--state <dir>] [--label <text>] [--shape api-key|bearer|password|card]
105
+ create a canary and print the value once. State is --state or VERAX_STATE_DIR.
106
+ canary list [--state <dir>]
107
+ ids, labels and creation times. Never the values.
108
+ canary remove [--state <dir>] <id>
109
+ retire one canary. It no longer matches.
110
+ canary plant memory [--state <dir>] [--iss <iss>] [--sub <sub>] <id>
111
+ write that canary into memory as an ordinary note, through the memory store.
81
112
 
82
113
  --help, -h print this
83
114
  --version, -v print the version
@@ -90,10 +121,11 @@ const version = bodyVersion;
90
121
  /**
91
122
  * Left to run, these read a help flag as a path or as an argument: `verax
92
123
  * witness --help` started a witness in a new directory named `--help`. verify,
93
- * anchor and watch print their own usage.
124
+ * report, anchor and watch print their own usage.
94
125
  */
95
126
  const ANSWERED_BY_HELP = new Set([
96
127
  "approve",
128
+ "canary",
97
129
  "demo",
98
130
  "desktop",
99
131
  "doctor",
@@ -334,6 +366,19 @@ async function dispatchCli(argv, stdout, stderr, env) {
334
366
  await new Promise(() => { });
335
367
  }
336
368
  if (argv[0] === "doctor") {
369
+ const fileFlag = argv.indexOf("--env-file");
370
+ if (fileFlag !== -1) {
371
+ const file = argv[fileFlag + 1];
372
+ if (!file || file.startsWith("-")) {
373
+ stderr.write("verax doctor --env-file <file>\n");
374
+ return 78;
375
+ }
376
+ const loaded = loadEnvFile(file, env);
377
+ if (!loaded.ok) {
378
+ stderr.write(`${terminalText(loaded.reason)}\n`);
379
+ return 78;
380
+ }
381
+ }
337
382
  const json = argv.includes("--json");
338
383
  const target = doctorStateTarget(env);
339
384
  if (target && directoryAccess(target) === "unreadable") {
@@ -343,6 +388,7 @@ async function dispatchCli(argv, stdout, stderr, env) {
343
388
  const nodeLabel = process.platform === "linux" ? linuxNodeLabelCheck() : null;
344
389
  const checks = [
345
390
  ...runDoctor(env, process.argv),
391
+ ...(await downstreamCredentialChecks(env)),
346
392
  ...liveInstalledChecks(),
347
393
  ...(process.platform === "linux" ? [linuxSelinuxCheck()] : []),
348
394
  ...(nodeLabel ? [nodeLabel] : []),
@@ -366,6 +412,15 @@ async function dispatchCli(argv, stdout, stderr, env) {
366
412
  if (argv[0] === "verify") {
367
413
  return runVerify(argv.slice(1), (s) => stdout.write(`${s}\n`));
368
414
  }
415
+ if (argv[0] === "explain") {
416
+ return runExplain(argv.slice(1), stdout, stderr);
417
+ }
418
+ if (argv[0] === "taint") {
419
+ return runTaint(argv.slice(1), stdout, stderr);
420
+ }
421
+ if (argv[0] === "report") {
422
+ return runReport(argv.slice(1), (s) => stdout.write(`${s}\n`));
423
+ }
369
424
  if (argv[0] === "anchor") {
370
425
  return runAnchor(argv.slice(1), (s) => stdout.write(`${s}\n`));
371
426
  }
@@ -387,12 +442,18 @@ async function dispatchCli(argv, stdout, stderr, env) {
387
442
  await runWitness(stateDir);
388
443
  return 0;
389
444
  }
445
+ if (argv[0] === "canary") {
446
+ return runCanary(argv.slice(1), stdout, stderr, env);
447
+ }
390
448
  if (argv[0] === "memory") {
391
449
  if (argv[1] === "rehead") {
392
450
  return runMemoryRehead(argv.slice(1), stdout, stderr, env);
393
451
  }
394
452
  return runMemoryReattest(argv.slice(1), stdout, stderr, env);
395
453
  }
454
+ if (argv[0] === "policy") {
455
+ return runPolicy(argv.slice(1), stdout, stderr);
456
+ }
396
457
  const head = argv[0];
397
458
  if (head !== undefined && !head.startsWith("--")) {
398
459
  stderr.write(`unknown command: ${terminalText(head)}\n`);
@@ -489,13 +550,39 @@ export function uncaughtText(err) {
489
550
  }
490
551
  return `${lines.join("\n")}\n`;
491
552
  }
553
+ /**
554
+ * process.exit cuts a pipe after ~146 KB on Linux and macOS when stdout still
555
+ * holds buffered writes. Wait for stdout and stderr to flush, then end with
556
+ * the same code. Long-running commands (serve, watch) never return here.
557
+ */
558
+ function drainStdioStream(stream) {
559
+ return new Promise((resolve) => {
560
+ if (!stream.writable) {
561
+ resolve();
562
+ return;
563
+ }
564
+ try {
565
+ stream.write("", (err) => {
566
+ void err;
567
+ resolve();
568
+ });
569
+ }
570
+ catch {
571
+ resolve();
572
+ }
573
+ });
574
+ }
575
+ async function exitAfterStdioDrain(code) {
576
+ await Promise.all([drainStdioStream(process.stdout), drainStdioStream(process.stderr)]);
577
+ process.exit(code);
578
+ }
492
579
  if (isCliEntry()) {
493
580
  try {
494
- process.exit(await runCli(process.argv.slice(2)));
581
+ await exitAfterStdioDrain(await runCli(process.argv.slice(2)));
495
582
  }
496
583
  catch (err) {
497
584
  // Replaces Node's printer, which would write the path raw and a source excerpt.
498
585
  process.stderr.write(terminalLines(uncaughtText(err)));
499
- endProcess(1);
586
+ await exitAfterStdioDrain(1);
500
587
  }
501
588
  }
package/dist/config.d.ts CHANGED
@@ -15,6 +15,12 @@ export type BodyConfig = {
15
15
  * Loopback binds only.
16
16
  */
17
17
  jwksFile?: string | null;
18
+ /**
19
+ * `verax install` writes `VERAX_INSTALLED=1` into verax.env. The HTTP
20
+ * credential check then refuses. Absent, a JWKS file is local mode and that
21
+ * check only warns.
22
+ */
23
+ installed?: boolean;
18
24
  /**
19
25
  * JWKS captured once at desktop start. Verification uses this set and does
20
26
  * not refetch `jwksUrl`. Null when the body should use the remote set.
package/dist/config.js CHANGED
@@ -223,6 +223,7 @@ export function loadConfig(env) {
223
223
  issuer,
224
224
  jwksUrl,
225
225
  jwksFile: jwksFile === "" ? null : jwksFile,
226
+ installed: env.VERAX_INSTALLED?.trim() === "1",
226
227
  jwksPin,
227
228
  audience,
228
229
  stateDir,
package/dist/demo.js CHANGED
@@ -95,6 +95,9 @@ function writeConariumDownstream(stateDir, child) {
95
95
  args: [...child.args],
96
96
  trust: "same-user",
97
97
  timeoutMs: CONARIUM_TIMEOUT_MS,
98
+ // The operator labelled this demonstration child as neither. An unlabelled
99
+ // child is reads-untrusted and egress, and the second query would be held.
100
+ labels: { query: [], list_tables: [] },
98
101
  };
99
102
  writeFileSync(path, `${JSON.stringify(document, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
100
103
  return path;
package/dist/doctor.d.ts CHANGED
@@ -11,6 +11,17 @@ export type DoctorOptions = {
11
11
  keyOwner?: (path: string) => "self" | "other" | "unknown";
12
12
  };
13
13
  export declare function runDoctor(env: NodeJS.ProcessEnv, argv: readonly string[], opts?: DoctorOptions): DoctorCheck[];
14
+ /**
15
+ * One initialize per HTTP child, with none of its headers. `verax doctor`
16
+ * appends these to `runDoctor`. An acknowledged child is a warning. A child
17
+ * with no credential, or one the probe saw answer, fails
18
+ * `downstream-http-credential-required`. Any other outcome except 401 and
19
+ * 403 fails `downstream-http-credential-undecided`. Local mode, a JWKS file
20
+ * without `VERAX_INSTALLED=1`, only warns. A body with no JWKS file is not
21
+ * local mode. A child that refuses the probe (401 or 403) and carries a
22
+ * header adds nothing. Header values are not written here.
23
+ */
24
+ export declare function downstreamCredentialChecks(env: NodeJS.ProcessEnv): Promise<DoctorCheck[]>;
14
25
  /** Last 20 lines of `<stateDir>/body.log`, or a missing-file sentence. */
15
26
  export declare function doctorBodyLog(stateDir: string): string;
16
27
  /**
package/dist/doctor.js CHANGED
@@ -3,9 +3,10 @@ import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { defaultElevated, readWindowsMachineRoots, SystemToolError, windowsAgentTokenPath, windowsFileOwner } from "./install.js";
5
5
  import { readLogTail } from "./body-log.js";
6
- import { indexCoverage, listPieceFiles } from "@verax-ai/proxy";
6
+ import { indexCoverage, listPieceFiles, loadPolicy, unlabelledDownstreamNames } from "@verax-ai/proxy";
7
7
  import { loadConfig, isLoopbackHost } from "./config.js";
8
- import { parseDownstreamDocument } from "./downstream.js";
8
+ import { resourceMetadataUrl } from "./auth.js";
9
+ import { httpCredentialFinding, httpCredentialIsLocal, parseDownstreamDocument, probeHttpDownstream } from "./downstream.js";
9
10
  import { lockHolderAlive, lockState } from "@verax-ai/proxy";
10
11
  import { readLockFile } from "./unlock.js";
11
12
  import { pendingAnchors } from "./anchor-cli.js";
@@ -36,6 +37,17 @@ export function runDoctor(env, argv, opts = {}) {
36
37
  : "VERAX_ISSUER, VERAX_JWKS_URL, and VERAX_AUDIENCE are set"
37
38
  : "one of VERAX_ISSUER, VERAX_JWKS_URL, VERAX_AUDIENCE is missing",
38
39
  });
40
+ const audienceValue = env.VERAX_AUDIENCE?.trim() ?? "";
41
+ if (audienceValue !== "") {
42
+ const audienceIsUrl = resourceMetadataUrl(audienceValue) !== null;
43
+ checks.push({
44
+ id: "audience-url",
45
+ level: audienceIsUrl ? "ok" : "warn",
46
+ detail: audienceIsUrl
47
+ ? "VERAX_AUDIENCE is an http(s) URL"
48
+ : "VERAX_AUDIENCE is not an http(s) URL: a 401 names no resource metadata, so an MCP client cannot discover the issuer",
49
+ });
50
+ }
39
51
  const loaded = loadConfig({
40
52
  ...env,
41
53
  VERAX_STATE_DIR: env.VERAX_STATE_DIR || "placeholder",
@@ -266,6 +278,31 @@ export function runDoctor(env, argv, opts = {}) {
266
278
  });
267
279
  }
268
280
  }
281
+ let policyLabels = {};
282
+ let unlabelledMode = "both";
283
+ const policyPath = env.VERAX_POLICY_FILE?.trim() ?? "";
284
+ if (policyPath !== "") {
285
+ try {
286
+ const policy = loadPolicy(JSON.parse(readFileSync(policyPath, "utf8")));
287
+ policyLabels = policy.toolLabels ?? {};
288
+ unlabelledMode = policy.unlabelledDownstream ?? "both";
289
+ }
290
+ catch {
291
+ // A policy this process cannot read is already a failed start. Doctor
292
+ // does not invent labels for it.
293
+ }
294
+ }
295
+ for (const name of unlabelledDownstreamNames(specs, policyLabels)) {
296
+ const prefixOnly = !name.includes(".");
297
+ const detail = unlabelledMode === "neither"
298
+ ? prefixOnly
299
+ ? `${name} has no tool list, so a tool it does not label is unlabelled. The policy says an unlabelled downstream tool is neither reads-untrusted nor egress.`
300
+ : `${name} has no reads-untrusted or egress label in the downstream document or the policy`
301
+ : prefixOnly
302
+ ? `${name} has no tool list, so a tool it does not label is unlabelled and is treated as reads-untrusted and egress`
303
+ : `${name} has no label in the downstream document or the policy, so it is treated as reads-untrusted and egress`;
304
+ checks.push({ id: `downstream-unlabelled:${name}`, level: "warn", detail });
305
+ }
269
306
  }
270
307
  catch (err) {
271
308
  checks.push({
@@ -278,6 +315,55 @@ export function runDoctor(env, argv, opts = {}) {
278
315
  checks.push(...jwksFileChecks(env, stateDir));
279
316
  return checks;
280
317
  }
318
+ /**
319
+ * One initialize per HTTP child, with none of its headers. `verax doctor`
320
+ * appends these to `runDoctor`. An acknowledged child is a warning. A child
321
+ * with no credential, or one the probe saw answer, fails
322
+ * `downstream-http-credential-required`. Any other outcome except 401 and
323
+ * 403 fails `downstream-http-credential-undecided`. Local mode, a JWKS file
324
+ * without `VERAX_INSTALLED=1`, only warns. A body with no JWKS file is not
325
+ * local mode. A child that refuses the probe (401 or 403) and carries a
326
+ * header adds nothing. Header values are not written here.
327
+ */
328
+ export async function downstreamCredentialChecks(env) {
329
+ const downstreamPath = env.VERAX_DOWNSTREAM?.trim() ?? "";
330
+ if (downstreamPath === "")
331
+ return [];
332
+ let specs;
333
+ try {
334
+ specs = parseDownstreamDocument(readFileSync(downstreamPath, "utf8"));
335
+ }
336
+ catch {
337
+ return [];
338
+ }
339
+ const local = httpCredentialIsLocal({
340
+ jwksFile: env.VERAX_JWKS_FILE,
341
+ installed: env.VERAX_INSTALLED?.trim() === "1",
342
+ });
343
+ const checks = [];
344
+ for (const spec of specs) {
345
+ if (spec.url === undefined)
346
+ continue;
347
+ const outcome = await probeHttpDownstream(spec);
348
+ if (spec.unauthenticated === "acknowledged") {
349
+ checks.push({
350
+ id: `downstream-http-unauthenticated:${spec.prefix}`,
351
+ level: "warn",
352
+ detail: `child ${spec.prefix} is acknowledged as unauthenticated. An agent that can reach it can call it with no decision record.`,
353
+ });
354
+ continue;
355
+ }
356
+ const finding = httpCredentialFinding(spec, outcome);
357
+ if (!finding)
358
+ continue;
359
+ checks.push({
360
+ id: finding.id,
361
+ level: local ? "warn" : "fail",
362
+ detail: finding.detail,
363
+ });
364
+ }
365
+ return checks;
366
+ }
281
367
  function commandBase(command) {
282
368
  const slash = Math.max(command.lastIndexOf("/"), command.lastIndexOf("\\"));
283
369
  const base = (slash === -1 ? command : command.slice(slash + 1)).toLowerCase();
@@ -130,6 +130,10 @@ function showDifference(out, spec, tools, docDir) {
130
130
  if (rec.prefix !== spec.prefix) {
131
131
  say(out, escapeLine(`manifest prefix differs from ${spec.prefix}`));
132
132
  }
133
+ const manifestAck = rec.unauthenticated === "acknowledged" ? "acknowledged" : null;
134
+ if (manifestAck !== (spec.unauthenticated ?? null)) {
135
+ say(out, escapeLine("manifest acknowledgement differs from the document"));
136
+ }
133
137
  try {
134
138
  if (canonical(rec.selected ?? null) !== canonical(spec.tools ?? null)) {
135
139
  say(out, escapeLine("manifest selection differs from the document"));
@@ -255,7 +259,13 @@ export async function runDownstreamPin(input, io) {
255
259
  }
256
260
  if (answer !== "yes")
257
261
  return 1;
258
- const manifest = { v: 1, prefix: spec.prefix, selected: spec.tools ?? null, tools };
262
+ const manifest = {
263
+ v: 1,
264
+ prefix: spec.prefix,
265
+ selected: spec.tools ?? null,
266
+ tools,
267
+ ...(spec.unauthenticated === "acknowledged" ? { unauthenticated: "acknowledged" } : {}),
268
+ };
259
269
  let written;
260
270
  try {
261
271
  written = writeManifest(dirname(input.file), manifest);