@verax-ai/body 0.8.1 → 0.9.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.
package/dist/server.js CHANGED
@@ -263,7 +263,11 @@ export function bearerStillLive(payload, stateDir) {
263
263
  return payload.exp * 1000 > Date.now();
264
264
  }
265
265
  function isProtectedResourcePath(pathname, audience) {
266
- const want = new URL(resourceMetadataUrl(audience)).pathname;
266
+ // RFC 9728 names the resource by URL; a non-URL audience has no metadata to serve.
267
+ const metadata = resourceMetadataUrl(audience);
268
+ if (metadata === null)
269
+ return false;
270
+ const want = new URL(metadata).pathname;
267
271
  return pathname === want || pathname === "/.well-known/oauth-protected-resource";
268
272
  }
269
273
  /**
@@ -3,5 +3,45 @@ import { type ApprovalSignatureReport } from "./approval-signature.ts";
3
3
  import { type ControlSignatureReport } from "./control-signature.ts";
4
4
  import { type StartSummary } from "./heartbeat.ts";
5
5
  export declare const EX_VERIFY_FAILED = 1;
6
+ /**
7
+ * The line a reader stops at. A bare VERIFIED reads as "not tampered with", so
8
+ * it is kept for a run that checked what that takes: every key from the reader,
9
+ * a checkpoint reaching the newest record, and a receipt from a service someone
10
+ * else runs, since only a checkpoint held elsewhere detects a rollback of the
11
+ * files. Anything less names what is missing. The exit code and `--json` are
12
+ * unchanged.
13
+ */
14
+ /** The line `verax verify` ends on. Shared with `verax report`. */
15
+ export declare function verdictLine(r: VerifyResult, approval: ApprovalSignatureReport, control: ControlSignatureReport): string;
16
+ export type CompletedVerify = {
17
+ result: VerifyResult;
18
+ approval: ApprovalSignatureReport;
19
+ control: ControlSignatureReport;
20
+ starts: StartSummary;
21
+ verdict: string;
22
+ };
23
+ export type CompleteVerifyOptions = {
24
+ credentialsFile?: string;
25
+ requireSignedStarts?: boolean;
26
+ /** When set, start rows are checked under this pinned record key. */
27
+ pinnedPublicKeyPem?: string;
28
+ /**
29
+ * How to name a thrown error as a problem line. `verax verify` keeps the
30
+ * raw message; `verax report` maps to a short class.
31
+ */
32
+ problemFromThrown?: (err: unknown, fallback: string) => string;
33
+ /**
34
+ * When true, a throw from reading starts becomes a problem on the result
35
+ * instead of escaping. The report uses this; verify lets it throw.
36
+ */
37
+ catchStartErrors?: boolean;
38
+ };
39
+ /**
40
+ * Approval signatures, control signatures and the start summary, folded into
41
+ * `result.ok` / `problems`, then the verdict line. Both `verax verify` and
42
+ * `verax report` call this so a change to one path cannot leave the other
43
+ * behind with every test still green.
44
+ */
45
+ export declare function completeVerify(dir: string, result: VerifyResult, opts?: CompleteVerifyOptions): Promise<CompletedVerify>;
6
46
  export declare function renderVerify(r: VerifyResult, approval?: ApprovalSignatureReport, control?: ControlSignatureReport, starts?: StartSummary): string;
7
47
  export declare function runVerify(argv: readonly string[], out?: (s: string) => void): Promise<number>;
@@ -109,6 +109,139 @@ const CONTROL_NOT_CHECKED = {
109
109
  trustSource: "none",
110
110
  trustNote: "control signatures were not checked",
111
111
  };
