@verax-ai/proxy 0.4.1 → 0.4.3

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/ledger.js CHANGED
@@ -190,6 +190,9 @@ function noteReauth(map, row) {
190
190
  map.set(row.requestHash, row.ref);
191
191
  }
192
192
  function noteCounted(times, row) {
193
+ // A halt or resume is not a tool call. Counting it would spend the rate budget on the switch.
194
+ if (row.reasonCode === "operator-halt" || row.reasonCode === "operator-resume")
195
+ return;
193
196
  if (row.decision === "allow" || row.decision === "defer")
194
197
  times.push(row.timestampMs);
195
198
  }
@@ -239,17 +242,25 @@ export class MemoryLedger {
239
242
  });
240
243
  }
241
244
  async appendDecisionChained(build) {
242
- return this.q.enqueue(async () => {
243
- const last = this._decisions[this._decisions.length - 1];
244
- const signed = build(last ? decisionRecordHash(last) : null);
245
- this._decisions.push(signed);
246
- const row = indexRowOf(signed);
247
- if (row) {
248
- this.byRef.set(row.ref, row);
249
- noteReauth(this.reauthByHash, row);
250
- noteCounted(this.countedAt, row);
251
- }
252
- });
245
+ return this.q.enqueue(() => this.appendDecisionChainedUnlocked(build));
246
+ }
247
+ async appendDecisionChainedUnlocked(build) {
248
+ const last = this._decisions[this._decisions.length - 1];
249
+ const signed = build(last ? decisionRecordHash(last) : null);
250
+ this._decisions.push(signed);
251
+ const row = indexRowOf(signed);
252
+ if (row) {
253
+ this.byRef.set(row.ref, row);
254
+ noteReauth(this.reauthByHash, row);
255
+ noteCounted(this.countedAt, row);
256
+ }
257
+ }
258
+ /** One turn of this ledger's queue: read a cursor and append without a second writer seeing the same cursor. */
259
+ async exclusive(fn) {
260
+ return this.q.enqueue(() => fn({
261
+ appendDecisionChained: (build) => this.appendDecisionChainedUnlocked(build),
262
+ appendEffect: (row, witnessClass, resultHash) => this.appendEffectUnlocked(row, witnessClass, resultHash),
263
+ }));
253
264
  }
254
265
  async appendEffect(row, witnessClass = DEFAULT_WITNESS, resultHash) {
255
266
  return this.q.enqueue(async () => this.appendEffectUnlocked(row, witnessClass, resultHash));
@@ -797,27 +808,35 @@ export class FileLedger {
797
808
  });
798
809
  }
799
810
  async appendDecisionChained(build) {
800
- return this.q.enqueue(async () => {
801
- this.assertOwned();
802
- const prev = await this.lastDecisionHashUnlocked();
803
- await mkdir(this.dir, { recursive: true, mode: 0o700 });
804
- const signed = build(prev);
805
- const line = lineOf(signed);
806
- await appendDurable(this.decisionsPath, line);
807
- await this.pulse("decisions.jsonl", line, "decision");
808
- this.tailHash = decisionRecordHash(signed);
809
- this.lastDecisionMs = signed.claims.timestampMs;
810
- this.noteActiveStamp(signed.claims.timestampMs);
811
- this.activeDecisionN += 1;
812
- const row = indexRowOf(signed);
813
- if (row) {
814
- this.byRef.set(row.ref, row);
815
- noteReauth(this.reauthByHash, row);
816
- noteCounted(this.countedAt, row);
817
- }
818
- await this.writeIndexForDecision(signed);
819
- await this.maybeRotate();
820
- });
811
+ return this.q.enqueue(() => this.appendDecisionChainedUnlocked(build));
812
+ }
813
+ async appendDecisionChainedUnlocked(build) {
814
+ this.assertOwned();
815
+ const prev = await this.lastDecisionHashUnlocked();
816
+ await mkdir(this.dir, { recursive: true, mode: 0o700 });
817
+ const signed = build(prev);
818
+ const line = lineOf(signed);
819
+ await appendDurable(this.decisionsPath, line);
820
+ await this.pulse("decisions.jsonl", line, "decision");
821
+ this.tailHash = decisionRecordHash(signed);
822
+ this.lastDecisionMs = signed.claims.timestampMs;
823
+ this.noteActiveStamp(signed.claims.timestampMs);
824
+ this.activeDecisionN += 1;
825
+ const row = indexRowOf(signed);
826
+ if (row) {
827
+ this.byRef.set(row.ref, row);
828
+ noteReauth(this.reauthByHash, row);
829
+ noteCounted(this.countedAt, row);
830
+ }
831
+ await this.writeIndexForDecision(signed);
832
+ await this.maybeRotate();
833
+ }
834
+ /** One turn of this ledger's queue: read a cursor and append without a second writer seeing the same cursor. */
835
+ async exclusive(fn) {
836
+ return this.q.enqueue(() => fn({
837
+ appendDecisionChained: (build) => this.appendDecisionChainedUnlocked(build),
838
+ appendEffect: (row, witnessClass, resultHash) => this.appendEffectUnlocked(row, witnessClass, resultHash),
839
+ }));
821
840
  }
