@verax-ai/body 0.4.0 → 0.4.2

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.
@@ -10,6 +10,7 @@ export type CredentialStore = {
10
10
  credentials: StoredCredential[];
11
11
  };
12
12
  export declare function credentialsPath(stateDir: string): string;
13
+ export declare function readCredentialsAt(path: string): StoredCredential[];
13
14
  export declare function readCredentials(stateDir: string): StoredCredential[];
14
15
  /**
15
16
  * The file is written only when an operator enrolls, so its presence is the
@@ -6,8 +6,7 @@ export const DEFAULT_OPERATOR_SUB = "operator-1";
6
6
  export function credentialsPath(stateDir) {
7
7
  return join(stateDir, CREDENTIALS_FILE);
8
8
  }
9
- export function readCredentials(stateDir) {
10
- const path = credentialsPath(stateDir);
9
+ export function readCredentialsAt(path) {
11
10
  if (!existsSync(path))
12
11
  return [];
13
12
  try {
@@ -23,6 +22,9 @@ export function readCredentials(stateDir) {
23
22
  return [];
24
23
  }
25
24
  }
25
+ export function readCredentials(stateDir) {
26
+ return readCredentialsAt(credentialsPath(stateDir));
27
+ }
26
28
  /**
27
29
  * The file is written only when an operator enrolls, so its presence is the
28
30
  * answer. Asking whether it parses would read a truncated or mistyped file as
@@ -0,0 +1,17 @@
1
+ /**
2
+ * System32 module directory loads for PowerShell started with systemToolEnv().
3
+ *
4
+ * #119, measured on windows-full 5a75875: under that environment PSModulePath is
5
+ * only the System32 Windows PowerShell 5.1 module directory, and resolving an
6
+ * autoloaded cmdlet (ConvertFrom-Json) took 23 to 30 s on a GitHub Windows
7
+ * runner. Import-Module of the same module by its System32 path took 0.27 s.
8
+ * Each statement names the module directory. LocalAccounts lives in a version
9
+ * subdirectory (1.0.0.0 on the measured Windows 11 machine); importing the
10
+ * directory lets Windows PowerShell choose that version and stay inside System32.
11
+ */
12
+ export declare const PS_MODULES: readonly ["Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Management", "Microsoft.PowerShell.Security", "Microsoft.PowerShell.LocalAccounts", "ScheduledTasks"];
13
+ export type PsModule = (typeof PS_MODULES)[number];
14
+ /** One Import-Module statement. The expected line shape lives only here. */
15
+ export declare function psModuleImportLine(module: PsModule): string;
16
+ /** One line per module, in the given order. A repeated module is emitted once. */
17
+ export declare function psModuleImports(modules: readonly PsModule[]): string;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * System32 module directory loads for PowerShell started with systemToolEnv().
3
+ *
4
+ * #119, measured on windows-full 5a75875: under that environment PSModulePath is
5
+ * only the System32 Windows PowerShell 5.1 module directory, and resolving an
6
+ * autoloaded cmdlet (ConvertFrom-Json) took 23 to 30 s on a GitHub Windows
7
+ * runner. Import-Module of the same module by its System32 path took 0.27 s.
8
+ * Each statement names the module directory. LocalAccounts lives in a version
9
+ * subdirectory (1.0.0.0 on the measured Windows 11 machine); importing the
10
+ * directory lets Windows PowerShell choose that version and stay inside System32.
11
+ */
12
+ export const PS_MODULES = [
13
+ "Microsoft.PowerShell.Utility",
14
+ "Microsoft.PowerShell.Management",
15
+ "Microsoft.PowerShell.Security",
16
+ "Microsoft.PowerShell.LocalAccounts",
17
+ "ScheduledTasks",
18
+ ];
19
+ /** One Import-Module statement. The expected line shape lives only here. */
20
+ export function psModuleImportLine(module) {
21
+ return `Import-Module "$env:SystemRoot\\System32\\WindowsPowerShell\\v1.0\\Modules\\${module}"`;
22
+ }
23
+ /** One line per module, in the given order. A repeated module is emitted once. */
24
+ export function psModuleImports(modules) {
25
+ const seen = new Set();
26
+ const lines = [];
27
+ for (const module of modules) {
28
+ if (seen.has(module))
29
+ continue;
30
+ seen.add(module);
31
+ lines.push(psModuleImportLine(module));
32
+ }
33
+ return lines.join("\n");
34
+ }
package/dist/server.js CHANGED
@@ -4,7 +4,11 @@ import { createServer } from "node:http";
4
4
  import { Server as McpServer } from "@modelcontextprotocol/sdk/server/index.js";
