@verax-ai/body 0.5.1 → 0.6.1

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 (50) 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 +27 -0
  8. package/dist/config.js +72 -1
  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 +11 -11
  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 +40 -6
  31. package/dist/operator-cli.d.ts +49 -1
  32. package/dist/operator-cli.js +136 -8
  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/operator-pairing.d.ts +2 -0
  42. package/dist/operator-pairing.js +11 -0
  43. package/dist/reconcile-cli.js +3 -1
  44. package/dist/server.d.ts +2 -0
  45. package/dist/server.js +133 -256
  46. package/dist/verify-cli.js +30 -10
  47. package/dist/webauthn-verify.d.ts +48 -4
  48. package/dist/webauthn-verify.js +183 -25
  49. package/dist/wiring.js +14 -1
  50. package/package.json +4 -4
@@ -0,0 +1,20 @@
1
+ function integerMinor(value) {
2
+ return typeof value === "number" && Number.isInteger(value) ? value : null;
3
+ }
4
+ /** An integer minor-unit amount, or null when the stored amount cannot be read as one. */
5
+ export function minorUnits(row) {
6
+ if (typeof row.amount === "number")
7
+ return integerMinor(row.amount);
8
+ return integerMinor(row.args.amountMinor);
9
+ }
10
+ /** Null for a held call that is not a spend. */
11
+ export function heldSpend(row) {
12
+ if (row.subject !== "spend")
13
+ return null;
14
+ return {
15
+ payee: typeof row.payee === "string" ? row.payee : String(row.args.payee ?? ""),
16
+ amountMinor: minorUnits(row),
17
+ currency: typeof row.currency === "string" ? row.currency : String(row.args.currency ?? ""),
18
+ reference: typeof row.args.reference === "string" ? row.args.reference : "",
19
+ };
20
+ }
@@ -0,0 +1,14 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ export declare const MAX_BODY_BYTES: number;
3
+ export declare function contentLengthOverLimit(req: IncomingMessage): boolean;
4
+ export declare function readJsonBody(req: IncomingMessage, max: number): Promise<{
5
+ ok: true;
6
+ value: unknown;
7
+ } | {
8
+ ok: false;
9
+ tooLarge: true;
10
+ } | {
11
+ ok: false;
12
+ bad: true;
13
+ }>;
14
+ export declare function send(res: ServerResponse, status: number, body: unknown, headers?: Record<string, string>): void;
@@ -0,0 +1,46 @@
1
+ export const MAX_BODY_BYTES = 1024 * 1024;
2
+ export function contentLengthOverLimit(req) {
3
+ const raw = req.headers["content-length"];
4
+ if (raw === undefined)
5
+ return false;
6
+ const n = Number(Array.isArray(raw) ? raw[0] : raw);
7
+ return Number.isFinite(n) && n > MAX_BODY_BYTES;
8
+ }
9
+ export async function readJsonBody(req, max) {
10
+ if (contentLengthOverLimit(req))
11
+ return { ok: false, tooLarge: true };
12
+ const chunks = [];
13
+ let seen = 0;
14
+ try {
15
+ for await (const chunk of req) {
16
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
17
+ seen += buf.length;
18
+ if (seen > max) {
19
+ return { ok: false, tooLarge: true };
20
+ }
21
+ chunks.push(buf);
22
+ }
23
+ }
24
+ catch {
25
+ return { ok: false, bad: true };
26
+ }
27
+ const text = Buffer.concat(chunks).toString("utf8");
28
+ if (text === "")
29
+ return { ok: true, value: undefined };
30
+ try {
31
+ return { ok: true, value: JSON.parse(text) };
32
+ }
33
+ catch {
34
+ return { ok: false, bad: true };
35
+ }
36
+ }
37
+ export function send(res, status, body, headers) {
38
+ const text = typeof body === "string" ? body : JSON.stringify(body);
39
+ res.writeHead(status, {
40
+ "content-type": "application/json",
41
+ "content-length": Buffer.byteLength(text),
42
+ "x-content-type-options": "nosniff",
43
+ ...headers,
44
+ });
45
+ res.end(text);
46
+ }
@@ -1,3 +1,4 @@
1
+ import { type OperatorDoorConfig } from "./config.ts";
1
2
  export type InitIo = {
2
3
  stdout: {
3
4
  write(s: string): unknown;
@@ -19,6 +20,16 @@ export declare function loadEnvFile(path: string, env?: NodeJS.ProcessEnv): {
19
20
  export declare function clearVeraxEnv(env: NodeJS.ProcessEnv): void;
20
21
  /** `serve --env-file` refuses a file that names neither JWKS source. */
21
22
  export declare function envFileJwksMissing(env: NodeJS.ProcessEnv): string | null;
23
+ /**
24
+ * The origin after `--operator-door`, held to what the body will accept when
25
+ * it reads `VERAX_OPERATOR_DOOR`, so a door the service would refuse to open
26
+ * is refused here, before anything is written.
27
+ */
28
+ export declare function parseOperatorDoorFlag(raw: string | undefined): {
29
+ value: OperatorDoorConfig;
30
+ } | {
31
+ error: string;
32
+ };
22
33
  export type InitLocalOpts = {
23
34
  /** Write the agent token here and leave no copy under the state directory. */
24
35
  tokenPath?: string;
@@ -3,7 +3,7 @@ import { chmodSync, existsSync, lstatSync, readFileSync, rmSync, unlinkSync, wri
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { beginWinOwnerRun, endWinOwnerRun, ensureTokenParent, mkdirLeaf, restrictToOwnerWin32, SystemToolError } from "./install.js";
5
5
  import { calculateJwkThumbprint, exportJWK, exportPKCS8, generateKeyPair, importPKCS8, SignJWT, } from "jose";
6
- import { EX_CONFIG } from "./config.js";
6
+ import { EX_CONFIG, readOperatorDoor } from "./config.js";
7
7
  import { shippedPolicyPath } from "./shipped-policy.js";
8
8
  const ISSUER = "verax-local";
9
9
  const SUBJECT = "local-agent";
@@ -95,8 +95,17 @@ function parseInitArgs(argv) {
95
95
  let port = DEFAULT_PORT;
96
96
  let sawDays = false;
97
97
  let sawPort = false;
98
+ let operatorDoor;
98
99
  for (let i = 0; i < argv.length; i += 1) {
99
100
  const a = argv[i];
101
+ if (a === "--operator-door") {
102
+ const door = parseOperatorDoorFlag(argv[i + 1]);
103
+ i += 1;
104
+ if ("error" in door)
105
+ return door;
106
+ operatorDoor = door.value;
107
+ continue;
108
+ }
100
109
  if (a === "--local") {
101
110
  stateDir = argv[i + 1] ?? "";
102
111
  i += 1;
@@ -127,7 +136,7 @@ function parseInitArgs(argv) {
127
136
  return { error: `flag-unknown:${a}` };
128
137
  }
129
138
  if (stateDir === "" || stateDir.startsWith("-")) {
130
- return { error: "verax init --local <stateDir> [--force] [--days N] [--port N]" };
139
+ return { error: "verax init --local <stateDir> [--force] [--days N] [--port N] [--operator-door <origin>]" };
131
140
  }
132
141
  if (sawDays && (!Number.isInteger(days) || days < 1 || days > MAX_DAYS)) {
133
142
  return { error: "--days wants an integer from 1 to 90" };
@@ -135,7 +144,26 @@ function parseInitArgs(argv) {
135
144
  if (sawPort && (!Number.isInteger(port) || port < MIN_PORT || port > MAX_PORT)) {
136
145
  return { error: "--port wants an integer from 1024 to 65535" };
137
146
  }
138
- return { stateDir: resolve(stateDir), force, days, port };
147
+ if (operatorDoor && operatorDoor.bindPort === port) {
148
+ return { error: `--operator-door listens on ${operatorDoor.bindPort}, which --port has taken` };
149
+ }
150
+ return { stateDir: resolve(stateDir), force, days, port, ...(operatorDoor ? { operatorDoor } : {}) };
151
+ }
152
+ /**
153
+ * The origin after `--operator-door`, held to what the body will accept when
154
+ * it reads `VERAX_OPERATOR_DOOR`, so a door the service would refuse to open
155
+ * is refused here, before anything is written.
156
+ */
157
+ export function parseOperatorDoorFlag(raw) {
158
+ if (raw === undefined || raw === "" || raw.startsWith("-")) {
159
+ return { error: "--operator-door needs an origin, such as https://approve.example.com" };
160
+ }
161
+ const door = readOperatorDoor({ VERAX_OPERATOR_DOOR: raw });
162
+ if (!door.ok)
163
+ return { error: door.reason.replace("VERAX_OPERATOR_DOOR", "--operator-door") };
164
+ if (!door.value)
165
+ return { error: "--operator-door needs an origin, such as https://approve.example.com" };
166
+ return { value: door.value };
139
167
  }
140
168
  function pathExists(target) {
141
169
  try {
@@ -248,6 +276,7 @@ async function runInitLocalBody(argv, io, opts) {
248
276
  `VERAX_STATE_DIR=${stateDir}`,
249
277
  `VERAX_POLICY_FILE=${policyDest}`,
250
278
  `VERAX_BIND=127.0.0.1:${parsed.port}`,
279
+ ...(parsed.operatorDoor ? [`VERAX_OPERATOR_DOOR=${parsed.operatorDoor.origin}`] : []),
251
280
  "",
252
281
  ].join("\n");
253
282
  writeNew(envPath, envBody);
package/dist/install.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type SpawnSyncReturns } from "node:child_process";
2
+ import { type OperatorDoorConfig } from "./config.ts";
2
3
  export declare const EX_ELEVATION = 77;
3
4
  export declare const ELEVATION_LINE = "verax install needs an elevated shell (Administrator / root)";
4
5
  /** The tarball Node under `/opt/verax-node`, plus the distribution `/usr/bin/node`. Neither is `env node`. */
@@ -102,6 +103,8 @@ export type PlanOpts = {
102
103
  port?: number;
103
104
  days?: number;
104
105
  force?: boolean;
106
+ /** The operator door to open with the service. Off when absent. */
107
+ operatorDoor?: OperatorDoorConfig;
105
108
  /**
106
109
  * Test-only. Prefixes the fixed POSIX install roots. Not read from CLI argv.
107
110
  * Win32 ignores it.
@@ -249,6 +252,7 @@ export type PlanOp = {
249
252
  days: number;
250
253
  force: boolean;
251
254
  noOwnerGrant: boolean;
255
+ operatorDoor?: string;
252
256
  } | {
253
257
  op: "user-token";
254
258
  tokenDir: string;
@@ -552,6 +556,7 @@ export declare function successText(platform: InstallPlatform, info: {
552
556
  stateDir: string;
553
557
  tokenPath: string;
554
558
  port: number;
559
+ operatorDoor?: OperatorDoorConfig;
555
560
  }): string;
556
561
  export declare function planInstall(platform: InstallPlatform, env: NodeJS.ProcessEnv, opts: PlanOpts): InstallPlan;
557
562
  /**
package/dist/install.js CHANGED
@@ -7,7 +7,7 @@ import path from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { EX_CONFIG } from "./config.js";
9
9
  import { INSTALL_HEALTH_NONCE } from "./health-extras.js";
10
- import { runInitLocal } from "./init-local.js";
10
+ import { parseOperatorDoorFlag, runInitLocal } from "./init-local.js";
11
11
  import { psModuleImports } from "./ps-module-imports.js";
12
12
  export const EX_ELEVATION = 77;
13
13
  export const ELEVATION_LINE = "verax install needs an elevated shell (Administrator / root)";
@@ -21,7 +21,7 @@ export function posixRootOwnedCommand(platform, command) {
21
21
  /** Names the administrator-owned copy. A same-user elevated shell is not that copy. */
22
22
  export function unreadableSentence(dir, command = "verax") {
23
23
  if (process.platform === "win32" && command === "approve") {
24
- return `cannot read ${dir}: approve from the panel with a passkey. An elevated CLI approve is a fallback from a separate administrator account, not this account elevated: & "$env:ProgramFiles\\verax-cli\\verax.cmd" approve`;
24
+ return `cannot read ${dir}: approve held calls with a passkey through the operator door when the install named an origin with --operator-door; without it, an elevated CLI approve from a separate administrator account, not this account elevated: & "$env:ProgramFiles\\verax-cli\\verax.cmd" approve`;
25
25
  }
26
26
  const copy = process.platform === "win32"
27
27
  ? `& "$env:ProgramFiles\\verax-cli\\verax.cmd" ${command}`
@@ -1996,16 +1996,29 @@ export function successText(platform, info) {
1996
1996
  "}",
1997
1997
  ].join("\n");
1998
1998
  const approve = platform === "win32"
1999
- ? 'Approve held calls from the panel with a passkey. An elevated CLI approve is a fallback from a separate administrator account, not this account elevated, because that shell inherits environment variables and the PowerShell profile: & "$env:ProgramFiles\\verax-cli\\verax.cmd" approve'
1999
+ ? info.operatorDoor
2000
+ ? 'Approve held calls with a passkey through the operator door (below); at the machine, an elevated CLI approve from a separate administrator account, not this account elevated, because that shell inherits environment variables and the PowerShell profile: & "$env:ProgramFiles\\verax-cli\\verax.cmd" approve'
2001
+ : 'Approve held calls with an elevated CLI approve from a separate administrator account, not this account elevated, because that shell inherits environment variables and the PowerShell profile: & "$env:ProgramFiles\\verax-cli\\verax.cmd" approve'
2000
2002
  : `Approve held calls from the root-owned Node: ${posixRootOwnedCommand(platform, "approve")}`;
2001
2003
  const uninstall = platform === "win32"
2002
2004
  ? 'Uninstall from that copy: & "$env:ProgramFiles\\verax-cli\\verax.cmd" uninstall'
2003
2005
  : `Uninstall from the root-owned Node: ${posixRootOwnedCommand(platform, "uninstall")}`;
2006
+ const enroll = platform === "win32"
2007
+ ? `& "$env:ProgramFiles\\verax-cli\\verax.cmd" operator enroll --state ${psSingleQuoted(info.stateDir)}`
2008
+ : posixRootOwnedCommand(platform, `operator enroll --state ${shSingleQuoted(info.stateDir)}`);
2009
+ const door = info.operatorDoor
2010
+ ? [
2011
+ `operator door ${info.operatorDoor.bindHost}:${info.operatorDoor.bindPort} for ${info.operatorDoor.origin}`,
2012
+ `A pairing code for a new passkey, good for five minutes: ${enroll}`,
2013
+ `Type the code at ${info.operatorDoor.origin}/ on the device whose passkey it is for. The same page signs in and approves.`,
2014
+ ]
2015
+ : [];
2004
2016
  return [
2005
2017
  `code ${info.codeDir}`,
2006
2018
  `state ${info.stateDir}`,
2007
2019
  "service is running",
2008
2020
  `agent token ${info.tokenPath}`,
2021
+ ...door,
2009
2022
  "",
2010
2023
  "Claude Code:",
2011
2024
  claude,
@@ -2414,6 +2427,7 @@ export function planInstall(platform, env, opts) {
2414
2427
  days: limited.days,
2415
2428
  force: Boolean(opts.force),
2416
2429
  noOwnerGrant: true,
2430
+ ...(opts.operatorDoor ? { operatorDoor: opts.operatorDoor.origin } : {}),
2417
2431
  });
2418
2432
  // Before the service starts, so /healthz can echo a value only this install wrote.
2419
2433
  ops.push({ op: "write", path: noncePath, contents: `${healthNonce}\n`, mode: 0o600 });
@@ -2432,7 +2446,7 @@ export function planInstall(platform, env, opts) {
2432
2446
  }
2433
2447
  ops.push({ op: "wait-healthz", port: limited.port, timeoutMs: HEALTH_WAIT_MS, nonce: healthNonce }, {
2434
2448
  op: "print",
2435
- text: successText(platform, { ...paths, port: limited.port }),
2449
+ text: successText(platform, { ...paths, port: limited.port, ...(opts.operatorDoor ? { operatorDoor: opts.operatorDoor } : {}) }),
2436
2450
  });
2437
2451
  if (platform === "win32")
2438
2452
  tagWinTemp(ops, tempDir);
@@ -3098,8 +3112,17 @@ function parseInstallArgs(argv) {
3098
3112
  let days = DEFAULT_DAYS;
3099
3113
  let force = false;
3100
3114
  let fromTarballs;
3115
+ let operatorDoor;
3101
3116
  for (let i = 0; i < body.length; i += 1) {
3102
3117
  const a = body[i];
3118
+ if (a === "--operator-door") {
3119
+ const door = parseOperatorDoorFlag(body[i + 1]);
3120
+ i += 1;
3121
+ if ("error" in door)
3122
+ return door;
3123
+ operatorDoor = door.value;
3124
+ continue;
3125
+ }
3103
3126
  if (a === "--force") {
3104
3127
  force = true;
3105
3128
  continue;
@@ -3132,7 +3155,10 @@ function parseInstallArgs(argv) {
3132
3155
  if (!Number.isInteger(days) || days < 1 || days > MAX_DAYS) {
3133
3156
  return { error: "--days wants an integer from 1 to 90" };
3134
3157
  }
3135
- return { port, days, force, ...(fromTarballs ? { fromTarballs } : {}) };
3158
+ if (operatorDoor && operatorDoor.bindPort === port) {
3159
+ return { error: `--operator-door listens on ${operatorDoor.bindPort}, which --port has taken` };
3160
+ }
3161
+ return { port, days, force, ...(fromTarballs ? { fromTarballs } : {}), ...(operatorDoor ? { operatorDoor } : {}) };
3136
3162
  }
3137
3163
  function hashFile(file) {
3138
3164
  return createHash("sha256").update(readFileSync(file)).digest("hex");
@@ -4339,6 +4365,7 @@ async function execute(plan, exec, io, platform, copyFile = copyFileSync, instal
4339
4365
  "--port",
4340
4366
  String(step.port),
4341
4367
  ...(step.force ? ["--force"] : []),
4368
+ ...(step.operatorDoor ? ["--operator-door", step.operatorDoor] : []),
4342
4369
  ], io, { quiet: true, noOwnerGrant: step.noOwnerGrant, env: installEnv });
4343
4370
  if (code !== 0)
4344
4371
  return finish(code);
@@ -5294,6 +5321,10 @@ async function runInstallBody(argv, hooks = {}) {
5294
5321
  io.stderr.write(`port-busy:${parsed.port}\n`);
5295
5322
  return EX_CONFIG;
5296
5323
  }
5324
+ if (parsed.operatorDoor && !(await loopbackPortFree(parsed.operatorDoor.bindPort))) {
5325
+ io.stderr.write(`port-busy:${parsed.operatorDoor.bindPort}\n`);
5326
+ return EX_CONFIG;
5327
+ }
5297
5328
  const exec = hooks.exec ?? defaultExec;
5298
5329
  const resolvedEnv = invokingEnv(platform, env, exec);
5299
5330
  if ("error" in resolvedEnv) {
@@ -5523,6 +5554,7 @@ async function runInstallBody(argv, hooks = {}) {
5523
5554
  port: parsed.port,
5524
5555
  days: parsed.days,
5525
5556
  force: parsed.force,
5557
+ ...(parsed.operatorDoor ? { operatorDoor: parsed.operatorDoor } : {}),
5526
5558
  posixRoot,
5527
5559
  stateExists: exists,
5528
5560
  veraxRootExists,
package/dist/main.d.ts CHANGED
@@ -1 +1,2 @@
1
+ export declare function endProcess(code: number): void;
1
2
  export declare function main(env?: NodeJS.ProcessEnv, argv?: readonly string[]): Promise<void>;
package/dist/main.js CHANGED
@@ -1,18 +1,38 @@
1
+ import { setTimeout } from "node:timers";
2
+ import { terminalText } from "@verax-ai/proxy";
1
3
  import { JwksFileError } from "./auth.js";
2
- import { EX_CONFIG, loadConfig, overlayInventoryArg } from "./config.js";
4
+ import { EX_CONFIG, POLICY_FILE_ERROR_PREFIX, loadConfig, overlayInventoryArg } from "./config.js";
3
5
  import { watchDesktopParent } from "./desktop-parent.js";
4
6
  import { KeyAlgorithmError, KeysPartialError } from "./keys.js";
5
- import { listen } from "./server.js";
7
+ import { listen, operatorDoorOf } from "./server.js";
8
+ // exitCode alone leaves a listening server up (for example `verax witness`).
9
+ // On Windows, process.exit while a handle is still closing crashes in libuv;
10
+ // letting the loop drain on its own exits cleanly. Set the code immediately so
11
+ // an empty loop ends at once, and after 3s an unref'd timer forces the exit.
12
+ // unref: the timer does not keep the loop alive, and by 3s a closing handle is
13
+ // gone.
14
+ export function endProcess(code) {
15
+ process.exitCode = code;
16
+ setTimeout(() => process.exit(code), 3000).unref();
17
+ }
6
18
  export async function main(env = process.env, argv = process.argv) {
19
+ // stderr can be a file: launchd gives the installed body one. When its disk
20
+ // stops taking writes, a line written there fails after the write has
21
+ // returned, as an 'error' on the stream, and with nobody listening Node ends
22
+ // the process on it. The line is lost; the body is not stopped by that.
23
+ process.stderr.on("error", () => { });
7
24
  watchDesktopParent({ env });
8
25
  const overlaid = overlayInventoryArg(env, argv);
9
26
  if ("error" in overlaid) {
10
- process.stderr.write(`${overlaid.error}\n`);
27
+ // ProcessEnv's index makes `error` look optional. The overlay's own
28
+ // failure is always a string; the same sentence is the stand-in.
29
+ const reason = overlaid.error ?? "missing --inventory path";
30
+ process.stderr.write(`${terminalText(reason)}\n`);
11
31
  process.exit(EX_CONFIG);
12
32
  }
13
33
  const loaded = loadConfig(overlaid);
14
34
  if (!loaded.ok) {
15
- process.stderr.write(`${loaded.reason}\n`);
35
+ process.stderr.write(`${terminalText(loaded.reason)}\n`);
16
36
  process.exit(loaded.code);
17
37
  }
18
38
  try {
@@ -21,6 +41,10 @@ export async function main(env = process.env, argv = process.argv) {
21
41
  if (addr && typeof addr === "object") {
22
42
  process.stderr.write(`listening ${addr.address}:${addr.port}\n`);
23
43
  }
44
+ const doorAddr = operatorDoorOf(server)?.address();
45
+ if (doorAddr && typeof doorAddr === "object" && loaded.value.operatorDoor) {
46
+ process.stderr.write(`operator door ${doorAddr.address}:${doorAddr.port} for ${loaded.value.operatorDoor.origin}\n`);
47
+ }
24
48
  const shutdown = () => {
25
49
  server.close(() => process.exit(0));
26
50
  };
@@ -33,13 +57,23 @@ export async function main(env = process.env, argv = process.argv) {
33
57
  process.exit(err.code);
34
58
  }
35
59
  if (err instanceof KeyAlgorithmError) {
36
- process.stderr.write(`${err.message}\n`);
60
+ process.stderr.write(`${terminalText(err.message)}\n`);
37
61
  process.exit(err.code);
38
62
  }
39
63
  if (err instanceof JwksFileError) {
40
- process.stderr.write(`${err.message}\n`);
64
+ process.stderr.write(`${terminalText(err.message)}\n`);
41
65
  process.exit(err.code);
42
66
  }
67
+ if (err instanceof Error && err.message.startsWith("downstream-")) {
68
+ process.stderr.write(`${terminalText(err.message)}\n`);
69
+ endProcess(EX_CONFIG);
70
+ return;
71
+ }
72
+ if (err instanceof Error && err.message.startsWith(POLICY_FILE_ERROR_PREFIX)) {
73
+ process.stderr.write(`${terminalText(err.message)}\n`);
74
+ endProcess(EX_CONFIG);
75
+ return;
76
+ }
43
77
  throw err;
44
78
  }
45
79
  }
@@ -1 +1,49 @@
1
- export declare function runOperator(argv: string[]): Promise<number>;
1
+ type Seen = {
2
+ uid: number;
3
+ gid: number;
4
+ isDirectory: boolean;
5
+ };
6
+ /** What `runOperator` asks of the process and the disk. Tests stand in for it. */
7
+ export type OperatorSys = {
8
+ platform: NodeJS.Platform;
9
+ getuid?: () => number;
10
+ getgid?: () => number;
11
+ setgroups?: (groups: number[]) => void;
12
+ setgid?: (gid: number) => void;
13
+ setuid?: (uid: number) => void;
14
+ /** lstat: a link is seen as a link, not as what it points at. Null when there is nothing there. */
15
+ look: (path: string) => Seen | null;
16
+ };
17
+ export type PairingWriter = {
18
+ kind: "as-is";
19
+ stateDir: string;
20
+ } | {
21
+ kind: "become";
22
+ stateDir: string;
23
+ uid: number;
24
+ gid: number;
25
+ } | {
26
+ kind: "refuse";
27
+ reason: string;
28
+ };
29
+ /**
30
+ * As whom the pairing code is written. An installed body runs as its own
31
+ * account and owns its state directory, and root asking for a code is the
32
+ * usual case there. A file root wrote would be root's, which that account
33
+ * cannot read; and a write by root into a directory another account owns is
34
+ * a write that account can aim somewhere else. So for such a directory root
35
+ * gives up being root first and writes as its owner. A link, a missing
36
+ * directory, a file, or a directory whose group is root's is refused: root
37
+ * makes no state directory here and keeps no part of itself.
38
+ *
39
+ * A directory that is root's own is written as root, as it always was. There
40
+ * is no other account to become, and a root-run body whose state someone else
41
+ * can replace is theirs already, whoever writes the code.
42
+ */
43
+ export declare function pairingWriter(stateDir: string, sys: Pick<OperatorSys, "platform" | "getuid" | "look">): PairingWriter;
44
+ /** Groups first, then the group, then the user: after the last one there is no way back. Null when it held. */
45
+ export declare function becomeOwner(sys: OperatorSys, uid: number, gid: number): string | null;
46
+ /** What is at the path itself. A link is a link here, whatever it points at. */
47
+ export declare function lookWithoutFollowing(path: string): Seen | null;
48
+ export declare function runOperator(argv: string[], sys?: OperatorSys): Promise<number>;
49
+ export {};
@@ -1,25 +1,153 @@
1
- import { beginPairing } from "./operator-pairing.js";
2
- export async function runOperator(argv) {
3
- if (argv[1] !== "enroll") {
4
- process.stderr.write("verax operator enroll --state <dir>\n");
1
+ import { lstatSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { credentialsPath, credentialsReadable, readCredentials, readCredentialsAt, readRemoved, removeCredential, removedPath, } from "./operator-credentials.js";
4
+ import { beginPairing, livePairing } from "./operator-pairing.js";
5
+ /**
6
+ * As whom the pairing code is written. An installed body runs as its own
7
+ * account and owns its state directory, and root asking for a code is the
8
+ * usual case there. A file root wrote would be root's, which that account
9
+ * cannot read; and a write by root into a directory another account owns is
10
+ * a write that account can aim somewhere else. So for such a directory root
11
+ * gives up being root first and writes as its owner. A link, a missing
12
+ * directory, a file, or a directory whose group is root's is refused: root
13
+ * makes no state directory here and keeps no part of itself.
14
+ *
15
+ * A directory that is root's own is written as root, as it always was. There
16
+ * is no other account to become, and a root-run body whose state someone else
17
+ * can replace is theirs already, whoever writes the code.
18
+ */
19
+ export function pairingWriter(stateDir, sys) {
20
+ if (sys.platform === "win32" || sys.getuid?.() !== 0)
21
+ return { kind: "as-is", stateDir };
22
+ // Resolved first: a link with a slash after it is looked through, and must not be.
23
+ const dir = resolve(stateDir);
24
+ const seen = sys.look(dir);
25
+ if (!seen)
26
+ return { kind: "refuse", reason: `state-dir-missing:${dir}` };
27
+ if (!seen.isDirectory)
28
+ return { kind: "refuse", reason: `state-dir-not-a-directory:${dir}` };
29
+ if (seen.uid === 0)
30
+ return { kind: "as-is", stateDir: dir };
31
+ if (seen.gid === 0)
32
+ return { kind: "refuse", reason: `state-dir-group-is-roots:${dir}` };
33
+ return { kind: "become", stateDir: dir, uid: seen.uid, gid: seen.gid };
34
+ }
35
+ /** Groups first, then the group, then the user: after the last one there is no way back. Null when it held. */
36
+ export function becomeOwner(sys, uid, gid) {
37
+ if (!sys.setgroups || !sys.setgid || !sys.setuid || !sys.getuid || !sys.getgid)
38
+ return "cannot-change-account";
39
+ try {
40
+ sys.setgroups([gid]);
41
+ sys.setgid(gid);
42
+ sys.setuid(uid);
43
+ }
44
+ catch {
45
+ return "cannot-change-account";
46
+ }
47
+ return sys.getuid() === uid && sys.getgid() === gid ? null : "account-did-not-change";
48
+ }
49
+ /** What is at the path itself. A link is a link here, whatever it points at. */
50
+ export function lookWithoutFollowing(path) {
51
+ try {
52
+ const st = lstatSync(path);
53
+ return { uid: st.uid, gid: st.gid, isDirectory: st.isDirectory() };
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
59
+ const realSys = {
60
+ platform: process.platform,
61
+ getuid: process.getuid?.bind(process),
62
+ getgid: process.getgid?.bind(process),
63
+ setgroups: process.setgroups?.bind(process),
64
+ setgid: process.setgid?.bind(process),
65
+ setuid: process.setuid?.bind(process),
66
+ look: lookWithoutFollowing,
67
+ };
68
+ const USAGE = "verax operator enroll --state <dir>\n" +
69
+ "verax operator list --state <dir>\n" +
70
+ "verax operator remove --state <dir> --id <passkey id>\n";
71
+ export async function runOperator(argv, sys = realSys) {
72
+ const verb = argv[1];
73
+ if (verb !== "enroll" && verb !== "list" && verb !== "remove") {
74
+ process.stderr.write(USAGE);
5
75
  return 78;
6
76
  }
7
77
  let stateDir = "";
78
+ let id = "";
8
79
  for (let i = 2; i < argv.length; i += 1) {
9
80
  if (argv[i] === "--state") {
10
81
  stateDir = argv[++i] ?? "";
11
82
  continue;
12
83
  }
84
+ if (argv[i] === "--id" && verb === "remove") {
85
+ id = argv[++i] ?? "";
86
+ continue;
87
+ }
13
88
  if (argv[i]?.startsWith("-")) {
14
89
  process.stderr.write(`flag-unknown:${argv[i]}\n`);
15
90
  return 78;
16
91
  }
17
92
  }
18
- if (!stateDir) {
19
- process.stderr.write("verax operator enroll --state <dir>\n");
93
+ if (!stateDir || (verb === "remove" && !id)) {
94
+ process.stderr.write(USAGE);
95
+ return 78;
96
+ }
97
+ // All three go in as the pairing code does. What `remove` writes the body
98
+ // must be able to read, and nothing here is read or written as root in a
99
+ // directory another account owns.
100
+ const writer = pairingWriter(stateDir, sys);
101
+ if (writer.kind === "refuse") {
102
+ process.stderr.write(`${writer.reason}\n`);
103
+ return 78;
104
+ }
105
+ if (writer.kind === "become") {
106
+ const failed = becomeOwner(sys, writer.uid, writer.gid);
107
+ if (failed) {
108
+ // Nothing has been written, and nothing will be as root.
109
+ process.stderr.write(`${failed}\n`);
110
+ return 78;
111
+ }
112
+ }
113
+ if (verb === "enroll") {
114
+ const replaced = livePairing(writer.stateDir);
115
+ const { code } = beginPairing(writer.stateDir);
116
+ if (replaced)
117
+ process.stderr.write("the earlier pairing code no longer works\n");
118
+ process.stdout.write(`${code}\n`);
119
+ return 0;
120
+ }
121
+ // A credentials file that does not parse lists as nothing. Said here, so
122
+ // that it is not taken for "nobody is enrolled".
123
+ if (!credentialsReadable(writer.stateDir)) {
124
+ process.stderr.write(`credentials-unreadable:${credentialsPath(writer.stateDir)}\n`);
20
125
  return 78;
21
126
  }
22
- const { code } = beginPairing(stateDir);
23
- process.stdout.write(`${code}\n`);
127
+ if (verb === "list") {
128
+ const removed = readRemoved(writer.stateDir);
129
+ if (!removed) {
130
+ process.stderr.write(`removed-list-unreadable:${removedPath(writer.stateDir)}\n`);
131
+ return 78;
132
+ }
133
+ // In the order they were enrolled: the file is only ever added to at its end.
134
+ for (const row of readCredentialsAt(credentialsPath(writer.stateDir))) {
135
+ process.stdout.write(`${row.id}\t${row.sub}\t${removed.has(row.id) ? "removed" : "in use"}\n`);
136
+ }
137
+ return 0;
138
+ }
139
+ const done = removeCredential(writer.stateDir, id);
140
+ if (done === "unreadable") {
141
+ process.stderr.write(`removed-list-unreadable:${removedPath(writer.stateDir)}\n`);
142
+ return 78;
143
+ }
144
+ if (done === "unknown") {
145
+ process.stderr.write("passkey-unknown\n");
146
+ return 78;
147
+ }
148
+ process.stdout.write(`${done}\n`);
149
+ if (readCredentials(writer.stateDir).length === 0) {
150
+ process.stdout.write("no passkey is left in use: verax operator enroll --state <dir> gives a code for a new one\n");
151
+ }
24
152
  return 0;
25
153
  }