822
841
  /**
823
842
  * What /healthz reports, from memory: the counts are kept on load and on
@@ -917,6 +936,7 @@ export class FileLedger {
917
936
  });
918
937
  }
919
938
  async appendEffectUnlocked(row, witnessClass = DEFAULT_WITNESS, resultHash) {
939
+ this.assertOwned();
920
940
  if (row.effectClass !== "duplicate-effect" && this.effectRefs.has(row.ref)) {
921
941
  const dup = lineOf(asStoredEffect({
922
942
  ref: row.ref,
package/dist/proxy.d.ts CHANGED
@@ -7,5 +7,6 @@ export declare const REF_RE: RegExp;
7
7
  export declare function createProxy(deps: ProxyDeps): {
8
8
  approvals: import("./approvals.ts").ApprovalsLog;
9
9
  inputsLog: import("./types.ts").InputsLog;
10
+ syncControlRecords: () => Promise<void>;
10
11
  call(call: ToolCall, principal: Principal): Promise<ToolResult>;
11
12
  };
package/dist/proxy.js CHANGED
@@ -7,6 +7,7 @@ import { diskProbe } from "./disk.js";
7
7
  import { markEnded, markStarted, startedWithoutEnd } from "./in-flight-log.js";
8
8
  import { effectDescriptor, sha256Canonical } from "./hash.js";
9
9
  import { inputsLogFor } from "./inputs.js";
10
+ import { controlUnchanged, createControlMemory, syncHaltControl } from "./control-sync.js";
10
11
  import { countedWork, hasPrimaryEffect, lookupDecisionByRef, lookupReauthByHash, lookupResolvedBy, noteResolution, noteTenantRef, } from "./ledger.js";
11
12
  import { spokenReason } from "./spoken-reason.js";
12
13
  import { tenantKey } from "./tenant.js";
@@ -178,6 +179,7 @@ export function createProxy(deps) {
178
179
  const inputsLog = deps.inputsLog ?? inputsLogFor(deps.ledger);
179
180
  const approvals = approvalsLogFor(deps.ledger);
180
181
  const admission = new SerialQueue();
182
+ const controlQueue = new SerialQueue();
181
183
  const inFlight = new Map();
182
184
  const budgetGuard = createApprovalBudgetGuard({
183
185
  policy: deps.policy,
@@ -188,6 +190,10 @@ export function createProxy(deps) {
188
190
  deps.ledger.effectSigner = deps.effectSigner;
189
191
  const ledgerDir = deps.ledger.dir;
190
192
  const stateDir = typeof ledgerDir === "string" ? ledgerDir : null;
193
+ // Single writer: after open, the ledger lock is this process. The first
194
+ // sync reads control records once; this snapshot is updated in place.
195
+ const controlMemory = createControlMemory();
196
+ let controlSyncReported = false;
191
197
  if (stateDir === null) {
192
198
  process.stderr.write("verax-proxy: halt and disk limits are inactive without a ledger directory\n");
193
199
  }
@@ -430,9 +436,52 @@ export function createProxy(deps) {
430
436
  });
431
437
  return denied(verdict.reasonCode, denyRef);
432
438
  }
439
+ async function syncControlRecords() {
440
+ if (stateDir === null)
441
+ return;
442
+ try {
443
+ if (controlUnchanged(stateDir, controlMemory))
444
+ return;
445
+ const run = (writer) => syncHaltControl({
446
+ stateDir,
447
+ now: deps.now,
448
+ nonce: deps.nonce,
449
+ policyHash: deps.policy.hash,
450
+ recordSigner: deps.recordSigner,
451
+ inputsLog,
452
+ decisions: () => deps.ledger.decisions(),
453
+ memory: controlMemory,
454
+ writer,
455
+ });
456
+ const host = deps.ledger;
457
+ if (typeof host.exclusive === "function") {
458
+ await host.exclusive((writer) => run(writer));
459
+ }
460
+ else {
461
+ await controlQueue.enqueue(() => run({
462
+ appendDecisionChained: (build) => deps.ledger.appendDecisionChained(build),
463
+ appendEffect: (row, witnessClass, resultHash) => deps.ledger.appendEffect(row, witnessClass, resultHash),
464
+ }));
465
+ }
466
+ controlSyncReported = false;
467
+ }
468
+ catch (err) {
469
+ // An unreadable ledger used to throw out of the call. Leave the snapshot
470
+ // unloaded so the next call reads again, and keep going: the halt switch
471
+ // and the rate limit still fail closed on their own path. One line per
472
+ // failure streak, so the admission retry in the same call does not repeat it.
473
+ controlMemory.loaded = false;
474
+ if (controlSyncReported)
475
+ return;
476
+ controlSyncReported = true;
477
+ const message = (err instanceof Error ? err.message : String(err)).replace(/[\r\n]+/g, " ");
478
+ process.stderr.write(`verax-proxy: control sync failed: ${message}\n`);
479
+ }
480
+ }
433
481
  return {
434
482
  approvals,
435
483
  inputsLog,
484
+ syncControlRecords,
436
485
  async call(call, principal) {
437
486
  if (stateDir) {
438
487
  await drainApprovalCommands(stateDir, async (cmd) => {
@@ -454,6 +503,7 @@ export function createProxy(deps) {
454
503
  budgetGuard,
455
504
  });
456
505
  });
506
+ await syncControlRecords();
457
507
  }
458
508
  const dispatched = toolCallOf(call);
459
509
  const requestHash = sha256Canonical(dispatched);
@@ -489,6 +539,9 @@ export function createProxy(deps) {
489
539
  }
490
540
  const given = readRef(call.arguments);
491
541
  const plan = await admission.enqueue(async () => {
542
+ // A halt that landed while this call waited must be on the chain before the deny.
543
+ if (stateDir)
544
+ await syncControlRecords();
492
545
  // A call that waited here behind another admission reads the halt flag again.
493
546
  if (stateDir && existsSync(join(stateDir, "halted"))) {
494
547
  const ref = deps.nonce();
@@ -0,0 +1,38 @@
1
+ export declare class CborTag {
2
+ readonly tag: number;
3
+ readonly value: unknown;
4
+ constructor(tag: number, value: unknown);
5
+ }
6
+ /** RFC 8949 definite-length items; floats and indefinite lengths are refused. */
7
+ export declare function decodeCborItem(bytes: Uint8Array): unknown;
8
+ /** RFC 9052 4.4: ["Signature1", body_protected, external_aad = h'', payload], CBOR-encoded. */
9
+ export declare function sign1Structure(protectedBytes: Uint8Array, payload: Uint8Array): Buffer;
10
+ export type Sign1 = {
11
+ protectedBytes: Uint8Array;
12
+ protectedHeader: Map<unknown, unknown>;
13
+ unprotected: Map<unknown, unknown>;
14
+ payload: Uint8Array | null;
15
+ signature: Uint8Array;
16
+ };
17
+ /** A COSE_Sign1, tagged 18 or untagged. */
18
+ export declare function decodeSign1(bytes: Uint8Array): Sign1;
19
+ /** COSE algorithms a receipt may use: EdDSA/Ed25519 (-8, -19), ES256 (-7), ES384 (-35). */
20
+ export declare function verifyCoseSignature(alg: unknown, publicKeyPem: string, data: Buffer, signature: Uint8Array): boolean;
21
+ /** RFC 9162 2.1.3.2: the root an inclusion proof yields for a leaf entry. */
22
+ export declare function rootFromInclusion(leafEntry: Uint8Array, leafIndex: number, treeSize: number, path: readonly Uint8Array[]): Buffer;
23
+ export type ReceiptStage = "receipt-decode" | "vds-gate" | "inclusion" | "receipt-sig";
24
+ export type ReceiptCheck = {
25
+ ok: true;
26
+ root: string;
27
+ treeSize: number;
28
+ leafIndex: number;
29
+ } | {
30
+ ok: false;
31
+ stage: ReceiptStage;
32
+ reason: string;
33
+ };
34
+ /**
35
+ * Checks one receipt for one leaf entry under the service key the reader
36
+ * holds. vds is read from the protected header only.
37
+ */
38
+ export declare function verifyReceipt(receipt: Uint8Array, leafEntry: Uint8Array, publicKeyPem: string): ReceiptCheck;
@@ -0,0 +1,277 @@
1
+ /**
2
+ * COSE Receipts from a SCITT Transparency Service (RFC 9943) over an RFC 9162
3
+ * SHA-256 Merkle tree, read without the service.
4
+ *
5
+ * A receipt is a COSE_Sign1, normally tagged 18, whose protected header names
6
+ * the verifiable data structure at label 395 (1 is RFC9162_SHA256) and whose
7
+ * unprotected header carries, at label 396 key -1, one inclusion proof: the
8
+ * CBOR array [tree_size, leaf_index, audit_path]. The payload is detached: it
9
+ * is the tree root, which the verifier rebuilds from the leaf entry and the
10
+ * path and then checks the signature over. A receipt carries no key id, so the
11
+ * service key is always the reader's to supply.
12
+ *
13
+ * This is a second CBOR reader beside @cedulon/cose on purpose. That one reads
14
+ * Cedulon's own objects and refuses tags, floats and non-empty unprotected
15
+ * headers, which is right for them; a receipt written by someone else's
16
+ * service uses all three.
17
+ */
18
+ import { createHash, createPublicKey, verify as verifySignature } from "node:crypto";
19
+ export class CborTag {
20
+ tag;
21
+ value;
22
+ constructor(tag, value) {
23
+ this.tag = tag;
24
+ this.value = value;
25
+ }
26
+ }
27
+ const MAX_BYTES = 65_536;
28
+ const MAX_DEPTH = 16;
29
+ const MAX_ITEMS = 4_096;
30
+ /** RFC 8949 definite-length items; floats and indefinite lengths are refused. */
31
+ export function decodeCborItem(bytes) {
32
+ if (bytes.length > MAX_BYTES)
33
+ throw new Error("cbor-too-large");
34
+ let at = 0;
35
+ let items = 0;
36
+ const need = (n) => {
37
+ if (at + n > bytes.length)
38
+ throw new Error("cbor-eof");
39
+ };
40
+ const length = (ai) => {
41
+ if (ai < 24)
42
+ return ai;
43
+ const size = ai === 24 ? 1 : ai === 25 ? 2 : ai === 26 ? 4 : ai === 27 ? 8 : 0;
44
+ if (size === 0)
45
+ throw new Error("cbor-indefinite-or-reserved");
46
+ need(size);
47
+ let n = 0n;
48
+ for (let i = 0; i < size; i += 1)
49
+ n = (n << 8n) | BigInt(bytes[at + i]);
50
+ at += size;
51
+ if (n > BigInt(Number.MAX_SAFE_INTEGER))
52
+ throw new Error("cbor-int-too-large");
53
+ return Number(n);
54
+ };
55
+ const item = (depth) => {
56
+ if (depth > MAX_DEPTH)
57
+ throw new Error("cbor-too-deep");
58
+ items += 1;
59
+ if (items > MAX_ITEMS)
60
+ throw new Error("cbor-too-many-items");
61
+ need(1);
62
+ const ib = bytes[at];
63
+ at += 1;
64
+ const major = ib >> 5;
65
+ const ai = ib & 31;
66
+ if (major === 7) {
67
+ if (ai === 20)
68
+ return false;
69
+ if (ai === 21)
70
+ return true;
71
+ if (ai === 22)
72
+ return null;
73
+ throw new Error("cbor-simple-or-float");
74
+ }
75
+ const n = length(ai);
76
+ switch (major) {
77
+ case 0:
78
+ return n;
79
+ case 1:
80
+ return -1 - n;
81
+ case 2:
82
+ need(n);
83
+ at += n;
84
+ return bytes.slice(at - n, at);
85
+ case 3:
86
+ need(n);
87
+ at += n;
88
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes.slice(at - n, at));
89
+ case 4: {
90
+ if (n > MAX_ITEMS)
91
+ throw new Error("cbor-too-many-items");
92
+ const out = [];
93
+ for (let i = 0; i < n; i += 1)
94
+ out.push(item(depth + 1));
95
+ return out;
96
+ }
97
+ case 5: {
98
+ if (n > MAX_ITEMS)
99
+ throw new Error("cbor-too-many-items");
100
+ const out = new Map();
101
+ for (let i = 0; i < n; i += 1) {
102
+ const key = item(depth + 1);
103
+ if (key instanceof Uint8Array || key instanceof Map || Array.isArray(key))
104
+ throw new Error("cbor-key-type");
105
+ if (out.has(key))
106
+ throw new Error("cbor-duplicate-key");
107
+ out.set(key, item(depth + 1));
108
+ }
109
+ return out;
110
+ }
111
+ case 6:
112
+ return new CborTag(n, item(depth + 1));
113
+ default:
114
+ throw new Error("cbor-major");
115
+ }
116
+ };
117
+ const value = item(0);
118
+ if (at !== bytes.length)
119
+ throw new Error("cbor-trailing");
120
+ return value;
121
+ }
122
+ function head(major, n) {
123
+ if (n < 24)
124
+ return Buffer.of((major << 5) | n);
125
+ if (n < 0x100)
126
+ return Buffer.of((major << 5) | 24, n);
127
+ if (n < 0x10000)
128
+ return Buffer.of((major << 5) | 25, n >> 8, n & 0xff);
129
+ const b = Buffer.alloc(5);
130
+ b[0] = (major << 5) | 26;
131
+ b.writeUInt32BE(n, 1);
132
+ return b;
133
+ }
134
+ /** RFC 9052 4.4: ["Signature1", body_protected, external_aad = h'', payload], CBOR-encoded. */
135
+ export function sign1Structure(protectedBytes, payload) {
136
+ const text = Buffer.from("Signature1", "utf8");
137
+ return Buffer.concat([
138
+ head(4, 4),
139
+ head(3, text.length),
140
+ text,
141
+ head(2, protectedBytes.length),
142
+ protectedBytes,
143
+ head(2, 0),
144
+ head(2, payload.length),
145
+ payload,
146
+ ]);
147
+ }
148
+ /** A COSE_Sign1, tagged 18 or untagged. */
149
+ export function decodeSign1(bytes) {
150
+ let value = decodeCborItem(bytes);
151
+ if (value instanceof CborTag) {
152
+ if (value.tag !== 18)
153
+ throw new Error(`cose-tag-${value.tag}`);
154
+ value = value.value;
155
+ }
156
+ if (!Array.isArray(value) || value.length !== 4)
157
+ throw new Error("cose-sign1-shape");
158
+ const [p, u, payload, signature] = value;
159
+ if (!(p instanceof Uint8Array) || !(u instanceof Map) || !(signature instanceof Uint8Array)) {
160
+ throw new Error("cose-sign1-members");
161
+ }
162
+ if (payload !== null && !(payload instanceof Uint8Array))
163
+ throw new Error("cose-sign1-payload");
164
+ const protectedHeader = p.length === 0 ? new Map() : decodeCborItem(p);
165
+ if (!(protectedHeader instanceof Map))
166
+ throw new Error("cose-protected-header");
167
+ return { protectedBytes: p, protectedHeader, unprotected: u, payload, signature };
168
+ }
169
+ /** COSE algorithms a receipt may use: EdDSA/Ed25519 (-8, -19), ES256 (-7), ES384 (-35). */
170
+ export function verifyCoseSignature(alg, publicKeyPem, data, signature) {
171
+ const key = createPublicKey(publicKeyPem);
172
+ if (alg === -8 || alg === -19) {
173
+ return key.asymmetricKeyType === "ed25519" && verifySignature(null, data, key, signature);
174
+ }
175
+ const curve = key.asymmetricKeyType === "ec" ? key.asymmetricKeyDetails?.namedCurve : undefined;
176
+ if (alg === -7) {
177
+ return curve === "prime256v1" && verifySignature("sha256", data, { key, dsaEncoding: "ieee-p1363" }, signature);
178
+ }
179
+ if (alg === -35) {
180
+ return curve === "secp384r1" && verifySignature("sha384", data, { key, dsaEncoding: "ieee-p1363" }, signature);
181
+ }
182
+ return false;
183
+ }
184
+ const sha256 = (...parts) => createHash("sha256").update(Buffer.concat(parts)).digest();
185
+ /** RFC 9162 2.1.3.2: the root an inclusion proof yields for a leaf entry. */
186
+ export function rootFromInclusion(leafEntry, leafIndex, treeSize, path) {
187
+ if (!Number.isSafeInteger(leafIndex) || !Number.isSafeInteger(treeSize) || leafIndex < 0 || leafIndex >= treeSize) {
188
+ throw new Error("inclusion-index");
189
+ }
190
+ let fn = leafIndex;
191
+ let sn = treeSize - 1;
192
+ // RFC 9162 2.1.1: a leaf hashes as SHA-256(0x00 || entry), an interior node as SHA-256(0x01 || left || right).
193
+ let r = sha256(Buffer.of(0x00), leafEntry);
194
+ for (const p of path) {
195
+ if (p.length !== 32)
196
+ throw new Error("inclusion-node-size");
197
+ if (sn === 0)
198
+ throw new Error("inclusion-path-too-long");
199
+ if (fn % 2 === 1 || fn === sn) {
200
+ r = sha256(Buffer.of(0x01), p, r);
201
+ while (fn % 2 === 0 && fn !== 0) {
202
+ fn = Math.floor(fn / 2);
203
+ sn = Math.floor(sn / 2);
204
+ }
205
+ }
206
+ else {
207
+ r = sha256(Buffer.of(0x01), r, p);
208
+ }
209
+ fn = Math.floor(fn / 2);
210
+ sn = Math.floor(sn / 2);
211
+ }
212
+ if (sn !== 0)
213
+ throw new Error("inclusion-path-too-short");
214
+ return r;
215
+ }
216
+ const UNDERSTOOD = new Set([1, 395]);
217
+ /**
218
+ * Checks one receipt for one leaf entry under the service key the reader
219
+ * holds. vds is read from the protected header only.
220
+ */
221
+ export function verifyReceipt(receipt, leafEntry, publicKeyPem) {
222
+ let sign1;
223
+ try {
224
+ sign1 = decodeSign1(receipt);
225
+ }
226
+ catch (err) {
227
+ return { ok: false, stage: "receipt-decode", reason: err instanceof Error ? err.message : String(err) };
228
+ }
229
+ // RFC 9052 3.1: crit lists labels a reader must understand, is non-empty and
230
+ // sits in the protected header. This reader understands alg and vds only.
231
+ const crit = sign1.protectedHeader.get(2);
232
+ if (crit !== undefined && (!Array.isArray(crit) || crit.length === 0 || !crit.every((l) => UNDERSTOOD.has(l)))) {
233
+ return { ok: false, stage: "receipt-decode", reason: "a critical header this reader does not understand" };
234
+ }
235
+ if (sign1.unprotected.has(2))
236
+ return { ok: false, stage: "receipt-decode", reason: "crit in the unprotected header" };
237
+ const vds = sign1.protectedHeader.get(395);
238
+ if (vds !== 1)
239
+ return { ok: false, stage: "vds-gate", reason: `vds ${String(vds)} is not RFC9162_SHA256` };
240
+ const vdp = sign1.unprotected.get(396);
241
+ const proofs = vdp instanceof Map ? vdp.get(-1) : undefined;
242
+ if (!Array.isArray(proofs) || proofs.length !== 1 || !(proofs[0] instanceof Uint8Array)) {
243
+ return { ok: false, stage: "receipt-decode", reason: "no single inclusion proof at 396/-1" };
244
+ }
245
+ if (sign1.payload !== null)
246
+ return { ok: false, stage: "receipt-decode", reason: "receipt payload is not detached" };
247
+ let proof;
248
+ try {
249
+ proof = decodeCborItem(proofs[0]);
250
+ }
251
+ catch (err) {
252
+ return { ok: false, stage: "receipt-decode", reason: err instanceof Error ? err.message : String(err) };
253
+ }
254
+ if (!Array.isArray(proof) || proof.length !== 3)
255
+ return { ok: false, stage: "receipt-decode", reason: "inclusion proof shape" };
256
+ const [treeSize, leafIndex, path] = proof;
257
+ if (typeof treeSize !== "number" || typeof leafIndex !== "number" || !Array.isArray(path) || !path.every((p) => p instanceof Uint8Array)) {
258
+ return { ok: false, stage: "receipt-decode", reason: "inclusion proof members" };
259
+ }
260
+ let root;
261
+ try {
262
+ root = rootFromInclusion(leafEntry, leafIndex, treeSize, path);
263
+ }
264
+ catch (err) {
265
+ return { ok: false, stage: "inclusion", reason: err instanceof Error ? err.message : String(err) };
266
+ }
267
+ let verified = false;
268
+ try {
269
+ verified = verifyCoseSignature(sign1.protectedHeader.get(1), publicKeyPem, sign1Structure(sign1.protectedBytes, root), sign1.signature);
270
+ }
271
+ catch {
272
+ verified = false;
273
+ }
274
+ if (!verified)
275
+ return { ok: false, stage: "receipt-sig", reason: "signature does not verify over the rebuilt root" };
276
+ return { ok: true, root: root.toString("hex"), treeSize, leafIndex };
277
+ }
package/dist/types.d.ts CHANGED
@@ -103,6 +103,40 @@ export type DecisionInputRow = {
103
103
  /** Optional provenance. Same idea as memory.put `source`; additive. */
104
104
  source?: Record<string, unknown>;
105
105
  };
