@verax-ai/body 0.8.2 → 0.10.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/README.md +9 -6
- package/dist/anchor-cli.d.ts +48 -3
- package/dist/anchor-cli.js +256 -17
- package/dist/auth.d.ts +14 -1
- package/dist/auth.js +25 -4
- package/dist/canary-cli.d.ts +5 -0
- package/dist/canary-cli.js +213 -0
- package/dist/cli.js +93 -6
- package/dist/config.d.ts +6 -0
- package/dist/config.js +1 -0
- package/dist/demo.js +3 -0
- package/dist/doctor.d.ts +11 -0
- package/dist/doctor.js +88 -2
- package/dist/downstream-pin.js +11 -1
- package/dist/downstream.d.ts +51 -0
- package/dist/downstream.js +329 -4
- package/dist/explain-cli.d.ts +5 -0
- package/dist/explain-cli.js +132 -0
- package/dist/init-local.d.ts +5 -0
- package/dist/init-local.js +1 -0
- package/dist/install.js +1 -1
- package/dist/policy-cli.d.ts +8 -0
- package/dist/policy-cli.js +169 -0
- package/dist/policy-rehearsal.d.ts +39 -0
- package/dist/policy-rehearsal.js +512 -0
- package/dist/report-cli.d.ts +163 -0
- package/dist/report-cli.js +1101 -0
- package/dist/server.js +43 -6
- package/dist/taint-cli.d.ts +5 -0
- package/dist/taint-cli.js +80 -0
- package/dist/verify-cli.d.ts +40 -0
- package/dist/verify-cli.js +131 -58
- package/dist/webauthn-verify.d.ts +3 -1
- package/dist/webauthn-verify.js +97 -4
- package/dist/wiring.d.ts +5 -0
- package/dist/wiring.js +2 -0
- package/dist/witness.d.ts +16 -5
- package/dist/witness.js +67 -8
- package/package.json +9 -9
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
import { lstatSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join, relative } from "node:path";
|
|
3
|
+
import { listPieceFiles, loadPolicy, sha256Canonical, } from "@verax-ai/proxy";
|
|
4
|
+
/**
|
|
5
|
+
* Read a ledger and say what a different policy would have decided.
|
|
6
|
+
* The state directory is only read. No tool is called.
|
|
7
|
+
*/
|
|
8
|
+
export class PolicyRehearsalError extends Error {
|
|
9
|
+
constructor(message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = "PolicyRehearsalError";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export const ARGUMENT_REASON = "the rule reads arguments the record does not keep";
|
|
15
|
+
const TEXT_REASON = "the policy reads argument text the record does not keep";
|
|
16
|
+
const COUNTER_REASON = "the policy's rate or daily limit depends on counters the record does not keep";
|
|
17
|
+
const DISK_REASON = "the policy's disk limit depends on free space the record does not keep";
|
|
18
|
+
const DEPTH_REASON = "the policy's data-class depth check depends on arguments the record does not keep";
|
|
19
|
+
const TIME_REASON = "the record's timestamp is outside -8.64e15..8.64e15";
|
|
20
|
+
const SNAPSHOT_REASON = "the recorded policy snapshot is missing or unreadable, so the disk limit cannot be compared";
|
|
21
|
+
const TENANT_GATE_REASON = "the tenant gate can still refuse memory.get or audit.explain with tenant-mismatch, and it reads arguments the record does not keep";
|
|
22
|
+
/** `Date` throws outside this. A record past it is not rehearsable. */
|
|
23
|
+
const TIME_LIMIT_MS = 8.64e15;
|
|
24
|
+
const RULES_WITHOUT_AN_ID = new Set(["no-rule", "spend-not-wired", "inputs-required"]);
|
|
25
|
+
const POLICY_REASONS = new Set([
|
|
26
|
+
"allow",
|
|
27
|
+
"no-rule",
|
|
28
|
+
"scope-missing",
|
|
29
|
+
"approval-required",
|
|
30
|
+
"inputs-required",
|
|
31
|
+
"spend-not-wired",
|
|
32
|
+
"spend-args-invalid",
|
|
33
|
+
"spend-currency",
|
|
34
|
+
"spend-cap",
|
|
35
|
+
"spend-payee",
|
|
36
|
+
"spend-daily",
|
|
37
|
+
"egress-host-missing",
|
|
38
|
+
"egress-blocked",
|
|
39
|
+
]);
|
|
40
|
+
const PROBES = [
|
|
41
|
+
{},
|
|
42
|
+
{ amountMinor: 1, currency: "USD", payee: "payee", reference: "ref" },
|
|
43
|
+
{ to: "user@example.com" },
|
|
44
|
+
];
|
|
45
|
+
const HASH_RE = /^[0-9a-f]{64}$/;
|
|
46
|
+
function word(decision) {
|
|
47
|
+
return decision === "defer" ? "held" : decision;
|
|
48
|
+
}
|
|
49
|
+
function outsidePolicy(reason) {
|
|
50
|
+
if (reason === "halted")
|
|
51
|
+
return "a halt is not a policy decision";
|
|
52
|
+
if (reason === "ledger-disk-low")
|
|
53
|
+
return "a disk refusal depends on free space the record does not keep";
|
|
54
|
+
if (reason === "rate-limited" || reason === "daily-limited") {
|
|
55
|
+
return "a rate or daily refusal depends on counters the record does not keep";
|
|
56
|
+
}
|
|
57
|
+
if (reason === "tenant-mismatch")
|
|
58
|
+
return "a tenant refusal depends on stored rows the record does not keep";
|
|
59
|
+
if (reason === "approved-by-operator")
|
|
60
|
+
return "an operator approval is not a policy decision";
|
|
61
|
+
if (reason === "input-invalid") {
|
|
62
|
+
return "the call's declared inputs were refused, and the record does not keep the declaration";
|
|
63
|
+
}
|
|
64
|
+
if (reason === "outcome-unknown")
|
|
65
|
+
return "an outcome-unknown decision depends on a run mark the record does not keep";
|
|
66
|
+
if (reason === "ref-reuse" || reason === "ref-invalid") {
|
|
67
|
+
return "the decision depends on the ref, which a policy rehearsal does not re-check";
|
|
68
|
+
}
|
|
69
|
+
if (reason === "expired")
|
|
70
|
+
return "an expiry is the approval clock, not a policy re-evaluation of the call";
|
|
71
|
+
if (reason === "spend-reauth-required") {
|
|
72
|
+
return "a spend re-authorisation depends on an earlier allow, not a new policy verdict";
|
|
73
|
+
}
|
|
74
|
+
if (reason === "operator-halt" || reason === "operator-resume" || reason === "halt-history-mismatch") {
|
|
75
|
+
return "the record is a control event, not a tool call";
|
|
76
|
+
}
|
|
77
|
+
if (reason === "token-revoked" || reason === "revoke-removed") {
|
|
78
|
+
return "the record is a token revocation, not a tool call";
|
|
79
|
+
}
|
|
80
|
+
if (reason === "passkey-removed" || reason === "passkey-removal-undone") {
|
|
81
|
+
return "the record is an operator-removal event, not a tool call";
|
|
82
|
+
}
|
|
83
|
+
if (reason.startsWith("data-class-") || reason.startsWith("file-type-")) {
|
|
84
|
+
return "the record keeps class counts, not the argument text";
|
|
85
|
+
}
|
|
86
|
+
if (reason.startsWith("result-class")) {
|
|
87
|
+
return "the record is about a tool result, and it keeps counts and a hash, not the result text";
|
|
88
|
+
}
|
|
89
|
+
return "the record's reason is not a policy decision, and a rehearsal does not guess what produced it";
|
|
90
|
+
}
|
|
91
|
+
function argumentTextMatters(policy, tool) {
|
|
92
|
+
const cfg = policy.dataClasses;
|
|
93
|
+
if (!cfg)
|
|
94
|
+
return false;
|
|
95
|
+
const choices = { ...cfg.document, ...(cfg.byTool[tool] ?? {}) };
|
|
96
|
+
for (const choice of Object.values(choices)) {
|
|
97
|
+
if (choice === "mask" || choice === "block" || choice === "local")
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
return cfg.blockedFileTypes.length > 0;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* evaluate() reads arguments only for spend and for an egress host. Two probes
|
|
104
|
+
* that would take those branches differently mean the verdict depends on
|
|
105
|
+
* argument values. Those values are not on the record, so the verdict is not
|
|
106
|
+
* used. When every probe agrees, the verdict does not depend on them.
|
|
107
|
+
*/
|
|
108
|
+
function probed(policy, tool, principal) {
|
|
109
|
+
let first;
|
|
110
|
+
for (const args of PROBES) {
|
|
111
|
+
const verdict = policy.evaluate({ name: tool, arguments: args }, principal);
|
|
112
|
+
if (!first) {
|
|
113
|
+
first = verdict;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (verdict.decision !== first.decision || verdict.reasonCode !== first.reasonCode || verdict.rule !== first.rule) {
|
|
117
|
+
return "arguments";
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (!first || !wordOrNull(first.decision))
|
|
121
|
+
return "arguments";
|
|
122
|
+
return { decision: first.decision, reasonCode: first.reasonCode, rule: first.rule };
|
|
123
|
+
}
|
|
124
|
+
function wordOrNull(decision) {
|
|
125
|
+
return decision === "allow" || decision === "deny" || decision === "defer";
|
|
126
|
+
}
|
|
127
|
+
function verdictOf(loaded, tool, principal, declared) {
|
|
128
|
+
if (loaded.policy.requireInputs === true && declared.length === 0) {
|
|
129
|
+
return { ok: true, verdict: { decision: "deny", reasonCode: "inputs-required", rule: null } };
|
|
130
|
+
}
|
|
131
|
+
const found = probed(loaded.policy, tool, principal);
|
|
132
|
+
if (found === "arguments")
|
|
133
|
+
return { ok: false, reason: ARGUMENT_REASON };
|
|
134
|
+
if (found.decision === "allow" || found.decision === "defer") {
|
|
135
|
+
if (loaded.policy.limits.ratePerMinute !== undefined || loaded.policy.limits.dailyMax !== undefined) {
|
|
136
|
+
return { ok: false, reason: COUNTER_REASON };
|
|
137
|
+
}
|
|
138
|
+
if (argumentTextMatters(loaded.policy, tool))
|
|
139
|
+
return { ok: false, reason: TEXT_REASON };
|
|
140
|
+
}
|
|
141
|
+
return { ok: true, verdict: found };
|
|
142
|
+
}
|
|
143
|
+
function oldRuleOf(snapshot, tool, reasonCode) {
|
|
144
|
+
if (RULES_WITHOUT_AN_ID.has(reasonCode))
|
|
145
|
+
return null;
|
|
146
|
+
const raw = snapshot.raw;
|
|
147
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw))
|
|
148
|
+
return null;
|
|
149
|
+
const rules = raw.rules;
|
|
150
|
+
if (!Array.isArray(rules))
|
|
151
|
+
return null;
|
|
152
|
+
let found = null;
|
|
153
|
+
for (const rule of rules) {
|
|
154
|
+
if (rule === null || typeof rule !== "object" || Array.isArray(rule))
|
|
155
|
+
continue;
|
|
156
|
+
const rec = rule;
|
|
157
|
+
if (rec.tool !== tool)
|
|
158
|
+
continue;
|
|
159
|
+
if (typeof rec.id !== "string" || rec.id === "")
|
|
160
|
+
return null;
|
|
161
|
+
if (found !== null)
|
|
162
|
+
return null;
|
|
163
|
+
found = rec.id;
|
|
164
|
+
}
|
|
165
|
+
return found;
|
|
166
|
+
}
|
|
167
|
+
function brainOf(inputs) {
|
|
168
|
+
if (!inputs)
|
|
169
|
+
return undefined;
|
|
170
|
+
const principal = inputs.principal;
|
|
171
|
+
if (principal === null || typeof principal !== "object" || Array.isArray(principal))
|
|
172
|
+
return undefined;
|
|
173
|
+
const brain = principal.brain;
|
|
174
|
+
return typeof brain === "string" ? brain : undefined;
|
|
175
|
+
}
|
|
176
|
+
function markerReason(inputs) {
|
|
177
|
+
if (inputs.control !== undefined)
|
|
178
|
+
return "the record is a control event, not a tool call";
|
|
179
|
+
if (inputs.revoke !== undefined)
|
|
180
|
+
return "the record is a token revocation, not a tool call";
|
|
181
|
+
if (inputs.operatorRemoval !== undefined)
|
|
182
|
+
return "the record is an operator-removal event, not a tool call";
|
|
183
|
+
if (inputs.resultOf !== undefined) {
|
|
184
|
+
return "the record is about a tool result, and it keeps counts and a hash, not the result text";
|
|
185
|
+
}
|
|
186
|
+
if (inputs.approver !== undefined)
|
|
187
|
+
return "an operator approval is not a policy decision";
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
function principalOf(inputs) {
|
|
191
|
+
const principal = inputs.principal;
|
|
192
|
+
if (principal === null || typeof principal !== "object" || Array.isArray(principal)) {
|
|
193
|
+
return "the inputs row does not keep a principal";
|
|
194
|
+
}
|
|
195
|
+
const rec = principal;
|
|
196
|
+
if (typeof rec.brain !== "string")
|
|
197
|
+
return "the inputs row does not keep a brain";
|
|
198
|
+
if (!Array.isArray(rec.scopes) || rec.scopes.some((scope) => typeof scope !== "string")) {
|
|
199
|
+
return "the inputs row does not keep scopes";
|
|
200
|
+
}
|
|
201
|
+
return {
|
|
202
|
+
brain: rec.brain,
|
|
203
|
+
scopes: new Set(rec.scopes),
|
|
204
|
+
...(typeof rec.iss === "string" ? { iss: rec.iss } : {}),
|
|
205
|
+
...(typeof rec.tenant === "string" ? { tenant: rec.tenant } : {}),
|
|
206
|
+
...(typeof rec.org === "string" ? { org: rec.org } : {}),
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
function labelOf(stateDir, path) {
|
|
210
|
+
return relative(stateDir, path).replaceAll("\\", "/");
|
|
211
|
+
}
|
|
212
|
+
function readFile(path, label) {
|
|
213
|
+
let st;
|
|
214
|
+
try {
|
|
215
|
+
st = lstatSync(path);
|
|
216
|
+
}
|
|
217
|
+
catch (err) {
|
|
218
|
+
if (err.code === "ENOENT")
|
|
219
|
+
return null;
|
|
220
|
+
throw new PolicyRehearsalError(`cannot read ${label}`);
|
|
221
|
+
}
|
|
222
|
+
if (st.isSymbolicLink())
|
|
223
|
+
throw new PolicyRehearsalError(`symbolic link: ${label}`);
|
|
224
|
+
if (!st.isFile())
|
|
225
|
+
throw new PolicyRehearsalError(`not a file: ${label}`);
|
|
226
|
+
try {
|
|
227
|
+
return readFileSync(path, "utf8");
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
throw new PolicyRehearsalError(`cannot read ${label}`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
function parseJsonl(text, label) {
|
|
234
|
+
const rows = [];
|
|
235
|
+
const lines = text.split("\n");
|
|
236
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
237
|
+
const line = lines[i].trim();
|
|
238
|
+
if (line === "")
|
|
239
|
+
continue;
|
|
240
|
+
try {
|
|
241
|
+
rows.push(JSON.parse(line));
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
throw new PolicyRehearsalError(`${label}:${i + 1}: not JSON`);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return rows;
|
|
248
|
+
}
|
|
249
|
+
function ledgerFiles(stateDir) {
|
|
250
|
+
const manifestPath = join(stateDir, "ledger-manifest.json");
|
|
251
|
+
const manifestText = readFile(manifestPath, "ledger-manifest.json");
|
|
252
|
+
if (manifestText === null) {
|
|
253
|
+
return {
|
|
254
|
+
decisions: [{ label: "decisions.jsonl", path: join(stateDir, "decisions.jsonl") }],
|
|
255
|
+
inputs: [{ label: "inputs.jsonl", path: join(stateDir, "inputs.jsonl") }],
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
let pieces;
|
|
259
|
+
try {
|
|
260
|
+
pieces = listPieceFiles(stateDir);
|
|
261
|
+
}
|
|
262
|
+
catch (err) {
|
|
263
|
+
throw new PolicyRehearsalError(err instanceof Error ? err.message : "ledger manifest cannot be read");
|
|
264
|
+
}
|
|
265
|
+
return {
|
|
266
|
+
decisions: pieces.map((piece) => ({ label: labelOf(stateDir, piece.decisions), path: piece.decisions })),
|
|
267
|
+
inputs: pieces.map((piece) => ({ label: labelOf(stateDir, piece.inputs), path: piece.inputs })),
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
function readLedger(stateDir) {
|
|
271
|
+
let st;
|
|
272
|
+
try {
|
|
273
|
+
st = lstatSync(stateDir);
|
|
274
|
+
}
|
|
275
|
+
catch {
|
|
276
|
+
throw new PolicyRehearsalError("cannot read state directory");
|
|
277
|
+
}
|
|
278
|
+
if (st.isSymbolicLink())
|
|
279
|
+
throw new PolicyRehearsalError("symbolic link: state directory");
|
|
280
|
+
if (!st.isDirectory())
|
|
281
|
+
throw new PolicyRehearsalError("not a directory");
|
|
282
|
+
const files = ledgerFiles(stateDir);
|
|
283
|
+
const decisions = [];
|
|
284
|
+
let sawDecisionFile = false;
|
|
285
|
+
for (const file of files.decisions) {
|
|
286
|
+
const text = readFile(file.path, file.label);
|
|
287
|
+
if (text === null) {
|
|
288
|
+
if (file.label === "decisions.jsonl")
|
|
289
|
+
throw new PolicyRehearsalError("no decisions file");
|
|
290
|
+
throw new PolicyRehearsalError(`missing piece: ${file.label}`);
|
|
291
|
+
}
|
|
292
|
+
sawDecisionFile = true;
|
|
293
|
+
const rows = parseJsonl(text, file.label);
|
|
294
|
+
for (let i = 0; i < rows.length; i += 1) {
|
|
295
|
+
const row = rows[i];
|
|
296
|
+
if (row === null || typeof row !== "object" || Array.isArray(row)) {
|
|
297
|
+
throw new PolicyRehearsalError(`${file.label}:${i + 1}: not a decision`);
|
|
298
|
+
}
|
|
299
|
+
const claims = row.claims;
|
|
300
|
+
if (claims === null || typeof claims !== "object" || Array.isArray(claims)) {
|
|
301
|
+
throw new PolicyRehearsalError(`${file.label}:${i + 1}: not a decision`);
|
|
302
|
+
}
|
|
303
|
+
decisions.push({ label: file.label, line: i + 1, claims: claims });
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
if (!sawDecisionFile)
|
|
307
|
+
throw new PolicyRehearsalError("no decisions file");
|
|
308
|
+
const inputs = new Map();
|
|
309
|
+
for (const file of files.inputs) {
|
|
310
|
+
const text = readFile(file.path, file.label);
|
|
311
|
+
if (text === null)
|
|
312
|
+
continue;
|
|
313
|
+
for (const row of parseJsonl(text, file.label)) {
|
|
314
|
+
if (row === null || typeof row !== "object" || Array.isArray(row)) {
|
|
315
|
+
throw new PolicyRehearsalError(`${file.label}: not an inputs row`);
|
|
316
|
+
}
|
|
317
|
+
const rec = row;
|
|
318
|
+
if (typeof rec.ref !== "string" || rec.inputs === null || typeof rec.inputs !== "object" || Array.isArray(rec.inputs)) {
|
|
319
|
+
throw new PolicyRehearsalError(`${file.label}: not an inputs row`);
|
|
320
|
+
}
|
|
321
|
+
const body = rec.inputs;
|
|
322
|
+
inputs.set(`${rec.ref}\0${sha256Canonical(body)}`, body);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return { decisions, inputs };
|
|
326
|
+
}
|
|
327
|
+
function loadSnapshot(stateDir, hash) {
|
|
328
|
+
if (typeof hash !== "string" || !HASH_RE.test(hash))
|
|
329
|
+
return null;
|
|
330
|
+
const path = join(stateDir, "policies", `${hash}.json`);
|
|
331
|
+
const text = readFile(path, `policies/${hash}.json`);
|
|
332
|
+
if (text === null)
|
|
333
|
+
return null;
|
|
334
|
+
let raw;
|
|
335
|
+
try {
|
|
336
|
+
raw = JSON.parse(text);
|
|
337
|
+
}
|
|
338
|
+
catch {
|
|
339
|
+
return null;
|
|
340
|
+
}
|
|
341
|
+
try {
|
|
342
|
+
const policy = loadPolicy(raw, { unknownKeys: "ignore" });
|
|
343
|
+
if (policy.hash !== hash)
|
|
344
|
+
return null;
|
|
345
|
+
return { policy, raw };
|
|
346
|
+
}
|
|
347
|
+
catch {
|
|
348
|
+
return null;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
function timeOf(ts) {
|
|
352
|
+
if (ts === null || Math.abs(ts) > TIME_LIMIT_MS)
|
|
353
|
+
return null;
|
|
354
|
+
return new Date(ts).toISOString();
|
|
355
|
+
}
|
|
356
|
+
function sortedCounts(counts) {
|
|
357
|
+
const out = {};
|
|
358
|
+
for (const key of [...counts.keys()].sort())
|
|
359
|
+
out[key] = counts.get(key);
|
|
360
|
+
return out;
|
|
361
|
+
}
|
|
362
|
+
export function rehearsePolicy(stateDir, policy, opts = {}) {
|
|
363
|
+
const ledger = readLedger(stateDir);
|
|
364
|
+
const next = { policy, raw: null };
|
|
365
|
+
const snapshots = new Map();
|
|
366
|
+
const changed = [];
|
|
367
|
+
const skipped = [];
|
|
368
|
+
const pairs = new Map();
|
|
369
|
+
let unchanged = 0;
|
|
370
|
+
const snapshotFor = (hash) => {
|
|
371
|
+
const key = typeof hash === "string" ? hash : "";
|
|
372
|
+
if (snapshots.has(key))
|
|
373
|
+
return snapshots.get(key) ?? null;
|
|
374
|
+
const loaded = loadSnapshot(stateDir, hash);
|
|
375
|
+
snapshots.set(key, loaded);
|
|
376
|
+
return loaded;
|
|
377
|
+
};
|
|
378
|
+
for (const row of ledger.decisions) {
|
|
379
|
+
const claims = row.claims;
|
|
380
|
+
const ts = typeof claims.timestampMs === "number" && Number.isFinite(claims.timestampMs) ? claims.timestampMs : null;
|
|
381
|
+
if (opts.notBeforeMs !== undefined && (ts === null || ts < opts.notBeforeMs))
|
|
382
|
+
continue;
|
|
383
|
+
const id = typeof claims.ref === "string" && claims.ref !== "" ? claims.ref : `${row.label}:${row.line}`;
|
|
384
|
+
const inputsHash = typeof claims.inputsHash === "string" ? claims.inputsHash : null;
|
|
385
|
+
const inputs = typeof claims.ref === "string" && inputsHash ? ledger.inputs.get(`${claims.ref}\0${inputsHash}`) : undefined;
|
|
386
|
+
if (opts.brain !== undefined && brainOf(inputs) !== opts.brain)
|
|
387
|
+
continue;
|
|
388
|
+
const skip = (reason) => {
|
|
389
|
+
skipped.push({
|
|
390
|
+
id,
|
|
391
|
+
time: timeOf(ts),
|
|
392
|
+
brain: brainOf(inputs) ?? null,
|
|
393
|
+
tool: typeof claims.subject === "string" ? claims.subject : null,
|
|
394
|
+
reason,
|
|
395
|
+
});
|
|
396
|
+
};
|
|
397
|
+
if (ts === null) {
|
|
398
|
+
skip("the record has no timestamp");
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
if (Math.abs(ts) > TIME_LIMIT_MS) {
|
|
402
|
+
skip(TIME_REASON);
|
|
403
|
+
continue;
|
|
404
|
+
}
|
|
405
|
+
if (typeof claims.ref !== "string" || claims.ref === "") {
|
|
406
|
+
skip("the record has no ref");
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
if (inputsHash === null) {
|
|
410
|
+
skip("the record has no inputsHash");
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
if (!inputs) {
|
|
414
|
+
skip("no inputs row matches the record");
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
const marked = markerReason(inputs);
|
|
418
|
+
if (marked) {
|
|
419
|
+
skip(marked);
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
const recordedDecision = typeof claims.decision === "string" ? claims.decision : "";
|
|
423
|
+
const recordedReason = typeof claims.reasonCode === "string" ? claims.reasonCode : "";
|
|
424
|
+
if (!wordOrNull(recordedDecision)) {
|
|
425
|
+
skip("the record's decision is not allow, deny or held");
|
|
426
|
+
continue;
|
|
427
|
+
}
|
|
428
|
+
if (!POLICY_REASONS.has(recordedReason)) {
|
|
429
|
+
skip(outsidePolicy(recordedReason));
|
|
430
|
+
continue;
|
|
431
|
+
}
|
|
432
|
+
if (typeof claims.subject !== "string" || claims.subject === "") {
|
|
433
|
+
skip("the record does not keep a tool name");
|
|
434
|
+
continue;
|
|
435
|
+
}
|
|
436
|
+
const principal = principalOf(inputs);
|
|
437
|
+
if (typeof principal === "string") {
|
|
438
|
+
skip(principal);
|
|
439
|
+
continue;
|
|
440
|
+
}
|
|
441
|
+
if (!Array.isArray(inputs.inputs)) {
|
|
442
|
+
skip("the inputs row does not keep the declared inputs");
|
|
443
|
+
continue;
|
|
444
|
+
}
|
|
445
|
+
// The policy that wrote the record is the one under rehearsal. The
|
|
446
|
+
// decision stands: re-evaluating it would call a rate limit, a missing
|
|
447
|
+
// argument or a depth check "not rehearsable".
|
|
448
|
+
if (typeof claims.policyHash === "string" && claims.policyHash === policy.hash) {
|
|
449
|
+
unchanged += 1;
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
const rehearsed = verdictOf(next, claims.subject, principal, inputs.inputs);
|
|
453
|
+
if (!rehearsed.ok) {
|
|
454
|
+
skip(rehearsed.reason);
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
const prior = snapshotFor(claims.policyHash);
|
|
458
|
+
// The proxy checks free space, then argument depth, before any rule
|
|
459
|
+
// (proxy.ts, the disk check and the depth check). Neither value is on
|
|
460
|
+
// the record. When the check would refuse or cannot be reproduced, the
|
|
461
|
+
// rehearsal does not name a rule. A missing snapshot still lets a deny
|
|
462
|
+
// through: the old limit cannot be compared, and that gap is separate.
|
|
463
|
+
if (prior !== null && next.policy.limits.diskFreeBytes > prior.policy.limits.diskFreeBytes) {
|
|
464
|
+
skip(DISK_REASON);
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
if (next.policy.dataClasses !== undefined) {
|
|
468
|
+
skip(DEPTH_REASON);
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
const open = rehearsed.verdict.decision === "allow" || rehearsed.verdict.decision === "defer";
|
|
472
|
+
if (open &&
|
|
473
|
+
recordedDecision === "deny" &&
|
|
474
|
+
(claims.subject === "memory.get" || claims.subject === "audit.explain")) {
|
|
475
|
+
skip(TENANT_GATE_REASON);
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
if (open && prior === null) {
|
|
479
|
+
skip(SNAPSHOT_REASON);
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
const oldRule = prior ? oldRuleOf(prior, claims.subject, recordedReason) : null;
|
|
483
|
+
const from = word(recordedDecision);
|
|
484
|
+
const to = word(rehearsed.verdict.decision);
|
|
485
|
+
if (from === to) {
|
|
486
|
+
unchanged += 1;
|
|
487
|
+
continue;
|
|
488
|
+
}
|
|
489
|
+
const pair = `${from} -> ${to}`;
|
|
490
|
+
pairs.set(pair, (pairs.get(pair) ?? 0) + 1);
|
|
491
|
+
changed.push({
|
|
492
|
+
id,
|
|
493
|
+
time: timeOf(ts),
|
|
494
|
+
brain: principal.brain,
|
|
495
|
+
tool: claims.subject,
|
|
496
|
+
from,
|
|
497
|
+
rule: oldRule,
|
|
498
|
+
to,
|
|
499
|
+
newRule: rehearsed.verdict.rule,
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
const reasons = new Map();
|
|
503
|
+
for (const row of skipped)
|
|
504
|
+
reasons.set(row.reason, (reasons.get(row.reason) ?? 0) + 1);
|
|
505
|
+
return {
|
|
506
|
+
unchanged,
|
|
507
|
+
changes: sortedCounts(pairs),
|
|
508
|
+
notRehearsable: sortedCounts(reasons),
|
|
509
|
+
changed,
|
|
510
|
+
skipped,
|
|
511
|
+
};
|
|
512
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { type SignedCheckpoint } from "@cedulon/checkpoint";
|
|
2
|
+
import { type SignedDecisionRecord } from "@cedulon/core";
|
|
3
|
+
export declare const EX_USAGE = 64;
|
|
4
|
+
/** Same code `verax verify` uses for an unreadable state directory. */
|
|
5
|
+
export declare const EX_STATE_UNREADABLE = 77;
|
|
6
|
+
type DecisionCounts = {
|
|
7
|
+
allow: number;
|
|
8
|
+
deny: number;
|
|
9
|
+
defer: number;
|
|
10
|
+
};
|
|
11
|
+
export type ApprovalCounts = {
|
|
12
|
+
approved: number;
|
|
13
|
+
withOperatorSignatureFieldPresent: number;
|
|
14
|
+
withoutOperatorSignatureField: number;
|
|
15
|
+
closedWithoutAllow: number;
|
|
16
|
+
/**
|
|
17
|
+
* Defers with no hash-bound answer. Established as a fact only when no held
|
|
18
|
+
* defer could be answered by an unbound record after it; otherwise null
|
|
19
|
+
* (see heldWithoutBoundAnswer / heldPossiblyAnsweredByUnbound).
|
|
20
|
+
*/
|
|
21
|
+
stillHeld: number | null;
|
|
22
|
+
unmatched: number;
|
|
23
|
+
/** Allow/deny records in the window whose inputs are not hash-bound. */
|
|
24
|
+
terminalsWithoutBoundInputs: number;
|
|
25
|
+
/** Defers with no hash-bound answer (raw open count; always computed). */
|
|
26
|
+
heldWithoutBoundAnswer: number;
|
|
27
|
+
/**
|
|
28
|
+
* Of those held without a bound answer, how many an unbound terminal's
|
|
29
|
+
* inputs row names with matching request hash and tool.
|
|
30
|
+
*/
|
|
31
|
+
heldPossiblyAnsweredByUnbound: number;
|
|
32
|
+
};
|
|
33
|
+
export type PeriodReport = {
|
|
34
|
+
from: string;
|
|
35
|
+
to: string;
|
|
36
|
+
/** Head of the whole verified ledger. Null when the ledger does not verify. */
|
|
37
|
+
headHash: string | null;
|
|
38
|
+
/** Records in the window. Null when the ledger does not verify. */
|
|
39
|
+
recordCount: number | null;
|
|
40
|
+
firstRecordMs: number | null;
|
|
41
|
+
lastRecordMs: number | null;
|
|
42
|
+
verification: {
|
|
43
|
+
ok: boolean;
|
|
44
|
+
verdict: string;
|
|
45
|
+
problems: string[];
|
|
46
|
+
};
|
|
47
|
+
/** Why every count is null, or null when counts are available. */
|
|
48
|
+
countsUnavailableReason: string | null;
|
|
49
|
+
/** Set when approvals.jsonl is malformed. Never affects verdict or counts. */
|
|
50
|
+
unsignedApprovalsNote: string | null;
|
|
51
|
+
decisions: {
|
|
52
|
+
total: DecisionCounts | null;
|
|
53
|
+
byTool: {
|
|
54
|
+
[tool: string]: DecisionCounts;
|
|
55
|
+
} | null;
|
|
56
|
+
/**
|
|
57
|
+
* Records whose subject is empty or not a string. Null when counts are
|
|
58
|
+
* unavailable. Identity: for each kind, sum(byTool[*][kind]) +
|
|
59
|
+
* withoutSubject[kind] === total[kind].
|
|
60
|
+
*/
|
|
61
|
+
withoutSubject: DecisionCounts | null;
|
|
62
|
+
};
|
|
63
|
+
approvals: {
|
|
64
|
+
approved: number | null;
|
|
65
|
+
/** Approving records whose hash-bound inputs carry an approver signature field. Not a verification. */
|
|
66
|
+
withOperatorSignatureFieldPresent: number | null;
|
|
67
|
+
withoutOperatorSignatureField: number | null;
|
|
68
|
+
closedWithoutAllow: number | null;
|
|
69
|
+
stillHeld: number | null;
|
|
70
|
+
unmatched: number | null;
|
|
71
|
+
/** Allow/deny in the window with no hash-bound inputs. Null when counts unavailable. */
|
|
72
|
+
terminalsWithoutBoundInputs: number | null;
|
|
73
|
+
/** Defers with no hash-bound answer. Null when counts unavailable. */
|
|
74
|
+
heldWithoutBoundAnswer: number | null;
|
|
75
|
+
/** Held defers an unbound terminal's inputs row could answer. Null when counts unavailable. */
|
|
76
|
+
heldPossiblyAnsweredByUnbound: number | null;
|
|
77
|
+
/** Class only, when approvals could not be counted although the ledger verified. */
|
|
78
|
+
unavailableReason: string | null;
|
|
79
|
+
};
|
|
80
|
+
checkpoints: {
|
|
81
|
+
count: number | null;
|
|
82
|
+
/** Anchor receipts for window checkpoints that verified. Zero when anchors were not checked. */
|
|
83
|
+
withAnchorVerified: number | null;
|
|
84
|
+
/** Anchor rows for window checkpoints present but not checked (no anchor key). */
|
|
85
|
+
anchorRowsPresentNotChecked: number | null;
|
|
86
|
+
/** Class only, when anchors could not be read although the ledger verified. */
|
|
87
|
+
anchorUnavailableReason: string | null;
|
|
88
|
+
};
|
|
89
|
+
whatThisReportDoesNotShow: string;
|
|
90
|
+
};
|
|
91
|
+
/** UTC midnight for a calendar date, or null when the string is not YYYY-MM-DD. */
|
|
92
|
+
export declare function parseReportDate(raw: string): number | null;
|
|
93
|
+
/**
|
|
94
|
+
* Usable per-tool subject, or null when empty or not a string. Null subjects
|
|
95
|
+
* are counted in `withoutSubject`, not under a synthetic byTool key, so a
|
|
96
|
+
* real tool named U+001F cannot collide with the empty/missing bucket.
|
|
97
|
+
*/
|
|
98
|
+
export declare function subjectToolKey(subject: unknown): string | null;
|
|
99
|
+
/**
|
|
100
|
+
* Stable class for a verify problem line: the longest known class prefix
|
|
101
|
+
* followed by a space, a colon, or the end. Ledger detail after that prefix
|
|
102
|
+
* is dropped. Anything that is not a known class is `unclassified`.
|
|
103
|
+
*/
|
|
104
|
+
export declare function problemClass(problem: string): string;
|
|
105
|
+
/** Decision records in chain order, using the same piece listing verify's helpers use. */
|
|
106
|
+
export declare function readDecisionRecords(dir: string): SignedDecisionRecord[];
|
|
107
|
+
/**
|
|
108
|
+
* Cedulon/verify coverage is half-open `[startMs, endMs)` (see verify-ledger:
|
|
109
|
+
* `r.claims.timestampMs >= startMs && r.claims.timestampMs < endMs`). Overlap
|
|
110
|
+
* with the report window `[fromMs, toExclusive)` is therefore
|
|
111
|
+
* `start < toExclusive && fromMs < end`. A checkpoint with `start >= end`
|
|
112
|
+
* covers nothing and is never counted.
|
|
113
|
+
*/
|
|
114
|
+
export declare function checkpointInWindow(row: SignedCheckpoint, fromMs: number, toExclusive: number): boolean;
|
|
115
|
+
/**
|
|
116
|
+
* Held-call counts from attested records only, in chain order.
|
|
117
|
+
*
|
|
118
|
+
* A defer is answered by the first terminal (allow or deny) record that
|
|
119
|
+
* follows it in chain order, whose hash-bound inputs name the defer's ref in
|
|
120
|
+
* `approver.resolves`, and that agrees with the defer on request hash and
|
|
121
|
+
* tool. A record whose decision is defer is never an answer. One answer
|
|
122
|
+
* answers one defer: each answer names at most one resolves ref, and a ref
|
|
123
|
+
* shared by two defers is unmatched, so no shared-consumption set is needed.
|
|
124
|
+
* A defer with no usable ref, a ref shared with another defer, or only
|
|
125
|
+
* disagreeing answers is unmatched.
|
|
126
|
+
*
|
|
127
|
+
* Identity (when counts are available):
|
|
128
|
+
* approved + closedWithoutAllow + unmatched + heldWithoutBoundAnswer
|
|
129
|
+
* === windowDeferCount
|
|
130
|
+
* Bound answers and unbound possibility both scan every later terminal in
|
|
131
|
+
* chain order, inside the window or not. stillHeld is heldWithoutBoundAnswer
|
|
132
|
+
* when no held defer could be answered by an unbound record after it
|
|
133
|
+
* (heldPossiblyAnsweredByUnbound === 0); otherwise null. terminalsWithoutBoundInputs
|
|
134
|
+
* still counts only unbound terminals whose time falls in the window.
|
|
135
|
+
* heldPossiblyAnsweredByUnbound never exceeds heldWithoutBoundAnswer.
|
|
136
|
+
*/
|
|
137
|
+
export declare function countApprovalsFromSigned(dir: string, all: readonly SignedDecisionRecord[], fromMs: number, toExclusive: number): ApprovalCounts;
|
|
138
|
+
/**
|
|
139
|
+
* Temp file with a random name, exclusive create, then a hard link to the
|
|
140
|
+
* final name: the link fails with EEXIST if the target exists, so an existing
|
|
141
|
+
* file is never replaced. The temp name is removed on every path.
|
|
142
|
+
* `tempPath` is for tests that plant a collision at a known name; the CLI
|
|
143
|
+
* never passes it.
|
|
144
|
+
*/
|
|
145
|
+
export declare function writeOutExclusive(outPath: string, content: string, tempPath?: string): void;
|
|
146
|
+
export declare function buildPeriodReport(dir: string, from: string, to: string, fromMs: number, toExclusive: number): Promise<PeriodReport>;
|
|
147
|
+
/**
|
|
148
|
+
* Fixed key order. The same ledger and window give the same bytes. These are
|
|
149
|
+
* the one canonical display-safe bytes: terminal-control and bidi characters
|
|
150
|
+
* are escaped here, before any digest, so stdout, the digest and the digest
|
|
151
|
+
* shown in HTML are all of this exact sequence.
|
|
152
|
+
*/
|
|
153
|
+
export declare function serializePeriodReport(report: PeriodReport): string;
|
|
154
|
+
export declare function reportDigest(jsonBytes: string): string;
|
|
155
|
+
export declare function htmlEscape(text: string): string;
|
|
156
|
+
export declare function renderReportHtml(report: PeriodReport, digest: string): string;
|
|
157
|
+
export declare function renderReportText(report: PeriodReport, digest: string): string;
|
|
158
|
+
export declare function runReport(argv: readonly string[], out?: (s: string) => void,
|
|
159
|
+
/** Test-only: force the exclusive-create temp path. Not a CLI flag. */
|
|
160
|
+
opts?: {
|
|
161
|
+
writeTempPath?: string;
|
|
162
|
+
}): Promise<number>;
|
|
163
|
+
export {};
|