5
5
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
6
6
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
7
+ import { decisionRecordHash } from "@cedulon/core";
7
8
  import { isLoopbackHost } from "./config.js";
9
+ import { approvalChallenge, gateApprovalSignature } from "./approval-signature.js";
10
+ import { readCredentials } from "./operator-credentials.js";
11
+ import { readRpConfig } from "./rp-config.js";
8
12
  import { approvalsLogFor, approvePending, createApprovalBudgetGuard, explain, LedgerDenyUnrecorded, loadApprovalsFromDir, } from "@verax-ai/proxy";
9
13
  import { createVerifier, readBearer, resourceMetadataUrl, wwwAuthenticate } from "./auth.js";
10
14
  import { bumpMetric, bumpUnauthenticated } from "./metrics.js";
@@ -14,6 +18,7 @@ import { matchingInputs } from "./inputs-read.js";
14
18
  import { readPolicySnapshots } from "./policy-store.js";
15
19
  import { readHeartbeat, readInstallHealthNonce, readWitnessPulse } from "./health-extras.js";
16
20
  import { agentsWindow } from "./agents.js";
21
+ import { haltBody, readHalt, resumeBody } from "./halt.js";
17
22
  import { inventoryHealth, readInventoryFile } from "./inventory-file.js";
18
23
  import { createBodyServices, TOOL_NAMES } from "./wiring.js";
19
24
  import { openDownstream, parseDownstreamDocument, } from "./downstream.js";
@@ -267,6 +272,10 @@ function isProtectedResourcePath(pathname, audience) {
267
272
  const want = new URL(resourceMetadataUrl(audience)).pathname;
268
273
  return pathname === want || pathname === "/.well-known/oauth-protected-resource";
269
274
  }
