@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
@@ -0,0 +1,39 @@
1
+ import type { ReceiptPredicate } from "./receipt.ts";
2
+ import { type VerifyOptions } from "./verify.ts";
3
+ export interface ReceiptExportOptions {
4
+ receiptsDir: string;
5
+ outDir: string;
6
+ verify: VerifyOptions;
7
+ /** keep the receipts issued at or after this time (ms since the epoch) */
8
+ since?: number;
9
+ /** copy a receipt that holds plain values */
10
+ allowClear?: boolean;
11
+ }
12
+ export interface ReceiptExportLine {
13
+ file: string;
14
+ outcome: "copied" | "refused" | "skipped";
15
+ /** the reason for a refusal or a skip */
16
+ reason?: string;
17
+ /** the sides of a copied receipt that carry plain values (only with allowClear) */
18
+ clear: string[];
19
+ }
20
+ export interface ReceiptExportResult {
21
+ lines: ReceiptExportLine[];
22
+ copied: number;
23
+ refused: number;
24
+ skipped: number;
25
+ /** set when no receipt was copied */
26
+ problem?: string;
27
+ }
28
+ /**
29
+ * The sides of a call that the signed receipt carries in plain values: "args", "result", or "facts". The signed capture
30
+ * note decides: a side that holds data and has no withheld path under it is in clear. A field that a rule lists in
31
+ * `clear` leaves a commitment for the other fields beside it, so it does not count. A side with only fields in its
32
+ * `clear` list has no commitment, and the check cannot tell it from a side in mode `clear`.
33
+ */
34
+ export declare function clearSides(p: ReceiptPredicate): string[];
35
+ /** Verifies each bundle, checks that it keeps its values private, and copies the bytes of those that pass. */
36
+ export declare function exportReceipts(opts: ReceiptExportOptions): ReceiptExportResult;
37
+ /** One line for each receipt, then the count. */
38
+ export declare function formatReceiptExport(r: ReceiptExportResult): string[];
39
+ export declare const CLEAR_WARNING = "warning: --allow-clear is on. Each receipt marked with plain values publishes its arguments or its result to everyone who can read the output directory.";
package/dist/export.js ADDED
@@ -0,0 +1,95 @@
1
+ // `agent-custody export`: copies receipt bundles from the receipts directory of a machine into a directory that goes into a pull request.
2
+ // The module reads files and calls the verifier. It never rewrites a receipt, because the signature covers it, and it never uses the network.
3
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
4
+ import { join, resolve } from "node:path";
5
+ import { under } from "./capture.js";
6
+ import { verifyBundle } from "./verify.js";
7
+ const AUTHORIZATION = ".authorization.json";
8
+ /** The bundle files at the top level of a directory. Subdirectories, symbolic links, `<id>.authorization.json` files, and other files are not read. */
9
+ function bundleFiles(dir) {
10
+ if (!existsSync(dir) || !statSync(dir).isDirectory())
11
+ throw new Error(`${dir} is not a directory`);
12
+ return readdirSync(dir, { withFileTypes: true })
13
+ .filter((e) => e.isFile() && e.name.endsWith(".json") && !e.name.endsWith(AUTHORIZATION))
14
+ .map((e) => e.name)
15
+ .sort();
16
+ }
17
+ /** True when a value carries something to read. An empty object, an empty list, and null do not. */
18
+ function hasData(v) {
19
+ if (v === undefined || v === null)
20
+ return false;
21
+ if (Array.isArray(v))
22
+ return v.some(hasData);
23
+ if (typeof v === "object")
24
+ return Object.values(v).some(hasData);
25
+ return true;
26
+ }
27
+ /**
28
+ * The sides of a call that the signed receipt carries in plain values: "args", "result", or "facts". The signed capture
29
+ * note decides: a side that holds data and has no withheld path under it is in clear. A field that a rule lists in
30
+ * `clear` leaves a commitment for the other fields beside it, so it does not count. A side with only fields in its
31
+ * `clear` list has no commitment, and the check cannot tell it from a side in mode `clear`.
32
+ */
33
+ export function clearSides(p) {
34
+ const withheld = p.capture?.withheld ?? [];
35
+ const open = (path, value) => hasData(value) && !withheld.some((w) => under(w, path));
36
+ const sides = [];
37
+ if (open(["request", "args"], p.request?.args))
38
+ sides.push("args");
39
+ const exec = p.execution;
40
+ // the error message and the denial reason follow the result: a private rule withholds them, a clear rule does not
41
+ if (["result", "error", "reason"].some((f) => open(["execution", f], exec[f])))
42
+ sides.push("result");
43
+ if (Object.entries(p.facts ?? {}).some(([name, fact]) => open(["facts", name, "value"], fact?.value)))
44
+ sides.push("facts");
45
+ return sides;
46
+ }
47
+ /** Verifies each bundle, checks that it keeps its values private, and copies the bytes of those that pass. */
48
+ export function exportReceipts(opts) {
49
+ if (resolve(opts.receiptsDir) === resolve(opts.outDir))
50
+ throw new Error("--out must not be the receipts directory");
51
+ const lines = [];
52
+ for (const name of bundleFiles(opts.receiptsDir)) {
53
+ const refuse = (reason) => void lines.push({ file: name, outcome: "refused", reason, clear: [] });
54
+ // the bytes that were verified are the bytes that are written
55
+ const bytes = readFileSync(join(opts.receiptsDir, name));
56
+ let result;
57
+ try {
58
+ result = verifyBundle(JSON.parse(bytes.toString("utf8")), opts.verify);
59
+ }
60
+ catch (e) {
61
+ refuse(`not a receipt bundle: ${e instanceof Error ? e.message : String(e)}`);
62
+ continue;
63
+ }
64
+ const p = result.statement?.predicate;
65
+ const failed = result.checks.filter((c) => !c.ok).map((c) => c.name);
66
+ if (p && name !== `${p.receiptId}.json`)
67
+ failed.push("file name matches receipt id");
68
+ if (!p || failed.length) {
69
+ refuse(failed.length ? failed.join("; ") : "no receipt in the bundle");
70
+ continue;
71
+ }
72
+ if (opts.since !== undefined && !(Date.parse(p.timestamp) >= opts.since)) {
73
+ lines.push({ file: name, outcome: "skipped", reason: `issued ${p.timestamp}, before --since`, clear: [] });
74
+ continue;
75
+ }
76
+ const clear = clearSides(p);
77
+ if (clear.length && !opts.allowClear) {
78
+ refuse(`${clear.join(" and ")} in clear: a capture rule must withhold it (or give --allow-clear)`);
79
+ continue;
80
+ }
81
+ mkdirSync(opts.outDir, { recursive: true });
82
+ writeFileSync(join(opts.outDir, name), bytes);
83
+ lines.push({ file: name, outcome: "copied", clear });
84
+ }
85
+ const count = (o) => lines.filter((l) => l.outcome === o).length;
86
+ const copied = count("copied");
87
+ return { lines, copied, refused: count("refused"), skipped: count("skipped"), ...(copied === 0 ? { problem: lines.length === 0 ? "The receipts directory holds no receipt bundle." : "No receipt was copied." } : {}) };
88
+ }
89
+ /** One line for each receipt, then the count. */
90
+ export function formatReceiptExport(r) {
91
+ const out = r.lines.map((l) => (l.outcome === "copied" ? `copied ${l.file}${l.clear.length ? ` (plain values: ${l.clear.join(", ")})` : ""}` : `${l.outcome.padEnd(7)} ${l.file}: ${l.reason}`));
92
+ out.push(`${r.copied} copied, ${r.refused} refused, ${r.skipped} skipped`);
93
+ return out;
94
+ }
95
+ export const CLEAR_WARNING = "warning: --allow-clear is on. Each receipt marked with plain values publishes its arguments or its result to everyone who can read the output directory.";
package/dist/gateway.js CHANGED
@@ -21,6 +21,8 @@ import { restUpstream } from "./rest.js";
21
21
  import { a2aUpstream } from "./a2a.js";
