@agent-custody/receipts 0.16.6 → 0.16.7

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.
package/dist/door.js CHANGED
@@ -2,8 +2,10 @@
2
2
  // agent's tools. Every arrival, a browser, an API client, or an agent, is classified by what it presented, decided by
3
3
  // the Cedar policy for its route, forwarded to the origin or refused, and receipted either way. Nothing here detects
4
4
  // an agent: `unknown` means nothing was presented, `claimed` means something was asserted and could not be checked,
5
- // and `verified` means a grant signed by a trusted principal names this agent for this route. The same key, policy
6
- // language, issuer, log, and verifier as the gateway; the receipt's issuer kind is `door`.
5
+ // and `verified` means a grant signed by a trusted principal names this agent for this route, or a Web Bot Auth
6
+ // signature checked against the key its agent's directory publishes. The same key, policy language, issuer, log, and
7
+ // verifier as the gateway; the receipt's issuer kind is `door`. A partner engine's detection verdict, when configured,
8
+ // is a fact beside the arrival, and only one the engine signed for this arrival (door-partner.ts).
7
9
  import { randomUUID } from "node:crypto";
8
10
  import { closeSync, fstatSync, openSync, readFileSync } from "node:fs";
9
11
  import { createServer } from "node:http";
@@ -12,6 +14,8 @@ import { digestOf, loadPrivateKey, loadPublicKey, sha256Hex } from "./crypto.js"
12
14
  import { decodeDelegation, delegationValidAt, verifyDelegation } from "./delegation.js";
13
15
  import { parseGrantHeader, GRANT_HEADER } from "./gateway-http.js";
14
16
  import { createIssuer, ReceiptPending } from "./issue.js";
17
+ import { createWebBotAuthVerifier, normalizeAuthority } from "./web-bot-auth.js";
18
+ import { createPartnerEngine, PARTNER_FACT, PARTNER_TOOL } from "./door-partner.js";
15
19
  import { openLog } from "./log-sink.js";
16
20
  import { openExporter } from "./otel.js";
17
21
  import { evaluate, hasPermitRule, policyDigest, policyParseErrors } from "./policy.js";
@@ -24,6 +28,11 @@ export const CLASS_HEADER = "x-agent-custody-class";
24
28
  export const ARRIVAL_FACT = "arrival";
25
29
  /** the header an agent may use to name itself without a grant; recorded as claimed, never checked */
26
30
  export const AGENT_HEADER = "x-agent-custody-agent";
31
+ /** in authz mode: the original request's method and target, as nginx `auth_request` and Envoy `ext_authz` are configured to send them */
32
+ export const ORIGINAL_METHOD_HEADER = "x-original-method";
33
+ export const ORIGINAL_URI_HEADER = "x-original-uri";
34
+ /** the reason an allowed authz receipt carries: the door decided, and the proxy, not the door, relays */
35
+ export const AUTHZ_ALLOWED_REASON = "allowed; the door answered the proxy's authz check and relays nothing: the proxy relays the request, and the door sees neither its body nor the origin's answer";
27
36
  const CHALLENGE_VERIFY_URL = { turnstile: "https://challenges.cloudflare.com/turnstile/v0/siteverify", hcaptcha: "https://api.hcaptcha.com/siteverify" };
28
37
  /** a provider token is about 2 KB; a longer value is refused as failed without calling the provider */
29
38
  export const MAX_CHALLENGE_TOKEN = 4096;
@@ -205,6 +214,20 @@ function requestUrl(req) {
205
214
  const raw = req.url ?? "/";
206
215
  return raw.startsWith("/") ? new URL(`http://door${raw}`) : new URL(raw, "http://door");
207
216
  }
217
+ /**
218
+ * The original request an authz check asks about, from `X-Original-Method` and `X-Original-URI`, with the check's own
219
+ * headers and address. The check request's own method and path are the proxy's (nginx sends GET to a fixed location),
220
+ * so both headers are required, and a check without them is refused rather than decided on the proxy's request.
221
+ */
222
+ export function authzTarget(req) {
223
+ const method = req.headers[ORIGINAL_METHOD_HEADER];
224
+ const uri = req.headers[ORIGINAL_URI_HEADER];
225
+ if (typeof method !== "string" || !/^[A-Za-z]+$/.test(method))
226
+ return { problem: `an authz check needs ${ORIGINAL_METHOD_HEADER}, the original request's method` };
227
+ if (typeof uri !== "string" || !uri.startsWith("/"))
228
+ return { problem: `an authz check needs ${ORIGINAL_URI_HEADER}, the original request's path and query` };
229
+ return { method: method.toUpperCase(), url: uri, headers: req.headers, ...(req.headersDistinct ? { headersDistinct: req.headersDistinct } : {}), socket: req.socket };
230
+ }
208
231
  /** A path without its trailing slash: `/refunds/` and `/refunds` are one route. */
209
232
  const bare = (p) => (p.length > 1 && p.endsWith("/") ? p.slice(0, -1) : p);
210
233
  /** The route an arrival falls under: the first configured route whose methods and decoded path match, else the unmatched name. A trailing slash matches as no trailing slash. */
@@ -238,23 +261,50 @@ export function remoteOf(req, trustProxy) {
238
261
  }
239
262
  return req.socket.remoteAddress ?? "unknown";
240
263
  }
