@agent-custody/receipts 0.13.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 (58) hide show
  1. package/README.md +46 -28
  2. package/dist/check.d.ts +10 -0
  3. package/dist/check.js +179 -3
  4. package/dist/claude-init.d.ts +46 -0
  5. package/dist/claude-init.js +208 -0
  6. package/dist/cli.js +126 -11
  7. package/dist/config.d.ts +128 -1
  8. package/dist/config.js +92 -3
  9. package/dist/console.js +16 -7
  10. package/dist/deny-report.d.ts +30 -0
  11. package/dist/deny-report.js +106 -0
  12. package/dist/door.d.ts +203 -0
  13. package/dist/door.js +712 -0
  14. package/dist/export.d.ts +39 -0
  15. package/dist/export.js +95 -0
  16. package/dist/gateway.js +53 -21
  17. package/dist/index.d.ts +8 -0
  18. package/dist/index.js +7 -0
  19. package/dist/issue.js +5 -65
  20. package/dist/lock.d.ts +12 -0
  21. package/dist/lock.js +124 -0
  22. package/dist/log-admin.js +3 -3
  23. package/dist/log.d.ts +20 -3
  24. package/dist/log.js +117 -24
  25. package/dist/opa-server.d.ts +34 -0
  26. package/dist/opa-server.js +93 -0
  27. package/dist/policy-rego.d.ts +30 -0
  28. package/dist/policy-rego.js +114 -0
  29. package/dist/policy.d.ts +6 -0
  30. package/dist/policy.js +17 -0
  31. package/dist/pr-summary.d.ts +25 -0
  32. package/dist/pr-summary.js +87 -0
  33. package/dist/receipt.d.ts +3 -1
  34. package/dist/retention.d.ts +1 -1
  35. package/dist/retention.js +14 -4
  36. package/dist/sdk/claude.js +18 -2
  37. package/dist/sdk/index.d.ts +2 -0
  38. package/dist/sdk/index.js +11 -2
  39. package/dist/simulate.d.ts +3 -1
  40. package/dist/simulate.js +15 -7
  41. package/dist/verify.js +6 -3
  42. package/dist/witness.js +3 -3
  43. package/docs/compliance.md +117 -7
  44. package/docs/configuration.md +3 -3
  45. package/docs/door-signals.md +66 -0
  46. package/docs/door.md +168 -0
  47. package/docs/github-action.md +164 -0
  48. package/docs/policies.md +124 -1
  49. package/docs/sdk.md +99 -1
  50. package/docs/tutorials.md +5 -0
  51. package/docs/usage.md +3 -3
  52. package/docs/verification.md +9 -2
  53. package/package.json +16 -14
  54. package/templates/claude-code.cedar +373 -0
  55. package/vectors/audit.json +27 -27
  56. package/vectors/canonical.json +5 -5
  57. package/vectors/merkle.json +123 -0
  58. 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, existsSync, mkdirSync, readFileSync } 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,27 +169,106 @@ export function verifyInclusion(leaf, proof, rootHex) {
153
169
  }
154
170
  return sn === 0 && r.toString("hex") === rootHex;
