@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.
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,
@@ -263,7 +266,11 @@ export function bearerStillLive(payload, stateDir) {
263
266
  return payload.exp * 1000 > Date.now();
264
267
  }
265
268
  function isProtectedResourcePath(pathname, audience) {
266
- const want = new URL(resourceMetadataUrl(audience)).pathname;
269
+ // RFC 9728 names the resource by URL; a non-URL audience has no metadata to serve.
270
+ const metadata = resourceMetadataUrl(audience);
271
+ if (metadata === null)
272
+ return false;
273
+ const want = new URL(metadata).pathname;
267
274
  return pathname === want || pathname === "/.well-known/oauth-protected-resource";
268
275
  }
269
276
  /**
@@ -325,7 +332,7 @@ function downstreamPublic(sessions, specs) {
325
332
  * closes the ones already open and throws: a half-attached body would serve a
326
333
  * tool list its operator never wrote.
327
334
  */
328
- async function attachDownstream(file, bodyPublicKeyPems) {
335
+ async function attachDownstream(file, bodyPublicKeyPems, opts) {
329
336
  if (file === null || file.trim() === "")
330
337
  return { sessions: [], specs: [] };
331
338
  let text;
@@ -342,6 +349,19 @@ async function attachDownstream(file, bodyPublicKeyPems) {
342
349
  try {
343
350
  // The manifest sits beside the operator's document. An installed body
344
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
+ }
345
365
  sessions.push(await openDownstream(spec, { definitionsDir: dirname(file) }));
346
366
  }
347
367
  catch (err) {
@@ -373,6 +393,18 @@ function definitionsForStart(stateDir, definitionsDir, specs) {
373
393
  }
374
394
  return downstream;
375
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
+ }
376
408
  export async function listen(config) {
377
409
  if (config.alarmWebhookUrl)
378
410
  assertAlarmWebhookUrl(config.alarmWebhookUrl);
@@ -391,7 +423,9 @@ export async function listen(config) {
391
423
  // The children are attached before the door opens. A named document the body
392
424
  // cannot honour stops the start: a body that serves six tools while its
393
425
  // operator wrote seven is answering for a gate it does not have.
394
- 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
+ });
395
429
  const extraTools = sessions.flatMap((session) => session.tools);
396
430
  let services;
397
431
  try {
@@ -405,6 +439,7 @@ export async function listen(config) {
405
439
  ...(config.alarmWebhookUrl ? { alarmWebhookUrl: config.alarmWebhookUrl } : {}),
406
440
  ...(config.alarmRetryMs !== undefined ? { alarmRetryMs: config.alarmRetryMs } : {}),
407
441
  ...(extraTools.length > 0 ? { extraTools } : {}),
442
+ ...downstreamLabelArgs(downstreamSpecs),
408
443
  });
409
444
  }
410
445
  catch (err) {
@@ -451,6 +486,7 @@ export async function listen(config) {
451
486
  ...(typeof bag.iss === "string" ? { iss: bag.iss } : {}),
452
487
  ...(typeof bag.tenant === "string" ? { tenant: bag.tenant } : {}),
453
488
  ...(typeof bag.org === "string" ? { org: bag.org } : {}),
489
+ ...(typeof bag.jti === "string" ? { jti: bag.jti } : {}),
454
490
  });
455
491
  }
456
492
  catch (err) {
@@ -779,6 +815,7 @@ export async function listen(config) {
779
815
  ...(verified.principal.iss ? { iss: verified.principal.iss } : {}),
780
816
  ...(verified.principal.tenant ? { tenant: verified.principal.tenant } : {}),
781
817
  ...(verified.principal.org ? { org: verified.principal.org } : {}),
818
+ ...(typeof verified.payload.jti === "string" ? { jti: verified.payload.jti } : {}),
782
819
  },
783
820
  },