264
+ /**
265
+ * The request as RFC 9421 reads it: the target as received, the `Host` as the authority, and every value of each field.
266
+ * A request without `headersDistinct` (a fetch request, which joins repeated fields with ", ") gives each field's value as
267
+ * it holds it.
268
+ */
269
+ export function signedRequestOf(req) {
270
+ const distinct = req.headersDistinct ?? Object.fromEntries(Object.entries(req.headers).filter((e) => e[1] !== undefined).map(([k, v]) => [k, Array.isArray(v) ? v : [v]]));
271
+ return {
272
+ method: (req.method ?? "GET").toUpperCase(),
273
+ target: req.url ?? "/",
274
+ authority: normalizeAuthority(typeof req.headers.host === "string" ? req.headers.host : ""),
275
+ header: (name) => (Object.hasOwn(distinct, name) ? distinct[name] : undefined),
276
+ };
277
+ }
241
278
  /**
242
279
  * What the arrival presented, checked where it can be. A grant signed by a trusted principal, in its window, naming this
243
280
  * route among its scopes, makes the arrival `verified` and its principal attested. A grant that is out of scope, expired,
244
281
  * or signed by a stranger leaves the arrival `claimed`: it asserted an identity the door could not accept for this route.
245
- * An `x-agent-custody-agent` header or an HTTP signature header alone is `claimed`. Nothing at all is `unknown`.
282
+ * Without a grant, a Web Bot Auth signature the door verified (`signature`, from `createWebBotAuthVerifier`) makes the
283
+ * arrival `verified` as its signature agent. With both, the signature binds the grant to its sender when the grant names
284
+ * that signature agent; a grant presented under another agent's signature is `wrong-sender` and the arrival `claimed`.
285
+ * An `x-agent-custody-agent` header or a signature that did not verify alone is `claimed`. Nothing at all is `unknown`.
286
+ * Without `signature`, a `Signature-Input` header is recorded as `unchecked`.
246
287
  */
