@verax-ai/body 0.9.0 → 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,512 @@
1
+ import { lstatSync, readFileSync } from "node:fs";
2
+ import { join, relative } from "node:path";
3
+ import { listPieceFiles, loadPolicy, sha256Canonical, } from "@verax-ai/proxy";
4
+ /**
5
+ * Read a ledger and say what a different policy would have decided.
6
+ * The state directory is only read. No tool is called.
7
+ */
8
+ export class PolicyRehearsalError extends Error {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = "PolicyRehearsalError";
12
+ }
13
+ }
14
+ export const ARGUMENT_REASON = "the rule reads arguments the record does not keep";
15
+ const TEXT_REASON = "the policy reads argument text the record does not keep";
16
+ const COUNTER_REASON = "the policy's rate or daily limit depends on counters the record does not keep";
17
+ const DISK_REASON = "the policy's disk limit depends on free space the record does not keep";
18
+ const DEPTH_REASON = "the policy's data-class depth check depends on arguments the record does not keep";
19
+ const TIME_REASON = "the record's timestamp is outside -8.64e15..8.64e15";
20
+ const SNAPSHOT_REASON = "the recorded policy snapshot is missing or unreadable, so the disk limit cannot be compared";
21
+ const TENANT_GATE_REASON = "the tenant gate can still refuse memory.get or audit.explain with tenant-mismatch, and it reads arguments the record does not keep";
22
+ /** `Date` throws outside this. A record past it is not rehearsable. */
23
+ const TIME_LIMIT_MS = 8.64e15;
24
+ const RULES_WITHOUT_AN_ID = new Set(["no-rule", "spend-not-wired", "inputs-required"]);
25
+ const POLICY_REASONS = new Set([
26
+ "allow",
27
+ "no-rule",
28
+ "scope-missing",
29
+ "approval-required",
30
+ "inputs-required",
31
+ "spend-not-wired",
32
+ "spend-args-invalid",
33
+ "spend-currency",
34
+ "spend-cap",
35
+ "spend-payee",
36
+ "spend-daily",
37
+ "egress-host-missing",
38
+ "egress-blocked",
39
+ ]);
40
+ const PROBES = [
41
+ {},
42
+ { amountMinor: 1, currency: "USD", payee: "payee", reference: "ref" },
43
+ { to: "user@example.com" },
44
+ ];
45
+ const HASH_RE = /^[0-9a-f]{64}$/;
46
+ function word(decision) {
47
+ return decision === "defer" ? "held" : decision;
48
+ }
49
+ function outsidePolicy(reason) {
50
+ if (reason === "halted")
51
+ return "a halt is not a policy decision";
52
+ if (reason === "ledger-disk-low")
53
+ return "a disk refusal depends on free space the record does not keep";
54
+ if (reason === "rate-limited" || reason === "daily-limited") {
55
+ return "a rate or daily refusal depends on counters the record does not keep";
56
+ }
57
+ if (reason === "tenant-mismatch")
58
+ return "a tenant refusal depends on stored rows the record does not keep";
59
+ if (reason === "approved-by-operator")
60
+ return "an operator approval is not a policy decision";
61
+ if (reason === "input-invalid") {
62
+ return "the call's declared inputs were refused, and the record does not keep the declaration";
63
+ }
64
+ if (reason === "outcome-unknown")
65
+ return "an outcome-unknown decision depends on a run mark the record does not keep";
66
+ if (reason === "ref-reuse" || reason === "ref-invalid") {
67
+ return "the decision depends on the ref, which a policy rehearsal does not re-check";
68
+ }
69
+ if (reason === "expired")
70
+ return "an expiry is the approval clock, not a policy re-evaluation of the call";
71
+ if (reason === "spend-reauth-required") {
72
+ return "a spend re-authorisation depends on an earlier allow, not a new policy verdict";
73
+ }
74
+ if (reason === "operator-halt" || reason === "operator-resume" || reason === "halt-history-mismatch") {
75
+ return "the record is a control event, not a tool call";
76
+ }
77
+ if (reason === "token-revoked" || reason === "revoke-removed") {
78
+ return "the record is a token revocation, not a tool call";
79
+ }
80
+ if (reason === "passkey-removed" || reason === "passkey-removal-undone") {
81
+ return "the record is an operator-removal event, not a tool call";
82
+ }
83
+ if (reason.startsWith("data-class-") || reason.startsWith("file-type-")) {
84
+ return "the record keeps class counts, not the argument text";
85
+ }
86
+ if (reason.startsWith("result-class")) {
87
+ return "the record is about a tool result, and it keeps counts and a hash, not the result text";
88
+ }
89
+ return "the record's reason is not a policy decision, and a rehearsal does not guess what produced it";
90
+ }
91
+ function argumentTextMatters(policy, tool) {
92
+ const cfg = policy.dataClasses;
93
+ if (!cfg)
94
+ return false;
95
+ const choices = { ...cfg.document, ...(cfg.byTool[tool] ?? {}) };
96
+ for (const choice of Object.values(choices)) {
97
+ if (choice === "mask" || choice === "block" || choice === "local")
98
+ return true;
99
+ }
100
+ return cfg.blockedFileTypes.length > 0;
101
+ }
102
+ /**
103
+ * evaluate() reads arguments only for spend and for an egress host. Two probes
104
+ * that would take those branches differently mean the verdict depends on
105
+ * argument values. Those values are not on the record, so the verdict is not
106
+ * used. When every probe agrees, the verdict does not depend on them.
107
+ */
108
+ function probed(policy, tool, principal) {
109
+ let first;
110
+ for (const args of PROBES) {
111
+ const verdict = policy.evaluate({ name: tool, arguments: args }, principal);
112
+ if (!first) {
113
+ first = verdict;
114
+ continue;
115
+ }
116
+ if (verdict.decision !== first.decision || verdict.reasonCode !== first.reasonCode || verdict.rule !== first.rule) {
117
+ return "arguments";
118
+ }
119
+ }
120
+ if (!first || !wordOrNull(first.decision))
121
+ return "arguments";
122
+ return { decision: first.decision, reasonCode: first.reasonCode, rule: first.rule };
123
+ }
124
+ function wordOrNull(decision) {
125
+ return decision === "allow" || decision === "deny" || decision === "defer";
126
+ }
127
+ function verdictOf(loaded, tool, principal, declared) {
128
+ if (loaded.policy.requireInputs === true && declared.length === 0) {
129
+ return { ok: true, verdict: { decision: "deny", reasonCode: "inputs-required", rule: null } };
130
+ }
131
+ const found = probed(loaded.policy, tool, principal);
132
+ if (found === "arguments")
133
+ return { ok: false, reason: ARGUMENT_REASON };
134
+ if (found.decision === "allow" || found.decision === "defer") {
135
+ if (loaded.policy.limits.ratePerMinute !== undefined || loaded.policy.limits.dailyMax !== undefined) {
136
+ return { ok: false, reason: COUNTER_REASON };
137
+ }
138
+ if (argumentTextMatters(loaded.policy, tool))
139
+ return { ok: false, reason: TEXT_REASON };
140
+ }
141
+ return { ok: true, verdict: found };
142
+ }
143
+ function oldRuleOf(snapshot, tool, reasonCode) {
144
+ if (RULES_WITHOUT_AN_ID.has(reasonCode))
145
+ return null;
146
+ const raw = snapshot.raw;
147
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
148
+ return null;
149
+ const rules = raw.rules;
150
+ if (!Array.isArray(rules))
151
+ return null;
152
+ let found = null;
153
+ for (const rule of rules) {
154
+ if (rule === null || typeof rule !== "object" || Array.isArray(rule))
155
+ continue;
156
+ const rec = rule;
157
+ if (rec.tool !== tool)
158
+ continue;
159
+ if (typeof rec.id !== "string" || rec.id === "")
160
+ return null;
161
+ if (found !== null)
162
+ return null;
163
+ found = rec.id;
164
+ }
165
+ return found;
166
+ }
167
+ function brainOf(inputs) {
168
+ if (!inputs)
169
+ return undefined;
170
+ const principal = inputs.principal;
171
+ if (principal === null || typeof principal !== "object" || Array.isArray(principal))
172
+ return undefined;
173
+ const brain = principal.brain;
174
+ return typeof brain === "string" ? brain : undefined;
175
+ }
176
+ function markerReason(inputs) {
177
+ if (inputs.control !== undefined)
178
+ return "the record is a control event, not a tool call";
179
+ if (inputs.revoke !== undefined)
180
+ return "the record is a token revocation, not a tool call";
181
+ if (inputs.operatorRemoval !== undefined)
182
+ return "the record is an operator-removal event, not a tool call";
183
+ if (inputs.resultOf !== undefined) {
184
+ return "the record is about a tool result, and it keeps counts and a hash, not the result text";
185
+ }
186
+ if (inputs.approver !== undefined)
187
+ return "an operator approval is not a policy decision";
188
+ return null;
189
+ }
190
+ function principalOf(inputs) {
191
+ const principal = inputs.principal;
192
+ if (principal === null || typeof principal !== "object" || Array.isArray(principal)) {
193
+ return "the inputs row does not keep a principal";
194
+ }
195
+ const rec = principal;
196
+ if (typeof rec.brain !== "string")
197
+ return "the inputs row does not keep a brain";
198
+ if (!Array.isArray(rec.scopes) || rec.scopes.some((scope) => typeof scope !== "string")) {
199
+ return "the inputs row does not keep scopes";
200
+ }
201
+ return {
202
+ brain: rec.brain,
203
+ scopes: new Set(rec.scopes),
204
+ ...(typeof rec.iss === "string" ? { iss: rec.iss } : {}),
205
+ ...(typeof rec.tenant === "string" ? { tenant: rec.tenant } : {}),
206
+ ...(typeof rec.org === "string" ? { org: rec.org } : {}),
207
+ };
208
+ }
209
+ function labelOf(stateDir, path) {
210
+ return relative(stateDir, path).replaceAll("\\", "/");
211
+ }
212
+ function readFile(path, label) {
213
+ let st;
214
+ try {
215
+ st = lstatSync(path);
216
+ }
217
+ catch (err) {
218
+ if (err.code === "ENOENT")
219
+ return null;
220
+ throw new PolicyRehearsalError(`cannot read ${label}`);
221
+ }
222
+ if (st.isSymbolicLink())
223
+ throw new PolicyRehearsalError(`symbolic link: ${label}`);
224
+ if (!st.isFile())
225
+ throw new PolicyRehearsalError(`not a file: ${label}`);
226
+ try {
227
+ return readFileSync(path, "utf8");
228
+ }
229
+ catch {
230
+ throw new PolicyRehearsalError(`cannot read ${label}`);
231
+ }
232
+ }
233
+ function parseJsonl(text, label) {
234
+ const rows = [];
235
+ const lines = text.split("\n");
236
+ for (let i = 0; i < lines.length; i += 1) {
237
+ const line = lines[i].trim();
238
+ if (line === "")
239
+ continue;
240
+ try {
241
+ rows.push(JSON.parse(line));
242
+ }
243
+ catch {
244
+ throw new PolicyRehearsalError(`${label}:${i + 1}: not JSON`);
245
+ }
246
+ }
247
+ return rows;
248
+ }
249
+ function ledgerFiles(stateDir) {
250
+ const manifestPath = join(stateDir, "ledger-manifest.json");
251
+ const manifestText = readFile(manifestPath, "ledger-manifest.json");
252
+ if (manifestText === null) {
253
+ return {
254
+ decisions: [{ label: "decisions.jsonl", path: join(stateDir, "decisions.jsonl") }],
255
+ inputs: [{ label: "inputs.jsonl", path: join(stateDir, "inputs.jsonl") }],
256
+ };
257
+ }
258
+ let pieces;
259
+ try {
260
+ pieces = listPieceFiles(stateDir);
261
+ }
262
+ catch (err) {
263
+ throw new PolicyRehearsalError(err instanceof Error ? err.message : "ledger manifest cannot be read");
264
+ }
265
+ return {
266
+ decisions: pieces.map((piece) => ({ label: labelOf(stateDir, piece.decisions), path: piece.decisions })),
267
+ inputs: pieces.map((piece) => ({ label: labelOf(stateDir, piece.inputs), path: piece.inputs })),
268
+ };
269
+ }
270
+ function readLedger(stateDir) {
271
+ let st;
272
+ try {
273
+ st = lstatSync(stateDir);
274
+ }
275
+ catch {
276
+ throw new PolicyRehearsalError("cannot read state directory");
277
+ }
278
+ if (st.isSymbolicLink())
279
+ throw new PolicyRehearsalError("symbolic link: state directory");
280
+ if (!st.isDirectory())
281
+ throw new PolicyRehearsalError("not a directory");
282
+ const files = ledgerFiles(stateDir);
283
+ const decisions = [];
284
+ let sawDecisionFile = false;
285
+ for (const file of files.decisions) {
286
+ const text = readFile(file.path, file.label);
287
+ if (text === null) {
288
+ if (file.label === "decisions.jsonl")
289
+ throw new PolicyRehearsalError("no decisions file");
290
+ throw new PolicyRehearsalError(`missing piece: ${file.label}`);
291
+ }
292
+ sawDecisionFile = true;
293
+ const rows = parseJsonl(text, file.label);
294
+ for (let i = 0; i < rows.length; i += 1) {
295
+ const row = rows[i];
296
+ if (row === null || typeof row !== "object" || Array.isArray(row)) {
297
+ throw new PolicyRehearsalError(`${file.label}:${i + 1}: not a decision`);
298
+ }
299
+ const claims = row.claims;
300
+ if (claims === null || typeof claims !== "object" || Array.isArray(claims)) {
301
+ throw new PolicyRehearsalError(`${file.label}:${i + 1}: not a decision`);
302
+ }
303
+ decisions.push({ label: file.label, line: i + 1, claims: claims });
304
+ }
305
+ }
306
+ if (!sawDecisionFile)
307
+ throw new PolicyRehearsalError("no decisions file");
308
+ const inputs = new Map();
309
+ for (const file of files.inputs) {
310
+ const text = readFile(file.path, file.label);
311
+ if (text === null)
312
+ continue;
313
+ for (const row of parseJsonl(text, file.label)) {
314
+ if (row === null || typeof row !== "object" || Array.isArray(row)) {
315
+ throw new PolicyRehearsalError(`${file.label}: not an inputs row`);
316
+ }
317
+ const rec = row;
318
+ if (typeof rec.ref !== "string" || rec.inputs === null || typeof rec.inputs !== "object" || Array.isArray(rec.inputs)) {
319
+ throw new PolicyRehearsalError(`${file.label}: not an inputs row`);
320
+ }
321
+ const body = rec.inputs;
322
+ inputs.set(`${rec.ref}\0${sha256Canonical(body)}`, body);
323
+ }
324
+ }
325
+ return { decisions, inputs };
326
+ }
327
+ function loadSnapshot(stateDir, hash) {
328
+ if (typeof hash !== "string" || !HASH_RE.test(hash))
329
+ return null;
330
+ const path = join(stateDir, "policies", `${hash}.json`);
331
+ const text = readFile(path, `policies/${hash}.json`);
332
+ if (text === null)
333
+ return null;
334
+ let raw;
335
+ try {
336
+ raw = JSON.parse(text);
337
+ }
338
+ catch {
339
+ return null;
340
+ }
341
+ try {
342
+ const policy = loadPolicy(raw, { unknownKeys: "ignore" });
343
+ if (policy.hash !== hash)
344
+ return null;
345
+ return { policy, raw };
346
+ }
347
+ catch {
348
+ return null;
349
+ }
350
+ }
351
+ function timeOf(ts) {
352
+ if (ts === null || Math.abs(ts) > TIME_LIMIT_MS)
353
+ return null;
354
+ return new Date(ts).toISOString();
355
+ }
356
+ function sortedCounts(counts) {
357
+ const out = {};
358
+ for (const key of [...counts.keys()].sort())
359
+ out[key] = counts.get(key);
360
+ return out;
361
+ }
362
+ export function rehearsePolicy(stateDir, policy, opts = {}) {
363
+ const ledger = readLedger(stateDir);
364
+ const next = { policy, raw: null };
365
+ const snapshots = new Map();
366
+ const changed = [];
367
+ const skipped = [];
368
+ const pairs = new Map();
369
+ let unchanged = 0;
370
+ const snapshotFor = (hash) => {
371
+ const key = typeof hash === "string" ? hash : "";
372
+ if (snapshots.has(key))
373
+ return snapshots.get(key) ?? null;
374
+ const loaded = loadSnapshot(stateDir, hash);
375
+ snapshots.set(key, loaded);
376
+ return loaded;
377
+ };
378
+ for (const row of ledger.decisions) {
379
+ const claims = row.claims;
380
+ const ts = typeof claims.timestampMs === "number" && Number.isFinite(claims.timestampMs) ? claims.timestampMs : null;
381
+ if (opts.notBeforeMs !== undefined && (ts === null || ts < opts.notBeforeMs))
382
+ continue;
383
+ const id = typeof claims.ref === "string" && claims.ref !== "" ? claims.ref : `${row.label}:${row.line}`;
384
+ const inputsHash = typeof claims.inputsHash === "string" ? claims.inputsHash : null;
385
+ const inputs = typeof claims.ref === "string" && inputsHash ? ledger.inputs.get(`${claims.ref}\0${inputsHash}`) : undefined;
386
+ if (opts.brain !== undefined && brainOf(inputs) !== opts.brain)
387
+ continue;
388
+ const skip = (reason) => {
389
+ skipped.push({
390
+ id,
391
+ time: timeOf(ts),
392
+ brain: brainOf(inputs) ?? null,
393
+ tool: typeof claims.subject === "string" ? claims.subject : null,
394
+ reason,
395
+ });
396
+ };
397
+ if (ts === null) {
398
+ skip("the record has no timestamp");
399
+ continue;
400
+ }
401
+ if (Math.abs(ts) > TIME_LIMIT_MS) {
402
+ skip(TIME_REASON);
403
+ continue;
404
+ }
405
+ if (typeof claims.ref !== "string" || claims.ref === "") {
406
+ skip("the record has no ref");
407
+ continue;
408
+ }
409
+ if (inputsHash === null) {
410
+ skip("the record has no inputsHash");
411
+ continue;
412
+ }
413
+ if (!inputs) {
414
+ skip("no inputs row matches the record");
415
+ continue;
416
+ }
417
+ const marked = markerReason(inputs);
418
+ if (marked) {
419
+ skip(marked);
420
+ continue;
421
+ }
422
+ const recordedDecision = typeof claims.decision === "string" ? claims.decision : "";
423
+ const recordedReason = typeof claims.reasonCode === "string" ? claims.reasonCode : "";
424
+ if (!wordOrNull(recordedDecision)) {
425
+ skip("the record's decision is not allow, deny or held");
426
+ continue;
427
+ }
428
+ if (!POLICY_REASONS.has(recordedReason)) {
429
+ skip(outsidePolicy(recordedReason));
430
+ continue;
431
+ }
432
+ if (typeof claims.subject !== "string" || claims.subject === "") {
433
+ skip("the record does not keep a tool name");
434
+ continue;
435
+ }
436
+ const principal = principalOf(inputs);
437
+ if (typeof principal === "string") {
438
+ skip(principal);
439
+ continue;
440
+ }
441
+ if (!Array.isArray(inputs.inputs)) {
442
+ skip("the inputs row does not keep the declared inputs");
443
+ continue;
444
+ }
445
+ // The policy that wrote the record is the one under rehearsal. The
446
+ // decision stands: re-evaluating it would call a rate limit, a missing
447
+ // argument or a depth check "not rehearsable".
448
+ if (typeof claims.policyHash === "string" && claims.policyHash === policy.hash) {
449
+ unchanged += 1;
450
+ continue;
451
+ }
452
+ const rehearsed = verdictOf(next, claims.subject, principal, inputs.inputs);
453
+ if (!rehearsed.ok) {
454
+ skip(rehearsed.reason);
455
+ continue;
456
+ }
457
+ const prior = snapshotFor(claims.policyHash);
458
+ // The proxy checks free space, then argument depth, before any rule
459
+ // (proxy.ts, the disk check and the depth check). Neither value is on
460
+ // the record. When the check would refuse or cannot be reproduced, the
461
+ // rehearsal does not name a rule. A missing snapshot still lets a deny
462
+ // through: the old limit cannot be compared, and that gap is separate.
463
+ if (prior !== null && next.policy.limits.diskFreeBytes > prior.policy.limits.diskFreeBytes) {
464
+ skip(DISK_REASON);
465
+ continue;
466
+ }
467
+ if (next.policy.dataClasses !== undefined) {
468
+ skip(DEPTH_REASON);
469
+ continue;
470
+ }
471
+ const open = rehearsed.verdict.decision === "allow" || rehearsed.verdict.decision === "defer";
472
+ if (open &&
473
+ recordedDecision === "deny" &&
474
+ (claims.subject === "memory.get" || claims.subject === "audit.explain")) {
475
+ skip(TENANT_GATE_REASON);
476
+ continue;
477
+ }
478
+ if (open && prior === null) {
479
+ skip(SNAPSHOT_REASON);
480
+ continue;
481
+ }
482
+ const oldRule = prior ? oldRuleOf(prior, claims.subject, recordedReason) : null;
483
+ const from = word(recordedDecision);
484
+ const to = word(rehearsed.verdict.decision);
485
+ if (from === to) {
486
+ unchanged += 1;
487
+ continue;
488
+ }
489
+ const pair = `${from} -> ${to}`;
490
+ pairs.set(pair, (pairs.get(pair) ?? 0) + 1);
491
+ changed.push({
492
+ id,
493
+ time: timeOf(ts),
494
+ brain: principal.brain,
495
+ tool: claims.subject,
496
+ from,
497
+ rule: oldRule,
498
+ to,
499
+ newRule: rehearsed.verdict.rule,
500
+ });
501
+ }
502
+ const reasons = new Map();
503
+ for (const row of skipped)
504
+ reasons.set(row.reason, (reasons.get(row.reason) ?? 0) + 1);
505
+ return {
506
+ unchanged,
507
+ changes: sortedCounts(pairs),
508
+ notRehearsable: sortedCounts(reasons),
509
+ changed,
510
+ skipped,
511
+ };
512
+ }
package/dist/server.js CHANGED
@@ -25,7 +25,7 @@ import { copyDefinition } from "./definitions.js";
25
25
  import { recordBodyStart, startHeartbeat } from "./heartbeat.js";
