@verax-ai/body 0.5.0 → 0.6.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.
Files changed (46) hide show
  1. package/README.md +4 -3
  2. package/dist/approval-signature.d.ts +19 -0
  3. package/dist/approval-signature.js +70 -5
  4. package/dist/approve-cli.js +20 -24
  5. package/dist/cli.d.ts +1 -0
  6. package/dist/cli.js +146 -14
  7. package/dist/config.d.ts +23 -0
  8. package/dist/config.js +41 -0
  9. package/dist/control-signature.d.ts +4 -0
  10. package/dist/control-signature.js +20 -5
  11. package/dist/definitions.d.ts +9 -0
  12. package/dist/definitions.js +53 -0
  13. package/dist/demo.js +15 -12
  14. package/dist/doctor.js +72 -0
  15. package/dist/downstream-pin.d.ts +9 -0
  16. package/dist/downstream-pin.js +273 -0
  17. package/dist/downstream.d.ts +22 -2
  18. package/dist/downstream.js +312 -44
  19. package/dist/heartbeat.d.ts +26 -2
  20. package/dist/heartbeat.js +90 -7
  21. package/dist/held-spend.d.ts +16 -0
  22. package/dist/held-spend.js +20 -0
  23. package/dist/http-io.d.ts +14 -0
  24. package/dist/http-io.js +46 -0
  25. package/dist/init-local.d.ts +11 -0
  26. package/dist/init-local.js +32 -3
  27. package/dist/install.d.ts +5 -0
  28. package/dist/install.js +37 -5
  29. package/dist/main.d.ts +1 -0
  30. package/dist/main.js +34 -5
  31. package/dist/operator-cli.d.ts +49 -1
  32. package/dist/operator-cli.js +132 -7
  33. package/dist/operator-credentials.d.ts +40 -1
  34. package/dist/operator-credentials.js +97 -7
  35. package/dist/operator-door-page.d.ts +3 -0
  36. package/dist/operator-door-page.js +819 -0
  37. package/dist/operator-door.d.ts +22 -0
  38. package/dist/operator-door.js +487 -0
  39. package/dist/operator-handlers.d.ts +28 -0
  40. package/dist/operator-handlers.js +221 -0
  41. package/dist/server.d.ts +2 -0
  42. package/dist/server.js +108 -255
  43. package/dist/verify-cli.js +30 -10
  44. package/dist/webauthn-verify.d.ts +48 -4
  45. package/dist/webauthn-verify.js +183 -25
  46. package/package.json +4 -4
package/README.md CHANGED
@@ -58,10 +58,11 @@ Point an MCP client at `http://127.0.0.1:8787/mcp` with a Bearer token from
58
58
  your issuer. The tools the body offers are `memory.get`, `memory.put`,
59
59
  `audit.explain`, `message.read`, `message.send` and `spend`. The policy
60
60
  decides which of them a token's scopes may call, and a call can be held
61
- until an operator on this machine approves it.
61
+ until an operator approves it, on this machine or, with the operator door
62
+ set up, from another device with a passkey.
62
63
 
63
- Other commands: `install`, `uninstall`, `approve`, `operator`, `reconcile`,
64
- `witness`, `halt`, `unlock`, `desktop`. `verax install` and an elevated
64
+ Other commands: `install`, `uninstall`, `approve`, `operator`, `downstream`,
65
+ `reconcile`, `witness`, `halt`, `unlock`, `desktop`. `verax install` and an elevated
65
66
  `verax approve` need an administrator-owned copy of this program (Windows,
66
67
  Administrator PowerShell: `npm install -g --prefix "$env:ProgramFiles\verax-cli" @verax-ai/body`;
67
68
  Linux and macOS: `sudo npm install -g --prefix /opt/verax-cli @verax-ai/body`). That