106
+ /**
107
+ * One halt or resume copied from `halt-history.jsonl`, or a file switch the
108
+ * history does not explain. `line` is the 0-based index of a history line.
109
+ * A switch with no history halt uses `line: -1`, `via: "file"`, and
110
+ * `action: "halt"`. Deleting that switch while a halt window is still open,
111
+ * with no history resume that closes it, uses the same line and via with
112
+ * `action: "resume"`. On a `halt-history-mismatch` deny, `line` is the index
113
+ * sync resumes from, not a history row.
114
+ */
115
+ export type ControlInput = {
116
+ action: "halt" | "resume";
117
+ by: string;
118
+ via: "cli" | "http" | "file";
119
+ atMs: number;
120
+ line: number;
121
+ lineHash: string;
122
+ };
123
+ /**
124
+ * The operator's own WebAuthn assertion for one HTTP approval.
125
+ * `authenticatorData`, `clientDataJSON` and `signature` are base64url.
126
+ * The challenge is not stored: it is rebuilt as the hash of a canonical
127
+ * document that names this defer record. `rpId` is the relying party id
128
+ * checked against authenticatorData, so a later read can rebuild rpIdHash
129
+ * without the body's configuration.
130
+ */
131
+ export type ApprovalSignature = {
132
+ credentialId: string;
133
+ sub: string;
134
+ authenticatorData: string;
135
+ clientDataJSON: string;
136
+ signature: string;
137
+ deferRecordHash: string;
138
+ rpId: string;
139
+ };
106
140
  export type DecisionInputs = {
107
141
  principal: {
108
142
  brain: string;
@@ -116,7 +150,9 @@ export type DecisionInputs = {
116
150
  id: string;
117
151
  via: ApprovalChannel | "proxy";
118
152
  resolves: string;
153
+ signature?: ApprovalSignature;
119
154
  };
155
+ control?: ControlInput;
120
156
  };
121
157
  /** How an operator's approval reached the ledger: a person at `verax approve`, a non-interactive `--from-script` run, or the body's `/api/approve`. */
122
158
  export type ApprovalChannel = "cli" | "cli-script" | "http";
@@ -32,8 +32,29 @@ export type VerifyResult = {
32
32
  effectCompleteness: string;
33
33
  /** What the newest checkpoint covers, and the records after it. */
34
34
  tail: VerifyTail;
35
+ /** Halt windows. A ledger with none says so; that sentence is not a violation. */
36
+ control: VerifyControl;
37
+ /** Inputs rows checked against each record's signed `inputsHash`. */
38
+ inputs: VerifyInputs;
39
+ /** Transparency Service receipts for checkpoints, when the ledger holds any. */
40
+ anchors: VerifyAnchors;
35
41
  problems: string[];
36
42
  };
43
+ export type VerifyAnchors = {
44
+ line: string;
45
+ /** Receipts in `checkpoint-anchors.jsonl`. */
46
+ receipts: number;
47
+ /** Receipts that verified under the reader's key. Zero when no key was given. */
48
+ verified: number;
49
+ checked: boolean;
50
+ };
51
+ export type VerifyInputs = {
52
+ line: string;
53
+ /** Records whose inputs row was found and hashes to their `inputsHash`. */
54
+ matched: number;
55
+ missing: number;
56
+ mismatched: number;
57
+ };
37
58
  export type VerifyIndex = {
38
59
  present: boolean;
39
60
  /** Index refs that are not decisions in the ledger. */
@@ -50,6 +71,12 @@ export type VerifyTail = {
50
71
  ledgerHoldsRecord: boolean | null;
51
72
  } | null;
52
73
  };
74
+ /** Halt windows taken from control records. Warnings do not change `ok`. */
75
+ export type VerifyControl = {
76
+ line: string;
77
+ windows: number;
78
+ warnings: string[];
79
+ };
53
80
  export type VerifyOptions = {
54
81
  /** Verify decision records against this key instead of the one they carry. */
55
82
  publicKeyPem?: string;
@@ -59,5 +86,7 @@ export type VerifyOptions = {
59
86
  witnessPublicKeyPem?: string;
60
87
  /** Verify every checkpoint row against this key instead of one key taken from the file. */
61
88
  checkpointPublicKeyPem?: string;
89
+ /** The Transparency Service key that receipts in `checkpoint-anchors.jsonl` are checked under. */
90
+ anchorPublicKeyPem?: string;
62
91
  };
63
92
  export declare function verifyLedger(dir: string, opts?: VerifyOptions): Promise<VerifyResult>;