@agent-custody/receipts 0.9.0 → 0.11.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 +22 -10
- package/dist/anchor-evm.d.ts +19 -0
- package/dist/anchor-evm.js +49 -0
- package/dist/anchor.d.ts +167 -0
- package/dist/anchor.js +367 -0
- package/dist/check.js +9 -3
- package/dist/cli.js +73 -7
- package/dist/config.d.ts +10 -0
- package/dist/config.js +25 -0
- package/dist/console-page.js +3 -3
- package/dist/console.js +2 -1
- package/dist/gateway-http.js +1 -1
- package/dist/gateway.d.ts +15 -1
- package/dist/gateway.js +161 -23
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/issue.d.ts +31 -1
- package/dist/issue.js +261 -10
- package/dist/log-check.d.ts +15 -0
- package/dist/log-check.js +52 -0
- package/dist/policy.d.ts +2 -0
- package/dist/policy.js +5 -0
- package/dist/portal.js +1 -0
- package/dist/receipt.d.ts +2 -0
- package/dist/simulate.d.ts +7 -1
- package/dist/simulate.js +27 -2
- package/dist/verify.d.ts +2 -0
- package/dist/verify.js +11 -3
- package/docs/anchoring.md +115 -0
- package/docs/codex-recovery.md +1 -1
- package/docs/configuration.md +7 -1
- package/docs/console.md +2 -3
- package/docs/policies.md +3 -1
- package/docs/threat-model.md +16 -2
- package/docs/tutorials.md +3 -0
- package/docs/usage.md +36 -3
- package/docs/verification.md +4 -2
- package/package.json +7 -2
- package/vectors/audit.json +27 -27
- package/vectors/canonical.json +5 -5
- package/vectors/receipts.json +1176 -967
package/dist/issue.js
CHANGED
|
@@ -1,11 +1,28 @@
|
|
|
1
1
|
// Signing, logging and writing a receipt. Shared by every producer: the gateway and the SDK.
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { chmodSync, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { hostname } from "node:os";
|
|
5
|
+
import { RECEIPT_ID, SALTS_DIR, saltsFileFor } from "./retention.js";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
5
7
|
import { effectiveRule, getAt, privateView } from "./capture.js";
|
|
6
8
|
import { canonicalize, dsseSign, dsseVerify } from "./crypto.js";
|
|
7
9
|
import { fileLog } from "./log-sink.js";
|
|
10
|
+
import { ownerAlive, processStamp } from "./operations.js";
|
|
8
11
|
import { buildAuthorizationStatement, buildStatement, RECEIPT_TYPE } from "./receipt.js";
|
|
12
|
+
/** The receipts whose log append failed wait here, signed, until `flushOutbox` appends them. */
|
|
13
|
+
export const OUTBOX_DIR = "outbox";
|
|
14
|
+
/**
|
|
15
|
+
* Thrown by `issue` with `deferLog` when the log did not take the receipt. The signed receipt is kept in the outbox and
|
|
16
|
+
* no bundle is written yet: `flushOutbox` appends it later and then writes the bundle.
|
|
17
|
+
*/
|
|
18
|
+
export class ReceiptPending extends Error {
|
|
19
|
+
receiptId;
|
|
20
|
+
constructor(receiptId, cause) {
|
|
21
|
+
super(`receipt ${receiptId} is kept in the outbox; its log append is pending: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
|
|
22
|
+
this.name = "ReceiptPending";
|
|
23
|
+
this.receiptId = receiptId;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
9
26
|
/** `log` is a sink, or a file path for the local log with tree heads signed by the issuer's key. */
|
|
10
27
|
export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
11
28
|
const sink = typeof log === "string" ? fileLog(log, key) : log;
|
|
@@ -32,6 +49,116 @@ export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
|
32
49
|
/** an authorization whose receipt has not followed within this long is a call that died; its view is let go */
|
|
33
50
|
const COMMITTED_FOR_MS = 60 * 60 * 1000;
|
|
34
51
|
const COMMITTED_AT_MOST = 100_000;
|
|
52
|
+
/** a lock that its owner has not touched for this long is broken, whatever machine the owner is on */
|
|
53
|
+
const LOCK_STALE_MS = 15 * 60 * 1000;
|
|
54
|
+
const outboxDir = join(receiptsDir, OUTBOX_DIR);
|
|
55
|
+
const outboxed = () => existsSync(outboxDir) ? readdirSync(outboxDir).filter((f) => f.endsWith(".json") && RECEIPT_ID.test(f.slice(0, -".json".length))) : [];
|
|
56
|
+
/** the outbox in the order of the signed statements' timestamps; an entry that cannot be read sorts first and is dealt with when its turn comes */
|
|
57
|
+
const outboxOrdered = () => outboxed().map((f) => {
|
|
58
|
+
let at = 0;
|
|
59
|
+
try {
|
|
60
|
+
const env = JSON.parse(readFileSync(join(outboxDir, f), "utf8")).envelope;
|
|
61
|
+
at = Date.parse(JSON.parse(Buffer.from(env.payload, "base64").toString("utf8")).predicate.timestamp) || 0;
|
|
62
|
+
}
|
|
63
|
+
catch { /* unreadable: at stays 0 */ }
|
|
64
|
+
return { f, at };
|
|
65
|
+
}).sort((a, b) => a.at - b.at || (a.f < b.f ? -1 : 1)).map((e) => e.f);
|
|
66
|
+
/** the file is whole or absent, and on disk before the caller goes on: it can be the only copy of the evidence */
|
|
67
|
+
const writeDurable = (file, text) => {
|
|
68
|
+
const fd = openSync(`${file}.tmp`, "w");
|
|
69
|
+
try {
|
|
70
|
+
writeFileSync(fd, text);
|
|
71
|
+
fsyncSync(fd);
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
closeSync(fd);
|
|
75
|
+
}
|
|
76
|
+
renameSync(`${file}.tmp`, file);
|
|
77
|
+
syncDir(dirname(file));
|
|
78
|
+
};
|
|
79
|
+
const syncDir = (dir) => {
|
|
80
|
+
const fd = openSync(dir, "r");
|
|
81
|
+
try {
|
|
82
|
+
fsyncSync(fd);
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
closeSync(fd);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
const lockFile = join(outboxDir, ".lock");
|
|
89
|
+
/** Takes the outbox lock with an exclusive create. A lock whose owner is gone, or that no one has touched for a long time, is broken. Returns its release, or undefined when another flusher holds it. */
|
|
90
|
+
const takeLock = () => {
|
|
91
|
+
const token = randomUUID();
|
|
92
|
+
const body = JSON.stringify({ token, pid: process.pid, start: processStamp(process.pid), host: hostname() });
|
|
93
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
94
|
+
try {
|
|
95
|
+
const fd = openSync(lockFile, "wx", 0o600);
|
|
96
|
+
try {
|
|
97
|
+
writeFileSync(fd, body);
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
closeSync(fd);
|
|
101
|
+
}
|
|
102
|
+
return () => {
|
|
103
|
+
try {
|
|
104
|
+
if (JSON.parse(readFileSync(lockFile, "utf8")).token === token)
|
|
105
|
+
rmSync(lockFile, { force: true });
|
|
106
|
+
}
|
|
107
|
+
catch { /* already broken by another flusher */ }
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
catch (e) {
|
|
111
|
+
if (e.code !== "EEXIST")
|
|
112
|
+
throw e;
|
|
113
|
+
}
|
|
114
|
+
if (!lockIsStale())
|
|
115
|
+
return undefined;
|
|
116
|
+
// two flushers may both judge it stale; the rename lets one of them move it, the other gets ENOENT and tries again
|
|
117
|
+
try {
|
|
118
|
+
const gone = `${lockFile}.stale-${randomUUID()}`;
|
|
119
|
+
renameSync(lockFile, gone);
|
|
120
|
+
rmSync(gone, { force: true });
|
|
121
|
+
}
|
|
122
|
+
catch (e) {
|
|
123
|
+
if (e.code !== "ENOENT")
|
|
124
|
+
throw e;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return undefined;
|
|
128
|
+
};
|
|
129
|
+
const lockIsStale = () => {
|
|
130
|
+
try {
|
|
131
|
+
const age = Date.now() - statSync(lockFile).mtimeMs;
|
|
132
|
+
let owner;
|
|
133
|
+
try {
|
|
134
|
+
owner = JSON.parse(readFileSync(lockFile, "utf8"));
|
|
135
|
+
}
|
|
136
|
+
catch { /* a lock being written */ }
|
|
137
|
+
if (!owner)
|
|
138
|
+
return age > 60_000;
|
|
139
|
+
if (owner.host === hostname() && !ownerAlive({ ownerPid: owner.pid, ...(owner.start ? { ownerStart: owner.start } : {}) }))
|
|
140
|
+
return true;
|
|
141
|
+
return age > LOCK_STALE_MS;
|
|
142
|
+
}
|
|
143
|
+
catch (e) {
|
|
144
|
+
if (e.code === "ENOENT")
|
|
145
|
+
return true;
|
|
146
|
+
throw e;
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
const writeBundle = async (receiptId, v, bundle) => {
|
|
150
|
+
const file = join(receiptsDir, `${receiptId}.json`);
|
|
151
|
+
// whole or absent: a flush takes a bundle that is there as proof that the outbox entry is done
|
|
152
|
+
writeFileSync(`${file}.tmp`, JSON.stringify(bundle, null, 2));
|
|
153
|
+
renameSync(`${file}.tmp`, file);
|
|
154
|
+
// After the evidence, not before, and awaited so a process that exits right after issuing still exports. The
|
|
155
|
+
// exporter sees the view, never the full call.
|
|
156
|
+
if (opts.exporter)
|
|
157
|
+
await opts.exporter.exported(v, bundle).catch(() => { });
|
|
158
|
+
};
|
|
159
|
+
let flushing;
|
|
160
|
+
/** the log's answer for a receipt whose bundle could not be written yet: a retry in this process writes the bundle and does not append again */
|
|
161
|
+
const appended = new Map();
|
|
35
162
|
/**
|
|
36
163
|
* The salts behind a statement's digest-only commitments, kept beside the receipts and never in them:
|
|
37
164
|
* `receipts/salts/<id>.json`, the owner's alone. They are what makes a disclosure possible for a value withheld
|
|
@@ -47,7 +174,7 @@ export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
|
47
174
|
return {
|
|
48
175
|
keyid: key.keyid,
|
|
49
176
|
log: sink,
|
|
50
|
-
async issue(predicate, ctx, retainPrepared) {
|
|
177
|
+
async issue(predicate, ctx, retainPrepared, issueOpts) {
|
|
51
178
|
ensureSaltsDir();
|
|
52
179
|
// the authorization's view stays until the log has taken the receipt: a producer that retries after a refusal gets the same commitments and salts
|
|
53
180
|
const prior = committed.get(predicate.receiptId)?.view;
|
|
@@ -63,16 +190,32 @@ export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
|
63
190
|
if (!checked.ok || envelope.payloadType !== RECEIPT_TYPE || v.receiptId !== predicate.receiptId || canonicalize(checked.payload) !== canonicalize(buildStatement(v)))
|
|
64
191
|
throw new Error("prepared receipt does not match this issuer, predicate, or receipt id");
|
|
65
192
|
}
|
|
66
|
-
|
|
193
|
+
let entry;
|
|
194
|
+
try {
|
|
195
|
+
entry = await sink.append(canonicalize(envelope));
|
|
196
|
+
}
|
|
197
|
+
catch (e) {
|
|
198
|
+
if (!issueOpts?.deferLog)
|
|
199
|
+
throw e;
|
|
200
|
+
// The call has happened, so its receipt is kept: signed, with its salts, and appended later. The salts go
|
|
201
|
+
// first, so an outbox entry never lacks them; the rename makes the entry whole or absent.
|
|
202
|
+
try {
|
|
203
|
+
keepSalts(pv);
|
|
204
|
+
mkdirSync(outboxDir, { recursive: true });
|
|
205
|
+
writeDurable(join(outboxDir, `${predicate.receiptId}.json`), JSON.stringify({ envelope }));
|
|
206
|
+
syncDir(receiptsDir);
|
|
207
|
+
}
|
|
208
|
+
catch (w) {
|
|
209
|
+
throw new Error(`${e instanceof Error ? e.message : String(e)}; the receipt could not be kept in the outbox either: ${w instanceof Error ? w.message : String(w)}`, { cause: e });
|
|
210
|
+
}
|
|
211
|
+
committed.delete(predicate.receiptId);
|
|
212
|
+
throw new ReceiptPending(predicate.receiptId, e);
|
|
213
|
+
}
|
|
67
214
|
committed.delete(predicate.receiptId);
|
|
68
215
|
// the salts once the log has taken the leaf: a receipt the log refused leaves nothing behind
|
|
69
216
|
keepSalts(pv);
|
|
70
217
|
const bundle = { envelope, treeHead: entry.treeHead, inclusion: entry.inclusion };
|
|
71
|
-
|
|
72
|
-
// After the evidence, not before, and awaited so a process that exits right after issuing still exports. The
|
|
73
|
-
// exporter sees the view, never the full call.
|
|
74
|
-
if (opts.exporter)
|
|
75
|
-
await opts.exporter.exported(v, bundle).catch(() => { });
|
|
218
|
+
await writeBundle(predicate.receiptId, v, bundle);
|
|
76
219
|
return bundle;
|
|
77
220
|
},
|
|
78
221
|
async authorize(predicate, ctx) {
|
|
@@ -97,5 +240,113 @@ export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
|
97
240
|
writeFileSync(join(receiptsDir, `${predicate.receiptId}.authorization.json`), JSON.stringify(bundle, null, 2));
|
|
98
241
|
return bundle;
|
|
99
242
|
},
|
|
243
|
+
pending: () => outboxed().length,
|
|
244
|
+
flushOutbox() {
|
|
245
|
+
flushing ??= (async () => {
|
|
246
|
+
const idle = () => ({ sent: 0, pending: outboxed().length, setAside: 0, foreign: 0 });
|
|
247
|
+
if (!outboxed().length)
|
|
248
|
+
return idle();
|
|
249
|
+
const release = takeLock();
|
|
250
|
+
if (!release)
|
|
251
|
+
return idle();
|
|
252
|
+
try {
|
|
253
|
+
let sent = 0;
|
|
254
|
+
let setAside = 0;
|
|
255
|
+
let foreign = 0;
|
|
256
|
+
const errors = [];
|
|
257
|
+
const done = () => ({ sent, pending: outboxed().length, setAside, foreign, ...(errors.length ? { error: errors.length === 1 ? errors[0] : `${errors[0]} (and ${errors.length - 1} more)` } : {}) });
|
|
258
|
+
const setAsideFile = (file) => {
|
|
259
|
+
try {
|
|
260
|
+
renameSync(file, `${file}.bad`);
|
|
261
|
+
setAside++;
|
|
262
|
+
}
|
|
263
|
+
catch (e) {
|
|
264
|
+
if (e.code !== "ENOENT")
|
|
265
|
+
throw e;
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
for (const f of outboxOrdered()) {
|
|
269
|
+
const receiptId = f.slice(0, -".json".length);
|
|
270
|
+
const file = join(outboxDir, f);
|
|
271
|
+
try {
|
|
272
|
+
// a bundle already there means the append and the write happened and only the removal did not
|
|
273
|
+
if (existsSync(join(receiptsDir, f))) {
|
|
274
|
+
rmSync(file, { force: true });
|
|
275
|
+
appended.delete(receiptId);
|
|
276
|
+
sent++;
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
let record;
|
|
280
|
+
try {
|
|
281
|
+
record = JSON.parse(readFileSync(file, "utf8"));
|
|
282
|
+
}
|
|
283
|
+
catch (e) {
|
|
284
|
+
// gone: another flusher took it; anything else that is not readable JSON is damaged
|
|
285
|
+
if (e.code === "ENOENT")
|
|
286
|
+
continue;
|
|
287
|
+
if (!(e instanceof SyntaxError))
|
|
288
|
+
throw e;
|
|
289
|
+
setAsideFile(file);
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
const envelope = record?.envelope;
|
|
293
|
+
if (typeof envelope?.payload !== "string" || !Array.isArray(envelope.signatures) || envelope.signatures.length === 0) {
|
|
294
|
+
setAsideFile(file);
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
// a signature by another key proves nothing about this entry (a rotated key, a restored backup): it stays, and is reported
|
|
298
|
+
if (!envelope.signatures.some((sig) => sig?.keyid === key.keyid)) {
|
|
299
|
+
foreign++;
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
// only this issuer's own receipt, under its own id, goes to the log; anything else is set aside, not retried
|
|
303
|
+
const checked = dsseVerify(envelope, [key]);
|
|
304
|
+
const statement = (checked.ok ? checked.payload : undefined);
|
|
305
|
+
if (!statement || envelope.payloadType !== RECEIPT_TYPE || statement.predicate?.receiptId !== receiptId) {
|
|
306
|
+
setAsideFile(file);
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
let entry = record.appended ?? appended.get(receiptId);
|
|
310
|
+
if (!entry) {
|
|
311
|
+
try {
|
|
312
|
+
entry = await sink.append(canonicalize(envelope));
|
|
313
|
+
}
|
|
314
|
+
catch (e) {
|
|
315
|
+
errors.push(e instanceof Error ? e.message : String(e));
|
|
316
|
+
return done();
|
|
317
|
+
}
|
|
318
|
+
// Until the bundle is written, the answer is the only proof that the log has the leaf. It is kept in
|
|
319
|
+
// memory and in the entry, so that a failure now does not make the next flush append the leaf again.
|
|
320
|
+
appended.set(receiptId, entry);
|
|
321
|
+
try {
|
|
322
|
+
writeDurable(file, JSON.stringify({ envelope, appended: entry }));
|
|
323
|
+
}
|
|
324
|
+
catch (e) {
|
|
325
|
+
errors.push(`receipt ${receiptId} is in the log, but its outbox entry could not record that: ${e instanceof Error ? e.message : String(e)}`);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
await writeBundle(receiptId, statement.predicate, { envelope, treeHead: entry.treeHead, inclusion: entry.inclusion });
|
|
329
|
+
rmSync(file, { force: true });
|
|
330
|
+
appended.delete(receiptId);
|
|
331
|
+
sent++;
|
|
332
|
+
try {
|
|
333
|
+
utimesSync(lockFile, new Date(), new Date());
|
|
334
|
+
}
|
|
335
|
+
catch { /* the lock is only a hint */ }
|
|
336
|
+
}
|
|
337
|
+
catch (e) {
|
|
338
|
+
if (e.code === "ENOENT" && !existsSync(file))
|
|
339
|
+
continue;
|
|
340
|
+
errors.push(`outbox entry ${f}: ${e instanceof Error ? e.message : String(e)}`);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
return done();
|
|
344
|
+
}
|
|
345
|
+
finally {
|
|
346
|
+
release();
|
|
347
|
+
}
|
|
348
|
+
})().finally(() => { flushing = undefined; });
|
|
349
|
+
return flushing;
|
|
350
|
+
},
|
|
100
351
|
};
|
|
101
352
|
}
|
package/dist/log-check.d.ts
CHANGED
|
@@ -8,6 +8,21 @@ export interface LogCheckOptions {
|
|
|
8
8
|
maxLagMs?: number;
|
|
9
9
|
/** how old a checkpoint may be while the head has not moved; default a day, since an idle log is not a broken one */
|
|
10
10
|
maxIdleMs?: number;
|
|
11
|
+
/** where the anchor publishes its records; with it, `anchorAddress` and `anchorRpcUrls` are required */
|
|
12
|
+
anchorUrl?: string;
|
|
13
|
+
/** the anchor's address, pinned from a source other than the anchor's host */
|
|
14
|
+
anchorAddress?: string;
|
|
15
|
+
/** JSON-RPC endpoints of the anchor's chain; with more than one, they must agree */
|
|
16
|
+
anchorRpcUrls?: string[];
|
|
17
|
+
/** the anchor's chain id; default 1, Ethereum mainnet (`resolveAnchorChain` maps a name to its id) */
|
|
18
|
+
anchorChainId?: number;
|
|
19
|
+
/**
|
|
20
|
+
* each anchored log's id, pinned by the verifier: tenant logs share the log's keys and the anchor's address, so only
|
|
21
|
+
* the id tells one log's anchored checkpoint from another's
|
|
22
|
+
*/
|
|
23
|
+
anchorLogIds?: Record<string, string>;
|
|
24
|
+
/** how long the log may stay ahead of its newest anchor, counted from that anchor's block time; default thirteen hours */
|
|
25
|
+
maxAnchorLagMs?: number;
|
|
11
26
|
fetch?: typeof fetch;
|
|
12
27
|
now?: () => number;
|
|
13
28
|
}
|
package/dist/log-check.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// log is down, its head does not verify, its checkpoints have fallen behind its head, or its witness has stopped
|
|
4
4
|
// countersigning. Run it from cron on a machine that is not the log's, or from a scheduled workflow; the exit code
|
|
5
5
|
// is the alert.
|
|
6
|
+
import { checkAnchorRecord } from "./anchor.js";
|
|
6
7
|
import { dsseVerify, dsseVerifiers } from "./crypto.js";
|
|
7
8
|
import { verifyConsistency } from "./log.js";
|
|
8
9
|
import { TREEHEAD_TYPE } from "./receipt.js";
|
|
@@ -26,6 +27,55 @@ export async function checkLog(o) {
|
|
|
26
27
|
throw new Error(`${res.status} from ${url.pathname}`);
|
|
27
28
|
return res.json();
|
|
28
29
|
};
|
|
30
|
+
const anchorChecks = async (tenant, head) => {
|
|
31
|
+
if (!o.anchorAddress || !o.anchorRpcUrls?.length) {
|
|
32
|
+
add(tenant, "anchor verifies on chain", false, "an anchor URL needs the pinned anchor address and at least one JSON-RPC endpoint");
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const logId = o.anchorLogIds && Object.hasOwn(o.anchorLogIds, tenant) ? o.anchorLogIds[tenant] : undefined;
|
|
36
|
+
if (logId === undefined) {
|
|
37
|
+
add(tenant, "anchor verifies on chain", false, `checking an anchor needs the log id of ${tenant} pinned (--anchor-log-id ${tenant}=<id>)`);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
const aBase = o.anchorUrl.endsWith("/") ? o.anchorUrl : `${o.anchorUrl}/`;
|
|
41
|
+
let record;
|
|
42
|
+
try {
|
|
43
|
+
record = (await get(new URL(`${tenant}/latest.json`, aBase)));
|
|
44
|
+
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
add(tenant, "anchor verifies on chain", false, e instanceof Error ? e.message : String(e));
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const r = await checkAnchorRecord(record, { rpcUrls: o.anchorRpcUrls, address: o.anchorAddress, chainId: o.anchorChainId ?? 1, logKeys: keys, fetch: f });
|
|
50
|
+
if (!add(tenant, "anchor verifies on chain", r.ok, r.ok ? `size ${record.treeSize} in block ${r.blockNumber} at ${r.blockTime}${r.finalized ? ", finalized" : ", not yet finalized"}` : r.error))
|
|
51
|
+
return;
|
|
52
|
+
if (!r.ok)
|
|
53
|
+
return;
|
|
54
|
+
// the record's id is its signed checkpoint's (checked above); both it and the head must be the pinned log's
|
|
55
|
+
if (!add(tenant, "anchor and head name the pinned log", record.logId === logId && head.log === logId, `pinned ${logId}, anchored ${record.logId ?? "none"}, head ${head.log ?? "none"}`))
|
|
56
|
+
return;
|
|
57
|
+
add(tenant, "anchor is the newest from its address", r.newer === 0, r.newer === 0 ? undefined : `the address has sent ${r.newer} transaction(s) since this one: the record is not the current anchor`);
|
|
58
|
+
if (record.treeSize > head.treeSize) {
|
|
59
|
+
add(tenant, "head extends the anchored checkpoint", false, `the head at ${head.treeSize} is behind the anchored size ${record.treeSize}: the log was rolled back`);
|
|
60
|
+
}
|
|
61
|
+
else if (record.treeSize === head.treeSize) {
|
|
62
|
+
add(tenant, "head extends the anchored checkpoint", record.rootHash === head.rootHash, record.rootHash === head.rootHash ? `at the anchored size ${head.treeSize}` : `a different root at the anchored size ${head.treeSize}: history was rewritten`);
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
try {
|
|
66
|
+
const proof = (await get(new URL(tenant === "default" ? `consistency?old=${record.treeSize}&new=${head.treeSize}` : `t/${tenant}/consistency?old=${record.treeSize}&new=${head.treeSize}`, base)));
|
|
67
|
+
const ok = verifyConsistency(record.treeSize, record.rootHash, head.treeSize, head.rootHash, proof.hashes);
|
|
68
|
+
add(tenant, "head extends the anchored checkpoint", ok, ok ? `${record.treeSize} -> ${head.treeSize}` : `the head at ${head.treeSize} does not extend the anchored ${record.treeSize}: history was rewritten`);
|
|
69
|
+
}
|
|
70
|
+
catch (e) {
|
|
71
|
+
add(tenant, "head extends the anchored checkpoint", false, e instanceof Error ? e.message : String(e));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
// the block's time is the chain's, so a host that stopped anchoring cannot make a log look covered
|
|
75
|
+
const age = now() - Date.parse(r.blockTime);
|
|
76
|
+
const ahead = head.treeSize > record.treeSize;
|
|
77
|
+
add(tenant, "anchor keeps up with the log", !ahead || age <= (o.maxAnchorLagMs ?? 13 * 3_600_000), ahead ? `the head at ${head.treeSize} is ahead of an anchor ${Math.round(age / 60_000)} min old` : `the anchor covers the head; anchored ${Math.round(age / 60_000)} min ago`);
|
|
78
|
+
};
|
|
29
79
|
let keys = [];
|
|
30
80
|
try {
|
|
31
81
|
keys = (await fetchLogKeys(base, f)).keys;
|
|
@@ -60,6 +110,8 @@ export async function checkLog(o) {
|
|
|
60
110
|
}
|
|
61
111
|
if (!head)
|
|
62
112
|
continue;
|
|
113
|
+
if (o.anchorUrl)
|
|
114
|
+
await anchorChecks(tenant, head);
|
|
63
115
|
if (!o.checkpointsUrl)
|
|
64
116
|
continue;
|
|
65
117
|
const cpBase = o.checkpointsUrl.endsWith("/") ? o.checkpointsUrl : `${o.checkpointsUrl}/`;
|
package/dist/policy.d.ts
CHANGED
|
@@ -16,6 +16,8 @@ export interface PolicyRequest {
|
|
|
16
16
|
}
|
|
17
17
|
/** True when the policy set contains a permit rule. Cedar answers, so a `permit(` in a comment does not count. */
|
|
18
18
|
export declare function hasPermitRule(policyText: string): boolean;
|
|
19
|
+
/** Why Cedar cannot parse the policy set, or an empty list when it can. */
|
|
20
|
+
export declare function policyParseErrors(policyText: string): string[];
|
|
19
21
|
export declare function policyDigest(policyText: string): string;
|
|
20
22
|
/**
|
|
21
23
|
* Cedar's JSON context reads `{ "__entity": … }` and `{ "__extn": … }` as typed values. Arguments come from the agent,
|
package/dist/policy.js
CHANGED
|
@@ -11,6 +11,11 @@ export function hasPermitRule(policyText) {
|
|
|
11
11
|
return j.type === "success" && j.json.effect === "permit";
|
|
12
12
|
});
|
|
13
13
|
}
|
|
14
|
+
/** Why Cedar cannot parse the policy set, or an empty list when it can. */
|
|
15
|
+
export function policyParseErrors(policyText) {
|
|
16
|
+
const parsed = cedar.checkParsePolicySet({ staticPolicies: policyText });
|
|
17
|
+
return parsed.type === "success" ? [] : parsed.errors.map((e) => e.message);
|
|
18
|
+
}
|
|
14
19
|
export function policyDigest(policyText) {
|
|
15
20
|
return sha256Hex(policyText);
|
|
16
21
|
}
|
package/dist/portal.js
CHANGED
|
@@ -222,6 +222,7 @@ export class PortalStore {
|
|
|
222
222
|
await this.init();
|
|
223
223
|
return (await this.client.query(`UPDATE ${this.p}members SET role = $3 WHERE user_id = $1 AND tenant_id = $2 AND ($3 = 'owner' OR role <> 'owner' OR EXISTS (SELECT 1 FROM ${this.p}members o WHERE o.tenant_id = $2 AND o.role = 'owner' AND o.user_id <> $1)) RETURNING user_id`, [userId, tenantId, role])).rows.length > 0;
|
|
224
224
|
}
|
|
225
|
+
// The removal record stays after a rejoin by invite. It has no effect while the user is a member: only findOrCreateSsoUser reads it, and only when the home tenant differs.
|
|
225
226
|
async removeMember(tenantId, userId) {
|
|
226
227
|
await this.init();
|
|
227
228
|
const gone = (await this.client.query(`DELETE FROM ${this.p}members WHERE user_id = $1 AND tenant_id = $2 AND (role <> 'owner' OR EXISTS (SELECT 1 FROM ${this.p}members o WHERE o.tenant_id = $2 AND o.role = 'owner' AND o.user_id <> $1)) RETURNING user_id`, [userId, tenantId])).rows.length > 0;
|
package/dist/receipt.d.ts
CHANGED
|
@@ -63,11 +63,13 @@ export interface ReconciliationEvidence {
|
|
|
63
63
|
export interface ReceiptPredicate {
|
|
64
64
|
receiptId: string;
|
|
65
65
|
timestamp: string;
|
|
66
|
+
/** `strict` is the gateway's own statement that it ran in strict mode: every call precommitted to a remote, hash-only log, and no outbox */
|
|
66
67
|
issuer: {
|
|
67
68
|
kind: IssuerKind;
|
|
68
69
|
keyid: string;
|
|
69
70
|
version: string;
|
|
70
71
|
framework?: string;
|
|
72
|
+
strict?: boolean;
|
|
71
73
|
};
|
|
72
74
|
principal: {
|
|
73
75
|
id: string;
|
package/dist/simulate.d.ts
CHANGED
|
@@ -27,6 +27,8 @@ export interface SimulationReport {
|
|
|
27
27
|
total: number;
|
|
28
28
|
evaluated: number;
|
|
29
29
|
unchanged: number;
|
|
30
|
+
/** Reconciliation receipts. Each is a provider read with no policy decision, so a replay counts it here and not in `evaluated` or `skipped`. */
|
|
31
|
+
reconciliations: number;
|
|
30
32
|
complete: boolean;
|
|
31
33
|
changes: SimulationChange[];
|
|
32
34
|
skipped: SimulationSkip[];
|
|
@@ -50,7 +52,11 @@ export declare function verifyOrphanAuthorization(bundle: AuthorizationBundle, i
|
|
|
50
52
|
/**
|
|
51
53
|
* Compare a proposed Cedar policy with recorded policy decisions, using each receipt's original arguments, fact
|
|
52
54
|
* values, agent, and (for gateways) grant context. Observe-mode decisions are the baseline even when the call ran.
|
|
53
|
-
* Receipts are not signature-verified here; verify their bundles separately when their authenticity matters.
|
|
55
|
+
* Receipts are not signature-verified here; verify their bundles separately when their authenticity matters. A
|
|
56
|
+
* reconciliation receipt is trusted as a provider read only after `verifyBundle` accepts it: the library checks no more
|
|
57
|
+
* than its shape and its link to an original receipt id.
|
|
58
|
+
* A reconciliation whose original receipt is not among the supplied receipts or `unreplayable` is reported as skipped,
|
|
59
|
+
* because the call it settles cannot be replayed.
|
|
54
60
|
* Missing inputs and non-Cedar gate failures are reported as skipped, never guessed or fetched again.
|
|
55
61
|
* The receipts are read once, one at a time, so a caller can verify and parse a large history lazily.
|
|
56
62
|
*/
|
package/dist/simulate.js
CHANGED
|
@@ -57,7 +57,11 @@ export function verifyOrphanAuthorization(bundle, issuerKeys, logKeys) {
|
|
|
57
57
|
/**
|
|
58
58
|
* Compare a proposed Cedar policy with recorded policy decisions, using each receipt's original arguments, fact
|
|
59
59
|
* values, agent, and (for gateways) grant context. Observe-mode decisions are the baseline even when the call ran.
|
|
60
|
-
* Receipts are not signature-verified here; verify their bundles separately when their authenticity matters.
|
|
60
|
+
* Receipts are not signature-verified here; verify their bundles separately when their authenticity matters. A
|
|
61
|
+
* reconciliation receipt is trusted as a provider read only after `verifyBundle` accepts it: the library checks no more
|
|
62
|
+
* than its shape and its link to an original receipt id.
|
|
63
|
+
* A reconciliation whose original receipt is not among the supplied receipts or `unreplayable` is reported as skipped,
|
|
64
|
+
* because the call it settles cannot be replayed.
|
|
61
65
|
* Missing inputs and non-Cedar gate failures are reported as skipped, never guessed or fetched again.
|
|
62
66
|
* The receipts are read once, one at a time, so a caller can verify and parse a large history lazily.
|
|
63
67
|
*/
|
|
@@ -74,22 +78,37 @@ export function simulatePolicy(policyText, receipts, options = {}) {
|
|
|
74
78
|
total: unreplayable.length,
|
|
75
79
|
evaluated: 0,
|
|
76
80
|
unchanged: 0,
|
|
81
|
+
reconciliations: 0,
|
|
77
82
|
complete: true,
|
|
78
83
|
changes: [],
|
|
79
84
|
skipped: [...unreplayable],
|
|
80
85
|
groups: [],
|
|
81
86
|
};
|
|
82
87
|
const digests = new Set();
|
|
88
|
+
const seen = new Set(unreplayable.map((u) => u.receiptId));
|
|
89
|
+
const reconciled = [];
|
|
83
90
|
for (const original of receipts) {
|
|
84
91
|
report.total++;
|
|
85
92
|
const receiptId = typeof original?.receiptId === "string" ? original.receiptId : "(unknown receipt)";
|
|
86
93
|
const tool = typeof original?.tool?.name === "string" ? original.tool.name : "(unknown tool)";
|
|
87
94
|
const skip = (reason) => { report.skipped.push({ receiptId, tool, reason }); };
|
|
95
|
+
if (original?.reconciliation === undefined)
|
|
96
|
+
seen.add(receiptId);
|
|
88
97
|
const broken = structuralProblem(original);
|
|
89
98
|
if (broken) {
|
|
90
99
|
skip(`malformed receipt: ${broken}`);
|
|
91
100
|
continue;
|
|
92
101
|
}
|
|
102
|
+
if (original.reconciliation !== undefined) {
|
|
103
|
+
const link = original.operation?.originalReceiptId;
|
|
104
|
+
if (original.issuer.kind !== "gateway" || typeof link !== "string" || link === receiptId) {
|
|
105
|
+
skip("malformed receipt: a reconciliation needs a gateway issuer and an operation that names another receipt");
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
report.reconciliations++;
|
|
109
|
+
reconciled.push({ receiptId: link, tool, reason: `only the reconciliation ${receiptId} survives; the original receipt is missing, so the call cannot be replayed` });
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
93
112
|
if (original.policy === null) {
|
|
94
113
|
skip("no recorded policy decision (record-only receipt)");
|
|
95
114
|
continue;
|
|
@@ -166,6 +185,12 @@ export function simulatePolicy(policyText, receipts, options = {}) {
|
|
|
166
185
|
else
|
|
167
186
|
report.changes.push({ receiptId, tool, previous, proposed });
|
|
168
187
|
}
|
|
188
|
+
for (const lost of reconciled) {
|
|
189
|
+
if (seen.has(lost.receiptId))
|
|
190
|
+
continue;
|
|
191
|
+
report.reconciliations--;
|
|
192
|
+
report.skipped.push(lost);
|
|
193
|
+
}
|
|
169
194
|
report.previousPolicyDigests = [...digests].sort(order);
|
|
170
195
|
report.complete = report.skipped.length === 0;
|
|
171
196
|
const groups = new Map();
|
|
@@ -188,7 +213,7 @@ export function formatSimulation(report) {
|
|
|
188
213
|
`Timestamp: ${report.timestamp}`,
|
|
189
214
|
`Proposed policy: ${report.policyDigest}`,
|
|
190
215
|
`Previous policies: ${report.previousPolicyDigests.join(", ") || "none"}`,
|
|
191
|
-
`Receipts: ${report.total}; evaluated: ${report.evaluated}; unchanged: ${report.unchanged}; changed: ${report.changes.length}; skipped: ${report.skipped.length}`,
|
|
216
|
+
`Receipts: ${report.total}; evaluated: ${report.evaluated}; unchanged: ${report.unchanged}; reconciliations: ${report.reconciliations}; changed: ${report.changes.length}; skipped: ${report.skipped.length}`,
|
|
192
217
|
];
|
|
193
218
|
for (const group of report.groups) {
|
|
194
219
|
lines.push("", `${group.tool}: ${group.reason}`);
|
package/dist/verify.d.ts
CHANGED
|
@@ -22,6 +22,8 @@ export interface VerifyOptions {
|
|
|
22
22
|
logFile?: string;
|
|
23
23
|
/** If given, every tree head in the bundle must name this log, so a head from another tenant's log cannot be presented as this one's. */
|
|
24
24
|
logId?: string;
|
|
25
|
+
/** Require a strict gateway receipt: one whose issuer says it ran in strict mode, and whose call, if forwarded, carries the authorization committed before it. */
|
|
26
|
+
requireStrict?: boolean;
|
|
25
27
|
/**
|
|
26
28
|
* The withheld values, as `agent-custody reveal` writes them or the party that holds them hands them over: a partial
|
|
27
29
|
* predicate with `{ $custody: "disclosed", salt, value }` at each withheld path (`{ receiptId, request: { args: { reason: {...} } }, execution: { result: { content: {...} }, error, upstream: { rawBody } }, policy: { errors }, facts: { <name>: { value, args } } }`).
|
package/dist/verify.js
CHANGED
|
@@ -186,6 +186,12 @@ export function verifyBundle(bundle, opts) {
|
|
|
186
186
|
const p = st.predicate;
|
|
187
187
|
add("issuer kind is known", p.issuer.kind === "gateway" || p.issuer.kind === "sdk", `${p.issuer.kind}${p.issuer.framework ? ` / ${p.issuer.framework}` : ""}`);
|
|
188
188
|
add("issuer keyid matches signer", p.issuer.keyid === sig.keyid);
|
|
189
|
+
if (opts.requireStrict) {
|
|
190
|
+
add("strict mode in force", p.issuer.kind === "gateway" && p.issuer.strict === true, p.issuer.strict === true ? undefined : "the issuer does not say it ran in strict mode");
|
|
191
|
+
// under strict mode every call is precommitted; a provider read the operator ran is a lookup, not a call
|
|
192
|
+
const forwarded = p.execution.status === "executed" || p.execution.status === "failed" || p.execution.status === "error";
|
|
193
|
+
add("strict: call precommitted before forwarding", !forwarded || !!p.reconciliation || !!p.authorization, forwarded && !p.reconciliation && !p.authorization ? `the call was ${p.execution.status} with no authorization committed first` : undefined);
|
|
194
|
+
}
|
|
189
195
|
if (p.operation) {
|
|
190
196
|
add("operation observed by gateway", p.issuer.kind === "gateway" && p.operation.provenance === "observed");
|
|
191
197
|
if (!p.reconciliation) {
|
|
@@ -547,7 +553,7 @@ export function formatReport(r) {
|
|
|
547
553
|
return lines.join("\n");
|
|
548
554
|
const p = r.statement.predicate;
|
|
549
555
|
lines.push("");
|
|
550
|
-
lines.push(`ISSUER: ${p.issuer.kind}${p.issuer.framework ? ` (${p.issuer.framework})` : ""}, ${ISSUER_NOTE[p.issuer.kind] ?? "unknown issuer kind"}`);
|
|
556
|
+
lines.push(`ISSUER: ${p.issuer.kind}${p.issuer.framework ? ` (${p.issuer.framework})` : ""}${p.issuer.strict ? ", strict mode" : ""}, ${ISSUER_NOTE[p.issuer.kind] ?? "unknown issuer kind"}`);
|
|
551
557
|
lines.push("");
|
|
552
558
|
lines.push("field provenance value");
|
|
553
559
|
const row = (f, prov, v) => lines.push(`${f.padEnd(15)} ${prov.padEnd(11)} ${typeof v === "string" ? v : JSON.stringify(v)}`);
|
|
@@ -561,7 +567,9 @@ export function formatReport(r) {
|
|
|
561
567
|
row("args", p.request.provenance, p.request.args);
|
|
562
568
|
for (const [k, f] of Object.entries(p.facts))
|
|
563
569
|
row(`fact.${k}`, f.provenance, f.value);
|
|
564
|
-
if (p.
|
|
570
|
+
if (p.reconciliation)
|
|
571
|
+
row("policy", "-", "(none evaluated: a provider read, not a call)");
|
|
572
|
+
else if (p.policy)
|
|
565
573
|
row("policy", p.policy.provenance, `${p.policy.decision}${p.policy.enforced === false ? " (observe mode, not enforced)" : ""} [${p.policy.reasons.join(",")}] policy ${short(p.policy.policyDigest)}`);
|
|
566
574
|
else
|
|
567
575
|
row("policy", "-", "(none evaluated)");
|
|
@@ -583,6 +591,6 @@ export function formatReport(r) {
|
|
|
583
591
|
// a refusal says why, as the receipt records it; under a capture rule the reason is a commitment, and the report says so rather than printing it
|
|
584
592
|
const reason = "reason" in p.execution ? p.execution.reason : undefined;
|
|
585
593
|
const why = reason === undefined ? "" : typeof reason === "string" ? `: ${reason}` : ": (reason withheld under the capture rule)";
|
|
586
|
-
row("execution", attestedAs, `${p.execution.status}${why}${note}`);
|
|
594
|
+
row("execution", attestedAs, `${p.reconciliation ? "provider read, " : ""}${p.execution.status}${why}${note}`);
|
|
587
595
|
return lines.join("\n");
|
|
588
596
|
}
|