@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/egress.js ADDED
@@ -0,0 +1,585 @@
1
+ // The egress witness: an HTTP forward proxy in the agent's network path, the door turned around to face outbound
2
+ // traffic. An agent whose environment is locked down (default-deny egress except the gateway and this witness) reaches
3
+ // anything else only through here. Each connection is tied to an agent by the proxy credential the witness checked,
4
+ // decided by the Cedar or Rego policy for its destination, relayed or refused, and receipted either way with issuer kind
5
+ // `egress`. CONNECT is relayed as an opaque tunnel: the witness sees the destination, the times, and the byte counts,
6
+ // never the request, the response, or anything inside TLS. A receipt is an observed bypass of the gateway, not a record
7
+ // of what was done.
8
+ import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
9
+ import { closeSync, fstatSync, openSync, readFileSync } from "node:fs";
10
+ import { createServer, request as httpRequest } from "node:http";
11
+ import { lookup as dnsLookup } from "node:dns";
12
+ import { connect, isIP } from "node:net";
13
+ import { internalAddress } from "./addresses.js";
14
+ import { digestOf, loadPrivateKey } from "./crypto.js";
15
+ import { RECEIPT_HEADER } from "./door.js";
16
+ import { createIssuer, ReceiptPending } from "./issue.js";
17
+ import { openLog } from "./log-sink.js";
18
+ import { openExporter } from "./otel.js";
19
+ import { evaluate, hasPermitRule, policyDigest, policyParseErrors } from "./policy.js";
20
+ import { compileRego, evaluateRego, isRegoFile } from "./policy-rego.js";
21
+ export const EGRESS_VERSION = "0.1.0";
22
+ /** the fact every egress receipt carries, and the policy reads as `context.facts.destination` */
23
+ export const DESTINATION_FACT = "destination";
24
+ export const PROXY_REALM = "agent-custody egress";
25
+ /**
26
+ * Lowercase, without a final dot or IPv6 brackets; refused unless it is an IP address or a DNS name. A name whose last
27
+ * label is all digits or starts with `0x` is refused: the URL parser and `getaddrinfo` read it as an IPv4 address
28
+ * (`2130706433`, `0x7f.1`), so the policy would decide on a string that is not the address dialled.
29
+ */
30
+ export function normalizeHost(raw) {
31
+ let h = raw.toLowerCase();
32
+ if (h.startsWith("[") && h.endsWith("]")) {
33
+ h = h.slice(1, -1);
34
+ return isIP(h) === 6 ? h : null;
35
+ }
36
+ if (h.endsWith("."))
37
+ h = h.slice(0, -1);
38
+ if (isIP(h))
39
+ return h;
40
+ if (h.length === 0 || h.length > 253)
41
+ return null;
42
+ const last = h.slice(h.lastIndexOf(".") + 1);
43
+ if (/^\d+$/.test(last) || last.startsWith("0x"))
44
+ return null;
45
+ return h.split(".").every((label) => /^[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?$/.test(label)) ? h : null;
46
+ }
47
+ function parsePort(raw) {
48
+ if (!/^\d{1,5}$/.test(raw))
49
+ return null;
50
+ const n = Number(raw);
51
+ return n >= 1 && n <= 65535 ? n : null;
52
+ }
53
+ /**
54
+ * A CONNECT authority, `host:port` or `[v6]:port`; the port is required. The host goes through the same URL parser as a
55
+ * plain request's, so both paths decide on one canonical string: `010.0.0.1` is `8.0.0.1` and `2130706433` is
56
+ * `127.0.0.1`, the addresses `getaddrinfo` would dial.
57
+ */
58
+ export function parseAuthority(authority) {
59
+ const m = /^(\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9._-]+):(\d+)$/.exec(authority);
60
+ if (!m)
61
+ return null;
62
+ let canonical;
63
+ try {
64
+ canonical = new URL(`http://${m[1]}/`).hostname;
65
+ }
66
+ catch {
67
+ return null;
68
+ }
69
+ const host = normalizeHost(canonical);
70
+ const port = parsePort(m[2]);
71
+ return host && port ? { host, port } : null;
72
+ }
73
+ /** The policy's action for a destination: `host:port`, with an IPv6 address in brackets. */
74
+ export const destinationName = (host, port) => `${isIP(host) === 6 ? `[${host}]` : host}:${port}`;
75
+ const sha = (s) => createHash("sha256").update(s).digest();
76
+ /** compared against on every unknown id, so a miss costs what a hit costs: one hash of the presented secret and one compare */
77
+ const STAND_IN = sha(`stand-in:${randomUUID()}`);
78
+ /**
79
+ * Checks `Proxy-Authorization: Basic base64(id:secret)` against the secrets the witness holds. The comparison is over
80
+ * sha256 digests in constant time, and runs against one stand-in, hashed once, when the id is unknown, so the answer
81
+ * time does not say which ids exist.
82
+ */
83
+ export function checkProxyCredential(header, agents) {
84
+ if (!header)
85
+ return { credential: "absent" };
86
+ const m = /^basic\s+([A-Za-z0-9+/=]+)\s*$/i.exec(header);
87
+ if (!m)
88
+ return { credential: "invalid" };
89
+ const decoded = Buffer.from(m[1], "base64").toString("utf8");
90
+ const colon = decoded.indexOf(":");
91
+ if (colon < 1)
92
+ return { credential: "invalid" };
93
+ const id = decoded.slice(0, colon);
94
+ const presented = sha(decoded.slice(colon + 1));
95
+ const expected = agents.get(id);
96
+ const match = timingSafeEqual(presented, expected ?? STAND_IN) && expected !== undefined;
97
+ return match ? { credential: "verified", agent: id } : { credential: "invalid", declared: id.slice(0, 200) };
98
+ }
99
+ /**
100
+ * Wraps a resolver so that a host name never leads to an internal address: the policy decided on the name, and a name
101
+ * the agent chose (or a DNS answer someone else chose) must not turn a permit for a public host into a request to the
102
+ * metadata service, loopback, or the private network. Addresses that are internal are dropped before any connection is
103
+ * made; a name with none left fails. An IP literal is never looked up: it is the Cedar action itself, so a rule permits
104
+ * it by name. The check sits in the resolver the socket connects with, so there is no second lookup to rebind.
105
+ */
106
+ export function publicOnlyLookup(resolve = dnsLookup) {
107
+ return ((hostname, options, callback) => {
108
+ resolve(hostname, { ...options, all: true }, ((err, found) => {
109
+ if (err)
110
+ return callback(err);
111
+ const list = Array.isArray(found) ? found : [];
112
+ const usable = list.filter((a) => !internalAddress(a.address));
113
+ if (!usable.length)
114
+ return callback(Object.assign(new Error(`${hostname} resolves only to internal addresses (${list.map((a) => a.address).join(", ") || "none"}); the witness does not dial them for a host name`), { code: "EGRESS_INTERNAL" }));
115
+ if (options.all)
116
+ callback(null, usable);
117
+ else
118
+ callback(null, usable[0].address, usable[0].family);
119
+ }));
120
+ });
121
+ }
122
+ /** Headers that belong to the connection to the witness, never relayed to the destination. Proxy-Authorization is the agent's secret. */
123
+ const HOP_BY_HOP = new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade"]);
124
+ export async function createEgressHost(cfg, options = {}) {
125
+ const key = loadPrivateKey(cfg.identity.keyFile);
126
+ const agents = new Map();
127
+ for (const a of cfg.agents) {
128
+ const secret = process.env[a.secretEnv];
129
+ if (!secret)
130
+ throw new Error(`agent ${a.id}: environment variable ${a.secretEnv} is not set`);
131
+ agents.set(a.id, sha(secret));
132
+ }
133
+ const sink = options.log ?? openLog(cfg, key);
134
+ const issuer = createIssuer(key, cfg.receiptsDir, sink, { exporter: options.exporter ?? openExporter(cfg) });
135
+ // The policy, re-read when the file changes, as the gateway and the door do; a file that does not parse is refused and
136
+ // the policy in force stays. The bytes and the metadata come from one open file. A .rego file is compiled with the opa
137
+ // binary, as the gateway compiles one; a file that does not compile is refused the same way.
138
+ const readPolicy = () => {
139
+ const fd = openSync(cfg.policyFile, "r");
140
+ try {
141
+ const st = fstatSync(fd);
142
+ return { text: readFileSync(fd, "utf8"), key: `${st.ino}:${st.mtimeMs}:${st.ctimeMs}:${st.size}` };
143
+ }
144
+ finally {
145
+ closeSync(fd);
146
+ }
147
+ };
148
+ const rego = isRegoFile(cfg.policyFile);
149
+ const loadPolicy = ({ text, key }) => {
150
+ const digest = policyDigest(text);
151
+ if (!rego) {
152
+ const errors = policyParseErrors(text);
153
+ return errors.length ? { errors } : { policy: { text, digest, key }, errors: [] };
154
+ }
155
+ const compiled = compileRego(text);
156
+ return compiled.policy ? { policy: { text, digest, key, rego: compiled.policy }, errors: [] } : { errors: compiled.errors };
157
+ };
158
+ const first = loadPolicy(readPolicy());
159
+ if (!first.policy)
160
+ throw new Error(`policy ${cfg.policyFile} does not ${rego ? "compile" : "parse"}: ${first.errors.join("; ")}`);
161
+ if (!rego && !hasPermitRule(first.policy.text))
162
+ console.error(`agent-custody egress: ${cfg.policyFile} has no permit rule, so every connection is refused`);
163
+ let policyNow = first.policy;
164
+ // A file that failed to load is not tried again until it changes: a Rego compile runs opa build on the event loop, so
165
+ // retrying it on every connection would stall every tunnel until the file is fixed.
166
+ let failedKey = "";
167
+ const currentPolicy = () => {
168
+ try {
169
+ const next = readPolicy();
170
+ if (next.key !== policyNow.key && next.key !== failedKey) {
171
+ const loaded = loadPolicy(next);
172
+ failedKey = loaded.policy ? "" : next.key;
173
+ if (!loaded.policy)
174
+ console.error(`agent-custody egress: POLICY NOT RELOADED: ${cfg.policyFile} ${loaded.errors.join("; ")}; policy ${policyNow.digest} stays in force`);
175
+ else
176
+ policyNow = loaded.policy;
177
+ }
178
+ }
179
+ catch (e) {
180
+ console.error(`agent-custody egress: cannot read ${cfg.policyFile}: ${e instanceof Error ? e.message : String(e)}; policy ${policyNow.digest} stays in force`);
181
+ }
182
+ return policyNow;
183
+ };
184
+ let inFlight = 0;
185
+ let closing = false;
186
+ const open = new Set();
187
+ const pending = new Set();
188
+ function decide(req, scheme, host, port) {
189
+ const receiptId = randomUUID();
190
+ const timestamp = new Date().toISOString();
191
+ const header = req.headers["proxy-authorization"];
192
+ const checked = checkProxyCredential(typeof header === "string" ? header : undefined, agents);
193
+ const destination = { host, port, scheme, credential: checked.credential, ...(checked.declared ? { declared: checked.declared } : {}), remote: req.socket.remoteAddress ?? "unknown" };
194
+ const name = destinationName(host, port);
195
+ const method = (req.method ?? "GET").toUpperCase();
196
+ const args = { method, host, port };
197
+ const { text, digest, rego: regoPolicy } = currentPolicy();
198
+ // The principal is an agent whose credential the witness checked; an id in a credential that failed stays in the
199
+ // destination fact as a claim, so a rule on `Agent::"x"` (Cedar) or `input.principal == "x"` (Rego) cannot be met by
200
+ // naming x.
201
+ let policy;
202
+ try {
203
+ const request = { agentId: checked.agent ?? "unknown", tool: name, context: { args, facts: { [DESTINATION_FACT]: destination } } };
204
+ policy = regoPolicy ? evaluateRego(regoPolicy, digest, request) : evaluate(text, request);
205
+ }
206
+ catch (e) {
207
+ policy = { decision: "deny", reasons: [], errors: [String(e instanceof Error ? e.message : e)], policyDigest: digest };
208
+ }
209
+ if (cfg.mode === "observe")
210
+ policy = { ...policy, enforced: false };
211
+ // An agent the witness could not identify is refused in every mode: a receipt that names nobody proves nothing.
212
+ const refusal = checked.agent === undefined
213
+ ? { status: 407, reason: checked.credential === "absent" ? "no proxy credential was presented" : "the proxy credential did not verify" }
214
+ : policy.decision === "allow" || policy.enforced === false
215
+ ? undefined
216
+ : { status: 403, reason: [...policy.reasons, ...policy.errors].join("; ") || "no permit policy matched" };
217
+ const facts = { [DESTINATION_FACT]: { tool: "egress.destination", args: {}, value: destination, resultDigest: digestOf(destination), provenance: "observed" } };
218
+ const head = {
219
+ receiptId,
220
+ timestamp,
221
+ issuer: { kind: "egress", keyid: issuer.keyid, version: EGRESS_VERSION, framework: scheme },
222
+ principal: { id: null, provenance: "claimed" },
223
+ agent: { id: checked.agent ?? "unknown", provenance: checked.agent ? "observed" : "claimed" },
224
+ tool: { name, provenance: "observed" },
225
+ request: { args, argsDigest: digestOf(args), provenance: "claimed" },
226
+ facts,
227
+ policy: { ...policy, provenance: "observed" },
228
+ };
229
+ return { receiptId, timestamp, destination, agent: checked.agent, policy, forward: !refusal, ...(refusal ? { refusal } : {}), head };
230
+ }
231
+ /** Signs, logs, and writes the receipt. A log that does not answer leaves it in the outbox; any other failure is printed and returns false. */
232
+ async function record(d, execution) {
233
+ try {
234
+ await issuer.issue({ ...d.head, session: { id: null, toolUseId: null, provenance: "claimed" }, model: { id: null, provenance: "claimed" }, ...(d.authorization ? { authorization: d.authorization } : {}), execution }, undefined, undefined, { deferLog: true });
235
+ return { written: true, logPending: false };
236
+ }
237
+ catch (e) {
238
+ if (e instanceof ReceiptPending) {
239
+ console.error(`agent-custody egress: ${e.message}`);
240
+ return { written: true, logPending: true };
241
+ }
242
+ console.error(`agent-custody egress: receipt ${d.receiptId} was not written: ${e instanceof Error ? e.message : String(e)}`);
243
+ return { written: false, logPending: false };
244
+ }
245
+ }
246
+ /**
247
+ * Commits the connection to the log before any byte of the agent's moves, as the door commits a request that can change
248
+ * something: the bypass is on record even if the witness dies while the tunnel is open, or the closing receipt is never
249
+ * written. If the log will not take it, nothing is relayed; in observe mode it is relayed and the gap is printed.
250
+ */
251
+ async function commitOpen(d) {
252
+ try {
253
+ d.authorization = await issuer.authorize(d.head);
254
+ return undefined;
255
+ }
256
+ catch (e) {
257
+ const why = e instanceof Error ? e.message : String(e);
258
+ if (cfg.mode === "observe") {
259
+ console.error(`agent-custody egress (observe mode): the log did not commit connection ${d.receiptId} to ${d.head.tool.name}; it was relayed without it: ${why}`);
260
+ return undefined;
261
+ }
262
+ return `the log did not commit the connection, so it was not relayed: ${why}`;
263
+ }
264
+ }
265
+ const lookup = publicOnlyLookup(options.lookup);
266
+ const STOPPED = "the witness stopped before the connection opened";
267
+ const tracked = (p) => {
268
+ pending.add(p);
269
+ void p.finally(() => pending.delete(p)).catch(() => undefined);
270
+ return p;
271
+ };
272
+ /** Writes a whole HTTP/1.1 answer on a raw socket and closes it: a CONNECT is answered on the socket, not through a response object. */
273
+ const answerSocket = (socket, status, phrase, headers, body) => {
274
+ const text = JSON.stringify(body);
275
+ const lines = [`HTTP/1.1 ${status} ${phrase}`, "content-type: application/json", `content-length: ${Buffer.byteLength(text)}`, "connection: close", ...Object.entries(headers).map(([k, v]) => `${k}: ${v}`)];
276
+ socket.end(`${lines.join("\r\n")}\r\n\r\n${text}`);
277
+ };
278
+ const refusalHeaders = (d, logPending) => ({
279
+ [RECEIPT_HEADER]: d.receiptId,
280
+ ...(d.refusal?.status === 407 ? { "proxy-authenticate": `Basic realm="${PROXY_REALM}"` } : {}),
281
+ ...(logPending ? { "x-agent-custody-log-pending": "true" } : {}),
282
+ });
283
+ async function handleConnect(req, client, head) {
284
+ if (closing || inFlight >= cfg.maxInFlight) {
285
+ answerSocket(client, 503, "Service Unavailable", { "retry-after": "1" }, { error: `the witness is handling ${cfg.maxInFlight} connections; this one was not decided, relayed, or receipted. Retry` });
286
+ return;
287
+ }
288
+ const target = parseAuthority(req.url ?? "");
289
+ if (!target) {
290
+ answerSocket(client, 400, "Bad Request", {}, { error: "a CONNECT target is host:port; nothing was relayed or receipted" });
291
+ return;
292
+ }
293
+ inFlight += 1;
294
+ try {
295
+ await tracked(tunnel(req, client, head, target));
296
+ }
297
+ finally {
298
+ inFlight -= 1;
299
+ }
300
+ }
301
+ async function tunnel(req, client, head, target) {
302
+ client.on("error", () => undefined);
303
+ const d = decide(req, "connect", target.host, target.port);
304
+ if (!d.forward) {
305
+ const r = await record(d, { status: "denied", reason: d.refusal.reason, provenance: "observed" });
306
+ if (!r.written)
307
+ return answerSocket(client, 500, "Internal Server Error", {}, { error: "the witness could not record this connection; nothing was relayed", receipt: d.receiptId });
308
+ return answerSocket(client, d.refusal.status, d.refusal.status === 407 ? "Proxy Authentication Required" : "Forbidden", refusalHeaders(d, r.logPending), { error: d.refusal.status === 407 ? "the witness needs a proxy credential it can check" : "refused by the egress policy", reason: d.refusal.reason, receipt: d.receiptId });
309
+ }
310
+ // Registered before anything is awaited: close() must reach a connection that is still committing or connecting,
311
+ // or it would open after shutdown began and outlive it.
312
+ let stopped = false;
313
+ let upstream;
314
+ let wake;
315
+ const stopEarly = () => { stopped = true; upstream?.destroy(); wake?.(); };
316
+ open.add(stopEarly);
317
+ let connected;
318
+ try {
319
+ const withheld = await commitOpen(d);
320
+ if (withheld) {
321
+ const r = await record(d, { status: "withheld", reason: withheld, provenance: "observed" });
322
+ return answerSocket(client, 503, "Service Unavailable", { [RECEIPT_HEADER]: d.receiptId, ...(r.logPending ? { "x-agent-custody-log-pending": "true" } : {}) }, { error: "not relayed", reason: withheld, receipt: d.receiptId });
323
+ }
324
+ const socket = connect({ host: target.host, port: target.port, lookup });
325
+ upstream = socket;
326
+ socket.on("error", () => undefined);
327
+ if (stopped)
328
+ socket.destroy();
329
+ connected = stopped ? { ok: false, error: STOPPED } : await new Promise((resolve) => {
330
+ const timer = setTimeout(() => { socket.destroy(); resolve({ ok: false, error: `no connection within ${cfg.connectTimeoutMs} ms` }); }, cfg.connectTimeoutMs);
331
+ const done = (v) => { clearTimeout(timer); resolve(v); };
332
+ wake = () => done({ ok: false, error: STOPPED });
333
+ socket.once("connect", () => done({ ok: true }));
334
+ socket.once("error", (e) => done({ ok: false, error: e.message }));
335
+ client.once("close", () => { socket.destroy(); done({ ok: false, error: "the agent closed the connection before the destination answered" }); });
336
+ });
337
+ }
338
+ finally {
339
+ open.delete(stopEarly);
340
+ }
341
+ if (!connected.ok || stopped) {
342
+ // the tunnel never opened, so no byte of the agent's reached the destination
343
+ upstream?.destroy();
344
+ const error = stopped ? STOPPED : connected.error;
345
+ const r = await record(d, { status: "error", error: stopped ? STOPPED : `the destination could not be reached: ${error}`, provenance: "observed" });
346
+ const mark = { [RECEIPT_HEADER]: d.receiptId, ...(r.logPending ? { "x-agent-custody-log-pending": "true" } : {}) };
347
+ return stopped
348
+ ? answerSocket(client, 503, "Service Unavailable", mark, { error: STOPPED, receipt: d.receiptId })
349
+ : answerSocket(client, 502, "Bad Gateway", mark, { error: "the destination could not be reached", detail: error, receipt: d.receiptId });
350
+ }
351
+ const tunnelTo = upstream;
352
+ const openedAt = new Date().toISOString();
353
+ const peer = tunnelTo.remoteAddress ?? "unknown";
354
+ let bytesUp = head.length;
355
+ let bytesDown = 0;
356
+ let end = "closed";
357
+ const ended = new Promise((resolve) => {
358
+ let done = false;
359
+ const finish = (why) => {
360
+ if (why && end === "closed")
361
+ end = why;
362
+ if (done)
363
+ return;
364
+ done = true;
365
+ open.delete(stop);
366
+ client.destroy();
367
+ tunnelTo.destroy();
368
+ resolve();
369
+ };
370
+ const stop = () => finish("witness-stopped");
371
+ open.add(stop);
372
+ for (const s of [client, tunnelTo]) {
373
+ s.on("error", () => finish("reset"));
374
+ s.on("close", () => finish());
375
+ }
376
+ tunnelTo.setTimeout(cfg.idleTimeoutMs, () => finish("idle-timeout"));
377
+ // a socket's timeout counts reads and writes, so either direction keeps the tunnel open
378
+ client.on("data", (c) => { bytesUp += c.length; });
379
+ tunnelTo.on("data", (c) => { bytesDown += c.length; });
380
+ });
381
+ client.write(`HTTP/1.1 200 Connection Established\r\n${RECEIPT_HEADER}: ${d.receiptId}\r\n\r\n`);
382
+ if (head.length)
383
+ tunnelTo.write(head);
384
+ client.pipe(tunnelTo);
385
+ tunnelTo.pipe(client);
386
+ await ended;
387
+ const result = { peer, openedAt, closedAt: new Date().toISOString(), bytesUp, bytesDown, end };
388
+ await record(d, { status: "executed", result, resultDigest: digestOf(result), provenance: "observed" });
389
+ }
390
+ async function handleRequest(req, res) {
391
+ const json = (status, headers, body) => {
392
+ res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", ...headers });
393
+ res.end(JSON.stringify(body));
394
+ };
395
+ if (closing || inFlight >= cfg.maxInFlight) {
396
+ req.resume();
397
+ return json(503, { "retry-after": "1" }, { error: `the witness is handling ${cfg.maxInFlight} connections; this one was not decided, relayed, or receipted. Retry` });
398
+ }
399
+ let url;
400
+ try {
401
+ url = new URL(req.url ?? "");
402
+ }
403
+ catch { /* not absolute form */ }
404
+ const host = url ? normalizeHost(url.hostname) : null;
405
+ const port = url ? (url.port ? parsePort(url.port) : 80) : null;
406
+ if (!url || url.protocol !== "http:" || !host || !port || url.username || url.password) {
407
+ req.resume();
408
+ return json(400, {}, { error: "a proxied request names an absolute http:// URL with no credentials in it; HTTPS goes through CONNECT. Nothing was relayed or receipted" });
409
+ }
410
+ inFlight += 1;
411
+ try {
412
+ await tracked(relayPlain(req, res, url, host, port, json));
413
+ }
414
+ finally {
415
+ inFlight -= 1;
416
+ }
417
+ }
418
+ async function relayPlain(req, res, url, host, port, json) {
419
+ const d = decide(req, "http", host, port);
420
+ if (!d.forward) {
421
+ req.resume();
422
+ const r = await record(d, { status: "denied", reason: d.refusal.reason, provenance: "observed" });
423
+ if (!r.written)
424
+ return json(500, {}, { error: "the witness could not record this connection; nothing was relayed", receipt: d.receiptId });
425
+ return json(d.refusal.status, refusalHeaders(d, r.logPending), { error: d.refusal.status === 407 ? "the witness needs a proxy credential it can check" : "refused by the egress policy", reason: d.refusal.reason, receipt: d.receiptId });
426
+ }
427
+ let stoppedEarly = false;
428
+ const stopEarly = () => { stoppedEarly = true; };
429
+ open.add(stopEarly);
430
+ let withheld;
431
+ try {
432
+ withheld = await commitOpen(d);
433
+ }
434
+ finally {
435
+ open.delete(stopEarly);
436
+ }
437
+ if (withheld || stoppedEarly) {
438
+ req.resume();
439
+ const r = await record(d, withheld ? { status: "withheld", reason: withheld, provenance: "observed" } : { status: "error", error: STOPPED, provenance: "observed" });
440
+ return json(503, { [RECEIPT_HEADER]: d.receiptId, ...(r.logPending ? { "x-agent-custody-log-pending": "true" } : {}) }, { error: withheld ? "not relayed" : STOPPED, ...(withheld ? { reason: withheld } : {}), receipt: d.receiptId });
441
+ }
442
+ const headers = {};
443
+ for (const [name, value] of Object.entries(req.headers))
444
+ if (value !== undefined && !HOP_BY_HOP.has(name) && name !== "host" && name !== "expect")
445
+ headers[name] = value;
446
+ // the destination the policy decided on is the one the request names, whatever Host the agent wrote
447
+ headers.host = port === 80 ? (isIP(host) === 6 ? `[${host}]` : host) : destinationName(host, port);
448
+ const openedAt = new Date().toISOString();
449
+ let bytesUp = 0;
450
+ let bytesDown = 0;
451
+ let end = "closed";
452
+ let peer = "unknown";
453
+ let status;
454
+ let sent = false;
455
+ const outcome = await new Promise((resolve) => {
456
+ let settled = false;
457
+ const settle = (v) => { if (!settled) {
458
+ settled = true;
459
+ open.delete(stop);
460
+ resolve(v);
461
+ } };
462
+ const up = httpRequest({ host, port, method: req.method, path: `${url.pathname}${url.search}`, headers, agent: false, setHost: false, lookup });
463
+ const stop = () => { end = "witness-stopped"; up.destroy(); res.destroy(); settle({ ok: true }); };
464
+ open.add(stop);
465
+ const connectTimer = setTimeout(() => up.destroy(new Error(`no connection within ${cfg.connectTimeoutMs} ms`)), cfg.connectTimeoutMs);
466
+ up.on("socket", (s) => s.once("connect", () => { clearTimeout(connectTimer); sent = true; peer = s.remoteAddress ?? "unknown"; }));
467
+ up.setTimeout(cfg.idleTimeoutMs, () => { end = "idle-timeout"; up.destroy(new Error(`no bytes for ${cfg.idleTimeoutMs} ms`)); });
468
+ up.on("error", (e) => {
469
+ clearTimeout(connectTimer);
470
+ if (status !== undefined) {
471
+ if (end === "closed")
472
+ end = "reset";
473
+ res.destroy();
474
+ settle({ ok: true });
475
+ }
476
+ else
477
+ settle({ ok: false, error: e.message });
478
+ });
479
+ up.on("response", (answer) => {
480
+ status = answer.statusCode ?? 502;
481
+ const back = {};
482
+ for (const [name, value] of Object.entries(answer.headers))
483
+ if (value !== undefined && !HOP_BY_HOP.has(name))
484
+ back[name] = value;
485
+ res.writeHead(status, { ...back, [RECEIPT_HEADER]: d.receiptId });
486
+ answer.on("data", (c) => { bytesDown += c.length; });
487
+ answer.on("error", () => { if (end === "closed")
488
+ end = "reset"; });
489
+ answer.pipe(res);
490
+ answer.on("end", () => settle({ ok: true }));
491
+ answer.on("close", () => settle({ ok: true }));
492
+ });
493
+ res.on("close", () => {
494
+ if (res.writableFinished)
495
+ return;
496
+ if (end === "closed")
497
+ end = "reset";
498
+ up.destroy();
499
+ settle(sent ? { ok: true } : { ok: false, error: "the agent closed the connection before the destination answered" });
500
+ });
501
+ req.on("data", (c) => { bytesUp += c.length; });
502
+ req.on("error", () => { if (end === "closed")
503
+ end = "reset"; up.destroy(); });
504
+ req.pipe(up);
505
+ });
506
+ if (!outcome.ok) {
507
+ // a refused or unresolved connection never reached the destination; any later failure may have
508
+ const error = sent ? `the destination may have received the request: ${outcome.error}` : `the destination could not be reached: ${outcome.error}`;
509
+ const r = await record(d, { status: "error", error, provenance: "observed" });
510
+ if (!res.headersSent)
511
+ json(sent ? 504 : 502, { [RECEIPT_HEADER]: d.receiptId, ...(r.logPending ? { "x-agent-custody-log-pending": "true" } : {}) }, { error, receipt: d.receiptId });
512
+ return;
513
+ }
514
+ const result = { peer, openedAt, closedAt: new Date().toISOString(), bytesUp, bytesDown, end, ...(status !== undefined ? { status } : {}) };
515
+ await record(d, { status: "executed", result, resultDigest: digestOf(result), provenance: "observed" });
516
+ }
517
+ let timer;
518
+ if (options.autoFlush) {
519
+ const flush = () => void issuer.flushOutbox().catch((e) => console.error(`agent-custody egress: outbox flush failed: ${e instanceof Error ? e.message : String(e)}`));
520
+ flush();
521
+ timer = setInterval(flush, 30_000);
522
+ timer.unref?.();
523
+ }
524
+ return {
525
+ keyid: issuer.keyid,
526
+ policyDigest: () => currentPolicy().digest,
527
+ handleRequest,
528
+ handleConnect,
529
+ flushOutbox: () => issuer.flushOutbox(),
530
+ pendingReceipts: () => issuer.pending(),
531
+ async close() {
532
+ closing = true;
533
+ if (timer)
534
+ clearInterval(timer);
535
+ for (const stop of [...open])
536
+ stop();
537
+ await Promise.allSettled([...pending]);
538
+ },
539
+ };
540
+ }
541
+ /**
542
+ * Serves an egress host as an HTTP forward proxy. A request in origin form is for the witness itself:
543
+ * `GET /.well-known/agent-custody-egress` answers the key id and the policy digest, anything else 404. Bind it where
544
+ * only the locked-down agents can reach it.
545
+ */
546
+ export async function serveEgress(host, opts) {
547
+ const bind = opts.host ?? "127.0.0.1";
548
+ const log = opts.log ?? ((m) => console.error(m));
549
+ const fail = (e) => log(`agent-custody egress: ${e instanceof Error ? e.message : String(e)}`);
550
+ const server = createServer((req, res) => {
551
+ if ((req.url ?? "").startsWith("/")) {
552
+ req.resume();
553
+ if (req.method === "GET" && req.url === "/.well-known/agent-custody-egress") {
554
+ res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
555
+ res.end(JSON.stringify({ keyid: host.keyid, policyDigest: host.policyDigest(), version: EGRESS_VERSION, pendingReceipts: host.pendingReceipts() }));
556
+ }
557
+ else {
558
+ res.writeHead(404, { "content-type": "application/json" });
559
+ res.end(JSON.stringify({ error: "this is a forward proxy: name an absolute http:// URL, or CONNECT host:port" }));
560
+ }
561
+ return;
562
+ }
563
+ host.handleRequest(req, res).catch((e) => {
564
+ fail(e);
565
+ if (!res.headersSent) {
566
+ res.writeHead(500, { "content-type": "application/json" });
567
+ res.end(JSON.stringify({ error: "the witness failed before it could answer; whether the destination received the request is unknown", receipt: res.getHeader(RECEIPT_HEADER) ?? null }));
568
+ }
569
+ else
570
+ res.end();
571
+ });
572
+ });
573
+ server.on("connect", (req, socket, head) => {
574
+ host.handleConnect(req, socket, head).catch((e) => { fail(e); socket.destroy(); });
575
+ });
576
+ await new Promise((resolve) => server.listen(opts.port, bind, resolve));
577
+ const { port } = server.address();
578
+ return {
579
+ url: `http://${bind.includes(":") ? `[${bind}]` : bind}:${port}`,
580
+ async close() {
581
+ server.closeAllConnections?.();
582
+ await new Promise((resolve) => server.close(() => resolve()));
583
+ },
584
+ };
585
+ }
@@ -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.";