247
- export function classifyArrival(req, trusted, route, trustProxy, at) {
288
+ export function classifyArrival(req, trusted, route, trustProxy, at, signature) {
248
289
  const url = requestUrl(req);
249
290
  const method = (req.method ?? "GET").toUpperCase();
250
291
  const declaredRaw = req.headers[AGENT_HEADER];
251
292
  const declared = typeof declaredRaw === "string" && declaredRaw.trim() ? declaredRaw.trim().slice(0, 200) : undefined;
252
- const signature = typeof req.headers["signature-input"] === "string";
293
+ const sig = signature ?? (req.headers["signature-input"] !== undefined ? { outcome: "unchecked" } : { outcome: "absent" });
294
+ const signer = sig.outcome === "verified" ? { agent: sig.agent, keyid: sig.keyid } : undefined;
295
+ const sigFields = {
296
+ signature: sig.outcome,
297
+ ...("agent" in sig && sig.agent ? { signatureAgent: sig.agent } : {}),
298
+ ...("keyid" in sig && sig.keyid ? { signatureKeyid: sig.keyid } : {}),
299
+ ...("error" in sig ? { signatureError: sig.error } : {}),
300
+ };
253
301
  const norm = normalizePath(url.pathname);
254
- const base = { signature, ...(declared ? { declared } : {}), remote: remoteOf(req, trustProxy), method, path: "path" in norm ? norm.path : url.pathname, route };
302
+ const base = { ...sigFields, ...(declared ? { declared } : {}), remote: remoteOf(req, trustProxy), method, path: "path" in norm ? norm.path : url.pathname, route };
255
303
  const envelope = parseGrantHeader(req);
256
304
  if (!envelope) {
257
- const claimed = !!declared || signature;
305
+ if (signer)
306
+ return { arrival: { class: "verified", subject: signer.agent, grant: "absent", ...base }, signer };
307
+ const claimed = !!declared || sig.outcome !== "absent";
258
308
  return { arrival: { class: claimed ? "claimed" : "unknown", subject: declared ?? "unknown", grant: "absent", ...base } };
259
309
  }
260
310
  const checked = verifyDelegation(envelope, trusted);
@@ -267,12 +317,15 @@ export function classifyArrival(req, trusted, route, trustProxy, at) {
267
317
  return { arrival: { class: "claimed", subject: grant.agent, grant: "invalid", grantError: "the grant is outside its validity window", ...base } };
268
318
  if (!grant.scopes.includes(route))
269
319
  return { arrival: { class: "claimed", subject: grant.agent, grant: "out-of-scope", grantError: `route "${route}" is not in the grant's scopes`, ...base } };
270
- return { arrival: { class: "verified", subject: grant.agent, grant: "verified", ...base }, delegation: { envelope, grant, principalKeyid: checked.keyid } };
320
+ // The signature proves who sent the request. A grant for one agent in a request another agent signed was handed on or taken.
321
+ if (signer && signer.agent !== grant.agent)
322
+ return { arrival: { class: "claimed", subject: grant.agent, grant: "wrong-sender", grantError: `the grant names agent "${grant.agent}", and the request is signed by ${signer.agent}`, ...base } };
323
+ return { arrival: { class: "verified", subject: grant.agent, grant: "verified", ...base }, delegation: { envelope, grant, principalKeyid: checked.keyid }, ...(signer ? { signer } : {}) };
271
324
  }
272
325
  /** methods that must not change anything at the origin; every other method is relayed only after its receipt is committed to the log */
273
326
  const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
274
327
  /** The body, or how many bytes had arrived when it passed the limit; the rest is drained and dropped. */
275
- function readBody(req, max) {
328
+ export function readBody(req, max) {
276
329
  return new Promise((resolve, reject) => {
277
330
  const chunks = [];
278
331
  let size = 0;
@@ -290,11 +343,11 @@ function readBody(req, max) {
290
343
  req.on("error", reject);
291
344
  });
292
345
  }
293
- /** The origin's answer, or how many bytes had arrived when it passed the limit; the rest is not read. */
294
- async function readResponse(upstream, max) {
295
- if (!upstream.body)
346
+ /** A fetch body, or how many bytes had arrived when it passed the limit; the rest is not read. */
347
+ export async function readStream(stream, max) {
348
+ if (!stream)
296
349
  return { body: Buffer.alloc(0) };
297
- const reader = upstream.body.getReader();
350
+ const reader = stream.getReader();
298
351
  const chunks = [];
299
352
  let size = 0;
300
353
  for (;;) {
@@ -330,7 +383,9 @@ function unreached(e) {
330
383
  return true;
331
384
  return Array.isArray(cause.errors) && cause.errors.length > 0 && cause.errors.every((x) => typeof x?.code === "string" && UNREACHED_CODES.has(x.code));
332
385
  }
333
- export async function createDoorHost(cfg, options = {}) {
386
+ const json = (status, headers, body) => ({ status, headers: { "content-type": "application/json", "cache-control": "no-store", ...headers }, body: JSON.stringify(body) });
387
+ /** The decision loop for a door config; `framework` is the receipt's `issuer.framework`. Throws when the config cannot be served. */
388
+ export function createDoorCore(cfg, options, framework) {
334
389
  const key = loadPrivateKey(cfg.identity.keyFile);
335
390
  const trusted = cfg.trustedPrincipalKeys.map(loadPublicKey);
336
391
  const captureKey = cfg.captureKeyEnv ? captureKeyFrom(process.env[cfg.captureKeyEnv] ?? (() => { throw new Error(`capture key: environment variable ${cfg.captureKeyEnv} is not set`); })()) : undefined;
@@ -339,15 +394,6 @@ export async function createDoorHost(cfg, options = {}) {
339
394
  if (side?.mode === "encrypted" && !captureKey)
340
395
  throw new Error(`capture for ${route} uses mode encrypted, which needs captureKeyEnv`);
341
396
  }
342
- const originHeaders = { ...(cfg.origin.headers ?? {}) };
343
- for (const [header, variable] of Object.entries(cfg.origin.headerEnv ?? {})) {
344
- const v = process.env[variable];
345
- if (!v)
346
- throw new Error(`origin: environment variable ${variable} is not set`);
347
- originHeaders[header] = v;
348
- }
349
- const origin = new URL(cfg.origin.url);
350
- const originPath = origin.pathname.replace(/\/$/, "");
351
397
  const f = options.fetch ?? fetch;
352
398
  const challengeSecret = cfg.challenge ? process.env[cfg.challenge.secretEnv] : undefined;
353
399
  if (cfg.challenge && !challengeSecret)
@@ -358,9 +404,11 @@ export async function createDoorHost(cfg, options = {}) {
358
404
  // a route the config gives no rule falls to "*", and without a "*" rule of the config's own, to the door's default
359
405
  const rules = cfg.capture && Object.hasOwn(cfg.capture, "*") ? cfg.capture : { ...(cfg.capture ?? {}), "*": DOOR_DEFAULT_CAPTURE };
360
406
  const issuer = createIssuer(key, cfg.receiptsDir, sink, { exporter: options.exporter ?? openExporter(cfg), capture: { rules, key: captureKey } });
361
- const issuedBy = { kind: "door", keyid: issuer.keyid, version: DOOR_VERSION, framework: "http" };
407
+ const issuedBy = { kind: "door", keyid: issuer.keyid, version: DOOR_VERSION, framework };
362
408
  const precommit = new Set(cfg.precommit);
363
409
  const rates = createRateTracker();
410
+ const webBotAuth = cfg.webBotAuth ? createWebBotAuthVerifier(cfg.webBotAuth, f) : undefined;
411
+ const partner = cfg.partner ? createPartnerEngine(cfg.partner, f) : undefined;
364
412
  // The policy, re-read when the file changes, as the gateway does; a file that does not parse is refused and the
365
413
  // policy in force stays. The bytes and the metadata come from one open file.
366
414
  const readPolicy = () => {
@@ -396,42 +444,19 @@ export async function createDoorHost(cfg, options = {}) {
396
444
  }
397
445
  return policyNow;
398
446
  };
399
- const json = (res, status, headers, body) => {
400
- res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", ...headers });
401
- res.end(JSON.stringify(body));
402
- };
403
- // Each arrival holds its body (up to maxBodyBytes) and the origin's answer (up to maxResponseBytes) in memory until it
404
- // is answered. Past maxInFlight arrivals at once, the next is answered 503 before its body is read: it is not decided,
405
- // relayed, or receipted.
406
- let inFlight = 0;
407
- async function handle(req, res) {
408
- if (inFlight >= cfg.maxInFlight) {
409
- req.resume();
410
- res.writeHead(503, { "content-type": "application/json", "cache-control": "no-store", "retry-after": "1" });
411
- res.end(JSON.stringify({ error: `the door is handling ${cfg.maxInFlight} requests; this one was not read, decided, or relayed. Retry` }));
412
- return;
413
- }
414
- inFlight += 1;
415
- try {
416
- await decideAndAnswer(req, res);
417
- }
418
- finally {
419
- inFlight -= 1;
420
- }
421
- }
422
- async function decideAndAnswer(req, res) {
423
- const receiptId = randomUUID();
447
+ async function decide(req, receiptId, readArrivalBody, framework) {
424
448
  const timestamp = new Date().toISOString();
425
- res.setHeader(RECEIPT_HEADER, receiptId);
426
449
  const url = requestUrl(req);
427
450
  const method = (req.method ?? "GET").toUpperCase();
428
451
  // A path that does not decode cleanly is never relayed; it falls under the unmatched route for the receipt.
429
452
  const norm = normalizePath(url.pathname);
430
453
  const path = "path" in norm ? norm.path : url.pathname;
431
454
  const route = "path" in norm ? matchRoute(cfg.routes, cfg.unmatchedRoute, method, path) : cfg.unmatchedRoute;
432
- const { arrival, delegation } = classifyArrival(req, trusted, route, !!cfg.trustProxy, timestamp);
433
- const by = delegation ? "agent" : "remote";
434
- arrival.rate = { by, ...rates.hit(`${by}:${delegation ? arrival.subject : arrival.remote}`) };
455
+ const signature = webBotAuth ? await webBotAuth.verify(signedRequestOf(req)) : undefined;
456
+ const { arrival, delegation, signer } = classifyArrival(req, trusted, route, !!cfg.trustProxy, timestamp, signature);
457
+ const checkedAgent = arrival.class === "verified";
458
+ const by = checkedAgent ? "agent" : "remote";
459
+ arrival.rate = { by, ...rates.hit(`${by}:${checkedAgent ? arrival.subject : arrival.remote}`) };
435
460
  if (cfg.challenge && challengeHeader) {
436
461
  const c = cfg.challenge;
437
462
  const token = req.headers[challengeHeader];
@@ -452,14 +477,26 @@ export async function createDoorHost(cfg, options = {}) {
452
477
  }
453
478
  }
454
479
  const { text: policyText, digest: pDigest } = currentPolicy();
455
- const read = await readBody(req, cfg.maxBodyBytes);
456
- const body = "body" in read ? read.body : null;
480
+ const read = readArrivalBody ? await readArrivalBody(cfg.maxBodyBytes) : null;
481
+ const body = read === null ? Buffer.alloc(0) : "body" in read ? read.body : null;
457
482
  const headers = {};
458
483
  for (const name of RECORDED_HEADERS) {
459
484
  const v = req.headers[name];
460
485
  if (typeof v === "string")
461
486
  headers[name] = v;
462
487
  }
488
+ // A verdict reaches the policy and the receipt only when its signature verified for this receipt and route. Without
489
+ // one, onFailure "deny" refuses the arrival whatever the policy says, and "absent" leaves the policy without the fact.
490
+ let verdict;
491
+ let partnerRefusal;
492
+ if (partner && cfg.partner && partner.applies(route)) {
493
+ const asked = await partner.ask({ receiptId, route, method, path, remote: arrival.remote, class: arrival.class, headers });
494
+ arrival.partner = asked.check;
495
+ if (asked.verdict)
496
+ verdict = { value: asked.verdict, signature: asked.signature };
497
+ else if (cfg.partner.onFailure === "deny")
498
+ partnerRefusal = `the partner engine ${cfg.partner.engine} gave no verified verdict (${asked.check.outcome}: ${asked.check.error ?? "no detail"}), and partner.onFailure is deny`;
499
+ }
463
500
  const contentType = req.headers["content-type"] ?? "";
464
501
  let recordedBody;
465
502
  if (body && body.length > 0 && body.length <= RECORDED_BODY_BYTES && /^application\/json\b/i.test(contentType)) {
@@ -478,18 +515,21 @@ export async function createDoorHost(cfg, options = {}) {
478
515
  query: queryOf(url),
479
516
  headers,
480
517
  ...(recordedBody !== undefined ? { body: recordedBody } : {}),
481
- ...(body ? { bodyBytes: body.length, bodyDigest: sha256Hex(body) } : { bodyBytes: read.bytes, bodyOversized: true }),
518
+ ...(read === null ? {} : body ? { bodyBytes: body.length, bodyDigest: sha256Hex(body) } : { bodyBytes: read.bytes, bodyOversized: true }),
482
519
  };
483
- const facts = { [ARRIVAL_FACT]: { tool: "door.arrival", args: {}, value: arrival, resultDigest: digestOf(arrival), provenance: "observed" } };
484
- // The Cedar principal is an agent the door checked: the one a verified grant names. A declared name, or the agent a
485
- // rejected grant names, stays in the arrival fact as a claim, so a permit on `principal == Agent::"x"` cannot be
486
- // satisfied by sending a header.
520
+ const facts = {
521
+ [ARRIVAL_FACT]: { tool: "door.arrival", args: {}, value: arrival, resultDigest: digestOf(arrival), provenance: "observed" },
522
+ ...(verdict ? { [PARTNER_FACT]: { tool: PARTNER_TOOL, args: {}, value: verdict.value, resultDigest: digestOf(verdict.value), provenance: "attested", attestation: verdict.signature } } : {}),
523
+ };
524
+ // The Cedar principal is an agent the door checked: the one a verified grant names, or the signature agent of a
525
+ // verified signature. A declared name, or the agent a rejected grant names, stays in the arrival fact as a claim, so
526
+ // a permit on `principal == Agent::"x"` cannot be satisfied by sending a header.
487
527
  let policy;
488
528
  try {
489
529
  policy = evaluate(policyText, {
490
- agentId: delegation ? delegation.grant.agent : "unknown",
530
+ agentId: checkedAgent ? arrival.subject : "unknown",
491
531
  tool: route,
492
- context: { args: cedarArgs(args), facts: { [ARRIVAL_FACT]: arrival }, ...(delegation ? { grant: { principal: delegation.grant.principal, scopes: delegation.grant.scopes } } : {}) },
532
+ context: { args: cedarArgs(args), facts: { [ARRIVAL_FACT]: arrival, ...(verdict ? { [PARTNER_FACT]: verdict.value } : {}) }, ...(delegation ? { grant: { principal: delegation.grant.principal, scopes: delegation.grant.scopes } } : {}) },
493
533
  });
494
534
  }
495
535
  catch (e) {
@@ -501,66 +541,171 @@ export async function createDoorHost(cfg, options = {}) {
501
541
  const head = {
502
542
  receiptId,
503
543
  timestamp,
504
- issuer: issuedBy,
544
+ issuer: framework ? { ...issuedBy, framework } : issuedBy,
505
545
  principal: delegation ? { id: delegation.grant.principal, keyid: delegation.principalKeyid, provenance: "attested" } : { id: null, provenance: "claimed" },
506
- agent: { id: arrival.subject, provenance: delegation ? "attested" : "claimed" },
546
+ // a signature alone is the door's own check against a directory it fetched, which a reader of the receipt cannot repeat
547
+ agent: { id: arrival.subject, provenance: delegation ? "attested" : signer ? "observed" : "claimed" },
507
548
  ...(delegation ? { delegation: { envelope: delegation.envelope, provenance: "attested" } } : {}),
508
549
  tool: { name: route, provenance: "observed" },
509
550
  request: { args, argsDigest: digestOf(args), provenance: "claimed" },
510
551
  facts,
511
552
  policy: { ...policy, provenance: "observed" },
512
553
  };
513
- let execution;
514
- let authorization;
515
- let answer;
516
- let withheldStatus = 503;
517
- // set when the relay failed before the request left the door; any other relay failure leaves the outcome unknown
518
- let notSent = false;
554
+ const decision = { receiptId, arrival, method, url, route, ...("relay" in norm ? { relay: norm.relay } : {}), body, head };
555
+ // observe mode records the missing verdict in the arrival fact and relays, as it does a deny
556
+ if (partnerRefusal && cfg.mode === "observe")
557
+ console.error(`agent-custody door (observe mode): ${partnerRefusal}; not enforced, receipt ${receiptId}`);
519
558
  if (!forward) {
520
- execution = { status: "denied", reason: [...policy.reasons, ...policy.errors].join("; ") || "no permit policy matched", provenance: "observed" };
559
+ decision.refused = { status: 403, execution: { status: "denied", reason: [...policy.reasons, ...policy.errors].join("; ") || "no permit policy matched", provenance: "observed" } };
560
+ }
561
+ else if (partnerRefusal && cfg.mode !== "observe") {
562
+ decision.refused = { status: 503, execution: { status: "withheld", reason: `not relayed: ${partnerRefusal}`, provenance: "observed" } };
521
563
  }
522
564
  else if ("problem" in norm) {
523
- withheldStatus = 400;
524
- execution = { status: "withheld", reason: `the path was not relayed: ${norm.problem}`, provenance: "observed" };
565
+ decision.refused = { status: 400, execution: { status: "withheld", reason: `the path was not relayed: ${norm.problem}`, provenance: "observed" } };
525
566
  }
526
567
  else if (body === null) {
527
- withheldStatus = 413;
528
- execution = { status: "withheld", reason: `the request body is larger than ${cfg.maxBodyBytes} bytes and was not relayed`, provenance: "observed" };
568
+ decision.refused = { status: 413, execution: { status: "withheld", reason: `the request body is larger than ${cfg.maxBodyBytes} bytes and was not relayed`, provenance: "observed" } };
529
569
  }
530
- else {
531
- if (!SAFE_METHODS.has(method) || precommit.has("*") || precommit.has(route)) {
532
- // A request that can change something at the origin is committed to the log before it is relayed, so that
533
- // evidence of the side effect exists before the side effect does. If the log will not take it, the request
534
- // is not relayed; in observe mode it is relayed and the missing authorization is printed.
535
- try {
536
- authorization = await issuer.authorize(head);
537
- }
538
- catch (e) {
539
- if (cfg.mode === "observe")
540
- console.error(`agent-custody door (observe mode): the log did not commit the authorization for ${route}, receipt ${receiptId}; the request was relayed without it: ${String(e instanceof Error ? e.message : e)}`);
541
- else
542
- execution = { status: "withheld", reason: `the log did not commit the authorization, so the request was not relayed: ${String(e instanceof Error ? e.message : e)}`, provenance: "observed" };
570
+ else if (!SAFE_METHODS.has(method) || precommit.has("*") || precommit.has(route)) {
571
+ // A request that can change something is committed to the log before it goes on, so that evidence of the side
572
+ // effect exists before the side effect does. If the log will not take it, the request does not go on; in observe
573
+ // mode it goes on and the missing authorization is printed.
574
+ try {
575
+ decision.authorization = await issuer.authorize(head);
576
+ }
577
+ catch (e) {
578
+ if (cfg.mode === "observe")
579
+ console.error(`agent-custody door (observe mode): the log did not commit the authorization for ${route}, receipt ${receiptId}; the request was relayed without it: ${String(e instanceof Error ? e.message : e)}`);
580
+ else
581
+ decision.refused = { status: 503, execution: { status: "withheld", reason: `the log did not commit the authorization, so the request was not relayed: ${String(e instanceof Error ? e.message : e)}`, provenance: "observed" } };
582
+ }
583
+ }
584
+ return decision;
585
+ }
586
+ const mark = (d, logPending) => ({ [RECEIPT_HEADER]: d.receiptId, [CLASS_HEADER]: d.arrival.class, ...(logPending ? { "x-agent-custody-log-pending": "true" } : {}) });
587
+ let inFlight = 0;
588
+ let timer;
589
+ if (options.autoFlush) {
590
+ const flush = () => void issuer.flushOutbox().catch((e) => console.error(`agent-custody door: outbox flush failed: ${e instanceof Error ? e.message : String(e)}`));
591
+ flush();
592
+ timer = setInterval(flush, 30_000);
593
+ timer.unref?.();
594
+ }
595
+ return {
596
+ keyid: issuer.keyid,
597
+ policyDigest: () => currentPolicy().digest,
598
+ // Each arrival holds its body (up to maxBodyBytes) in memory until it is decided. Past maxInFlight arrivals at once,
599
+ // the next is answered 503 before its body is read: it is not decided, passed on, or receipted.
600
+ admit: () => (inFlight >= cfg.maxInFlight ? false : (inFlight += 1, true)),
601
+ release: () => void (inFlight -= 1),
602
+ busy: () => json(503, { "retry-after": "1" }, { error: `the door is handling ${cfg.maxInFlight} requests; this one was not read, decided, or relayed. Retry` }),
603
+ decide,
604
+ consumed: (name, req, arrival) => name === GRANT_HEADER || name === AGENT_HEADER || name === challengeHeader ||
605
+ // the grant travelled in Authorization: it is the door's credential, not the origin's
606
+ (name === "authorization" && arrival.grant !== "absent" && !req.headers[GRANT_HEADER]),
607
+ async record(d, execution) {
608
+ try {
609
+ await issuer.issue({
610
+ ...d.head,
611
+ session: { id: null, toolUseId: null, provenance: "claimed" },
612
+ model: { id: null, provenance: "claimed" },
613
+ ...(d.authorization ? { authorization: d.authorization } : {}),
614
+ execution,
615
+ }, undefined, undefined, { deferLog: true });
616
+ return { logPending: false };
617
+ }
618
+ catch (e) {
619
+ if (e instanceof ReceiptPending) {
620
+ console.error(`agent-custody door: ${e.message}`);
621
+ return { logPending: true };
543
622
  }
623
+ console.error(`agent-custody door: receipt ${d.receiptId} was not written: ${e instanceof Error ? e.message : String(e)}`);
624
+ return null;
544
625
  }
626
+ },
627
+ mark,
628
+ refusal(d, logPending) {
629
+ const execution = d.refused.execution;
630
+ // A refused arrival that could have passed a challenge is told how: the provider, the public site key, and the header
631
+ if (execution.status === "denied")
632
+ return json(403, mark(d, logPending), { error: "refused by the door's policy", reason: execution.reason, receipt: d.receiptId, ...(cfg.challenge && d.arrival.challenge?.outcome !== "passed" ? { challenge: { provider: cfg.challenge.provider, siteKey: cfg.challenge.siteKey, header: cfg.challenge.header } } : {}) });
633
+ return json(d.refused.status, mark(d, logPending), { error: "not relayed", reason: execution.reason, receipt: d.receiptId });
634
+ },
635
+ unrecorded(d, execution, notSent) {
636
+ // The decision was carried out and the receipt of it could not be written. The client is told what happened
637
+ // rather than "not relayed", which would invite a retry of a refund that went through.
638
+ const outcome = execution.status === "executed" || execution.status === "failed" ? "the origin acted on the request; its answer is not relayed because there is no receipt of it. Do not retry" : execution.status === "error" ? (notSent ? "the origin could not be reached" : "the origin may have acted on the request. Do not retry") : "nothing was relayed";
639
+ return json(500, { [CLASS_HEADER]: d.arrival.class }, { error: "the door could not record this request", outcome, receipt: d.receiptId });
640
+ },
641
+ flushOutbox: () => issuer.flushOutbox(),
642
+ pendingReceipts: () => issuer.pending(),
643
+ close() {
644
+ if (timer)
645
+ clearInterval(timer);
646
+ rates.close();
647
+ },
648
+ };
649
+ }
650
+ export const sendAnswer = (res, a) => {
651
+ res.writeHead(a.status, a.headers);
652
+ res.end(a.body);
653
+ };
654
+ /** The door as a reverse proxy: decides each arrival with the shared core, relays an allowed one to the origin, and receipts it before answering. */
655
+ export async function createDoorHost(cfg, options = {}) {
656
+ if (cfg.authz)
657
+ return createAuthzHost(cfg, options);
658
+ if (!cfg.origin)
659
+ throw new Error("the door proxy needs origin.url: the site it relays to, or authz: true to answer a proxy's authz checks. A config without either is for the door in-process (@agent-custody/receipts/door)");
660
+ const originCfg = cfg.origin;
661
+ const originHeaders = { ...(originCfg.headers ?? {}) };
662
+ for (const [header, variable] of Object.entries(originCfg.headerEnv ?? {})) {
663
+ const v = process.env[variable];
664
+ if (!v)
665
+ throw new Error(`origin: environment variable ${variable} is not set`);
666
+ originHeaders[header] = v;
667
+ }
668
+ const origin = new URL(originCfg.url);
669
+ const originPath = origin.pathname.replace(/\/$/, "");
670
+ const f = options.fetch ?? fetch;
671
+ const core = createDoorCore(cfg, options, "http");
672
+ // Each arrival also holds the origin's answer (up to maxResponseBytes) in memory until it is answered.
673
+ async function handle(req, res) {
674
+ if (!core.admit()) {
675
+ req.resume();
676
+ return sendAnswer(res, core.busy());
677
+ }
678
+ try {
679
+ await decideAndAnswer(req, res);
680
+ }
681
+ finally {
682
+ core.release();
545
683
  }
684
+ }
685
+ async function decideAndAnswer(req, res) {
686
+ const receiptId = randomUUID();
687
+ res.setHeader(RECEIPT_HEADER, receiptId);
688
+ const d = await core.decide(req, receiptId, (max) => readBody(req, max));
689
+ const { arrival, method, url } = d;
690
+ let execution = d.refused?.execution;
691
+ let answer;
692
+ // set when the relay failed before the request left the door; any other relay failure leaves the outcome unknown
693
+ let notSent = false;
546
694
  if (!execution) {
547
695
  let upstream;
548
696
  try {
549
697
  // The path is set on a copy of the origin's URL, never resolved against it: resolving `//evil.example/x` would
550
698
  // move the relay, with the origin's credentials, to another host.
551
699
  const target = new URL(origin);
552
- target.pathname = originPath + norm.relay;
700
+ target.pathname = originPath + d.relay;
553
701
  target.search = url.search;
554
702
  const out = new Headers();
555
703
  for (const [name, value] of Object.entries(req.headers)) {
556
704
  // `expect` is the client's conversation with the door, which Node answered; fetch refuses to carry it
557
- if (value === undefined || HOP_BY_HOP.has(name) || name === "host" || name === "expect" || name === GRANT_HEADER || name === AGENT_HEADER || name === challengeHeader || name === "accept-encoding")
705
+ if (value === undefined || HOP_BY_HOP.has(name) || name === "host" || name === "expect" || name === "accept-encoding" || core.consumed(name, req, arrival))
558
706
  continue;
559
707
  if (!cfg.trustProxy && (CLIENT_ADDRESS_HEADERS.has(name) || name.startsWith("x-forwarded-")))
560
708
  continue;
561
- // the grant travelled in Authorization: it is the door's credential, not the origin's
562
- if (name === "authorization" && arrival.grant !== "absent" && !req.headers[GRANT_HEADER])
563
- continue;
564
709
  out.set(name, Array.isArray(value) ? value.join(", ") : value);
565
710
  }
566
711
  out.set("accept-encoding", "identity");
@@ -578,8 +723,8 @@ export async function createDoorHost(cfg, options = {}) {
578
723
  out.set(CLASS_HEADER, arrival.class);
579
724
  for (const [h, v] of Object.entries(originHeaders))
580
725
  out.set(h, v);
581
- upstream = await f(target, { method, headers: out, ...(method === "GET" || method === "HEAD" ? {} : { body: new Uint8Array(body) }), redirect: "manual", signal: AbortSignal.timeout(cfg.origin.timeoutMs) });
582
- const got = await readResponse(upstream, cfg.maxResponseBytes);
726
+ upstream = await f(target, { method, headers: out, ...(method === "GET" || method === "HEAD" ? {} : { body: new Uint8Array(d.body) }), redirect: "manual", signal: AbortSignal.timeout(originCfg.timeoutMs) });
727
+ const got = await readStream(upstream.body, cfg.maxResponseBytes);
583
728
  const back = {};
584
729
  upstream.headers.forEach((v, k) => { if (!HOP_BY_HOP.has(k) && k !== "content-length" && k !== "content-encoding" && k !== "set-cookie")
585
730
  back[k] = v; });
@@ -620,63 +765,78 @@ export async function createDoorHost(cfg, options = {}) {
620
765
  execution = { status: "error", error: notSent ? `the origin could not be reached: ${message}` : `the origin may have acted on the request${upstream ? ` (it answered ${upstream.status} and its body did not arrive)` : ""}: ${message}`, provenance: "observed" };
621
766
  }
622
767
  }
623
- let logPending = false;
624
- try {
625
- await issuer.issue({
626
- ...head,
627
- session: { id: null, toolUseId: null, provenance: "claimed" },
628
- model: { id: null, provenance: "claimed" },
629
- ...(authorization ? { authorization } : {}),
630
- execution,
631
- }, undefined, undefined, { deferLog: true });
632
- }
633
- catch (e) {
634
- if (!(e instanceof ReceiptPending)) {
635
- // The decision was carried out and the receipt of it could not be written. The client is told what happened at
636
- // the origin rather than "not relayed", which would invite a retry of a refund that went through.
637
- console.error(`agent-custody door: receipt ${receiptId} was not written: ${e instanceof Error ? e.message : String(e)}`);
638
- const outcome = execution.status === "executed" || execution.status === "failed" ? "the origin acted on the request; its answer is not relayed because there is no receipt of it. Do not retry" : execution.status === "error" ? (notSent ? "the origin could not be reached" : "the origin may have acted on the request. Do not retry") : "nothing was relayed";
639
- return json(res, 500, { [CLASS_HEADER]: arrival.class }, { error: "the door could not record this request", outcome, receipt: receiptId });
640
- }
641
- console.error(`agent-custody door: ${e.message}`);
642
- logPending = true;
643
- }
644
- const mark = { [RECEIPT_HEADER]: receiptId, [CLASS_HEADER]: arrival.class, ...(logPending ? { "x-agent-custody-log-pending": "true" } : {}) };
768
+ const recorded = await core.record(d, execution);
769
+ if (!recorded)
770
+ return sendAnswer(res, core.unrecorded(d, execution, notSent));
771
+ const mark = core.mark(d, recorded.logPending);
645
772
  switch (execution.status) {
646
773
  case "denied":
647
- // A refused arrival that could have passed a challenge is told how: the provider, the public site key, and the header
648
- return json(res, 403, mark, { error: "refused by the door's policy", reason: execution.reason, receipt: receiptId, ...(cfg.challenge && arrival.challenge?.outcome !== "passed" ? { challenge: { provider: cfg.challenge.provider, siteKey: cfg.challenge.siteKey, header: cfg.challenge.header } } : {}) });
649
774
  case "withheld":
650
- return json(res, withheldStatus, mark, { error: "not relayed", reason: execution.reason, receipt: receiptId });
775
+ return sendAnswer(res, core.refusal(d, recorded.logPending));
651
776
  case "error":
652
- return notSent
653
- ? json(res, 502, mark, { error: "the origin could not be reached", detail: execution.error, receipt: receiptId })
654
- : json(res, 504, mark, { error: "the origin may have acted on the request; its answer did not arrive. Do not retry", detail: execution.error, receipt: receiptId });
777
+ return sendAnswer(res, notSent
778
+ ? json(502, mark, { error: "the origin could not be reached", detail: execution.error, receipt: receiptId })
779
+ : json(504, mark, { error: "the origin may have acted on the request; its answer did not arrive. Do not retry", detail: execution.error, receipt: receiptId }));
655
780
  default: {
656
781
  if (!answer)
657
- return json(res, 502, mark, { error: `the origin answered, but its response is larger than ${cfg.maxResponseBytes} bytes and was not relayed. Do not retry`, receipt: receiptId });
782
+ return sendAnswer(res, json(502, mark, { error: `the origin answered, but its response is larger than ${cfg.maxResponseBytes} bytes and was not relayed. Do not retry`, receipt: receiptId }));
658
783
  res.writeHead(answer.status, { ...answer.headers, ...mark });
659
784
  res.end(answer.body);
660
785
  }
661
786
  }
662
787
  }
663
- let timer;
664
- if (options.autoFlush) {
665
- const flush = () => void issuer.flushOutbox().catch((e) => console.error(`agent-custody door: outbox flush failed: ${e instanceof Error ? e.message : String(e)}`));
666
- flush();
667
- timer = setInterval(flush, 30_000);
668
- timer.unref?.();
788
+ return {
789
+ keyid: core.keyid,
790
+ policyDigest: core.policyDigest,
791
+ handle,
792
+ flushOutbox: core.flushOutbox,
793
+ pendingReceipts: core.pendingReceipts,
794
+ async close() {
795
+ core.close();
796
+ },
797
+ };
798
+ }
799
+ /**
800
+ * The door behind nginx `auth_request` or Envoy `ext_authz`: decides each check about the original request with the
801
+ * shared core, receipts the decision, and answers 200 with the receipt id and class, or the refusal. It relays nothing,
802
+ * so the receipt records the decision, not the result: an allow is `withheld` with `AUTHZ_ALLOWED_REASON`.
803
+ */
804
+ function createAuthzHost(cfg, options) {
805
+ const core = createDoorCore(cfg, options, "authz");
806
+ async function handle(req, res) {
807
+ // a check carries no body: the proxy holds the original's and relays it after the answer
808
+ req.resume();
809
+ if (!core.admit())
810
+ return sendAnswer(res, core.busy());
811
+ try {
812
+ await answerCheck(req, res);
813
+ }
814
+ finally {
815
+ core.release();
816
+ }
817
+ }
818
+ async function answerCheck(req, res) {
819
+ // a check that does not say what it is checking is the proxy's misconfiguration, not an arrival: nothing to decide or receipt
820
+ const original = authzTarget(req);
821
+ if ("problem" in original)
822
+ return sendAnswer(res, json(400, {}, { error: original.problem }));
823
+ const d = await core.decide(original, randomUUID(), null);
824
+ const execution = d.refused?.execution ?? { status: "withheld", reason: d.head.policy?.decision === "allow" ? AUTHZ_ALLOWED_REASON : `${AUTHZ_ALLOWED_REASON}. Observe mode: the policy denied it and the denial was not enforced`, provenance: "observed" };
825
+ const recorded = await core.record(d, execution);
826
+ if (!recorded)
827
+ return sendAnswer(res, core.unrecorded(d, execution, true));
828
+ if (d.refused)
829
+ return sendAnswer(res, core.refusal(d, recorded.logPending));
830
+ return sendAnswer(res, json(200, core.mark(d, recorded.logPending), { allowed: true, receipt: d.receiptId }));
669
831
  }
670
832
  return {
671
- keyid: issuer.keyid,
672
- policyDigest: () => currentPolicy().digest,
833
+ keyid: core.keyid,
834
+ policyDigest: core.policyDigest,
673
835
  handle,
674
- flushOutbox: () => issuer.flushOutbox(),
675
- pendingReceipts: () => issuer.pending(),
836
+ flushOutbox: core.flushOutbox,
837
+ pendingReceipts: core.pendingReceipts,
676
838
  async close() {
677
- if (timer)
678
- clearInterval(timer);
679
- rates.close();
839
+ core.close();
680
840
  },
681
841
  };
682
842
  }