784
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;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * `verax taint clear` appends one line. It does not open the ledger and does
3
+ * not sign anything: the body copies the line into a signed record on its
4
+ * next sync. A tool call has no path here.
5
+ */
6
+ import { readdirSync, statSync } from "node:fs";
7
+ import { userInfo } from "node:os";
8
+ import { appendTaintClearLine, terminalText } from "@verax-ai/proxy";
9
+ const USAGE = `usage: verax taint clear <stateDir> --session <jti>
10
+
11
+ Clears that token's session taint. The body signs the clear the next time
12
+ it syncs. A tool call cannot clear a session.
13
+ `;
14
+ function option(argv, name) {
15
+ const i = argv.indexOf(name);
16
+ if (i < 0)
17
+ return null;
18
+ const value = argv[i + 1];
19
+ if (value === undefined || value.startsWith("-"))
20
+ return null;
21
+ return value;
22
+ }
23
+ function stateProblem(stateDir) {
24
+ let entries;
25
+ try {
26
+ if (!statSync(stateDir).isDirectory())
27
+ return "not a directory";
28
+ entries = readdirSync(stateDir);
29
+ }
30
+ catch (err) {
31
+ const code = err.code;
32
+ if (code === "ENOENT")
33
+ return "no such directory";
34
+ return "not a directory";
35
+ }
36
+ const names = new Set(entries);
37
+ if (names.has("decisions.jsonl") || names.has("ledger.lock") || names.has("pieces") || names.has("halted")) {
38
+ return null;
39
+ }
40
+ return "no ledger files there";
41
+ }
42
+ function cliUser() {
43
+ try {
44
+ return userInfo().username || "unknown";
45
+ }
46
+ catch {
47
+ return "unknown";
48
+ }
49
+ }
50
+ export function runTaint(argv, stdout, stderr) {
51
+ if (argv.length === 0 || argv.includes("--help") || argv.includes("-h")) {
52
+ stdout.write(USAGE);
53
+ return argv.includes("--help") || argv.includes("-h") ? 0 : 78;
54
+ }
55
+ if (argv[0] !== "clear") {
56
+ stderr.write(USAGE);
57
+ return 64;
58
+ }
59
+ const session = option(argv, "--session");
60
+ const stateDir = argv.slice(1).find((arg) => arg !== "--session" && arg !== session);
61
+ if (!stateDir || !session || stateDir.startsWith("-")) {
62
+ stderr.write(USAGE);
63
+ return 78;
64
+ }
65
+ const problem = stateProblem(stateDir);
66
+ if (problem) {
67
+ stderr.write(`taint-clear-failed: ${problem}\n`);
68
+ return 1;
69
+ }
70
+ try {
71
+ appendTaintClearLine(stateDir, { session, by: cliUser(), atMs: Date.now() });
72
+ }
73
+ catch (err) {
74
+ const message = err instanceof Error ? err.message : "taint-clear-failed";
75
+ stderr.write(`taint-clear-failed: ${terminalText(message.replace(/[\r\n]+/g, " ").slice(0, 300))}\n`);
76
+ return 1;
77
+ }
78
+ stdout.write("taint-clear appended\n");
79
+ return 0;
80
+ }
@@ -3,5 +3,45 @@ import { type ApprovalSignatureReport } from "./approval-signature.ts";
3
3
  import { type ControlSignatureReport } from "./control-signature.ts";
4
4
  import { type StartSummary } from "./heartbeat.ts";
5
5
  export declare const EX_VERIFY_FAILED = 1;