@@ -43,6 +43,7 @@ export type ApprovalSignatureReport = {
43
43
  ok: boolean;
44
44
  signedVerified: number;
45
45
  signedFailed: number;
46
+ signedAfterRemoval: number;
46
47
  unsignedHttp: number;
47
48
  cli: number;
48
49
  line: string;
@@ -53,11 +54,29 @@ export declare function readLines(path: string): string[];
53
54
  export declare function originInClientData(clientDataJSON: string): string | null;
54
55
  export declare function assertionMatches(sig: Pick<ApprovalSignature, "clientDataJSON" | "authenticatorData" | "signature" | "rpId">, publicKey: string, challenge: string): boolean;
55
56
  export declare function trustOf(pinned: boolean, credentials: StoredCredential[]): Pick<ApprovalSignatureReport, "trustSource" | "trustNote">;
57
+ /**
58
+ * Remember `operatorRemoval.mark` under the canonical SHA-256 of the inputs
59
+ * row. A later record reads only the row its signed inputsHash names.
60
+ */
61
+ export declare function indexRemovalMark(byRef: Map<string, Map<string, string>>, ref: string, hash: string, inputs: unknown): void;
62
+ /**
63
+ * One record, in chain order. A `verax.operator` deny of effect `verax.control`
64
+ * adds the mark on `passkey-removed` and drops it on `passkey-removal-undone`.
65
+ * The set is what the chain says at this record, so a signature that landed
66
+ * before the removal still verifies.
67
+ */
68
+ export declare function noteChainRemoval(claims: object, byRef: Map<string, Map<string, string>>, removed: Set<string>): void;
69
+ /** True when this passkey's mark is one the chain has already recorded as removed. */
70
+ export declare function passkeyRemovedAt(credentialId: string, removed: ReadonlySet<string>): boolean;
71
+ /** Omitted when the count is zero, so a line with none stays as it was. */
72
+ export declare function signedAfterRemovalSegment(count: number): string;
56
73
  /**
57
74
  * Recount operator approvals without a body. A signature is checked against
58
75
  * the operator public key and the challenge rebuilt from the defer record.
59
76
  * The authenticator counter is not consulted: this is a re-read, not a second use.
60
77
  * `cli` and `cli-script` are both the unsigned CLI door.
78
+ * A signature whose passkey the chain has already removed is not signed-verified.
79
+ * One earlier in the chain still is: the removal record does not rewrite it.
61
80
  */
62
81
  export declare function verifyApprovalSignatures(stateDir: string, opts?: {
63
82
  credentialsFile?: string;
@@ -6,7 +6,7 @@
6
6
  import { createHash } from "node:crypto";
7
7
  import { readFileSync } from "node:fs";
8
8
  import { canonical, decisionRecordHash } from "@cedulon/core";
9
- import { listPieceFiles } from "@verax-ai/proxy";
9
+ import { listPieceFiles, operatorRemovalMark } from "@verax-ai/proxy";
10
10
  import { credentialsPath, findCredential, hasRegisteredOperator, readCredentialsAt, updateCounter, } from "./operator-credentials.js";
11
11
  import { readRpConfig } from "./rp-config.js";
12
12
  import { verifyAssertion } from "./webauthn-verify.js";
@@ -175,11 +175,62 @@ export function trustOf(pinned, credentials) {
175
175
  return { trustSource: "in-ledger", trustNote: FILE_NOTE };
176
176
  return { trustSource: "none", trustNote: NO_KEY_NOTE };
177
177
  }
178
+ /** The mark on an inputs row, or null when that row does not name one. */
179
+ function removalMarkOf(inputs) {
180
+ if (!inputs || typeof inputs !== "object")
181
+ return null;
182
+ const mark = inputs.operatorRemoval?.mark;
183
+ return typeof mark === "string" && mark !== "" ? mark : null;
184
+ }
185
+ /**
186
+ * Remember `operatorRemoval.mark` under the canonical SHA-256 of the inputs
187
+ * row. A later record reads only the row its signed inputsHash names.
188
+ */
189
+ export function indexRemovalMark(byRef, ref, hash, inputs) {
190
+ const mark = removalMarkOf(inputs);
191
+ if (mark === null)
192
+ return;
193
+ const byHash = byRef.get(ref) ?? new Map();
194
+ byHash.set(hash, mark);
195
+ byRef.set(ref, byHash);
196
+ }
197
+ /**
198
+ * One record, in chain order. A `verax.operator` deny of effect `verax.control`
199
+ * adds the mark on `passkey-removed` and drops it on `passkey-removal-undone`.
200
+ * The set is what the chain says at this record, so a signature that landed
201
+ * before the removal still verifies.
202
+ */
203
+ export function noteChainRemoval(claims, byRef, removed) {
204
+ const row = claims;
205
+ if (row.subject !== "verax.operator" || row.effectClass !== "verax.control" || row.decision !== "deny")
206
+ return;
207
+ if (row.reasonCode !== "passkey-removed" && row.reasonCode !== "passkey-removal-undone")
208
+ return;
209
+ if (typeof row.ref !== "string" || typeof row.inputsHash !== "string")
210
+ return;
211
+ const mark = byRef.get(row.ref)?.get(row.inputsHash);
212
+ if (mark === undefined)
213
+ return;
214
+ if (row.reasonCode === "passkey-removed")
215
+ removed.add(mark);
216
+ else
217
+ removed.delete(mark);
218
+ }
219
+ /** True when this passkey's mark is one the chain has already recorded as removed. */
220
+ export function passkeyRemovedAt(credentialId, removed) {
221
+ return removed.has(operatorRemovalMark(credentialId));
222
+ }
223
+ /** Omitted when the count is zero, so a line with none stays as it was. */
224
+ export function signedAfterRemovalSegment(count) {
225
+ return count > 0 ? ` · signed-after-removal ${count}` : "";
226
+ }
178
227
  /**
179
228
  * Recount operator approvals without a body. A signature is checked against
180
229
  * the operator public key and the challenge rebuilt from the defer record.
181
230
  * The authenticator counter is not consulted: this is a re-read, not a second use.
182
231
  * `cli` and `cli-script` are both the unsigned CLI door.
232
+ * A signature whose passkey the chain has already removed is not signed-verified.
233
+ * One earlier in the chain still is: the removal record does not rewrite it.
183
234
  */
184
235
  export async function verifyApprovalSignatures(stateDir, opts = {}) {
185
236
  const pinned = typeof opts.credentialsFile === "string";
@@ -190,6 +241,7 @@ export async function verifyApprovalSignatures(stateDir, opts = {}) {
190
241
  // hold rows with no record (a crash, a retry, or a row appended by hand);
191
242
  // only the row the allow's signed inputsHash names speaks for that allow.
192
243
  const inputsByRef = new Map();
244
+ const removalByRef = new Map();
193
245
  for (const piece of listPieceFiles(stateDir)) {
194
246
  for (const line of readLines(piece.decisions)) {
195
247
  try {
@@ -208,6 +260,7 @@ export async function verifyApprovalSignatures(stateDir, opts = {}) {
208
260
  const byHash = inputsByRef.get(row.ref) ?? new Map();
209
261
  byHash.set(hash, row.inputs?.approver ?? null);
210
262
  inputsByRef.set(row.ref, byHash);
263
+ indexRemovalMark(removalByRef, row.ref, hash, row.inputs);
211
264
  }
212
265
  catch {
213
266
  // Same as a decision line: skip, do not invent a failure from a torn line.
@@ -216,6 +269,7 @@ export async function verifyApprovalSignatures(stateDir, opts = {}) {
216
269
  }
217
270
  let signedVerified = 0;
218
271
  let signedFailed = 0;
272
+ let signedAfterRemoval = 0;
219
273
  let unsignedHttp = 0;
220
274
  let cli = 0;
221
275
  let other = 0;
@@ -223,10 +277,14 @@ export async function verifyApprovalSignatures(stateDir, opts = {}) {
223
277
  // A defer resolves once. A second signed allow for the same defer reuses an
224
278
  // operator signature the operator gave for one approval.
225
279
  const signedDefers = new Set();
280
+ // Filled as this walk passes removal records. A signature is held against
281
+ // the set at its own place, so one written before the removal still verifies.
282
+ const removed = new Set();
226
283
  for (const row of decisions) {
227
284
  // A parsed line that is not a decision record is the ledger statement's problem, not a crash here.
228
285
  if (!row || typeof row !== "object" || !row.claims || typeof row.claims !== "object")
229
286
  continue;
287
+ noteChainRemoval(row.claims, removalByRef, removed);
230
288
  if (row.claims.decision !== "allow" || typeof row.claims.ref !== "string")
231
289
  continue;
232
290
  // No row hashes to the signed inputsHash: the ledger statement names that
@@ -270,19 +328,26 @@ export async function verifyApprovalSignatures(stateDir, opts = {}) {
270
328
  const challenge = sig && defer && sameRequest && firstUse && recordHash && recordHash === sig.deferRecordHash && typeof defer.claims.requestHash === "string"
271
329
  ? approvalChallenge({ ref: approver.resolves, requestHash: defer.claims.requestHash, deferRecordHash: recordHash })
272
330
  : null;
273
- if (sig && cred && challenge && assertionMatches(sig, cred.publicKey, challenge))
274
- signedVerified += 1;
331
+ if (sig && cred && challenge && assertionMatches(sig, cred.publicKey, challenge)) {
332
+ // Already removed at this place in the chain: not signed-verified, and
333
+ // not a byte failure. A signature earlier in the walk still verifies.
334
+ if (passkeyRemovedAt(sig.credentialId, removed))
335
+ signedAfterRemoval += 1;
336
+ else
337
+ signedVerified += 1;
338
+ }
275
339
  else
276
340
  signedFailed += 1;
277
341
  }
278
342
  const originSuffix = origins.length === 0 ? "" : ` · origin ${origins.join(", ")}`;
279
343
  const report = {
280
- ok: signedFailed === 0,
344
+ ok: signedFailed === 0 && signedAfterRemoval === 0,
281
345
  signedVerified,
282
346
  signedFailed,
347
+ signedAfterRemoval,
283
348
  unsignedHttp,
284
349
  cli,
285
- line: `approval signatures signed-verified ${signedVerified} · signed-failed ${signedFailed} · unsigned-http ${unsignedHttp} · cli ${cli}${other > 0 ? ` · other ${other}` : ""}${originSuffix}`,
350
+ line: `approval signatures signed-verified ${signedVerified} · signed-failed ${signedFailed} · unsigned-http ${unsignedHttp} · cli ${cli}${other > 0 ? ` · other ${other}` : ""}${originSuffix}${signedAfterRemovalSegment(signedAfterRemoval)}`,
286
351
  trustSource: trust.trustSource,
287
352
  trustNote: trust.trustNote,
288
353
  };
@@ -2,8 +2,9 @@ import { existsSync, readFileSync } from "node:fs";
2
2
  import { userInfo } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { createInterface } from "node:readline";
5
- import { approvePending, approvalsLogFor, createApprovalBudgetGuard, enqueueApprovalCommand, FileLedger, loadApprovalsFromDir, loadPolicy, TERMINAL_CONTROL_CLASS, } from "@verax-ai/proxy";
5
+ import { approvePending, approvalsLogFor, createApprovalBudgetGuard, enqueueApprovalCommand, FileLedger, loadApprovalsFromDir, loadPolicy, DISPLAY_ESCAPE_CLASS, } from "@verax-ai/proxy";
6
6
  import { EX_CONFIG } from "./config.js";
7
+ import { heldSpend } from "./held-spend.js";
7
8
  import { cliCodeCheckPassedAlready, defaultElevated, directoryAccess, elevatedCommandCodeRefusal, elevatedStateDirRefusal, readWindowsMachineRoots, stateDirFor, SystemToolError, unreadableSentence, windowsProgramDataRefusal } from "./install.js";
8
9
  import { loadOrCreateSigners } from "./keys.js";
9
10
  function policyFromSnapshot(stateDir, policyHash) {
@@ -65,23 +66,20 @@ export function resolveApproveRef(pending, given) {
65
66
  return { ok: false, reason: "unknown-ref", candidates: [] };
66
67
  }
67
68
  const NEEDS_TERMINAL = "verax approve needs a terminal: it shows what is waiting and asks you to type the amount back\n";
68
- function integerMinor(value) {
69
- return typeof value === "number" && Number.isInteger(value) ? value : null;
70
- }
71
- /** An integer minor-unit amount, or null when the stored amount cannot be read as one. */
72
- function minorUnits(row) {
73
- if (typeof row.amount === "number")
74
- return integerMinor(row.amount);
75
- return integerMinor(row.args.amountMinor);
76
- }
77
- const HELD_CONTROL = new RegExp(`[${TERMINAL_CONTROL_CLASS}]`, "gu");
69
+ const HELD_CONTROL = new RegExp(`[${DISPLAY_ESCAPE_CLASS}]`, "gu");
78
70
  /**
79
71
  * One argument per line, name and value both JSON-quoted, so neither can look like another field.
80
- * JSON leaves U+0085, U+FEFF, U+2028 and U+2029 as they are, so every terminal-control code point
81
- * is written as a \u escape as well.
72
+ * JSON leaves U+007F, the C1 controls, format characters, separators and the other code points
73
+ * that draw nothing as they are, so every remaining code point of DISPLAY_ESCAPE_CLASS is
74
+ * written as a \u escape, one per UTF-16 unit.
82
75
  */
83
76
  function escapeHeld(text) {
84
- return text.replace(HELD_CONTROL, (ch) => `\\u${ch.codePointAt(0).toString(16).padStart(4, "0")}`);
77
+ return text.replace(HELD_CONTROL, (ch) => {
78
+ let out = "";
79
+ for (let i = 0; i < ch.length; i += 1)
80
+ out += `\\u${ch.charCodeAt(i).toString(16).padStart(4, "0")}`;
81
+ return out;
82
+ });
85
83
  }
86
84
  function quotedField(name, value) {
87
85
  const text = typeof value === "string" ? value : value === undefined || value === null ? "" : JSON.stringify(value);
@@ -89,16 +87,13 @@ function quotedField(name, value) {
89
87
  const quoted = escapeHeld(JSON.stringify(text));
90
88
  return `${quotedName}: ${quoted}\n`;
91
89
  }
92
- function spendPrompt(row, amount) {
93
- const payee = typeof row.payee === "string" ? row.payee : String(row.args.payee ?? "");
94
- const currency = typeof row.currency === "string" ? row.currency : String(row.args.currency ?? "");
95
- const reference = typeof row.args.reference === "string" ? row.args.reference : "";
90
+ function spendPrompt(row, spend, amount) {
96
91
  return [
97
92
  quotedField("tool", row.subject),
98
- quotedField("payee", payee),
93
+ quotedField("payee", spend.payee),
99
94
  quotedField("amount", String(amount)),
100
- quotedField("currency", currency),
101
- quotedField("reference", reference),
95
+ quotedField("currency", spend.currency),
96
+ quotedField("reference", spend.reference),
102
97
  quotedField("requestHash", row.requestHash.slice(0, 12)),
103
98
  ].join("");
104
99
  }
@@ -222,13 +217,14 @@ export async function runApprove(argv, writeErr = (s) => process.stderr.write(s)
222
217
  writeErr("approve-unknown-ref\n");
223
218
  return 78;
224
219
  }
225
- if (waiting.subject === "spend") {
226
- const expected = minorUnits(waiting);
220
+ const spend = heldSpend(waiting);
221
+ if (spend) {
222
+ const expected = spend.amountMinor;
227
223
  if (expected === null) {
228
224
  writeErr("approve-amount-unreadable\n");
229
225
  return 1;
230
226
  }
231
- writeOut(spendPrompt(waiting, expected));
227
+ writeOut(spendPrompt(waiting, spend, expected));
232
228
  writeOut("Type the amount in minor units:\n");
233
229
  const typed = (await terminal.ask("Type the amount in minor units:\n")).trim();
234
230
  if (typed !== String(expected)) {
package/dist/cli.d.ts CHANGED
@@ -22,3 +22,4 @@ export type CliHooks = {
22
22
  * a second check in this process.
23
23
  */
24
24
  export declare function runCli(argv: string[], hooks?: CliHooks): Promise<number>;
25
+ export declare function uncaughtText(err: unknown): string;
package/dist/cli.js CHANGED
@@ -1,16 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
  import { realpathSync } from "node:fs";
3
3
  import path from "node:path";
4
+ import { createInterface } from "node:readline";
4
5
  import { fileURLToPath } from "node:url";
6
+ import { terminalLines, terminalText } from "@verax-ai/proxy";
5
7
  import { runApprove } from "./approve-cli.js";
6
8
  import { attachBodyLog } from "./body-log.js";
7
9
  import { bodyVersion } from "./body-version.js";
8
10
  import { runDemo } from "./demo.js";
9
11
  import { doctorBodyLog, doctorExit, runDoctor } from "./doctor.js";
12
+ import { runDownstreamPin } from "./downstream-pin.js";
10
13
  import { clearVeraxEnv, envFileJwksMissing, loadEnvFile, runInitLocal } from "./init-local.js";
11
14
  import { clearCliCodeCheckPassed, defaultElevated, directoryAccess, doctorStateTarget, elevatedCommandCodeRefusal, linuxNodeLabelCheck, linuxSelinuxCheck, liveInstalledChecks, markCliCodeCheckPassed, runInstall, runUninstall, SystemToolError, unreadableSentence } from "./install.js";
12
15
  import { runHalt, runResume } from "./halt.js";
13
- import { main } from "./main.js";
16
+ import { endProcess, main } from "./main.js";
14
17
  import { runOperator } from "./operator-cli.js";
15
18
  import { runAnchor } from "./anchor-cli.js";
16
19
  import { runReconcile } from "./reconcile-cli.js";
@@ -26,9 +29,9 @@ Usage: verax <command> [options]
26
29
  serve [--env-file <file>] [--log-file <file>]
27
30
  same as serving, after loading KEY=VALUE lines from that file.
28
31
  --log-file appends this process's stdout and stderr
29
- init --local <stateDir> [--force] [--days N] [--port N]
32
+ init --local <stateDir> [--force] [--days N] [--port N] [--operator-door <origin>]
30
33
  write a loopback key, one agent token, and verax.env
31
- install [--port N] [--days N] [--force]
34
+ install [--port N] [--days N] [--force] [--operator-door <origin>]
32
35
  copy this body to an administrator-owned directory and run it
33
36
  as another account. Needs an elevated shell, and this program
34
37
  must live in a directory only an administrator can change.
@@ -38,11 +41,15 @@ Usage: verax <command> [options]
38
41
  stop that body and remove its code. Needs an elevated shell
39
42
  and the same administrator-owned copy.
40
43
  doctor [--json] check the configuration this process would run with
44
+ downstream pin --file <file> --prefix <prefix>
45
+ list that child's tools once and, after a typed yes,
46
+ write a manifest beside the document. The document is not edited.
41
47
  demo [--keep] run a loopback body against a temporary ledger and print what it recorded
42
48
  [--with-conarium] also fetch Conarium with npx, attach it as a child, and put a masked read through the gate
43
49
  approve <args> approve a waiting request from this machine.
44
- On Windows the panel with a passkey is how a held call is approved.
45
- An elevated CLI approve is a fallback from a separate administrator
50
+ On Windows, approve held calls with a passkey through the operator door
51
+ when the install named an origin with --operator-door; without it,
52
+ an elevated CLI approve from a separate administrator
46
53
  account, not this account elevated:
47
54
  "%ProgramFiles%\\verax-cli\\verax.cmd" approve.
48
55
  Linux and macOS the root-owned Node, for example
@@ -109,7 +116,7 @@ export async function runCli(argv, hooks = {}) {
109
116
  }
110
117
  catch (err) {
111
118
  if (err instanceof SystemToolError) {
112
- stderr.write(`${err.message}\n`);
119
+ stderr.write(`${terminalText(err.message)}\n`);
113
120
  return 78;
114
121
  }
115
122
  throw err;
@@ -120,7 +127,7 @@ export async function runCli(argv, hooks = {}) {
120
127
  execArgv: hooks.execArgv,
121
128
  });
122
129
  if (refusal) {
123
- stderr.write(refusal.endsWith("\n") ? refusal : `${refusal}\n`);
130
+ stderr.write(`${terminalLines(refusal.replace(/\n+$/, ""))}\n`);
124
131
  return 78;
125
132
  }
126
133
  markCliCodeCheckPassed();
@@ -136,6 +143,43 @@ export async function runCli(argv, hooks = {}) {
136
143
  clearCliCodeCheckPassed();
137
144
  }
138
145
  }
146
+ function option(argv, name) {
147
+ const i = argv.indexOf(name);
148
+ if (i < 0)
149
+ return null;
150
+ const value = argv[i + 1];
151
+ if (value === undefined || value.startsWith("-"))
152
+ return null;
153
+ return value;
154
+ }
155
+ function readTerminalLine() {
156
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
157
+ return new Promise((resolve) => {
158
+ rl.once("line", (line) => {
159
+ rl.close();
160
+ resolve(line);
161
+ });
162
+ });
163
+ }
164
+ /** `verax downstream pin` reads one line from a terminal. A pipe is not a person typing yes. */
165
+ async function runDownstreamCli(argv, stdout, stderr) {
166
+ const usage = "verax downstream pin --file <file> --prefix <prefix>\n";
167
+ if (argv[0] !== "pin") {
168
+ stderr.write(usage);
169
+ return 64;
170
+ }
171
+ const file = option(argv.slice(1), "--file");
172
+ const prefix = option(argv.slice(1), "--prefix");
173
+ if (file === null || prefix === null) {
174
+ stderr.write(usage);
175
+ return 64;
176
+ }
177
+ if (!process.stdin.isTTY) {
178
+ stderr.write("refusing: downstream pin reads the confirmation from a terminal\n");
179
+ return 78;
180
+ }
181
+ return runDownstreamPin({ file, prefix }, { out: (s) => stdout.write(s), ask: readTerminalLine });
182
+ }
139
183
  async function dispatchCli(argv, stdout, stderr, env) {
140
184
  if (argv[0] === "demo") {
141
185
  return runDemo(argv, env, {
@@ -208,7 +252,7 @@ async function dispatchCli(argv, stdout, stderr, env) {
208
252
  }
209
253
  const attached = attachBodyLog(logPath);
210
254
  if (!attached.ok) {
211
- stderr.write(`${attached.reason}\n`);
255
+ stderr.write(`${terminalText(attached.reason)}\n`);
212
256
  return 78;
213
257
  }
214
258
  stderr.write("verax serve starting\n");
@@ -223,12 +267,12 @@ async function dispatchCli(argv, stdout, stderr, env) {
223
267
  clearVeraxEnv(process.env);
224
268
  const loaded = loadEnvFile(file);
225
269
  if (!loaded.ok) {
226
- stderr.write(`${loaded.reason}\n`);
270
+ stderr.write(`${terminalText(loaded.reason)}\n`);
227
271
  return 78;
228
272
  }
229
273
  const missingJwks = envFileJwksMissing(process.env);
230
274
  if (missingJwks) {
231
- stderr.write(`${missingJwks}\n`);
275
+ stderr.write(`${terminalText(missingJwks)}\n`);
232
276
  return 78;
233
277
  }
234
278
  }
@@ -241,7 +285,7 @@ async function dispatchCli(argv, stdout, stderr, env) {
241
285
  const json = argv.includes("--json");
242
286
  const target = doctorStateTarget(env);
243
287
  if (target && directoryAccess(target) === "unreadable") {
244
- stderr.write(`${unreadableSentence(target, "doctor")}\n`);
288
+ stderr.write(`${terminalText(unreadableSentence(target, "doctor"))}\n`);
245
289
  return 77;
246
290
  }
247
291
  const nodeLabel = process.platform === "linux" ? linuxNodeLabelCheck() : null;
@@ -277,6 +321,9 @@ async function dispatchCli(argv, stdout, stderr, env) {
277
321
  stderr.write("desktop-not-released: the desktop panel is not in this release\n");
278
322
  return 64;
279
323
  }
324
+ if (argv[0] === "downstream") {
325
+ return runDownstreamCli(argv.slice(1), stdout, stderr);
326
+ }
280
327
  if (argv[0] === "witness") {
281
328
  const stateDir = argv[1];
282
329
  if (!stateDir) {
@@ -288,13 +335,13 @@ async function dispatchCli(argv, stdout, stderr, env) {
288
335
  }
289
336
  const head = argv[0];
290
337
  if (head !== undefined && !head.startsWith("--")) {
291
- stderr.write(`unknown command: ${head}\n`);
338
+ stderr.write(`unknown command: ${terminalText(head)}\n`);
292
339
  stderr.write(HELP);
293
340
  return 64;
294
341
  }
295
342
  // `main()` reads `--inventory`. Any other leading flag is not a serve option.
296
343
  if (head !== undefined && head.startsWith("--") && head !== "--inventory") {
297
- stderr.write(`unknown option: ${head}\n`);
344
+ stderr.write(`unknown option: ${terminalText(head)}\n`);
298
345
  stderr.write(HELP);
299
346
  return 64;
300
347
  }
@@ -304,6 +351,91 @@ async function dispatchCli(argv, stdout, stderr, env) {
304
351
  await new Promise(() => { });
305
352
  return 0;
306
353
  }
354
+ // First line is the name and the whole message. Frames are the ` at ` lines
355
+ // after the first copy of that message in err.stack, or after the first line
356
+ // when the message is empty or missing, so a forged frame inside the message
357
+ // stays on the first line. name, message, stack, and String(value) are read in
358
+ // their own try; a read that throws uses a fixed stand-in. This never throws.
359
+ export function uncaughtText(err) {
360
+ const unread = "unprintable thrown value";
361
+ let error;
362
+ try {
363
+ if (err instanceof Error)
364
+ error = err;
365
+ }
366
+ catch {
367
+ error = undefined;
368
+ }
369
+ let name = "Error";
370
+ let message = unread;
371
+ let messageKnown = false;
372
+ if (error !== undefined) {
373
+ try {
374
+ const read = error.name;
375
+ if (typeof read === "string")
376
+ name = read;
377
+ }
378
+ catch {
379
+ name = "Error";
380
+ }
381
+ try {
382
+ const read = error.message;
383
+ if (typeof read === "string") {
384
+ message = read;
385
+ messageKnown = true;
386
+ }
387
+ }
388
+ catch {
389
+ message = unread;
390
+ messageKnown = false;
391
+ }
392
+ }
393
+ else {
394
+ try {
395
+ message = String(err);
396
+ messageKnown = true;
397
+ }
398
+ catch {
399
+ message = unread;
400
+ messageKnown = false;
401
+ }
402
+ }
403
+ const lines = [terminalText(`${name}: ${message}`)];
404
+ if (error !== undefined) {
405
+ let stack;
406
+ try {
407
+ const read = error.stack;
408
+ if (typeof read === "string")
409
+ stack = read;
410
+ }
411
+ catch {
412
+ stack = undefined;
413
+ }
414
+ if (stack !== undefined) {
415
+ const at = messageKnown && message !== "" ? stack.indexOf(message) : -1;
416
+ let rest;
417
+ if (at === -1) {
418
+ const nl = stack.indexOf("\n");
419
+ rest = nl === -1 ? "" : stack.slice(nl + 1);
420
+ }
421
+ else {
422
+ rest = stack.slice(at + message.length);
423
+ }
424
+ for (const line of rest.split("\n")) {
425
+ if (line.startsWith(" at "))
426
+ lines.push(terminalText(line));
427
+ }
428
+ }
429
+ }
430
+ return `${lines.join("\n")}\n`;
431
+ }
307
432
  if (isCliEntry()) {
308
- process.exit(await runCli(process.argv.slice(2)));
433
+ try {
434
+ process.exit(await runCli(process.argv.slice(2)));
435
+ }
436
+ catch (err) {
437
+ // Replaces Node's printer, which would write the path raw and a source excerpt.
438
+ process.stderr.write(terminalLines(uncaughtText(err)));
439
+ endProcess(1);
440
+ }
309
441
  }
package/dist/config.d.ts CHANGED
@@ -42,6 +42,15 @@ export type BodyConfig = {
42
42
  * Default is 1 MiB. `VERAX_MESSAGE_QUOTA_BYTES` overrides it.
43
43
  */
44
44
  messageQuotaBytes?: number;
45
+ /** The operator door, a second listener. Null leaves it shut. */
46
+ operatorDoor?: OperatorDoorConfig | null;
47
+ };
48
+ export type OperatorDoorConfig = {
49
+ /** The one origin the door answers for. It is the passkey relying party. */
50
+ origin: string;
51
+ rpID: string;
52
+ bindHost: string;
53
+ bindPort: number;
45
54
  };
46
55
  /** Per-tenant `memory.put` cap. The HTTP body cap does not reset this total. */
47
56
  export declare const DEFAULT_MEMORY_QUOTA_BYTES: number;
@@ -58,6 +67,20 @@ export type ConfigResult = {
58
67
  code: typeof EX_CONFIG;
59
68
  };
60
69
  export declare function isLoopbackHost(host: string): boolean;
70
+ /**
71
+ * `VERAX_OPERATOR_DOOR` names the origin an operator reaches the door at. It
72
+ * is HTTPS, or `http://localhost` for a trial on the machine itself, and it
73
+ * is a name: WebAuthn does not take an IP address as a relying party. The
74
+ * door itself listens on loopback (`VERAX_OPERATOR_BIND`); what stands in
75
+ * front of it with a certificate is the operator's.
76
+ */
77
+ export declare function readOperatorDoor(env: NodeJS.ProcessEnv): {
78
+ ok: true;
79
+ value: OperatorDoorConfig | null;
80
+ } | {
81
+ ok: false;
82
+ reason: string;
83
+ };
61
84
  export declare function loadConfig(env: NodeJS.ProcessEnv): ConfigResult;
62
85
  /** `--inventory <file>` wins over VERAX_INVENTORY_FILE. */
63
86
  export declare function overlayInventoryArg(env: NodeJS.ProcessEnv, argv: readonly string[]): NodeJS.ProcessEnv | {
package/dist/config.js CHANGED
@@ -56,6 +56,42 @@ function jwksFileParses(path) {
56
56
  return false;
57
57
  }
58
58
  }
59
+ const DEFAULT_DOOR_BIND = "127.0.0.1:8788";
60
+ /**
61
+ * `VERAX_OPERATOR_DOOR` names the origin an operator reaches the door at. It
62
+ * is HTTPS, or `http://localhost` for a trial on the machine itself, and it
63
+ * is a name: WebAuthn does not take an IP address as a relying party. The
64
+ * door itself listens on loopback (`VERAX_OPERATOR_BIND`); what stands in
65
+ * front of it with a certificate is the operator's.
66
+ */
67
+ export function readOperatorDoor(env) {
68
+ const raw = env.VERAX_OPERATOR_DOOR?.trim() ?? "";
69
+ if (raw === "")
70
+ return { ok: true, value: null };
71
+ let url;
72
+ try {
73
+ url = new URL(raw);
74
+ }
75
+ catch {
76
+ return { ok: false, reason: "VERAX_OPERATOR_DOOR is not an origin" };
77
+ }
78
+ if (url.origin !== raw) {
79
+ return { ok: false, reason: "VERAX_OPERATOR_DOOR is an origin only: scheme, host and port" };
80
+ }
81
+ const host = url.hostname;
82
+ if (/^[0-9.]+$/.test(host) || host.startsWith("[")) {
83
+ return { ok: false, reason: "VERAX_OPERATOR_DOOR needs a name, not an IP address" };
84
+ }
85
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && host === "localhost")) {
86
+ return { ok: false, reason: "VERAX_OPERATOR_DOOR needs https" };
87
+ }
88
+ const bindRaw = env.VERAX_OPERATOR_BIND?.trim() ?? "";
89
+ const bind = parseBind(bindRaw === "" ? DEFAULT_DOOR_BIND : bindRaw);
90
+ if (!isLoopbackHost(bind.host)) {
91
+ return { ok: false, reason: "VERAX_OPERATOR_BIND needs a loopback address" };
92
+ }
93
+ return { ok: true, value: { origin: url.origin, rpID: host, bindHost: bind.host, bindPort: bind.port } };
94
+ }
59
95
  export function loadConfig(env) {
60
96
  const issuer = env.VERAX_ISSUER?.trim() ?? "";
61
97
  const jwksUrl = env.VERAX_JWKS_URL?.trim() ?? "";
@@ -114,6 +150,10 @@ export function loadConfig(env) {
114
150
  if (policyFile === "") {
115
151
  return { ok: false, code: EX_CONFIG, reason: "missing VERAX_POLICY_FILE" };
116
152
  }
153
+ const door = readOperatorDoor(env);
154
+ if (!door.ok) {
155
+ return { ok: false, code: EX_CONFIG, reason: door.reason };
156
+ }
117
157
  const inventoryRaw = env.VERAX_INVENTORY_FILE?.trim() ?? "";
118
158
  const downstreamRaw = env.VERAX_DOWNSTREAM?.trim() ?? "";
119
159
  return {
@@ -137,6 +177,7 @@ export function loadConfig(env) {
137
177
  .filter((item) => item !== ""),
138
178
  memoryQuotaBytes: memoryQuotaBytes(env),
139
179
  messageQuotaBytes: messageQuotaBytes(env),
180
+ operatorDoor: door.value,
140
181
  },
141
182
  };
142
183
  }
@@ -33,6 +33,7 @@ export type ControlSignatureReport = {
33
33
  ok: boolean;
34
34
  signedVerified: number;
35
35
  signedFailed: number;
36
+ signedAfterRemoval: number;
36
37
  unsignedHttp: number;
37
38
  cli: number;
38
39
  file: number;
@@ -46,6 +47,9 @@ export type ControlSignatureReport = {
46
47
  * just before its own (`null` for line 0), and verify under the operator key
47
48
  * over the challenge rebuilt from that and the record's subject. A challenge
48
49
  * counts once. The authenticator counter is not consulted.
50
+ * Removal marks advance in this same walk. They are not history lines:
51
+ * `prev` still names the history line before this record. A signature whose
52
+ * passkey is already in the set is not signed-verified; one earlier still is.
49
53
  */
50
54
  export declare function verifyControlSignatures(stateDir: string, opts?: {
51
55
  credentialsFile?: string;