155
171
  }
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
+ }
156
178
  export class MerkleLog {
157
179
  hashes = [];
158
- tree;
180
+ tree = new SubtreeCache(this.hashes);
159
181
  file;
182
+ bytes = 0;
183
+ inode = -1;
160
184
  constructor(file) {
161
185
  this.file = file;
162
- this.tree = new SubtreeCache(this.hashes);
163
- if (existsSync(file)) {
164
- for (const line of readFileSync(file, "utf8").split("\n")) {
165
- if (!line.trim())
166
- continue;
167
- const parsed = JSON.parse(line);
168
- // A pruned leaf keeps only its hash, and a leaf appended by hash never had content here: the tree, its
169
- // roots, and every proof are the same either way.
170
- this.hashes.push(typeof parsed === "string" ? leafHash(parsed) : Buffer.from((parsed.pruned ?? parsed.hash), "hex"));
186
+ mkdirSync(dirname(file), { recursive: true });
187
+ this.catchUp();
188
+ }
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
+ */
194
+ catchUp() {
195
+ let st;
196
+ try {
197
+ st = statSync(this.file);
198
+ }
199
+ catch {
200
+ st = null;
201
+ }
202
+ if (!st || st.ino !== this.inode || st.size < this.bytes) {
203
+ this.hashes.length = 0;
204
+ this.tree = new SubtreeCache(this.hashes);
205
+ this.bytes = 0;
206
+ }
207
+ if (!st)
208
+ return;
209
+ this.inode = st.ino;
210
+ if (st.size === this.bytes)
211
+ return;
212
+ const buf = Buffer.alloc(st.size - this.bytes);
213
+ const fd = openSync(this.file, "r");
214
+ let got = 0;
215
+ try {
216
+ while (got < buf.length) {
217
+ const n = readSync(fd, buf, got, buf.length - got, this.bytes + got);
218
+ if (n === 0)
219
+ break;
220
+ got += n;
171
221
  }
172
222
  }
173
- else {
174
- mkdirSync(dirname(file), { recursive: true });
223
+ finally {
224
+ closeSync(fd);
225
+ }
226
+ got = buf.subarray(0, got).lastIndexOf(0x0a) + 1;
227
+ this.bytes += got;
228
+ for (const line of buf.subarray(0, got).toString("utf8").split("\n")) {
229
+ if (!line.trim())
230
+ continue;
231
+ const parsed = JSON.parse(line);
232
+ // A pruned leaf keeps only its hash, and a leaf appended by hash never had content here: the tree, its
233
+ // roots, and every proof are the same either way.
234
+ this.hashes.push(typeof parsed === "string" ? leafHash(parsed) : Buffer.from((parsed.pruned ?? parsed.hash), "hex"));
175
235
  }
176
236
  }
237
+ /**
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.
240
+ */
241
+ cutTornTail() {
242
+ let size;
243
+ try {
244
+ size = statSync(this.file).size;
245
+ }
246
+ catch {
247
+ return;
248
+ }
249
+ if (size <= this.bytes)
250
+ return;
251
+ const tail = Buffer.alloc(size - this.bytes);
252
+ const fd = openSync(this.file, "r");
253
+ try {
254
+ readSync(fd, tail, 0, tail.length, this.bytes);
255
+ }
256
+ finally {
257
+ closeSync(fd);
258
+ }
259
+ appendFileSync(`${this.file}.torn`, tail, { mode: 0o600 });
260
+ truncateSync(this.file, this.bytes);
261
+ }
262
+ /** Under the lock: reads what other writers appended, then writes this line, so each leaf gets the next index. */
263
+ appendLine(line, hash) {
264
+ return logLocked(this.file, () => {
265
+ this.catchUp();
266
+ this.cutTornTail();
267
+ appendFileSync(this.file, line);
268
+ this.bytes += Buffer.byteLength(line);
269
+ return this.pushHash(hash());
270
+ });
271
+ }
177
272
  get size() {
178
273
  return this.hashes.length;
179
274
  }
@@ -183,8 +278,7 @@ export class MerkleLog {
183
278
  }
184
279
  /** Appends a leaf (an opaque string, typically a canonical JSON envelope). Returns its proof against the new root. */
185
280
  append(leaf) {
186
- appendFileSync(this.file, JSON.stringify(leaf) + "\n");
187
- return this.pushHash(leafHash(leaf));
281
+ return this.appendLine(JSON.stringify(leaf) + "\n", () => leafHash(leaf));
188
282
  }
189
283
  /**
190
284
  * Appends a leaf by its RFC 6962 leaf hash, sha256(0x00 || leaf), as hex. The log commits to the leaf without ever
@@ -193,8 +287,7 @@ export class MerkleLog {
193
287
  appendHash(leafHashHex) {
194
288
  if (!/^[0-9a-f]{64}$/.test(leafHashHex))
195
289
  throw new Error("leafHash must be 64 lowercase hex characters");
196
- appendFileSync(this.file, JSON.stringify({ hash: leafHashHex }) + "\n");
197
- return this.pushHash(Buffer.from(leafHashHex, "hex"));
290
+ return this.appendLine(JSON.stringify({ hash: leafHashHex }) + "\n", () => Buffer.from(leafHashHex, "hex"));
198
291
  }
199
292
  pushHash(hash) {
200
293
  this.hashes.push(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
+ }
package/dist/policy.d.ts CHANGED
@@ -18,6 +18,12 @@ export interface PolicyRequest {
18
18
  export declare function hasPermitRule(policyText: string): boolean;
19
19
  /** Why Cedar cannot parse the policy set, or an empty list when it can. */
20
20
  export declare function policyParseErrors(policyText: string): string[];
21
+ /** The text of each static policy, in file order. Cedar names them `policy0`, `policy1`, and so on in this order. */
22
+ export declare function policyRules(policyText: string): string[];
23
+ /** The `@reason("...")` annotation of each static policy, in file order, or null for a policy without one. */
24
+ export declare function policyReasons(policyText: string): (string | null)[];
25
+ /** The reason of the policy that a Cedar id such as `policy3` names: its `@reason` text, or the id when it has none. */
26
+ export declare function reasonOfRule(id: string, reasons: readonly (string | null)[]): string;
21
27
  export declare function policyDigest(policyText: string): string;
22
28
  /**
23
29
  * Cedar's JSON context reads `{ "__entity": … }` and `{ "__extn": … }` as typed values. Arguments come from the agent,
package/dist/policy.js CHANGED
@@ -16,6 +16,23 @@ export function policyParseErrors(policyText) {
16
16
  const parsed = cedar.checkParsePolicySet({ staticPolicies: policyText });
17
17
  return parsed.type === "success" ? [] : parsed.errors.map((e) => e.message);
18
18
  }
19
+ /** The text of each static policy, in file order. Cedar names them `policy0`, `policy1`, and so on in this order. */
20
+ export function policyRules(policyText) {
21
+ const parts = cedar.policySetTextToParts(policyText);
22
+ return parts.type === "success" ? parts.policies : [];
23
+ }
24
+ /** The `@reason("...")` annotation of each static policy, in file order, or null for a policy without one. */
25
+ export function policyReasons(policyText) {
26
+ return policyRules(policyText).map((rule) => {
27
+ const j = cedar.policyToJson(rule);
28
+ const reason = j.type === "success" ? j.json.annotations?.reason : undefined;
29
+ return typeof reason === "string" && reason.trim() ? reason.trim() : null;
30
+ });
31
+ }
32
+ /** The reason of the policy that a Cedar id such as `policy3` names: its `@reason` text, or the id when it has none. */
33
+ export function reasonOfRule(id, reasons) {
34
+ return reasons[Number(id.replace(/^policy/, ""))] ?? id;
35
+ }
19
36
  export function policyDigest(policyText) {
20
37
  return sha256Hex(policyText);
21
38
  }
@@ -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>;