@verax-ai/proxy 0.4.7 → 0.5.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/index.d.ts CHANGED
@@ -2,7 +2,8 @@ export { createProxy, LedgerDenyUnrecorded } from "./proxy.ts";
2
2
  export { effectDescriptor, sha256Canonical } from "./hash.ts";
3
3
  export { samePublicKey, thirdPartyReceiptRejection } from "./third-party.ts";
4
4
  export { loadPolicy, TERMINAL_CONTROL_CLASS } from "./policy.ts";
5
- export { FileLedger, MemoryLedger, readLedgerTail } from "./ledger.ts";
5
+ export type { PolicyParseOptions } from "./policy.ts";
6
+ export { FileLedger, MemoryLedger, readLedgerTail, lockHolderAlive, lockState, lockBeatOf } from "./ledger.ts";
6
7
  export { indexCoverage, listPieceFiles } from "./ledger-manifest.ts";
7
8
  export { explain } from "./explain.ts";
8
9
  export { approvePending, approvalsLogFor, createApprovalBudgetGuard, enqueueApprovalCommand, loadApprovalsFromDir, } from "./approvals.ts";
@@ -14,7 +15,7 @@ export { signEffectAttestation } from "./ledger.ts";
14
15
  export { spokenReason } from "./spoken-reason.ts";
15
16
  export type { ApprovalRow, ApproveResult } from "./approvals.ts";
16
17
  export type { CardCsvOpts, ChannelRow, ReconcileReport } from "./reconcile.ts";
17
- export type { FileLedgerOpts, LedgerCounts } from "./ledger.ts";
18
+ export type { FileLedgerOpts, LedgerCounts, LockHolder } from "./ledger.ts";
18
19
  export type { ApprovalSignature, ControlSignature, RevokeInput } from "./types.ts";
19
20
  export type { EffectSigner, ExplainChain, ExplainPair, ExplainFinding, ExplainOpts, ExplainResult, ExplainTrustRoot, ExplainWarning, ExtractWindow, Ledger, LedgerEffect, Policy, PolicyDecision, Principal, ProxyDeps, RecordSigner, ToolCall, ToolResult, WitnessClass, } from "./types.ts";
20
21
  export { verifyLedger } from "./verify-ledger.ts";
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ export { createProxy, LedgerDenyUnrecorded } from "./proxy.js";
2
2
  export { effectDescriptor, sha256Canonical } from "./hash.js";
3
3
  export { samePublicKey, thirdPartyReceiptRejection } from "./third-party.js";
4
4
  export { loadPolicy, TERMINAL_CONTROL_CLASS } from "./policy.js";
5
- export { FileLedger, MemoryLedger, readLedgerTail } from "./ledger.js";
5
+ export { FileLedger, MemoryLedger, readLedgerTail, lockHolderAlive, lockState, lockBeatOf } from "./ledger.js";
6
6
  export { indexCoverage, listPieceFiles } from "./ledger-manifest.js";
7
7
  export { explain } from "./explain.js";
8
8
  export { approvePending, approvalsLogFor, createApprovalBudgetGuard, enqueueApprovalCommand, loadApprovalsFromDir, } from "./approvals.js";
package/dist/ledger.d.ts CHANGED
@@ -78,6 +78,45 @@ export declare class MemoryLedger implements Ledger {
78
78
  lastDecisionHash(): Promise<string | null>;
79
79
  exportExtract(window: ExtractWindow, signer: EffectSigner): Promise<SignedEffectExtract>;
80
80
  }