22
22
  import { captureKeyFrom, effectiveRule } from "./capture.js";
23
23
  import { evaluate, hasPermitRule, policyDigest, policyParseErrors } from "./policy.js";
24
+ import { compileRego, evaluateRego, isRegoFile } from "./policy-rego.js";
25
+ import { createOpaServerPolicy } from "./opa-server.js";
24
26
  import { OPERATION_META_KEY, OperationStore, ownerAlive } from "./operations.js";
25
27
  export const GATEWAY_VERSION = "0.1.0";
26
28
  export const RECEIPT_META_KEY = "agent-custody/receipt";
@@ -96,18 +98,31 @@ export async function createGatewayHost(cfg, options = {}) {
96
98
  const trusted = cfg.trustedPrincipalKeys.map(loadPublicKey);
97
99
  const approvalKeys = cfg.approvals?.trustedKeys.map(loadPublicKey) ?? [];
98
100
  const approvalRule = (tool) => cfg.approvals?.tools.find((rule) => rule.tool === tool) ?? cfg.approvals?.tools.find((rule) => rule.tool === "*");
99
- // The Cedar policy, re-read whenever the file changes, like the revocation list. A call is evaluated under the policy
100
- // in force when it starts, and its receipt names that policy's digest. A changed file that cannot be read or does not
101
- // parse is refused and the policy in force stays: never an allow, and never a fall back to no policy. Every change
102
- // and every refusal is printed and appended to receiptsDir/policy-reloads.jsonl with both digests and the time.
101
+ // The policy file, Cedar or Rego, re-read whenever the file changes, like the revocation list. A Rego file is compiled
102
+ // with the opa binary each time it changes, and a compile failure is refused like a Cedar file that does not parse.
103
+ // A call is evaluated under the policy in force when it starts, and its receipt names that policy's digest. A changed
104
+ // file that cannot be read or does not parse is refused and the policy in force stays: never an allow, and never a
105
+ // fall back to no policy. Every change and every refusal is printed and appended to receiptsDir/policy-reloads.jsonl
106
+ // with both digests and the time.
103
107
  // The bytes and the metadata come from one open file, so a rename between reading and stat'ing cannot pair them wrongly.
104
108
  // ctime is in the key because a program can set mtime back but not ctime, and every write moves it. A file written in
105
109
  // the last two seconds may still be being written within one timestamp tick, so its key is not kept: it is re-read on
106
110
  // each call until it settles, and a half-written file read meanwhile is replaced by the finished one.
107
111
  const keyOf = (st) => `${st.dev}:${st.ino}:${st.mtimeMs}:${st.ctimeMs}:${st.size}`;
108
112
  const settled = (st) => Date.now() - Math.max(st.mtimeMs, st.ctimeMs) >= 2000;
113
+ const policyFile = cfg.policyFile ?? "";
114
+ const rego = isRegoFile(policyFile);
115
+ const loadPolicy = (text) => {
116
+ const digest = policyDigest(text);
117
+ if (!rego) {
118
+ const errors = policyParseErrors(text);
119
+ return errors.length ? { errors } : { policy: { text, digest }, errors: [] };
120
+ }
121
+ const compiled = compileRego(text);
122
+ return compiled.policy ? { policy: { text, digest, rego: compiled.policy }, errors: [] } : { errors: compiled.errors };
123
+ };
109
124
  const readPolicy = () => {
110
- const fd = openSync(cfg.policyFile, "r");
125
+ const fd = openSync(policyFile, "r");
111
126
  try {
112
127
  const st = fstatSync(fd);
113
128
  const text = readFileSync(fd, "utf8");
@@ -117,9 +132,17 @@ export async function createGatewayHost(cfg, options = {}) {
117
132
  closeSync(fd);
118
133
  }
119
134
  };
120
- const policyStat = () => keyOf(statSync(cfg.policyFile));
121
- const initialPolicy = readPolicy();
135
+ const policyStat = () => keyOf(statSync(policyFile));
136
+ const initialPolicy = cfg.policyFile ? readPolicy() : { text: "", seen: "" };
122
137
  let policyNow = { text: initialPolicy.text, digest: policyDigest(initialPolicy.text) };
138
+ // A Cedar file that does not parse at start denies every call with the parse errors. A Rego file must compile: with
139
+ // no wasm module there is nothing to evaluate, so the gateway does not start.
140
+ if (rego) {
141
+ const loaded = loadPolicy(initialPolicy.text);
142
+ if (!loaded.policy)
143
+ throw new Error(`agent-custody gateway: ${policyFile} does not compile: ${loaded.errors.join("; ")}`);
144
+ policyNow = loaded.policy;
145
+ }
123
146
  let policySeen = initialPolicy.seen;
124
147
  // A file that cannot be read is retried on every call, since restoring access changes none of its metadata; this
125
148
  // keeps the refusal from being printed and recorded on each of those calls.
@@ -130,17 +153,29 @@ export async function createGatewayHost(cfg, options = {}) {
130
153
  const recordReload = (entry) => {
131
154
  try {
132
155
  mkdirSync(cfg.receiptsDir, { recursive: true });
133
- appendFileSync(policyReloads, JSON.stringify({ at: new Date().toISOString(), file: cfg.policyFile, ...entry }) + "\n");
156
+ appendFileSync(policyReloads, JSON.stringify({ at: new Date().toISOString(), ...(cfg.opa ? { opa: cfg.opa.url } : { file: policyFile }), ...entry }) + "\n");
134
157
  }
135
158
  catch (e) {
136
159
  console.error(`agent-custody gateway: cannot record the policy change in ${policyReloads}: ${e instanceof Error ? e.message : String(e)}`);
137
160
  }
138
161
  };
139
162
  const refuseReload = (to, errors) => {
140
- console.error(`agent-custody gateway: POLICY NOT RELOADED: ${cfg.policyFile} ${errors.join("; ")}; policy ${policyNow.digest} stays in force`);
163
+ console.error(`agent-custody gateway: POLICY NOT RELOADED: ${policyFile} ${errors.join("; ")}; policy ${policyNow.digest} stays in force`);
141
164
  recordReload({ event: "refused", from: policyNow.digest, to, errors });
142
165
  };
166
+ // An OPA server holds the policy itself. Every new provenance it reports is printed and recorded beside file reloads,
167
+ // so each digest a receipt carries maps to the bundle revisions that decided it.
168
+ const opaServer = cfg.opa ? createOpaServerPolicy(cfg.opa, (p) => {
169
+ const warnings = p.bundles === null ? ["the OPA server did not answer: the calls it left undecided are denied under this digest"]
170
+ : Object.keys(p.bundles).length ? [] : ["the OPA server reports no bundle revision, so receipts cannot name the policy that decided"];
171
+ console.error(`agent-custody gateway: OPA policy ${p.digest} at ${p.decision}: ${JSON.stringify(p.bundles)}${warnings.length ? `; WARNING: ${warnings.join("; ")}` : ""}`);
172
+ recordReload({ event: "opa-provenance", to: p.digest, decision: p.decision, bundles: p.bundles, ...(warnings.length ? { warnings } : {}) });
173
+ }) : undefined;
174
+ if (opaServer)
175
+ await opaServer.probe();
143
176
  const currentPolicy = () => {
177
+ if (opaServer)
178
+ return { text: "", digest: opaServer.digest() };
144
179
  const unreadable = (seen, e) => {
145
180
  if (unreadableSeen !== seen)
146
181
  refuseReload(null, [`cannot be read (${e instanceof Error ? e.message : String(e)})`]);
@@ -171,18 +206,18 @@ export async function createGatewayHost(cfg, options = {}) {
171
206
  return policyNow;
172
207
  if (digest === refusedDigest)
173
208
  return policyNow;
174
- const errors = policyParseErrors(text);
175
- if (errors.length > 0) {
209
+ const loaded = loadPolicy(text);
210
+ if (!loaded.policy) {
176
211
  refusedDigest = digest;
177
- refuseReload(digest, [`does not parse: ${errors.join("; ")}`]);
212
+ refuseReload(digest, [`does not ${rego ? "compile" : "parse"}: ${loaded.errors.join("; ")}`]);
178
213
  return policyNow;
179
214
  }
180
215
  refusedDigest = "";
181
216
  // a policy with no permit rule parses and denies every call: fail-closed, but never a reload to pass over quietly
182
- const warnings = hasPermitRule(text) ? [] : ["no permit rule: every call is denied"];
183
- console.error(`agent-custody gateway: policy reloaded from ${cfg.policyFile}: ${policyNow.digest} -> ${digest}${warnings.length ? `; WARNING: ${warnings.join("; ")}` : ""}`);
217
+ const warnings = rego || hasPermitRule(text) ? [] : ["no permit rule: every call is denied"];
218
+ console.error(`agent-custody gateway: policy reloaded from ${policyFile}: ${policyNow.digest} -> ${digest}${warnings.length ? `; WARNING: ${warnings.join("; ")}` : ""}`);
184
219
  recordReload({ event: "reloaded", from: policyNow.digest, to: digest, ...(warnings.length ? { warnings } : {}) });
185
- policyNow = { text, digest };
220
+ policyNow = loaded.policy;
186
221
  return policyNow;
187
222
  };
188
223
  // Private evidence: the key that encrypts withheld fields, read once; a rule in mode encrypted without it is a config error.
@@ -420,7 +455,7 @@ export async function createGatewayHost(cfg, options = {}) {
420
455
  };
421
456
  async function handleCall(params) {
422
457
  const tool = params.name;
423
- const { text: policyText, digest: pDigest } = currentPolicy();
458
+ const { text: policyText, digest: pDigest, rego: regoPolicy } = currentPolicy();
424
459
  // An embedding caller can mutate its objects while a lookup or log append is awaited. Snapshot the call and
425
460
  // approval before the first await, so the approved bytes are the bytes evaluated, logged, and forwarded. A caller
426
461
  // also cannot change the payment after its reservation was bound.
@@ -490,11 +525,8 @@ export async function createGatewayHost(cfg, options = {}) {
490
525
  try {
491
526
  ({ facts, templates: factTemplates, results: factResults } = await gatherFacts(tool, args, upstreamMeta));
492
527
  const factValues = Object.fromEntries(Object.entries(facts).map(([k, f]) => [k, f.value]));
493
- policy = evaluate(policyText, {
494
- agentId: delegation.agent,
495
- tool,
496
- context: { args, facts: factValues, grant: { principal: delegation.principal, scopes: delegation.scopes } },
497
- });
528
+ const request = { agentId: delegation.agent, tool, context: { args, facts: factValues, grant: { principal: delegation.principal, scopes: delegation.scopes } } };
529
+ policy = opaServer ? await opaServer.decide(request) : regoPolicy ? evaluateRego(regoPolicy, pDigest, request) : evaluate(policyText, request);
498
530
  }
499
531
  catch (e) {
500
532
  policy = { decision: "deny", reasons: [], errors: [String(e instanceof Error ? e.message : e)], policyDigest: pDigest };
package/dist/index.d.ts CHANGED
@@ -7,6 +7,8 @@ export { hecEvent, splunkExporter } from "./splunk.ts";
7
7
  export { serveConsole, type ConsoleOptions, type RunningConsole } from "./console.ts";
8
8
  export { checkConfig, formatFindings, type CheckFinding, type CheckOptions } from "./check.ts";
9
9
  export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.ts";
10
+ export { AGENT_HEADER, ARRIVAL_FACT, CLASS_HEADER, DOOR_DEFAULT_CAPTURE, DOOR_VERSION, MAX_CHALLENGE_TOKEN, RECEIPT_HEADER, RATE_BURST_MS, RATE_MINUTE_MS, cedarArgs, classifyArrival, createDoorHost, createRateTracker, matchRoute, normalizePath, remoteOf, serveDoor, verifyChallengeToken } from "./door.ts";
11
+ export type { Arrival, ArrivalChallenge, ArrivalClass, ArrivalRate, ChallengeCheck, Classified, DoorHost, DoorOptions, DoorServerOptions, RateTracker, RateTrackerLimits, RunningDoor } from "./door.ts";
10
12
  export * from "./capture.ts";
11
13
  export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.ts";
12
14
  export { deliverMail, founderNote, PortalStore, portalHandler, readSession, readSessionVia, sendFollowUps, servePortal, signSession, SsoRefusedError, stripeRequest, verifyStripeSignature } from "./portal.ts";
@@ -52,6 +54,8 @@ export * from "./issue.ts";
52
54
  export * from "./log.ts";
53
55
  export * from "./log-sink.ts";
54
56
  export * from "./policy.ts";
57
+ export * from "./policy-rego.ts";
58
+ export * from "./opa-server.ts";
55
59
  export * from "./receipt.ts";
56
60
  export * from "./verify.ts";
57
61
  export * from "./sdk/index.ts";
@@ -59,3 +63,7 @@ export * from "./sidecar.ts";
59
63
  export * from "./upstream.ts";
60
64
  export * from "./retention.ts";
61
65
  export * from "./simulate.ts";
66
+ export * from "./pr-summary.ts";
67
+ export * from "./export.ts";
68
+ export * from "./claude-init.ts";
69
+ export * from "./deny-report.ts";
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ export { hecEvent, splunkExporter } from "./splunk.js";
6
6
  export { serveConsole } from "./console.js";
7
7
  export { checkConfig, formatFindings } from "./check.js";
8
8
  export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.js";
9
+ export { AGENT_HEADER, ARRIVAL_FACT, CLASS_HEADER, DOOR_DEFAULT_CAPTURE, DOOR_VERSION, MAX_CHALLENGE_TOKEN, RECEIPT_HEADER, RATE_BURST_MS, RATE_MINUTE_MS, cedarArgs, classifyArrival, createDoorHost, createRateTracker, matchRoute, normalizePath, remoteOf, serveDoor, verifyChallengeToken } from "./door.js";
9
10
  export * from "./capture.js";
10
11
  export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.js";
11
12
  export { deliverMail, founderNote, PortalStore, portalHandler, readSession, readSessionVia, sendFollowUps, servePortal, signSession, SsoRefusedError, stripeRequest, verifyStripeSignature } from "./portal.js";
@@ -31,6 +32,8 @@ export * from "./issue.js";
31
32
  export * from "./log.js";
32
33
  export * from "./log-sink.js";
33
34
  export * from "./policy.js";
35
+ export * from "./policy-rego.js";
36
+ export * from "./opa-server.js";
34
37
  export * from "./receipt.js";
35
38
  export * from "./verify.js";
36
39
  export * from "./sdk/index.js";
@@ -38,3 +41,7 @@ export * from "./sidecar.js";
38
41
  export * from "./upstream.js";
39
42
  export * from "./retention.js";
40
43
  export * from "./simulate.js";
44
+ export * from "./pr-summary.js";
45
+ export * from "./export.js";
46
+ export * from "./claude-init.js";
47
+ export * from "./deny-report.js";
package/dist/issue.js CHANGED
@@ -1,13 +1,11 @@
1
1
  // Signing, logging and writing a receipt. Shared by every producer: the gateway and the SDK.
2
- import { randomUUID } from "node:crypto";
3
- import { chmodSync, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
4
- import { hostname } from "node:os";
2
+ import { chmodSync, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, utimesSync, writeFileSync } from "node:fs";
5
3
  import { RECEIPT_ID, SALTS_DIR, saltsFileFor } from "./retention.js";
6
4
  import { dirname, join } from "node:path";
7
5
  import { effectiveRule, getAt, privateView } from "./capture.js";
8
6
  import { canonicalize, dsseSign, dsseVerify } from "./crypto.js";
9
7
  import { fileLog } from "./log-sink.js";
10
- import { ownerAlive, processStamp } from "./operations.js";
8
+ import { takeLock } from "./lock.js";
11
9
  import { buildAuthorizationStatement, buildStatement, RECEIPT_TYPE } from "./receipt.js";
12
10
  /** The receipts whose log append failed wait here, signed, until `flushOutbox` appends them. */
13
11
  export const OUTBOX_DIR = "outbox";
@@ -86,66 +84,8 @@ export function createIssuer(key, receiptsDir, log, opts = {}) {
86
84
  }
87
85
  };
88
86
  const lockFile = join(outboxDir, ".lock");
89
- /** Takes the outbox lock with an exclusive create. A lock whose owner is gone, or that no one has touched for a long time, is broken. Returns its release, or undefined when another flusher holds it. */
90
- const takeLock = () => {
91
- const token = randomUUID();
92
- const body = JSON.stringify({ token, pid: process.pid, start: processStamp(process.pid), host: hostname() });
93
- for (let attempt = 0; attempt < 3; attempt++) {
94
- try {
95
- const fd = openSync(lockFile, "wx", 0o600);
96
- try {
97
- writeFileSync(fd, body);
98
- }
99
- finally {
100
- closeSync(fd);
101
- }
102
- return () => {
103
- try {
104
- if (JSON.parse(readFileSync(lockFile, "utf8")).token === token)
105
- rmSync(lockFile, { force: true });
106
- }
107
- catch { /* already broken by another flusher */ }
108
- };
109
- }
110
- catch (e) {
111
- if (e.code !== "EEXIST")
112
- throw e;
113
- }
114
- if (!lockIsStale())
115
- return undefined;
116
- // two flushers may both judge it stale; the rename lets one of them move it, the other gets ENOENT and tries again
117
- try {
118
- const gone = `${lockFile}.stale-${randomUUID()}`;
119
- renameSync(lockFile, gone);
120
- rmSync(gone, { force: true });
121
- }
122
- catch (e) {
123
- if (e.code !== "ENOENT")
124
- throw e;
125
- }
126
- }
127
- return undefined;
128
- };
129
- const lockIsStale = () => {
130
- try {
131
- const age = Date.now() - statSync(lockFile).mtimeMs;
132
- let owner;
133
- try {
134
- owner = JSON.parse(readFileSync(lockFile, "utf8"));
135
- }
136
- catch { /* a lock being written */ }
137
- if (!owner)
138
- return age > 60_000;
139
- if (owner.host === hostname() && !ownerAlive({ ownerPid: owner.pid, ...(owner.start ? { ownerStart: owner.start } : {}) }))
140
- return true;
141
- return age > LOCK_STALE_MS;
142
- }
143
- catch (e) {
144
- if (e.code === "ENOENT")
145
- return true;
146
- throw e;
147
- }
148
- };
87
+ /** Undefined when another flusher holds the lock. A lock whose owner is gone, or that no one has touched for a long time, is broken. */
88
+ const takeOutboxLock = () => takeLock(lockFile, LOCK_STALE_MS);
149
89
  const writeBundle = async (receiptId, v, bundle) => {
150
90
  const file = join(receiptsDir, `${receiptId}.json`);
151
91
  // whole or absent: a flush takes a bundle that is there as proof that the outbox entry is done
@@ -246,7 +186,7 @@ export function createIssuer(key, receiptsDir, log, opts = {}) {
246
186
  const idle = () => ({ sent: 0, pending: outboxed().length, setAside: 0, foreign: 0 });
247
187
  if (!outboxed().length)
248
188
  return idle();
249
- const release = takeLock();
189
+ const release = takeOutboxLock();
250
190
  if (!release)
251
191
  return idle();
252
192
  try {
package/dist/lock.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Takes the lock with an exclusive create, and returns its release. The release removes the file only when it still
3
+ * holds this call's token, so a holder whose lock was broken never removes the lock of the next holder. Returns
4
+ * undefined when a live holder has the lock. A lock file that is gone between the create and the judgment is no
5
+ * reason to break anything: the caller tries the create again.
6
+ */
7
+ export declare function takeLock(lockFile: string, staleMs: number): (() => void) | undefined;
8
+ /** Runs `fn` under the lock. Waits up to `waitMs` for a live holder, then throws. */
9
+ export declare function withLock<T>(lockFile: string, opts: {
10
+ staleMs: number;
11
+ waitMs: number;
12
+ }, fn: () => T): T;
package/dist/lock.js ADDED
@@ -0,0 +1,124 @@
1
+ // One lock file design for the files that many processes write: the outbox and the local receipt log.
2
+ import { randomUUID } from "node:crypto";
3
+ import { closeSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
+ import { hostname } from "node:os";
5
+ import { ownerAlive, processStamp } from "./operations.js";
6
+ /** A lock file that holds no readable owner is a lock that is being written. After this age it is a leftover. */
7
+ const UNREADABLE_STALE_MS = 60_000;
8
+ const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
9
+ function readOwner(lockFile) {
10
+ try {
11
+ const o = JSON.parse(readFileSync(lockFile, "utf8"));
12
+ return o && typeof o.token === "string" && typeof o.pid === "number" && typeof o.host === "string" ? o : undefined;
13
+ }
14
+ catch {
15
+ return undefined;
16
+ }
17
+ }
18
+ /**
19
+ * A lock is stale when its owner on this host is gone. A live owner on this host keeps its lock, so a laptop that
20
+ * sleeps while it holds the lock keeps it. The owner on another host, and a file with no readable owner, are judged by age.
21
+ */
22
+ function judge(lockFile, staleMs) {
23
+ try {
24
+ const st = statSync(lockFile);
25
+ const age = Date.now() - st.mtimeMs;
26
+ const owner = readOwner(lockFile);
27
+ const stale = { token: owner?.token, ino: st.ino };
28
+ if (!owner)
29
+ return age > UNREADABLE_STALE_MS ? stale : "held";
30
+ if (owner.host === hostname())
31
+ return ownerAlive({ ownerPid: owner.pid, ...(owner.start ? { ownerStart: owner.start } : {}) }) ? "held" : stale;
32
+ return age > staleMs ? stale : "held";
33
+ }
34
+ catch (e) {
35
+ if (e.code === "ENOENT")
36
+ return "gone";
37
+ throw e;
38
+ }
39
+ }
40
+ /** Moves the lock away only if it is still the file that was judged stale. One breaker at a time holds `<lock>.break`. */
41
+ function breakLock(lockFile, judged) {
42
+ const breaker = `${lockFile}.break`;
43
+ try {
44
+ closeSync(openSync(breaker, "wx", 0o600));
45
+ }
46
+ catch (e) {
47
+ if (e.code !== "EEXIST")
48
+ throw e;
49
+ try {
50
+ if (Date.now() - statSync(breaker).mtimeMs > UNREADABLE_STALE_MS)
51
+ rmSync(breaker, { force: true });
52
+ }
53
+ catch { }
54
+ return;
55
+ }
56
+ try {
57
+ // between the judgment and now, the judged owner can release and a live caller can take the lock
58
+ if (statSync(lockFile).ino !== judged.ino || readOwner(lockFile)?.token !== judged.token)
59
+ return;
60
+ const gone = `${lockFile}.stale-${randomUUID()}`;
61
+ renameSync(lockFile, gone);
62
+ rmSync(gone, { force: true });
63
+ }
64
+ catch (e) {
65
+ if (e.code !== "ENOENT")
66
+ throw e;
67
+ }
68
+ finally {
69
+ rmSync(breaker, { force: true });
70
+ }
71
+ }
72
+ /**
73
+ * Takes the lock with an exclusive create, and returns its release. The release removes the file only when it still
74
+ * holds this call's token, so a holder whose lock was broken never removes the lock of the next holder. Returns
75
+ * undefined when a live holder has the lock. A lock file that is gone between the create and the judgment is no
76
+ * reason to break anything: the caller tries the create again.
77
+ */
78
+ export function takeLock(lockFile, staleMs) {
79
+ const token = randomUUID();
80
+ const body = JSON.stringify({ token, pid: process.pid, start: processStamp(process.pid), host: hostname() });
81
+ for (let attempt = 0; attempt < 3; attempt++) {
82
+ try {
83
+ const fd = openSync(lockFile, "wx", 0o600);
84
+ try {
85
+ writeFileSync(fd, body);
86
+ }
87
+ finally {
88
+ closeSync(fd);
89
+ }
90
+ return () => {
91
+ if (readOwner(lockFile)?.token === token)
92
+ rmSync(lockFile, { force: true });
93
+ };
94
+ }
95
+ catch (e) {
96
+ if (e.code !== "EEXIST")
97
+ throw e;
98
+ }
99
+ const j = judge(lockFile, staleMs);
100
+ if (j === "held")
101
+ return undefined;
102
+ if (j !== "gone")
103
+ breakLock(lockFile, j);
104
+ }
105
+ return undefined;
106
+ }
107
+ /** Runs `fn` under the lock. Waits up to `waitMs` for a live holder, then throws. */
108
+ export function withLock(lockFile, opts, fn) {
109
+ const deadline = Date.now() + opts.waitMs;
110
+ for (;;) {
111
+ const release = takeLock(lockFile, opts.staleMs);
112
+ if (release) {
113
+ try {
114
+ return fn();
115
+ }
116
+ finally {
117
+ release();
118
+ }
119
+ }
120
+ if (Date.now() > deadline)
121
+ throw new Error(`${lockFile} is held by another process, so the file is not written. Remove the lock file if no agent-custody process runs.`);
122
+ pause(2 + Math.random() * 8);
123
+ }
124
+ }
package/dist/log-admin.js CHANGED
@@ -31,12 +31,12 @@ export function welcomeSheet(o) {
31
31
  "hashOnly means this log never receives your receipts, only their hashes.",
32
32
  "",
33
33
  "For whoever verifies your receipts:",
34
- ` npx agent-custody verify receipts/<id>.json --issuer-key <your gateway.pub> --principal-key <your principal.pub> --log-url ${url} --log-id ${o.logId}`,
35
- ` npx agent-custody audit --older receipts/<earlier>.json --newer receipts/<later>.json --log-url ${url} --log-id ${o.logId}`,
34
+ ` npx @agent-custody/receipts verify receipts/<id>.json --issuer-key <your gateway.pub> --principal-key <your principal.pub> --log-url ${url} --log-id ${o.logId}`,
35
+ ` npx @agent-custody/receipts audit --older receipts/<earlier>.json --newer receipts/<later>.json --log-url ${url} --log-id ${o.logId}`,
36
36
  "--log-url fetches this log's published keys and pins them; --log-id makes sure the tree heads are this log's.",
37
37
  "",
38
38
  "Your log is yours to take, any time, with your token:",
39
- ` npx agent-custody log-export --log-url ${url} --tenant ${o.tenant} --token-env AGENT_CUSTODY_LOG_TOKEN --out custody-export/`,
39
+ ` npx @agent-custody/receipts log-export --log-url ${url} --tenant ${o.tenant} --token-env AGENT_CUSTODY_LOG_TOKEN --out custody-export/`,
40
40
  "It fetches every leaf hash, the signed head, the keys, the checkpoints, and your usage, checks they add up, and writes",
41
41
  "a log copy that verify --log and audit --log read with no server.",
42
42
  "",
package/dist/log.d.ts CHANGED
@@ -20,16 +20,33 @@ export declare class SubtreeCache {
20
20
  /** Proof that the tree of size newSize extends the tree of size oldSize. Empty when oldSize is 0 or equal to newSize. */
21
21
  export declare function consistencyProof(leafHashes: Buffer[], oldSize: number, newSize?: number): string[];
22
22
  /** RFC 9162 section 2.1.4.2. Pure: needs only the two sizes, the two roots, and the proof. */
23
- export declare function verifyConsistency(oldSize: number, oldRootHex: string, newSize: number, newRootHex: string, proofHex: string[]): boolean;
23
+ export declare function verifyConsistency(oldSize: number, oldRoot: string, newSize: number, newRoot: string, proofHex: string[]): boolean;
24
24
  export declare function rootOf(leafHashes: Buffer[], size?: number): string;
25
25
  export declare function inclusionProof(leafHashes: Buffer[], leafIndex: number, treeSize?: number): InclusionProof;
26
26
  /** RFC 9162 section 2.1.3.2 verification. Pure function: needs only the leaf hash, proof and claimed root. */
27
27
  export declare function verifyInclusion(leaf: Buffer, proof: InclusionProof, rootHex: string): boolean;
28
+ /** Each hook of a coding agent is its own process, so appends overlap: one writer at a time holds `<file>.lock`. */
29
+ export declare function logLocked<T>(file: string, fn: () => T): T;
28
30
  export declare class MerkleLog {
29
- private hashes;
30
- private readonly tree;
31
+ private readonly hashes;
32
+ private tree;
31
33
  private readonly file;
34
+ private bytes;
35
+ private inode;
32
36
  constructor(file: string);
37
+ /**
38
+ * Reads the leaves that another handle or process appended since the last read. A file that was replaced or cut
39
+ * short is read again from the start. Bytes after the last newline are not read: a writer may be in the middle of its
40
+ * write, or may have died in it.
41
+ */
42
+ private catchUp;
43
+ /**
44
+ * Under the lock: a last line with no newline is the remains of a writer that died in the middle of its write. No
45
+ * 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.
46
+ */
47
+ private cutTornTail;
48
+ /** Under the lock: reads what other writers appended, then writes this line, so each leaf gets the next index. */
49
+ private appendLine;
33
50
  get size(): number;
34
51
  /** Leaf hashes `from` (inclusive) to `to` (exclusive), as hex: what an export carries and what a copy is rebuilt from. */
35
52
  leafHashes(from: number, to?: number): string[];