112
+ /**
113
+ * The line a reader stops at. A bare VERIFIED reads as "not tampered with", so
114
+ * it is kept for a run that checked what that takes: every key from the reader,
115
+ * a checkpoint reaching the newest record, and a receipt from a service someone
116
+ * else runs, since only a checkpoint held elsewhere detects a rollback of the
117
+ * files. Anything less names what is missing. The exit code and `--json` are
118
+ * unchanged.
119
+ */
120
+ /** The line `verax verify` ends on. Shared with `verax report`. */
121
+ export function verdictLine(r, approval, control) {
122
+ if (!r.ok)
123
+ return "NOT VERIFIED";
124
+ const fromFiles = [r.trust, r.effectTrust, r.witnessTrust, r.checkpointTrust].some((trust) => trust?.source === "in-ledger") ||
125
+ approval.trustSource === "in-ledger" ||
126
+ control.trustSource === "in-ledger";
127
+ if (fromFiles || r.trust.source !== "pinned")
128
+ return "VERIFIED (internal consistency only)";
129
+ const { checkpoint } = r.tail;
130
+ if (!checkpoint)
131
+ return "VERIFIED (tail not covered: no checkpoint)";
132
+ if (checkpoint.receiptCount === null || checkpoint.ledgerHoldsRecord !== true) {
133
+ return "VERIFIED (tail not covered: the newest checkpoint does not reach a known record)";
134
+ }
135
+ const after = r.decisions - checkpoint.receiptCount;
136
+ if (after > 0)
137
+ return `VERIFIED (tail not covered: ${after} record(s) after the newest checkpoint)`;
138
+ if (r.anchors.verified === 0)
139
+ return "VERIFIED (rollback not checked: no anchored checkpoint)";
140
+ return "VERIFIED";
141
+ }
142
+ function defaultProblemFromThrown(err, fallback) {
143
+ return err instanceof Error ? err.message : fallback;
144
+ }
145
+ /**
146
+ * Approval signatures, control signatures and the start summary, folded into
147
+ * `result.ok` / `problems`, then the verdict line. Both `verax verify` and
148
+ * `verax report` call this so a change to one path cannot leave the other
149
+ * behind with every test still green.
150
+ */
151
+ export async function completeVerify(dir, result, opts = {}) {
152
+ const problemFromThrown = opts.problemFromThrown ?? defaultProblemFromThrown;
153
+ let next = result;
154
+ let approval;
155
+ try {
156
+ approval = await verifyApprovalSignatures(dir, opts.credentialsFile ? { credentialsFile: opts.credentialsFile } : {});
157
+ }
158
+ catch (err) {
159
+ const problem = problemFromThrown(err, "approval signatures could not be read");
160
+ approval = { ...APPROVAL_NOT_CHECKED, ok: false, trustNote: problem };
161
+ next = { ...next, ok: false, problems: [...next.problems, problem] };
162
+ }
163
+ if (approval.signedFailed > 0) {
164
+ next = {
165
+ ...next,
166
+ ok: false,
167
+ problems: [...next.problems, `approval signatures: ${approval.signedFailed} did not verify`],
168
+ };
169
+ }
170
+ if (approval.signedAfterRemoval > 0) {
171
+ next = {
172
+ ...next,
173
+ ok: false,
174
+ problems: [...next.problems, `approval signatures: ${approval.signedAfterRemoval} signed after removal`],
175
+ };
176
+ }
177
+ let control;
178
+ try {
179
+ control = await verifyControlSignatures(dir, opts.credentialsFile ? { credentialsFile: opts.credentialsFile } : {});
180
+ }
181
+ catch (err) {
182
+ const problem = problemFromThrown(err, "control signatures could not be read");
183
+ control = { ...CONTROL_NOT_CHECKED, ok: false, trustNote: problem };
184
+ next = { ...next, ok: false, problems: [...next.problems, problem] };
185
+ }
186
+ if (control.signedFailed > 0) {
187
+ next = {
188
+ ...next,
189
+ ok: false,
190
+ problems: [...next.problems, `control signatures: ${control.signedFailed} did not verify`],
191
+ };
192
+ }
193
+ if (control.signedAfterRemoval > 0) {
194
+ next = {
195
+ ...next,
196
+ ok: false,
197
+ problems: [...next.problems, `control signatures: ${control.signedAfterRemoval} signed after removal`],
198
+ };
199
+ }
200
+ const startKeyPem = opts.pinnedPublicKeyPem ?? next.trust.publicKeyPem ?? null;
201
+ const startTrust = opts.pinnedPublicKeyPem ? "pinned" : "in-ledger";
202
+ let starts;
203
+ if (opts.catchStartErrors) {
204
+ try {
205
+ starts = readStartSummary(dir, startKeyPem, startTrust, {
206
+ requireSigned: opts.requireSignedStarts === true,
207
+ });
208
+ if (starts.problems.length > 0) {
209
+ next = { ...next, ok: false, problems: [...next.problems, ...starts.problems] };
210
+ }
211
+ }
212
+ catch (err) {
213
+ const problem = problemFromThrown(err, "start-summary-unreadable");
214
+ next = { ...next, ok: false, problems: [...next.problems, problem] };
215
+ starts = {
216
+ count: 0,
217
+ largestGapMs: null,
218
+ missingPreviousBeat: [],
219
+ unsigned: false,
220
+ signed: 0,
221
+ signedVerified: 0,
222
+ startKey: startKeyPem ? startTrust : "none",
223
+ problems: [problem],
224
+ warnings: [],
225
+ downstream: [],
226
+ };
227
+ }
228
+ }
229
+ else {
230
+ starts = readStartSummary(dir, startKeyPem, startTrust, {
231
+ requireSigned: opts.requireSignedStarts === true,
232
+ });
233
+ if (starts.problems.length > 0) {
234
+ next = { ...next, ok: false, problems: [...next.problems, ...starts.problems] };
235
+ }
236
+ }
237
+ return {
238
+ result: next,
239
+ approval,
240
+ control,
241
+ starts,
242
+ verdict: verdictLine(next, approval, control),
243
+ };
244
+ }
112
245
  export function renderVerify(r, approval = APPROVAL_NOT_CHECKED, control = CONTROL_NOT_CHECKED, starts) {
113
246
  const lines = [];
114
247
  lines.push(`ledger ${r.directory}`);
@@ -180,10 +313,10 @@ export function renderVerify(r, approval = APPROVAL_NOT_CHECKED, control = CONTR
180
313
  for (const p of r.problems.slice(0, 50))
181
314
  lines.push(` - ${p}`);
182
315
  if (r.problems.length > 50)
183
- lines.push(` … and ${r.problems.length - 50} more`);
316
+ lines.push(` ... and ${r.problems.length - 50} more`);
184
317
  }
185
318
  lines.push("");
186
- lines.push(r.ok ? "VERIFIED" : "NOT VERIFIED");
319
+ lines.push(verdictLine(r, approval, control));
187
320
  // Escape before the join. verify reads a ledger someone else wrote, and a
188
321
  // line break in that text must not become a line of its own.
189
322
  return lines.map((line) => terminalText(line)).join("\n");
@@ -361,71 +494,40 @@ export async function runVerify(argv, out = (s) => process.stdout.write(`${s}\n`
361
494
  inputs: { line: "inputs: not checked", matched: 0, missing: 0, mismatched: 0 },
362
495
  anchors: { line: "anchors: not checked", receipts: 0, verified: 0, checked: false },
363
496
  problems: [problem],
497
+ attestedDecisions: [],
498
+ attestedCheckpoints: [],
364
499
  };
365
500
  const starts = readStartSummary(dir, publicKeyPem ?? null, publicKeyPem ? "pinned" : "none", {
366
501
  requireSigned: requireSignedStarts,
367
502
  });
368
- const failedReport = { ...failed, approvalSignatures: APPROVAL_NOT_CHECKED, controlSignatures: CONTROL_NOT_CHECKED, starts };
503
+ // attested* stay on the in-process result for report; --json matches main.
504
+ const { attestedDecisions: _ad, attestedCheckpoints: _ac, ...failedPublic } = failed;
505
+ const failedReport = {
506
+ ...failedPublic,
507
+ approvalSignatures: APPROVAL_NOT_CHECKED,
508
+ controlSignatures: CONTROL_NOT_CHECKED,
509
+ starts,
510
+ };
369
511
  // Human lines are escaped in renderVerify. JSON keeps the breaks it wrote.
370
512
  out(json ? terminalLines(JSON.stringify(failedReport, null, 2)) : renderVerify(failed, APPROVAL_NOT_CHECKED, CONTROL_NOT_CHECKED, starts));
371
513
  return EX_VERIFY_FAILED;
372
514
  }
373
- let approval;
374
- try {
375
- approval = await verifyApprovalSignatures(dir, credentialsFile ? { credentialsFile } : {});
376
- }
377
- catch (err) {
378
- const problem = err instanceof Error ? err.message : "approval signatures could not be read";
379
- approval = { ...APPROVAL_NOT_CHECKED, ok: false, trustNote: problem };
380
- result = { ...result, ok: false, problems: [...result.problems, problem] };
381
- }
382
- if (approval.signedFailed > 0) {
383
- result = {
384
- ...result,
385
- ok: false,
386
- problems: [...result.problems, `approval signatures: ${approval.signedFailed} did not verify`],
387
- };
388
- }
389
- if (approval.signedAfterRemoval > 0) {
390
- result = {
391
- ...result,
392
- ok: false,
393
- problems: [...result.problems, `approval signatures: ${approval.signedAfterRemoval} signed after removal`],
394
- };
395
- }
396
- let control;
397
- try {
398
- control = await verifyControlSignatures(dir, credentialsFile ? { credentialsFile } : {});
399
- }
400
- catch (err) {
401
- const problem = err instanceof Error ? err.message : "control signatures could not be read";
402
- control = { ...CONTROL_NOT_CHECKED, ok: false, trustNote: problem };
403
- result = { ...result, ok: false, problems: [...result.problems, problem] };
404
- }
405
- if (control.signedFailed > 0) {
406
- result = {
407
- ...result,
408
- ok: false,
409
- problems: [...result.problems, `control signatures: ${control.signedFailed} did not verify`],
410
- };
411
- }
412
- if (control.signedAfterRemoval > 0) {
413
- result = {
414
- ...result,
415
- ok: false,
416
- problems: [...result.problems, `control signatures: ${control.signedAfterRemoval} signed after removal`],
417
- };
418
- }
419
- // Start rows are signed by the record key: the pinned one, else the one the records carry.
420
- const startKeyPem = publicKeyPem ?? result.trust.publicKeyPem ?? null;
421
- const starts = readStartSummary(dir, startKeyPem, publicKeyPem ? "pinned" : "in-ledger", {
422
- requireSigned: requireSignedStarts,
515
+ const completed = await completeVerify(dir, result, {
516
+ ...(credentialsFile ? { credentialsFile } : {}),
517
+ requireSignedStarts,
518
+ ...(publicKeyPem ? { pinnedPublicKeyPem: publicKeyPem } : {}),
423
519
  });
424
- if (starts.problems.length > 0) {
425
- result = { ...result, ok: false, problems: [...result.problems, ...starts.problems] };
426
- }
427
- const reported = { ...result, approvalSignatures: approval, controlSignatures: control, starts };
520
+ // attested* stay on completed.result for report; --json matches main.
521
+ const { attestedDecisions: _ad, attestedCheckpoints: _ac, ...publicResult } = completed.result;
522
+ const reported = {
523
+ ...publicResult,
524
+ approvalSignatures: completed.approval,
525
+ controlSignatures: completed.control,
526
+ starts: completed.starts,
527
+ };
428
528
  // Human lines are escaped in renderVerify. JSON keeps the breaks it wrote.
429
- out(json ? terminalLines(JSON.stringify(reported, null, 2)) : renderVerify(reported, approval, control, reported.starts));
430
- return reported.ok ? 0 : EX_VERIFY_FAILED;
529
+ out(json
530
+ ? terminalLines(JSON.stringify(reported, null, 2))
531
+ : renderVerify(completed.result, completed.approval, completed.control, completed.starts));
532
+ return completed.result.ok ? 0 : EX_VERIFY_FAILED;
431
533
  }
package/dist/watch.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { setTimeout as delay } from "node:timers/promises";
4
- import { haltBody, readHalt } from "./halt.js";
4
+ import { haltBody, notStateDir, readHalt } from "./halt.js";
5
5
  import { readHeartbeat } from "./health-extras.js";
6
6
  import { isLoopbackHost } from "./config.js";
7
7
  const USAGE = "usage: verax watch <stateDir> | --url <https://host/healthz> --token-file <path> [--max-silence 30s] [--once] [--on-silence halt|exec] [--exec <command>]";
@@ -175,6 +175,7 @@ export async function runWatch(argv, hooks = {}) {
175
175
  if (reason && !silent) {
176
176
  silent = true;
177
177
  let actionResult = "halted";
178
+ let refused = null;
178
179
  if (opts.action === "exec") {
179
180
  actionResult = await execute(opts, reason, hooks) ? "exec-ok" : "exec-failed";
180
181
  }
@@ -182,18 +183,22 @@ export async function runWatch(argv, hooks = {}) {
182
183
  actionResult = "remote halt is out of scope";
183
184
  }
184
185
  else {
185
- try {
186
- haltBody(opts.stateDir, "verax-watch", "cli", now);
187
- if (!readHalt(opts.stateDir).halted)
188
- actionResult = "halt-failed";
189
- }
190
- catch {
186
+ refused = notStateDir(opts.stateDir);
187
+ if (refused)
191
188
  actionResult = "halt-failed";
192
- }
189
+ else
190
+ try {
191
+ haltBody(opts.stateDir, "verax-watch", "cli", now);
192
+ if (!readHalt(opts.stateDir).halted)
193
+ actionResult = "halt-failed";
194
+ }
195
+ catch {
196
+ actionResult = "halt-failed";
197
+ }
193
198
  }
194
199
  stdout.write(`${JSON.stringify({ event: "silence", atMs: now, reason, action: opts.action, actionResult })}\n`);
195
200
  if (actionResult === "halt-failed") {
196
- stderr.write("verax-watch: could not persist halt\n");
201
+ stderr.write(`verax-watch: ${refused ?? "could not persist halt"}\n`);
197
202
  return 3;
198
203
  }
199
204
  if (opts.url && opts.action === "halt")
@@ -49,7 +49,9 @@ export type PostedRegistration = {
49
49
  * and the exponent 65537. Any other kty, alg, curve or RSA shape is refused.
50
50
  * A refusal returns null; this does not throw.
51
51
  */
52
- export declare function coseKeyToPublicKey(base64urlCose: string): KeyObject | null;
52
+ export declare function coseKeyToPublicKey(base64urlCose: string, opts?: {
53
+ storedKey?: boolean;
54
+ }): KeyObject | null;
53
55
  /**
54
56
  * Check one authentication assertion. `expectedOrigins` is the caller's
55
57
  * allow-list; a caller that does not have one passes the origin it read
@@ -5,7 +5,89 @@
5
5
  * verify one signature.
6
6
  */
7
7
  import { constants, createHash, createPublicKey, verify as cryptoVerify } from "node:crypto";
8
- import { decodeCbor, isCborMap, mapGet } from "@cedulon/cose";
8
+ import { cborMap, decodeCbor, isCborMap, mapGet } from "@cedulon/cose";
9
+ /**
10
+ * A COSE_Key that was enrolled before @cedulon/cose 0.16 may be a valid map
11
+ * whose keys are not in the deterministic order 0.16 requires. Refusing it
12
+ * would lock out that operator and make every approval they already signed
13
+ * fail `verax verify`. This reads only the COSE_Key shape (a definite map of
14
+ * at most 16 integer labels to integers or byte strings, no duplicates, no
15
+ * trailing bytes) and is used for a key the store already holds, never for a
16
+ * new enrolment. The public key it yields is the same as the canonical one;
17
+ * the stored bytes are not rewritten.
18
+ */
19
+ function decodeStoredCoseKey(bytes) {
20
+ let off = 0;
21
+ const head = () => {
22
+ if (off >= bytes.length)
23
+ return null;
24
+ const b = bytes[off++];
25
+ const major = b >> 5;
26
+ const info = b & 0x1f;
27
+ if (info < 24)
28
+ return { major, value: info };
29
+ const width = info === 24 ? 1 : info === 25 ? 2 : info === 26 ? 4 : 0;
30
+ if (width === 0 || off + width > bytes.length)
31
+ return null;
32
+ let value = 0;
33
+ for (let i = 0; i < width; i += 1)
34
+ value = value * 256 + bytes[off++];
35
+ // Only the key order may differ from the deterministic form; a head longer than it needs is refused.
36
+ const floor = width === 1 ? 24 : width === 2 ? 256 : 65536;
37
+ if (value < floor)
38
+ return null;
39
+ return { major, value };
40
+ };
41
+ const intOf = (h) => h.major === 0 ? h.value : h.major === 1 ? -1 - h.value : null;
42
+ const top = head();
43
+ if (!top || top.major !== 5 || top.value > 16)
44
+ return null;
45
+ const entries = [];
46
+ const seen = new Set();
47
+ for (let i = 0; i < top.value; i += 1) {
48
+ const k = head();
49
+ if (!k || (k.major !== 0 && k.major !== 1))
50
+ return null;
51
+ const label = k.major === 0 ? k.value : -1 - k.value;
52
+ if (seen.has(label))
53
+ return null;
54
+ seen.add(label);
55
+ const v = head();
56
+ if (!v)
57
+ return null;
58
+ let value;
59
+ if (v.major === 0)
60
+ value = v.value;
61
+ else if (v.major === 1)
62
+ value = -1 - v.value;
63
+ else if (v.major === 4) {
64
+ // key_ops (label 4) is an array of integers.
65
+ if (v.value > 8)
66
+ return null;
67
+ const items = [];
68
+ for (let j = 0; j < v.value; j += 1) {
69
+ const item = head();
70
+ const n = item ? intOf(item) : null;
71
+ if (n === null)
72
+ return null;
73
+ items.push(n);
74
+ }
75
+ value = items;
76
+ }
77
+ else if (v.major === 2) {
78
+ if (v.value > 16384 || off + v.value > bytes.length)
79
+ return null;
80
+ value = bytes.slice(off, off + v.value);
81
+ off += v.value;
82
+ }
83
+ else
84
+ return null;
85
+ entries.push([label, value]);
86
+ }
87
+ if (off !== bytes.length)
88
+ return null;
89
+ return cborMap(entries);
90
+ }
9
91
  /** The COSE algorithms `coseKeyToPublicKey` takes. An enrolment offers these and no others. */
10
92
  export const COSE_ALGORITHMS = [-7, -8, -257];
11
93
  /** The shortest and the longest RSA modulus taken, for a sign-in as for an enrolment. */
@@ -43,12 +125,23 @@ function mapBytes(map, key, length) {
43
125
  * and the exponent 65537. Any other kty, alg, curve or RSA shape is refused.
44
126
  * A refusal returns null; this does not throw.
45
127
  */
46
- export function coseKeyToPublicKey(base64urlCose) {
128
+ export function coseKeyToPublicKey(base64urlCose, opts = {}) {
47
129
  try {
48
130
  const bytes = fromBase64Url(base64urlCose);
49
131
  if (!bytes)
50
132
  return null;
51
- const decoded = decodeCbor(new Uint8Array(bytes));
133
+ let decoded;
134
+ try {
135
+ decoded = decodeCbor(new Uint8Array(bytes));
136
+ }
137
+ catch (err) {
138
+ if (!opts.storedKey || !(err instanceof Error) || err.message !== "cbor-non-deterministic")
139
+ throw err;
140
+ const stored = decodeStoredCoseKey(new Uint8Array(bytes));
141
+ if (!stored)
142
+ return null;
143
+ decoded = stored;
144
+ }
52
145
  if (!isCborMap(decoded))
53
146
  return null;
54
147
  const kty = mapNum(decoded, 1);
@@ -164,7 +257,7 @@ export function verifyAssertion(opts) {
164
257
  if (flags === undefined || (flags & 0x05) !== 0x05)
165
258
  return { ok: false, reason: "user-verification" };
166
259
  const counter = authenticatorData.readUInt32BE(33);
167
- const key = coseKeyToPublicKey(opts.publicKeyCose);
260
+ const key = coseKeyToPublicKey(opts.publicKeyCose, { storedKey: true });
168
261
  if (!key)
169
262
  return { ok: false, reason: "public-key" };
170
263
  const clientHash = createHash("sha256").update(clientBytes).digest();
package/dist/witness.d.ts CHANGED
@@ -10,16 +10,27 @@ export type WitnessListen = {
10
10
  /** The Transparency Service this witness registers each checkpoint with, or absent. */
11
11
  anchorService?: string;
12
12
  };
13
- /** Where `verax witness` sends each checkpoint it signs, read once at start. */
13
+ /**
14
+ * Where `verax witness` sends each checkpoint it signs, read once at start.
15
+ * With `chainPem` the witness registers each checkpoint over SCRAPI as a
16
+ * Signed Statement it signs as the Issuer that chain names. With `token` every
17
+ * request to the service carries that bearer token; the token is not written
18
+ * to listen or status files.
19
+ */
14
20
  export type WitnessAnchor = {
15
21
  serviceName: string;
16
22
  serviceKey: string | null;
23
+ chainPem: string | null;
24
+ token: string | null;
17
25
  };
18
26
  /**
19
- * `VERAX_ANCHOR_SERVICE` names the service (https; http only on loopback) and
20
- * `VERAX_ANCHOR_SERVICE_KEY` a file holding its public key. Neither set is no
21
- * anchoring. A value that is set but unusable is an error, so a witness the
22
- * operator meant to anchor does not start without anchoring.
27
+ * `VERAX_ANCHOR_SERVICE` names the service (https; http only on loopback),
28
+ * `VERAX_ANCHOR_SERVICE_KEY` a file holding its public key,
29
+ * `VERAX_ANCHOR_X5CHAIN` a PEM file holding the witness certificate chain,
30
+ * leaf first, which selects SCRAPI, and `VERAX_ANCHOR_TOKEN_FILE` a file
31
+ * holding the bearer token the service requires. None set is no anchoring. A
32
+ * value that is set but unusable is an error, so a witness the operator meant
33
+ * to anchor does not start without anchoring.
23
34
  */
24
35
  export declare function witnessAnchorFromEnv(env?: NodeJS.ProcessEnv): {
25
36
  ok: true;
package/dist/witness.js CHANGED
@@ -7,26 +7,53 @@ import { buildCheckpointClaims, checkpointHash, signCheckpoint, totalsFromDecisi
7
7
  import { canonical, decisionRecordHash } from "@cedulon/core";
8
8
  import { coseFromHex, decodeCoseSign1, verifyCoseSign1 } from "@cedulon/cose";
9
9
  import { verifyEffectExtract } from "@cedulon/effect-extract";
10
- import { appendAnchor, checkpointsPath, listPieceFiles, signEffectAttestation } from "@verax-ai/proxy";
11
- import { pendingAnchors, registerCheckpoint, serviceNameOf, serviceUrl } from "./anchor-cli.js";
10
+ import { appendAnchor, checkpointStatement, checkpointsPath, listPieceFiles, readIssuerChain, signEffectAttestation, } from "@verax-ai/proxy";
11
+ import { pendingAnchors, readAnchorTokenFile, registerCheckpoint, registerStatement, serviceNameOf, serviceUrl, statementIssuer, } from "./anchor-cli.js";
12
12
  import { assertEd25519PublicKey } from "./keys.js";
13
13
  import { lockHolderAlive } from "@verax-ai/proxy";
14
14
  import { pidAlive } from "./unlock.js";
15
15
  const WITNESS_CLASS = "same-org";
16
16
  /**
17
- * `VERAX_ANCHOR_SERVICE` names the service (https; http only on loopback) and
18
- * `VERAX_ANCHOR_SERVICE_KEY` a file holding its public key. Neither set is no
19
- * anchoring. A value that is set but unusable is an error, so a witness the
20
- * operator meant to anchor does not start without anchoring.
17
+ * `VERAX_ANCHOR_SERVICE` names the service (https; http only on loopback),
18
+ * `VERAX_ANCHOR_SERVICE_KEY` a file holding its public key,
19
+ * `VERAX_ANCHOR_X5CHAIN` a PEM file holding the witness certificate chain,
20
+ * leaf first, which selects SCRAPI, and `VERAX_ANCHOR_TOKEN_FILE` a file
21
+ * holding the bearer token the service requires. None set is no anchoring. A
22
+ * value that is set but unusable is an error, so a witness the operator meant
23
+ * to anchor does not start without anchoring.
21
24
  */
22
25
  export function witnessAnchorFromEnv(env = process.env) {
23
26
  const raw = env.VERAX_ANCHOR_SERVICE?.trim() ?? "";
24
27
  const keyPath = env.VERAX_ANCHOR_SERVICE_KEY?.trim() ?? "";
28
+ const chainPath = env.VERAX_ANCHOR_X5CHAIN?.trim() ?? "";
29
+ const tokenPath = env.VERAX_ANCHOR_TOKEN_FILE?.trim() ?? "";
25
30
  if (raw === "") {
26
31
  if (keyPath !== "")
27
32
  return { ok: false, reason: "VERAX_ANCHOR_SERVICE_KEY is set without VERAX_ANCHOR_SERVICE" };
33
+ if (chainPath !== "")
34
+ return { ok: false, reason: "VERAX_ANCHOR_X5CHAIN is set without VERAX_ANCHOR_SERVICE" };
35
+ if (tokenPath !== "")
36
+ return { ok: false, reason: "VERAX_ANCHOR_TOKEN_FILE is set without VERAX_ANCHOR_SERVICE" };
28
37
  return { ok: true, anchor: null };
29
38
  }
39
+ let chainPem = null;
40
+ if (chainPath !== "") {
41
+ try {
42
+ chainPem = readFileSync(chainPath, "utf8");
43
+ }
44
+ catch {
45
+ return { ok: false, reason: `cannot read VERAX_ANCHOR_X5CHAIN file ${chainPath}` };
46
+ }
47
+ try {
48
+ readIssuerChain(chainPem);
49
+ }
50
+ catch {
51
+ return {
52
+ ok: false,
53
+ reason: `VERAX_ANCHOR_X5CHAIN file ${chainPath} must hold the witness certificate and at least one CA certificate, leaf first`,
54
+ };
55
+ }
56
+ }
30
57
  const url = serviceUrl(raw);
31
58
  if (!url) {
32
59
  return {
@@ -53,7 +80,14 @@ export function witnessAnchorFromEnv(env = process.env) {
53
80
  return { ok: false, reason: `VERAX_ANCHOR_SERVICE_KEY file ${keyPath} is not a public key` };
54
81
  }
55
82
  }
56
- return { ok: true, anchor: { serviceName: serviceNameOf(url), serviceKey } };
83
+ let token = null;
84
+ if (tokenPath !== "") {
85
+ const got = readAnchorTokenFile(tokenPath);
86
+ if (!got.ok)
87
+ return { ok: false, reason: `VERAX_ANCHOR_TOKEN_FILE: ${got.reason}` };
88
+ token = got.token;
89
+ }
90
+ return { ok: true, anchor: { serviceName: serviceNameOf(url), serviceKey, chainPem, token } };
57
91
  }
58
92
  /**
59
93
  * Registers every checkpoint in `stateDir` not yet anchored at the service,
@@ -72,8 +106,24 @@ export async function anchorPendingCheckpoints(stateDir, anchor, fetchImpl = fet
72
106
  });
73
107
  return;
74
108
  }
109
+ let issuer = null;
110
+ if (anchor.chainPem !== null) {
111
+ const found = statementIssuer(stateDir, anchor.chainPem);
112
+ if (!found.ok) {
113
+ appendStatus(stateDir, {
114
+ atMs: Date.now(),
115
+ result: "anchor-failed",
116
+ service: anchor.serviceName,
117
+ reason: "issuer",
118
+ });
119
+ return;
120
+ }
121
+ issuer = found.issuer;
122
+ }
75
123
  for (const hash of pending) {
76
- const got = await registerCheckpoint(anchor.serviceName, hash, anchor.serviceKey, fetchImpl);
124
+ const got = issuer
125
+ ? await registerStatement(anchor.serviceName, hash, checkpointStatement(hash, issuer.chain, issuer.keys), anchor.serviceKey, fetchImpl, Date.now, undefined, anchor.token)
126
+ : await registerCheckpoint(anchor.serviceName, hash, anchor.serviceKey, fetchImpl, Date.now, anchor.token);
77
127
  if (!got.ok) {
78
128
  appendStatus(stateDir, {
79
129
  atMs: Date.now(),
@@ -500,6 +550,15 @@ export async function runWitness(stateDir) {
500
550
  }))
501
551
  : () => undefined;
502
552
  const keys = loadOrCreateWitnessKeys(stateDir);
553
+ if (anchor?.chainPem) {
554
+ // A chain for another key would start a witness whose every statement the
555
+ // service refuses; the operator hears it here instead.
556
+ const issuer = statementIssuer(stateDir, anchor.chainPem);
557
+ if (!issuer.ok) {
558
+ process.stderr.write(`witness-anchor-config: ${issuer.reason}\n`);
559
+ process.exit(64);
560
+ }
561
+ }
503
562
  const token = randomBytes(16).toString("hex");
504
563
  const server = createServer((req, res) => {
505
564
  void (async () => {