6
+ /**
7
+ * The line a reader stops at. A bare VERIFIED reads as "not tampered with", so
8
+ * it is kept for a run that checked what that takes: every key from the reader,
9
+ * a checkpoint reaching the newest record, and a receipt from a service someone
10
+ * else runs, since only a checkpoint held elsewhere detects a rollback of the
11
+ * files. Anything less names what is missing. The exit code and `--json` are
12
+ * unchanged.
13
+ */
14
+ /** The line `verax verify` ends on. Shared with `verax report`. */
15
+ export declare function verdictLine(r: VerifyResult, approval: ApprovalSignatureReport, control: ControlSignatureReport): string;
16
+ export type CompletedVerify = {
17
+ result: VerifyResult;
18
+ approval: ApprovalSignatureReport;
19
+ control: ControlSignatureReport;
20
+ starts: StartSummary;
21
+ verdict: string;
22
+ };
23
+ export type CompleteVerifyOptions = {
24
+ credentialsFile?: string;
25
+ requireSignedStarts?: boolean;
26
+ /** When set, start rows are checked under this pinned record key. */
27
+ pinnedPublicKeyPem?: string;
28
+ /**
29
+ * How to name a thrown error as a problem line. `verax verify` keeps the
30
+ * raw message; `verax report` maps to a short class.
31
+ */
32
+ problemFromThrown?: (err: unknown, fallback: string) => string;
33
+ /**
34
+ * When true, a throw from reading starts becomes a problem on the result
35
+ * instead of escaping. The report uses this; verify lets it throw.
36
+ */
37
+ catchStartErrors?: boolean;
38
+ };
39
+ /**
40
+ * Approval signatures, control signatures and the start summary, folded into
41
+ * `result.ok` / `problems`, then the verdict line. Both `verax verify` and
42
+ * `verax report` call this so a change to one path cannot leave the other
43
+ * behind with every test still green.
44
+ */
45
+ export declare function completeVerify(dir: string, result: VerifyResult, opts?: CompleteVerifyOptions): Promise<CompletedVerify>;
6
46
  export declare function renderVerify(r: VerifyResult, approval?: ApprovalSignatureReport, control?: ControlSignatureReport, starts?: StartSummary): string;
7
47
  export declare function runVerify(argv: readonly string[], out?: (s: string) => void): Promise<number>;
