@agent-custody/receipts 0.14.0 → 0.16.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 (60) hide show
  1. package/README.md +48 -21
  2. package/dist/acs.d.ts +47 -0
  3. package/dist/acs.js +235 -0
  4. package/dist/addresses.d.ts +6 -0
  5. package/dist/addresses.js +90 -0
  6. package/dist/check.d.ts +10 -0
  7. package/dist/check.js +179 -3
  8. package/dist/cli.js +147 -12
  9. package/dist/config.d.ts +198 -1
  10. package/dist/config.js +154 -3
  11. package/dist/console.js +16 -7
  12. package/dist/deny-report.js +1 -1
  13. package/dist/door.d.ts +203 -0
  14. package/dist/door.js +712 -0
  15. package/dist/egress-draft.d.ts +43 -0
  16. package/dist/egress-draft.js +153 -0
  17. package/dist/egress.d.ts +116 -0
  18. package/dist/egress.js +585 -0
  19. package/dist/export.d.ts +39 -0
  20. package/dist/export.js +95 -0
  21. package/dist/gateway.js +53 -21
  22. package/dist/index.d.ts +15 -0
  23. package/dist/index.js +10 -0
  24. package/dist/issue.js +5 -65
  25. package/dist/lock.d.ts +12 -0
  26. package/dist/lock.js +124 -0
  27. package/dist/log.d.ts +11 -5
  28. package/dist/log.js +63 -43
  29. package/dist/opa-server.d.ts +34 -0
  30. package/dist/opa-server.js +93 -0
  31. package/dist/policy-rego.d.ts +30 -0
  32. package/dist/policy-rego.js +116 -0
  33. package/dist/portal.js +147 -41
  34. package/dist/pr-summary.d.ts +25 -0
  35. package/dist/pr-summary.js +87 -0
  36. package/dist/receipt.d.ts +8 -2
  37. package/dist/retention.d.ts +1 -1
  38. package/dist/retention.js +14 -4
  39. package/dist/sdk/index.js +10 -3
  40. package/dist/simulate.d.ts +3 -1
  41. package/dist/simulate.js +15 -7
  42. package/dist/verify.js +35 -4
  43. package/docs/acs.md +107 -0
  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/egress.md +177 -0
  48. package/docs/github-action.md +164 -0
  49. package/docs/policies.md +112 -1
  50. package/docs/sdk.md +25 -9
  51. package/docs/threat-model.md +1 -1
  52. package/docs/tutorials.md +7 -0
  53. package/docs/usage.md +2 -2
  54. package/docs/verification.md +16 -2
  55. package/package.json +14 -13
  56. package/templates/claude-code.cedar +287 -10
  57. package/vectors/audit.json +27 -27
  58. package/vectors/canonical.json +5 -5
  59. package/vectors/merkle.json +123 -0
  60. package/vectors/receipts.json +1951 -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,21 @@ 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;
25
+ /** n is a power of two. Exact for every safe integer: `(n & (n - 1)) === 0` reads only the low 32 bits of n. */
26
+ function isPowerOfTwo(n) {
27
+ let k = 1;
28
+ while (k < n)
29
+ k *= 2;
30
+ return k === n;
31
+ }
16
32
  /** largest power of two strictly less than n (n >= 2) */
