@verax-ai/body 0.8.2 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- 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/cli.js +37 -4
- package/dist/doctor.js +12 -0
- package/dist/report-cli.d.ts +163 -0
- package/dist/report-cli.js +1101 -0
- package/dist/server.js +5 -1
- 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/witness.d.ts +16 -5
- package/dist/witness.js +67 -8
- package/package.json +9 -9
|
@@ -0,0 +1,1101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `verax report <stateDir> --from <YYYY-MM-DD> --to <YYYY-MM-DD>` — a period
|
|
3
|
+
* evidence summary read offline from the ledger, the same way `verax verify`
|
|
4
|
+
* reads: no body running, nothing on the network.
|
|
5
|
+
*
|
|
6
|
+
* It counts decisions, held-call approvals and checkpoints inside the window,
|
|
7
|
+
* and carries the verification verdict `verax verify` would give for the whole
|
|
8
|
+
* ledger. It does not judge whether a decision was right.
|
|
9
|
+
*
|
|
10
|
+
* Counts come only from the records and checkpoints `verifyLedger` attested,
|
|
11
|
+
* and only when the ledger verifies. A ledger that does not verify yields
|
|
12
|
+
* `null` for every count: unverified material is never counted.
|
|
13
|
+
*/
|
|
14
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
15
|
+
import { linkSync, readFileSync, realpathSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
16
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
17
|
+
import { checkpointHash } from "@cedulon/checkpoint";
|
|
18
|
+
import { canonical, decisionRecordHash } from "@cedulon/core";
|
|
19
|
+
import { listPieceFiles, loadApprovalsFromDir, readAnchors, terminalLines, terminalText, verifyLedger, } from "@verax-ai/proxy";
|
|
20
|
+
import { directoryAccess, EX_ELEVATION } from "./install.js";
|
|
21
|
+
import { completeVerify, EX_VERIFY_FAILED, verdictLine } from "./verify-cli.js";
|
|
22
|
+
export const EX_USAGE = 64;
|
|
23
|
+
/** Same code `verax verify` uses for an unreadable state directory. */
|
|
24
|
+
export const EX_STATE_UNREADABLE = EX_ELEVATION;
|
|
25
|
+
const DAY_MS = 86_400_000;
|
|
26
|
+
const COUNTS_UNAVAILABLE_REASON = "the ledger did not verify; nothing is counted from unverified records (see the verification problem classes)";
|
|
27
|
+
const UNSIGNED_APPROVALS_NOTE = "approvals.jsonl could not be parsed cleanly. It is an unsigned candidate file: it is not a source of any count and it does not change the verdict.";
|
|
28
|
+
const WHAT_NOT_SHOWN = "It counts what is in the ledger. A call that never passed through the gate is not in it. A count is not a judgement that a decision was right. Counts are taken only from records and checkpoints that verification attested, and only when the ledger verifies; when it does not, every count is null. A held call is a signed defer counted by the time it was held. It is approved when the first signed allow or deny that follows it in chain order, names it, and agrees on request hash and tool, is an allow; it is closed without an allow when that first answer is a deny (expired or otherwise); it is still held when no signed bound answer exists and no later unbound record could have answered it; when a held defer could have been answered by an unbound record anywhere after it in chain order, stillHeld is not established and the report says how many held records an unbound inputs row could have answered; it is unmatched when the defer has no usable reference, shares its reference with another defer, or its only bound answers disagree on request hash or tool. A signature field present on an approving record is not a verified operator signature in this report; signature verification is part of the verdict. approvals.jsonl is not the source of a count. A checkpoint is counted when its coverage overlaps the window under the same [startMs, endMs) rule the ledger uses and its start is before its end. The report verifies with default options only (no key pins, operator credentials, anchor requirements or signed-start requirement), so anchor rows are only counted as present and not checked. The report does not name the ledger directory. Verification problems are named by class only; run verax verify on the machine for the detail. A ledger that cannot be read still yields a report that says it does not verify.";
|
|
29
|
+
function usage() {
|
|
30
|
+
return [
|
|
31
|
+
"usage: verax report <stateDir> --from <YYYY-MM-DD> --to <YYYY-MM-DD> [--out <file.html>] [--json]",
|
|
32
|
+
"",
|
|
33
|
+
" <stateDir> the directory holding decisions.jsonl and related ledger files",
|
|
34
|
+
" --from <date> inclusive start of the window, UTC midnight (YYYY-MM-DD)",
|
|
35
|
+
" --to <date> the last day, included in full; the window is [from, to + 1 day) UTC",
|
|
36
|
+
" --out <file> write one self-contained HTML file (refuses to overwrite, and",
|
|
37
|
+
" refuses a path inside <stateDir>)",
|
|
38
|
+
" --json one JSON object on stdout; no generation timestamp",
|
|
39
|
+
"",
|
|
40
|
+
"Counts come only from ledger records that verified. When the ledger does not",
|
|
41
|
+
"verify, every count is null and the report says NOT VERIFIED.",
|
|
42
|
+
"The report verifies with default options only: it does not accept key pins,",
|
|
43
|
+
"--operator-credentials, --require-anchored, --anchor-key, or",
|
|
44
|
+
"--require-signed-starts. Run verax verify with those flags when you need them.",
|
|
45
|
+
"Exit code is 0 when the ledger verifies and the same non-zero code",
|
|
46
|
+
"`verax verify` uses when it does not (an unreadable directory included).",
|
|
47
|
+
"Usage errors exit 64.",
|
|
48
|
+
].join("\n");
|
|
49
|
+
}
|
|
50
|
+
/** UTC midnight for a calendar date, or null when the string is not YYYY-MM-DD. */
|
|
51
|
+
export function parseReportDate(raw) {
|
|
52
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(raw);
|
|
53
|
+
if (!m)
|
|
54
|
+
return null;
|
|
55
|
+
const year = Number(m[1]);
|
|
56
|
+
const month = Number(m[2]);
|
|
57
|
+
const day = Number(m[3]);
|
|
58
|
+
if (month < 1 || month > 12 || day < 1 || day > 31)
|
|
59
|
+
return null;
|
|
60
|
+
const ms = Date.UTC(year, month - 1, day);
|
|
61
|
+
const d = new Date(ms);
|
|
62
|
+
if (d.getUTCFullYear() !== year || d.getUTCMonth() !== month - 1 || d.getUTCDate() !== day)
|
|
63
|
+
return null;
|
|
64
|
+
return ms;
|
|
65
|
+
}
|
|
66
|
+
function emptyCounts() {
|
|
67
|
+
return { allow: 0, deny: 0, defer: 0 };
|
|
68
|
+
}
|
|
69
|
+
function bump(counts, decision) {
|
|
70
|
+
if (decision === "allow")
|
|
71
|
+
counts.allow += 1;
|
|
72
|
+
else if (decision === "deny")
|
|
73
|
+
counts.deny += 1;
|
|
74
|
+
else if (decision === "defer")
|
|
75
|
+
counts.defer += 1;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Usable per-tool subject, or null when empty or not a string. Null subjects
|
|
79
|
+
* are counted in `withoutSubject`, not under a synthetic byTool key, so a
|
|
80
|
+
* real tool named U+001F cannot collide with the empty/missing bucket.
|
|
81
|
+
*/
|
|
82
|
+
export function subjectToolKey(subject) {
|
|
83
|
+
if (typeof subject === "string" && subject !== "")
|
|
84
|
+
return subject;
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
function readLines(path) {
|
|
88
|
+
try {
|
|
89
|
+
return readFileSync(path, "utf8")
|
|
90
|
+
.split("\n")
|
|
91
|
+
.filter((line) => line !== "");
|
|
92
|
+
}
|
|
93
|
+
catch (err) {
|
|
94
|
+
if (err.code === "ENOENT")
|
|
95
|
+
return [];
|
|
96
|
+
throw err;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Known verify / report problem-class prefixes, taken from the strings the
|
|
101
|
+
* verifier and `completeVerify` push into `problems` (and the report's own
|
|
102
|
+
* shell classes). Matched as a prefix of the problem line followed by a
|
|
103
|
+
* space, a colon, or the end of the string; longest match wins. Anything
|
|
104
|
+
* else is `unclassified`, so a ledger ref after a class cannot become the
|
|
105
|
+
* class label.
|
|
106
|
+
*/
|
|
107
|
+
const KNOWN_PROBLEM_CLASSES = [
|
|
108
|
+
"allow-while-halted",
|
|
109
|
+
"anchor entry hash is not the checkpoint's",
|
|
110
|
+
"anchor line",
|
|
111
|
+
"anchor names a checkpoint the ledger does not hold",
|
|
112
|
+
"anchor receipt does not verify",
|
|
113
|
+
"anchor route is not one this verifier reads",
|
|
114
|
+
"anchor row disagrees with its receipt",
|
|
115
|
+
"anchor statement is not this checkpoint's",
|
|
116
|
+
"approval signatures could not be read",
|
|
117
|
+
"approval signatures",
|
|
118
|
+
"approval-signatures-unreadable",
|
|
119
|
+
"approvals-malformed",
|
|
120
|
+
"approvals-unreadable",
|
|
121
|
+
"anchors-not-all-verified",
|
|
122
|
+
"anchors-unreadable",
|
|
123
|
+
"chain breaks at record",
|
|
124
|
+
"checkpoint chain breaks at checkpoint",
|
|
125
|
+
"checkpoint chain could not be checked",
|
|
126
|
+
"checkpoint covers",
|
|
127
|
+
"checkpoint file could not be read",
|
|
128
|
+
"checkpoint has no window",
|
|
129
|
+
"checkpoint line",
|
|
130
|
+
"checkpoint names a head the ledger does not hold",
|
|
131
|
+
"checkpoint signature does not verify",
|
|
132
|
+
"checkpoint totals do not match the records in its window",
|
|
133
|
+
"checkpoint-not-anchored",
|
|
134
|
+
"checkpoint-window-in-future",
|
|
135
|
+
"control signatures could not be read",
|
|
136
|
+
"control signatures",
|
|
137
|
+
"control-signatures-unreadable",
|
|
138
|
+
"decision-without-effect",
|
|
139
|
+
"downstream-manifest-invalid",
|
|
140
|
+
"downstream-manifest-mismatch",
|
|
141
|
+
"downstream-manifest-missing",
|
|
142
|
+
"duplicate-effect hash is not the fixed refusal",
|
|
143
|
+
"duplicate-effect row repeated",
|
|
144
|
+
"duplicate-effect with no decision",
|
|
145
|
+
"effect attestation does not cover the row",
|
|
146
|
+
"effect class is not the signed class",
|
|
147
|
+
"effect hash does not match its decision",
|
|
148
|
+
"effect is not an effect row",
|
|
149
|
+
"effect with no decision",
|
|
150
|
+
"halted effect does not match an allowed decision",
|
|
151
|
+
"index could not be read",
|
|
152
|
+
"index line",
|
|
153
|
+
"index names",
|
|
154
|
+
"index says ref",
|
|
155
|
+
"inputs row does not match",
|
|
156
|
+
"inputs row missing",
|
|
157
|
+
"ledger could not be read",
|
|
158
|
+
"ledger-manifest-corrupt",
|
|
159
|
+
"ledger-manifest-invalid",
|
|
160
|
+
"ledger-manifest-unreadable",
|
|
161
|
+
"ledger-unreadable",
|
|
162
|
+
"manifest piece path leaves the ledger directory",
|
|
163
|
+
"missing piece",
|
|
164
|
+
"newest checkpoint names a record the ledger no longer holds",
|
|
165
|
+
"no decisions found",
|
|
166
|
+
"public key is not ed25519",
|
|
167
|
+
"record is not a decision",
|
|
168
|
+
"record shape is not a decision",
|
|
169
|
+
"ref",
|
|
170
|
+
"require-anchored needs the service key",
|
|
171
|
+
"result-record-mismatch",
|
|
172
|
+
"same-org rows need --witness-key when --effect-key is pinned",
|
|
173
|
+
"self rows need --effect-key when --witness-key is pinned",
|
|
174
|
+
"signature does not verify",
|
|
175
|
+
"signed start row is malformed",
|
|
176
|
+
"signed start row is not written as the body writes it",
|
|
177
|
+
"start chain breaks at starts.jsonl line",
|
|
178
|
+
"start row at starts.jsonl line",
|
|
179
|
+
"start signature does not verify",
|
|
180
|
+
"start signature is not canonical base64",
|
|
181
|
+
"start-row-unreadable",
|
|
182
|
+
"start-row-unsigned",
|
|
183
|
+
"start-rows-missing",
|
|
184
|
+
"start-rows-not-checked",
|
|
185
|
+
"start-summary-unreadable",
|
|
186
|
+
"starts.jsonl could not be read",
|
|
187
|
+
"starts.jsonl line",
|
|
188
|
+
"state-unreadable",
|
|
189
|
+
"symbolic link",
|
|
190
|
+
"third-party key equals",
|
|
191
|
+
"third-party key rejected",
|
|
192
|
+
"third-party row",
|
|
193
|
+
"thrown effect does not match an allowed decision",
|
|
194
|
+
"unreadable file",
|
|
195
|
+
"unreadable row",
|
|
196
|
+
"unsigned start row after a signed one",
|
|
197
|
+
].slice().sort((a, b) => b.length - a.length || a.localeCompare(b));
|
|
198
|
+
/**
|
|
199
|
+
* Stable class for a verify problem line: the longest known class prefix
|
|
200
|
+
* followed by a space, a colon, or the end. Ledger detail after that prefix
|
|
201
|
+
* is dropped. Anything that is not a known class is `unclassified`.
|
|
202
|
+
*/
|
|
203
|
+
export function problemClass(problem) {
|
|
204
|
+
for (const known of KNOWN_PROBLEM_CLASSES) {
|
|
205
|
+
if (problem === known)
|
|
206
|
+
return known;
|
|
207
|
+
if (!problem.startsWith(known))
|
|
208
|
+
continue;
|
|
209
|
+
const next = problem[known.length];
|
|
210
|
+
if (next === " " || next === ":")
|
|
211
|
+
return known;
|
|
212
|
+
}
|
|
213
|
+
return "unclassified";
|
|
214
|
+
}
|
|
215
|
+
function classOfThrown(err, fallback) {
|
|
216
|
+
if (err instanceof Error && err.message) {
|
|
217
|
+
const cls = problemClass(err.message);
|
|
218
|
+
if (cls !== "unclassified")
|
|
219
|
+
return cls;
|
|
220
|
+
}
|
|
221
|
+
return fallback;
|
|
222
|
+
}
|
|
223
|
+
/** Decision records in chain order, using the same piece listing verify's helpers use. */
|
|
224
|
+
export function readDecisionRecords(dir) {
|
|
225
|
+
const out = [];
|
|
226
|
+
for (const piece of listPieceFiles(dir)) {
|
|
227
|
+
for (const line of readLines(piece.decisions)) {
|
|
228
|
+
try {
|
|
229
|
+
const row = JSON.parse(line);
|
|
230
|
+
if (row && typeof row === "object" && row.claims && typeof row.claims === "object")
|
|
231
|
+
out.push(row);
|
|
232
|
+
}
|
|
233
|
+
catch {
|
|
234
|
+
// A torn line is the ledger statement's problem; verify names it.
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return out;
|
|
239
|
+
}
|
|
240
|
+
function buildInputsIndex(dir) {
|
|
241
|
+
const index = new Map();
|
|
242
|
+
for (const piece of listPieceFiles(dir)) {
|
|
243
|
+
for (const line of readLines(piece.inputs)) {
|
|
244
|
+
try {
|
|
245
|
+
const doc = JSON.parse(line);
|
|
246
|
+
if (typeof doc.ref !== "string" || doc.inputs === undefined || doc.inputs === null)
|
|
247
|
+
continue;
|
|
248
|
+
if (typeof doc.inputs !== "object")
|
|
249
|
+
continue;
|
|
250
|
+
const hash = createHash("sha256").update(canonical(doc.inputs), "utf8").digest("hex");
|
|
251
|
+
let list = index.get(doc.ref);
|
|
252
|
+
if (!list) {
|
|
253
|
+
list = [];
|
|
254
|
+
index.set(doc.ref, list);
|
|
255
|
+
}
|
|
256
|
+
list.push({ hash, inputs: doc.inputs });
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
// skip a torn line
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
return index;
|
|
264
|
+
}
|
|
265
|
+
/** The inputs row that hashes to the record's signed `inputsHash`, or null. */
|
|
266
|
+
function inputsForRecord(index, row) {
|
|
267
|
+
const ref = row.claims.ref;
|
|
268
|
+
const inputsHash = row.claims.inputsHash;
|
|
269
|
+
if (typeof ref !== "string" || typeof inputsHash !== "string")
|
|
270
|
+
return null;
|
|
271
|
+
const list = index.get(ref);
|
|
272
|
+
if (!list)
|
|
273
|
+
return null;
|
|
274
|
+
for (const entry of list) {
|
|
275
|
+
if (entry.hash === inputsHash)
|
|
276
|
+
return entry.inputs;
|
|
277
|
+
}
|
|
278
|
+
return null;
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Cedulon/verify coverage is half-open `[startMs, endMs)` (see verify-ledger:
|
|
282
|
+
* `r.claims.timestampMs >= startMs && r.claims.timestampMs < endMs`). Overlap
|
|
283
|
+
* with the report window `[fromMs, toExclusive)` is therefore
|
|
284
|
+
* `start < toExclusive && fromMs < end`. A checkpoint with `start >= end`
|
|
285
|
+
* covers nothing and is never counted.
|
|
286
|
+
*/
|
|
287
|
+
export function checkpointInWindow(row, fromMs, toExclusive) {
|
|
288
|
+
const start = row.claims.startMs;
|
|
289
|
+
const end = row.claims.endMs;
|
|
290
|
+
if (typeof start !== "number" || typeof end !== "number")
|
|
291
|
+
return false;
|
|
292
|
+
if (!(start < end))
|
|
293
|
+
return false;
|
|
294
|
+
return start < toExclusive && fromMs < end;
|
|
295
|
+
}
|
|
296
|
+
const APPROVAL_NOT_CHECKED = {
|
|
297
|
+
ok: true,
|
|
298
|
+
signedVerified: 0,
|
|
299
|
+
signedFailed: 0,
|
|
300
|
+
signedAfterRemoval: 0,
|
|
301
|
+
unsignedHttp: 0,
|
|
302
|
+
cli: 0,
|
|
303
|
+
line: "approval signatures not checked",
|
|
304
|
+
trustSource: "none",
|
|
305
|
+
trustNote: "approval signatures were not checked",
|
|
306
|
+
};
|
|
307
|
+
const CONTROL_NOT_CHECKED = {
|
|
308
|
+
ok: true,
|
|
309
|
+
signedVerified: 0,
|
|
310
|
+
signedFailed: 0,
|
|
311
|
+
signedAfterRemoval: 0,
|
|
312
|
+
unsignedHttp: 0,
|
|
313
|
+
cli: 0,
|
|
314
|
+
file: 0,
|
|
315
|
+
integrity: 0,
|
|
316
|
+
line: "control signatures not checked",
|
|
317
|
+
trustSource: "none",
|
|
318
|
+
trustNote: "control signatures were not checked",
|
|
319
|
+
};
|
|
320
|
+
function failedVerifyShell(dir, problem) {
|
|
321
|
+
const result = {
|
|
322
|
+
ok: false,
|
|
323
|
+
directory: dir,
|
|
324
|
+
decisions: 0,
|
|
325
|
+
effects: 0,
|
|
326
|
+
signaturesValid: 0,
|
|
327
|
+
signaturesInvalid: 0,
|
|
328
|
+
chainBreakAt: null,
|
|
329
|
+
effectsBound: 0,
|
|
330
|
+
effectsOrphaned: 0,
|
|
331
|
+
effectsDeferred: [],
|
|
332
|
+
trust: { source: "none", publicKeyPem: null, note: problem },
|
|
333
|
+
effectTrust: { source: "none", publicKeyPem: null, note: problem },
|
|
334
|
+
witnessTrust: { source: "none", publicKeyPem: null, note: problem },
|
|
335
|
+
checkpointTrust: { source: "none", publicKeyPem: null, note: problem },
|
|
336
|
+
index: { present: false, missing: 0, line: "index: none (cannot check for removed records)" },
|
|
337
|
+
effectCompleteness: "effect completeness was not checked",
|
|
338
|
+
tail: {
|
|
339
|
+
line: "tail: no checkpoint; removing the newest records with their effects is not detectable from these files",
|
|
340
|
+
checkpoint: null,
|
|
341
|
+
},
|
|
342
|
+
control: { line: "control: not checked", windows: 0, warnings: [] },
|
|
343
|
+
inputs: { line: "inputs: not checked", matched: 0, missing: 0, mismatched: 0 },
|
|
344
|
+
anchors: { line: "anchors: not checked", receipts: 0, verified: 0, checked: false },
|
|
345
|
+
problems: [problem],
|
|
346
|
+
attestedDecisions: [],
|
|
347
|
+
attestedCheckpoints: [],
|
|
348
|
+
};
|
|
349
|
+
return {
|
|
350
|
+
result,
|
|
351
|
+
approval: APPROVAL_NOT_CHECKED,
|
|
352
|
+
control: CONTROL_NOT_CHECKED,
|
|
353
|
+
verdict: verdictLine(result, APPROVAL_NOT_CHECKED, CONTROL_NOT_CHECKED),
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
async function verifyLikeVerifyCli(dir) {
|
|
357
|
+
let result;
|
|
358
|
+
try {
|
|
359
|
+
result = await verifyLedger(dir);
|
|
360
|
+
}
|
|
361
|
+
catch (err) {
|
|
362
|
+
return failedVerifyShell(dir, classOfThrown(err, "ledger-unreadable"));
|
|
363
|
+
}
|
|
364
|
+
const completed = await completeVerify(dir, result, {
|
|
365
|
+
requireSignedStarts: false,
|
|
366
|
+
catchStartErrors: true,
|
|
367
|
+
problemFromThrown: (err, fallback) => {
|
|
368
|
+
const reportFallback = fallback === "approval signatures could not be read"
|
|
369
|
+
? "approval-signatures-unreadable"
|
|
370
|
+
: fallback === "control signatures could not be read"
|
|
371
|
+
? "control-signatures-unreadable"
|
|
372
|
+
: fallback;
|
|
373
|
+
return classOfThrown(err, reportFallback);
|
|
374
|
+
},
|
|
375
|
+
});
|
|
376
|
+
return {
|
|
377
|
+
result: completed.result,
|
|
378
|
+
approval: completed.approval,
|
|
379
|
+
control: completed.control,
|
|
380
|
+
verdict: completed.verdict,
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
function refOf(row) {
|
|
384
|
+
const ref = row.claims.ref;
|
|
385
|
+
return typeof ref === "string" && ref !== "" ? ref : null;
|
|
386
|
+
}
|
|
387
|
+
function nonEmptyString(v) {
|
|
388
|
+
return typeof v === "string" && v !== "" ? v : null;
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Held-call counts from attested records only, in chain order.
|
|
392
|
+
*
|
|
393
|
+
* A defer is answered by the first terminal (allow or deny) record that
|
|
394
|
+
* follows it in chain order, whose hash-bound inputs name the defer's ref in
|
|
395
|
+
* `approver.resolves`, and that agrees with the defer on request hash and
|
|
396
|
+
* tool. A record whose decision is defer is never an answer. One answer
|
|
397
|
+
* answers one defer: each answer names at most one resolves ref, and a ref
|
|
398
|
+
* shared by two defers is unmatched, so no shared-consumption set is needed.
|
|
399
|
+
* A defer with no usable ref, a ref shared with another defer, or only
|
|
400
|
+
* disagreeing answers is unmatched.
|
|
401
|
+
*
|
|
402
|
+
* Identity (when counts are available):
|
|
403
|
+
* approved + closedWithoutAllow + unmatched + heldWithoutBoundAnswer
|
|
404
|
+
* === windowDeferCount
|
|
405
|
+
* Bound answers and unbound possibility both scan every later terminal in
|
|
406
|
+
* chain order, inside the window or not. stillHeld is heldWithoutBoundAnswer
|
|
407
|
+
* when no held defer could be answered by an unbound record after it
|
|
408
|
+
* (heldPossiblyAnsweredByUnbound === 0); otherwise null. terminalsWithoutBoundInputs
|
|
409
|
+
* still counts only unbound terminals whose time falls in the window.
|
|
410
|
+
* heldPossiblyAnsweredByUnbound never exceeds heldWithoutBoundAnswer.
|
|
411
|
+
*/
|
|
412
|
+
export function countApprovalsFromSigned(dir, all, fromMs, toExclusive) {
|
|
413
|
+
const index = buildInputsIndex(dir);
|
|
414
|
+
const deferRefCount = new Map();
|
|
415
|
+
for (const row of all) {
|
|
416
|
+
if (row.claims.decision !== "defer")
|
|
417
|
+
continue;
|
|
418
|
+
const ref = refOf(row);
|
|
419
|
+
if (ref !== null)
|
|
420
|
+
deferRefCount.set(ref, (deferRefCount.get(ref) ?? 0) + 1);
|
|
421
|
+
}
|
|
422
|
+
// resolves ref -> terminal records naming it, in chain order (bound only).
|
|
423
|
+
const answersByRef = new Map();
|
|
424
|
+
// Unbound terminals: no string inputsHash or no row hashing to it. Every
|
|
425
|
+
// inputs row for the terminal (not only the first with resolves) is
|
|
426
|
+
// consulted for heldPossiblyAnsweredByUnbound.
|
|
427
|
+
const unboundTerminals = [];
|
|
428
|
+
let terminalsWithoutBoundInputs = 0;
|
|
429
|
+
for (let pos = 0; pos < all.length; pos += 1) {
|
|
430
|
+
const row = all[pos];
|
|
431
|
+
const decision = row.claims.decision;
|
|
432
|
+
if (decision !== "allow" && decision !== "deny")
|
|
433
|
+
continue;
|
|
434
|
+
const ts = row.claims.timestampMs;
|
|
435
|
+
const inWindow = typeof ts === "number" && ts >= fromMs && ts < toExclusive;
|
|
436
|
+
const inputs = inputsForRecord(index, row);
|
|
437
|
+
if (inputs === null) {
|
|
438
|
+
if (inWindow)
|
|
439
|
+
terminalsWithoutBoundInputs += 1;
|
|
440
|
+
const ref = typeof row.claims.ref === "string" ? row.claims.ref : null;
|
|
441
|
+
const resolves = new Set();
|
|
442
|
+
if (ref !== null) {
|
|
443
|
+
const rows = index.get(ref);
|
|
444
|
+
if (rows) {
|
|
445
|
+
for (const entry of rows) {
|
|
446
|
+
const r = entry.inputs.approver?.resolves;
|
|
447
|
+
if (typeof r === "string" && r !== "")
|
|
448
|
+
resolves.add(r);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
unboundTerminals.push({ pos, row, resolves });
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
const resolves = inputs.approver?.resolves;
|
|
456
|
+
if (typeof resolves !== "string" || resolves === "")
|
|
457
|
+
continue;
|
|
458
|
+
let list = answersByRef.get(resolves);
|
|
459
|
+
if (!list) {
|
|
460
|
+
list = [];
|
|
461
|
+
answersByRef.set(resolves, list);
|
|
462
|
+
}
|
|
463
|
+
list.push({ pos, row, inputs });
|
|
464
|
+
}
|
|
465
|
+
const counts = {
|
|
466
|
+
approved: 0,
|
|
467
|
+
withOperatorSignatureFieldPresent: 0,
|
|
468
|
+
withoutOperatorSignatureField: 0,
|
|
469
|
+
closedWithoutAllow: 0,
|
|
470
|
+
stillHeld: 0,
|
|
471
|
+
unmatched: 0,
|
|
472
|
+
terminalsWithoutBoundInputs,
|
|
473
|
+
heldWithoutBoundAnswer: 0,
|
|
474
|
+
heldPossiblyAnsweredByUnbound: 0,
|
|
475
|
+
};
|
|
476
|
+
const heldPositions = [];
|
|
477
|
+
for (let pos = 0; pos < all.length; pos += 1) {
|
|
478
|
+
const defer = all[pos];
|
|
479
|
+
if (defer.claims.decision !== "defer")
|
|
480
|
+
continue;
|
|
481
|
+
const ts = defer.claims.timestampMs;
|
|
482
|
+
const inWindow = typeof ts === "number" && ts >= fromMs && ts < toExclusive;
|
|
483
|
+
const ref = refOf(defer);
|
|
484
|
+
let outcome;
|
|
485
|
+
let decided = null;
|
|
486
|
+
if (ref === null || (deferRefCount.get(ref) ?? 0) !== 1) {
|
|
487
|
+
outcome = "unmatched";
|
|
488
|
+
}
|
|
489
|
+
else {
|
|
490
|
+
const candidates = (answersByRef.get(ref) ?? []).filter((c) => c.pos > pos);
|
|
491
|
+
if (candidates.length === 0) {
|
|
492
|
+
outcome = "held";
|
|
493
|
+
}
|
|
494
|
+
else {
|
|
495
|
+
const reqHash = nonEmptyString(defer.claims.requestHash);
|
|
496
|
+
const subject = nonEmptyString(defer.claims.subject);
|
|
497
|
+
const valid = candidates.find((c) => {
|
|
498
|
+
const aReq = nonEmptyString(c.row.claims.requestHash);
|
|
499
|
+
const aSubject = nonEmptyString(c.row.claims.subject);
|
|
500
|
+
return reqHash !== null && subject !== null && aReq === reqHash && aSubject === subject;
|
|
501
|
+
});
|
|
502
|
+
if (!valid) {
|
|
503
|
+
outcome = "unmatched";
|
|
504
|
+
}
|
|
505
|
+
else {
|
|
506
|
+
decided = valid;
|
|
507
|
+
outcome = valid.row.claims.decision === "allow" ? "approved" : "closed";
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
if (!inWindow)
|
|
512
|
+
continue;
|
|
513
|
+
if (outcome === "approved") {
|
|
514
|
+
counts.approved += 1;
|
|
515
|
+
if (decided?.inputs.approver?.signature !== undefined)
|
|
516
|
+
counts.withOperatorSignatureFieldPresent += 1;
|
|
517
|
+
else
|
|
518
|
+
counts.withoutOperatorSignatureField += 1;
|
|
519
|
+
}
|
|
520
|
+
else if (outcome === "closed") {
|
|
521
|
+
counts.closedWithoutAllow += 1;
|
|
522
|
+
}
|
|
523
|
+
else if (outcome === "held") {
|
|
524
|
+
counts.heldWithoutBoundAnswer += 1;
|
|
525
|
+
heldPositions.push({ pos, defer, ref: ref });
|
|
526
|
+
}
|
|
527
|
+
else {
|
|
528
|
+
counts.unmatched += 1;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
for (const held of heldPositions) {
|
|
532
|
+
const reqHash = nonEmptyString(held.defer.claims.requestHash);
|
|
533
|
+
const subject = nonEmptyString(held.defer.claims.subject);
|
|
534
|
+
const maybe = unboundTerminals.some((u) => {
|
|
535
|
+
if (u.pos <= held.pos)
|
|
536
|
+
return false;
|
|
537
|
+
if (!u.resolves.has(held.ref))
|
|
538
|
+
return false;
|
|
539
|
+
const aReq = nonEmptyString(u.row.claims.requestHash);
|
|
540
|
+
const aSubject = nonEmptyString(u.row.claims.subject);
|
|
541
|
+
return reqHash !== null && subject !== null && aReq === reqHash && aSubject === subject;
|
|
542
|
+
});
|
|
543
|
+
if (maybe)
|
|
544
|
+
counts.heldPossiblyAnsweredByUnbound += 1;
|
|
545
|
+
}
|
|
546
|
+
counts.stillHeld =
|
|
547
|
+
counts.heldPossiblyAnsweredByUnbound === 0 ? counts.heldWithoutBoundAnswer : null;
|
|
548
|
+
return counts;
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* Temp file with a random name, exclusive create, then a hard link to the
|
|
552
|
+
* final name: the link fails with EEXIST if the target exists, so an existing
|
|
553
|
+
* file is never replaced. The temp name is removed on every path.
|
|
554
|
+
* `tempPath` is for tests that plant a collision at a known name; the CLI
|
|
555
|
+
* never passes it.
|
|
556
|
+
*/
|
|
557
|
+
export function writeOutExclusive(outPath, content, tempPath) {
|
|
558
|
+
const tmp = tempPath ?? join(dirname(outPath), `.verax-report-${randomBytes(12).toString("hex")}.tmp`);
|
|
559
|
+
let created = false;
|
|
560
|
+
try {
|
|
561
|
+
writeFileSync(tmp, content, { encoding: "utf8", flag: "wx" });
|
|
562
|
+
created = true;
|
|
563
|
+
linkSync(tmp, outPath);
|
|
564
|
+
}
|
|
565
|
+
finally {
|
|
566
|
+
if (created) {
|
|
567
|
+
try {
|
|
568
|
+
unlinkSync(tmp);
|
|
569
|
+
}
|
|
570
|
+
catch {
|
|
571
|
+
// best-effort cleanup
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Real path when the file exists. When it does not, walk up to the nearest
|
|
578
|
+
* existing ancestor, realpath that, and append the missing segments. One
|
|
579
|
+
* parent is not enough: a state directory reached through a symlink (macOS
|
|
580
|
+
* /var, or a junction) resolves, while `--out dir/sub/nested` may not, and
|
|
581
|
+
* comparing the unresolved path then misses "inside the state directory".
|
|
582
|
+
*/
|
|
583
|
+
function realOrResolved(path) {
|
|
584
|
+
const abs = resolve(path);
|
|
585
|
+
const missing = [];
|
|
586
|
+
let cur = abs;
|
|
587
|
+
for (;;) {
|
|
588
|
+
try {
|
|
589
|
+
const real = realpathSync(cur);
|
|
590
|
+
return missing.length === 0 ? real : join(real, ...missing);
|
|
591
|
+
}
|
|
592
|
+
catch {
|
|
593
|
+
const parent = dirname(cur);
|
|
594
|
+
if (parent === cur)
|
|
595
|
+
return abs;
|
|
596
|
+
missing.unshift(basename(cur));
|
|
597
|
+
cur = parent;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
function pathInside(child, parent) {
|
|
602
|
+
const rel = relative(parent, child);
|
|
603
|
+
if (rel === "")
|
|
604
|
+
return true;
|
|
605
|
+
if (isAbsolute(rel))
|
|
606
|
+
return false;
|
|
607
|
+
return rel !== ".." && !rel.startsWith(`..${sep}`);
|
|
608
|
+
}
|
|
609
|
+
function outInsideStateDir(dir, outPath) {
|
|
610
|
+
return pathInside(realOrResolved(outPath), realOrResolved(dir));
|
|
611
|
+
}
|
|
612
|
+
function unverifiedReport(from, to, problem) {
|
|
613
|
+
const shell = failedVerifyShell("", problem);
|
|
614
|
+
return {
|
|
615
|
+
from,
|
|
616
|
+
to,
|
|
617
|
+
headHash: null,
|
|
618
|
+
recordCount: null,
|
|
619
|
+
firstRecordMs: null,
|
|
620
|
+
lastRecordMs: null,
|
|
621
|
+
verification: {
|
|
622
|
+
ok: false,
|
|
623
|
+
verdict: shell.verdict,
|
|
624
|
+
problems: [problem],
|
|
625
|
+
},
|
|
626
|
+
countsUnavailableReason: COUNTS_UNAVAILABLE_REASON,
|
|
627
|
+
unsignedApprovalsNote: null,
|
|
628
|
+
decisions: { total: null, byTool: null, withoutSubject: null },
|
|
629
|
+
approvals: {
|
|
630
|
+
approved: null,
|
|
631
|
+
withOperatorSignatureFieldPresent: null,
|
|
632
|
+
withoutOperatorSignatureField: null,
|
|
633
|
+
closedWithoutAllow: null,
|
|
634
|
+
stillHeld: null,
|
|
635
|
+
unmatched: null,
|
|
636
|
+
terminalsWithoutBoundInputs: null,
|
|
637
|
+
heldWithoutBoundAnswer: null,
|
|
638
|
+
heldPossiblyAnsweredByUnbound: null,
|
|
639
|
+
unavailableReason: null,
|
|
640
|
+
},
|
|
641
|
+
checkpoints: {
|
|
642
|
+
count: null,
|
|
643
|
+
withAnchorVerified: null,
|
|
644
|
+
anchorRowsPresentNotChecked: null,
|
|
645
|
+
anchorUnavailableReason: null,
|
|
646
|
+
},
|
|
647
|
+
whatThisReportDoesNotShow: WHAT_NOT_SHOWN,
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
export async function buildPeriodReport(dir, from, to, fromMs, toExclusive) {
|
|
651
|
+
if (directoryAccess(dir) === "unreadable") {
|
|
652
|
+
return unverifiedReport(from, to, "state-unreadable");
|
|
653
|
+
}
|
|
654
|
+
let verified;
|
|
655
|
+
try {
|
|
656
|
+
verified = await verifyLikeVerifyCli(dir);
|
|
657
|
+
}
|
|
658
|
+
catch (err) {
|
|
659
|
+
return unverifiedReport(from, to, classOfThrown(err, "ledger-unreadable"));
|
|
660
|
+
}
|
|
661
|
+
const result = verified.result;
|
|
662
|
+
const problemClasses = [...new Set(result.problems.map(problemClass))];
|
|
663
|
+
// Candidate file only: a malformed line is noted, never counted, and never
|
|
664
|
+
// changes the verdict.
|
|
665
|
+
let unsignedApprovalsNote = null;
|
|
666
|
+
try {
|
|
667
|
+
loadApprovalsFromDir(dir);
|
|
668
|
+
}
|
|
669
|
+
catch {
|
|
670
|
+
unsignedApprovalsNote = UNSIGNED_APPROVALS_NOTE;
|
|
671
|
+
}
|
|
672
|
+
const verification = {
|
|
673
|
+
ok: result.ok,
|
|
674
|
+
verdict: verified.verdict,
|
|
675
|
+
problems: problemClasses,
|
|
676
|
+
};
|
|
677
|
+
if (!result.ok) {
|
|
678
|
+
const report = unverifiedReport(from, to, "unused");
|
|
679
|
+
return {
|
|
680
|
+
...report,
|
|
681
|
+
verification,
|
|
682
|
+
unsignedApprovalsNote,
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
const attested = result.attestedDecisions;
|
|
686
|
+
let headHash = null;
|
|
687
|
+
if (attested.length > 0) {
|
|
688
|
+
try {
|
|
689
|
+
headHash = decisionRecordHash(attested[attested.length - 1]);
|
|
690
|
+
}
|
|
691
|
+
catch {
|
|
692
|
+
headHash = null;
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
const inWindow = attested.filter((r) => {
|
|
696
|
+
const ts = r.claims.timestampMs;
|
|
697
|
+
return typeof ts === "number" && ts >= fromMs && ts < toExclusive;
|
|
698
|
+
});
|
|
699
|
+
const total = emptyCounts();
|
|
700
|
+
const withoutSubject = emptyCounts();
|
|
701
|
+
const byToolMap = new Map();
|
|
702
|
+
let firstRecordMs = null;
|
|
703
|
+
let lastRecordMs = null;
|
|
704
|
+
for (const row of inWindow) {
|
|
705
|
+
const ts = row.claims.timestampMs;
|
|
706
|
+
if (firstRecordMs === null || ts < firstRecordMs)
|
|
707
|
+
firstRecordMs = ts;
|
|
708
|
+
if (lastRecordMs === null || ts > lastRecordMs)
|
|
709
|
+
lastRecordMs = ts;
|
|
710
|
+
const decision = row.claims.decision;
|
|
711
|
+
if (typeof decision !== "string")
|
|
712
|
+
continue;
|
|
713
|
+
bump(total, decision);
|
|
714
|
+
const tool = subjectToolKey(row.claims.subject);
|
|
715
|
+
if (tool === null) {
|
|
716
|
+
bump(withoutSubject, decision);
|
|
717
|
+
continue;
|
|
718
|
+
}
|
|
719
|
+
let counts = byToolMap.get(tool);
|
|
720
|
+
if (!counts) {
|
|
721
|
+
counts = emptyCounts();
|
|
722
|
+
byToolMap.set(tool, counts);
|
|
723
|
+
}
|
|
724
|
+
bump(counts, decision);
|
|
725
|
+
}
|
|
726
|
+
// Own keys only: tool names such as __proto__ must not hit Object.prototype.
|
|
727
|
+
// byTool holds only real subjects; empty/missing are in withoutSubject.
|
|
728
|
+
// Identity: per-tool numbers plus withoutSubject equal the totals.
|
|
729
|
+
const byTool = Object.create(null);
|
|
730
|
+
for (const tool of [...byToolMap.keys()].sort()) {
|
|
731
|
+
byTool[tool] = byToolMap.get(tool);
|
|
732
|
+
}
|
|
733
|
+
let approvals = {
|
|
734
|
+
approved: null,
|
|
735
|
+
withOperatorSignatureFieldPresent: null,
|
|
736
|
+
withoutOperatorSignatureField: null,
|
|
737
|
+
closedWithoutAllow: null,
|
|
738
|
+
stillHeld: null,
|
|
739
|
+
unmatched: null,
|
|
740
|
+
terminalsWithoutBoundInputs: null,
|
|
741
|
+
heldWithoutBoundAnswer: null,
|
|
742
|
+
heldPossiblyAnsweredByUnbound: null,
|
|
743
|
+
unavailableReason: null,
|
|
744
|
+
};
|
|
745
|
+
try {
|
|
746
|
+
approvals = { ...countApprovalsFromSigned(dir, attested, fromMs, toExclusive), unavailableReason: null };
|
|
747
|
+
}
|
|
748
|
+
catch (err) {
|
|
749
|
+
approvals.unavailableReason = classOfThrown(err, "approvals-unreadable");
|
|
750
|
+
}
|
|
751
|
+
// Checkpoints come from verify's attested set; anchors are read on their own
|
|
752
|
+
// so that an unreadable anchor file cannot hide the checkpoint count.
|
|
753
|
+
const windowCheckpoints = result.attestedCheckpoints.filter((row) => checkpointInWindow(row, fromMs, toExclusive));
|
|
754
|
+
const windowHashes = new Set();
|
|
755
|
+
for (const row of windowCheckpoints) {
|
|
756
|
+
try {
|
|
757
|
+
windowHashes.add(checkpointHash(row));
|
|
758
|
+
}
|
|
759
|
+
catch {
|
|
760
|
+
// A row that cannot be hashed cannot be matched to an anchor row.
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
const checkpoints = {
|
|
764
|
+
count: windowCheckpoints.length,
|
|
765
|
+
withAnchorVerified: null,
|
|
766
|
+
anchorRowsPresentNotChecked: null,
|
|
767
|
+
anchorUnavailableReason: null,
|
|
768
|
+
};
|
|
769
|
+
try {
|
|
770
|
+
const anchorRows = readAnchors(dir).rows;
|
|
771
|
+
const inWindowRows = anchorRows.filter((r) => windowHashes.has(r.checkpointHash)).length;
|
|
772
|
+
if (result.anchors.checked) {
|
|
773
|
+
// An ok ledger has no failed receipt: every row verified.
|
|
774
|
+
if (result.anchors.verified === result.anchors.receipts) {
|
|
775
|
+
checkpoints.withAnchorVerified = inWindowRows;
|
|
776
|
+
checkpoints.anchorRowsPresentNotChecked = 0;
|
|
777
|
+
}
|
|
778
|
+
else {
|
|
779
|
+
checkpoints.anchorUnavailableReason = "anchors-not-all-verified";
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
else {
|
|
783
|
+
checkpoints.withAnchorVerified = 0;
|
|
784
|
+
checkpoints.anchorRowsPresentNotChecked = inWindowRows;
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
catch (err) {
|
|
788
|
+
checkpoints.anchorUnavailableReason = classOfThrown(err, "anchors-unreadable");
|
|
789
|
+
}
|
|
790
|
+
return {
|
|
791
|
+
from,
|
|
792
|
+
to,
|
|
793
|
+
headHash,
|
|
794
|
+
recordCount: inWindow.length,
|
|
795
|
+
firstRecordMs,
|
|
796
|
+
lastRecordMs,
|
|
797
|
+
verification,
|
|
798
|
+
countsUnavailableReason: null,
|
|
799
|
+
unsignedApprovalsNote,
|
|
800
|
+
decisions: { total, byTool, withoutSubject },
|
|
801
|
+
approvals,
|
|
802
|
+
checkpoints,
|
|
803
|
+
whatThisReportDoesNotShow: WHAT_NOT_SHOWN,
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
function jsonNum(n) {
|
|
807
|
+
return n === null ? "null" : String(n);
|
|
808
|
+
}
|
|
809
|
+
function jsonCounts(c) {
|
|
810
|
+
return c === null ? "null" : `{"allow":${c.allow},"deny":${c.deny},"defer":${c.defer}}`;
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* Fixed key order. The same ledger and window give the same bytes. These are
|
|
814
|
+
* the one canonical display-safe bytes: terminal-control and bidi characters
|
|
815
|
+
* are escaped here, before any digest, so stdout, the digest and the digest
|
|
816
|
+
* shown in HTML are all of this exact sequence.
|
|
817
|
+
*/
|
|
818
|
+
export function serializePeriodReport(report) {
|
|
819
|
+
const byToolJson = report.decisions.byTool === null
|
|
820
|
+
? "null"
|
|
821
|
+
: `{${Object.keys(report.decisions.byTool)
|
|
822
|
+
.sort()
|
|
823
|
+
.map((tool) => `${JSON.stringify(tool)}:${jsonCounts(report.decisions.byTool[tool])}`)
|
|
824
|
+
.join(",")}}`;
|
|
825
|
+
const withoutSubjectJson = jsonCounts(report.decisions.withoutSubject);
|
|
826
|
+
const problemsJson = `[${report.verification.problems.map((p) => JSON.stringify(p)).join(",")}]`;
|
|
827
|
+
const a = report.approvals;
|
|
828
|
+
const c = report.checkpoints;
|
|
829
|
+
const json = "{" +
|
|
830
|
+
[
|
|
831
|
+
`"from":${JSON.stringify(report.from)}`,
|
|
832
|
+
`"to":${JSON.stringify(report.to)}`,
|
|
833
|
+
`"headHash":${JSON.stringify(report.headHash)}`,
|
|
834
|
+
`"recordCount":${jsonNum(report.recordCount)}`,
|
|
835
|
+
`"firstRecordMs":${jsonNum(report.firstRecordMs)}`,
|
|
836
|
+
`"lastRecordMs":${jsonNum(report.lastRecordMs)}`,
|
|
837
|
+
`"verification":{"ok":${report.verification.ok},"verdict":${JSON.stringify(report.verification.verdict)},"problems":${problemsJson}}`,
|
|
838
|
+
`"countsUnavailableReason":${JSON.stringify(report.countsUnavailableReason)}`,
|
|
839
|
+
`"unsignedApprovalsNote":${JSON.stringify(report.unsignedApprovalsNote)}`,
|
|
840
|
+
`"decisions":{"total":${jsonCounts(report.decisions.total)},"byTool":${byToolJson},"withoutSubject":${withoutSubjectJson}}`,
|
|
841
|
+
`"approvals":{"approved":${jsonNum(a.approved)},"withOperatorSignatureFieldPresent":${jsonNum(a.withOperatorSignatureFieldPresent)},"withoutOperatorSignatureField":${jsonNum(a.withoutOperatorSignatureField)},"closedWithoutAllow":${jsonNum(a.closedWithoutAllow)},"stillHeld":${jsonNum(a.stillHeld)},"unmatched":${jsonNum(a.unmatched)},"terminalsWithoutBoundInputs":${jsonNum(a.terminalsWithoutBoundInputs)},"heldWithoutBoundAnswer":${jsonNum(a.heldWithoutBoundAnswer)},"heldPossiblyAnsweredByUnbound":${jsonNum(a.heldPossiblyAnsweredByUnbound)},"unavailableReason":${JSON.stringify(a.unavailableReason)}}`,
|
|
842
|
+
`"checkpoints":{"count":${jsonNum(c.count)},"withAnchorVerified":${jsonNum(c.withAnchorVerified)},"anchorRowsPresentNotChecked":${jsonNum(c.anchorRowsPresentNotChecked)},"anchorUnavailableReason":${JSON.stringify(c.anchorUnavailableReason)}}`,
|
|
843
|
+
`"whatThisReportDoesNotShow":${JSON.stringify(report.whatThisReportDoesNotShow)}`,
|
|
844
|
+
].join(",") +
|
|
845
|
+
"}";
|
|
846
|
+
return terminalLines(json);
|
|
847
|
+
}
|
|
848
|
+
export function reportDigest(jsonBytes) {
|
|
849
|
+
return createHash("sha256").update(jsonBytes, "utf8").digest("hex");
|
|
850
|
+
}
|
|
851
|
+
export function htmlEscape(text) {
|
|
852
|
+
return text
|
|
853
|
+
.replaceAll("&", "&")
|
|
854
|
+
.replaceAll("<", "<")
|
|
855
|
+
.replaceAll(">", ">")
|
|
856
|
+
.replaceAll('"', """)
|
|
857
|
+
.replaceAll("'", "'");
|
|
858
|
+
}
|
|
859
|
+
function shown(n) {
|
|
860
|
+
return n === null ? "not available" : String(n);
|
|
861
|
+
}
|
|
862
|
+
function shownCounts(c) {
|
|
863
|
+
return c === null ? "not available" : `allow ${c.allow}, deny ${c.deny}, defer ${c.defer}`;
|
|
864
|
+
}
|
|
865
|
+
function unavailableSentence(report) {
|
|
866
|
+
const classes = report.verification.problems.join(", ");
|
|
867
|
+
return `Counts not available (null): ${report.countsUnavailableReason ?? ""}${classes === "" ? "" : ` Problem classes: ${classes}.`}`;
|
|
868
|
+
}
|
|
869
|
+
const WINDOW_SENTENCE = "The to day is included in full: the window is half-open, from 00:00:00 UTC on the from day up to, not including, 00:00:00 UTC on the day after the to day.";
|
|
870
|
+
export function renderReportHtml(report, digest) {
|
|
871
|
+
const esc = (s) => htmlEscape(terminalText(s));
|
|
872
|
+
const toolRows = report.decisions.byTool === null
|
|
873
|
+
? ""
|
|
874
|
+
: Object.keys(report.decisions.byTool)
|
|
875
|
+
.sort()
|
|
876
|
+
.map((tool) => {
|
|
877
|
+
const c = report.decisions.byTool[tool];
|
|
878
|
+
return `<tr><td>${esc(tool)}</td><td>${c.allow}</td><td>${c.deny}</td><td>${c.defer}</td></tr>`;
|
|
879
|
+
})
|
|
880
|
+
.join("");
|
|
881
|
+
const problemItems = report.verification.problems.map((p) => `<li>${esc(p)}</li>`).join("");
|
|
882
|
+
const problemsBlock = report.verification.problems.length === 0
|
|
883
|
+
? "<p>No verification problems named.</p>"
|
|
884
|
+
: `<p>${report.verification.problems.length} problem class(es). Run <code>verax verify</code> on the machine for the detail.</p><ul>${problemItems}</ul>`;
|
|
885
|
+
const countsNotice = report.countsUnavailableReason === null ? [] : [`<p class="verdict">${esc(unavailableSentence(report))}</p>`];
|
|
886
|
+
const approvalsNote = report.unsignedApprovalsNote === null ? [] : [`<p>Note: ${esc(report.unsignedApprovalsNote)}</p>`];
|
|
887
|
+
const a = report.approvals;
|
|
888
|
+
const c = report.checkpoints;
|
|
889
|
+
const approvalsReason = a.unavailableReason === null ? "" : ` Approvals not available: ${esc(a.unavailableReason)}.`;
|
|
890
|
+
const anchorReason = c.anchorUnavailableReason === null ? "" : ` Anchor counts not available: ${esc(c.anchorUnavailableReason)}.`;
|
|
891
|
+
return [
|
|
892
|
+
"<!DOCTYPE html>",
|
|
893
|
+
'<html lang="en">',
|
|
894
|
+
"<head>",
|
|
895
|
+
'<meta charset="utf-8">',
|
|
896
|
+
"<title>Period report</title>",
|
|
897
|
+
"<style>",
|
|
898
|
+
"body{font-family:ui-sans-serif,system-ui,sans-serif;margin:2rem;line-height:1.45;color:#111}",
|
|
899
|
+
"h1{font-size:1.5rem;margin:0 0 0.5rem}",
|
|
900
|
+
"h2{font-size:1.1rem;margin:1.5rem 0 0.5rem}",
|
|
901
|
+
"table{border-collapse:collapse;margin:0.5rem 0}",
|
|
902
|
+
"th,td{border:1px solid #ccc;padding:0.35rem 0.6rem;text-align:left}",
|
|
903
|
+
".verdict{font-weight:600;margin:0.75rem 0}",
|
|
904
|
+
".digest{margin-top:2rem;font-size:0.95rem}",
|
|
905
|
+
"code{word-break:break-all}",
|
|
906
|
+
"</style>",
|
|
907
|
+
"</head>",
|
|
908
|
+
"<body>",
|
|
909
|
+
"<h1>Period report</h1>",
|
|
910
|
+
`<p class="verdict">${esc(report.verification.verdict)}</p>`,
|
|
911
|
+
...countsNotice,
|
|
912
|
+
`<p>Window ${esc(report.from)} to ${esc(report.to)} (UTC). ${esc(WINDOW_SENTENCE)}</p>`,
|
|
913
|
+
`<p>Records in window: ${shown(report.recordCount)}. First record time: ${report.firstRecordMs === null ? "none" : String(report.firstRecordMs)}. Last record time: ${report.lastRecordMs === null ? "none" : String(report.lastRecordMs)}. Ledger head hash: ${esc(report.headHash ?? "none")}.</p>`,
|
|
914
|
+
"<h2>Decisions</h2>",
|
|
915
|
+
`<p>Total: ${shownCounts(report.decisions.total)}.</p>`,
|
|
916
|
+
"<table><thead><tr><th>Tool</th><th>Allow</th><th>Deny</th><th>Defer</th></tr></thead>",
|
|
917
|
+
`<tbody>${toolRows}</tbody></table>`,
|
|
918
|
+
`<p>No usable subject: ${shownCounts(report.decisions.withoutSubject)}.</p>`,
|
|
919
|
+
"<h2>Approvals</h2>",
|
|
920
|
+
`<p>Approved held calls: ${shown(a.approved)} (${shown(a.withOperatorSignatureFieldPresent)} with an operator signature field present, ${shown(a.withoutOperatorSignatureField)} without; signature field present is not a verified signature here). Closed without an allow: ${shown(a.closedWithoutAllow)}. Still held: ${shown(a.stillHeld)}. Unmatched: ${shown(a.unmatched)}. Held, and no bound answer found: ${shown(a.heldWithoutBoundAnswer)}. Terminals without bound inputs: ${shown(a.terminalsWithoutBoundInputs)}. Held record(s) that could have been answered by an unbound record: ${shown(a.heldPossiblyAnsweredByUnbound)}.${approvalsReason}</p>`,
|
|
921
|
+
"<p>Approved means the first signed bound answer after the defer, naming it and agreeing on request hash and tool, is an allow. Closed without an allow means that first answer is a deny (expired or otherwise). Still held means no signed bound answer exists and no later unbound record could have answered the defer; when a held defer could have been answered by an unbound record anywhere after it, still held is not established. Unmatched means the defer has no usable reference, shares it with another defer, or its bound answers disagree on request hash or tool.</p>",
|
|
922
|
+
...approvalsNote,
|
|
923
|
+
"<h2>Checkpoints</h2>",
|
|
924
|
+
`<p>Checkpoints in the window: ${shown(c.count)}. Anchor receipts verified: ${shown(c.withAnchorVerified)}. Anchor rows present, not checked (no anchor key): ${shown(c.anchorRowsPresentNotChecked)}.${anchorReason}</p>`,
|
|
925
|
+
"<h2>Verification</h2>",
|
|
926
|
+
problemsBlock,
|
|
927
|
+
"<h2>What this report does not show</h2>",
|
|
928
|
+
`<p>${esc(report.whatThisReportDoesNotShow)}</p>`,
|
|
929
|
+
`<p class="digest">Report digest (SHA-256 of the JSON form, the same bytes as --json): <code>${htmlEscape(digest)}</code></p>`,
|
|
930
|
+
"</body>",
|
|
931
|
+
"</html>",
|
|
932
|
+
"",
|
|
933
|
+
].join("\n");
|
|
934
|
+
}
|
|
935
|
+
export function renderReportText(report, digest) {
|
|
936
|
+
const lines = [];
|
|
937
|
+
const a = report.approvals;
|
|
938
|
+
const c = report.checkpoints;
|
|
939
|
+
lines.push(report.verification.verdict);
|
|
940
|
+
if (report.countsUnavailableReason !== null)
|
|
941
|
+
lines.push(unavailableSentence(report));
|
|
942
|
+
lines.push(`window ${report.from} .. ${report.to} (UTC)`);
|
|
943
|
+
lines.push(`window note ${WINDOW_SENTENCE}`);
|
|
944
|
+
lines.push(`records ${shown(report.recordCount)}`);
|
|
945
|
+
lines.push(`first ${report.firstRecordMs === null ? "none" : String(report.firstRecordMs)}`);
|
|
946
|
+
lines.push(`last ${report.lastRecordMs === null ? "none" : String(report.lastRecordMs)}`);
|
|
947
|
+
lines.push(`head ${report.headHash ?? "none"}`);
|
|
948
|
+
lines.push(`decisions ${shownCounts(report.decisions.total)}`);
|
|
949
|
+
if (report.decisions.byTool !== null) {
|
|
950
|
+
for (const tool of Object.keys(report.decisions.byTool).sort()) {
|
|
951
|
+
const t = report.decisions.byTool[tool];
|
|
952
|
+
lines.push(` ${tool} allow ${t.allow}, deny ${t.deny}, defer ${t.defer}`);
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
lines.push(`no usable subject ${shownCounts(report.decisions.withoutSubject)}`);
|
|
956
|
+
lines.push(`approvals approved ${shown(a.approved)} (signature field present ${shown(a.withOperatorSignatureFieldPresent)}, absent ${shown(a.withoutOperatorSignatureField)}), closed without an allow ${shown(a.closedWithoutAllow)}, still held ${shown(a.stillHeld)}, unmatched ${shown(a.unmatched)}`);
|
|
957
|
+
lines.push(`approvals held, and no bound answer found ${shown(a.heldWithoutBoundAnswer)}, terminals without bound inputs ${shown(a.terminalsWithoutBoundInputs)}, held record(s) that could have been answered by an unbound record ${shown(a.heldPossiblyAnsweredByUnbound)}`);
|
|
958
|
+
if (a.unavailableReason !== null)
|
|
959
|
+
lines.push(`approvals not available: ${a.unavailableReason}`);
|
|
960
|
+
lines.push("approvals mean: approved = first signed bound answer after the defer (naming it, same request hash and tool) is an allow; closed without an allow = that answer is a deny; still held = no signed bound answer and no later unbound record could have answered it (otherwise not available); unmatched = no usable ref, shared ref, or disagreeing bound answers; signature field present is not a verified signature");
|
|
961
|
+
if (report.unsignedApprovalsNote !== null)
|
|
962
|
+
lines.push(`note ${report.unsignedApprovalsNote}`);
|
|
963
|
+
lines.push(`checkpoints ${shown(c.count)} in window, anchor receipts verified ${shown(c.withAnchorVerified)}, anchor rows present not checked ${shown(c.anchorRowsPresentNotChecked)}`);
|
|
964
|
+
if (c.anchorUnavailableReason !== null)
|
|
965
|
+
lines.push(`anchors not available: ${c.anchorUnavailableReason}`);
|
|
966
|
+
if (report.verification.problems.length > 0) {
|
|
967
|
+
lines.push(`problems ${report.verification.problems.length} class(es); run verax verify on the machine for the detail`);
|
|
968
|
+
for (const p of report.verification.problems.slice(0, 50))
|
|
969
|
+
lines.push(` - ${p}`);
|
|
970
|
+
if (report.verification.problems.length > 50) {
|
|
971
|
+
lines.push(` ... and ${report.verification.problems.length - 50} more`);
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
lines.push("");
|
|
975
|
+
lines.push(`What this report does not show: ${report.whatThisReportDoesNotShow}`);
|
|
976
|
+
lines.push(`digest ${digest}`);
|
|
977
|
+
return lines.map((line) => terminalText(line)).join("\n");
|
|
978
|
+
}
|
|
979
|
+
function parseArgs(argv) {
|
|
980
|
+
const args = [...argv];
|
|
981
|
+
if (args.length === 0 || args[0] === "--help" || args[0] === "-h") {
|
|
982
|
+
return { ok: false, message: usage() };
|
|
983
|
+
}
|
|
984
|
+
let from;
|
|
985
|
+
let to;
|
|
986
|
+
let outPath = null;
|
|
987
|
+
let json = false;
|
|
988
|
+
const positionals = [];
|
|
989
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
990
|
+
const a = args[i];
|
|
991
|
+
if (a === "--json") {
|
|
992
|
+
json = true;
|
|
993
|
+
continue;
|
|
994
|
+
}
|
|
995
|
+
if (a === "--from") {
|
|
996
|
+
const v = args[i + 1];
|
|
997
|
+
if (!v || v.startsWith("-"))
|
|
998
|
+
return { ok: false, message: "report: --from needs a YYYY-MM-DD date" };
|
|
999
|
+
from = v;
|
|
1000
|
+
i += 1;
|
|
1001
|
+
continue;
|
|
1002
|
+
}
|
|
1003
|
+
if (a === "--to") {
|
|
1004
|
+
const v = args[i + 1];
|
|
1005
|
+
if (!v || v.startsWith("-"))
|
|
1006
|
+
return { ok: false, message: "report: --to needs a YYYY-MM-DD date" };
|
|
1007
|
+
to = v;
|
|
1008
|
+
i += 1;
|
|
1009
|
+
continue;
|
|
1010
|
+
}
|
|
1011
|
+
if (a === "--out") {
|
|
1012
|
+
const v = args[i + 1];
|
|
1013
|
+
if (!v || v.startsWith("-"))
|
|
1014
|
+
return { ok: false, message: "report: --out needs a file path" };
|
|
1015
|
+
outPath = v;
|
|
1016
|
+
i += 1;
|
|
1017
|
+
continue;
|
|
1018
|
+
}
|
|
1019
|
+
if (a.startsWith("-")) {
|
|
1020
|
+
return { ok: false, message: `report: unknown option ${a}` };
|
|
1021
|
+
}
|
|
1022
|
+
positionals.push(a);
|
|
1023
|
+
}
|
|
1024
|
+
if (positionals.length !== 1) {
|
|
1025
|
+
return { ok: false, message: "report: one ledger directory is required" };
|
|
1026
|
+
}
|
|
1027
|
+
if (from === undefined || to === undefined) {
|
|
1028
|
+
return { ok: false, message: "report: --from and --to are required (YYYY-MM-DD)" };
|
|
1029
|
+
}
|
|
1030
|
+
const fromMs = parseReportDate(from);
|
|
1031
|
+
const toStart = parseReportDate(to);
|
|
1032
|
+
if (fromMs === null || toStart === null) {
|
|
1033
|
+
return { ok: false, message: "report: --from and --to must be YYYY-MM-DD calendar dates" };
|
|
1034
|
+
}
|
|
1035
|
+
if (fromMs > toStart) {
|
|
1036
|
+
return { ok: false, message: "report: --from must not be after --to" };
|
|
1037
|
+
}
|
|
1038
|
+
return {
|
|
1039
|
+
ok: true,
|
|
1040
|
+
dir: positionals[0],
|
|
1041
|
+
from,
|
|
1042
|
+
to,
|
|
1043
|
+
fromMs,
|
|
1044
|
+
toExclusive: toStart + DAY_MS,
|
|
1045
|
+
json,
|
|
1046
|
+
outPath,
|
|
1047
|
+
};
|
|
1048
|
+
}
|
|
1049
|
+
export async function runReport(argv, out = (s) => process.stdout.write(`${s}\n`),
|
|
1050
|
+
/** Test-only: force the exclusive-create temp path. Not a CLI flag. */
|
|
1051
|
+
opts) {
|
|
1052
|
+
const parsed = parseArgs(argv);
|
|
1053
|
+
if (!parsed.ok) {
|
|
1054
|
+
out(parsed.message.startsWith("usage:") ? parsed.message : terminalText(parsed.message));
|
|
1055
|
+
return argv.length === 0 || argv[0] === "--help" || argv[0] === "-h" ? (argv.length === 0 ? EX_USAGE : 0) : EX_USAGE;
|
|
1056
|
+
}
|
|
1057
|
+
// Before any compute or write: the report must not land inside the ledger.
|
|
1058
|
+
if (parsed.outPath !== null && outInsideStateDir(parsed.dir, parsed.outPath)) {
|
|
1059
|
+
out("report: --out must not be inside the state directory");
|
|
1060
|
+
return EX_USAGE;
|
|
1061
|
+
}
|
|
1062
|
+
let report;
|
|
1063
|
+
try {
|
|
1064
|
+
report = await buildPeriodReport(parsed.dir, parsed.from, parsed.to, parsed.fromMs, parsed.toExclusive);
|
|
1065
|
+
}
|
|
1066
|
+
catch (err) {
|
|
1067
|
+
report = unverifiedReport(parsed.from, parsed.to, classOfThrown(err, "ledger-unreadable"));
|
|
1068
|
+
}
|
|
1069
|
+
const json = serializePeriodReport(report);
|
|
1070
|
+
const digest = reportDigest(json);
|
|
1071
|
+
if (parsed.outPath !== null) {
|
|
1072
|
+
try {
|
|
1073
|
+
writeOutExclusive(parsed.outPath, renderReportHtml(report, digest), opts?.writeTempPath);
|
|
1074
|
+
}
|
|
1075
|
+
catch (err) {
|
|
1076
|
+
const code = err.code;
|
|
1077
|
+
if (code === "EEXIST") {
|
|
1078
|
+
out(terminalText(`report: refusing to overwrite ${basename(parsed.outPath)}`));
|
|
1079
|
+
return EX_USAGE;
|
|
1080
|
+
}
|
|
1081
|
+
out(terminalText(`report: could not write ${basename(parsed.outPath)}`));
|
|
1082
|
+
return EX_USAGE;
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
if (parsed.json) {
|
|
1086
|
+
out(json);
|
|
1087
|
+
}
|
|
1088
|
+
else if (parsed.outPath === null) {
|
|
1089
|
+
out(renderReportText(report, digest));
|
|
1090
|
+
}
|
|
1091
|
+
else {
|
|
1092
|
+
out(terminalText(`wrote ${basename(parsed.outPath)}`));
|
|
1093
|
+
out(terminalText(`digest ${digest}`));
|
|
1094
|
+
}
|
|
1095
|
+
if (report.verification.ok)
|
|
1096
|
+
return 0;
|
|
1097
|
+
// Match verax verify: an unreadable directory is 77, not the generic verify-failed 1.
|
|
1098
|
+
if (report.verification.problems.includes("state-unreadable"))
|
|
1099
|
+
return EX_STATE_UNREADABLE;
|
|
1100
|
+
return EX_VERIFY_FAILED;
|
|
1101
|
+
}
|