81
+ /** The kernel's id for this boot on Linux; null elsewhere or when unreadable. */
82
+ export declare function currentBootId(): string | null;
83
+ export type LockHolder = {
84
+ pid: number;
85
+ startedAt: number;
86
+ bootId?: string;
87
+ token?: string;
88
+ beatMs?: number;
89
+ };
90
+ /** How often a held lock is touched. A reader watches for five beats before it calls a lock still. */
91
+ export declare const LOCK_BEAT_MS = 2000;
92
+ /**
93
+ * Watches a lock file for five of its beats and says whether its holder
94
+ * touched it. Only a change is read, never a time, so a clock that stepped
95
+ * and a pid from another container cannot mislead it.
96
+ */
97
+ export declare function watchLock(lockPath: string, beatMs: number, sleep?: (ms: number) => void): "moving" | "still" | "gone";
98
+ /**
99
+ * Whether the lock on disk still has a holder. A lock that records a beat
100
+ * and is seen to move is held, whatever pid it names. Stillness alone proves
101
+ * nothing: a live body can miss its beats while a long synchronous call holds
102
+ * it. So a lock that does not move, like one from a version that did not
103
+ * beat, is then judged by its pid and start time, and is stale only when
104
+ * that says so too. "quiet" is the case in between: a beating lock that did
105
+ * not move while its pid is alive. That is a frozen body, or a dead one whose
106
+ * pid another process now has, and nothing on disk tells the two apart.
107
+ */
108
+ export declare function lockState(lockPath: string, lock: LockHolder): "held" | "quiet" | "stale" | "gone";
109
+ /**
110
+ * Whether the process a lock names can still be the one that wrote it. A
111
+ * live pid is not enough: a container restarted on the same volume runs the
112
+ * body as PID 1 again, and a host that rebooted hands pids out again. So a
113
+ * lock is not held when its pid is dead, when it names this process but was
114
+ * written before this process started, or when it records a boot other than
115
+ * this one. Nothing here takes a lock over; it only says it is stale.
116
+ */
117
+ export declare function lockHolderAlive(lock: LockHolder, bootId?: string | null): boolean;
118
+ /** A beat a lock file may record: a whole number of milliseconds a reader can afford to watch. */
119
+ export declare function lockBeatOf(raw: unknown): number | undefined;
81
120
  export type FileLedgerOpts = {
82
121
  pieceMaxRows?: number;
83
122
  pieceMaxBytes?: number;
@@ -86,6 +125,8 @@ export type FileLedgerOpts = {
86
125
  endMs: number;
87
126
  pieceId: string;
88
127
  }) => Promise<void>;
128
+ /** How often the held lock is touched; tests shorten it. */
129
+ lockBeatMs?: number;
89
130
  };
