@verax-ai/proxy 0.4.0 → 0.4.2
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/approvals.d.ts +3 -1
- package/dist/approvals.js +10 -2
- package/dist/control-sync.d.ts +49 -0
- package/dist/control-sync.js +364 -0
- package/dist/index.d.ts +2 -1
- package/dist/ledger.d.ts +11 -0
- package/dist/ledger.js +52 -32
- package/dist/proxy.d.ts +1 -0
- package/dist/proxy.js +53 -0
- package/dist/types.d.ts +36 -0
- package/dist/verify-ledger.d.ts +8 -0
- package/dist/verify-ledger.js +69 -0
- package/package.json +1 -1
package/dist/approvals.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ export declare const approvalFs: {
|
|
|
6
6
|
export declare const drainMetrics: {
|
|
7
7
|
renameBusy: number;
|
|
8
8
|
};
|
|
9
|
-
import type { ApprovalChannel, InputsLog, Ledger, Policy, RecordSigner } from "./types.ts";
|
|
9
|
+
import type { ApprovalChannel, ApprovalSignature, InputsLog, Ledger, Policy, RecordSigner } from "./types.ts";
|
|
10
10
|
export type ApprovalRow = {
|
|
11
11
|
ref: string;
|
|
12
12
|
requestHash: string;
|
|
@@ -106,6 +106,8 @@ export declare function approvePending(opts: {
|
|
|
106
106
|
policyHash: string;
|
|
107
107
|
approvals: ApprovalsLog;
|
|
108
108
|
inputsLog?: InputsLog;
|
|
109
|
+
/** Set only for an HTTP approval whose passkey assertion already verified. */
|
|
110
|
+
signature?: ApprovalSignature;
|
|
109
111
|
budgetGuard?: (snap: ApprovalRow) => {
|
|
110
112
|
ok: true;
|
|
111
113
|
} | {
|
package/dist/approvals.js
CHANGED
|
@@ -220,6 +220,14 @@ async function hasResolves(inputsLog, ledger, deferRef) {
|
|
|
220
220
|
export async function approvePending(opts) {
|
|
221
221
|
return approvalLockFor(opts.ledger).enqueue(() => approvePendingUnlocked(opts));
|
|
222
222
|
}
|
|
223
|
+
function approverInputs(opts) {
|
|
224
|
+
return {
|
|
225
|
+
id: opts.approverId,
|
|
226
|
+
via: opts.via,
|
|
227
|
+
resolves: opts.ref,
|
|
228
|
+
...(opts.signature ? { signature: opts.signature } : {}),
|
|
229
|
+
};
|
|
230
|
+
}
|
|
223
231
|
function ledgerStateDir(ledger) {
|
|
224
232
|
const dir = ledger.dir;
|
|
225
233
|
return typeof dir === "string" && dir !== "" ? dir : null;
|
|
@@ -268,7 +276,7 @@ async function approvePendingUnlocked(opts) {
|
|
|
268
276
|
const inputs = {
|
|
269
277
|
principal: prior?.principal ?? { brain: snap.brain, scopes: [] },
|
|
270
278
|
inputs: prior?.inputs ?? [],
|
|
271
|
-
approver:
|
|
279
|
+
approver: approverInputs(opts),
|
|
272
280
|
};
|
|
273
281
|
const inputsHash = sha256Canonical(inputs);
|
|
274
282
|
await inputsLog.append(expireRef, inputs);
|
|
@@ -303,7 +311,7 @@ async function approvePendingUnlocked(opts) {
|
|
|
303
311
|
const inputs = {
|
|
304
312
|
principal: prior?.principal ?? { brain: snap.brain, scopes: [] },
|
|
305
313
|
inputs: prior?.inputs ?? [],
|
|
306
|
-
approver:
|
|
314
|
+
approver: approverInputs(opts),
|
|
307
315
|
};
|
|
308
316
|
const inputsHash = sha256Canonical(inputs);
|
|
309
317
|
const effectHash = sha256Canonical(effectDescriptor(snap.subject, snap.args));
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { SignedDecisionRecord } from "@cedulon/core";
|
|
2
|
+
import type { LedgerWriter } from "./ledger.ts";
|
|
3
|
+
import type { InputsLog, RecordSigner } from "./types.ts";
|
|
4
|
+
/** `null` means `halt-history.jsonl` was absent. Content is not part of the stamp. */
|
|
5
|
+
type HistoryStamp = {
|
|
6
|
+
size: number;
|
|
7
|
+
mtimeMs: number;
|
|
8
|
+
} | null;
|
|
9
|
+
type Recorded = {
|
|
10
|
+
mismatched: boolean;
|
|
11
|
+
hasMismatch: boolean;
|
|
12
|
+
seenMismatch: boolean;
|
|
13
|
+
resumeFrom: number;
|
|
14
|
+
maxLine: number;
|
|
15
|
+
maxAfterAck: number;
|
|
16
|
+
fileHaltCovers: boolean;
|
|
17
|
+
/** Last control allow is a halt, so a halt window is open. */
|
|
18
|
+
openHalt: boolean;
|
|
19
|
+
hashesByLine: Map<number, string[]>;
|
|
20
|
+
};
|
|
21
|
+
export type ControlMemory = {
|
|
22
|
+
loaded: boolean;
|
|
23
|
+
recorded: Recorded;
|
|
24
|
+
stamp: HistoryStamp;
|
|
25
|
+
haltedPresent: boolean | null;
|
|
26
|
+
};
|
|
27
|
+
export declare function createControlMemory(): ControlMemory;
|
|
28
|
+
/**
|
|
29
|
+
* True when the history file and the switch look as they did at the last sync,
|
|
30
|
+
* so there is nothing to record. Cheap enough to run before taking the ledger
|
|
31
|
+
* queue: waiting a turn behind the previous call's durable writes only to find
|
|
32
|
+
* nothing changed doubled the cost of a call. Only `syncHaltControl` updates
|
|
33
|
+
* `memory`, inside the queue, and it checks again there.
|
|
34
|
+
*/
|
|
35
|
+
export declare function controlUnchanged(stateDir: string, memory: ControlMemory): boolean;
|
|
36
|
+
export declare function syncHaltControl(opts: {
|
|
37
|
+
stateDir: string;
|
|
38
|
+
now: () => number;
|
|
39
|
+
nonce: () => string;
|
|
40
|
+
policyHash: string;
|
|
41
|
+
recordSigner: RecordSigner;
|
|
42
|
+
inputsLog: InputsLog;
|
|
43
|
+
decisions: () => Promise<SignedDecisionRecord[]>;
|
|
44
|
+
memory: ControlMemory;
|
|
45
|
+
writer: LedgerWriter;
|
|
46
|
+
/** Test seam: runs just before the history file is read. */
|
|
47
|
+
beforeHistoryRead?: () => void;
|
|
48
|
+
}): Promise<void>;
|
|
49
|
+
export {};
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { signDecisionRecord } from "@cedulon/core";
|
|
4
|
+
import { sha256Canonical } from "./hash.js";
|
|
5
|
+
/**
|
|
6
|
+
* Same file names as `packages/body/src/halt.ts`. The history file stays plain
|
|
7
|
+
* text; this module copies each line into the ledger as a signed control record.
|
|
8
|
+
* A CLI halt is not in the ledger until the body opens, the HTTP door syncs,
|
|
9
|
+
* or the next call. That delay is real.
|
|
10
|
+
*
|
|
11
|
+
* The body is the only ledger writer, and the ledger lock keeps it that way.
|
|
12
|
+
* After this proxy opens, no other process appends decisions. The first sync
|
|
13
|
+
* reads the ledger once; later syncs trust the snapshot held in the proxy
|
|
14
|
+
* closure and only reread `halt-history.jsonl` when its size or mtime changed
|
|
15
|
+
* or the `halted` switch appeared or disappeared.
|
|
16
|
+
*
|
|
17
|
+
* A switch with no history halt is one `via: "file"` halt. Deleting that
|
|
18
|
+
* switch while the last control record is still a halt, and while history has
|
|
19
|
+
* no resume that closes that window, is one symmetric `via: "file"` resume.
|
|
20
|
+
* The proxy catches a sync throw, leaves this snapshot unloaded, and lets the
|
|
21
|
+
* call continue; halt and rate limits stay fail-closed on their own path.
|
|
22
|
+
*/
|
|
23
|
+
const HALT_SWITCH = "halted";
|
|
24
|
+
const HALT_HISTORY = "halt-history.jsonl";
|
|
25
|
+
const CONTROL_EFFECT = "verax.control";
|
|
26
|
+
export function createControlMemory() {
|
|
27
|
+
return {
|
|
28
|
+
loaded: false,
|
|
29
|
+
recorded: {
|
|
30
|
+
mismatched: false,
|
|
31
|
+
hasMismatch: false,
|
|
32
|
+
seenMismatch: false,
|
|
33
|
+
resumeFrom: 0,
|
|
34
|
+
maxLine: -1,
|
|
35
|
+
maxAfterAck: -1,
|
|
36
|
+
fileHaltCovers: false,
|
|
37
|
+
openHalt: false,
|
|
38
|
+
hashesByLine: new Map(),
|
|
39
|
+
},
|
|
40
|
+
stamp: null,
|
|
41
|
+
haltedPresent: null,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* True when the history file and the switch look as they did at the last sync,
|
|
46
|
+
* so there is nothing to record. Cheap enough to run before taking the ledger
|
|
47
|
+
* queue: waiting a turn behind the previous call's durable writes only to find
|
|
48
|
+
* nothing changed doubled the cost of a call. Only `syncHaltControl` updates
|
|
49
|
+
* `memory`, inside the queue, and it checks again there.
|
|
50
|
+
*/
|
|
51
|
+
export function controlUnchanged(stateDir, memory) {
|
|
52
|
+
return (memory.loaded &&
|
|
53
|
+
sameStamp(memory.stamp, historyStamp(stateDir)) &&
|
|
54
|
+
memory.haltedPresent === existsSync(join(stateDir, HALT_SWITCH)));
|
|
55
|
+
}
|
|
56
|
+
export async function syncHaltControl(opts) {
|
|
57
|
+
const memory = opts.memory;
|
|
58
|
+
if (memory.loaded &&
|
|
59
|
+
sameStamp(memory.stamp, historyStamp(opts.stateDir)) &&
|
|
60
|
+
memory.haltedPresent === existsSync(join(opts.stateDir, HALT_SWITCH))) {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
// Read the history first and the switch after it. haltBody creates the
|
|
64
|
+
// switch before it writes its line, so a halt line read here means the
|
|
65
|
+
// switch already existed; reading the switch first let a halt that landed
|
|
66
|
+
// in between look like a hand-removed switch and wrote a resume while the
|
|
67
|
+
// body was halted. If the history changed while it was read, read again.
|
|
68
|
+
let stamp = historyStamp(opts.stateDir);
|
|
69
|
+
let history = [];
|
|
70
|
+
let haltedPresent = false;
|
|
71
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
72
|
+
opts.beforeHistoryRead?.();
|
|
73
|
+
history = readHistory(opts.stateDir);
|
|
74
|
+
haltedPresent = existsSync(join(opts.stateDir, HALT_SWITCH));
|
|
75
|
+
const after = historyStamp(opts.stateDir);
|
|
76
|
+
if (sameStamp(stamp, after))
|
|
77
|
+
break;
|
|
78
|
+
stamp = after;
|
|
79
|
+
}
|
|
80
|
+
if (!memory.loaded) {
|
|
81
|
+
memory.recorded = await readRecorded(opts, history);
|
|
82
|
+
memory.loaded = true;
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
markMismatch(memory.recorded, history);
|
|
86
|
+
}
|
|
87
|
+
const recorded = memory.recorded;
|
|
88
|
+
try {
|
|
89
|
+
let cursor;
|
|
90
|
+
if (recorded.mismatched && !recorded.hasMismatch) {
|
|
91
|
+
await writeMismatch(opts, history.length);
|
|
92
|
+
recorded.hasMismatch = true;
|
|
93
|
+
recorded.seenMismatch = true;
|
|
94
|
+
recorded.resumeFrom = history.length;
|
|
95
|
+
recorded.maxAfterAck = history.length - 1;
|
|
96
|
+
cursor = history.length;
|
|
97
|
+
}
|
|
98
|
+
else if (recorded.mismatched) {
|
|
99
|
+
cursor = recorded.maxAfterAck + 1;
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
cursor = recorded.maxLine + 1;
|
|
103
|
+
}
|
|
104
|
+
let wroteHistory = false;
|
|
105
|
+
for (let i = cursor; i < history.length; i += 1) {
|
|
106
|
+
const raw = history[i];
|
|
107
|
+
const lineHash = sha256Canonical(raw);
|
|
108
|
+
const known = recorded.hashesByLine.get(i);
|
|
109
|
+
if (known?.includes(lineHash))
|
|
110
|
+
continue;
|
|
111
|
+
const event = parseHistoryLine(raw, i);
|
|
112
|
+
if (!event)
|
|
113
|
+
continue;
|
|
114
|
+
await writeControlAllow(opts, event, lineHash);
|
|
115
|
+
wroteHistory = true;
|
|
116
|
+
noteHistoryAllow(recorded, i, lineHash);
|
|
117
|
+
recorded.openHalt = event.action === "halt";
|
|
118
|
+
}
|
|
119
|
+
const needFile = haltedPresent && lastAction(history) !== "halt";
|
|
120
|
+
if (needFile && (wroteHistory || !recorded.fileHaltCovers)) {
|
|
121
|
+
await writeControlAllow(opts, { action: "halt", atMs: opts.now(), by: "unknown", via: "file", line: -1 }, sha256Canonical({ via: "file", line: -1 }));
|
|
122
|
+
recorded.fileHaltCovers = true;
|
|
123
|
+
recorded.openHalt = true;
|
|
124
|
+
}
|
|
125
|
+
// The switch is gone and the last control record is still a halt. A
|
|
126
|
+
// history resume that closed this window has already cleared `openHalt`.
|
|
127
|
+
// One file resume, symmetric with the file halt, and not repeated while
|
|
128
|
+
// the window stays closed.
|
|
129
|
+
if (!haltedPresent && recorded.openHalt) {
|
|
130
|
+
await writeControlAllow(opts, { action: "resume", atMs: opts.now(), by: "unknown", via: "file", line: -1 }, sha256Canonical({ via: "file", line: -1 }));
|
|
131
|
+
recorded.fileHaltCovers = false;
|
|
132
|
+
recorded.openHalt = false;
|
|
133
|
+
}
|
|
134
|
+
memory.stamp = stamp;
|
|
135
|
+
memory.haltedPresent = haltedPresent;
|
|
136
|
+
}
|
|
137
|
+
catch (err) {
|
|
138
|
+
// A partial append is already on disk. Drop the snapshot so the next sync
|
|
139
|
+
// reads the ledger once and does not write that line again.
|
|
140
|
+
memory.loaded = false;
|
|
141
|
+
throw err;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function historyStamp(stateDir) {
|
|
145
|
+
try {
|
|
146
|
+
const st = statSync(join(stateDir, HALT_HISTORY));
|
|
147
|
+
return { size: st.size, mtimeMs: st.mtimeMs };
|
|
148
|
+
}
|
|
149
|
+
catch (err) {
|
|
150
|
+
if (err.code === "ENOENT")
|
|
151
|
+
return null;
|
|
152
|
+
throw err;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
function sameStamp(a, b) {
|
|
156
|
+
if (a === null || b === null)
|
|
157
|
+
return a === b;
|
|
158
|
+
return a.size === b.size && a.mtimeMs === b.mtimeMs;
|
|
159
|
+
}
|
|
160
|
+
function noteHistoryAllow(recorded, line, lineHash) {
|
|
161
|
+
recorded.fileHaltCovers = false;
|
|
162
|
+
const bag = recorded.hashesByLine.get(line) ?? [];
|
|
163
|
+
bag.push(lineHash);
|
|
164
|
+
recorded.hashesByLine.set(line, bag);
|
|
165
|
+
if (line > recorded.maxLine)
|
|
166
|
+
recorded.maxLine = line;
|
|
167
|
+
if (recorded.seenMismatch && line >= recorded.resumeFrom && line > recorded.maxAfterAck) {
|
|
168
|
+
recorded.maxAfterAck = line;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function markMismatch(recorded, history) {
|
|
172
|
+
let mismatched = recorded.maxLine > history.length;
|
|
173
|
+
for (const [line, hashes] of recorded.hashesByLine) {
|
|
174
|
+
if (line >= history.length) {
|
|
175
|
+
mismatched = true;
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
const nowHash = sha256Canonical(history[line]);
|
|
179
|
+
if (hashes.some((hash) => hash !== nowHash))
|
|
180
|
+
mismatched = true;
|
|
181
|
+
}
|
|
182
|
+
recorded.mismatched = mismatched;
|
|
183
|
+
}
|
|
184
|
+
function readHistory(stateDir) {
|
|
185
|
+
let text;
|
|
186
|
+
try {
|
|
187
|
+
text = readFileSync(join(stateDir, HALT_HISTORY), "utf8");
|
|
188
|
+
}
|
|
189
|
+
catch (err) {
|
|
190
|
+
if (err.code === "ENOENT")
|
|
191
|
+
return [];
|
|
192
|
+
throw err;
|
|
193
|
+
}
|
|
194
|
+
return text
|
|
195
|
+
.split("\n")
|
|
196
|
+
.map((line) => line.replace(/\r$/, ""))
|
|
197
|
+
.filter((line) => line.trim() !== "");
|
|
198
|
+
}
|
|
199
|
+
function parseHistoryLine(raw, line) {
|
|
200
|
+
let row;
|
|
201
|
+
try {
|
|
202
|
+
row = JSON.parse(raw);
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
if (row.action !== "halt" && row.action !== "resume")
|
|
208
|
+
return null;
|
|
209
|
+
// A line that names no finite time or an implausible actor is not copied into a signed record.
|
|
210
|
+
if (typeof row.atMs !== "number" || !Number.isFinite(row.atMs))
|
|
211
|
+
return null;
|
|
212
|
+
if (typeof row.by !== "string" || row.by.length === 0 || row.by.length > 256)
|
|
213
|
+
return null;
|
|
214
|
+
const via = row.via === "http" ? "http" : row.via === "file" ? "file" : "cli";
|
|
215
|
+
return { action: row.action, atMs: row.atMs, by: row.by, via, line };
|
|
216
|
+
}
|
|
217
|
+
function lastAction(lines) {
|
|
218
|
+
for (let i = lines.length - 1; i >= 0; i -= 1) {
|
|
219
|
+
const event = parseHistoryLine(lines[i], i);
|
|
220
|
+
if (event)
|
|
221
|
+
return event.action;
|
|
222
|
+
}
|
|
223
|
+
return null;
|
|
224
|
+
}
|
|
225
|
+
async function readRecorded(opts, history) {
|
|
226
|
+
const hashesByLine = new Map();
|
|
227
|
+
let maxLine = -1;
|
|
228
|
+
let hasMismatch = false;
|
|
229
|
+
let fileHaltCovers = false;
|
|
230
|
+
let openHalt = false;
|
|
231
|
+
let seenMismatch = false;
|
|
232
|
+
let resumeFrom = 0;
|
|
233
|
+
let maxAfterAck = -1;
|
|
234
|
+
for (const decision of await opts.decisions()) {
|
|
235
|
+
const reason = decision.claims.reasonCode;
|
|
236
|
+
const subject = decision.claims.subject;
|
|
237
|
+
const ref = decision.claims.ref;
|
|
238
|
+
if (reason !== "halt-history-mismatch" && subject !== "verax.halt" && subject !== "verax.resume") {
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
if (typeof ref !== "string")
|
|
242
|
+
continue;
|
|
243
|
+
const inputs = await opts.inputsLog.get(ref);
|
|
244
|
+
const control = inputs?.control;
|
|
245
|
+
if (reason === "halt-history-mismatch") {
|
|
246
|
+
hasMismatch = true;
|
|
247
|
+
seenMismatch = true;
|
|
248
|
+
resumeFrom = typeof control?.line === "number" ? control.line : 0;
|
|
249
|
+
maxAfterAck = resumeFrom - 1;
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
if (decision.claims.decision !== "allow" || !control)
|
|
253
|
+
continue;
|
|
254
|
+
if (control.line === -1 && control.via === "file" && (subject === "verax.halt" || subject === "verax.resume")) {
|
|
255
|
+
const halt = subject === "verax.halt";
|
|
256
|
+
fileHaltCovers = halt;
|
|
257
|
+
openHalt = halt;
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
if (typeof control.line !== "number" || control.line < 0)
|
|
261
|
+
continue;
|
|
262
|
+
if (subject !== "verax.halt" && subject !== "verax.resume")
|
|
263
|
+
continue;
|
|
264
|
+
fileHaltCovers = false;
|
|
265
|
+
openHalt = subject === "verax.halt";
|
|
266
|
+
const bag = hashesByLine.get(control.line) ?? [];
|
|
267
|
+
if (typeof control.lineHash === "string")
|
|
268
|
+
bag.push(control.lineHash);
|
|
269
|
+
hashesByLine.set(control.line, bag);
|
|
270
|
+
if (control.line > maxLine)
|
|
271
|
+
maxLine = control.line;
|
|
272
|
+
if (seenMismatch && control.line >= resumeFrom && control.line > maxAfterAck) {
|
|
273
|
+
maxAfterAck = control.line;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
const recorded = {
|
|
277
|
+
mismatched: false,
|
|
278
|
+
hasMismatch,
|
|
279
|
+
seenMismatch,
|
|
280
|
+
resumeFrom,
|
|
281
|
+
maxLine,
|
|
282
|
+
maxAfterAck,
|
|
283
|
+
fileHaltCovers,
|
|
284
|
+
openHalt,
|
|
285
|
+
hashesByLine,
|
|
286
|
+
};
|
|
287
|
+
markMismatch(recorded, history);
|
|
288
|
+
return recorded;
|
|
289
|
+
}
|
|
290
|
+
async function writeMismatch(opts, resumeFrom) {
|
|
291
|
+
const atMs = opts.now();
|
|
292
|
+
const control = {
|
|
293
|
+
action: "halt",
|
|
294
|
+
by: "unknown",
|
|
295
|
+
via: "file",
|
|
296
|
+
atMs,
|
|
297
|
+
line: resumeFrom,
|
|
298
|
+
lineHash: sha256Canonical("halt-history-mismatch"),
|
|
299
|
+
};
|
|
300
|
+
await writeDecision(opts, {
|
|
301
|
+
decision: "deny",
|
|
302
|
+
subject: CONTROL_EFFECT,
|
|
303
|
+
reasonCode: "halt-history-mismatch",
|
|
304
|
+
effectClass: CONTROL_EFFECT,
|
|
305
|
+
effectHash: null,
|
|
306
|
+
requestHash: sha256Canonical({ mismatch: "halt-history", resumeFrom }),
|
|
307
|
+
timestampMs: atMs,
|
|
308
|
+
control,
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
async function writeControlAllow(opts, event, lineHash) {
|
|
312
|
+
const body = {
|
|
313
|
+
action: event.action,
|
|
314
|
+
atMs: event.atMs,
|
|
315
|
+
by: event.by,
|
|
316
|
+
via: event.via,
|
|
317
|
+
line: event.line,
|
|
318
|
+
};
|
|
319
|
+
const bound = sha256Canonical(body);
|
|
320
|
+
const ref = await writeDecision(opts, {
|
|
321
|
+
decision: "allow",
|
|
322
|
+
subject: event.action === "halt" ? "verax.halt" : "verax.resume",
|
|
323
|
+
reasonCode: event.action === "halt" ? "operator-halt" : "operator-resume",
|
|
324
|
+
effectClass: CONTROL_EFFECT,
|
|
325
|
+
effectHash: bound,
|
|
326
|
+
requestHash: bound,
|
|
327
|
+
timestampMs: event.atMs,
|
|
328
|
+
control: { ...body, lineHash },
|
|
329
|
+
});
|
|
330
|
+
const row = {
|
|
331
|
+
ref,
|
|
332
|
+
effectHash: bound,
|
|
333
|
+
effectClass: CONTROL_EFFECT,
|
|
334
|
+
timestampMs: event.atMs,
|
|
335
|
+
actor: event.by,
|
|
336
|
+
};
|
|
337
|
+
await opts.writer.appendEffect(row, "self", bound);
|
|
338
|
+
}
|
|
339
|
+
async function writeDecision(opts, row) {
|
|
340
|
+
const ref = opts.nonce();
|
|
341
|
+
const inputs = {
|
|
342
|
+
principal: { brain: "verax-proxy", scopes: [] },
|
|
343
|
+
inputs: [],
|
|
344
|
+
control: row.control,
|
|
345
|
+
};
|
|
346
|
+
const inputsHash = sha256Canonical(inputs);
|
|
347
|
+
await opts.inputsLog.append(ref, inputs);
|
|
348
|
+
await opts.writer.appendDecisionChained((prevRecordHash) => signDecisionRecord({
|
|
349
|
+
decider: "verax-proxy",
|
|
350
|
+
subject: row.subject,
|
|
351
|
+
requestHash: row.requestHash,
|
|
352
|
+
policyHash: opts.policyHash,
|
|
353
|
+
inputsHash,
|
|
354
|
+
decision: row.decision,
|
|
355
|
+
reasonCode: row.reasonCode,
|
|
356
|
+
ref,
|
|
357
|
+
effectHash: row.effectHash,
|
|
358
|
+
effectClass: row.effectClass,
|
|
359
|
+
timestampMs: row.timestampMs,
|
|
360
|
+
nonce: ref,
|
|
361
|
+
prevRecordHash,
|
|
362
|
+
}, opts.recordSigner.privateKeyPem, opts.recordSigner.publicKeyPem));
|
|
363
|
+
return ref;
|
|
364
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -13,6 +13,7 @@ export { spokenReason } from "./spoken-reason.ts";
|
|
|
13
13
|
export type { ApprovalRow, ApproveResult } from "./approvals.ts";
|
|
14
14
|
export type { CardCsvOpts, ChannelRow, ReconcileReport } from "./reconcile.ts";
|
|
15
15
|
export type { FileLedgerOpts, LedgerCounts } from "./ledger.ts";
|
|
16
|
+
export type { ApprovalSignature } from "./types.ts";
|
|
16
17
|
export type { EffectSigner, ExplainChain, ExplainPair, ExplainFinding, ExplainOpts, ExplainResult, ExplainTrustRoot, ExplainWarning, ExtractWindow, Ledger, LedgerEffect, Policy, PolicyDecision, Principal, ProxyDeps, RecordSigner, ToolCall, ToolResult, WitnessClass, } from "./types.ts";
|
|
17
18
|
export { verifyLedger } from "./verify-ledger.ts";
|
|
18
|
-
export type { VerifyResult, VerifyOptions, VerifyTrust } from "./verify-ledger.ts";
|
|
19
|
+
export type { VerifyResult, VerifyOptions, VerifyTrust, VerifyControl } from "./verify-ledger.ts";
|
package/dist/ledger.d.ts
CHANGED
|
@@ -11,6 +11,11 @@ import { type TailVisit } from "./jsonl-tail.ts";
|
|
|
11
11
|
import type { DecisionInputs, EffectSigner, ExtractWindow, Ledger, LedgerEffect, WitnessClass } from "./types.ts";
|
|
12
12
|
import type { DecisionKind, SignedDecisionRecord } from "@cedulon/core";
|
|
13
13
|
export type PermissionCheck = "owner-only" | "not checked on this platform";
|
|
14
|
+
/** Appends that already hold the ledger queue. Calling the public methods from here deadlocks. */
|
|
15
|
+
export type LedgerWriter = {
|
|
16
|
+
appendDecisionChained(build: (prevRecordHash: string | null) => SignedDecisionRecord): Promise<void>;
|
|
17
|
+
appendEffect(row: EffectRow, witnessClass: WitnessClass, resultHash?: string): Promise<void>;
|
|
18
|
+
};
|
|
14
19
|
/**
|
|
15
20
|
* A ledger file read from its end through the same seam the reads above use,
|
|
16
21
|
* so a test can count what a window costs.
|
|
@@ -63,6 +68,9 @@ export declare class MemoryLedger implements Ledger {
|
|
|
63
68
|
hasPrimaryEffect(ref: string): boolean;
|
|
64
69
|
appendDecision(signed: SignedDecisionRecord): Promise<void>;
|
|
65
70
|
appendDecisionChained(build: (prevRecordHash: string | null) => SignedDecisionRecord): Promise<void>;
|
|
71
|
+
private appendDecisionChainedUnlocked;
|
|
72
|
+
/** One turn of this ledger's queue: read a cursor and append without a second writer seeing the same cursor. */
|
|
73
|
+
exclusive<T>(fn: (writer: LedgerWriter) => Promise<T>): Promise<T>;
|
|
66
74
|
appendEffect(row: EffectRow, witnessClass?: WitnessClass, resultHash?: string): Promise<void>;
|
|
67
75
|
private appendEffectUnlocked;
|
|
68
76
|
decisions(): Promise<SignedDecisionRecord[]>;
|
|
@@ -163,6 +171,9 @@ export declare class FileLedger implements Ledger {
|
|
|
163
171
|
close(): void;
|
|
164
172
|
appendDecision(signed: SignedDecisionRecord): Promise<void>;
|
|
165
173
|
appendDecisionChained(build: (prevRecordHash: string | null) => SignedDecisionRecord): Promise<void>;
|
|
174
|
+
private appendDecisionChainedUnlocked;
|
|
175
|
+
/** One turn of this ledger's queue: read a cursor and append without a second writer seeing the same cursor. */
|
|
176
|
+
exclusive<T>(fn: (writer: LedgerWriter) => Promise<T>): Promise<T>;
|
|
166
177
|
/**
|
|
167
178
|
* What /healthz reports, from memory: the counts are kept on load and on
|
|
168
179
|
* every append. Rereading both files to count lines cost a second per call
|
package/dist/ledger.js
CHANGED
|
@@ -190,6 +190,9 @@ function noteReauth(map, row) {
|
|
|
190
190
|
map.set(row.requestHash, row.ref);
|
|
191
191
|
}
|
|
192
192
|
function noteCounted(times, row) {
|
|
193
|
+
// A halt or resume is not a tool call. Counting it would spend the rate budget on the switch.
|
|
194
|
+
if (row.reasonCode === "operator-halt" || row.reasonCode === "operator-resume")
|
|
195
|
+
return;
|
|
193
196
|
if (row.decision === "allow" || row.decision === "defer")
|
|
194
197
|
times.push(row.timestampMs);
|
|
195
198
|
}
|
|
@@ -239,17 +242,25 @@ export class MemoryLedger {
|
|
|
239
242
|
});
|
|
240
243
|
}
|
|
241
244
|
async appendDecisionChained(build) {
|
|
242
|
-
return this.q.enqueue(
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
245
|
+
return this.q.enqueue(() => this.appendDecisionChainedUnlocked(build));
|
|
246
|
+
}
|
|
247
|
+
async appendDecisionChainedUnlocked(build) {
|
|
248
|
+
const last = this._decisions[this._decisions.length - 1];
|
|
249
|
+
const signed = build(last ? decisionRecordHash(last) : null);
|
|
250
|
+
this._decisions.push(signed);
|
|
251
|
+
const row = indexRowOf(signed);
|
|
252
|
+
if (row) {
|
|
253
|
+
this.byRef.set(row.ref, row);
|
|
254
|
+
noteReauth(this.reauthByHash, row);
|
|
255
|
+
noteCounted(this.countedAt, row);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
/** One turn of this ledger's queue: read a cursor and append without a second writer seeing the same cursor. */
|
|
259
|
+
async exclusive(fn) {
|
|
260
|
+
return this.q.enqueue(() => fn({
|
|
261
|
+
appendDecisionChained: (build) => this.appendDecisionChainedUnlocked(build),
|
|
262
|
+
appendEffect: (row, witnessClass, resultHash) => this.appendEffectUnlocked(row, witnessClass, resultHash),
|
|
263
|
+
}));
|
|
253
264
|
}
|
|
254
265
|
async appendEffect(row, witnessClass = DEFAULT_WITNESS, resultHash) {
|
|
255
266
|
return this.q.enqueue(async () => this.appendEffectUnlocked(row, witnessClass, resultHash));
|
|
@@ -797,27 +808,35 @@ export class FileLedger {
|
|
|
797
808
|
});
|
|
798
809
|
}
|
|
799
810
|
async appendDecisionChained(build) {
|
|
800
|
-
return this.q.enqueue(
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
811
|
+
return this.q.enqueue(() => this.appendDecisionChainedUnlocked(build));
|
|
812
|
+
}
|
|
813
|
+
async appendDecisionChainedUnlocked(build) {
|
|
814
|
+
this.assertOwned();
|
|
815
|
+
const prev = await this.lastDecisionHashUnlocked();
|
|
816
|
+
await mkdir(this.dir, { recursive: true, mode: 0o700 });
|
|
817
|
+
const signed = build(prev);
|
|
818
|
+
const line = lineOf(signed);
|
|
819
|
+
await appendDurable(this.decisionsPath, line);
|
|
820
|
+
await this.pulse("decisions.jsonl", line, "decision");
|
|
821
|
+
this.tailHash = decisionRecordHash(signed);
|
|
822
|
+
this.lastDecisionMs = signed.claims.timestampMs;
|
|
823
|
+
this.noteActiveStamp(signed.claims.timestampMs);
|
|
824
|
+
this.activeDecisionN += 1;
|
|
825
|
+
const row = indexRowOf(signed);
|
|
826
|
+
if (row) {
|
|
827
|
+
this.byRef.set(row.ref, row);
|
|
828
|
+
noteReauth(this.reauthByHash, row);
|
|
829
|
+
noteCounted(this.countedAt, row);
|
|
830
|
+
}
|
|
831
|
+
await this.writeIndexForDecision(signed);
|
|
832
|
+
await this.maybeRotate();
|
|
833
|
+
}
|
|
834
|
+
/** One turn of this ledger's queue: read a cursor and append without a second writer seeing the same cursor. */
|
|
835
|
+
async exclusive(fn) {
|
|
836
|
+
return this.q.enqueue(() => fn({
|
|
837
|
+
appendDecisionChained: (build) => this.appendDecisionChainedUnlocked(build),
|
|
838
|
+
appendEffect: (row, witnessClass, resultHash) => this.appendEffectUnlocked(row, witnessClass, resultHash),
|
|
839
|
+
}));
|
|
821
840
|
}
|
|
822
841
|
/**
|
|
823
842
|
* What /healthz reports, from memory: the counts are kept on load and on
|
|
@@ -917,6 +936,7 @@ export class FileLedger {
|
|
|
917
936
|
});
|
|
918
937
|
}
|
|
919
938
|
async appendEffectUnlocked(row, witnessClass = DEFAULT_WITNESS, resultHash) {
|
|
939
|
+
this.assertOwned();
|
|
920
940
|
if (row.effectClass !== "duplicate-effect" && this.effectRefs.has(row.ref)) {
|
|
921
941
|
const dup = lineOf(asStoredEffect({
|
|
922
942
|
ref: row.ref,
|
package/dist/proxy.d.ts
CHANGED
|
@@ -7,5 +7,6 @@ export declare const REF_RE: RegExp;
|
|
|
7
7
|
export declare function createProxy(deps: ProxyDeps): {
|
|
8
8
|
approvals: import("./approvals.ts").ApprovalsLog;
|
|
9
9
|
inputsLog: import("./types.ts").InputsLog;
|
|
10
|
+
syncControlRecords: () => Promise<void>;
|
|
10
11
|
call(call: ToolCall, principal: Principal): Promise<ToolResult>;
|
|
11
12
|
};
|
package/dist/proxy.js
CHANGED
|
@@ -7,6 +7,7 @@ import { diskProbe } from "./disk.js";
|
|
|
7
7
|
import { markEnded, markStarted, startedWithoutEnd } from "./in-flight-log.js";
|
|
8
8
|
import { effectDescriptor, sha256Canonical } from "./hash.js";
|
|
9
9
|
import { inputsLogFor } from "./inputs.js";
|
|
10
|
+
import { controlUnchanged, createControlMemory, syncHaltControl } from "./control-sync.js";
|
|
10
11
|
import { countedWork, hasPrimaryEffect, lookupDecisionByRef, lookupReauthByHash, lookupResolvedBy, noteResolution, noteTenantRef, } from "./ledger.js";
|
|
11
12
|
import { spokenReason } from "./spoken-reason.js";
|
|
12
13
|
import { tenantKey } from "./tenant.js";
|
|
@@ -178,6 +179,7 @@ export function createProxy(deps) {
|
|
|
178
179
|
const inputsLog = deps.inputsLog ?? inputsLogFor(deps.ledger);
|
|
179
180
|
const approvals = approvalsLogFor(deps.ledger);
|
|
180
181
|
const admission = new SerialQueue();
|
|
182
|
+
const controlQueue = new SerialQueue();
|
|
181
183
|
const inFlight = new Map();
|
|
182
184
|
const budgetGuard = createApprovalBudgetGuard({
|
|
183
185
|
policy: deps.policy,
|
|
@@ -188,6 +190,10 @@ export function createProxy(deps) {
|
|
|
188
190
|
deps.ledger.effectSigner = deps.effectSigner;
|
|
189
191
|
const ledgerDir = deps.ledger.dir;
|
|
190
192
|
const stateDir = typeof ledgerDir === "string" ? ledgerDir : null;
|
|
193
|
+
// Single writer: after open, the ledger lock is this process. The first
|
|
194
|
+
// sync reads control records once; this snapshot is updated in place.
|
|
195
|
+
const controlMemory = createControlMemory();
|
|
196
|
+
let controlSyncReported = false;
|
|
191
197
|
if (stateDir === null) {
|
|
192
198
|
process.stderr.write("verax-proxy: halt and disk limits are inactive without a ledger directory\n");
|
|
193
199
|
}
|
|
@@ -430,9 +436,52 @@ export function createProxy(deps) {
|
|
|
430
436
|
});
|
|
431
437
|
return denied(verdict.reasonCode, denyRef);
|
|
432
438
|
}
|
|
439
|
+
async function syncControlRecords() {
|
|
440
|
+
if (stateDir === null)
|
|
441
|
+
return;
|
|
442
|
+
try {
|
|
443
|
+
if (controlUnchanged(stateDir, controlMemory))
|
|
444
|
+
return;
|
|
445
|
+
const run = (writer) => syncHaltControl({
|
|
446
|
+
stateDir,
|
|
447
|
+
now: deps.now,
|
|
448
|
+
nonce: deps.nonce,
|
|
449
|
+
policyHash: deps.policy.hash,
|
|
450
|
+
recordSigner: deps.recordSigner,
|
|
451
|
+
inputsLog,
|
|
452
|
+
decisions: () => deps.ledger.decisions(),
|
|
453
|
+
memory: controlMemory,
|
|
454
|
+
writer,
|
|
455
|
+
});
|
|
456
|
+
const host = deps.ledger;
|
|
457
|
+
if (typeof host.exclusive === "function") {
|
|
458
|
+
await host.exclusive((writer) => run(writer));
|
|
459
|
+
}
|
|
460
|
+
else {
|
|
461
|
+
await controlQueue.enqueue(() => run({
|
|
462
|
+
appendDecisionChained: (build) => deps.ledger.appendDecisionChained(build),
|
|
463
|
+
appendEffect: (row, witnessClass, resultHash) => deps.ledger.appendEffect(row, witnessClass, resultHash),
|
|
464
|
+
}));
|
|
465
|
+
}
|
|
466
|
+
controlSyncReported = false;
|
|
467
|
+
}
|
|
468
|
+
catch (err) {
|
|
469
|
+
// An unreadable ledger used to throw out of the call. Leave the snapshot
|
|
470
|
+
// unloaded so the next call reads again, and keep going: the halt switch
|
|
471
|
+
// and the rate limit still fail closed on their own path. One line per
|
|
472
|
+
// failure streak, so the admission retry in the same call does not repeat it.
|
|
473
|
+
controlMemory.loaded = false;
|
|
474
|
+
if (controlSyncReported)
|
|
475
|
+
return;
|
|
476
|
+
controlSyncReported = true;
|
|
477
|
+
const message = (err instanceof Error ? err.message : String(err)).replace(/[\r\n]+/g, " ");
|
|
478
|
+
process.stderr.write(`verax-proxy: control sync failed: ${message}\n`);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
433
481
|
return {
|
|
434
482
|
approvals,
|
|
435
483
|
inputsLog,
|
|
484
|
+
syncControlRecords,
|
|
436
485
|
async call(call, principal) {
|
|
437
486
|
if (stateDir) {
|
|
438
487
|
await drainApprovalCommands(stateDir, async (cmd) => {
|
|
@@ -454,6 +503,7 @@ export function createProxy(deps) {
|
|
|
454
503
|
budgetGuard,
|
|
455
504
|
});
|
|
456
505
|
});
|
|
506
|
+
await syncControlRecords();
|
|
457
507
|
}
|
|
458
508
|
const dispatched = toolCallOf(call);
|
|
459
509
|
const requestHash = sha256Canonical(dispatched);
|
|
@@ -489,6 +539,9 @@ export function createProxy(deps) {
|
|
|
489
539
|
}
|
|
490
540
|
const given = readRef(call.arguments);
|
|
491
541
|
const plan = await admission.enqueue(async () => {
|
|
542
|
+
// A halt that landed while this call waited must be on the chain before the deny.
|
|
543
|
+
if (stateDir)
|
|
544
|
+
await syncControlRecords();
|
|
492
545
|
// A call that waited here behind another admission reads the halt flag again.
|
|
493
546
|
if (stateDir && existsSync(join(stateDir, "halted"))) {
|
|
494
547
|
const ref = deps.nonce();
|
package/dist/types.d.ts
CHANGED
|
@@ -103,6 +103,40 @@ export type DecisionInputRow = {
|
|
|
103
103
|
/** Optional provenance. Same idea as memory.put `source`; additive. */
|
|
104
104
|
source?: Record<string, unknown>;
|
|
105
105
|
};
|
|
106
|
+
/**
|
|
107
|
+
* One halt or resume copied from `halt-history.jsonl`, or a file switch the
|
|
108
|
+
* history does not explain. `line` is the 0-based index of a history line.
|
|
109
|
+
* A switch with no history halt uses `line: -1`, `via: "file"`, and
|
|
110
|
+
* `action: "halt"`. Deleting that switch while a halt window is still open,
|
|
111
|
+
* with no history resume that closes it, uses the same line and via with
|
|
112
|
+
* `action: "resume"`. On a `halt-history-mismatch` deny, `line` is the index
|
|
113
|
+
* sync resumes from, not a history row.
|
|
114
|
+
*/
|
|
115
|
+
export type ControlInput = {
|
|
116
|
+
action: "halt" | "resume";
|
|
117
|
+
by: string;
|
|
118
|
+
via: "cli" | "http" | "file";
|
|
119
|
+
atMs: number;
|
|
120
|
+
line: number;
|
|
121
|
+
lineHash: string;
|
|
122
|
+
};
|
|
123
|
+
/**
|
|
124
|
+
* The operator's own WebAuthn assertion for one HTTP approval.
|
|
125
|
+
* `authenticatorData`, `clientDataJSON` and `signature` are base64url.
|
|
126
|
+
* The challenge is not stored: it is rebuilt as the hash of a canonical
|
|
127
|
+
* document that names this defer record. `rpId` is the relying party id
|
|
128
|
+
* checked against authenticatorData, so a later read can rebuild rpIdHash
|
|
129
|
+
* without the body's configuration.
|
|
130
|
+
*/
|
|
131
|
+
export type ApprovalSignature = {
|
|
132
|
+
credentialId: string;
|
|
133
|
+
sub: string;
|
|
134
|
+
authenticatorData: string;
|
|
135
|
+
clientDataJSON: string;
|
|
136
|
+
signature: string;
|
|
137
|
+
deferRecordHash: string;
|
|
138
|
+
rpId: string;
|
|
139
|
+
};
|
|
106
140
|
export type DecisionInputs = {
|
|
107
141
|
principal: {
|
|
108
142
|
brain: string;
|
|
@@ -116,7 +150,9 @@ export type DecisionInputs = {
|
|
|
116
150
|
id: string;
|
|
117
151
|
via: ApprovalChannel | "proxy";
|
|
118
152
|
resolves: string;
|
|
153
|
+
signature?: ApprovalSignature;
|
|
119
154
|
};
|
|
155
|
+
control?: ControlInput;
|
|
120
156
|
};
|
|
121
157
|
/** How an operator's approval reached the ledger: a person at `verax approve`, a non-interactive `--from-script` run, or the body's `/api/approve`. */
|
|
122
158
|
export type ApprovalChannel = "cli" | "cli-script" | "http";
|
package/dist/verify-ledger.d.ts
CHANGED
|
@@ -32,6 +32,8 @@ export type VerifyResult = {
|
|
|
32
32
|
effectCompleteness: string;
|
|
33
33
|
/** What the newest checkpoint covers, and the records after it. */
|
|
34
34
|
tail: VerifyTail;
|
|
35
|
+
/** Halt windows. A ledger with none says so; that sentence is not a violation. */
|
|
36
|
+
control: VerifyControl;
|
|
35
37
|
problems: string[];
|
|
36
38
|
};
|
|
37
39
|
export type VerifyIndex = {
|
|
@@ -50,6 +52,12 @@ export type VerifyTail = {
|
|
|
50
52
|
ledgerHoldsRecord: boolean | null;
|
|
51
53
|
} | null;
|
|
52
54
|
};
|
|
55
|
+
/** Halt windows taken from control records. Warnings do not change `ok`. */
|
|
56
|
+
export type VerifyControl = {
|
|
57
|
+
line: string;
|
|
58
|
+
windows: number;
|
|
59
|
+
warnings: string[];
|
|
60
|
+
};
|
|
53
61
|
export type VerifyOptions = {
|
|
54
62
|
/** Verify decision records against this key instead of the one they carry. */
|
|
55
63
|
publicKeyPem?: string;
|
package/dist/verify-ledger.js
CHANGED
|
@@ -51,6 +51,14 @@
|
|
|
51
51
|
* that verified. A key taken from the file shows the checkpoints agree
|
|
52
52
|
* with each other, not that the key was ever trusted.
|
|
53
53
|
*
|
|
54
|
+
* Control records are a further statement. An allow whose subject is
|
|
55
|
+
* `verax.halt` opens a halt window; an allow whose subject is `verax.resume`
|
|
56
|
+
* closes it. An allow whose subject does not start with `verax.` while a
|
|
57
|
+
* window is open is `allow-while-halted <ref>` and `ok` is false. A deny
|
|
58
|
+
* whose reason is `halted` and which sits outside every window is the
|
|
59
|
+
* warning `halted-deny-without-halt-record <ref>` and does not change `ok`.
|
|
60
|
+
* A ledger with no control record says so, and that sentence is not a violation.
|
|
61
|
+
*
|
|
54
62
|
* And a fourth, which matters most and is the easiest to fudge: **which key**.
|
|
55
63
|
* A ledger checked against the key sitting next to it is internally
|
|
56
64
|
* consistent and nothing more — whatever could write the file could write
|
|
@@ -414,6 +422,16 @@ const INDEX_NONE = "index: none (cannot check for removed records)";
|
|
|
414
422
|
const EFFECT_COMPLETENESS_UNCHECKED = "effect completeness was not checked";
|
|
415
423
|
const EFFECT_COMPLETENESS_CHECKED = "effect completeness checked";
|
|
416
424
|
const TAIL_NONE = "tail: no checkpoint; removing the newest records with their effects is not detectable from these files";
|
|
425
|
+
const CONTROL_NONE = {
|
|
426
|
+
line: "control: no control records",
|
|
427
|
+
windows: 0,
|
|
428
|
+
warnings: [],
|
|
429
|
+
};
|
|
430
|
+
const CONTROL_UNCHECKED = {
|
|
431
|
+
line: "control: not checked",
|
|
432
|
+
windows: 0,
|
|
433
|
+
warnings: [],
|
|
434
|
+
};
|
|
417
435
|
/**
|
|
418
436
|
* A torn last line is the crash the writer already documents: earlier lines
|
|
419
437
|
* parsed, so that tail is skipped. Any other line that is not JSON, and a
|
|
@@ -573,6 +591,51 @@ function tailStatement(dir, records, checkpointPublicKeyPem) {
|
|
|
573
591
|
problems,
|
|
574
592
|
};
|
|
575
593
|
}
|
|
594
|
+
function controlStatement(records) {
|
|
595
|
+
let open = false;
|
|
596
|
+
let windows = 0;
|
|
597
|
+
let controlRecords = 0;
|
|
598
|
+
const warnings = [];
|
|
599
|
+
const violations = [];
|
|
600
|
+
for (const record of records) {
|
|
601
|
+
const subject = typeof record.claims?.subject === "string" ? record.claims.subject : "";
|
|
602
|
+
const decision = record.claims?.decision;
|
|
603
|
+
const reason = record.claims?.reasonCode;
|
|
604
|
+
const ref = typeof record.claims?.ref === "string" ? record.claims.ref : "?";
|
|
605
|
+
// Only the two control subjects, with the control effect class, open or
|
|
606
|
+
// close a window. Any other allow inside one is a violation, including a
|
|
607
|
+
// downstream tool whose prefix happens to be "verax".
|
|
608
|
+
const control = record.claims?.effectClass === "verax.control";
|
|
609
|
+
const halt = control && decision === "allow" && subject === "verax.halt";
|
|
610
|
+
const resume = control && decision === "allow" && subject === "verax.resume";
|
|
611
|
+
if (halt || resume)
|
|
612
|
+
controlRecords += 1;
|
|
613
|
+
if (halt) {
|
|
614
|
+
if (!open)
|
|
615
|
+
windows += 1;
|
|
616
|
+
open = true;
|
|
617
|
+
continue;
|
|
618
|
+
}
|
|
619
|
+
if (resume) {
|
|
620
|
+
open = false;
|
|
621
|
+
continue;
|
|
622
|
+
}
|
|
623
|
+
if (decision === "allow") {
|
|
624
|
+
if (open)
|
|
625
|
+
violations.push(`allow-while-halted ${ref}`);
|
|
626
|
+
continue;
|
|
627
|
+
}
|
|
628
|
+
if (decision === "deny" && reason === "halted" && !open) {
|
|
629
|
+
warnings.push(`halted-deny-without-halt-record ${ref}`);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
if (controlRecords === 0)
|
|
633
|
+
return { control: { ...CONTROL_NONE, warnings }, violations };
|
|
634
|
+
return {
|
|
635
|
+
control: { line: `control: ${windows} halt window(s)`, windows, warnings },
|
|
636
|
+
violations,
|
|
637
|
+
};
|
|
638
|
+
}
|
|
576
639
|
function unreadableResult(dir, problem) {
|
|
577
640
|
const trust = { source: "none", publicKeyPem: null, note: problem };
|
|
578
641
|
return {
|
|
@@ -592,6 +655,7 @@ function unreadableResult(dir, problem) {
|
|
|
592
655
|
index: { present: false, missing: 0, line: INDEX_NONE },
|
|
593
656
|
effectCompleteness: EFFECT_COMPLETENESS_UNCHECKED,
|
|
594
657
|
tail: { line: TAIL_NONE, checkpoint: null },
|
|
658
|
+
control: CONTROL_UNCHECKED,
|
|
595
659
|
problems: [problem],
|
|
596
660
|
};
|
|
597
661
|
}
|
|
@@ -634,6 +698,7 @@ async function verifyLedgerUnchecked(dir, opts = {}) {
|
|
|
634
698
|
const emptyTail = tailStatement(dir, records, opts.checkpointPublicKeyPem ?? "");
|
|
635
699
|
const effectCompleteness = noteEffectCompleteness(emptyIndex.effectRefs, new Set(), problems);
|
|
636
700
|
problems.push(...emptyIndex.problems, ...emptyTail.problems);
|
|
701
|
+
const emptyControl = controlStatement(records);
|
|
637
702
|
return {
|
|
638
703
|
ok: false,
|
|
639
704
|
directory: dir,
|
|
@@ -651,6 +716,7 @@ async function verifyLedgerUnchecked(dir, opts = {}) {
|
|
|
651
716
|
index: emptyIndex.index,
|
|
652
717
|
effectCompleteness,
|
|
653
718
|
tail: emptyTail.tail,
|
|
719
|
+
control: emptyControl.control,
|
|
654
720
|
problems,
|
|
655
721
|
};
|
|
656
722
|
}
|
|
@@ -843,6 +909,8 @@ async function verifyLedgerUnchecked(dir, opts = {}) {
|
|
|
843
909
|
const effectCompleteness = noteEffectCompleteness(indexed.effectRefs, boundPrimaryRefs, problems);
|
|
844
910
|
const tailed = tailStatement(dir, records, opts.checkpointPublicKeyPem ?? "");
|
|
845
911
|
problems.push(...indexed.problems, ...tailed.problems);
|
|
912
|
+
const stated = controlStatement(records);
|
|
913
|
+
problems.push(...stated.violations);
|
|
846
914
|
const ok = problems.length === 0 && signaturesInvalid === 0 && chainBreakAt === null && effectsOrphaned === 0;
|
|
847
915
|
return {
|
|
848
916
|
ok,
|
|
@@ -861,6 +929,7 @@ async function verifyLedgerUnchecked(dir, opts = {}) {
|
|
|
861
929
|
index: indexed.index,
|
|
862
930
|
effectCompleteness,
|
|
863
931
|
tail: tailed.tail,
|
|
932
|
+
control: stated.control,
|
|
864
933
|
problems,
|
|
865
934
|
};
|
|
866
935
|
}
|