@@ -117,7 +117,8 @@ const CONTROL_NOT_CHECKED = {
117
117
  * files. Anything less names what is missing. The exit code and `--json` are
118
118
  * unchanged.
119
119
  */
120
- function verdictLine(r, approval, control) {
120
+ /** The line `verax verify` ends on. Shared with `verax report`. */
121
+ export function verdictLine(r, approval, control) {
121
122
  if (!r.ok)
122
123
  return "NOT VERIFIED";
123
124
  const fromFiles = [r.trust, r.effectTrust, r.witnessTrust, r.checkpointTrust].some((trust) => trust?.source === "in-ledger") ||
@@ -138,6 +139,109 @@ function verdictLine(r, approval, control) {
138
139
  return "VERIFIED (rollback not checked: no anchored checkpoint)";
139
140
  return "VERIFIED";
140
141
  }
142
+ function defaultProblemFromThrown(err, fallback) {
143
+ return err instanceof Error ? err.message : fallback;
144
+ }
145
+ /**
146
+ * Approval signatures, control signatures and the start summary, folded into
147
+ * `result.ok` / `problems`, then the verdict line. Both `verax verify` and
148
+ * `verax report` call this so a change to one path cannot leave the other
149
+ * behind with every test still green.
150
+ */
151
+ export async function completeVerify(dir, result, opts = {}) {
152
+ const problemFromThrown = opts.problemFromThrown ?? defaultProblemFromThrown;
153
+ let next = result;
154
+ let approval;
155
+ try {
156
+ approval = await verifyApprovalSignatures(dir, opts.credentialsFile ? { credentialsFile: opts.credentialsFile } : {});
157
+ }
158
+ catch (err) {
159
+ const problem = problemFromThrown(err, "approval signatures could not be read");
160
+ approval = { ...APPROVAL_NOT_CHECKED, ok: false, trustNote: problem };
161
+ next = { ...next, ok: false, problems: [...next.problems, problem] };
162
+ }
163
+ if (approval.signedFailed > 0) {
164
+ next = {
165
+ ...next,
166
+ ok: false,
167
+ problems: [...next.problems, `approval signatures: ${approval.signedFailed} did not verify`],
168
+ };
169
+ }
170
+ if (approval.signedAfterRemoval > 0) {
171
+ next = {
172
+ ...next,
173
+ ok: false,
174
+ problems: [...next.problems, `approval signatures: ${approval.signedAfterRemoval} signed after removal`],
175
+ };
176
+ }
177
+ let control;
178
+ try {
179
+ control = await verifyControlSignatures(dir, opts.credentialsFile ? { credentialsFile: opts.credentialsFile } : {});
180
+ }
181
+ catch (err) {
182
+ const problem = problemFromThrown(err, "control signatures could not be read");
183
+ control = { ...CONTROL_NOT_CHECKED, ok: false, trustNote: problem };
184
+ next = { ...next, ok: false, problems: [...next.problems, problem] };
185
+ }
186
+ if (control.signedFailed > 0) {
187
+ next = {
188
+ ...next,
189
+ ok: false,
190
+ problems: [...next.problems, `control signatures: ${control.signedFailed} did not verify`],
191
+ };
192
+ }
193
+ if (control.signedAfterRemoval > 0) {
194
+ next = {
195
+ ...next,
196
+ ok: false,
197
+ problems: [...next.problems, `control signatures: ${control.signedAfterRemoval} signed after removal`],
198
+ };
199
+ }
200
+ const startKeyPem = opts.pinnedPublicKeyPem ?? next.trust.publicKeyPem ?? null;
201
+ const startTrust = opts.pinnedPublicKeyPem ? "pinned" : "in-ledger";
202
+ let starts;
203
+ if (opts.catchStartErrors) {
204
+ try {
205
+ starts = readStartSummary(dir, startKeyPem, startTrust, {
206
+ requireSigned: opts.requireSignedStarts === true,
207
+ });
208
+ if (starts.problems.length > 0) {
209
+ next = { ...next, ok: false, problems: [...next.problems, ...starts.problems] };
210
+ }
211
+ }
212
+ catch (err) {
213
+ const problem = problemFromThrown(err, "start-summary-unreadable");
214
+ next = { ...next, ok: false, problems: [...next.problems, problem] };
215
+ starts = {
216
+ count: 0,
217
+ largestGapMs: null,
218
+ missingPreviousBeat: [],
219
+ unsigned: false,
220
+ signed: 0,
221
+ signedVerified: 0,
222
+ startKey: startKeyPem ? startTrust : "none",
223
+ problems: [problem],
224
+ warnings: [],
225
+ downstream: [],
226
+ };
227
+ }
228
+ }
229
+ else {
230
+ starts = readStartSummary(dir, startKeyPem, startTrust, {
231
+ requireSigned: opts.requireSignedStarts === true,
232
+ });
233
+ if (starts.problems.length > 0) {
234
+ next = { ...next, ok: false, problems: [...next.problems, ...starts.problems] };
235
+ }
236
+ }
237
+ return {
238
+ result: next,
239
+ approval,
240
+ control,
241
+ starts,
242
+ verdict: verdictLine(next, approval, control),
243
+ };
244
+ }
141
245
  export function renderVerify(r, approval = APPROVAL_NOT_CHECKED, control = CONTROL_NOT_CHECKED, starts) {
142
246
  const lines = [];
143
247
  lines.push(`ledger ${r.directory}`);
@@ -390,71 +494,40 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
390
494
  inputs: { line: "inputs: not checked", matched: 0, missing: 0, mismatched: 0 },
391
495
  anchors: { line: "anchors: not checked", receipts: 0, verified: 0, checked: false },
392
496
  problems: [problem],
497
+ attestedDecisions: [],
498
+ attestedCheckpoints: [],
393
499
  };
394
500
  const starts = readStartSummary(dir, publicKeyPem ?? null, publicKeyPem ? "pinned" : "none", {
395
501
  requireSigned: requireSignedStarts,
396
502
  });
397
- const failedReport = { ...failed, approvalSignatures: APPROVAL_NOT_CHECKED, controlSignatures: CONTROL_NOT_CHECKED, starts };
503
+ // attested* stay on the in-process result for report; --json matches main.
504
+ const { attestedDecisions: _ad, attestedCheckpoints: _ac, ...failedPublic } = failed;
505
+ const failedReport = {
506
+ ...failedPublic,
507
+ approvalSignatures: APPROVAL_NOT_CHECKED,
508
+ controlSignatures: CONTROL_NOT_CHECKED,
509
+ starts,
510
+ };
398
511
  // Human lines are escaped in renderVerify. JSON keeps the breaks it wrote.
399
512
  out(json ? terminalLines(JSON.stringify(failedReport, null, 2)) : renderVerify(failed, APPROVAL_NOT_CHECKED, CONTROL_NOT_CHECKED, starts));
400
513
  return EX_VERIFY_FAILED;
401
514
  }
402
- let approval;
403
- try {
404
- approval = await verifyApprovalSignatures(dir, credentialsFile ? { credentialsFile } : {});
405
- }
406
- catch (err) {
407
- const problem = err instanceof Error ? err.message : "approval signatures could not be read";
408
- approval = { ...APPROVAL_NOT_CHECKED, ok: false, trustNote: problem };
409
- result = { ...result, ok: false, problems: [...result.problems, problem] };
410
- }
411
- if (approval.signedFailed > 0) {
412
- result = {
413
- ...result,
414
- ok: false,
415
- problems: [...result.problems, `approval signatures: ${approval.signedFailed} did not verify`],
416
- };
417
- }
418
- if (approval.signedAfterRemoval > 0) {
419
- result = {
420
- ...result,
421
- ok: false,
422
- problems: [...result.problems, `approval signatures: ${approval.signedAfterRemoval} signed after removal`],
423
- };
424
- }
425
- let control;
426
- try {
427
- control = await verifyControlSignatures(dir, credentialsFile ? { credentialsFile } : {});
428
- }
429
- catch (err) {
430
- const problem = err instanceof Error ? err.message : "control signatures could not be read";
431
- control = { ...CONTROL_NOT_CHECKED, ok: false, trustNote: problem };
432
- result = { ...result, ok: false, problems: [...result.problems, problem] };
433
- }
434
- if (control.signedFailed > 0) {
435
- result = {
436
- ...result,
437
- ok: false,
438
- problems: [...result.problems, `control signatures: ${control.signedFailed} did not verify`],
439
- };
440
- }
441
- if (control.signedAfterRemoval > 0) {
442
- result = {
443
- ...result,
444
- ok: false,
445
- problems: [...result.problems, `control signatures: ${control.signedAfterRemoval} signed after removal`],
446
- };
447
- }
448
- // Start rows are signed by the record key: the pinned one, else the one the records carry.
449
- const startKeyPem = publicKeyPem ?? result.trust.publicKeyPem ?? null;
450
- const starts = readStartSummary(dir, startKeyPem, publicKeyPem ? "pinned" : "in-ledger", {
451
- requireSigned: requireSignedStarts,
515
+ const completed = await completeVerify(dir, result, {
516
+ ...(credentialsFile ? { credentialsFile } : {}),
517
+ requireSignedStarts,
518
+ ...(publicKeyPem ? { pinnedPublicKeyPem: publicKeyPem } : {}),
452
519
  });
453
- if (starts.problems.length > 0) {
454
- result = { ...result, ok: false, problems: [...result.problems, ...starts.problems] };
455
- }
456
- const reported = { ...result, approvalSignatures: approval, controlSignatures: control, starts };
520
+ // attested* stay on completed.result for report; --json matches main.
521
+ const { attestedDecisions: _ad, attestedCheckpoints: _ac, ...publicResult } = completed.result;
522
+ const reported = {
523
+ ...publicResult,
524
+ approvalSignatures: completed.approval,
525
+ controlSignatures: completed.control,
526
+ starts: completed.starts,
527
+ };
457
528
  // Human lines are escaped in renderVerify. JSON keeps the breaks it wrote.
458
- out(json ? terminalLines(JSON.stringify(reported, null, 2)) : renderVerify(reported, approval, control, reported.starts));
459
- return reported.ok ? 0 : EX_VERIFY_FAILED;
529
+ out(json
530
+ ? terminalLines(JSON.stringify(reported, null, 2))
531
+ : renderVerify(completed.result, completed.approval, completed.control, completed.starts));
532
+ return completed.result.ok ? 0 : EX_VERIFY_FAILED;
460
533
  }
@@ -49,7 +49,9 @@ export type PostedRegistration = {
49
49
  * and the exponent 65537. Any other kty, alg, curve or RSA shape is refused.
50
50
  * A refusal returns null; this does not throw.
51
51
  */
52
- export declare function coseKeyToPublicKey(base64urlCose: string): KeyObject | null;
52
+ export declare function coseKeyToPublicKey(base64urlCose: string, opts?: {
53
+ storedKey?: boolean;
54
+ }): KeyObject | null;
53
55
  /**
54
56
  * Check one authentication assertion. `expectedOrigins` is the caller's
55
57
  * allow-list; a caller that does not have one passes the origin it read
@@ -5,7 +5,89 @@
5
5
  * verify one signature.
6
6
  */
7
7
  import { constants, createHash, createPublicKey, verify as cryptoVerify } from "node:crypto";
8
- import { decodeCbor, isCborMap, mapGet } from "@cedulon/cose";
8
+ import { cborMap, decodeCbor, isCborMap, mapGet } from "@cedulon/cose";
9
+ /**
10
+ * A COSE_Key that was enrolled before @cedulon/cose 0.16 may be a valid map
11
+ * whose keys are not in the deterministic order 0.16 requires. Refusing it
12
+ * would lock out that operator and make every approval they already signed
13
+ * fail `verax verify`. This reads only the COSE_Key shape (a definite map of
14
+ * at most 16 integer labels to integers or byte strings, no duplicates, no
15
+ * trailing bytes) and is used for a key the store already holds, never for a
16
+ * new enrolment. The public key it yields is the same as the canonical one;
17
+ * the stored bytes are not rewritten.
18
+ */
19
+ function decodeStoredCoseKey(bytes) {
20
+ let off = 0;
21
+ const head = () => {
22
+ if (off >= bytes.length)
23
+ return null;
24
+ const b = bytes[off++];
25
+ const major = b >> 5;
26
+ const info = b & 0x1f;
27
+ if (info < 24)
28
+ return { major, value: info };
29
+ const width = info === 24 ? 1 : info === 25 ? 2 : info === 26 ? 4 : 0;
30
+ if (width === 0 || off + width > bytes.length)
31
+ return null;
32
+ let value = 0;
33
+ for (let i = 0; i < width; i += 1)
34
+ value = value * 256 + bytes[off++];
35
+ // Only the key order may differ from the deterministic form; a head longer than it needs is refused.
36
+ const floor = width === 1 ? 24 : width === 2 ? 256 : 65536;
37
+ if (value < floor)
38
+ return null;
39
+ return { major, value };
40
+ };
41
+ const intOf = (h) => h.major === 0 ? h.value : h.major === 1 ? -1 - h.value : null;
42
+ const top = head();
43
+ if (!top || top.major !== 5 || top.value > 16)
44
+ return null;
45
+ const entries = [];
46
+ const seen = new Set();
47
+ for (let i = 0; i < top.value; i += 1) {
48
+ const k = head();
49
+ if (!k || (k.major !== 0 && k.major !== 1))
50
+ return null;
51
+ const label = k.major === 0 ? k.value : -1 - k.value;
52
+ if (seen.has(label))
53
+ return null;
54
+ seen.add(label);
55
+ const v = head();
56
+ if (!v)
57
+ return null;
58
+ let value;
59
+ if (v.major === 0)
60
+ value = v.value;
61
+ else if (v.major === 1)
62
+ value = -1 - v.value;
63
+ else if (v.major === 4) {
64
+ // key_ops (label 4) is an array of integers.
65
+ if (v.value > 8)
66
+ return null;
67
+ const items = [];
68
+ for (let j = 0; j < v.value; j += 1) {
69
+ const item = head();
70
+ const n = item ? intOf(item) : null;
71
+ if (n === null)
72
+ return null;
73
+ items.push(n);
74
+ }
75
+ value = items;
76
+ }
77
+ else if (v.major === 2) {
78
+ if (v.value > 16384 || off + v.value > bytes.length)
79
+ return null;
80
+ value = bytes.slice(off, off + v.value);
81
+ off += v.value;
82
+ }
83
+ else
84
+ return null;
85
+ entries.push([label, value]);
86
+ }
87
+ if (off !== bytes.length)
88
+ return null;
89
+ return cborMap(entries);
90
+ }
9
91
  /** The COSE algorithms `coseKeyToPublicKey` takes. An enrolment offers these and no others. */
10
92
  export const COSE_ALGORITHMS = [-7, -8, -257];
11
93
  /** The shortest and the longest RSA modulus taken, for a sign-in as for an enrolment. */
@@ -43,12 +125,23 @@ function mapBytes(map, key, length) {
43
125
  * and the exponent 65537. Any other kty, alg, curve or RSA shape is refused.
44
126
  * A refusal returns null; this does not throw.
45
127
  */
46
- export function coseKeyToPublicKey(base64urlCose) {
128
+ export function coseKeyToPublicKey(base64urlCose, opts = {}) {
47
129
  try {
48
130
  const bytes = fromBase64Url(base64urlCose);
49
131
  if (!bytes)
50
132
  return null;
51
- const decoded = decodeCbor(new Uint8Array(bytes));
133
+ let decoded;
134
+ try {
135
+ decoded = decodeCbor(new Uint8Array(bytes));
136
+ }
137
+ catch (err) {
138
+ if (!opts.storedKey || !(err instanceof Error) || err.message !== "cbor-non-deterministic")
139
+ throw err;
140
+ const stored = decodeStoredCoseKey(new Uint8Array(bytes));
141
+ if (!stored)
142
+ return null;
143
+ decoded = stored;
144
+ }
52
145
  if (!isCborMap(decoded))
53
146
  return null;
54
147
  const kty = mapNum(decoded, 1);
@@ -164,7 +257,7 @@ export function verifyAssertion(opts) {
164
257
  if (flags === undefined || (flags & 0x05) !== 0x05)
165
258
  return { ok: false, reason: "user-verification" };
166
259
  const counter = authenticatorData.readUInt32BE(33);
167
- const key = coseKeyToPublicKey(opts.publicKeyCose);
260
+ const key = coseKeyToPublicKey(opts.publicKeyCose, { storedKey: true });
168
261
  if (!key)
169
262
  return { ok: false, reason: "public-key" };
170
263
  const clientHash = createHash("sha256").update(clientBytes).digest();
package/dist/wiring.d.ts CHANGED
@@ -37,6 +37,11 @@ export declare function createBodyServices(opts: {
37
37
  now?: () => number;
38
38
  nonce?: () => string;
39
39
  extraTools?: readonly ExtraTool[];
40
+ /**
41
+ * Labels from the downstream document, keyed by the prefixed tool name.
42
+ * A key that is present replaces the unlabelled-downstream default.
43
+ */
44
+ downstreamLabels?: Readonly<Record<string, readonly ("reads-untrusted" | "egress")[]>>;
40
45
  keysDir?: string;
41
46
  headDir?: string;
42
47
  alarmWebhookUrl?: string;
package/dist/wiring.js CHANGED
@@ -167,6 +167,8 @@ export function createBodyServices(opts) {
167
167
  nonce,
168
168
  inner,
169
169
  resolveInput: (id, principal) => readMemoryMeta(opts.stateDir, id, principal, store, onIntegrity),
170
+ ...(extraNames.length > 0 ? { downstreamTools: new Set(extraNames) } : {}),
171
+ ...(opts.downstreamLabels !== undefined ? { downstreamLabels: opts.downstreamLabels } : {}),
170
172
  checkTenantMismatch: async (call, principal) => {
171
173
  if (call.name === "memory.get") {
172
174
  if (memoryHistoryUnavailable(opts.stateDir, store))