275
+ async function signedDefer(ledger, ref) {
276
+ const rows = await ledger.decisions();
277
+ return rows.find((row) => row.claims.ref === ref && row.claims.decision === "defer") ?? null;
278
+ }
270
279
  function send(res, status, body, headers) {
271
280
  const text = typeof body === "string" ? body : JSON.stringify(body);
272
281
  res.writeHead(status, {
@@ -361,6 +370,15 @@ export async function listen(config) {
361
370
  await closeAll(sessions);
362
371
  throw err;
363
372
  }
373
+ try {
374
+ await services.proxy.syncControlRecords();
375
+ }
376
+ catch (err) {
377
+ // syncControlRecords reports its own failure and does not throw. This
378
+ // catch is the door: a sync miss must not close the ledger or refuse to listen.
379
+ const message = (err instanceof Error ? err.message : String(err)).replace(/[\r\n]+/g, " ");
380
+ process.stderr.write(`verax-proxy: control sync failed: ${message}\n`);
381
+ }
364
382
  const toolMeta = [...TOOL_META, ...extraTools.map(downstreamMeta)];
365
383
  const verify = createVerifier(config.jwksUrl, config.issuer, config.audience, config.jwksFile, config.jwksPin);
366
384
  const attachHandlers = (mcp) => {
@@ -502,8 +520,19 @@ export async function listen(config) {
502
520
  const apiInventory = url.pathname === "/api/inventory";
503
521
  const contest = req.method === "POST" && url.pathname.startsWith("/api/contest/");
504
522
  const apiApprove = req.method === "POST" && url.pathname === "/api/approve";
523
+ const apiApproveChallenge = req.method === "GET" && url.pathname === "/api/approve/challenge";
505
524
  const apiAgents = req.method === "GET" && url.pathname === "/api/agents";
506
- if (url.pathname !== "/mcp" && !apiLedger && !apiInventory && !contest && !apiApprove && !apiAgents) {
525
+ const apiHalt = url.pathname === "/api/halt" && (req.method === "GET" || req.method === "POST");
526
+ const apiResume = req.method === "POST" && url.pathname === "/api/resume";
527
+ if (url.pathname !== "/mcp" &&
528
+ !apiLedger &&
529
+ !apiInventory &&
530
+ !contest &&
531
+ !apiApprove &&
532
+ !apiApproveChallenge &&
533
+ !apiAgents &&
534
+ !apiHalt &&
535
+ !apiResume) {
507
536
  send(res, 404, { error: "not-found" });
508
537
  return;
509
538
  }
@@ -544,6 +573,65 @@ export async function listen(config) {
544
573
  return;
545
574
  }
546
575
  try {
576
+ if (apiHalt || apiResume) {
577
+ if (await refuseStaleBearer())
578
+ return;
579
+ const scopes = verified.principal.scopes;
580
+ const operator = scopes.has("verax:audit") || scopes.has("verax:approve");
581
+ // Stopping is the safe direction, so any operator session may do it.
582
+ // Lifting a halt lets everything through again: that is an approval of
583
+ // everything at once and needs the approve scope. The agent token
584
+ // carries neither, so an agent cannot stop itself being stopped.
585
+ if (!operator || (apiResume && !scopes.has("verax:approve"))) {
586
+ send(res, 403, { error: "scope-missing" });
587
+ return;
588
+ }
589
+ if (req.method === "GET") {
590
+ send(res, 200, readHalt(config.stateDir));
591
+ return;
592
+ }
593
+ const by = verified.principal.brain;
594
+ const state = apiResume ? resumeBody(config.stateDir, by, "http") : haltBody(config.stateDir, by, "http");
595
+ try {
596
+ await services.proxy.syncControlRecords();
597
+ }
598
+ catch (err) {
599
+ // The switch is already on disk. A sync miss must not turn this into a 500.
600
+ const message = (err instanceof Error ? err.message : String(err)).replace(/[\r\n]+/g, " ");
601
+ process.stderr.write(`verax-proxy: control sync failed: ${message}\n`);
602
+ }
603
+ send(res, 200, state);
604
+ return;
605
+ }
606
+ if (apiApproveChallenge) {
607
+ if (!verified.principal.scopes.has("verax:approve")) {
608
+ send(res, 403, { error: "scope-missing" });
609
+ return;
610
+ }
611
+ if (await refuseStaleBearer())
612
+ return;
613
+ const ref = url.searchParams.get("ref") ?? "";
614
+ const deferRecord = ref === "" ? null : await signedDefer(services.ledger, ref);
615
+ if (!deferRecord) {
616
+ send(res, 404, { error: "unknown-ref" });
617
+ return;
618
+ }
619
+ const rp = readRpConfig(process.env);
620
+ if (!rp.ok) {
621
+ send(res, 503, { error: "passkey-closed", reason: rp.reason });
622
+ return;
623
+ }
624
+ send(res, 200, {
625
+ challenge: approvalChallenge({
626
+ ref,
627
+ requestHash: deferRecord.claims.requestHash,
628
+ deferRecordHash: decisionRecordHash(deferRecord),
629
+ }),
630
+ rpId: rp.config.rpID,
631
+ allowCredentials: readCredentials(config.stateDir).map((row) => ({ id: row.id, type: "public-key" })),
632
+ });
633
+ return;
634
+ }
547
635
  if (apiApprove) {
548
636
  // Reading the ledger is not approving from it. The audit scope opens
549
637
  // every door above; this one signs a new decision and lets money go,
@@ -579,11 +667,28 @@ export async function listen(config) {
579
667
  send(res, 409, { error: "stale", requestHash: waiting.requestHash });
580
668
  return;
581
669
  }
582
- const defer = services.ledger.lookupByRef(ref);
583
- if (!defer || defer.decision !== "defer") {
670
+ const deferRecord = await signedDefer(services.ledger, ref);
671
+ if (!deferRecord) {
584
672
  send(res, 404, { error: "unknown-ref" });
585
673
  return;
586
674
  }
675
+ const deferRecordHash = decisionRecordHash(deferRecord);
676
+ // The challenge is rebuilt from the defer on disk, not from anything the client sent.
677
+ const gated = await gateApprovalSignature({
678
+ stateDir: config.stateDir,
679
+ env: process.env,
680
+ assertion: asked.assertion,
681
+ ref,
682
+ requestHash: deferRecord.claims.requestHash,
683
+ deferRecordHash,
684
+ });
685
+ if (!gated.ok) {
686
+ send(res, gated.status, {
687
+ error: gated.error,
688
+ ...(gated.reason ? { reason: gated.reason } : {}),
689
+ });
690
+ return;
691
+ }
587
692
  // Who approved, on the record. The CLI writes the machine's login name,
588
693
  // which says nothing about the person holding the phone; the session's
589
694
  // own subject does.
@@ -597,7 +702,8 @@ export async function listen(config) {
597
702
  ref,
598
703
  approverId: approver,
599
704
  via: "http",
600
- policyHash: defer.policyHash,
705
+ policyHash: deferRecord.claims.policyHash,
706
+ ...(gated.signature ? { signature: gated.signature } : {}),
601
707
  approvals,
602
708
  budgetGuard: createApprovalBudgetGuard({
603
709
  policy: services.policy,
@@ -1,5 +1,5 @@
1
1
  import { type VerifyResult } from "@verax-ai/proxy";
2
+ import { type ApprovalSignatureReport } from "./approval-signature.ts";
2
3
  export declare const EX_VERIFY_FAILED = 1;
3
- /** Lines a person reads. The trust line is never omitted. */
4
- export declare function renderVerify(r: VerifyResult): string;
4
+ export declare function renderVerify(r: VerifyResult, approval?: ApprovalSignatureReport): string;
5
5
  export declare function runVerify(argv: readonly string[], out?: (s: string) => void): Promise<number>;
@@ -15,11 +15,12 @@
15
15
  */
16
16
  import { readFileSync } from "node:fs";
17
17
  import { verifyLedger } from "@verax-ai/proxy";
18
+ import { verifyApprovalSignatures } from "./approval-signature.js";
18
19
  import { directoryAccess, unreadableSentence } from "./install.js";
19
20
  export const EX_VERIFY_FAILED = 1;
20
21
  function usage() {
21
22
  return [
22
- "usage: verax verify <stateDir> [--key <public.pem>] [--effect-key <public.pem>] [--witness-key <public.pem>] [--checkpoint-key <public.pem>] [--json]",
23
+ "usage: verax verify <stateDir> [--key <public.pem>] [--effect-key <public.pem>] [--witness-key <public.pem>] [--checkpoint-key <public.pem>] [--operator-credentials <file>] [--json]",
23
24
  "",
24
25
  " <stateDir> the directory holding decisions.jsonl and effects.jsonl",
25
26
  " --key <file> verify decision records against a public key you hold,",
@@ -42,13 +43,28 @@ function usage() {
42
43
  " verify every checkpoint row against a public key you",
43
44
  " hold, instead of one key taken from the checkpoint",
44
45
  " file. Same distinction as --key, for the witness.",
46
+ " --operator-credentials <file>",
47
+ " verify HTTP approval signatures against this operator",
48
+ " credential file, instead of operator-credentials.json",
49
+ " in the state directory. A CLI approval is unsigned and",
50
+ " is counted as such. Same distinction as --key.",
45
51
  " --json machine-readable result on stdout",
46
52
  "",
47
53
  "Exit code is 0 when the ledger verifies and 1 when it does not.",
48
54
  ].join("\n");
49
55
  }
50
56
  /** Lines a person reads. The trust line is never omitted. */
51
- export function renderVerify(r) {
57
+ const APPROVAL_NOT_CHECKED = {
58
+ ok: true,
59
+ signedVerified: 0,
60
+ signedFailed: 0,
61
+ unsignedHttp: 0,
62
+ cli: 0,
63
+ line: "approval signatures not checked",
64
+ trustSource: "none",
65
+ trustNote: "approval signatures were not checked",
66
+ };
67
+ export function renderVerify(r, approval = APPROVAL_NOT_CHECKED) {
52
68
  const lines = [];
53
69
  lines.push(`ledger ${r.directory}`);
54
70
  lines.push(`decisions ${r.decisions}`);
@@ -99,6 +115,11 @@ export function renderVerify(r) {
99
115
  lines.push(`checkpoint newest covers ${covered}, head ${head}, ${holds}`);
100
116
  }
101
117
  lines.push(r.tail.line);
118
+ lines.push(r.control.line);
119
+ for (const warning of r.control.warnings)
120
+ lines.push(`warning ${warning}`);
121
+ lines.push(approval.line);
122
+ lines.push(` ${approval.trustNote}`);
102
123
  if (r.problems.length > 0) {
103
124
  lines.push("");
104
125
  lines.push("problems:");
@@ -161,6 +182,28 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
161
182
  if (!checkpointKey.ok)
162
183
  return EX_VERIFY_FAILED;
163
184
  checkpointPublicKeyPem = checkpointKey.pem;
185
+ let credentialsFile;
186
+ const credentialsAt = args.indexOf("--operator-credentials");
187
+ if (credentialsAt !== -1) {
188
+ const path = args[credentialsAt + 1];
189
+ if (!path || path.startsWith("-")) {
190
+ out("verify: --operator-credentials needs a file path");
191
+ return EX_VERIFY_FAILED;
192
+ }
193
+ try {
194
+ const text = readFileSync(path, "utf8");
195
+ if (text.trim() === "") {
196
+ out("verify: operator credentials file is empty");
197
+ return EX_VERIFY_FAILED;
198
+ }
199
+ }
200
+ catch {
201
+ out(`verify: cannot read operator credentials file ${path}`);
202
+ return EX_VERIFY_FAILED;
203
+ }
204
+ args.splice(credentialsAt, 2);
205
+ credentialsFile = path;
206
+ }
164
207
  const dir = args.find((a) => !a.startsWith("-"));
165
208
  if (!dir) {
166
209
  out(usage());
@@ -201,11 +244,30 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
201
244
  line: "tail: no checkpoint; removing the newest records with their effects is not detectable from these files",
202
245
  checkpoint: null,
203
246
  },
247
+ control: { line: "control: not checked", windows: 0, warnings: [] },
204
248
  problems: [problem],
205
249
  };
206
- out(json ? JSON.stringify(failed, null, 2) : renderVerify(failed));
250
+ const failedReport = { ...failed, approvalSignatures: APPROVAL_NOT_CHECKED };
251
+ out(json ? JSON.stringify(failedReport, null, 2) : renderVerify(failed, APPROVAL_NOT_CHECKED));
207
252
  return EX_VERIFY_FAILED;
208
253
  }
209
- out(json ? JSON.stringify(result, null, 2) : renderVerify(result));
210
- return result.ok ? 0 : EX_VERIFY_FAILED;
254
+ let approval;
255
+ try {
256
+ approval = await verifyApprovalSignatures(dir, credentialsFile ? { credentialsFile } : {});
257
+ }
258
+ catch (err) {
259
+ const problem = err instanceof Error ? err.message : "approval signatures could not be read";
260
+ approval = { ...APPROVAL_NOT_CHECKED, ok: false, trustNote: problem };
261
+ result = { ...result, ok: false, problems: [...result.problems, problem] };
262
+ }
263
+ if (approval.signedFailed > 0) {
264
+ result = {
265
+ ...result,
266
+ ok: false,
267
+ problems: [...result.problems, `approval signatures: ${approval.signedFailed} did not verify`],
268
+ };
269
+ }
270
+ const reported = { ...result, approvalSignatures: approval };
271
+ out(json ? JSON.stringify(reported, null, 2) : renderVerify(reported, approval));
272
+ return reported.ok ? 0 : EX_VERIFY_FAILED;
211
273
  }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * WebAuthn assertion checks for an HTTP approval, using only node:crypto
3
+ * and the CBOR decoder already in @cedulon/cose. The body does not take a
4
+ * certificate stack to verify one signature.
5
+ */
6
+ import { type KeyObject } from "node:crypto";
7
+ export type AssertionVerdict = {
8
+ ok: true;
9
+ counter: number;
10
+ flags: number;
11
+ } | {
12
+ ok: false;
13
+ reason: string;
14
+ };
15
+ type PostedAssertion = {
16
+ response?: {
17
+ clientDataJSON?: unknown;
18
+ authenticatorData?: unknown;
19
+ signature?: unknown;
20
+ };
21
+ };
22
+ /**
23
+ * COSE public key, base64url, to a node key. EC2 is P-256 / ES256, OKP is
24
+ * Ed25519 / EdDSA, RSA is RS256. Any other kty, alg, or curve is refused.
25
+ * A refusal returns null; this does not throw.
26
+ */
27
+ export declare function coseKeyToPublicKey(base64urlCose: string): KeyObject | null;
28
+ /**
29
+ * Check one authentication assertion. `expectedOrigins` is the caller's
30
+ * allow-list; a caller that does not have one passes the origin it read
31
+ * back, and says so at the call site. `crossOrigin: true` is refused.
32
+ */
33
+ export declare function verifyAssertion(opts: {
34
+ response: PostedAssertion;
35
+ expectedChallenge: string;
36
+ expectedOrigins: readonly string[];
37
+ rpId: string;
38
+ publicKeyCose: string;
39
+ }): AssertionVerdict;
40
+ export {};
@@ -0,0 +1,159 @@
1
+ /**
2
+ * WebAuthn assertion checks for an HTTP approval, using only node:crypto
3
+ * and the CBOR decoder already in @cedulon/cose. The body does not take a
4
+ * certificate stack to verify one signature.
5
+ */
6
+ import { constants, createHash, createPublicKey, verify as cryptoVerify } from "node:crypto";
7
+ import { decodeCbor, isCborMap, mapGet } from "@cedulon/cose";
8
+ function b64url(bytes) {
9
+ return Buffer.from(bytes).toString("base64url");
10
+ }
11
+ function fromBase64Url(value) {
12
+ if (value === "")
13
+ return null;
14
+ const trimmed = value.replace(/=+$/u, "");
15
+ if (trimmed === "" || !/^[A-Za-z0-9_-]+$/u.test(trimmed))
16
+ return null;
17
+ const buf = Buffer.from(trimmed, "base64url");
18
+ return buf.length === 0 ? null : buf;
19
+ }
20
+ function mapNum(map, key) {
21
+ const value = mapGet(map, key);
22
+ return typeof value === "number" && Number.isInteger(value) ? value : null;
23
+ }
24
+ function mapBytes(map, key, length) {
25
+ const value = mapGet(map, key);
26
+ if (!(value instanceof Uint8Array))
27
+ return null;
28
+ if (value.length === 0)
29
+ return null;
30
+ if (length !== undefined && value.length !== length)
31
+ return null;
32
+ return value;
33
+ }
34
+ /**
35
+ * COSE public key, base64url, to a node key. EC2 is P-256 / ES256, OKP is
36
+ * Ed25519 / EdDSA, RSA is RS256. Any other kty, alg, or curve is refused.
37
+ * A refusal returns null; this does not throw.
38
+ */
39
+ export function coseKeyToPublicKey(base64urlCose) {
40
+ try {
41
+ const bytes = fromBase64Url(base64urlCose);
42
+ if (!bytes)
43
+ return null;
44
+ const decoded = decodeCbor(new Uint8Array(bytes));
45
+ if (!isCborMap(decoded))
46
+ return null;
47
+ const kty = mapNum(decoded, 1);
48
+ const alg = mapNum(decoded, 3);
49
+ if (kty === 2 && alg === -7) {
50
+ const x = mapBytes(decoded, -2, 32);
51
+ const y = mapBytes(decoded, -3, 32);
52
+ if (mapNum(decoded, -1) !== 1 || !x || !y)
53
+ return null;
54
+ return createPublicKey({
55
+ format: "jwk",
56
+ key: { kty: "EC", crv: "P-256", alg: "ES256", x: b64url(x), y: b64url(y) },
57
+ });
58
+ }
59
+ if (kty === 1 && alg === -8) {
60
+ const x = mapBytes(decoded, -2, 32);
61
+ if (mapNum(decoded, -1) !== 6 || !x)
62
+ return null;
63
+ return createPublicKey({
64
+ format: "jwk",
65
+ key: { kty: "OKP", crv: "Ed25519", alg: "EdDSA", x: b64url(x) },
66
+ });
67
+ }
68
+ if (kty === 3 && alg === -257) {
69
+ const n = mapBytes(decoded, -1);
70
+ const e = mapBytes(decoded, -2);
71
+ if (!n || !e)
72
+ return null;
73
+ return createPublicKey({
74
+ format: "jwk",
75
+ key: { kty: "RSA", alg: "RS256", n: b64url(n), e: b64url(e) },
76
+ });
77
+ }
78
+ return null;
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ }
84
+ function signatureHolds(key, data, signature) {
85
+ try {
86
+ const kind = key.asymmetricKeyType;
87
+ if (kind === "ec")
88
+ return cryptoVerify("sha256", data, { key, dsaEncoding: "der" }, signature);
89
+ if (kind === "ed25519")
90
+ return cryptoVerify(null, data, key, signature);
91
+ if (kind === "rsa") {
92
+ return cryptoVerify("sha256", data, { key, padding: constants.RSA_PKCS1_PADDING }, signature);
93
+ }
94
+ return false;
95
+ }
96
+ catch {
97
+ return false;
98
+ }
99
+ }
100
+ /**
101
+ * Check one authentication assertion. `expectedOrigins` is the caller's
102
+ * allow-list; a caller that does not have one passes the origin it read
103
+ * back, and says so at the call site. `crossOrigin: true` is refused.
104
+ */
105
+ export function verifyAssertion(opts) {
106
+ try {
107
+ const clientB64 = opts.response.response?.clientDataJSON;
108
+ const authB64 = opts.response.response?.authenticatorData;
109
+ const sigB64 = opts.response.response?.signature;
110
+ if (typeof clientB64 !== "string" || typeof authB64 !== "string" || typeof sigB64 !== "string") {
111
+ return { ok: false, reason: "bad-assertion" };
112
+ }
113
+ const clientBytes = fromBase64Url(clientB64);
114
+ const authenticatorData = fromBase64Url(authB64);
115
+ const signature = fromBase64Url(sigB64);
116
+ if (!clientBytes || !authenticatorData || !signature)
117
+ return { ok: false, reason: "bad-assertion" };
118
+ let client;
119
+ try {
120
+ const parsed = JSON.parse(clientBytes.toString("utf8"));
121
+ if (!parsed || typeof parsed !== "object")
122
+ return { ok: false, reason: "bad-client-data" };
123
+ client = parsed;
124
+ }
125
+ catch {
126
+ return { ok: false, reason: "bad-client-data" };
127
+ }
128
+ if (client.type !== "webauthn.get")
129
+ return { ok: false, reason: "type" };
130
+ if (client.challenge !== opts.expectedChallenge)
131
+ return { ok: false, reason: "challenge" };
132
+ if (typeof client.origin !== "string" || !opts.expectedOrigins.includes(client.origin)) {
133
+ return { ok: false, reason: "origin" };
134
+ }
135
+ // Absent or false only: a string such as "true" is not a same-origin answer either.
136
+ if (client.crossOrigin !== undefined && client.crossOrigin !== false)
137
+ return { ok: false, reason: "cross-origin" };
138
+ if (authenticatorData.length < 37)
139
+ return { ok: false, reason: "authenticator-data" };
140
+ const rpIdHash = createHash("sha256").update(opts.rpId).digest();
141
+ if (Buffer.compare(authenticatorData.subarray(0, 32), rpIdHash) !== 0)
142
+ return { ok: false, reason: "rp-id" };
143
+ const flags = authenticatorData[32];
144
+ if (flags === undefined || (flags & 0x05) !== 0x05)
145
+ return { ok: false, reason: "user-verification" };
146
+ const counter = authenticatorData.readUInt32BE(33);
147
+ const key = coseKeyToPublicKey(opts.publicKeyCose);
148
+ if (!key)
149
+ return { ok: false, reason: "public-key" };
150
+ const clientHash = createHash("sha256").update(clientBytes).digest();
151
+ const data = Buffer.concat([authenticatorData, clientHash]);
152
+ if (!signatureHolds(key, data, signature))
153
+ return { ok: false, reason: "signature" };
154
+ return { ok: true, counter, flags };
155
+ }
156
+ catch {
157
+ return { ok: false, reason: "signature" };
158
+ }
159
+ }
package/dist/wiring.js CHANGED
@@ -83,6 +83,9 @@ export function createBodyServices(opts) {
83
83
  }
84
84
  return fn(call, principal, ref);
85
85
  };
86
+ // Halt and resume lines are copied into the ledger when the body opens
87
+ // (`listen` awaits `proxy.syncControlRecords` before the socket accepts)
88
+ // and again before each call. A CLI halt waits for one of those.
86
89
  const proxy = createProxy({
87
90
  policy,
88
91
  recordSigner: opts.recordSigner,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verax-ai/body",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "engines": {
@@ -26,8 +26,8 @@
26
26
  "@cedulon/cose": "0.13.1",
27
27
  "@cedulon/effect-extract": "0.13.1",
28
28
  "@modelcontextprotocol/sdk": "^1.30.0",
29
- "@verax-ai/inventory": "^0.4.0",
30
- "@verax-ai/proxy": "^0.4.0",
29
+ "@verax-ai/inventory": "^0.4.2",
30
+ "@verax-ai/proxy": "^0.4.2",
31
31
  "jose": "^6.2.11"
32
32
  },
33
33
  "description": "VERAX body: an MCP server that decides, records and proves what an agent did.",