@agent-custody/receipts 0.14.0 → 0.15.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.
Files changed (48) hide show
  1. package/README.md +33 -20
  2. package/dist/check.d.ts +10 -0
  3. package/dist/check.js +179 -3
  4. package/dist/cli.js +82 -11
  5. package/dist/config.d.ts +128 -1
  6. package/dist/config.js +92 -3
  7. package/dist/console.js +16 -7
  8. package/dist/deny-report.js +1 -1
  9. package/dist/door.d.ts +203 -0
  10. package/dist/door.js +712 -0
  11. package/dist/export.d.ts +39 -0
  12. package/dist/export.js +95 -0
  13. package/dist/gateway.js +53 -21
  14. package/dist/index.d.ts +6 -0
  15. package/dist/index.js +5 -0
  16. package/dist/issue.js +5 -65
  17. package/dist/lock.d.ts +12 -0
  18. package/dist/lock.js +124 -0
  19. package/dist/log.d.ts +11 -5
  20. package/dist/log.js +55 -42
  21. package/dist/opa-server.d.ts +34 -0
  22. package/dist/opa-server.js +93 -0
  23. package/dist/policy-rego.d.ts +30 -0
  24. package/dist/policy-rego.js +114 -0
  25. package/dist/pr-summary.d.ts +25 -0
  26. package/dist/pr-summary.js +87 -0
  27. package/dist/receipt.d.ts +3 -1
  28. package/dist/retention.d.ts +1 -1
  29. package/dist/retention.js +14 -4
  30. package/dist/sdk/index.js +10 -3
  31. package/dist/simulate.d.ts +3 -1
  32. package/dist/simulate.js +15 -7
  33. package/dist/verify.js +6 -3
  34. package/docs/configuration.md +3 -3
  35. package/docs/door-signals.md +66 -0
  36. package/docs/door.md +168 -0
  37. package/docs/github-action.md +164 -0
  38. package/docs/policies.md +112 -1
  39. package/docs/sdk.md +25 -9
  40. package/docs/tutorials.md +3 -0
  41. package/docs/usage.md +2 -2
  42. package/docs/verification.md +9 -2
  43. package/package.json +14 -13
  44. package/templates/claude-code.cedar +287 -10
  45. package/vectors/audit.json +27 -27
  46. package/vectors/canonical.json +5 -5
  47. package/vectors/merkle.json +123 -0
  48. package/vectors/receipts.json +1258 -1005
package/dist/log.js CHANGED
@@ -1,8 +1,9 @@
1
1
  // Append-only Merkle log with RFC 6962 / RFC 9162 hashing and inclusion proofs.
2
2
  // Leaves are stored as JSONL so anyone holding the file can recompute the root.
3
3
  import { createHash } from "node:crypto";
4
- import { appendFileSync, closeSync, mkdirSync, openSync, readSync, statSync, unlinkSync } from "node:fs";
4
+ import { appendFileSync, closeSync, mkdirSync, openSync, readSync, statSync, truncateSync } from "node:fs";
5
5
  import { dirname } from "node:path";