17
33
  function split(n) {
18
34
  let k = 1;
@@ -78,18 +94,21 @@ export function consistencyProof(leafHashes, oldSize, newSize = leafHashes.lengt
78
94
  return subproof(oldSize, leafHashes, 0, newSize, true).map((b) => b.toString("hex"));
79
95
  }
80
96
  /** 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)
97
+ export function verifyConsistency(oldSize, oldRoot, newSize, newRoot, proofHex) {
98
+ if (!isSize(oldSize) || !isSize(newSize) || oldSize > newSize)
83
99
  return false;
84
- if (oldSize === newSize)
85
- return proofHex.length === 0 && oldRootHex === newRootHex;
100
+ if (!isHash(oldRoot) || !isHash(newRoot) || !Array.isArray(proofHex) || !proofHex.every(isHash))
101
+ return false;
102
+ // 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
103
  if (oldSize === 0)
87
- return proofHex.length === 0;
104
+ return proofHex.length === 0 && oldRoot === EMPTY_ROOT && (newSize > 0 || newRoot === EMPTY_ROOT);
105
+ if (oldSize === newSize)
106
+ return proofHex.length === 0 && oldRoot === newRoot;
88
107
  if (proofHex.length === 0)
89
108
  return false;
90
109
  const proof = proofHex.map((x) => Buffer.from(x, "hex"));
91
- if ((oldSize & (oldSize - 1)) === 0)
92
- proof.unshift(Buffer.from(oldRootHex, "hex"));
110
+ if (isPowerOfTwo(oldSize))
111
+ proof.unshift(Buffer.from(oldRoot, "hex"));
93
112
  let fn = oldSize - 1;
94
113
  let sn = newSize - 1;
95
114
  while (fn % 2 === 1) {
@@ -115,7 +134,7 @@ export function verifyConsistency(oldSize, oldRootHex, newSize, newRootHex, proo
115
134
  fn = Math.floor(fn / 2);
116
135
  sn = Math.floor(sn / 2);
117
136
  }
118
- return sn === 0 && fr.toString("hex") === oldRootHex && sr.toString("hex") === newRootHex;
137
+ return sn === 0 && fr.toString("hex") === oldRoot && sr.toString("hex") === newRoot;
119
138
  }
120
139
  export function rootOf(leafHashes, size = leafHashes.length) {
121
140
  return mth(leafHashes, 0, size).toString("hex");
@@ -127,10 +146,14 @@ export function inclusionProof(leafHashes, leafIndex, treeSize = leafHashes.leng
127
146
  }
128
147
  /** RFC 9162 section 2.1.3.2 verification. Pure function: needs only the leaf hash, proof and claimed root. */
129
148
  export function verifyInclusion(leaf, proof, rootHex) {
149
+ if (!isSize(proof.leafIndex) || !isSize(proof.treeSize))
150
+ return false;
130
151
  let fn = proof.leafIndex;
131
152
  let sn = proof.treeSize - 1;
132
153
  if (fn < 0 || sn < 0 || fn > sn)
133
154
  return false;
155
+ if (leaf.length !== 32 || !isHash(rootHex) || !Array.isArray(proof.hashes) || !proof.hashes.every(isHash))
156
+ return false;
134
157
  let r = leaf;
135
158
  for (const hex of proof.hashes) {
136
159
  if (sn === 0)
@@ -153,9 +176,12 @@ export function verifyInclusion(leaf, proof, rootHex) {
153
176
  }
154
177
  return sn === 0 && r.toString("hex") === rootHex;
155
178
  }
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);
179
+ const LOCK_STALE_MS = 60_000;
180
+ const LOG_LOCK_WAIT_MS = 20_000;
181
+ /** Each hook of a coding agent is its own process, so appends overlap: one writer at a time holds `<file>.lock`. */
182
+ export function logLocked(file, fn) {
183
+ return withLock(`${file}.lock`, { staleMs: LOCK_STALE_MS, waitMs: LOG_LOCK_WAIT_MS }, fn);
184
+ }
159
185
  export class MerkleLog {
160
186
  hashes = [];
161
187
  tree = new SubtreeCache(this.hashes);
@@ -167,7 +193,11 @@ export class MerkleLog {
167
193
  mkdirSync(dirname(file), { recursive: true });
168
194
  this.catchUp();
169
195
  }
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. */
196
+ /**
197
+ * Reads the leaves that another handle or process appended since the last read. A file that was replaced or cut
198
+ * short is read again from the start. Bytes after the last newline are not read: a writer may be in the middle of its
199
+ * write, or may have died in it.
200
+ */
171
201
  catchUp() {
172
202
  let st;
173
203
  try {
@@ -200,6 +230,7 @@ export class MerkleLog {
200
230
  finally {
201
231
  closeSync(fd);
202
232
  }
233
+ got = buf.subarray(0, got).lastIndexOf(0x0a) + 1;
203
234
  this.bytes += got;
204
235
  for (const line of buf.subarray(0, got).toString("utf8").split("\n")) {
205
236
  if (!line.trim())
@@ -211,46 +242,35 @@ export class MerkleLog {
211
242
  }
212
243
  }
213
244
  /**
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.
245
+ * Under the lock: a last line with no newline is the remains of a writer that died in the middle of its write. No
246
+ * 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
247
  */
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);
248
+ cutTornTail() {
249
+ let size;
250
+ try {
251
+ size = statSync(this.file).size;
239
252
  }
253
+ catch {
254
+ return;
255
+ }
256
+ if (size <= this.bytes)
257
+ return;
258
+ const tail = Buffer.alloc(size - this.bytes);
259
+ const fd = openSync(this.file, "r");
240
260
  try {
241
- return fn();
261
+ readSync(fd, tail, 0, tail.length, this.bytes);
242
262
  }
243
263
  finally {
244
- try {
245
- unlinkSync(lock);
246
- }
247
- catch { /* a writer removed it as stale */ }
264
+ closeSync(fd);
248
265
  }
266
+ appendFileSync(`${this.file}.torn`, tail, { mode: 0o600 });
267
+ truncateSync(this.file, this.bytes);
249
268
  }
250
269
  /** Under the lock: reads what other writers appended, then writes this line, so each leaf gets the next index. */
251
270
  appendLine(line, hash) {
252
- return this.locked(() => {
271
+ return logLocked(this.file, () => {
253
272
  this.catchUp();
273
+ this.cutTornTail();
254
274
  appendFileSync(this.file, line);
255
275
  this.bytes += Buffer.byteLength(line);
256
276
  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,116 @@
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 or changes, not to evaluate a
3
+ // call. A gateway or witness reloads on the first call after a change, and the compile is synchronous with no timeout,
4
+ // so the whole process waits for it (and an opa that hangs stalls it). An OPA
5
+ // server the operator runs answers the same contract over HTTP (opa-server.ts). Either way, fails closed.
6
+ import { execFileSync } from "node:child_process";
7
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8
+ import { createRequire } from "node:module";
9
+ import { tmpdir } from "node:os";
10
+ import { dirname, join } from "node:path";
11
+ import { gunzipSync } from "node:zlib";
12
+ // The SDK's ES module entry exports only the async loader; its CommonJS entry has loadPolicySync, which lets a policy
13
+ // load inside the gateway's synchronous reload, like a Cedar file.
14
+ const require = createRequire(import.meta.url);
15
+ const opa = require("@open-policy-agent/opa-wasm");
16
+ /** The package a Rego policy file declares. Its `allow` and `deny` rules are the decision. */
17
+ export const REGO_PACKAGE = "agentcustody";
18
+ export function isRegoFile(path) {
19
+ return path.toLowerCase().endsWith(".rego");
20
+ }
21
+ /**
22
+ * The input a Rego policy reads: the Cedar request with plain strings for the three identifiers. `context` holds `args`
23
+ * (claimed), `facts` (observed), and `grant` (attested), exactly as Cedar sees them.
24
+ */
25
+ export function regoInput(req) {
26
+ return { principal: req.agentId, action: req.tool, resource: req.tool, context: req.context };
27
+ }
28
+ /**
29
+ * The decision from the document the policy package evaluates to. Default deny: `allow` must be exactly `true`. Any
30
+ * entry in `deny` wins over `allow`, as a Cedar `forbid` wins over a `permit`, and its strings are the reasons. A
31
+ * document of the wrong shape is an error, and an error is a deny.
32
+ */
33
+ export function regoDecision(doc, policyDigest, rule = `data.${REGO_PACKAGE}`, where = rule) {
34
+ const deny = (errors, reasons = []) => ({ decision: "deny", reasons, errors, policyDigest });
35
+ if (doc === undefined)
36
+ return deny([`${where} is undefined`]);
37
+ if (!doc || typeof doc !== "object" || Array.isArray(doc))
38
+ return deny([`${where} is not an object with allow and deny rules`]);
39
+ const { allow, deny: denied } = doc;
40
+ if (allow !== undefined && typeof allow !== "boolean")
41
+ return deny([`${where}.allow is not a boolean`]);
42
+ if (denied !== undefined && (!Array.isArray(denied) || !denied.every((d) => typeof d === "string")))
43
+ return deny([`${where}.deny is not a set of strings`]);
44
+ if (denied && denied.length > 0)
45
+ return deny([], denied);
46
+ return allow === true ? { decision: "allow", reasons: [`${rule}.allow`], errors: [], policyDigest } : deny([]);
47
+ }
48
+ export function evaluateRego(policy, policyDigest, req) {
49
+ let result;
50
+ try {
51
+ result = policy.evaluate(regoInput(req), REGO_PACKAGE);
52
+ }
53
+ catch (e) {
54
+ return { decision: "deny", reasons: [], errors: [e instanceof Error ? e.message : String(e)], policyDigest };
55
+ }
56
+ const set = Array.isArray(result) ? result : [];
57
+ return regoDecision(set[0]?.result, policyDigest);
58
+ }
59
+ /** One file out of a gzipped tar, as `opa build` writes its bundle. */
60
+ function fromTarGz(gz, name) {
61
+ const tar = gunzipSync(gz);
62
+ for (let at = 0; at + 512 <= tar.length;) {
63
+ const header = tar.subarray(at, at + 512);
64
+ if (header.every((b) => b === 0))
65
+ return undefined;
66
+ const field = (from, to) => header.subarray(from, to).toString("utf8").replace(/\0.*$/s, "");
67
+ const path = [field(345, 500), field(0, 100)].filter(Boolean).join("/").replace(/^\/+/, "");
68
+ const size = parseInt(field(124, 136).trim() || "0", 8);
69
+ if (path === name && (field(156, 157) === "0" || field(156, 157) === ""))
70
+ return Buffer.from(tar.subarray(at + 512, at + 512 + size));
71
+ at += 512 + Math.ceil(size / 512) * 512;
72
+ }
73
+ return undefined;
74
+ }
75
+ let capabilities;
76
+ /**
77
+ * The builtins `opa build` may compile in: the current opa's capabilities, cut down to the builtins the WebAssembly
78
+ * SDK can run. A policy calling another one, such as `http.send` or `time.now_ns`, is refused when it loads, instead of
79
+ * failing on each call.
80
+ */
81
+ function sdkCapabilities(opaBin) {
82
+ if (capabilities)
83
+ return capabilities;
84
+ const sdkFile = join(dirname(require.resolve("@open-policy-agent/opa-wasm")), "..", "capabilities.json");
85
+ const supported = new Set(JSON.parse(readFileSync(sdkFile, "utf8")).builtins.map((b) => b.name));
86
+ const current = JSON.parse(execFileSync(opaBin, ["capabilities", "--current"], { encoding: "utf8" }));
87
+ capabilities = JSON.stringify({ ...current, builtins: current.builtins.filter((b) => supported.has(b.name)) });
88
+ return capabilities;
89
+ }
90
+ /**
91
+ * Compiles Rego text with the opa binary on PATH. Answers the loaded policy, or why it cannot be used: a syntax or type
92
+ * error, a builtin the SDK cannot run, no `package agentcustody`, or no opa binary.
93
+ */
94
+ export function compileRego(text, opaBin = "opa") {
95
+ const dir = mkdtempSync(join(tmpdir(), "agent-custody-rego-"));
96
+ try {
97
+ writeFileSync(join(dir, "policy.rego"), text);
98
+ writeFileSync(join(dir, "capabilities.json"), sdkCapabilities(opaBin));
99
+ execFileSync(opaBin, ["build", "-t", "wasm", "-e", REGO_PACKAGE, "--capabilities", "capabilities.json", "-o", "bundle.tar.gz", "policy.rego"], { cwd: dir, stdio: ["ignore", "pipe", "pipe"] });
100
+ const wasm = fromTarGz(readFileSync(join(dir, "bundle.tar.gz")), "policy.wasm");
101
+ if (!wasm)
102
+ return { errors: ["opa build wrote no policy.wasm"] };
103
+ return { policy: opa.loadPolicySync(wasm), errors: [] };
104
+ }
105
+ catch (e) {
106
+ const err = e;
107
+ if (err.code === "ENOENT")
108
+ return { errors: [`compiling a Rego policy needs the opa binary on PATH (${opaBin} was not found)`] };
109
+ const said = [err.stderr, err.stdout].map((b) => b?.toString("utf8").trim() ?? "").filter(Boolean).join("\n");
110
+ const message = said ? said.replace(/^error: /, "") : err.message;
111
+ return { errors: [/entrypoint "[^"]*" does not refer to a rule/.test(message) ? `${message}: the policy must declare package ${REGO_PACKAGE}` : message] };
112
+ }
113
+ finally {
114
+ rmSync(dir, { recursive: true, force: true });
115
+ }
116
+ }