@verax-ai/body 0.5.1 → 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 +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 +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
@@ -12,7 +12,7 @@
12
12
  import { createHash } from "node:crypto";
13
13
  import { canonical } from "@cedulon/core";
14
14
  import { listPieceFiles } from "@verax-ai/proxy";
15
- import { asAssertion, assertionMatches, readLines, trustOf } from "./approval-signature.js";
15
+ import { asAssertion, assertionMatches, indexRemovalMark, noteChainRemoval, passkeyRemovedAt, readLines, signedAfterRemovalSegment, trustOf, } from "./approval-signature.js";
16
16
  import { historyTail } from "./halt.js";
17
17
  import { credentialsPath, findCredential, hasRegisteredOperator, readCredentialsAt, updateCounter, } from "./operator-credentials.js";
18
18
  import { readRpConfig } from "./rp-config.js";
@@ -91,6 +91,9 @@ function controlSignatureOf(value) {
91
91
  * just before its own (`null` for line 0), and verify under the operator key
92
92
  * over the challenge rebuilt from that and the record's subject. A challenge
93
93
  * counts once. The authenticator counter is not consulted.
94
+ * Removal marks advance in this same walk. They are not history lines:
95
+ * `prev` still names the history line before this record. A signature whose
96
+ * passkey is already in the set is not signed-verified; one earlier still is.
94
97
  */
95
98
  export async function verifyControlSignatures(stateDir, opts = {}) {
96
99
  const pinned = typeof opts.credentialsFile === "string";
@@ -98,6 +101,7 @@ export async function verifyControlSignatures(stateDir, opts = {}) {
98
101
  const trust = trustOf(pinned, credentials);
99
102
  const decisions = [];
100
103
  const inputsByRef = new Map();
104
+ const removalByRef = new Map();
101
105
  for (const piece of listPieceFiles(stateDir)) {
102
106
  for (const line of readLines(piece.decisions)) {
103
107
  try {
@@ -116,6 +120,7 @@ export async function verifyControlSignatures(stateDir, opts = {}) {
116
120
  const byHash = inputsByRef.get(row.ref) ?? new Map();
117
121
  byHash.set(hash, row.inputs?.control ?? null);
118
122
  inputsByRef.set(row.ref, byHash);
123
+ indexRemovalMark(removalByRef, row.ref, hash, row.inputs);
119
124
  }
120
125
  catch {
121
126
  // Same as a decision line.
@@ -124,14 +129,19 @@ export async function verifyControlSignatures(stateDir, opts = {}) {
124
129
  }
125
130
  let signedVerified = 0;
126
131
  let signedFailed = 0;
132
+ let signedAfterRemoval = 0;
127
133
  let unsignedHttp = 0;
128
134
  let cli = 0;
129
135
  let file = 0;
130
136
  const lineHashByLine = new Map();
131
137
  const used = new Set();
138
+ // Ledger order, not history-line order. A removal between two control
139
+ // records updates this set and leaves `lineHashByLine` where it was.
140
+ const removed = new Set();
132
141
  for (const row of decisions) {
133
142
  if (!row || typeof row !== "object" || !row.claims || typeof row.claims !== "object")
134
143
  continue;
144
+ noteChainRemoval(row.claims, removalByRef, removed);
135
145
  const claims = row.claims;
136
146
  if (claims.effectClass !== "verax.control" || claims.decision !== "allow")
137
147
  continue;
@@ -162,8 +172,12 @@ export async function verifyControlSignatures(stateDir, opts = {}) {
162
172
  if (challenge !== null)
163
173
  used.add(challenge);
164
174
  const cred = sig ? credentials.find((c) => c.id === sig.credentialId && c.sub === sig.sub) : undefined;
165
- if (sig && cred && challenge && firstUse && assertionMatches(sig, cred.publicKey, challenge))
166
- signedVerified += 1;
175
+ if (sig && cred && challenge && firstUse && assertionMatches(sig, cred.publicKey, challenge)) {
176
+ if (passkeyRemovedAt(sig.credentialId, removed))
177
+ signedAfterRemoval += 1;
178
+ else
179
+ signedVerified += 1;
180
+ }
167
181
  else
168
182
  signedFailed += 1;
169
183
  }
@@ -171,13 +185,14 @@ export async function verifyControlSignatures(stateDir, opts = {}) {
171
185
  lineHashByLine.set(at, control.lineHash);
172
186
  }
173
187
  return {
174
- ok: signedFailed === 0,
188
+ ok: signedFailed === 0 && signedAfterRemoval === 0,
175
189
  signedVerified,
176
190
  signedFailed,
191
+ signedAfterRemoval,
177
192
  unsignedHttp,
178
193
  cli,
179
194
  file,
180
- line: `control signatures signed-verified ${signedVerified} · signed-failed ${signedFailed} · unsigned-http ${unsignedHttp} · cli ${cli} · file ${file}`,
195
+ line: `control signatures signed-verified ${signedVerified} · signed-failed ${signedFailed} · unsigned-http ${unsignedHttp} · cli ${cli} · file ${file}${signedAfterRemovalSegment(signedAfterRemoval)}`,
181
196
  trustSource: trust.trustSource,
182
197
  trustNote: trust.trustNote,
183
198
  };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Copies the pinned manifest into the state directory, create-only, before a
3
+ * start row names it. The source bytes must hash to the digest; a file
4
+ * already there must be those same bytes. What the copy and the signed row
5
+ * prove, and no more: the body that held a trusted record key recorded these
6
+ * definitions at that start. They do not prove that a person read them or
7
+ * that the child's code behaves as described.
8
+ */
9
+ export declare function copyDefinition(stateDir: string, definitionsDir: string, digest: string): void;
@@ -0,0 +1,53 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ const DIGEST_RE = /^[0-9a-f]{64}$/;
5
+ /**
6
+ * Copies the pinned manifest into the state directory, create-only, before a
7
+ * start row names it. The source bytes must hash to the digest; a file
8
+ * already there must be those same bytes. What the copy and the signed row
9
+ * prove, and no more: the body that held a trusted record key recorded these
10
+ * definitions at that start. They do not prove that a person read them or
11
+ * that the child's code behaves as described.
12
+ */
13
+ export function copyDefinition(stateDir, definitionsDir, digest) {
14
+ if (!DIGEST_RE.test(digest))
15
+ throw new Error(`downstream-manifest-invalid:${digest}`);
16
+ const source = join(definitionsDir, "definitions", `${digest}.json`);
17
+ let bytes;
18
+ try {
19
+ bytes = readFileSync(source);
20
+ }
21
+ catch {
22
+ throw new Error(`downstream-manifest-invalid:${digest}`);
23
+ }
24
+ if (createHash("sha256").update(bytes).digest("hex") !== digest) {
25
+ throw new Error(`downstream-manifest-invalid:${digest}`);
26
+ }
27
+ const dest = join(stateDir, "definitions", `${digest}.json`);
28
+ let existing;
29
+ try {
30
+ existing = readFileSync(dest);
31
+ }
32
+ catch (err) {
33
+ if (err.code !== "ENOENT")
34
+ throw err;
35
+ }
36
+ if (existing !== undefined) {
37
+ if (existing.equals(bytes))
38
+ return;
39
+ throw new Error(`downstream-manifest-conflict:${digest}`);
40
+ }
41
+ mkdirSync(join(stateDir, "definitions"), { recursive: true, mode: 0o700 });
42
+ try {
43
+ writeFileSync(dest, bytes, { flag: "wx", mode: 0o600 });
44
+ }
45
+ catch (err) {
46
+ if (err.code !== "EEXIST")
47
+ throw err;
48
+ const raced = readFileSync(dest);
49
+ if (raced.equals(bytes))
50
+ return;
51
+ throw new Error(`downstream-manifest-conflict:${digest}`);
52
+ }
53
+ }
package/dist/demo.js CHANGED
@@ -6,7 +6,7 @@ import { join } from "node:path";
6
6
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
7
7
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
8
8
  import { exportJWK, generateKeyPair, SignJWT } from "jose";
9
- import { verifyLedger } from "@verax-ai/proxy";
9
+ import { terminalText, verifyLedger } from "@verax-ai/proxy";
10
10
  import { runApprove } from "./approve-cli.js";
11
11
  import { listen } from "./server.js";
12
12
  import { shippedPolicyPath } from "./shipped-policy.js";
@@ -341,8 +341,8 @@ export async function runDemo(argv, env, io, opts) {
341
341
  if (!denied)
342
342
  throw new Error(`demo: message.send ${toolText(sent)}`);
343
343
  writeOut(`message.send -> ops@${DENY_HOST}\n`);
344
- writeOut(` refused ${denied.code} (signed)\n`);
345
- writeOut(` ref ${denied.ref}\n`);
344
+ writeOut(` refused ${terminalText(denied.code)} (signed)\n`);
345
+ writeOut(` ref ${terminalText(denied.ref)}\n`);
346
346
  writeOut("\n");
347
347
  const spent = await client.callTool({
348
348
  name: "spend",
@@ -398,7 +398,7 @@ export async function runDemo(argv, env, io, opts) {
398
398
  const secretsDenied = parseTagged(secrets.text, "denied");
399
399
  writeOut("conarium.query public.secrets\n");
400
400
  if (secretsDenied) {
401
- writeOut(` refused ${secretsDenied.code} (signed)\n`);
401
+ writeOut(` refused ${terminalText(secretsDenied.code)} (signed)\n`);
402
402
  failed = true;
403
403
  }
404
404
  else if (childAnsweredWithError(secrets.text, "conarium.query")) {
@@ -419,7 +419,7 @@ export async function runDemo(argv, env, io, opts) {
419
419
  writeOut("conarium.list_tables\n");
420
420
  if (!listedDenied)
421
421
  throw new Error(`demo: conarium.list_tables ${listed.text}`);
422
- writeOut(` refused ${listedDenied.code} (signed)\n`);
422
+ writeOut(` refused ${terminalText(listedDenied.code)} (signed)\n`);
423
423
  writeOut(" refused by this gate; the downstream server never saw the call\n");
424
424
  writeOut("\n");
425
425
  }
@@ -442,8 +442,8 @@ export async function runDemo(argv, env, io, opts) {
442
442
  findingCode = "unparsed";
443
443
  }
444
444
  writeOut("audit.explain of the refuse\n");
445
- writeOut(` finding ${findingCode}\n`);
446
- writeOut(` trust-root ${trust}\n`);
445
+ writeOut(` finding ${terminalText(findingCode)}\n`);
446
+ writeOut(` trust-root ${terminalText(trust)}\n`);
447
447
  if (findingCode === "none" && trust !== "unread") {
448
448
  writeOut(" chain and signatures read back\n");
449
449
  }
@@ -461,8 +461,8 @@ export async function runDemo(argv, env, io, opts) {
461
461
  writeOut(`records ${counted.decisions}\n`);
462
462
  writeOut(`effects ${counted.effects}\n`);
463
463
  if (keep) {
464
- writeOut(`ledger ${stateDir}\n`);
465
- writeOut(`verax verify ${stateDir}\n`);
464
+ writeOut(`ledger ${terminalText(stateDir)}\n`);
465
+ writeOut(`verax verify ${terminalText(stateDir)}\n`);
466
466
  }
467
467
  else {
468
468
  writeOut("ledger removed on exit (run with --keep to keep it and check it with verax verify)\n");
@@ -476,10 +476,10 @@ export async function runDemo(argv, env, io, opts) {
476
476
  const detail = err instanceof Error ? err.message : "fault";
477
477
  if (withConarium && attachFailedDetail(detail)) {
478
478
  discardState = true;
479
- writeErr(`could not start the Conarium child (${detail}). run without --with-conarium\n`);
479
+ writeErr(`could not start the Conarium child (${terminalText(detail)}). run without --with-conarium\n`);
480
480
  }
481
481
  else {
482
- writeErr(`demo: ${detail.replace(/^demo: /, "")}\n`);
482
+ writeErr(`demo: ${terminalText(detail.replace(/^demo: /, ""))}\n`);
483
483
  }
484
484
  await cleanup();
485
485
  return 1;
package/dist/doctor.js CHANGED
@@ -241,6 +241,22 @@ export function runDoctor(env, argv, opts = {}) {
241
241
  detail: `stdio child ${spec.prefix} runs as the same user as the body and can read the body's signing keys (keys/*.pem). An untrusted child should be reached over HTTP, ideally on a separate machine or under a separate operating-system user.`,
242
242
  });
243
243
  }
244
+ for (const spec of specs) {
245
+ if (spec.pins === undefined) {
246
+ checks.push({
247
+ id: `downstream-unpinned:${spec.prefix}`,
248
+ level: "warn",
249
+ detail: `child ${spec.prefix} has no pins; tool definitions are not compared at start`,
250
+ });
251
+ }
252
+ if (spec.command !== undefined && fetchesUnversionedPackage(spec.command, spec.args ?? [])) {
253
+ checks.push({
254
+ id: `downstream-unversioned:${spec.prefix}`,
255
+ level: "warn",
256
+ detail: `child ${spec.prefix} fetches a package with no version. A version is a name for the code, not proof of its integrity.`,
257
+ });
258
+ }
259
+ }
244
260
  }
245
261
  catch (err) {
246
262
  checks.push({
@@ -253,6 +269,62 @@ export function runDoctor(env, argv, opts = {}) {
253
269
  checks.push(...jwksFileChecks(env, stateDir));
254
270
  return checks;
255
271
  }
272
+ function commandBase(command) {
273
+ const slash = Math.max(command.lastIndexOf("/"), command.lastIndexOf("\\"));
274
+ const base = (slash === -1 ? command : command.slice(slash + 1)).toLowerCase();
275
+ return base.replace(/\.(cmd|exe|bat)$/, "");
276
+ }
277
+ /** The package named by `--package` / `--from`, when that flag is present. */
278
+ function flaggedSpec(args, flag) {
279
+ for (let i = 0; i < args.length; i += 1) {
280
+ const arg = args[i];
281
+ if (arg === flag)
282
+ return { present: true, value: args[i + 1] };
283
+ if (arg.startsWith(`${flag}=`))
284
+ return { present: true, value: arg.slice(flag.length + 1) };
285
+ }
286
+ return { present: false };
287
+ }
288
+ /** First argument that is not a flag. `-y` and `--yes` are flags and are skipped. */
289
+ function positionalSpec(args) {
290
+ for (const arg of args) {
291
+ if (arg === "-y" || arg === "--yes" || arg.startsWith("-"))
292
+ continue;
293
+ return arg;
294
+ }
295
+ return undefined;
296
+ }
297
+ /** major.minor.patch, with an optional prerelease or build. A dist-tag or a range is not this. */
298
+ const FULL_VERSION = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
299
+ /** `name@1.2.3`. A scoped name's leading `@` is not a version. */
300
+ function npxVersioned(spec) {
301
+ const at = spec.startsWith("@") ? spec.indexOf("@", 1) : spec.indexOf("@");
302
+ return at > 0 && FULL_VERSION.test(spec.slice(at + 1));
303
+ }
304
+ /** `name==1.2.3`. `>=`, `~=` and `*` leave the package unversioned. */
305
+ function uvxVersioned(spec) {
306
+ const at = spec.indexOf("==");
307
+ if (at <= 0)
308
+ return false;
309
+ const version = spec.slice(at + 2);
310
+ return FULL_VERSION.test(version);
311
+ }
312
+ /**
313
+ * True when `npx` or `uvx` fetches a package that carries no version.
314
+ * `npx name@1.2.3`, `npx --package name@1.2.3`, `uvx name==1.2.3` and
315
+ * `uvx --from name==1.2.3` are versioned. Any other command is not this check.
316
+ */
317
+ function fetchesUnversionedPackage(command, args) {
318
+ const base = commandBase(command);
319
+ if (base !== "npx" && base !== "uvx")
320
+ return false;
321
+ const flag = base === "npx" ? "--package" : "--from";
322
+ const named = flaggedSpec(args, flag);
323
+ const spec = named.present ? named.value : positionalSpec(args);
324
+ if (spec === undefined || spec === "" || spec.startsWith("-"))
325
+ return true;
326
+ return base === "npx" ? !npxVersioned(spec) : !uvxVersioned(spec);
327
+ }
256
328
  function jwksFileChecks(env, stateDir) {
257
329
  const file = env.VERAX_JWKS_FILE?.trim() ?? "";
258
330
  if (file === "")
@@ -0,0 +1,9 @@
1
+ export type DownstreamPinIO = {
2
+ out: (s: string) => void;
3
+ ask: () => Promise<string>;
4
+ };
5
+ export declare function renderToolEntry(entry: unknown): string;
6
+ export declare function runDownstreamPin(input: {
7
+ file: string;
8
+ prefix: string;
9
+ }, io: DownstreamPinIO): Promise<number>;
@@ -0,0 +1,273 @@
1
+ import { createHash } from "node:crypto";
2
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { userInfo } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { canonical } from "@cedulon/core";
6
+ import { DISPLAY_ESCAPE_CLASS, sha256Canonical } from "@verax-ai/proxy";
7
+ import { defaultElevated } from "./install.js";
8
+ import { listDownstreamOnce, parseDownstreamDocument } from "./downstream.js";
9
+ /**
10
+ * `verax downstream pin` lists one child's tools a single time, shows each
11
+ * entry with characters that draw nothing visible as escapes, and writes a
12
+ * content-addressed manifest beside the downstream document only after the
13
+ * operator types yes. The document is never edited. The operator copies the
14
+ * printed pins line into it, so this command cannot race another editor on
15
+ * that file.
16
+ */
17
+ const PINS_RE = /^sha256:([0-9a-f]{64})$/;
18
+ function say(out, text) {
19
+ out(text.endsWith("\n") ? text : `${text}\n`);
20
+ }
21
+ function errorText(err) {
22
+ return err instanceof Error && err.message !== "" ? err.message : "downstream-pin-failed";
23
+ }
24
+ /**
25
+ * Control and format characters, and the other code points that draw nothing
26
+ * (default-ignorable code points, variation selectors, the braille blank,
27
+ * every space separator except U+0020), are written as `\uXXXX` so a child
28
+ * cannot hide text or drive the terminal. A supplementary-plane code point
29
+ * is two escapes, one per UTF-16 unit. The entry itself is not shortened.
30
+ *
31
+ * A written escape and the character it names must not look the same. A real
32
+ * backslash is written as two characters first, then the class is escaped:
33
+ * the same rule as `plain()` on the door page. A JSON line has already
34
+ * doubled every backslash, so it uses `escapeVisible` alone; doubling it
35
+ * again would change the value. Every other line uses `escapeLine`.
36
+ */
37
+ function escapeVisible(text) {
38
+ return text.replace(new RegExp(`[${DISPLAY_ESCAPE_CLASS}]`, "gu"), (ch) => {
39
+ const cp = ch.codePointAt(0) ?? 0;
40
+ if (cp <= 0xffff)
41
+ return `\\u${cp.toString(16).padStart(4, "0")}`;
42
+ const rest = cp - 0x10000;
43
+ const high = 0xd800 + (rest >> 10);
44
+ const low = 0xdc00 + (rest & 0x3ff);
45
+ return `\\u${high.toString(16).padStart(4, "0")}\\u${low.toString(16).padStart(4, "0")}`;
46
+ });
47
+ }
48
+ function escapeLine(text) {
49
+ return escapeVisible(text.replace(/\\/g, "\\\\"));
50
+ }
51
+ export function renderToolEntry(entry) {
52
+ let encoded;
53
+ try {
54
+ encoded = canonical(entry);
55
+ }
56
+ catch {
57
+ encoded = JSON.stringify(entry) ?? "null";
58
+ }
59
+ return escapeVisible(encoded);
60
+ }
61
+ function runningAccount() {
62
+ if (process.platform === "win32") {
63
+ const name = process.env.USERNAME?.trim() ?? "";
64
+ const domain = process.env.USERDOMAIN?.trim() ?? "";
65
+ if (name !== "")
66
+ return domain !== "" ? `${domain}\\${name}` : name;
67
+ }
68
+ try {
69
+ const info = userInfo();
70
+ const name = info.username || "unknown";
71
+ if (typeof info.uid === "number" && info.uid >= 0)
72
+ return `${name} (uid ${info.uid})`;
73
+ return name;
74
+ }
75
+ catch {
76
+ return "unknown";
77
+ }
78
+ }
79
+ /** Windows elevation, or POSIX uid 0. An HTTP child is not spawned here, so it is not refused. */
80
+ function stdioElevationRefusal(prefix) {
81
+ if (process.platform === "win32") {
82
+ try {
83
+ if (!defaultElevated("win32"))
84
+ return null;
85
+ }
86
+ catch (err) {
87
+ return `refusing: could not tell whether this process is elevated (${errorText(err)}); stdio child ${prefix} was not started`;
88
+ }
89
+ return `refusing: this process is elevated, so stdio child ${prefix} was not started`;
90
+ }
91
+ if (typeof process.getuid === "function" && process.getuid() === 0) {
92
+ return `refusing: this process is uid 0, so stdio child ${prefix} was not started`;
93
+ }
94
+ return null;
95
+ }
96
+ function showDifference(out, spec, tools, docDir) {
97
+ if (spec.pins === undefined)
98
+ return;
99
+ const digest = PINS_RE.exec(spec.pins)?.[1];
100
+ if (digest === undefined) {
101
+ say(out, escapeLine(`pins ${spec.pins} is not a digest`));
102
+ return;
103
+ }
104
+ const path = join(docDir, "definitions", `${digest}.json`);
105
+ let bytes;
106
+ try {
107
+ bytes = readFileSync(path);
108
+ }
109
+ catch (err) {
110
+ say(out, escapeLine(`named manifest sha256:${digest} could not be read: ${errorText(err)}`));
111
+ return;
112
+ }
113
+ if (createHash("sha256").update(bytes).digest("hex") !== digest) {
114
+ say(out, escapeLine(`named manifest sha256:${digest} does not hash to its name`));
115
+ return;
116
+ }
117
+ let parsed;
118
+ try {
119
+ parsed = JSON.parse(bytes.toString("utf8"));
120
+ }
121
+ catch {
122
+ say(out, escapeLine(`named manifest sha256:${digest} is not json`));
123
+ return;
124
+ }
125
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
126
+ say(out, escapeLine(`named manifest sha256:${digest} is not an object`));
127
+ return;
128
+ }
129
+ const rec = parsed;
130
+ if (rec.prefix !== spec.prefix) {
131
+ say(out, escapeLine(`manifest prefix differs from ${spec.prefix}`));
132
+ }
133
+ try {
134
+ if (canonical(rec.selected ?? null) !== canonical(spec.tools ?? null)) {
135
+ say(out, escapeLine("manifest selection differs from the document"));
136
+ }
137
+ }
138
+ catch {
139
+ say(out, escapeLine("manifest selection could not be compared"));
140
+ }
141
+ if (rec.tools === null || typeof rec.tools !== "object" || Array.isArray(rec.tools)) {
142
+ say(out, escapeLine("manifest tools are not an object"));
143
+ return;
144
+ }
145
+ const previous = rec.tools;
146
+ const names = [...new Set([...Object.keys(previous), ...Object.keys(tools)])].sort();
147
+ let differed = false;
148
+ for (const name of names) {
149
+ const before = Object.hasOwn(previous, name) ? previous[name] : undefined;
150
+ const after = Object.hasOwn(tools, name) ? tools[name] : undefined;
151
+ if (before === undefined) {
152
+ differed = true;
153
+ say(out, escapeLine(`added ${name}`));
154
+ continue;
155
+ }
156
+ if (after === undefined) {
157
+ differed = true;
158
+ say(out, escapeLine(`removed ${name}`));
159
+ say(out, renderToolEntry(before));
160
+ continue;
161
+ }
162
+ if (sha256Canonical(before) !== sha256Canonical(after)) {
163
+ differed = true;
164
+ say(out, escapeLine(`changed ${name}`));
165
+ say(out, renderToolEntry(before));
166
+ }
167
+ }
168
+ if (!differed)
169
+ say(out, escapeLine(`listed definitions match sha256:${digest}`));
170
+ }
171
+ function writeManifest(docDir, manifest) {
172
+ const bytes = canonical(manifest);
173
+ const digest = sha256Canonical(manifest);
174
+ const folder = join(docDir, "definitions");
175
+ const dest = join(folder, `${digest}.json`);
176
+ // The file is named by its digest, and the operator's document names that
177
+ // digest, so the manifest is not a secret. 0755 and 0644 let the account
178
+ // that runs the body read a manifest an operator account wrote. chmod
179
+ // follows the create because the process umask would otherwise clear
180
+ // the other-read and other-execute bits.
181
+ mkdirSync(folder, { recursive: true, mode: 0o755 });
182
+ chmodSync(folder, 0o755);
183
+ try {
184
+ writeFileSync(dest, bytes, { encoding: "utf8", flag: "wx", mode: 0o644 });
185
+ }
186
+ catch (err) {
187
+ if (err.code !== "EEXIST")
188
+ return { ok: false, reason: errorText(err) };
189
+ let existing;
190
+ try {
191
+ existing = readFileSync(dest);
192
+ }
193
+ catch (readErr) {
194
+ return { ok: false, reason: errorText(readErr) };
195
+ }
196
+ if (!existing.equals(Buffer.from(bytes, "utf8"))) {
197
+ return { ok: false, reason: `downstream-manifest-conflict:${digest}` };
198
+ }
199
+ }
200
+ chmodSync(dest, 0o644);
201
+ return { ok: true, digest };
202
+ }
203
+ export async function runDownstreamPin(input, io) {
204
+ let specs;
205
+ try {
206
+ specs = parseDownstreamDocument(readFileSync(input.file, "utf8"));
207
+ }
208
+ catch (err) {
209
+ say(io.out, escapeLine(errorText(err)));
210
+ return 1;
211
+ }
212
+ const spec = specs.find((item) => item.prefix === input.prefix);
213
+ if (spec === undefined) {
214
+ say(io.out, escapeLine(`no downstream child with prefix ${input.prefix}`));
215
+ return 1;
216
+ }
217
+ if (spec.command !== undefined) {
218
+ say(io.out, escapeLine(`stdio child ${spec.prefix} will run as ${runningAccount()}`));
219
+ const refusal = stdioElevationRefusal(spec.prefix);
220
+ if (refusal !== null) {
221
+ say(io.out, escapeLine(refusal));
222
+ return 1;
223
+ }
224
+ }
225
+ // Elevation was refused above, before this call. The tools returned here are
226
+ // the snapshot that is shown and, after yes, written. There is no second list.
227
+ let listed;
228
+ try {
229
+ listed = await listDownstreamOnce(spec);
230
+ }
231
+ catch (err) {
232
+ const stderr = err.stderr;
233
+ if (typeof stderr === "string" && stderr !== "") {
234
+ say(io.out, "child stderr:");
235
+ say(io.out, escapeLine(stderr));
236
+ }
237
+ say(io.out, escapeLine(errorText(err)));
238
+ return 1;
239
+ }
240
+ if (listed.stderr !== "") {
241
+ say(io.out, "child stderr:");
242
+ say(io.out, escapeLine(listed.stderr));
243
+ }
244
+ const tools = listed.tools;
245
+ for (const name of Object.keys(tools).sort())
246
+ say(io.out, renderToolEntry(tools[name]));
247
+ showDifference(io.out, spec, tools, dirname(input.file));
248
+ let answer;
249
+ try {
250
+ answer = await io.ask();
251
+ }
252
+ catch (err) {
253
+ say(io.out, escapeLine(errorText(err)));
254
+ return 1;
255
+ }
256
+ if (answer !== "yes")
257
+ return 1;
258
+ const manifest = { v: 1, prefix: spec.prefix, selected: spec.tools ?? null, tools };
259
+ let written;
260
+ try {
261
+ written = writeManifest(dirname(input.file), manifest);
262
+ }
263
+ catch (err) {
264
+ say(io.out, escapeLine(errorText(err)));
265
+ return 1;
266
+ }
267
+ if (!written.ok) {
268
+ say(io.out, escapeLine(written.reason));
269
+ return 1;
270
+ }
271
+ say(io.out, `"pins": "sha256:${written.digest}"`);
272
+ return 0;
273
+ }
@@ -32,12 +32,18 @@ export type DownstreamSpec = {
32
32
  * stops the attach. Absent means every tool the child lists.
33
33
  */
34
34
  tools?: string[];
35
+ /**
36
+ * Content address of the manifest the operator approved: `sha256:` and 64
37
+ * lowercase hex digits. Absent means the child is attached without
38
+ * comparing definitions.
39
+ */
40
+ pins?: string;
35
41
  };
36
42
  export type DownstreamTool = {
37
43
  name: string;
38
44
  /** The child's own description, as `tools/list` gave it. */
39
45
  description?: string;
40
- /** The child's own input schema, republished unchanged. */
46
+ /** The child's input schema, object keys in canonical order. */
41
47
  inputSchema?: unknown;
42
48
  fn: DownstreamToolFn;
43
49
  };
@@ -46,6 +52,7 @@ export type DownstreamSession = {
46
52
  tools: readonly DownstreamTool[];
47
53
  close(): Promise<void>;
48
54
  };
55
+ export declare const CHILD_TOOL_RE: RegExp;
49
56
  export declare class DownstreamCallError extends Error {
50
57
  readonly prefix: string;
51
58
  readonly tool: string;
@@ -60,4 +67,17 @@ export declare function parseDownstreamJson(raw: string, bodyPublicKeyPems?: rea
60
67
  * document at all — the operator wrote it, so it is honoured.
61
68
  */
62
69
  export declare function parseDownstreamDocument(raw: string, bodyPublicKeyPems?: readonly string[]): DownstreamSpec[];
63
- export declare function openDownstream(spec: DownstreamSpec): Promise<DownstreamSession>;
70
+ /**
71
+ * Connects the child once, takes `tools/list` under the same bounds as
72
+ * `openDownstream`, collects stderr, and closes. The returned tools are the
73
+ * snapshot that is shown and, after the operator types yes, written. Listing
74
+ * again would let the child answer differently from the text that was read.
75
+ * On failure the error carries `stderr` when the child wrote any.
76
+ */
77
+ export declare function listDownstreamOnce(spec: DownstreamSpec): Promise<{
78
+ tools: Record<string, unknown>;
79
+ stderr: string;
80
+ }>;
81
+ export declare function openDownstream(spec: DownstreamSpec, opts?: {
82
+ definitionsDir?: string;
83
+ }): Promise<DownstreamSession>;