6
+ import { withLock } from "./lock.js";
6
7
  const h = (...parts) => {
7
8
  const c = createHash("sha256");
8
9
  for (const p of parts)
@@ -13,6 +14,14 @@ export function leafHash(data) {
13
14
  return h(Buffer.from([0x00]), Buffer.from(data));
14
15
  }
15
16
  const nodeHash = (l, r) => h(Buffer.from([0x01]), l, r);
17
+ // Every hash a proof check reads is 32 bytes: a proof hash and a root are each a string of 64 lowercase hex digits, as
18
+ // the Python verifier requires. Checked before the loop: with children of other widths, sha256(0x01 || left || right)
19
+ // no longer fixes where one child ends and the other begins.
20
+ const HASH_HEX = /^[0-9a-f]{64}$/;
21
+ const isHash = (x) => typeof x === "string" && HASH_HEX.test(x);
22
+ const EMPTY_ROOT = createHash("sha256").digest("hex");
23
+ // Sizes and indices are integers. The loops halve them with Math.floor, so a fraction such as 6.5 can walk a real path.
24
+ const isSize = (n) => Number.isSafeInteger(n) && n >= 0;
16
25
  /** largest power of two strictly less than n (n >= 2) */
17
26
  function split(n) {
18
27
  let k = 1;
@@ -78,18 +87,21 @@ export function consistencyProof(leafHashes, oldSize, newSize = leafHashes.lengt
78
87
  return subproof(oldSize, leafHashes, 0, newSize, true).map((b) => b.toString("hex"));
79
88
  }
80
89
  /** RFC 9162 section 2.1.4.2. Pure: needs only the two sizes, the two roots, and the proof. */
81
- export function verifyConsistency(oldSize, oldRootHex, newSize, newRootHex, proofHex) {
82
- if (oldSize < 0 || oldSize > newSize)
90
+ export function verifyConsistency(oldSize, oldRoot, newSize, newRoot, proofHex) {
91
+ if (!isSize(oldSize) || !isSize(newSize) || oldSize > newSize)
83
92
  return false;
84
- if (oldSize === newSize)
85
- return proofHex.length === 0 && oldRootHex === newRootHex;
93
+ if (!isHash(oldRoot) || !isHash(newRoot) || !Array.isArray(proofHex) || !proofHex.every(isHash))
94
+ return false;
95
+ // the empty tree has one root, sha256 of nothing; any other root at size 0, old or new, is a head no log could have signed
86
96
  if (oldSize === 0)
87
- return proofHex.length === 0;
97
+ return proofHex.length === 0 && oldRoot === EMPTY_ROOT && (newSize > 0 || newRoot === EMPTY_ROOT);
98
+ if (oldSize === newSize)
99
+ return proofHex.length === 0 && oldRoot === newRoot;
88
100
  if (proofHex.length === 0)
89
101
  return false;
90
102
  const proof = proofHex.map((x) => Buffer.from(x, "hex"));
91
103
  if ((oldSize & (oldSize - 1)) === 0)
92
- proof.unshift(Buffer.from(oldRootHex, "hex"));
104
+ proof.unshift(Buffer.from(oldRoot, "hex"));
93
105
  let fn = oldSize - 1;
94
106
  let sn = newSize - 1;
95
107
  while (fn % 2 === 1) {
@@ -115,7 +127,7 @@ export function verifyConsistency(oldSize, oldRootHex, newSize, newRootHex, proo
115
127
  fn = Math.floor(fn / 2);
116
128
  sn = Math.floor(sn / 2);
117
129
  }
118
- return sn === 0 && fr.toString("hex") === oldRootHex && sr.toString("hex") === newRootHex;
130
+ return sn === 0 && fr.toString("hex") === oldRoot && sr.toString("hex") === newRoot;
119
131
  }
120
132
  export function rootOf(leafHashes, size = leafHashes.length) {
121
133
  return mth(leafHashes, 0, size).toString("hex");
@@ -127,10 +139,14 @@ export function inclusionProof(leafHashes, leafIndex, treeSize = leafHashes.leng
127
139
  }
128
140
  /** RFC 9162 section 2.1.3.2 verification. Pure function: needs only the leaf hash, proof and claimed root. */
129
141
  export function verifyInclusion(leaf, proof, rootHex) {
142
+ if (!isSize(proof.leafIndex) || !isSize(proof.treeSize))
143
+ return false;
130
144
  let fn = proof.leafIndex;
131
145
  let sn = proof.treeSize - 1;
132
146
  if (fn < 0 || sn < 0 || fn > sn)
133
147
  return false;
148
+ if (leaf.length !== 32 || !isHash(rootHex) || !Array.isArray(proof.hashes) || !proof.hashes.every(isHash))
149
+ return false;
134
150
  let r = leaf;
135
151
  for (const hex of proof.hashes) {
136
152
  if (sn === 0)
@@ -153,9 +169,12 @@ export function verifyInclusion(leaf, proof, rootHex) {
153
169
  }
154
170
  return sn === 0 && r.toString("hex") === rootHex;
155
171
  }
156
- const LOCK_STALE_MS = 10_000;
157
- const LOCK_WAIT_MS = 20_000;
158
- const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
172
+ const LOCK_STALE_MS = 60_000;
173
+ const LOG_LOCK_WAIT_MS = 20_000;
174
+ /** Each hook of a coding agent is its own process, so appends overlap: one writer at a time holds `<file>.lock`. */
175
+ export function logLocked(file, fn) {
176
+ return withLock(`${file}.lock`, { staleMs: LOCK_STALE_MS, waitMs: LOG_LOCK_WAIT_MS }, fn);
177
+ }
159
178
  export class MerkleLog {
160
179
  hashes = [];
161
180
  tree = new SubtreeCache(this.hashes);
@@ -167,7 +186,11 @@ export class MerkleLog {
167
186
  mkdirSync(dirname(file), { recursive: true });
168
187
  this.catchUp();
169
188
  }
170
- /** Reads the leaves that another handle or process appended since the last read. A file that was replaced or cut short is read again from the start. */
189
+ /**
190
+ * Reads the leaves that another handle or process appended since the last read. A file that was replaced or cut
191
+ * short is read again from the start. Bytes after the last newline are not read: a writer may be in the middle of its
192
+ * write, or may have died in it.
193
+ */
171
194
  catchUp() {
172
195
  let st;
173
196
  try {
@@ -200,6 +223,7 @@ export class MerkleLog {
200
223
  finally {
201
224
  closeSync(fd);
202
225
  }
226
+ got = buf.subarray(0, got).lastIndexOf(0x0a) + 1;
203
227
  this.bytes += got;
204
228
  for (const line of buf.subarray(0, got).toString("utf8").split("\n")) {
205
229
  if (!line.trim())
@@ -211,46 +235,35 @@ export class MerkleLog {
211
235
  }
212
236
  }
213
237
  /**
214
- * Runs `fn` while this process holds `<file>.lock`, made with O_EXCL. Each hook of a coding agent is its own
215
- * process, so appends overlap. A lock older than ten seconds belongs to a process that died: the next writer removes it.
238
+ * Under the lock: a last line with no newline is the remains of a writer that died in the middle of its write. No
239
+ * leaf was acknowledged for it. The bytes go to `<file>.torn`, so no data is lost, and the file ends after the last whole line.
216
240
  */
217
- locked(fn) {
218
- const lock = `${this.file}.lock`;
219
- const deadline = Date.now() + LOCK_WAIT_MS;
220
- for (;;) {
221
- try {
222
- closeSync(openSync(lock, "wx"));
223
- break;
224
- }
225
- catch (e) {
226
- if (e.code !== "EEXIST")
227
- throw e;
228
- }
229
- try {
230
- if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS)
231
- unlinkSync(lock);
232
- }
233
- catch {
234
- // The holder released the lock between the two calls. Try again.
235
- }
236
- if (Date.now() > deadline)
237
- throw new Error(`${lock} is held by another process, so the log is not appended. Remove the file if no agent-custody process runs.`);
238
- pause(2 + Math.random() * 8);
241
+ cutTornTail() {
242
+ let size;
243
+ try {
244
+ size = statSync(this.file).size;
245
+ }
246
+ catch {
247
+ return;
239
248
  }
249
+ if (size <= this.bytes)
250
+ return;
251
+ const tail = Buffer.alloc(size - this.bytes);
252
+ const fd = openSync(this.file, "r");
240
253
  try {
241
- return fn();
254
+ readSync(fd, tail, 0, tail.length, this.bytes);
242
255
  }
243
256
  finally {
244
- try {
245
- unlinkSync(lock);
246
- }
247
- catch { /* a writer removed it as stale */ }
257
+ closeSync(fd);
248
258
  }
259
+ appendFileSync(`${this.file}.torn`, tail, { mode: 0o600 });
260
+ truncateSync(this.file, this.bytes);
249
261
  }
250
262
  /** Under the lock: reads what other writers appended, then writes this line, so each leaf gets the next index. */
251
263
  appendLine(line, hash) {
252
- return this.locked(() => {
264
+ return logLocked(this.file, () => {
253
265
  this.catchUp();
266
+ this.cutTornTail();
254
267
  appendFileSync(this.file, line);
255
268
  this.bytes += Buffer.byteLength(line);
256
269
  return this.pushHash(hash());
@@ -0,0 +1,34 @@
1
+ import type { PolicyDecision, PolicyRequest } from "./policy.ts";
2
+ export interface OpaServerConfig {
3
+ /** the OPA server, e.g. http://localhost:8181 */
4
+ url: string;
5
+ /** the package whose `allow` and `deny` rules decide, as a path under /v1/data; default agentcustody */
6
+ decision?: string;
7
+ /** environment variable holding a bearer token for the server */
8
+ tokenEnv?: string;
9
+ /** milliseconds one query may take; past that the call is denied. Default 2000 */
10
+ timeoutMs?: number;
11
+ }
12
+ export interface OpaProvenance {
13
+ /** the policy digest receipts carry while this provenance holds */
14
+ digest: string;
15
+ /** the decision URL, without its query */
16
+ decision: string;
17
+ /** bundle name to revision, as the server reports them; null when the server did not answer */
18
+ bundles: Record<string, string> | null;
19
+ }
20
+ export interface OpaServerPolicy {
21
+ /** the decision for one call; any failure to get a well-formed answer is a deny */
22
+ decide(req: PolicyRequest): Promise<PolicyDecision>;
23
+ /** the digest of the provenance seen last */
24
+ digest(): string;
25
+ /** queries the server once without input, so a gateway that cannot reach it, or reaches one without the package, does not start */
26
+ probe(): Promise<void>;
27
+ }
28
+ /** Bundle revisions out of OPA's `provenance` object: `bundles.<name>.revision`, or the older top-level `revision`. */
29
+ export declare function opaRevisions(provenance: unknown): Record<string, string>;
30
+ /** The policy digest for a decision URL and the bundles that answered; with null, for a call the server did not answer. */
31
+ export declare function opaDigest(decision: string, bundles: Record<string, string> | null): string;
32
+ /** Why the gateway will not send calls to this URL, or null: https anywhere, http only to a loopback address. */
33
+ export declare function opaUrlProblem(url: string): string | null;
34
+ export declare function createOpaServerPolicy(cfg: OpaServerConfig, onProvenance: (p: OpaProvenance) => void): OpaServerPolicy;
@@ -0,0 +1,93 @@
1
+ // An OPA server the operator runs, asked for every call through its Data API. The gateway holds no policy text then,
2
+ // so a receipt cannot pin the text's sha256 as it does for a local file. It pins what the server reports instead: the
3
+ // sha256 of the decision URL and the revision of each bundle loaded, with provenance=true on every query. Each new
4
+ // digest is recorded with what it stands for, so a receipt's policyDigest maps back to a bundle revision. A call the
5
+ // server did not answer is receipted under the decision URL's "unanswered" digest, never a revision that did not decide it.
6
+ // The query carries the call's arguments and the bearer token, so the server must be https, or http on a loopback address,
7
+ // and a redirect is refused rather than followed.
8
+ import { sha256Hex } from "./crypto.js";
9
+ import { REGO_PACKAGE, regoDecision, regoInput } from "./policy-rego.js";
10
+ /** Bundle revisions out of OPA's `provenance` object: `bundles.<name>.revision`, or the older top-level `revision`. */
11
+ export function opaRevisions(provenance) {
12
+ const out = {};
13
+ if (!provenance || typeof provenance !== "object")
14
+ return out;
15
+ const p = provenance;
16
+ if (typeof p.revision === "string" && p.revision)
17
+ out[""] = p.revision;
18
+ for (const [name, b] of Object.entries(p.bundles ?? {}))
19
+ if (b && typeof b.revision === "string")
20
+ out[name] = b.revision;
21
+ return out;
22
+ }
23
+ /** The policy digest for a decision URL and the bundles that answered; with null, for a call the server did not answer. */
24
+ export function opaDigest(decision, bundles) {
25
+ return sha256Hex(JSON.stringify({ decision, bundles: bundles === null ? null : Object.keys(bundles).sort().map((name) => [name, bundles[name]]) }));
26
+ }
27
+ const LOOPBACK = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/i;
28
+ /** Why the gateway will not send calls to this URL, or null: https anywhere, http only to a loopback address. */
29
+ export function opaUrlProblem(url) {
30
+ const u = new URL(url);
31
+ if (u.protocol === "https:")
32
+ return null;
33
+ if (u.protocol === "http:" && LOOPBACK.test(u.hostname))
34
+ return null;
35
+ return `${u.origin} is not https or a loopback address; the query carries each call's arguments and the bearer token`;
36
+ }
37
+ export function createOpaServerPolicy(cfg, onProvenance) {
38
+ const path = (cfg.decision ?? REGO_PACKAGE).replace(/^\/+|\/+$/g, "").replaceAll(".", "/");
39
+ const decision = new URL(`v1/data/${path}`, cfg.url.endsWith("/") ? cfg.url : `${cfg.url}/`).toString();
40
+ const rule = `data.${path.replaceAll("/", ".")}`;
41
+ const where = `${rule} on ${new URL(cfg.url).origin}`;
42
+ const problem = opaUrlProblem(cfg.url);
43
+ if (problem)
44
+ throw new Error(`opa: ${problem}`);
45
+ const token = cfg.tokenEnv ? process.env[cfg.tokenEnv] ?? (() => { throw new Error(`opa: environment variable ${cfg.tokenEnv} is not set`); })() : undefined;
46
+ let current = opaDigest(decision, {});
47
+ const unanswered = opaDigest(decision, null);
48
+ const seen = new Set();
49
+ const note = (p) => {
50
+ if (seen.has(p.digest))
51
+ return;
52
+ seen.add(p.digest);
53
+ onProvenance(p);
54
+ };
55
+ const query = async (input) => {
56
+ const res = await fetch(`${decision}?provenance=true`, {
57
+ method: "POST",
58
+ headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
59
+ body: JSON.stringify(input === undefined ? {} : { input }),
60
+ signal: AbortSignal.timeout(cfg.timeoutMs ?? 2000),
61
+ redirect: "manual",
62
+ });
63
+ if (res.status >= 300 && res.status < 400)
64
+ throw new Error(`OPA server answered a redirect (${res.status}); the gateway does not follow it`);
65
+ if (!res.ok)
66
+ throw new Error(`OPA server answered ${res.status} ${res.statusText}`.trim());
67
+ const body = await res.json();
68
+ const bundles = opaRevisions(body.provenance);
69
+ const digest = opaDigest(decision, bundles);
70
+ note({ digest, decision, bundles });
71
+ current = digest;
72
+ return { result: body.result, digest };
73
+ };
74
+ return {
75
+ async decide(req) {
76
+ try {
77
+ const { result, digest } = await query(regoInput(req));
78
+ return regoDecision(result, digest, rule, where);
79
+ }
80
+ catch (e) {
81
+ // no answer, or none that parsed: no revision decided this call
82
+ note({ digest: unanswered, decision, bundles: null });
83
+ return { decision: "deny", reasons: [], errors: [`opa: ${e instanceof Error ? e.message : String(e)}`], policyDigest: unanswered };
84
+ }
85
+ },
86
+ digest: () => current,
87
+ async probe() {
88
+ const { result } = await query();
89
+ if (result === undefined)
90
+ throw new Error(`opa: ${where} is undefined; load a policy with package ${path.replaceAll("/", ".")}`);
91
+ },
92
+ };
93
+ }
@@ -0,0 +1,30 @@
1
+ import type { PolicyDecision, PolicyRequest } from "./policy.ts";
2
+ declare const opa: typeof import("@open-policy-agent/opa-wasm");
3
+ /** The package a Rego policy file declares. Its `allow` and `deny` rules are the decision. */
4
+ export declare const REGO_PACKAGE = "agentcustody";
5
+ export type RegoPolicy = ReturnType<typeof opa.loadPolicySync>;
6
+ export declare function isRegoFile(path: string): boolean;
7
+ /**
8
+ * The input a Rego policy reads: the Cedar request with plain strings for the three identifiers. `context` holds `args`
9
+ * (claimed), `facts` (observed), and `grant` (attested), exactly as Cedar sees them.
10
+ */
11
+ export declare function regoInput(req: PolicyRequest): Record<string, unknown>;
12
+ /**
13
+ * The decision from the document the policy package evaluates to. Default deny: `allow` must be exactly `true`. Any
14
+ * entry in `deny` wins over `allow`, as a Cedar `forbid` wins over a `permit`, and its strings are the reasons. A
15
+ * document of the wrong shape is an error, and an error is a deny.
16
+ */
17
+ export declare function regoDecision(doc: unknown, policyDigest: string, rule?: string, where?: string): PolicyDecision;
18
+ export declare function evaluateRego(policy: RegoPolicy, policyDigest: string, req: PolicyRequest): PolicyDecision;
19
+ /**
20
+ * Compiles Rego text with the opa binary on PATH. Answers the loaded policy, or why it cannot be used: a syntax or type
21
+ * error, a builtin the SDK cannot run, no `package agentcustody`, or no opa binary.
22
+ */
23
+ export declare function compileRego(text: string, opaBin?: string): {
24
+ policy: RegoPolicy;
25
+ errors: [];
26
+ } | {
27
+ policy?: undefined;
28
+ errors: string[];
29
+ };
30
+ export {};
@@ -0,0 +1,114 @@
1
+ // Rego policies. A policy file ending in .rego is compiled once per change with `opa build -t wasm` and evaluated
2
+ // in-process by the OPA WebAssembly SDK, so the opa binary is needed when the policy loads, never on a call. An OPA
3
+ // server the operator runs answers the same contract over HTTP (opa-server.ts). Either way, fails closed.
4
+ import { execFileSync } from "node:child_process";
5
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
+ import { createRequire } from "node:module";
7
+ import { tmpdir } from "node:os";
8
+ import { dirname, join } from "node:path";
9
+ import { gunzipSync } from "node:zlib";
10
+ // The SDK's ES module entry exports only the async loader; its CommonJS entry has loadPolicySync, which lets a policy
11
+ // load inside the gateway's synchronous reload, like a Cedar file.
12
+ const require = createRequire(import.meta.url);
13
+ const opa = require("@open-policy-agent/opa-wasm");
14
+ /** The package a Rego policy file declares. Its `allow` and `deny` rules are the decision. */
15
+ export const REGO_PACKAGE = "agentcustody";
16
+ export function isRegoFile(path) {
17
+ return path.toLowerCase().endsWith(".rego");
18
+ }
19
+ /**
20
+ * The input a Rego policy reads: the Cedar request with plain strings for the three identifiers. `context` holds `args`
21
+ * (claimed), `facts` (observed), and `grant` (attested), exactly as Cedar sees them.
22
+ */
23
+ export function regoInput(req) {
24
+ return { principal: req.agentId, action: req.tool, resource: req.tool, context: req.context };
25
+ }
26
+ /**
27
+ * The decision from the document the policy package evaluates to. Default deny: `allow` must be exactly `true`. Any
28
+ * entry in `deny` wins over `allow`, as a Cedar `forbid` wins over a `permit`, and its strings are the reasons. A
29
+ * document of the wrong shape is an error, and an error is a deny.
30
+ */
31
+ export function regoDecision(doc, policyDigest, rule = `data.${REGO_PACKAGE}`, where = rule) {
32
+ const deny = (errors, reasons = []) => ({ decision: "deny", reasons, errors, policyDigest });
33
+ if (doc === undefined)
34
+ return deny([`${where} is undefined`]);
35
+ if (!doc || typeof doc !== "object" || Array.isArray(doc))
36
+ return deny([`${where} is not an object with allow and deny rules`]);
37
+ const { allow, deny: denied } = doc;
38
+ if (allow !== undefined && typeof allow !== "boolean")
39
+ return deny([`${where}.allow is not a boolean`]);
40
+ if (denied !== undefined && (!Array.isArray(denied) || !denied.every((d) => typeof d === "string")))
41
+ return deny([`${where}.deny is not a set of strings`]);
42
+ if (denied && denied.length > 0)
43
+ return deny([], denied);
44
+ return allow === true ? { decision: "allow", reasons: [`${rule}.allow`], errors: [], policyDigest } : deny([]);
45
+ }
46
+ export function evaluateRego(policy, policyDigest, req) {
47
+ let result;
48
+ try {
49
+ result = policy.evaluate(regoInput(req), REGO_PACKAGE);
50
+ }
51
+ catch (e) {
52
+ return { decision: "deny", reasons: [], errors: [e instanceof Error ? e.message : String(e)], policyDigest };
53
+ }
54
+ const set = Array.isArray(result) ? result : [];
55
+ return regoDecision(set[0]?.result, policyDigest);
56
+ }
57
+ /** One file out of a gzipped tar, as `opa build` writes its bundle. */
58
+ function fromTarGz(gz, name) {
59
+ const tar = gunzipSync(gz);
60
+ for (let at = 0; at + 512 <= tar.length;) {
61
+ const header = tar.subarray(at, at + 512);
62
+ if (header.every((b) => b === 0))
63
+ return undefined;
64
+ const field = (from, to) => header.subarray(from, to).toString("utf8").replace(/\0.*$/s, "");
65
+ const path = [field(345, 500), field(0, 100)].filter(Boolean).join("/").replace(/^\/+/, "");
66
+ const size = parseInt(field(124, 136).trim() || "0", 8);
67
+ if (path === name && (field(156, 157) === "0" || field(156, 157) === ""))
68
+ return Buffer.from(tar.subarray(at + 512, at + 512 + size));
69
+ at += 512 + Math.ceil(size / 512) * 512;
70
+ }
71
+ return undefined;
72
+ }
73
+ let capabilities;
74
+ /**
75
+ * The builtins `opa build` may compile in: the current opa's capabilities, cut down to the builtins the WebAssembly
76
+ * SDK can run. A policy calling another one, such as `http.send` or `time.now_ns`, is refused when it loads, instead of
77
+ * failing on each call.
78
+ */
79
+ function sdkCapabilities(opaBin) {
80
+ if (capabilities)
81
+ return capabilities;
82
+ const sdkFile = join(dirname(require.resolve("@open-policy-agent/opa-wasm")), "..", "capabilities.json");
83
+ const supported = new Set(JSON.parse(readFileSync(sdkFile, "utf8")).builtins.map((b) => b.name));
84
+ const current = JSON.parse(execFileSync(opaBin, ["capabilities", "--current"], { encoding: "utf8" }));
85
+ capabilities = JSON.stringify({ ...current, builtins: current.builtins.filter((b) => supported.has(b.name)) });
86
+ return capabilities;
87
+ }
88
+ /**
89
+ * Compiles Rego text with the opa binary on PATH. Answers the loaded policy, or why it cannot be used: a syntax or type
90
+ * error, a builtin the SDK cannot run, no `package agentcustody`, or no opa binary.
91
+ */
92
+ export function compileRego(text, opaBin = "opa") {
93
+ const dir = mkdtempSync(join(tmpdir(), "agent-custody-rego-"));
94
+ try {
95
+ writeFileSync(join(dir, "policy.rego"), text);
96
+ writeFileSync(join(dir, "capabilities.json"), sdkCapabilities(opaBin));
97
+ execFileSync(opaBin, ["build", "-t", "wasm", "-e", REGO_PACKAGE, "--capabilities", "capabilities.json", "-o", "bundle.tar.gz", "policy.rego"], { cwd: dir, stdio: ["ignore", "pipe", "pipe"] });
98
+ const wasm = fromTarGz(readFileSync(join(dir, "bundle.tar.gz")), "policy.wasm");
99
+ if (!wasm)
100
+ return { errors: ["opa build wrote no policy.wasm"] };
101
+ return { policy: opa.loadPolicySync(wasm), errors: [] };
102
+ }
103
+ catch (e) {
104
+ const err = e;
105
+ if (err.code === "ENOENT")
106
+ return { errors: [`compiling a Rego policy needs the opa binary on PATH (${opaBin} was not found)`] };
107
+ const said = [err.stderr, err.stdout].map((b) => b?.toString("utf8").trim() ?? "").filter(Boolean).join("\n");
108
+ const message = said ? said.replace(/^error: /, "") : err.message;
109
+ return { errors: [/entrypoint "[^"]*" does not refer to a rule/.test(message) ? `${message}: the policy must declare package ${REGO_PACKAGE}` : message] };
110
+ }
111
+ finally {
112
+ rmSync(dir, { recursive: true, force: true });
113
+ }
114
+ }
@@ -0,0 +1,25 @@
1
+ import { type VerifyOptions } from "./verify.ts";
2
+ /** The action finds its own comment again by this line, so it edits one comment and never adds a second. */
3
+ export declare const SUMMARY_MARKER = "<!-- agent-custody -->";
4
+ export interface SummaryRow {
5
+ file: string;
6
+ receiptId: string;
7
+ tool: string;
8
+ /** the execution status in the signed receipt, or "-" when the signature fails and nothing in the receipt is trusted */
9
+ status: string;
10
+ /** "verified", or the names of the checks that failed, joined with "; " */
11
+ result: string;
12
+ ok: boolean;
13
+ }
14
+ export interface PrSummary {
15
+ ok: boolean;
16
+ rows: SummaryRow[];
17
+ /** set when no receipt was read */
18
+ problem?: string;
19
+ }
20
+ /** The bundle files of a directory (not the `<id>.authorization.json` files, not the subdirectories, not the symbolic links), or the one file given. A path that does not exist holds no receipts. */
21
+ export declare function receiptFiles(path: string): string[];
22
+ /** Verifies each file. Fails when a receipt does not verify, and when there is no receipt at all. */
23
+ export declare function summarizeReceipts(files: string[], opts: VerifyOptions): PrSummary;
24
+ /** The pull request comment and the job summary. It starts with the marker line. */
25
+ export declare function formatSummaryMarkdown(s: PrSummary): string;
@@ -0,0 +1,87 @@
1
+ // `agent-custody verify --markdown`: verifies every receipt bundle in a directory and prints one table for a pull request.
2
+ // The GitHub Action in action.yml posts this table. The module reads files and calls the verifier. It never uses the network.
3
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
4
+ import { basename, join } from "node:path";
5
+ import { verifyBundle } from "./verify.js";
6
+ /** The action finds its own comment again by this line, so it edits one comment and never adds a second. */
7
+ export const SUMMARY_MARKER = "<!-- agent-custody -->";
8
+ const AUTHORIZATION = ".authorization.json";
9
+ const MAX_ROWS = 200;
10
+ const MAX_NAMES = 3;
11
+ const KNOWN_STATUS = new Set(["executed", "denied", "failed", "error", "withheld"]);
12
+ /** The bundle files of a directory (not the `<id>.authorization.json` files, not the subdirectories, not the symbolic links), or the one file given. A path that does not exist holds no receipts. */
13
+ export function receiptFiles(path) {
14
+ if (!existsSync(path))
15
+ return [];
16
+ if (!statSync(path).isDirectory())
17
+ return [path];
18
+ return readdirSync(path, { withFileTypes: true })
19
+ .filter((e) => e.isFile() && e.name.endsWith(".json") && !e.name.endsWith(AUTHORIZATION))
20
+ .map((e) => join(path, e.name))
21
+ .sort();
22
+ }
23
+ function rowOf(file, opts) {
24
+ const stem = basename(file).replace(/\.json$/, "");
25
+ const fail = (result) => ({ file, receiptId: stem, tool: "-", status: "-", result, ok: false });
26
+ let bundle;
27
+ try {
28
+ bundle = JSON.parse(readFileSync(file, "utf8"));
29
+ }
30
+ catch {
31
+ // the comment is public: a parser message can quote the first bytes of the file
32
+ return fail("not a JSON file");
33
+ }
34
+ let result;
35
+ try {
36
+ result = verifyBundle(bundle, opts);
37
+ }
38
+ catch {
39
+ return fail("not a receipt bundle");
40
+ }
41
+ const failed = result.checks.filter((c) => !c.ok).map((c) => c.name);
42
+ const p = result.statement?.predicate;
43
+ if (!p)
44
+ return fail(failed.length ? failed.join("; ") : "no receipt in the bundle");
45
+ // the gateway names each file by its receipt id, so a valid receipt under another name does not stand in for that one
46
+ if (basename(file) !== `${p.receiptId}.json`)
47
+ failed.push("file name matches receipt id");
48
+ return { file, receiptId: p.receiptId, tool: p.tool.name, status: p.execution.status, result: failed.length ? failed.join("; ") : "verified", ok: failed.length === 0 };
49
+ }
50
+ /** Verifies each file. Fails when a receipt does not verify, and when there is no receipt at all. */
51
+ export function summarizeReceipts(files, opts) {
52
+ if (files.length === 0)
53
+ return { ok: false, rows: [], problem: "No receipt bundles found." };
54
+ const rows = files.map((f) => rowOf(f, opts));
55
+ return { ok: rows.every((r) => r.ok), rows };
56
+ }
57
+ /** Receipt data is text from the agent. Remove what could break a table cell or inject Markdown or HTML. */
58
+ function code(text, max = 80) {
59
+ if (text === "-")
60
+ return text;
61
+ const clean = text.replace(/[^\x20-\x7e]|[|`<>\\]/g, "?");
62
+ return `\`${clean.length > max ? `${clean.slice(0, max - 3)}...` : clean}\``;
63
+ }
64
+ function resultCell(r) {
65
+ if (r.ok)
66
+ return "verified";
67
+ const names = r.result.split("; ");
68
+ const shown = names.slice(0, MAX_NAMES).map((n) => code(n)).join("; ");
69
+ return names.length > MAX_NAMES ? `${shown} (+${names.length - MAX_NAMES} more)` : shown;
70
+ }
71
+ /** The pull request comment and the job summary. It starts with the marker line. */
72
+ export function formatSummaryMarkdown(s) {
73
+ const lines = [SUMMARY_MARKER, "## agent-custody receipts", ""];
74
+ if (s.rows.length === 0) {
75
+ lines.push(`**Not verified.** ${s.problem ?? "No receipt bundles found."}`);
76
+ return lines.join("\n") + "\n";
77
+ }
78
+ const failed = s.rows.filter((r) => !r.ok).length;
79
+ lines.push(failed === 0 ? `**Verified.** All ${s.rows.length} receipts verify.` : `**Not verified.** ${failed} of ${s.rows.length} receipts do not verify.`, "");
80
+ lines.push("| Receipt | Tool | Status | Result |", "| --- | --- | --- | --- |");
81
+ const shown = [...s.rows.filter((r) => !r.ok), ...s.rows.filter((r) => r.ok)].slice(0, MAX_ROWS);
82
+ for (const r of shown)
83
+ lines.push(`| ${code(r.receiptId)} | ${code(r.tool)} | ${KNOWN_STATUS.has(r.status) ? r.status : code(r.status)} | ${resultCell(r)} |`);
84
+ if (s.rows.length > shown.length)
85
+ lines.push("", `${s.rows.length - shown.length} more receipts are not shown. Every receipt that does not verify is listed first.`);
86
+ return lines.join("\n") + "\n";
87
+ }
package/dist/receipt.d.ts CHANGED
@@ -21,8 +21,10 @@ export type Provenance = "attested" | "observed" | "claimed";
21
21
  * Who produced the receipt. This is the first thing a verifier should read.
22
22
  * - gateway: an out-of-process enforcement point; the agent could neither skip nor forge it
23
23
  * - sdk: an interceptor inside the agent's own process; self-reported, tamper-evident after issue but not before
24
+ * - door: an out-of-process enforcement point in front of a business's own HTTP surface; the arriving agent, caller,
25
+ * or browser could neither skip nor forge it, and has no grant unless it presented one
24
26
  */
25
- export type IssuerKind = "gateway" | "sdk";
27
+ export type IssuerKind = "gateway" | "sdk" | "door";
26
28
  export interface FactRecord {
27
29
  tool: string;
28
30
  args: Record<string, unknown>;
@@ -16,6 +16,6 @@ export interface PruneResult {
16
16
  /**
17
17
  * Prunes every leaf whose receipt timestamp is before the cutoff. Leaves already pruned, and leaves that are not
18
18
  * receipts, are left as they are. Rewrites the log file in place and deletes the pruned receipts' bundle files, and
19
- * the salts the issuer kept for them.
19
+ * the salts the issuer kept for them. It holds the log lock, so a receipt that a hook appends during the prune is not lost.
20
20
  */
21
21
  export declare function pruneLog(logFile: string, before: string, receiptsDir?: string): PruneResult;
package/dist/retention.js CHANGED
@@ -3,9 +3,9 @@
3
3
  // the Merkle tree, every root, and every inclusion and consistency proof for the remaining leaves are unchanged, while
4
4
  // the pruned receipt's content is gone from the log and its bundle file is removed. A verifier holding a pruned
5
5
  // receipt's bundle can still prove inclusion; nobody holding only the log can recover what the receipt said.
6
- import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
6
+ import { appendFileSync, existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
7
7
  import { join } from "node:path";
8
- import { leafHash } from "./log.js";
8
+ import { leafHash, logLocked } from "./log.js";
9
9
  /** where the issuer keeps the salts behind a receipt's commitments, under the receipts directory; private, pruned with the receipt */
10
10
  export const SALTS_DIR = "salts";
11
11
  /** a receipt id as the issuer mints it; anything else never becomes part of a path */
@@ -29,10 +29,20 @@ function receiptOf(leaf) {
29
29
  /**
30
30
  * Prunes every leaf whose receipt timestamp is before the cutoff. Leaves already pruned, and leaves that are not
31
31
  * receipts, are left as they are. Rewrites the log file in place and deletes the pruned receipts' bundle files, and
32
- * the salts the issuer kept for them.
32
+ * the salts the issuer kept for them. It holds the log lock, so a receipt that a hook appends during the prune is not lost.
33
33
  */
34
34
  export function pruneLog(logFile, before, receiptsDir) {
35
- const lines = readFileSync(logFile, "utf8").split("\n").filter((l) => l.trim());
35
+ return logLocked(logFile, () => pruneLocked(logFile, before, receiptsDir));
36
+ }
37
+ function pruneLocked(logFile, before, receiptsDir) {
38
+ let text = readFileSync(logFile, "utf8");
39
+ const whole = text.lastIndexOf("\n") + 1;
40
+ if (whole < text.length) {
41
+ // the remains of a writer that died in its write: kept apart, as an append keeps them
42
+ appendFileSync(`${logFile}.torn`, text.slice(whole), { mode: 0o600 });
43
+ text = text.slice(0, whole);
44
+ }
45
+ const lines = text.split("\n").filter((l) => l.trim());
36
46
  const out = [];
37
47
  const result = { pruned: [], kept: 0, bundlesRemoved: 0 };
38
48
  lines.forEach((line, i) => {