@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.
- package/README.md +4 -3
- package/dist/approval-signature.d.ts +19 -0
- package/dist/approval-signature.js +70 -5
- package/dist/approve-cli.js +20 -24
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +146 -14
- package/dist/config.d.ts +27 -0
- package/dist/config.js +72 -1
- package/dist/control-signature.d.ts +4 -0
- package/dist/control-signature.js +20 -5
- package/dist/definitions.d.ts +9 -0
- package/dist/definitions.js +53 -0
- package/dist/demo.js +11 -11
- package/dist/doctor.js +72 -0
- package/dist/downstream-pin.d.ts +9 -0
- package/dist/downstream-pin.js +273 -0
- package/dist/downstream.d.ts +22 -2
- package/dist/downstream.js +312 -44
- package/dist/heartbeat.d.ts +26 -2
- package/dist/heartbeat.js +90 -7
- package/dist/held-spend.d.ts +16 -0
- package/dist/held-spend.js +20 -0
- package/dist/http-io.d.ts +14 -0
- package/dist/http-io.js +46 -0
- package/dist/init-local.d.ts +11 -0
- package/dist/init-local.js +32 -3
- package/dist/install.d.ts +5 -0
- package/dist/install.js +37 -5
- package/dist/main.d.ts +1 -0
- package/dist/main.js +40 -6
- package/dist/operator-cli.d.ts +49 -1
- package/dist/operator-cli.js +136 -8
- package/dist/operator-credentials.d.ts +40 -1
- package/dist/operator-credentials.js +97 -7
- package/dist/operator-door-page.d.ts +3 -0
- package/dist/operator-door-page.js +819 -0
- package/dist/operator-door.d.ts +22 -0
- package/dist/operator-door.js +487 -0
- package/dist/operator-handlers.d.ts +28 -0
- package/dist/operator-handlers.js +221 -0
- package/dist/operator-pairing.d.ts +2 -0
- package/dist/operator-pairing.js +11 -0
- package/dist/reconcile-cli.js +3 -1
- package/dist/server.d.ts +2 -0
- package/dist/server.js +133 -256
- package/dist/verify-cli.js +30 -10
- package/dist/webauthn-verify.d.ts +48 -4
- package/dist/webauthn-verify.js +183 -25
- package/dist/wiring.js +14 -1
- package/package.json +4 -4
package/dist/server.js
CHANGED
|
@@ -1,17 +1,16 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
|
-
import { join } from "node:path";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
4
|
import { createServer } from "node:http";
|
|
5
5
|
import { Server as McpServer } from "@modelcontextprotocol/sdk/server/index.js";
|
|
6
6
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
7
7
|
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
8
|
-
import { decisionRecordHash } from "@cedulon/core";
|
|
9
8
|
import { bodyVersion } from "./body-version.js";
|
|
10
9
|
import { isLoopbackHost } from "./config.js";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
10
|
+
import { contentLengthOverLimit, MAX_BODY_BYTES, readJsonBody, send } from "./http-io.js";
|
|
11
|
+
import { openOperatorDoor } from "./operator-door.js";
|
|
12
|
+
import { handleApprove, handleApproveChallenge, handleControl } from "./operator-handlers.js";
|
|
13
|
+
import { explain, LedgerDenyUnrecorded, loadApprovalsFromDir, loadDecisionRequestHashesFromDir, sha256Canonical, terminalText, } from "@verax-ai/proxy";
|
|
15
14
|
import { createVerifier, readBearer, resourceMetadataUrl, wwwAuthenticate } from "./auth.js";
|
|
16
15
|
import { bumpMetric, bumpUnauthenticated } from "./metrics.js";
|
|
17
16
|
import { isRevokedJti } from "./revoke.js";
|
|
@@ -20,8 +19,7 @@ import { matchingInputs } from "./inputs-read.js";
|
|
|
20
19
|
import { readPolicySnapshots } from "./policy-store.js";
|
|
21
20
|
import { readHeartbeat, readInstallHealthNonce, readWitnessPulse } from "./health-extras.js";
|
|
22
21
|
import { agentsWindow } from "./agents.js";
|
|
23
|
-
import {
|
|
24
|
-
import { haltBody, readHalt, resumeBody } from "./halt.js";
|
|
22
|
+
import { copyDefinition } from "./definitions.js";
|
|
25
23
|
import { recordBodyStart, startHeartbeat } from "./heartbeat.js";
|
|
26
24
|
import { inventoryHealth, readInventoryFile } from "./inventory-file.js";
|
|
27
25
|
import { createBodyServices, TOOL_NAMES } from "./wiring.js";
|
|
@@ -179,11 +177,34 @@ export const TOOL_META = [
|
|
|
179
177
|
},
|
|
180
178
|
},
|
|
181
179
|
];
|
|
182
|
-
const MAX_BODY_BYTES = 1024 * 1024;
|
|
183
180
|
// Node's default requestTimeout is 300s. A stalled body would otherwise stay
|
|
184
181
|
// authorised until that default. Headers are bounded tighter than the body.
|
|
185
182
|
const REQUEST_TIMEOUT_MS = 30_000;
|
|
186
183
|
const HEADERS_TIMEOUT_MS = 20_000;
|
|
184
|
+
/**
|
|
185
|
+
* Amount, currency and payee on a ledger approval are the arguments only when
|
|
186
|
+
* those arguments still hash to the signed request on the defer. Otherwise
|
|
187
|
+
* the copies are left off and the row is marked unbound.
|
|
188
|
+
*/
|
|
189
|
+
function approvalsForLedger(stateDir) {
|
|
190
|
+
const requestHashes = loadDecisionRequestHashesFromDir(stateDir);
|
|
191
|
+
return loadApprovalsFromDir(stateDir).map((row) => {
|
|
192
|
+
const signed = requestHashes.get(row.ref);
|
|
193
|
+
const rowHash = sha256Canonical({ name: row.subject, arguments: row.args });
|
|
194
|
+
const bound = typeof signed === "string" && signed !== "" && rowHash === signed;
|
|
195
|
+
if (!bound) {
|
|
196
|
+
const { amount: _amount, currency: _currency, payee: _payee, ...rest } = row;
|
|
197
|
+
return { ...rest, bound: false };
|
|
198
|
+
}
|
|
199
|
+
return {
|
|
200
|
+
...row,
|
|
201
|
+
bound: true,
|
|
202
|
+
amount: row.args.amountMinor,
|
|
203
|
+
currency: row.args.currency,
|
|
204
|
+
payee: row.args.payee,
|
|
205
|
+
};
|
|
206
|
+
});
|
|
207
|
+
}
|
|
187
208
|
// Unbounded GET /api/ledger stringified ~690 MB at 200k rows and threw Invalid string length (HTTP 500).
|
|
188
209
|
const DEFAULT_LEDGER_LIMIT = 1000;
|
|
189
210
|
const MAX_LEDGER_LIMIT = 5000;
|
|
@@ -222,41 +243,6 @@ export function loopbackHostDecision(hostHeader, bindPort) {
|
|
|
222
243
|
return bindPort === 80 ? "allow" : "deny";
|
|
223
244
|
return port === bindPort ? "allow" : "deny";
|
|
224
245
|
}
|
|
225
|
-
function contentLengthOverLimit(req) {
|
|
226
|
-
const raw = req.headers["content-length"];
|
|
227
|
-
if (raw === undefined)
|
|
228
|
-
return false;
|
|
229
|
-
const n = Number(Array.isArray(raw) ? raw[0] : raw);
|
|
230
|
-
return Number.isFinite(n) && n > MAX_BODY_BYTES;
|
|
231
|
-
}
|
|
232
|
-
async function readJsonBody(req, max) {
|
|
233
|
-
if (contentLengthOverLimit(req))
|
|
234
|
-
return { ok: false, tooLarge: true };
|
|
235
|
-
const chunks = [];
|
|
236
|
-
let seen = 0;
|
|
237
|
-
try {
|
|
238
|
-
for await (const chunk of req) {
|
|
239
|
-
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
240
|
-
seen += buf.length;
|
|
241
|
-
if (seen > max) {
|
|
242
|
-
return { ok: false, tooLarge: true };
|
|
243
|
-
}
|
|
244
|
-
chunks.push(buf);
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
catch {
|
|
248
|
-
return { ok: false, bad: true };
|
|
249
|
-
}
|
|
250
|
-
const text = Buffer.concat(chunks).toString("utf8");
|
|
251
|
-
if (text === "")
|
|
252
|
-
return { ok: true, value: undefined };
|
|
253
|
-
try {
|
|
254
|
-
return { ok: true, value: JSON.parse(text) };
|
|
255
|
-
}
|
|
256
|
-
catch {
|
|
257
|
-
return { ok: false, bad: true };
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
246
|
/**
|
|
261
247
|
* Second look at a bearer that already verified. The first look runs before
|
|
262
248
|
* the body is read; this one runs after the body and before dispatch or
|
|
@@ -276,20 +262,6 @@ function isProtectedResourcePath(pathname, audience) {
|
|
|
276
262
|
const want = new URL(resourceMetadataUrl(audience)).pathname;
|
|
277
263
|
return pathname === want || pathname === "/.well-known/oauth-protected-resource";
|
|
278
264
|
}
|
|
279
|
-
async function signedDefer(ledger, ref) {
|
|
280
|
-
const rows = await ledger.decisions();
|
|
281
|
-
return rows.find((row) => row.claims.ref === ref && row.claims.decision === "defer") ?? null;
|
|
282
|
-
}
|
|
283
|
-
function send(res, status, body, headers) {
|
|
284
|
-
const text = typeof body === "string" ? body : JSON.stringify(body);
|
|
285
|
-
res.writeHead(status, {
|
|
286
|
-
"content-type": "application/json",
|
|
287
|
-
"content-length": Buffer.byteLength(text),
|
|
288
|
-
"x-content-type-options": "nosniff",
|
|
289
|
-
...headers,
|
|
290
|
-
});
|
|
291
|
-
res.end(text);
|
|
292
|
-
}
|
|
293
265
|
/**
|
|
294
266
|
* The body has answered on a response the MCP transport also holds. The
|
|
295
267
|
* transport still writes its own answer when the handler throws; a second
|
|
@@ -352,11 +324,21 @@ function downstreamPublic(sessions, specs) {
|
|
|
352
324
|
async function attachDownstream(file, bodyPublicKeyPems) {
|
|
353
325
|
if (file === null || file.trim() === "")
|
|
354
326
|
return { sessions: [], specs: [] };
|
|
355
|
-
|
|
327
|
+
let text;
|
|
328
|
+
try {
|
|
329
|
+
text = readFileSync(file, "utf8");
|
|
330
|
+
}
|
|
331
|
+
catch {
|
|
332
|
+
// The path stays raw. main() prints a downstream- refusal as one escaped line.
|
|
333
|
+
throw new Error(`downstream-document-unreadable:${file}`);
|
|
334
|
+
}
|
|
335
|
+
const specs = parseDownstreamDocument(text, bodyPublicKeyPems);
|
|
356
336
|
const sessions = [];
|
|
357
337
|
for (const spec of specs) {
|
|
358
338
|
try {
|
|
359
|
-
|
|
339
|
+
// The manifest sits beside the operator's document. An installed body
|
|
340
|
+
// cannot write the state directory, so the pin is read from here.
|
|
341
|
+
sessions.push(await openDownstream(spec, { definitionsDir: dirname(file) }));
|
|
360
342
|
}
|
|
361
343
|
catch (err) {
|
|
362
344
|
await closeAll(sessions);
|
|
@@ -366,6 +348,27 @@ async function attachDownstream(file, bodyPublicKeyPems) {
|
|
|
366
348
|
}
|
|
367
349
|
return { sessions, specs };
|
|
368
350
|
}
|
|
351
|
+
function pinDigest(prefix, pins) {
|
|
352
|
+
const digest = /^sha256:([0-9a-f]{64})$/.exec(pins)?.[1];
|
|
353
|
+
if (digest === undefined)
|
|
354
|
+
throw new Error(`downstream-manifest-invalid:${prefix}`);
|
|
355
|
+
return digest;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* One entry per child, in document order. Pinned manifests are copied into
|
|
359
|
+
* the state directory before the caller writes the start row that names them.
|
|
360
|
+
*/
|
|
361
|
+
function definitionsForStart(stateDir, definitionsDir, specs) {
|
|
362
|
+
const downstream = specs.map((spec) => ({
|
|
363
|
+
prefix: spec.prefix,
|
|
364
|
+
manifest: spec.pins === undefined ? null : pinDigest(spec.prefix, spec.pins),
|
|
365
|
+
}));
|
|
366
|
+
for (const child of downstream) {
|
|
367
|
+
if (child.manifest !== null)
|
|
368
|
+
copyDefinition(stateDir, definitionsDir, child.manifest);
|
|
369
|
+
}
|
|
370
|
+
return downstream;
|
|
371
|
+
}
|
|
369
372
|
export async function listen(config) {
|
|
370
373
|
const signers = loadOrCreateSigners(config.stateDir);
|
|
371
374
|
const bodyPublicKeyPems = [signers.recordSigner.publicKeyPem, signers.effectSigner.publicKeyPem];
|
|
@@ -399,7 +402,12 @@ export async function listen(config) {
|
|
|
399
402
|
}
|
|
400
403
|
try {
|
|
401
404
|
// This must precede syncControlRecords: those records pulse too.
|
|
402
|
-
|
|
405
|
+
// The state copy is written first: the start row names those bytes, and
|
|
406
|
+
// a copy that cannot be made stops the start. No children, no field.
|
|
407
|
+
const downstream = downstreamSpecs.length === 0
|
|
408
|
+
? undefined
|
|
409
|
+
: definitionsForStart(config.stateDir, dirname(config.downstreamFile ?? ""), downstreamSpecs);
|
|
410
|
+
recordBodyStart(config.stateDir, services.ledger.startedAtMs, signers.recordSigner, downstream === undefined ? undefined : { downstream });
|
|
403
411
|
}
|
|
404
412
|
catch (err) {
|
|
405
413
|
services.ledger.close();
|
|
@@ -413,7 +421,7 @@ export async function listen(config) {
|
|
|
413
421
|
// syncControlRecords reports its own failure and does not throw. This
|
|
414
422
|
// catch is the door: a sync miss must not close the ledger or refuse to listen.
|
|
415
423
|
const message = (err instanceof Error ? err.message : String(err)).replace(/[\r\n]+/g, " ");
|
|
416
|
-
process.stderr.write(`verax-proxy: control sync failed: ${message}\n`);
|
|
424
|
+
process.stderr.write(`verax-proxy: control sync failed: ${terminalText(message)}\n`);
|
|
417
425
|
}
|
|
418
426
|
const toolMeta = [...TOOL_META, ...extraTools.map(downstreamMeta)];
|
|
419
427
|
const verify = createVerifier(config.jwksUrl, config.issuer, config.audience, config.jwksFile, config.jwksPin);
|
|
@@ -612,201 +620,30 @@ export async function listen(config) {
|
|
|
612
620
|
return;
|
|
613
621
|
}
|
|
614
622
|
try {
|
|
623
|
+
const operatorRequest = {
|
|
624
|
+
req,
|
|
625
|
+
res,
|
|
626
|
+
url,
|
|
627
|
+
stateDir: config.stateDir,
|
|
628
|
+
services,
|
|
629
|
+
subject: verified.principal.brain,
|
|
630
|
+
scopes: verified.principal.scopes,
|
|
631
|
+
refuseStale: refuseStaleBearer,
|
|
632
|
+
env: process.env,
|
|
633
|
+
};
|
|
615
634
|
if (apiHalt || apiResume || apiControlChallenge) {
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
const operator = scopes.has("verax:audit") || scopes.has("verax:approve");
|
|
620
|
-
const resuming = apiResume || url.pathname === "/api/resume/challenge";
|
|
621
|
-
// Stopping is the safe direction, so any operator session may do it.
|
|
622
|
-
// Lifting a halt lets everything through again: that is an approval of
|
|
623
|
-
// everything at once and needs the approve scope. The agent token
|
|
624
|
-
// carries neither, so an agent cannot stop itself being stopped.
|
|
625
|
-
if (!operator || (resuming && !scopes.has("verax:approve"))) {
|
|
626
|
-
send(res, 403, { error: "scope-missing" });
|
|
627
|
-
return;
|
|
628
|
-
}
|
|
629
|
-
if (apiControlChallenge) {
|
|
630
|
-
const rp = readRpConfig(process.env);
|
|
631
|
-
if (!rp.ok) {
|
|
632
|
-
send(res, 503, { error: "passkey-closed", reason: rp.reason });
|
|
633
|
-
return;
|
|
634
|
-
}
|
|
635
|
-
send(res, 200, {
|
|
636
|
-
...nextControlChallenge(config.stateDir, resuming ? "resume" : "halt"),
|
|
637
|
-
rpId: rp.config.rpID,
|
|
638
|
-
allowCredentials: readCredentials(config.stateDir).map((row) => ({ id: row.id, type: "public-key" })),
|
|
639
|
-
});
|
|
640
|
-
return;
|
|
641
|
-
}
|
|
642
|
-
if (req.method === "GET") {
|
|
643
|
-
send(res, 200, readHalt(config.stateDir));
|
|
644
|
-
return;
|
|
645
|
-
}
|
|
646
|
-
const parsed = await readJsonBody(req, MAX_BODY_BYTES);
|
|
647
|
-
if (await refuseStaleBearer())
|
|
648
|
-
return;
|
|
649
|
-
if (!parsed.ok && apiResume) {
|
|
650
|
-
send(res, 400, { error: "bad-body" });
|
|
651
|
-
return;
|
|
652
|
-
}
|
|
653
|
-
const asked = parsed.ok && parsed.value && typeof parsed.value === "object" ? parsed.value : {};
|
|
654
|
-
// The tail is read inside the gate and the line is appended right
|
|
655
|
-
// after it, with nothing awaited in between.
|
|
656
|
-
const gated = gateControlSignature({
|
|
657
|
-
stateDir: config.stateDir,
|
|
658
|
-
env: process.env,
|
|
659
|
-
action: apiResume ? "resume" : "halt",
|
|
660
|
-
assertion: asked.assertion,
|
|
635
|
+
await handleControl(operatorRequest, {
|
|
636
|
+
resuming: apiResume || url.pathname === "/api/resume/challenge",
|
|
637
|
+
challenge: apiControlChallenge,
|
|
661
638
|
});
|
|
662
|
-
// A refused resume writes nothing. A halt is never refused for its
|
|
663
|
-
// signature: it stops unsigned, and the answer says what was refused.
|
|
664
|
-
if (!gated.ok && apiResume) {
|
|
665
|
-
send(res, gated.status, { error: gated.error, ...(gated.reason ? { reason: gated.reason } : {}) });
|
|
666
|
-
return;
|
|
667
|
-
}
|
|
668
|
-
const signature = gated.ok ? gated.signature : undefined;
|
|
669
|
-
const refused = !parsed.ok ? "bad-body" : gated.ok ? undefined : gated.error;
|
|
670
|
-
const by = verified.principal.brain;
|
|
671
|
-
const state = apiResume
|
|
672
|
-
? resumeBody(config.stateDir, by, "http", Date.now(), signature)
|
|
673
|
-
: {
|
|
674
|
-
...haltBody(config.stateDir, by, "http", Date.now(), signature),
|
|
675
|
-
...(refused ? { signatureRefused: refused } : {}),
|
|
676
|
-
};
|
|
677
|
-
try {
|
|
678
|
-
await services.proxy.syncControlRecords();
|
|
679
|
-
}
|
|
680
|
-
catch (err) {
|
|
681
|
-
// The switch is already on disk. A sync miss must not turn this into a 500.
|
|
682
|
-
const message = (err instanceof Error ? err.message : String(err)).replace(/[\r\n]+/g, " ");
|
|
683
|
-
process.stderr.write(`verax-proxy: control sync failed: ${message}\n`);
|
|
684
|
-
}
|
|
685
|
-
send(res, 200, state);
|
|
686
639
|
return;
|
|
687
640
|
}
|
|
688
641
|
if (apiApproveChallenge) {
|
|
689
|
-
|
|
690
|
-
send(res, 403, { error: "scope-missing" });
|
|
691
|
-
return;
|
|
692
|
-
}
|
|
693
|
-
if (await refuseStaleBearer())
|
|
694
|
-
return;
|
|
695
|
-
const ref = url.searchParams.get("ref") ?? "";
|
|
696
|
-
const deferRecord = ref === "" ? null : await signedDefer(services.ledger, ref);
|
|
697
|
-
if (!deferRecord) {
|
|
698
|
-
send(res, 404, { error: "unknown-ref" });
|
|
699
|
-
return;
|
|
700
|
-
}
|
|
701
|
-
const rp = readRpConfig(process.env);
|
|
702
|
-
if (!rp.ok) {
|
|
703
|
-
send(res, 503, { error: "passkey-closed", reason: rp.reason });
|
|
704
|
-
return;
|
|
705
|
-
}
|
|
706
|
-
send(res, 200, {
|
|
707
|
-
challenge: approvalChallenge({
|
|
708
|
-
ref,
|
|
709
|
-
requestHash: deferRecord.claims.requestHash,
|
|
710
|
-
deferRecordHash: decisionRecordHash(deferRecord),
|
|
711
|
-
}),
|
|
712
|
-
rpId: rp.config.rpID,
|
|
713
|
-
allowCredentials: readCredentials(config.stateDir).map((row) => ({ id: row.id, type: "public-key" })),
|
|
714
|
-
});
|
|
642
|
+
await handleApproveChallenge(operatorRequest);
|
|
715
643
|
return;
|
|
716
644
|
}
|
|
717
645
|
if (apiApprove) {
|
|
718
|
-
|
|
719
|
-
// every door above; this one signs a new decision and lets money go,
|
|
720
|
-
// so it has a scope of its own.
|
|
721
|
-
if (!verified.principal.scopes.has("verax:approve")) {
|
|
722
|
-
send(res, 403, { error: "scope-missing" });
|
|
723
|
-
return;
|
|
724
|
-
}
|
|
725
|
-
const parsed = await readJsonBody(req, MAX_BODY_BYTES);
|
|
726
|
-
if (await refuseStaleBearer())
|
|
727
|
-
return;
|
|
728
|
-
if (!parsed.ok) {
|
|
729
|
-
send(res, 400, { error: "bad-body" });
|
|
730
|
-
return;
|
|
731
|
-
}
|
|
732
|
-
const asked = (parsed.value ?? {});
|
|
733
|
-
const ref = typeof asked.ref === "string" ? asked.ref : "";
|
|
734
|
-
const sawHash = typeof asked.requestHash === "string" ? asked.requestHash : "";
|
|
735
|
-
if (ref === "" || sawHash === "") {
|
|
736
|
-
send(res, 400, { error: "ref-and-requestHash-required" });
|
|
737
|
-
return;
|
|
738
|
-
}
|
|
739
|
-
const waiting = loadApprovalsFromDir(config.stateDir).find((row) => row.ref === ref);
|
|
740
|
-
if (!waiting) {
|
|
741
|
-
send(res, 404, { error: "unknown-ref" });
|
|
742
|
-
return;
|
|
743
|
-
}
|
|
744
|
-
// The list on a phone can be ten minutes old. An approval names the
|
|
745
|
-
// request the operator was looking at, and if that is not what is
|
|
746
|
-
// waiting any more, nothing is approved: "I approved what I saw" is
|
|
747
|
-
// only true when something checks it.
|
|
748
|
-
if (waiting.requestHash !== sawHash) {
|
|
749
|
-
send(res, 409, { error: "stale", requestHash: waiting.requestHash });
|
|
750
|
-
return;
|
|
751
|
-
}
|
|
752
|
-
const deferRecord = await signedDefer(services.ledger, ref);
|
|
753
|
-
if (!deferRecord) {
|
|
754
|
-
send(res, 404, { error: "unknown-ref" });
|
|
755
|
-
return;
|
|
756
|
-
}
|
|
757
|
-
const deferRecordHash = decisionRecordHash(deferRecord);
|
|
758
|
-
// The challenge is rebuilt from the defer on disk, not from anything the client sent.
|
|
759
|
-
const gated = await gateApprovalSignature({
|
|
760
|
-
stateDir: config.stateDir,
|
|
761
|
-
env: process.env,
|
|
762
|
-
assertion: asked.assertion,
|
|
763
|
-
ref,
|
|
764
|
-
requestHash: deferRecord.claims.requestHash,
|
|
765
|
-
deferRecordHash,
|
|
766
|
-
});
|
|
767
|
-
if (!gated.ok) {
|
|
768
|
-
send(res, gated.status, {
|
|
769
|
-
error: gated.error,
|
|
770
|
-
...(gated.reason ? { reason: gated.reason } : {}),
|
|
771
|
-
});
|
|
772
|
-
return;
|
|
773
|
-
}
|
|
774
|
-
// Who approved, on the record. The CLI writes the machine's login name,
|
|
775
|
-
// which says nothing about the person holding the phone; the session's
|
|
776
|
-
// own subject does.
|
|
777
|
-
const approver = verified.principal.brain;
|
|
778
|
-
const approvals = approvalsLogFor(services.ledger);
|
|
779
|
-
const outcome = await approvePending({
|
|
780
|
-
ledger: services.ledger,
|
|
781
|
-
recordSigner: loadOrCreateSigners(config.stateDir).recordSigner,
|
|
782
|
-
now: () => Date.now(),
|
|
783
|
-
nonce: () => crypto.randomUUID(),
|
|
784
|
-
ref,
|
|
785
|
-
approverId: approver,
|
|
786
|
-
via: "http",
|
|
787
|
-
policyHash: deferRecord.claims.policyHash,
|
|
788
|
-
...(gated.signature ? { signature: gated.signature } : {}),
|
|
789
|
-
approvals,
|
|
790
|
-
budgetGuard: createApprovalBudgetGuard({
|
|
791
|
-
policy: services.policy,
|
|
792
|
-
approvals,
|
|
793
|
-
now: () => Date.now(),
|
|
794
|
-
ledger: services.ledger,
|
|
795
|
-
}),
|
|
796
|
-
});
|
|
797
|
-
if (!outcome.ok) {
|
|
798
|
-
if (outcome.reason === "halted") {
|
|
799
|
-
send(res, 409, { error: "approve-halted" });
|
|
800
|
-
return;
|
|
801
|
-
}
|
|
802
|
-
const code = outcome.reason === "unknown-ref" || outcome.reason === "snapshot-missing" ? 404 : 409;
|
|
803
|
-
send(res, code, {
|
|
804
|
-
error: outcome.reason,
|
|
805
|
-
...(outcome.allowRef ? { allowRef: outcome.allowRef } : {}),
|
|
806
|
-
});
|
|
807
|
-
return;
|
|
808
|
-
}
|
|
809
|
-
send(res, 200, { allowRef: outcome.allowRef, approver });
|
|
646
|
+
await handleApprove(operatorRequest);
|
|
810
647
|
return;
|
|
811
648
|
}
|
|
812
649
|
if (apiLedger || apiInventory || contest || apiAgents) {
|
|
@@ -876,7 +713,7 @@ export async function listen(config) {
|
|
|
876
713
|
policy: { hash: services.policyHash, document: services.policyDocument },
|
|
877
714
|
policies: readPolicySnapshots(config.stateDir, hashes),
|
|
878
715
|
inputs: await matchingInputs(config.stateDir, decisions),
|
|
879
|
-
approvals:
|
|
716
|
+
approvals: approvalsForLedger(config.stateDir),
|
|
880
717
|
more,
|
|
881
718
|
piecesTouched,
|
|
882
719
|
limit,
|
|
@@ -953,7 +790,7 @@ export async function listen(config) {
|
|
|
953
790
|
return;
|
|
954
791
|
}
|
|
955
792
|
const detail = err instanceof Error ? err.message : "fault";
|
|
956
|
-
process.stderr.write(`verax-transport: ${detail}\n`);
|
|
793
|
+
process.stderr.write(`verax-transport: ${terminalText(detail)}\n`);
|
|
957
794
|
if (!res.headersSent) {
|
|
958
795
|
send(res, 500, { error: "transport" });
|
|
959
796
|
}
|
|
@@ -974,7 +811,7 @@ export async function listen(config) {
|
|
|
974
811
|
send(res, 400, { error: "bad-request" });
|
|
975
812
|
return;
|
|
976
813
|
}
|
|
977
|
-
process.stderr.write(`verax-handler: ${msg || "fault"}\n`);
|
|
814
|
+
process.stderr.write(`verax-handler: ${terminalText(msg || "fault")}\n`);
|
|
978
815
|
send(res, 500, { error: "fault" });
|
|
979
816
|
}
|
|
980
817
|
}
|
|
@@ -985,7 +822,7 @@ export async function listen(config) {
|
|
|
985
822
|
send(res, 400, { error: "bad-request" });
|
|
986
823
|
return;
|
|
987
824
|
}
|
|
988
|
-
process.stderr.write(`verax-handler: ${err instanceof Error ? err.message : "fault"}\n`);
|
|
825
|
+
process.stderr.write(`verax-handler: ${terminalText(err instanceof Error ? err.message : "fault")}\n`);
|
|
989
826
|
send(res, 500, { error: "fault" });
|
|
990
827
|
}
|
|
991
828
|
finally {
|
|
@@ -994,10 +831,43 @@ export async function listen(config) {
|
|
|
994
831
|
});
|
|
995
832
|
server.requestTimeout = REQUEST_TIMEOUT_MS;
|
|
996
833
|
server.headersTimeout = HEADERS_TIMEOUT_MS;
|
|
834
|
+
// Closing the ledger can fail, on a disk that has gone read-only for one.
|
|
835
|
+
// That is said on stderr and goes no further: thrown from a close listener
|
|
836
|
+
// it would stop the listeners after it and take the process down, and
|
|
837
|
+
// thrown after a failed start it would replace the reason the start failed.
|
|
838
|
+
const closeLedger = () => {
|
|
839
|
+
try {
|
|
840
|
+
services.ledger.close();
|
|
841
|
+
}
|
|
842
|
+
catch (err) {
|
|
843
|
+
process.stderr.write(`verax: ledger close: ${terminalText(err instanceof Error ? err.message : "fault")}\n`);
|
|
844
|
+
}
|
|
845
|
+
};
|
|
997
846
|
server.on("close", () => {
|
|
998
|
-
|
|
847
|
+
closeLedger();
|
|
999
848
|
void closeAll(sessions);
|
|
1000
849
|
});
|
|
850
|
+
const stopStart = async () => {
|
|
851
|
+
closeLedger();
|
|
852
|
+
await closeAll(sessions);
|
|
853
|
+
};
|
|
854
|
+
// A door that was asked for and cannot open stops the start: an operator
|
|
855
|
+
// who expects to approve from away must not find that out with a call held.
|
|
856
|
+
// It opens before the main listener answers anything, so a body whose
|
|
857
|
+
// /healthz answers has its door, and the port is not someone else's.
|
|
858
|
+
let door = null;
|
|
859
|
+
if (config.operatorDoor) {
|
|
860
|
+
try {
|
|
861
|
+
door = await openOperatorDoor({ door: config.operatorDoor, stateDir: config.stateDir, services });
|
|
862
|
+
}
|
|
863
|
+
catch (err) {
|
|
864
|
+
await stopStart();
|
|
865
|
+
throw err;
|
|
866
|
+
}
|
|
867
|
+
const opened = door;
|
|
868
|
+
// First among the close listeners: the door shuts even when closing the ledger throws.
|
|
869
|
+
server.prependOnceListener("close", () => opened.close());
|
|
870
|
+
}
|
|
1001
871
|
try {
|
|
1002
872
|
await new Promise((resolve, reject) => {
|
|
1003
873
|
server.once("error", reject);
|
|
@@ -1005,8 +875,8 @@ export async function listen(config) {
|
|
|
1005
875
|
});
|
|
1006
876
|
}
|
|
1007
877
|
catch (err) {
|
|
1008
|
-
|
|
1009
|
-
await
|
|
878
|
+
door?.close();
|
|
879
|
+
await stopStart();
|
|
1010
880
|
throw err;
|
|
1011
881
|
}
|
|
1012
882
|
const bound = server.address();
|
|
@@ -1023,6 +893,13 @@ export async function listen(config) {
|
|
|
1023
893
|
await new Promise((resolve) => server.close(() => resolve()));
|
|
1024
894
|
throw err;
|
|
1025
895
|
}
|
|
896
|
+
if (door)
|
|
897
|
+
doors.set(server, door);
|
|
1026
898
|
return server;
|
|
1027
899
|
}
|
|
900
|
+
const doors = new WeakMap();
|
|
901
|
+
/** The operator door opened with this body, or null when it is shut. */
|
|
902
|
+
export function operatorDoorOf(server) {
|
|
903
|
+
return doors.get(server) ?? null;
|
|
904
|
+
}
|
|
1028
905
|
export { TOOL_NAMES };
|
package/dist/verify-cli.js
CHANGED
|
@@ -17,11 +17,11 @@
|
|
|
17
17
|
* unattested. A record, effect or witness key cannot be a third-party pin.
|
|
18
18
|
*/
|
|
19
19
|
import { readFileSync } from "node:fs";
|
|
20
|
-
import { verifyLedger } from "@verax-ai/proxy";
|
|
20
|
+
import { terminalLines, terminalText, verifyLedger } from "@verax-ai/proxy";
|
|
21
21
|
import { verifyApprovalSignatures } from "./approval-signature.js";
|
|
22
22
|
import { verifyControlSignatures } from "./control-signature.js";
|
|
23
23
|
import { directoryAccess, unreadableSentence } from "./install.js";
|
|
24
|
-
import { readStartSummary,
|
|
24
|
+
import { readStartSummary, startLines } from "./heartbeat.js";
|
|
25
25
|
export const EX_VERIFY_FAILED = 1;
|
|
26
26
|
function usage() {
|
|
27
27
|
return [
|
|
@@ -89,6 +89,7 @@ const APPROVAL_NOT_CHECKED = {
|
|
|
89
89
|
ok: true,
|
|
90
90
|
signedVerified: 0,
|
|
91
91
|
signedFailed: 0,
|
|
92
|
+
signedAfterRemoval: 0,
|
|
92
93
|
unsignedHttp: 0,
|
|
93
94
|
cli: 0,
|
|
94
95
|
line: "approval signatures not checked",
|
|
@@ -99,6 +100,7 @@ const CONTROL_NOT_CHECKED = {
|
|
|
99
100
|
ok: true,
|
|
100
101
|
signedVerified: 0,
|
|
101
102
|
signedFailed: 0,
|
|
103
|
+
signedAfterRemoval: 0,
|
|
102
104
|
unsignedHttp: 0,
|
|
103
105
|
cli: 0,
|
|
104
106
|
file: 0,
|
|
@@ -170,7 +172,7 @@ export function renderVerify(r, approval = APPROVAL_NOT_CHECKED, control = CONTR
|
|
|
170
172
|
// Halt and resume signatures are checked under the same operator key.
|
|
171
173
|
lines.push(control.line);
|
|
172
174
|
if (starts)
|
|
173
|
-
lines.push(
|
|
175
|
+
lines.push(...startLines(starts));
|
|
174
176
|
if (r.problems.length > 0) {
|
|
175
177
|
lines.push("");
|
|
176
178
|
lines.push("problems:");
|
|
@@ -181,7 +183,9 @@ export function renderVerify(r, approval = APPROVAL_NOT_CHECKED, control = CONTR
|
|
|
181
183
|
}
|
|
182
184
|
lines.push("");
|
|
183
185
|
lines.push(r.ok ? "VERIFIED" : "NOT VERIFIED");
|
|
184
|
-
|
|
186
|
+
// Escape before the join. verify reads a ledger someone else wrote, and a
|
|
187
|
+
// line break in that text must not become a line of its own.
|
|
188
|
+
return lines.map((line) => terminalText(line)).join("\n");
|
|
185
189
|
}
|
|
186
190
|
export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`)) {
|
|
187
191
|
const args = [...argv];
|
|
@@ -213,7 +217,7 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
|
|
|
213
217
|
return { ok: true, pem };
|
|
214
218
|
}
|
|
215
219
|
catch {
|
|
216
|
-
out(`verify: cannot read key file ${path}`);
|
|
220
|
+
out(terminalText(`verify: cannot read key file ${path}`));
|
|
217
221
|
return { ok: false };
|
|
218
222
|
}
|
|
219
223
|
};
|
|
@@ -288,7 +292,7 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
|
|
|
288
292
|
}
|
|
289
293
|
}
|
|
290
294
|
catch {
|
|
291
|
-
out(`verify: cannot read operator credentials file ${path}`);
|
|
295
|
+
out(terminalText(`verify: cannot read operator credentials file ${path}`));
|
|
292
296
|
return EX_VERIFY_FAILED;
|
|
293
297
|
}
|
|
294
298
|
args.splice(credentialsAt, 2);
|
|
@@ -300,7 +304,7 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
|
|
|
300
304
|
const rest = args.filter((a) => a !== "--json");
|
|
301
305
|
const unknown = rest.find((a) => a.startsWith("-"));
|
|
302
306
|
if (unknown !== undefined) {
|
|
303
|
-
out(`verify: unknown option ${unknown}`);
|
|
307
|
+
out(terminalText(`verify: unknown option ${unknown}`));
|
|
304
308
|
return EX_VERIFY_FAILED;
|
|
305
309
|
}
|
|
306
310
|
if (rest.length > 1) {
|
|
@@ -313,7 +317,7 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
|
|
|
313
317
|
return EX_VERIFY_FAILED;
|
|
314
318
|
}
|
|
315
319
|
if (directoryAccess(dir) === "unreadable") {
|
|
316
|
-
out(unreadableSentence(dir, "verify"));
|
|
320
|
+
out(terminalText(unreadableSentence(dir, "verify")));
|
|
317
321
|
return 77;
|
|
318
322
|
}
|
|
319
323
|
let result;
|
|
@@ -361,7 +365,8 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
|
|
|
361
365
|
requireSigned: requireSignedStarts,
|
|
362
366
|
});
|
|
363
367
|
const failedReport = { ...failed, approvalSignatures: APPROVAL_NOT_CHECKED, controlSignatures: CONTROL_NOT_CHECKED, starts };
|
|
364
|
-
|
|
368
|
+
// Human lines are escaped in renderVerify. JSON keeps the breaks it wrote.
|
|
369
|
+
out(json ? terminalLines(JSON.stringify(failedReport, null, 2)) : renderVerify(failed, APPROVAL_NOT_CHECKED, CONTROL_NOT_CHECKED, starts));
|
|
365
370
|
return EX_VERIFY_FAILED;
|
|
366
371
|
}
|
|
367
372
|
let approval;
|
|
@@ -380,6 +385,13 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
|
|
|
380
385
|
problems: [...result.problems, `approval signatures: ${approval.signedFailed} did not verify`],
|
|
381
386
|
};
|
|
382
387
|
}
|
|
388
|
+
if (approval.signedAfterRemoval > 0) {
|
|
389
|
+
result = {
|
|
390
|
+
...result,
|
|
391
|
+
ok: false,
|
|
392
|
+
problems: [...result.problems, `approval signatures: ${approval.signedAfterRemoval} signed after removal`],
|
|
393
|
+
};
|
|
394
|
+
}
|
|
383
395
|
let control;
|
|
384
396
|
try {
|
|
385
397
|
control = await verifyControlSignatures(dir, credentialsFile ? { credentialsFile } : {});
|
|
@@ -396,6 +408,13 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
|
|
|
396
408
|
problems: [...result.problems, `control signatures: ${control.signedFailed} did not verify`],
|
|
397
409
|
};
|
|
398
410
|
}
|
|
411
|
+
if (control.signedAfterRemoval > 0) {
|
|
412
|
+
result = {
|
|
413
|
+
...result,
|
|
414
|
+
ok: false,
|
|
415
|
+
problems: [...result.problems, `control signatures: ${control.signedAfterRemoval} signed after removal`],
|
|
416
|
+
};
|
|
417
|
+
}
|
|
399
418
|
// Start rows are signed by the record key: the pinned one, else the one the records carry.
|
|
400
419
|
const startKeyPem = publicKeyPem ?? result.trust.publicKeyPem ?? null;
|
|
401
420
|
const starts = readStartSummary(dir, startKeyPem, publicKeyPem ? "pinned" : "in-ledger", {
|
|
@@ -405,6 +424,7 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
|
|
|
405
424
|
result = { ...result, ok: false, problems: [...result.problems, ...starts.problems] };
|
|
406
425
|
}
|
|
407
426
|
const reported = { ...result, approvalSignatures: approval, controlSignatures: control, starts };
|
|
408
|
-
|
|
427
|
+
// Human lines are escaped in renderVerify. JSON keeps the breaks it wrote.
|
|
428
|
+
out(json ? terminalLines(JSON.stringify(reported, null, 2)) : renderVerify(reported, approval, control, reported.starts));
|
|
409
429
|
return reported.ok ? 0 : EX_VERIFY_FAILED;
|
|
410
430
|
}
|