@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,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>;