26
26
  import { inventoryHealth, readInventoryFile } from "./inventory-file.js";
27
27
  import { createBodyServices, TOOL_NAMES } from "./wiring.js";
28
- import { openDownstream, parseDownstreamDocument, } from "./downstream.js";
28
+ import { httpCredentialFinding, httpCredentialIsLocal, openDownstream, parseDownstreamDocument, probeHttpDownstream, } from "./downstream.js";
29
29
  // What a brain reads before it calls. Each description says what the tool is
30
30
  // for, what it does and does not do, what the gate may answer, and what comes
31
31
  // back; each parameter says its format and its bounds. The answers named here
@@ -119,7 +119,8 @@ export const TOOL_META = [
119
119
  name: "message.read",
120
120
  description: "Reads this tenant's inbox, the messages placed for it in the body's state directory on this machine, and returns them as a JSON array in arrival order, oldest first. " +
121
121
  "Use it to see what has arrived before deciding what to answer. " +
122
- "Takes no arguments; read-only; the call is recorded like every other. An empty or absent inbox answers [].",
122
+ "Takes no arguments; read-only; the call is recorded like every other. An empty or absent inbox answers []. " +
123
+ "After this call returns, this token's session is tainted: a later message.send or spend is held for an operator until the operator clears the taint.",
123
124
  inputSchema: {
124
125
  type: "object",
125
126
  additionalProperties: false,
@@ -133,6 +134,7 @@ export const TOOL_META = [
133
134
  "Like every call it passes the policy gate and leaves a signed decision record. " +
134
135
  "The gate reads the host after the last '@' in to and allows it only when it is on the policy's egress allow-list; otherwise the call is refused with denied:egress-blocked, or denied:egress-host-missing when no host can be read. " +
135
136
  "A policy rule in approve mode holds the call for an operator instead and answers deferred:approval-required:<ref>. " +
137
+ "If this token's session is tainted, the call is held for an operator even when this rule would allow it. " +
136
138
  "Returns {queued: true, ref}, where ref is the decision reference for audit.explain.",
137
139
  inputSchema: {
138
140
  type: "object",
@@ -154,7 +156,8 @@ export const TOOL_META = [
154
156
  "Use it before any payment so that amount, currency, payee and reference are checked against the policy: the one currency the policy names, a cap per call, a payee list and a daily limit. " +
155
157
  "A call outside those bounds is refused with a signed deny naming the bound: denied:spend-cap, denied:spend-payee, denied:spend-currency or denied:spend-daily. " +
156
158
  "A call within them is held for an operator on this machine and answers deferred:approval-required:<ref>; once that ref is approved (verax approve, or the panel), resending the same call with the same _ref answers allowed:<ref>, and the authorization is recorded as {authorized: true, ref, amountMinor, currency, payee, reference}. " +
157
- "Without a spend rule in the policy every call answers denied:spend-not-wired.",
159
+ "Without a spend rule in the policy every call answers denied:spend-not-wired. " +
160
+ "If this token's session is tainted, the hold still names the call that tainted it.",
158
161
  inputSchema: {
159
162
  type: "object",
160
163
  additionalProperties: false,
@@ -329,7 +332,7 @@ function downstreamPublic(sessions, specs) {
329
332
  * closes the ones already open and throws: a half-attached body would serve a
330
333
  * tool list its operator never wrote.
331
334
  */
332
- async function attachDownstream(file, bodyPublicKeyPems) {
335
+ async function attachDownstream(file, bodyPublicKeyPems, opts) {
333
336
  if (file === null || file.trim() === "")
334
337
  return { sessions: [], specs: [] };
335
338
  let text;
@@ -346,6 +349,19 @@ async function attachDownstream(file, bodyPublicKeyPems) {
346
349
  try {
347
350
  // The manifest sits beside the operator's document. An installed body
348
351
  // cannot write the state directory, so the pin is read from here.
352
+ // Local mode is not a boundary: the same finding is one stderr line
353
+ // here and a doctor warning. `installed` is VERAX_INSTALLED, which
354
+ // `verax install` writes. A JWKS file without that line is local mode.
355
+ // A body with no JWKS file is not.
356
+ if (spec.url !== undefined) {
357
+ const finding = httpCredentialFinding(spec, await probeHttpDownstream(spec));
358
+ if (finding) {
359
+ if (opts.local)
360
+ process.stderr.write(`verax-body: ${terminalText(spec.prefix)}: ${terminalText(finding.id)}\n`);
361
+ else
362
+ throw new Error(finding.id);
363
+ }
364
+ }
349
365
  sessions.push(await openDownstream(spec, { definitionsDir: dirname(file) }));
350
366
  }
351
367
  catch (err) {
@@ -377,6 +393,18 @@ function definitionsForStart(stateDir, definitionsDir, specs) {
377
393
  }
378
394
  return downstream;
379
395
  }
396
+ /** Prefixed names the downstream document labelled, including an empty list. */
397
+ function downstreamLabelArgs(specs) {
398
+ const downstreamLabels = {};
399
+ for (const spec of specs) {
400
+ if (!spec.labels)
401
+ continue;
402
+ for (const [child, labels] of Object.entries(spec.labels)) {
403
+ downstreamLabels[`${spec.prefix}.${child}`] = labels;
404
+ }
405
+ }
406
+ return Object.keys(downstreamLabels).length > 0 ? { downstreamLabels } : {};
407
+ }
380
408
  export async function listen(config) {
381
409
  if (config.alarmWebhookUrl)
382
410
  assertAlarmWebhookUrl(config.alarmWebhookUrl);
@@ -395,7 +423,9 @@ export async function listen(config) {
395
423
  // The children are attached before the door opens. A named document the body
396
424
  // cannot honour stops the start: a body that serves six tools while its
397
425
  // operator wrote seven is answering for a gate it does not have.
398
- const { sessions, specs: downstreamSpecs } = await attachDownstream(config.downstreamFile ?? null, bodyPublicKeyPems);
426
+ const { sessions, specs: downstreamSpecs } = await attachDownstream(config.downstreamFile ?? null, bodyPublicKeyPems, {
427
+ local: httpCredentialIsLocal(config),
428
+ });
399
429
  const extraTools = sessions.flatMap((session) => session.tools);
400
430
  let services;
401
431
  try {
@@ -409,6 +439,7 @@ export async function listen(config) {
409
439
  ...(config.alarmWebhookUrl ? { alarmWebhookUrl: config.alarmWebhookUrl } : {}),
410
440
  ...(config.alarmRetryMs !== undefined ? { alarmRetryMs: config.alarmRetryMs } : {}),
411
441
  ...(extraTools.length > 0 ? { extraTools } : {}),
442
+ ...downstreamLabelArgs(downstreamSpecs),
412
443
  });
413
444
  }
414
445
  catch (err) {
@@ -455,6 +486,7 @@ export async function listen(config) {
455
486
  ...(typeof bag.iss === "string" ? { iss: bag.iss } : {}),
456
487
  ...(typeof bag.tenant === "string" ? { tenant: bag.tenant } : {}),
457
488
  ...(typeof bag.org === "string" ? { org: bag.org } : {}),
489
+ ...(typeof bag.jti === "string" ? { jti: bag.jti } : {}),
458
490
  });
459
491
  }
460
492
  catch (err) {
@@ -783,6 +815,7 @@ export async function listen(config) {
783
815
  ...(verified.principal.iss ? { iss: verified.principal.iss } : {}),
784
816
  ...(verified.principal.tenant ? { tenant: verified.principal.tenant } : {}),
785
817
  ...(verified.principal.org ? { org: verified.principal.org } : {}),
818
+ ...(typeof verified.payload.jti === "string" ? { jti: verified.payload.jti } : {}),
786
819
  },
787
820
  },
788
821
  }), res, parsed.value);
@@ -0,0 +1,5 @@
1
+ export declare function runTaint(argv: readonly string[], stdout: {
2
+ write(s: string): unknown;
3
+ }, stderr: {
4
+ write(s: string): unknown;
5
+ }): number;