90
131
  export type LedgerCounts = {
91
132
  decisions: number;
@@ -112,6 +153,8 @@ export declare class FileLedger implements Ledger {
112
153
  private readonly lockPath;
113
154
  private readonly q;
114
155
  private readonly token;
156
+ private readonly lockBeatMs;
157
+ private lockBeat;
115
158
  private closed;
116
159
  private lost;
117
160
  private tailHash;
@@ -168,6 +211,9 @@ export declare class FileLedger implements Ledger {
168
211
  private markLost;
169
212
  private assertOwned;
170
213
  private lockedError;
214
+ /** Touch the held lock so a reader that watches it sees a holder. Never touches a lock that is not ours. */
215
+ private startLockBeat;
216
+ private stopLockBeat;
171
217
  private acquireLock;
172
218
  close(): void;
173
219
  appendDecision(signed: SignedDecisionRecord): Promise<void>;
package/dist/ledger.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { mkdir, open, readFile } from "node:fs/promises";
3
- import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
3
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, unlinkSync, utimesSync, writeFileSync, } from "node:fs";
4
4
  /** I/O seam so append-cost tests can count rereads without mocking node:fs. */
5
5
  export const ledgerFs = {
6
6
  readFile,
@@ -309,15 +309,114 @@ function pidAlive(pid) {
309
309
  return err.code === "EPERM";
310
310
  }
311
311
  }
312
+ /** The kernel's id for this boot on Linux; null elsewhere or when unreadable. */
313
+ export function currentBootId() {
314
+ if (process.platform !== "linux")
315
+ return null;
316
+ try {
317
+ const id = readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
318
+ return id === "" ? null : id;
319
+ }
320
+ catch {
321
+ return null;
322
+ }
323
+ }
324
+ /** How often a held lock is touched. A reader watches for five beats before it calls a lock still. */
325
+ export const LOCK_BEAT_MS = 2000;
326
+ const LOCK_WATCH_BEATS = 5;
327
+ /** Tokens of the locks this process wrote: the only way it knows a lock naming its pid is its own. */
328
+ const ownLockTokens = new Set();
329
+ function sleepSync(ms) {
330
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
331
+ }
332
+ /**
333
+ * Watches a lock file for five of its beats and says whether its holder
334
+ * touched it. Only a change is read, never a time, so a clock that stepped
335
+ * and a pid from another container cannot mislead it.
336
+ */
337
+ export function watchLock(lockPath, beatMs, sleep = sleepSync) {
338
+ const mtime = () => {
339
+ try {
340
+ return statSync(lockPath).mtimeMs;
341
+ }
342
+ catch {
343
+ return null;
344
+ }
345
+ };
346
+ const first = mtime();
347
+ if (first === null)
348
+ return "gone";
349
+ const step = Math.max(10, Math.min(250, Math.floor(beatMs / 2)));
350
+ for (let waited = 0; waited < beatMs * LOCK_WATCH_BEATS; waited += step) {
351
+ sleep(step);
352
+ const now = mtime();
353
+ if (now === null)
354
+ return "gone";
355
+ if (now !== first)
356
+ return "moving";
357
+ }
358
+ return "still";
359
+ }
360
+ /**
361
+ * Whether the lock on disk still has a holder. A lock that records a beat
362
+ * and is seen to move is held, whatever pid it names. Stillness alone proves
363
+ * nothing: a live body can miss its beats while a long synchronous call holds
364
+ * it. So a lock that does not move, like one from a version that did not
365
+ * beat, is then judged by its pid and start time, and is stale only when
366
+ * that says so too. "quiet" is the case in between: a beating lock that did
367
+ * not move while its pid is alive. That is a frozen body, or a dead one whose
368
+ * pid another process now has, and nothing on disk tells the two apart.
369
+ */
370
+ export function lockState(lockPath, lock) {
371
+ if (lock.token !== undefined && ownLockTokens.has(lock.token))
372
+ return "held";
373
+ let still = false;
374
+ if (lock.beatMs !== undefined) {
375
+ const seen = watchLock(lockPath, lock.beatMs);
376
+ if (seen === "moving")
377
+ return "held";
378
+ if (seen === "gone")
379
+ return "gone";
380
+ still = true;
381
+ }
382
+ if (!lockHolderAlive(lock))
383
+ return "stale";
384
+ return still ? "quiet" : "held";
385
+ }
386
+ /**
387
+ * Whether the process a lock names can still be the one that wrote it. A
388
+ * live pid is not enough: a container restarted on the same volume runs the
389
+ * body as PID 1 again, and a host that rebooted hands pids out again. So a
390
+ * lock is not held when its pid is dead, when it names this process but was
391
+ * written before this process started, or when it records a boot other than
392
+ * this one. Nothing here takes a lock over; it only says it is stale.
393
+ */
394
+ export function lockHolderAlive(lock, bootId = currentBootId()) {
395
+ if (!Number.isFinite(lock.startedAt))
396
+ return false;
397
+ if (typeof lock.bootId === "string" && bootId !== null && lock.bootId !== bootId)
398
+ return false;
399
+ // Written before this process started, or stamped with a time that has not come yet.
400
+ if (lock.pid === process.pid && (lock.startedAt < performance.timeOrigin || lock.startedAt > Date.now()))
401
+ return false;
402
+ return pidAlive(lock.pid);
403
+ }
404
+ /** A beat a lock file may record: a whole number of milliseconds a reader can afford to watch. */
405
+ export function lockBeatOf(raw) {
406
+ return typeof raw === "number" && Number.isInteger(raw) && raw >= 20 && raw <= 60_000 ? raw : undefined;
407
+ }
312
408
  function readLock(path) {
313
409
  try {
314
410
  const raw = JSON.parse(readFileSync(path, "utf8"));
315
- if (typeof raw.pid !== "number" || typeof raw.startedAt !== "number")
411
+ if (typeof raw.pid !== "number" || typeof raw.startedAt !== "number" || !Number.isFinite(raw.startedAt))
316
412
  return null;
413
+ const beatMs = lockBeatOf(raw.beatMs);
317
414
  return {
318
415
  pid: raw.pid,
319
416
  startedAt: raw.startedAt,
320
417
  ...(typeof raw.token === "string" ? { token: raw.token } : {}),
418
+ ...(typeof raw.bootId === "string" && raw.bootId !== "" ? { bootId: raw.bootId } : {}),
419
+ ...(beatMs !== undefined ? { beatMs } : {}),
321
420
  };
322
421
  }
323
422
  catch {
@@ -342,6 +441,8 @@ export class FileLedger {
342
441
  lockPath;
343
442
  q = new SerialQueue();
344
443
  token = randomBytes(16).toString("hex");
444
+ lockBeatMs;
445
+ lockBeat;
345
446
  closed = false;
346
447
  lost = false;
347
448
  tailHash = null;
@@ -368,6 +469,7 @@ export class FileLedger {
368
469
  this.pieceMaxRows = opts?.pieceMaxRows ?? DEFAULT_PIECE_MAX_ROWS;
369
470
  this.pieceMaxBytes = opts?.pieceMaxBytes ?? DEFAULT_PIECE_MAX_BYTES;
370
471
  this.onPieceClose = opts?.onPieceClose;
472
+ this.lockBeatMs = lockBeatOf(opts?.lockBeatMs) ?? LOCK_BEAT_MS;
371
473
  this.decisionsPath = join(dir, "decisions.jsonl");
372
474
  this.effectsPath = join(dir, "effects.jsonl");
373
475
  this.inputsPath = join(dir, "inputs.jsonl");
@@ -715,7 +817,8 @@ export class FileLedger {
715
817
  await this.closeActivePiece();
716
818
  }
717
819
  lockBody() {
718
- return `${JSON.stringify({ pid: process.pid, startedAt: Date.now(), token: this.token })}\n`;
820
+ const bootId = currentBootId();
821
+ return `${JSON.stringify({ pid: process.pid, startedAt: Date.now(), token: this.token, ...(bootId ? { bootId } : {}), beatMs: this.lockBeatMs })}\n`;
719
822
  }
720
823
  ownsLock() {
721
824
  const existing = readLock(this.lockPath);
@@ -744,6 +847,8 @@ export class FileLedger {
744
847
  pid: existing.pid,
745
848
  startedAt: existing.startedAt,
746
849
  token: this.token,
850
+ ...(existing.bootId ? { bootId: existing.bootId } : {}),
851
+ ...(existing.beatMs !== undefined ? { beatMs: existing.beatMs } : {}),
747
852
  port,
748
853
  })}\n`;
749
854
  writeFileAtomic(this.lockPath, body);
@@ -760,11 +865,33 @@ export class FileLedger {
760
865
  lockedError() {
761
866
  const existing = readLock(this.lockPath);
762
867
  const pid = existing?.pid ?? "unknown";
763
- if (typeof existing?.pid === "number" && !pidAlive(existing.pid)) {
868
+ if (existing && lockState(this.lockPath, existing) === "stale") {
764
869
  return new Error(`ledger-locked-stale:${pid}\nrun: verax unlock ${this.dir}`);
765
870
  }
766
871
  return new Error(`ledger-locked:${pid}`);
767
872
  }
873
+ /** Touch the held lock so a reader that watches it sees a holder. Never touches a lock that is not ours. */
874
+ startLockBeat() {
875
+ ownLockTokens.add(this.token);
876
+ this.lockBeat = setInterval(() => {
877
+ try {
878
+ if (!this.ownsLock())
879
+ return;
880
+ const now = new Date();
881
+ utimesSync(this.lockPath, now, now);
882
+ }
883
+ catch {
884
+ // A missed beat is read as a still lock; the next one corrects it.
885
+ }
886
+ }, this.lockBeatMs);
887
+ this.lockBeat.unref();
888
+ }
889
+ stopLockBeat() {
890
+ if (this.lockBeat)
891
+ clearInterval(this.lockBeat);
892
+ this.lockBeat = undefined;
893
+ ownLockTokens.delete(this.token);
894
+ }
768
895
  acquireLock() {
769
896
  const body = this.lockBody();
770
897
  try {
@@ -775,11 +902,13 @@ export class FileLedger {
775
902
  throw this.lockedError();
776
903
  throw err;
777
904
  }
905
+ this.startLockBeat();
778
906
  }
779
907
  close() {
780
908
  if (this.closed)
781
909
  return;
782
910
  this.closed = true;
911
+ this.stopLockBeat();
783
912
  if (!this.ownsLock()) {
784
913
  this.lost = true;
785
914
  return;
package/dist/policy.d.ts CHANGED
@@ -37,12 +37,21 @@ export type PolicyDocument = {
37
37
  };
38
38
  /** Named per tool. Do not sniff `host` / `url` on arbitrary arguments. */
39
39
  export declare const HOST_EXTRACTORS: Record<string, (args: Record<string, unknown>) => string | undefined>;
40
+ export type PolicyParseOptions = {
41
+ /**
42
+ * "refuse" (the default) for a policy an operator is loading: a misspelt
43
+ * control would otherwise leave the policy weaker than the file reads.
44
+ * "ignore" only for a snapshot already on disk, written by a release that
45
+ * dropped unknown keys; its hash was taken without them.
46
+ */
47
+ unknownKeys?: "refuse" | "ignore";
48
+ };
40
49
  /**
41
50
  * One class for the spend gate and the approve prompt: every control (Cc,
42
51
  * C0 and C1), every format character (Cf: bidi, ZWJ/ZWNJ, U+FEFF), and the
43
52
  * line and paragraph separators (Zl, Zp).
44
53
  */
45
54
  export declare const TERMINAL_CONTROL_CLASS = "\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}";
46
- export declare function parsePolicyDocument(json: unknown): PolicyDocument;
55
+ export declare function parsePolicyDocument(json: unknown, options?: PolicyParseOptions): PolicyDocument;
47
56
  export declare function ruleTextHash(text: string): string;
48
- export declare function loadPolicy(json: unknown): Policy;
57
+ export declare function loadPolicy(json: unknown, options?: PolicyParseOptions): Policy;
package/dist/policy.js CHANGED
@@ -47,7 +47,19 @@ export const HOST_EXTRACTORS = {
47
47
  "message.send": messageSendHost,
48
48
  };
49
49
  const DEFAULT_APPROVAL_TTL_MS = 86_400_000;
50
- function asRule(raw, index) {
50
+ const DOCUMENT_KEYS = new Set(["version", "default", "rules", "egress", "approvalTtlMs", "limits", "requireInputs"]);
51
+ const RULE_KEYS = new Set(["id", "tool", "requires", "text", "mode", "spend", "egress"]);
52
+ const SPEND_KEYS = new Set(["maxAmountMinor", "currency", "payees", "dailyMaxMinor", "dayOffsetMinutes", "descriptors"]);
53
+ const LIMIT_KEYS = new Set(["ratePerMinute", "dailyMax", "diskFreeBytes"]);
54
+ function rejectUnknownKeys(rec, known, code, options) {
55
+ if (options.unknownKeys === "ignore")
56
+ return;
57
+ for (const key of Object.keys(rec)) {
58
+ if (!known.has(key))
59
+ throw new Error(`${code}:${key}`);
60
+ }
61
+ }
62
+ function asRule(raw, index, options) {
51
63
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
52
64
  throw new Error(`policy-rule-invalid:${index}`);
53
65
  }
@@ -55,6 +67,7 @@ function asRule(raw, index) {
55
67
  if (typeof rec.id !== "string" || rec.id === "") {
56
68
  throw new Error(`policy-rule-id:${index}`);
57
69
  }
70
+ rejectUnknownKeys(rec, RULE_KEYS, `policy-rule-unknown-key:${rec.id}`, options);
58
71
  if (typeof rec.tool !== "string" || rec.tool === "") {
59
72
  throw new Error(`policy-rule-tool:${rec.id}`);
60
73
  }
@@ -83,21 +96,37 @@ function asRule(raw, index) {
83
96
  if (rec.spend === undefined) {
84
97
  throw new Error(`policy-rule-spend-missing:${rec.id}`);
85
98
  }
86
- rule.spend = asSpend(rec.spend, rec.id);
99
+ rule.spend = asSpend(rec.spend, rec.id, options);
100
+ }
101
+ else if (rec.spend !== undefined && options.unknownKeys !== "ignore") {
102
+ // The gate reads a spend block on the spend tool only. On any other rule it
103
+ // would set no cap and stay out of the policy hash, so the file does not load.
104
+ throw new Error(`policy-rule-spend-not-spend-tool:${rec.id}`);
87
105
  }
88
106
  if (rec.egress !== undefined) {
89
107
  if (rec.egress !== true) {
90
108
  throw new Error(`policy-rule-egress:${rec.id}`);
91
109
  }
110
+ // The gate decides `spend` by payee and amount and returns before it looks
111
+ // at a host. A mark there would read as a host check that never runs.
112
+ if (rec.tool === "spend" && options.unknownKeys !== "ignore") {
113
+ throw new Error(`policy-rule-egress-on-spend:${rec.id}`);
114
+ }
92
115
  rule.egress = true;
93
116
  }
117
+ else if (options.unknownKeys !== "ignore" && Object.hasOwn(HOST_EXTRACTORS, rec.tool)) {
118
+ // The gate reads this tool's host, and only under the mark. Without it
119
+ // the call would reach any host, so the rule does not load.
120
+ throw new Error(`policy-rule-egress-unmarked:${rec.id}`);
121
+ }
94
122
  return rule;
95
123
  }
96
- function asSpend(raw, id) {
124
+ function asSpend(raw, id, options) {
97
125
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
98
126
  throw new Error(`policy-rule-spend-missing:${id}`);
99
127
  }
100
128
  const rec = raw;
129
+ rejectUnknownKeys(rec, SPEND_KEYS, `policy-rule-spend-unknown-key:${id}`, options);
101
130
  if (typeof rec.maxAmountMinor !== "number" ||
102
131
  !Number.isInteger(rec.maxAmountMinor) ||
103
132
  rec.maxAmountMinor <= 0) {
@@ -164,12 +193,13 @@ function spendArgsInvalid(args) {
164
193
  return true;
165
194
  return false;
166
195
  }
167
- export function parsePolicyDocument(json) {
196
+ export function parsePolicyDocument(json, options = {}) {
168
197
  const raw = typeof json === "string" ? parseIJson(json) : json;
169
198
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
170
199
  throw new Error("policy-not-object");
171
200
  }
172
201
  const rec = raw;
202
+ rejectUnknownKeys(rec, DOCUMENT_KEYS, "policy-unknown-key", options);
173
203
  if (rec.version !== 1) {
174
204
  throw new Error("policy-version");
175
205
  }
@@ -182,13 +212,21 @@ export function parsePolicyDocument(json) {
182
212
  const document = {
183
213
  version: 1,
184
214
  default: "deny",
185
- rules: rec.rules.map(asRule),
215
+ rules: rec.rules.map((rule, index) => asRule(rule, index, options)),
186
216
  };
187
217
  if (rec.egress !== undefined) {
188
218
  if (!Array.isArray(rec.egress) ||
189
219
  rec.egress.some((h) => typeof h !== "string" || h.trim() === "")) {
190
220
  throw new Error("policy-egress");
191
221
  }
222
+ // Only a marked rule for a tool whose host the gate reads uses the list. A
223
+ // file that names hosts and has no such rule would restrict less than it
224
+ // reads, so it does not load. A mark on a tool with no host reader refuses
225
+ // every call to it and reads no list.
226
+ if (options.unknownKeys !== "ignore" &&
227
+ !document.rules.some((rule) => rule.egress === true && Object.hasOwn(HOST_EXTRACTORS, rule.tool))) {
228
+ throw new Error("policy-egress-unused");
229
+ }
192
230
  document.egress = rec.egress;
193
231
  }
194
232
  if (rec.approvalTtlMs !== undefined) {
@@ -198,7 +236,7 @@ export function parsePolicyDocument(json) {
198
236
  document.approvalTtlMs = rec.approvalTtlMs;
199
237
  }
200
238
  if (rec.limits !== undefined) {
201
- document.limits = asLimits(rec.limits);
239
+ document.limits = asLimits(rec.limits, options);
202
240
  }
203
241
  if (rec.requireInputs !== undefined) {
204
242
  if (rec.requireInputs !== true) {
@@ -224,11 +262,12 @@ function rejectDuplicateRules(rules) {
224
262
  toolOwner.set(rule.tool, rule.id);
225
263
  }
226
264
  }
227
- function asLimits(raw) {
265
+ function asLimits(raw, options) {
228
266
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
229
267
  throw new Error("policy-limits");
230
268
  }
231
269
  const rec = raw;
270
+ rejectUnknownKeys(rec, LIMIT_KEYS, "policy-limits-unknown-key", options);
232
271
  const limits = {};
233
272
  for (const key of ["ratePerMinute", "dailyMax", "diskFreeBytes"]) {
234
273
  if (rec[key] === undefined)
@@ -244,8 +283,8 @@ function asLimits(raw) {
244
283
  export function ruleTextHash(text) {
245
284
  return sha256Canonical(text);
246
285
  }
247
- export function loadPolicy(json) {
248
- const document = parsePolicyDocument(json);
286
+ export function loadPolicy(json, options = {}) {
287
+ const document = parsePolicyDocument(json, options);
249
288
  const hash = sha256Canonical(document);
250
289
  const limits = {
251
290
  diskFreeBytes: document.limits?.diskFreeBytes ?? defaultDiskFreeBytes(),
@@ -253,8 +292,17 @@ export function loadPolicy(json) {
253
292
  ...(document.limits?.dailyMax !== undefined ? { dailyMax: document.limits.dailyMax } : {}),
254
293
  };
255
294
  const spendRule = document.rules.find((rule) => rule.tool === "spend");
295
+ // Only a spend rule carries a parsed spend block, so these are the descriptors the hash covers.
296
+ const descriptorsByPayee = {};
297
+ for (const rule of document.rules) {
298
+ if (rule.tool !== "spend" || !rule.spend?.descriptors)
299
+ continue;
300
+ for (const payee of rule.spend.payees)
301
+ descriptorsByPayee[payee] = rule.spend.descriptors;
302
+ }
256
303
  return {
257
304
  hash,
305
+ descriptorsByPayee,
258
306
  dayOffsetMinutes: spendRule?.spend?.dayOffsetMinutes ?? 0,
259
307
  approvalTtlMs: document.approvalTtlMs ?? DEFAULT_APPROVAL_TTL_MS,
260
308
  limits,
package/dist/types.d.ts CHANGED
@@ -49,6 +49,8 @@ export type Policy = {
49
49
  evaluate(call: ToolCall, principal: Principal, ctx?: PolicyEvalCtx): PolicyDecision;
50
50
  /** Spend-rule day bucket. Absent means UTC, the same as `dayOffsetMinutes: 0`. */
51
51
  dayOffsetMinutes?: number;
52
+ /** Statement descriptors the spend rule names for each payee, as parsed: what the hash covers. */
53
+ descriptorsByPayee?: Readonly<Record<string, readonly string[]>>;
52
54
  rule(id: string | null): {
53
55
  id: string;
54
56
  text: string;
@@ -96,9 +96,27 @@ export type VerifyOptions = {
96
96
  checkpointPublicKeyPem?: string;
97
97
  /** The Transparency Service key that receipts in `checkpoint-anchors.jsonl` are checked under. */
98
98
  anchorPublicKeyPem?: string;
99
+ /**
100
+ * Every verified checkpoint whose window ended more than `anchorGraceMs`
101
+ * before `nowMs` must have a receipt that verifies under
102
+ * `anchorPublicKeyPem`; one without is `checkpoint-not-anchored <hash>`.
103
+ * A receipt deleted from the directory is then named instead of passing.
104
+ */
105
+ requireAnchored?: boolean;
106
+ /** Default `DEFAULT_ANCHOR_GRACE_MS`. */
107
+ anchorGraceMs?: number;
108
+ /** The clock `requireAnchored` reads. Default `Date.now()`. */
109
+ nowMs?: number;
99
110
  /** How close to the newest record an allow with no effect row is deferred rather than named. */
100
111
  boundaryAllowanceMs?: number;
101
112
  };
102
113
  /** The core's default clock-skew allowance, which decision profile 6.1 applies unchanged. */
103
114
  export declare const DEFAULT_BOUNDARY_ALLOWANCE_MS = 300000;
115
+ /**
116
+ * How long after its window ends a checkpoint may be unanchored. The witness
117
+ * signs when the body asks, after the window closes, and registers after it
118
+ * answers; one registration may take up to 15 s and a failure is retried with
119
+ * the next checkpoint. Ten minutes covers that with room.
120
+ */
121
+ export declare const DEFAULT_ANCHOR_GRACE_MS: number;
104
122
  export declare function verifyLedger(dir: string, opts?: VerifyOptions): Promise<VerifyResult>;
@@ -637,7 +637,12 @@ function tailStatement(dir, records, checkpointPublicKeyPem, attested = records)
637
637
  }
638
638
  try {
639
639
  const count = rows[i].claims.receiptCount;
640
- verified.push({ hash: checkpointHash(rows[i]), receiptCount: typeof count === "number" ? count : null });
640
+ const endMs = rows[i].claims.endMs;
641
+ verified.push({
642
+ hash: checkpointHash(rows[i]),
643
+ receiptCount: typeof count === "number" ? count : null,
644
+ endMs: typeof endMs === "number" ? endMs : null,
645
+ });
641
646
  }
642
647
  catch {
643
648
  // A row that verified but cannot be hashed cannot be anchored either.
@@ -694,16 +699,48 @@ function tailStatement(dir, records, checkpointPublicKeyPem, attested = records)
694
699
  verified,
695
700
  };
696
701
  }
702
+ /**
703
+ * How long after its window ends a checkpoint may be unanchored. The witness
704
+ * signs when the body asks, after the window closes, and registers after it
705
+ * answers; one registration may take up to 15 s and a failure is retried with
706
+ * the next checkpoint. Ten minutes covers that with room.
707
+ */
708
+ export const DEFAULT_ANCHOR_GRACE_MS = 10 * 60 * 1000;
697
709
  const ANCHORS_NONE = {
698
710
  line: "anchors: none (no checkpoint is registered with a transparency service)",
699
711
  receipts: 0,
700
712
  verified: 0,
701
713
  checked: false,
702
714
  };
703
- function anchorStatement(dir, checkpoints, keyPem, problems) {
715
+ /** How far past the reader's clock a checkpoint window may end before it is called a future window. */
716
+ const FUTURE_WINDOW_SKEW_MS = 60_000;
717
+ /** Checkpoints past the grace with no receipt that verified are named. */
718
+ function requireAnchoredProblems(checkpoints, anchoredHashes, required) {
719
+ if (!required)
720
+ return [];
721
+ const out = [];
722
+ for (const c of checkpoints) {
723
+ if (anchoredHashes.has(c.hash))
724
+ continue;
725
+ // The grace is counted from the end the checkpoint itself states. A window that has
726
+ // not ended yet would never come due, so it is named instead of being left to age.
727
+ if (c.endMs !== null && c.endMs > required.nowMs + FUTURE_WINDOW_SKEW_MS) {
728
+ out.push(`checkpoint-window-in-future ${c.hash.slice(0, 12)}`);
729
+ continue;
730
+ }
731
+ // A checkpoint with no window end cannot be aged; it is held to the rule.
732
+ if (c.endMs !== null && c.endMs + required.graceMs >= required.nowMs)
733
+ continue;
734
+ out.push(`checkpoint-not-anchored ${c.hash.slice(0, 12)}`);
735
+ }
736
+ return out;
737
+ }
738
+ function anchorStatement(dir, checkpoints, keyPem, problems, required = null) {
704
739
  const read = readAnchors(dir);
705
- if (!read.present)
740
+ if (!read.present) {
741
+ problems.push(...requireAnchoredProblems(checkpoints, new Set(), required));
706
742
  return ANCHORS_NONE;
743
+ }
707
744
  problems.push(...read.problems);
708
745
  const receipts = read.rows.length;
709
746
  const services = [...new Set(read.rows.map((r) => r.service))].join(", ");
@@ -716,6 +753,7 @@ function anchorStatement(dir, checkpoints, keyPem, problems) {
716
753
  };
717
754
  }
718
755
  const byHash = new Map(checkpoints.map((c) => [c.hash, c]));
756
+ const anchoredHashes = new Set();
719
757
  let verified = 0;
720
758
  let newestCount = null;
721
759
  for (const row of read.rows) {
@@ -747,10 +785,12 @@ function anchorStatement(dir, checkpoints, keyPem, problems) {
747
785
  continue;
748
786
  }
749
787
  verified += 1;
788
+ anchoredHashes.add(row.checkpointHash);
750
789
  if (checkpoint.receiptCount !== null && (newestCount === null || checkpoint.receiptCount > newestCount)) {
751
790
  newestCount = checkpoint.receiptCount;
752
791
  }
753
792
  }
793
+ problems.push(...requireAnchoredProblems(checkpoints, anchoredHashes, required));
754
794
  const covers = newestCount === null ? "" : `; the newest anchored checkpoint covers ${newestCount} record(s)`;
755
795
  return {
756
796
  line: verified === receipts
@@ -1236,7 +1276,13 @@ async function verifyLedgerUnchecked(dir, opts = {}) {
1236
1276
  problems.push(...indexed.problems, ...tailed.problems);
1237
1277
  const stated = controlStatement(records);
1238
1278
  problems.push(...stated.violations);
1239
- const anchors = anchorStatement(dir, tailed.verified, opts.anchorPublicKeyPem?.trim() ?? "", problems);
1279
+ const anchorKeyPem = opts.anchorPublicKeyPem?.trim() ?? "";
1280
+ if (opts.requireAnchored && anchorKeyPem === "") {
1281
+ problems.push("require-anchored needs the service key: receipts are checked only under a key the reader supplies");
1282
+ }
1283
+ const anchors = anchorStatement(dir, tailed.verified, anchorKeyPem, problems, opts.requireAnchored
1284
+ ? { graceMs: opts.anchorGraceMs ?? DEFAULT_ANCHOR_GRACE_MS, nowMs: opts.nowMs ?? Date.now() }
1285
+ : null);
1240
1286
  const ok = problems.length === 0 && signaturesInvalid === 0 && chainBreakAt === null && effectsOrphaned === 0;
1241
1287
  return {
1242
1288
  ok,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verax-ai/proxy",
3
- "version": "0.4.7",
3
+ "version": "0.5.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "engines": {