@agent-custody/receipts 0.16.10 → 0.16.11

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 (62) hide show
  1. package/README.md +20 -9
  2. package/dist/approval-requests.d.ts +114 -0
  3. package/dist/approval-requests.js +198 -0
  4. package/dist/approval.d.ts +8 -0
  5. package/dist/approval.js +10 -3
  6. package/dist/check.js +2 -0
  7. package/dist/cli.js +68 -2
  8. package/dist/completeness.d.ts +11 -2
  9. package/dist/completeness.js +45 -9
  10. package/dist/config.d.ts +3 -0
  11. package/dist/config.js +6 -1
  12. package/dist/console-page.js +87 -2
  13. package/dist/console.js +72 -0
  14. package/dist/crypto.d.ts +2 -0
  15. package/dist/crypto.js +2 -1
  16. package/dist/delegation.d.ts +1 -1
  17. package/dist/delegation.js +19 -2
  18. package/dist/did-key.d.ts +2 -0
  19. package/dist/did-key.js +21 -1
  20. package/dist/door-core.d.ts +373 -0
  21. package/dist/door-core.js +743 -0
  22. package/dist/door-worker.d.ts +133 -0
  23. package/dist/door-worker.js +259 -0
  24. package/dist/door.d.ts +11 -293
  25. package/dist/door.js +43 -753
  26. package/dist/gateway-http.d.ts +1 -6
  27. package/dist/gateway-http.js +2 -19
  28. package/dist/gateway.js +24 -3
  29. package/dist/grant-header.d.ts +8 -0
  30. package/dist/grant-header.js +19 -0
  31. package/dist/index.d.ts +3 -2
  32. package/dist/index.js +2 -1
  33. package/dist/issue.d.ts +2 -16
  34. package/dist/issue.js +2 -12
  35. package/dist/log-http.d.ts +37 -0
  36. package/dist/log-http.js +74 -0
  37. package/dist/log-sink.d.ts +3 -37
  38. package/dist/log-sink.js +5 -71
  39. package/dist/log.d.ts +2 -27
  40. package/dist/log.js +2 -173
  41. package/dist/merkle.d.ts +27 -0
  42. package/dist/merkle.js +175 -0
  43. package/dist/object-issuer.d.ts +29 -0
  44. package/dist/object-issuer.js +172 -0
  45. package/dist/receipt-pending.d.ts +16 -0
  46. package/dist/receipt-pending.js +14 -0
  47. package/dist/web-bot-auth.d.ts +26 -6
  48. package/dist/web-bot-auth.js +116 -56
  49. package/docs/approvals.md +33 -0
  50. package/docs/completeness.md +44 -5
  51. package/docs/console.md +11 -4
  52. package/docs/door-quickstart.md +53 -17
  53. package/docs/door-signals.md +5 -5
  54. package/docs/door-worker.md +81 -0
  55. package/docs/door.md +10 -8
  56. package/docs/github-action.md +2 -2
  57. package/docs/tutorials.md +2 -0
  58. package/docs/verification.md +1 -1
  59. package/package.json +3 -1
  60. package/vectors/audit.json +27 -27
  61. package/vectors/canonical.json +5 -5
  62. package/vectors/receipts.json +1645 -1549
package/dist/door.js CHANGED
@@ -9,359 +9,14 @@
9
9
  import { randomUUID } from "node:crypto";
10
10
  import { closeSync, fstatSync, openSync, readFileSync } from "node:fs";
11
11
  import { createServer } from "node:http";
12
- import { captureKeyFrom } from "./capture.js";
13
- import { digestOf, loadPrivateKey, loadPublicKey, publicKeyFromPem, sha256Hex } from "./crypto.js";
14
- import { DID_KEY_PREFIX, publicKeyFromDidKey } from "./did-key.js";
15
- import { decodeDelegation, delegationValidAt, grantChainDigests, verifyDelegation } from "./delegation.js";
16
- import { parseGrantHeader, GRANT_HEADER } from "./gateway-http.js";
17
- import { createIssuer, ReceiptPending } from "./issue.js";
18
- import { createWebBotAuthVerifier, normalizeAuthority } from "./web-bot-auth.js";
19
- import { createPartnerEngine, PARTNER_FACT, PARTNER_TOOL } from "./door-partner.js";
12
+ import { loadPrivateKey, loadPublicKey } from "./crypto.js";
13
+ import { createIssuer } from "./issue.js";
20
14
  import { openLog } from "./log-sink.js";
21
15
  import { FORM_SCRIPT_PATH, formScript } from "./door-form.js";
22
16
  import { createRevocationList } from "./revocation.js";
23
17
  import { openExporter } from "./otel.js";
24
- import { evaluate, hasPermitRule, policyDigest, policyParseErrors } from "./policy.js";
25
- export const DOOR_VERSION = "0.1.0";
26
- /** on every answer the door gives: the receipt that records the decision */
27
- export const RECEIPT_HEADER = "x-agent-custody-receipt";
28
- /** on every answer: `verified`, `claimed`, or `unknown`, what the door made of the arrival */
29
- export const CLASS_HEADER = "x-agent-custody-class";
30
- /** the fact the door records for every arrival, and the policy reads as `context.facts.arrival` */
31
- export const ARRIVAL_FACT = "arrival";
32
- /** the header an agent may use to name itself without a grant; recorded as claimed, never checked */
33
- export const AGENT_HEADER = "x-agent-custody-agent";
34
- /** in authz mode: the original request's method and target, as nginx `auth_request` and Envoy `ext_authz` are configured to send them */
35
- export const ORIGINAL_METHOD_HEADER = "x-original-method";
36
- export const ORIGINAL_URI_HEADER = "x-original-uri";
37
- /** the reason an allowed authz receipt carries: the door decided, and the proxy, not the door, relays */
38
- 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";
39
- const CHALLENGE_VERIFY_URL = { turnstile: "https://challenges.cloudflare.com/turnstile/v0/siteverify", hcaptcha: "https://api.hcaptcha.com/siteverify" };
40
- /** a provider token is about 2 KB; a longer value is refused as failed without calling the provider */
41
- export const MAX_CHALLENGE_TOKEN = 4096;
42
- /**
43
- * Error codes that are the provider's or the operator's fault, not the token's: a rotated secret, a site key that does not
44
- * match it, an outage. Every person would get one, so they are `unavailable`, which a policy handles as the provider's
45
- * state, and never `failed`, which a policy may treat as an attack. Token faults (`invalid-input-response`,
46
- * `timeout-or-duplicate`, `expired-input-response`, `already-seen-response`, `missing-input-response`) stay `failed`.
47
- */
48
- const PROVIDER_FAULT_CODES = new Set(["internal-error", "missing-input-secret", "invalid-input-secret", "bad-request", "sitekey-secret-mismatch", "invalid-sitekey", "missing-sitekey", "invalid-remoteip"]);
49
- /**
50
- * Asks the provider whether the token is good. The token and the secret go to the provider only; neither is recorded,
51
- * and a redirect is never followed, since it would resend both to the Location's host. `success` is not enough: the
52
- * token must have been issued on one of the site's own hostnames, and for the configured action, or a token solved on
53
- * another site with this site key, or for another widget, would pass.
54
- */
55
- export async function verifyChallengeToken(check, f) {
56
- const { provider } = check;
57
- // any client can send a value in the header: one no provider would issue costs no call
58
- if (check.token.length > MAX_CHALLENGE_TOKEN)
59
- return { provider, outcome: "failed", error: `the token is longer than ${MAX_CHALLENGE_TOKEN} characters and was not sent to the provider` };
60
- const body = new URLSearchParams({ secret: check.secret, response: check.token, ...(check.remoteIp ? { remoteip: check.remoteIp } : {}), ...(provider === "hcaptcha" && check.siteKey ? { sitekey: check.siteKey } : {}) });
61
- try {
62
- const res = await f(CHALLENGE_VERIFY_URL[provider], { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body, redirect: "manual", signal: AbortSignal.timeout(check.timeoutMs) });
63
- if (res.status >= 300 && res.status < 400)
64
- return { provider, outcome: "unavailable", error: `the provider answered a redirect (${res.status}); the secret is not resent` };
65
- if (!res.ok)
66
- return { provider, outcome: "unavailable", error: `the provider answered ${res.status}` };
67
- const answer = (await res.json());
68
- if (answer.success !== true) {
69
- const codes = Array.isArray(answer["error-codes"]) ? answer["error-codes"].filter((c) => typeof c === "string") : [];
70
- if (codes.some((c) => PROVIDER_FAULT_CODES.has(c)))
71
- return { provider, outcome: "unavailable", error: `the provider could not check the token: ${codes.join(", ")}` };
72
- return { provider, outcome: "failed", error: codes.join(", ") || "the provider refused the token" };
73
- }
74
- const host = typeof answer.hostname === "string" ? answer.hostname.toLowerCase() : undefined;
75
- if (!host || !check.hostnames.includes(host))
76
- return { provider, outcome: "failed", error: `the token was issued on ${host ?? "no hostname"}, not a hostname this door serves` };
77
- if (check.action !== undefined && answer.action !== check.action)
78
- return { provider, outcome: "failed", error: `the token was issued for action ${typeof answer.action === "string" ? answer.action : "(none)"}, not ${check.action}` };
79
- return { provider, outcome: "passed" };
80
- }
81
- catch (e) {
82
- return { provider, outcome: "unavailable", error: e instanceof Error ? e.message : String(e) };
83
- }
84
- }
85
- export const RATE_BURST_MS = 10_000;
86
- export const RATE_MINUTE_MS = 60_000;
87
- /**
88
- * Counts arrivals per source over the two windows. Each source keeps its arrival times in order with two heads that only
89
- * move forward, so one arrival costs the same however many came before it in the window; the array is compacted once
90
- * half of it is behind the minute head. The source key comes from the arrival, and with `trustProxy` the client may
91
- * choose it, so the map bounds itself: at most `maxSources` keys, none longer than `maxKeyLength`, and a source with no
92
- * arrival in the last minute is dropped every minute whether or not traffic goes on. A source forgotten early counts
93
- * again from 1, which only lowers what a pace rule sees for a client that floods the map. The clock is monotonic
94
- * (`performance.now`), so a step of the wall clock (an NTP correction, a VM resume) neither keeps old arrivals inside
95
- * the windows nor drops new ones; an injected clock that goes back is held at the last time seen. `now` is for tests.
96
- */
97
- export function createRateTracker(now = () => performance.now(), limits = {}) {
98
- const maxSources = limits.maxSources ?? 10_000;
99
- const maxKeyLength = limits.maxKeyLength ?? 256;
100
- // least recently seen first: a hit moves its key to the end
101
- const seen = new Map();
102
- let last = -Infinity;
103
- const clock = () => (last = Math.max(last, now()));
104
- const sweep = () => {
105
- const cutoff = clock() - RATE_MINUTE_MS;
106
- for (const [k, v] of seen)
107
- if (v.times[v.times.length - 1] <= cutoff)
108
- seen.delete(k);
109
- };
110
- const timer = setInterval(sweep, RATE_MINUTE_MS);
111
- timer.unref();
112
- return {
113
- hit(source) {
114
- const key = source.length > maxKeyLength ? `sha256:${sha256Hex(source)}` : source;
115
- const t = clock();
116
- const s = seen.get(key) ?? { times: [], minuteHead: 0, burstHead: 0 };
117
- s.times.push(t);
118
- while (s.times[s.minuteHead] <= t - RATE_MINUTE_MS)
119
- s.minuteHead += 1;
120
- if (s.burstHead < s.minuteHead)
121
- s.burstHead = s.minuteHead;
122
- while (s.times[s.burstHead] <= t - RATE_BURST_MS)
123
- s.burstHead += 1;
124
- if (s.minuteHead > 64 && s.minuteHead * 2 > s.times.length) {
125
- s.times = s.times.slice(s.minuteHead);
126
- s.burstHead -= s.minuteHead;
127
- s.minuteHead = 0;
128
- }
129
- seen.delete(key);
130
- seen.set(key, s);
131
- if (seen.size > maxSources)
132
- sweep();
133
- while (seen.size > maxSources)
134
- seen.delete(seen.keys().next().value);
135
- return { burst: s.times.length - s.burstHead, minute: s.times.length - s.minuteHead };
136
- },
137
- size: () => seen.size,
138
- close: () => clearInterval(timer),
139
- };
140
- }
141
- const HOP_BY_HOP = new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "proxy-connection"]);
142
- /** request headers the receipt records in clear; everything else is relayed and not recorded */
143
- const RECORDED_HEADERS = ["user-agent", "content-type", "accept", "host"];
144
- /** a JSON body up to this size is recorded in the receipt's arguments; a larger or non-JSON body is recorded by digest and size only */
145
- const RECORDED_BODY_BYTES = 64 * 1024;
146
- /**
147
- * Headers that name the client's address or the scheme and host it used. Without trustProxy the client wrote them, and an
148
- * origin that reads one (an allowlist on `X-Real-IP`, a rate limit on `Forwarded`) would trust the client's word: they
149
- * are dropped, and the door sets `X-Forwarded-For`, `X-Forwarded-Host`, `X-Forwarded-Proto`, and `X-Real-IP` itself.
150
- */
151
- const CLIENT_ADDRESS_HEADERS = new Set(["forwarded", "x-real-ip", "true-client-ip", "cf-connecting-ip", "x-client-ip", "x-cluster-client-ip", "fastly-client-ip"]);
152
- /** connection failures in which the request never left the door: the origin cannot have acted on it */
153
- const UNREACHED_CODES = new Set(["ECONNREFUSED", "ENOTFOUND", "EHOSTUNREACH", "ENETUNREACH", "EAI_AGAIN"]);
154
- /**
155
- * The record of the call keeps what arrived; the policy reads a copy Cedar accepts. Cedar has no `null` and no
156
- * non-integer number, and refuses the whole request on either, so a body with `"coupon": null` or `"price": 9.99` would
157
- * be denied whatever the policy says. In the copy a `null` is dropped and a number that is not a safe integer becomes its
158
- * string; a rule that compares `price` as a number then errors, and the call is denied by that rule rather than by Cedar.
159
- */
160
- export function cedarArgs(value) {
161
- if (Array.isArray(value))
162
- return value.filter((v) => v !== null).map(cedarArgs);
163
- if (typeof value === "number")
164
- return Number.isSafeInteger(value) ? value : String(value);
165
- if (value && typeof value === "object") {
166
- const out = {};
167
- for (const [k, v] of Object.entries(value))
168
- if (v !== null)
169
- Object.defineProperty(out, k, { value: cedarArgs(v), enumerable: true, writable: true, configurable: true });
170
- return out;
171
- }
172
- return value;
173
- }
174
- /**
175
- * What a receipt records of an arrival when the config gives its route no capture rule: the method, the path, the
176
- * recorded headers, and the body's size in clear; the query and the body withheld, each a salted commitment. A query can
177
- * carry an API key and a form body a password. Set a rule for the route (or `"*"`) to record more in clear.
178
- */
179
- export const DOOR_DEFAULT_CAPTURE = { args: { mode: "digest", clear: ["method", "path", "headers", "bodyBytes", "bodyOversized"] }, result: { mode: "clear" }, facts: { mode: "clear" } };
180
- /**
181
- * The path as the origin will read it: each segment percent-decoded once, so that `/%61dmin` falls under `/admin/*`, and
182
- * empty segments merged, so that `//admin/users` and `/admin//users` fall under it too (nginx, Apache, and many
183
- * frameworks merge them, and the origin would serve the admin page to an arrival the door matched as something else).
184
- * A trailing slash is kept. Refused when a segment does not decode, or decodes to a slash, a backslash, or a dot
185
- * segment: the origin would then read a path the door did not match. `relay` is the merged, decoded path encoded once
186
- * more, the form the origin is sent, so the door and the origin read one path.
187
- */
188
- export function normalizePath(pathname) {
189
- const segments = [];
190
- for (const raw of pathname.split("/")) {
191
- if (raw === "")
192
- continue;
193
- let segment;
194
- try {
195
- segment = decodeURIComponent(raw);
196
- }
197
- catch {
198
- return { problem: `the path segment "${raw}" does not percent-decode` };
199
- }
200
- if (segment.includes("/") || segment.includes("\\"))
201
- return { problem: `the path segment "${raw}" decodes to a slash` };
202
- if (segment === "." || segment === "..")
203
- return { problem: `the path segment "${raw}" decodes to a dot segment` };
204
- if (segment === "")
205
- return { problem: `the path segment "${raw}" decodes to nothing` };
206
- segments.push(segment);
207
- }
208
- const tail = segments.length > 0 && pathname.endsWith("/") ? "/" : "";
209
- return { path: `/${segments.join("/")}${tail}`, relay: `/${segments.map(encodeSegment).join("/")}${tail}` };
210
- }
211
- /** A path segment encoded once: what `encodeURIComponent` does, except that the characters a path segment may carry in clear stay in clear. */
212
- function encodeSegment(segment) {
213
- return encodeURIComponent(segment).replace(/%(3A|40|24|26|2B|2C|3B|3D)/gi, (m) => decodeURIComponent(m));
214
- }
215
- /** The request target as a URL whose host is the door's own: an origin-form target `//x/y` is a path, never a scheme-relative URL. */
216
- function requestUrl(req) {
217
- const raw = req.url ?? "/";
218
- return raw.startsWith("/") ? new URL(`http://door${raw}`) : new URL(raw, "http://door");
219
- }
220
- /**
221
- * The original request an authz check asks about, from `X-Original-Method` and `X-Original-URI`, with the check's own
222
- * headers and address. The check request's own method and path are the proxy's (nginx sends GET to a fixed location),
223
- * so both headers are required, and a check without them is refused rather than decided on the proxy's request.
224
- */
225
- export function authzTarget(req) {
226
- const method = req.headers[ORIGINAL_METHOD_HEADER];
227
- const uri = req.headers[ORIGINAL_URI_HEADER];
228
- if (typeof method !== "string" || !/^[A-Za-z]+$/.test(method))
229
- return { problem: `an authz check needs ${ORIGINAL_METHOD_HEADER}, the original request's method` };
230
- if (typeof uri !== "string" || !uri.startsWith("/"))
231
- return { problem: `an authz check needs ${ORIGINAL_URI_HEADER}, the original request's path and query` };
232
- return { method: method.toUpperCase(), url: uri, headers: req.headers, ...(req.headersDistinct ? { headersDistinct: req.headersDistinct } : {}), socket: req.socket };
233
- }
234
- /** A path without its trailing slash: `/refunds/` and `/refunds` are one route. */
235
- const bare = (p) => (p.length > 1 && p.endsWith("/") ? p.slice(0, -1) : p);
236
- /** 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. */
237
- export function matchRoute(routes, unmatched, method, pathname) {
238
- const path = bare(pathname);
239
- for (const r of routes) {
240
- if (r.methods && !r.methods.includes(method))
241
- continue;
242
- if (r.path === "*")
243
- return r.name;
244
- if (r.path.endsWith("/*")) {
245
- const prefix = bare(r.path.slice(0, -2)) || "/";
246
- if (path === prefix || path.startsWith(prefix === "/" ? "/" : `${prefix}/`))
247
- return r.name;
248
- }
249
- else if (bare(r.path) === path)
250
- return r.name;
251
- }
252
- return unmatched;
253
- }
254
- /**
255
- * The arrival's address: the socket's, or with trustProxy the last address in `X-Forwarded-For`, the one the proxy in
256
- * front of the door appended. Everything before it was sent by the client, which may write what it likes there.
257
- */
258
- export function remoteOf(req, trustProxy) {
259
- if (trustProxy) {
260
- const xff = req.headers["x-forwarded-for"];
261
- const last = (Array.isArray(xff) ? xff.join(",") : xff)?.split(",").map((a) => a.trim()).filter(Boolean).pop();
262
- if (last)
263
- return last;
264
- }
265
- return req.socket.remoteAddress ?? "unknown";
266
- }
267
- /**
268
- * The request as RFC 9421 reads it: the target as received, the `Host` as the authority, and every value of each field.
269
- * A request without `headersDistinct` (a fetch request, which joins repeated fields with ", ") gives each field's value as
270
- * it holds it.
271
- */
272
- export function signedRequestOf(req) {
273
- const distinct = req.headersDistinct ?? Object.fromEntries(Object.entries(req.headers).filter((e) => e[1] !== undefined).map(([k, v]) => [k, Array.isArray(v) ? v : [v]]));
274
- return {
275
- method: (req.method ?? "GET").toUpperCase(),
276
- target: req.url ?? "/",
277
- authority: normalizeAuthority(typeof req.headers.host === "string" ? req.headers.host : ""),
278
- header: (name) => (Object.hasOwn(distinct, name) ? distinct[name] : undefined),
279
- };
280
- }
281
- /**
282
- * What the arrival presented, checked where it can be. A grant signed by a trusted principal, in its window, naming this
283
- * route among its scopes, makes the arrival `verified` and its principal attested. A grant that is out of scope, expired,
284
- * or signed by a stranger leaves the arrival `claimed`: it asserted an identity the door could not accept for this route.
285
- * Without a grant, a Web Bot Auth signature the door verified (`signature`, from `createWebBotAuthVerifier`) makes the
286
- * arrival `verified` as its signature agent. With both, the signature binds the grant to its sender when the grant names
287
- * that signature agent; a grant presented under another agent's signature is `wrong-sender` and the arrival `claimed`.
288
- * An `x-agent-custody-agent` header or a signature that did not verify alone is `claimed`. Nothing at all is `unknown`.
289
- * Without `signature`, a `Signature-Input` header is recorded as `unchecked`. `revoked`, when given, says why a grant
290
- * that verified is revoked (from its chain's digests, leaf first), or null when it is not; a revoked grant is `claimed`.
291
- */
292
- export function classifyArrival(req, trusted, route, trustProxy, at, signature, revoked) {
293
- const url = requestUrl(req);
294
- const method = (req.method ?? "GET").toUpperCase();
295
- const declaredRaw = req.headers[AGENT_HEADER];
296
- const declared = typeof declaredRaw === "string" && declaredRaw.trim() ? declaredRaw.trim().slice(0, 200) : undefined;
297
- const sig = signature ?? (req.headers["signature-input"] !== undefined ? { outcome: "unchecked" } : { outcome: "absent" });
298
- const signer = sig.outcome === "verified" ? { agent: sig.agent, keyid: sig.keyid } : undefined;
299
- const sigFields = {
300
- signature: sig.outcome,
301
- ...("agent" in sig && sig.agent ? { signatureAgent: sig.agent } : {}),
302
- ...("keyid" in sig && sig.keyid ? { signatureKeyid: sig.keyid } : {}),
303
- ...("error" in sig ? { signatureError: sig.error } : {}),
304
- };
305
- const norm = normalizePath(url.pathname);
306
- const base = { ...sigFields, ...(declared ? { declared } : {}), remote: remoteOf(req, trustProxy), method, path: "path" in norm ? norm.path : url.pathname, route };
307
- const envelope = parseGrantHeader(req);
308
- if (!envelope) {
309
- if (signer)
310
- return { arrival: { class: "verified", subject: signer.agent, grant: "absent", ...base }, signer };
311
- const claimed = !!declared || sig.outcome !== "absent";
312
- return { arrival: { class: claimed ? "claimed" : "unknown", subject: declared ?? "unknown", grant: "absent", ...base } };
313
- }
314
- const checked = verifyDelegation(envelope, trusted);
315
- const asserted = decodeDelegation(envelope)?.agent;
316
- const subject = declared ?? asserted ?? "unknown";
317
- if (!checked.ok)
318
- return { arrival: { class: "claimed", subject, grant: "invalid", grantError: checked.error, ...base } };
319
- const grant = checked.delegation;
320
- const revocation = revoked?.(grantChainDigests(envelope));
321
- if (revocation)
322
- return { arrival: { class: "claimed", subject: grant.agent, grant: "revoked", grantError: revocation, ...base } };
323
- // An agent named by a did:key is its key: the identifier must decode to an Ed25519 key, and the grant's agentKey, if
324
- // it names one, must be that key, or the grant says two things about who the agent is. Every link of a chain, since a
325
- // parent's agentKey is what verified the link below it.
326
- for (const [i, link] of checked.chain.entries()) {
327
- if (!link.agent.startsWith(DID_KEY_PREFIX))
328
- continue;
329
- const named = didKeyAgent(link.agent, link.agentKey);
330
- const where = i === checked.chain.length - 1 ? "" : `link ${i} (${link.agent}): `;
331
- if (named)
332
- return { arrival: { class: "claimed", subject: grant.agent, grant: "invalid", grantError: where + named, ...base } };
333
- }
334
- if (!delegationValidAt(grant, at))
335
- return { arrival: { class: "claimed", subject: grant.agent, grant: "invalid", grantError: "the grant is outside its validity window", ...base } };
336
- if (!grant.scopes.includes(route))
337
- return { arrival: { class: "claimed", subject: grant.agent, grant: "out-of-scope", grantError: `route "${route}" is not in the grant's scopes`, ...base } };
338
- // The signature proves who sent the request. A grant for one agent in a request another agent signed was handed on or taken.
339
- if (signer && signer.agent !== grant.agent)
340
- 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 } };
341
- return { arrival: { class: "verified", subject: grant.agent, grant: "verified", ...base }, delegation: { envelope, grant, principalKeyid: checked.keyid }, ...(signer ? { signer } : {}) };
342
- }
343
- /** Why a did:key agent does not check out, or null when it decodes and agrees with the grant's agentKey. */
344
- function didKeyAgent(did, agentKey) {
345
- let named;
346
- try {
347
- named = publicKeyFromDidKey(did);
348
- }
349
- catch (e) {
350
- return `the grant's did:key agent does not decode: ${e instanceof Error ? e.message : String(e)}`;
351
- }
352
- if (agentKey === undefined)
353
- return null;
354
- try {
355
- if (publicKeyFromPem(agentKey).keyid === named.keyid)
356
- return null;
357
- }
358
- catch {
359
- return "the grant's agentKey is not a public key";
360
- }
361
- return "the grant's agentKey is not the key its did:key agent names";
362
- }
363
- /** methods that must not change anything at the origin; every other method is relayed only after its receipt is committed to the log */
364
- const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
18
+ import { AUTHZ_ALLOWED_REASON, DOOR_VERSION, RECEIPT_HEADER, authzTarget, createDoorCoreWith, jsonAnswer as json, relayedAnswer, relayToOrigin } from "./door-core.js";
19
+ export * from "./door-core.js";
365
20
  /** The body, or how many bytes had arrived when it passed the limit; the rest is drained and dropped. */
366
21
  export function readBody(req, max) {
367
22
  return new Promise((resolve, reject) => {
@@ -381,324 +36,52 @@ export function readBody(req, max) {
381
36
  req.on("error", reject);
382
37
  });
383
38
  }
384
- /** A fetch body, or how many bytes had arrived when it passed the limit; the rest is not read. */
385
- export async function readStream(stream, max) {
386
- if (!stream)
387
- return { body: Buffer.alloc(0) };
388
- const reader = stream.getReader();
389
- const chunks = [];
390
- let size = 0;
391
- for (;;) {
392
- const { done, value } = await reader.read();
393
- if (done)
394
- return { body: Buffer.concat(chunks) };
395
- size += value.length;
396
- if (size > max) {
397
- await reader.cancel().catch(() => undefined);
398
- return { oversized: true, bytes: size };
399
- }
400
- chunks.push(value);
401
- }
402
- }
403
- /** The query as own properties: a parameter named `constructor` or `__proto__` is a parameter, never an inherited member or the prototype. */
404
- export function queryOf(url) {
405
- const pairs = new Map();
406
- for (const [k, v] of url.searchParams) {
407
- const prior = pairs.get(k);
408
- pairs.set(k, prior === undefined ? v : Array.isArray(prior) ? [...prior, v] : [prior, v]);
409
- }
410
- return Object.fromEntries(pairs);
411
- }
412
- /** Whether a failed fetch never left the door: a refused or unresolved connection. Anything else (a timeout, a reset) may have reached the origin. */
413
- function unreached(e) {
414
- const cause = e?.cause;
415
- if (!cause)
416
- return false;
417
- if (typeof cause.code === "string")
418
- return UNREACHED_CODES.has(cause.code);
419
- // fetch refuses a port on its blocked list before it connects
420
- if (cause.message === "bad port")
421
- return true;
422
- return Array.isArray(cause.errors) && cause.errors.length > 0 && cause.errors.every((x) => typeof x?.code === "string" && UNREACHED_CODES.has(x.code));
423
- }
424
- const json = (status, headers, body) => ({ status, headers: { "content-type": "application/json", "cache-control": "no-store", ...headers }, body: JSON.stringify(body) });
425
- /** The decision loop for a door config; `framework` is the receipt's `issuer.framework`. Throws when the config cannot be served. */
426
- export function createDoorCore(cfg, options, framework) {
39
+ /**
40
+ * The door's I/O from a config's files and the process environment: the key file, the trusted principal key files, the
41
+ * policy file re-read when it changes, the revocation file re-read when it changes, and receipts written by the file
42
+ * issuer to the receipts directory and the config's log.
43
+ */
44
+ export function nodeDoorIO(cfg, options = {}) {
427
45
  const key = loadPrivateKey(cfg.identity.keyFile);
428
- const trusted = cfg.trustedPrincipalKeys.map(loadPublicKey);
429
46
  const revocations = createRevocationList(cfg.revokedGrants);
430
47
  revocations.reload();
431
- const revoked = (chainDigests) => {
432
- try {
433
- revocations.reload();
434
- }
435
- catch (e) {
436
- // fail closed: a revocation list that cannot be read revokes every grant until it can
437
- return `the grant cannot be checked against the revocation list (${e instanceof Error ? e.message : String(e)})`;
438
- }
439
- if (!revocations.has(chainDigests))
440
- return null;
441
- return revocations.has(chainDigests.slice(0, 1)) ? "the grant has been revoked" : "a grant above it in its chain has been revoked";
442
- };
443
- const captureKey = cfg.captureKeyEnv ? captureKeyFrom(process.env[cfg.captureKeyEnv] ?? (() => { throw new Error(`capture key: environment variable ${cfg.captureKeyEnv} is not set`); })()) : undefined;
444
- for (const [route, rule] of Object.entries(cfg.capture ?? {})) {
445
- for (const side of [rule.args, rule.result, rule.facts])
446
- if (side?.mode === "encrypted" && !captureKey)
447
- throw new Error(`capture for ${route} uses mode encrypted, which needs captureKeyEnv`);
448
- }
449
- const f = options.fetch ?? fetch;
450
- const challengeSecret = cfg.challenge ? process.env[cfg.challenge.secretEnv] : undefined;
451
- if (cfg.challenge && !challengeSecret)
452
- throw new Error(`challenge: environment variable ${cfg.challenge.secretEnv} is not set`);
453
- const challengeHeader = cfg.challenge?.header.toLowerCase();
454
- let challengesInFlight = 0;
455
- const sink = options.log ?? openLog(cfg, key);
456
- // a route the config gives no rule falls to "*", and without a "*" rule of the config's own, to the door's default
457
- const rules = cfg.capture && Object.hasOwn(cfg.capture, "*") ? cfg.capture : { ...(cfg.capture ?? {}), "*": DOOR_DEFAULT_CAPTURE };
458
- const issuer = createIssuer(key, cfg.receiptsDir, sink, { exporter: options.exporter ?? openExporter(cfg), capture: { rules, key: captureKey } });
459
- const issuedBy = { kind: "door", keyid: issuer.keyid, version: DOOR_VERSION, framework };
460
- const precommit = new Set(cfg.precommit);
461
- const rates = createRateTracker();
462
- const webBotAuth = cfg.webBotAuth ? createWebBotAuthVerifier(cfg.webBotAuth, f) : undefined;
463
- const partner = cfg.partner ? createPartnerEngine(cfg.partner, f) : undefined;
464
- // The policy, re-read when the file changes, as the gateway does; a file that does not parse is refused and the
465
- // policy in force stays. The bytes and the metadata come from one open file.
466
- const readPolicy = () => {
467
- const fd = openSync(cfg.policyFile, "r");
468
- try {
469
- const st = fstatSync(fd);
470
- return { text: readFileSync(fd, "utf8"), key: `${st.ino}:${st.mtimeMs}:${st.ctimeMs}:${st.size}` };
471
- }
472
- finally {
473
- closeSync(fd);
474
- }
475
- };
476
- const first = readPolicy();
477
- const errors = policyParseErrors(first.text);
478
- if (errors.length)
479
- throw new Error(`policy ${cfg.policyFile} does not parse: ${errors.join("; ")}`);
480
- if (!hasPermitRule(first.text))
481
- console.error(`agent-custody door: ${cfg.policyFile} has no permit rule, so every arrival is refused`);
482
- let policyNow = { text: first.text, digest: policyDigest(first.text), key: first.key };
483
- const currentPolicy = () => {
484
- try {
485
- const next = readPolicy();
486
- if (next.key !== policyNow.key) {
487
- const problems = policyParseErrors(next.text);
488
- if (problems.length)
489
- console.error(`agent-custody door: POLICY NOT RELOADED: ${cfg.policyFile} ${problems.join("; ")}; policy ${policyNow.digest} stays in force`);
490
- else
491
- policyNow = { text: next.text, digest: policyDigest(next.text), key: next.key };
492
- }
493
- }
494
- catch (e) {
495
- console.error(`agent-custody door: cannot read ${cfg.policyFile}: ${e instanceof Error ? e.message : String(e)}; policy ${policyNow.digest} stays in force`);
496
- }
497
- return policyNow;
498
- };
499
- async function decide(req, receiptId, readArrivalBody, framework) {
500
- const timestamp = new Date().toISOString();
501
- const url = requestUrl(req);
502
- const method = (req.method ?? "GET").toUpperCase();
503
- // A path that does not decode cleanly is never relayed; it falls under the unmatched route for the receipt.
504
- const norm = normalizePath(url.pathname);
505
- const path = "path" in norm ? norm.path : url.pathname;
506
- const route = "path" in norm ? matchRoute(cfg.routes, cfg.unmatchedRoute, method, path) : cfg.unmatchedRoute;
507
- const signature = webBotAuth ? await webBotAuth.verify(signedRequestOf(req)) : undefined;
508
- const { arrival, delegation, signer } = classifyArrival(req, trusted, route, !!cfg.trustProxy, timestamp, signature, revoked);
509
- const checkedAgent = arrival.class === "verified";
510
- const by = checkedAgent ? "agent" : "remote";
511
- arrival.rate = { by, ...rates.hit(`${by}:${checkedAgent ? arrival.subject : arrival.remote}`) };
512
- if (cfg.challenge && challengeHeader) {
513
- const c = cfg.challenge;
514
- const token = req.headers[challengeHeader];
515
- if (typeof token !== "string" || !token.trim())
516
- arrival.challenge = { provider: c.provider, outcome: "absent" };
517
- // every arrival with a token waits on the provider, so the checks at once are bounded; past that, unavailable
518
- else if (challengesInFlight >= c.maxInFlight)
519
- arrival.challenge = { provider: c.provider, outcome: "unavailable", error: `${c.maxInFlight} challenge checks are already waiting on the provider` };
520
- else {
521
- challengesInFlight++;
522
- try {
523
- // without trustProxy the socket's address may be a proxy's, and the provider would refuse the client's token on it
524
- arrival.challenge = await verifyChallengeToken({ provider: c.provider, secret: challengeSecret, token: token.trim(), ...(cfg.trustProxy ? { remoteIp: arrival.remote } : {}), hostnames: c.hostnames, ...(c.action ? { action: c.action } : {}), siteKey: c.siteKey, timeoutMs: c.timeoutMs }, f);
525
- }
526
- finally {
527
- challengesInFlight--;
528
- }
529
- }
530
- }
531
- const { text: policyText, digest: pDigest } = currentPolicy();
532
- const read = readArrivalBody ? await readArrivalBody(cfg.maxBodyBytes) : null;
533
- const body = read === null ? Buffer.alloc(0) : "body" in read ? read.body : null;
534
- const headers = {};
535
- for (const name of RECORDED_HEADERS) {
536
- const v = req.headers[name];
537
- if (typeof v === "string")
538
- headers[name] = v;
539
- }
540
- // A verdict reaches the policy and the receipt only when its signature verified for this receipt and route. Without
541
- // one, onFailure "deny" refuses the arrival whatever the policy says, and "absent" leaves the policy without the fact.
542
- let verdict;
543
- let partnerRefusal;
544
- if (partner && cfg.partner && partner.applies(route)) {
545
- const asked = await partner.ask({ receiptId, route, method, path, remote: arrival.remote, class: arrival.class, headers });
546
- arrival.partner = asked.check;
547
- if (asked.verdict)
548
- verdict = { value: asked.verdict, signature: asked.signature };
549
- else if (cfg.partner.onFailure === "deny")
550
- partnerRefusal = `the partner engine ${cfg.partner.engine} gave no verified verdict (${asked.check.outcome}: ${asked.check.error ?? "no detail"}), and partner.onFailure is deny`;
551
- }
552
- const contentType = req.headers["content-type"] ?? "";
553
- let recordedBody;
554
- if (body && body.length > 0 && body.length <= RECORDED_BODY_BYTES && /^application\/json\b/i.test(contentType)) {
48
+ return {
49
+ key,
50
+ trustedPrincipalKeys: cfg.trustedPrincipalKeys.map(loadPublicKey),
51
+ // the bytes and the metadata come from one open file
52
+ readPolicy() {
53
+ const fd = openSync(cfg.policyFile, "r");
555
54
  try {
556
- recordedBody = JSON.parse(body.toString("utf8"));
55
+ const st = fstatSync(fd);
56
+ return { text: readFileSync(fd, "utf8"), key: `${st.ino}:${st.mtimeMs}:${st.ctimeMs}:${st.size}` };
557
57
  }
558
- catch {
559
- recordedBody = undefined;
58
+ finally {
59
+ closeSync(fd);
560
60
  }
561
- }
562
- // An oversized body is dropped before anything is decided: the receipt records how far it was read and that there
563
- // is no digest of it, rather than a digest of nothing.
564
- const args = {
565
- method,
566
- path,
567
- query: queryOf(url),
568
- headers,
569
- ...(recordedBody !== undefined ? { body: recordedBody } : {}),
570
- ...(read === null ? {} : body ? { bodyBytes: body.length, bodyDigest: sha256Hex(body) } : { bodyBytes: read.bytes, bodyOversized: true }),
571
- };
572
- const facts = {
573
- [ARRIVAL_FACT]: { tool: "door.arrival", args: {}, value: arrival, resultDigest: digestOf(arrival), provenance: "observed" },
574
- ...(verdict ? { [PARTNER_FACT]: { tool: PARTNER_TOOL, args: {}, value: verdict.value, resultDigest: digestOf(verdict.value), provenance: "attested", attestation: verdict.signature } } : {}),
575
- };
576
- // The Cedar principal is an agent the door checked: the one a verified grant names, or the signature agent of a
577
- // verified signature. A declared name, or the agent a rejected grant names, stays in the arrival fact as a claim, so
578
- // a permit on `principal == Agent::"x"` cannot be satisfied by sending a header.
579
- let policy;
580
- try {
581
- policy = evaluate(policyText, {
582
- agentId: checkedAgent ? arrival.subject : "unknown",
583
- tool: route,
584
- context: { args: cedarArgs(args), facts: { [ARRIVAL_FACT]: arrival, ...(verdict ? { [PARTNER_FACT]: verdict.value } : {}) }, ...(delegation ? { grant: { principal: delegation.grant.principal, scopes: delegation.grant.scopes } } : {}) },
585
- });
586
- }
587
- catch (e) {
588
- policy = { decision: "deny", reasons: [], errors: [String(e instanceof Error ? e.message : e)], policyDigest: pDigest };
589
- }
590
- if (cfg.mode === "observe")
591
- policy = { ...policy, enforced: false };
592
- const forward = policy.decision === "allow" || policy.enforced === false;
593
- const head = {
594
- receiptId,
595
- timestamp,
596
- issuer: framework ? { ...issuedBy, framework } : issuedBy,
597
- principal: delegation ? { id: delegation.grant.principal, keyid: delegation.principalKeyid, provenance: "attested" } : { id: null, provenance: "claimed" },
598
- // a signature alone is the door's own check against a directory it fetched, which a reader of the receipt cannot repeat
599
- agent: { id: arrival.subject, provenance: delegation ? "attested" : signer ? "observed" : "claimed" },
600
- ...(delegation ? { delegation: { envelope: delegation.envelope, provenance: "attested" } } : {}),
601
- tool: { name: route, provenance: "observed" },
602
- request: { args, argsDigest: digestOf(args), provenance: "claimed" },
603
- facts,
604
- policy: { ...policy, provenance: "observed" },
605
- };
606
- const decision = { receiptId, arrival, method, url, route, ...("relay" in norm ? { relay: norm.relay } : {}), body, head };
607
- // observe mode records the missing verdict in the arrival fact and relays, as it does a deny
608
- if (partnerRefusal && cfg.mode === "observe")
609
- console.error(`agent-custody door (observe mode): ${partnerRefusal}; not enforced, receipt ${receiptId}`);
610
- if (!forward) {
611
- decision.refused = { status: 403, execution: { status: "denied", reason: [...policy.reasons, ...policy.errors].join("; ") || "no permit policy matched", provenance: "observed" } };
612
- }
613
- else if (partnerRefusal && cfg.mode !== "observe") {
614
- decision.refused = { status: 503, execution: { status: "withheld", reason: `not relayed: ${partnerRefusal}`, provenance: "observed" } };
615
- }
616
- else if ("problem" in norm) {
617
- decision.refused = { status: 400, execution: { status: "withheld", reason: `the path was not relayed: ${norm.problem}`, provenance: "observed" } };
618
- }
619
- else if (body === null) {
620
- decision.refused = { status: 413, execution: { status: "withheld", reason: `the request body is larger than ${cfg.maxBodyBytes} bytes and was not relayed`, provenance: "observed" } };
621
- }
622
- else if (!SAFE_METHODS.has(method) || precommit.has("*") || precommit.has(route)) {
623
- // A request that can change something is committed to the log before it goes on, so that evidence of the side
624
- // effect exists before the side effect does. If the log will not take it, the request does not go on; in observe
625
- // mode it goes on and the missing authorization is printed.
61
+ },
62
+ policySource: cfg.policyFile,
63
+ revoked(chainDigests) {
626
64
  try {
627
- decision.authorization = await issuer.authorize(head);
65
+ revocations.reload();
628
66
  }
629
67
  catch (e) {
630
- if (cfg.mode === "observe")
631
- 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)}`);
632
- else
633
- 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" } };
68
+ // fail closed: a revocation list that cannot be read revokes every grant until it can
69
+ return `the grant cannot be checked against the revocation list (${e instanceof Error ? e.message : String(e)})`;
634
70
  }
635
- }
636
- return decision;
637
- }
638
- const mark = (d, logPending) => ({ [RECEIPT_HEADER]: d.receiptId, [CLASS_HEADER]: d.arrival.class, ...(logPending ? { "x-agent-custody-log-pending": "true" } : {}) });
639
- let inFlight = 0;
640
- let timer;
641
- if (options.autoFlush) {
642
- const flush = () => void issuer.flushOutbox().catch((e) => console.error(`agent-custody door: outbox flush failed: ${e instanceof Error ? e.message : String(e)}`));
643
- flush();
644
- timer = setInterval(flush, 30_000);
645
- timer.unref?.();
646
- }
647
- return {
648
- keyid: issuer.keyid,
649
- policyDigest: () => currentPolicy().digest,
650
- // Each arrival holds its body (up to maxBodyBytes) in memory until it is decided. Past maxInFlight arrivals at once,
651
- // the next is answered 503 before its body is read: it is not decided, passed on, or receipted.
652
- admit: () => (inFlight >= cfg.maxInFlight ? false : (inFlight += 1, true)),
653
- release: () => void (inFlight -= 1),
654
- busy: () => json(503, { "retry-after": "1" }, { error: `the door is handling ${cfg.maxInFlight} requests; this one was not read, decided, or relayed. Retry` }),
655
- decide,
656
- consumed: (name, req, arrival) => name === GRANT_HEADER || name === AGENT_HEADER || name === challengeHeader ||
657
- // the grant travelled in Authorization: it is the door's credential, not the origin's
658
- (name === "authorization" && arrival.grant !== "absent" && !req.headers[GRANT_HEADER]),
659
- async record(d, execution) {
660
- try {
661
- await issuer.issue({
662
- ...d.head,
663
- session: { id: null, toolUseId: null, provenance: "claimed" },
664
- model: { id: null, provenance: "claimed" },
665
- ...(d.authorization ? { authorization: d.authorization } : {}),
666
- execution,
667
- }, undefined, undefined, { deferLog: true });
668
- return { logPending: false };
669
- }
670
- catch (e) {
671
- if (e instanceof ReceiptPending) {
672
- console.error(`agent-custody door: ${e.message}`);
673
- return { logPending: true };
674
- }
675
- console.error(`agent-custody door: receipt ${d.receiptId} was not written: ${e instanceof Error ? e.message : String(e)}`);
71
+ if (!revocations.has(chainDigests))
676
72
  return null;
677
- }
678
- },
679
- mark,
680
- refusal(d, logPending) {
681
- const execution = d.refused.execution;
682
- // A refused arrival that could have passed a challenge is told how: the provider, the public site key, and the header
683
- if (execution.status === "denied")
684
- 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 } } : {}) });
685
- return json(d.refused.status, mark(d, logPending), { error: "not relayed", reason: execution.reason, receipt: d.receiptId });
686
- },
687
- unrecorded(d, execution, notSent) {
688
- // The decision was carried out and the receipt of it could not be written. The client is told what happened
689
- // rather than "not relayed", which would invite a retry of a refund that went through.
690
- 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";
691
- return json(500, { [CLASS_HEADER]: d.arrival.class }, { error: "the door could not record this request", outcome, receipt: d.receiptId });
692
- },
693
- flushOutbox: () => issuer.flushOutbox(),
694
- pendingReceipts: () => issuer.pending(),
695
- close() {
696
- if (timer)
697
- clearInterval(timer);
698
- rates.close();
73
+ return revocations.has(chainDigests.slice(0, 1)) ? "the grant has been revoked" : "a grant above it in its chain has been revoked";
699
74
  },
75
+ secret: (name) => process.env[name],
76
+ issuer: (capture) => createIssuer(key, cfg.receiptsDir, options.log ?? openLog(cfg, key), { exporter: options.exporter ?? openExporter(cfg), capture }),
77
+ fetch: options.fetch ?? fetch,
78
+ timers: true,
700
79
  };
701
80
  }
81
+ /** The decision loop for a door config, reading its files and the environment; `framework` is the receipt's `issuer.framework`. Throws when the config cannot be served. */
82
+ export function createDoorCore(cfg, options, framework) {
83
+ return createDoorCoreWith(cfg, nodeDoorIO(cfg, options), framework, { autoFlush: options.autoFlush });
84
+ }
702
85
  export const sendAnswer = (res, a) => {
703
86
  res.writeHead(a.status, a.headers);
704
87
  res.end(a.body);
@@ -717,11 +100,9 @@ export async function createDoorHost(cfg, options = {}) {
717
100
  throw new Error(`origin: environment variable ${variable} is not set`);
718
101
  originHeaders[header] = v;
719
102
  }
720
- const origin = new URL(originCfg.url);
721
- const originPath = origin.pathname.replace(/\/$/, "");
103
+ const target = { url: new URL(originCfg.url), headers: originHeaders, timeoutMs: originCfg.timeoutMs, proto: "http" };
722
104
  const f = options.fetch ?? fetch;
723
105
  const core = createDoorCore(cfg, options, "http");
724
- // Each arrival also holds the origin's answer (up to maxResponseBytes) in memory until it is answered.
725
106
  async function handle(req, res) {
726
107
  if (!core.admit()) {
727
108
  req.resume();
@@ -738,104 +119,13 @@ export async function createDoorHost(cfg, options = {}) {
738
119
  const receiptId = randomUUID();
739
120
  res.setHeader(RECEIPT_HEADER, receiptId);
740
121
  const d = await core.decide(req, receiptId, (max) => readBody(req, max));
741
- const { arrival, method, url } = d;
742
- let execution = d.refused?.execution;
743
- let answer;
744
- // set when the relay failed before the request left the door; any other relay failure leaves the outcome unknown
745
- let notSent = false;
746
- if (!execution) {
747
- let upstream;
748
- try {
749
- // The path is set on a copy of the origin's URL, never resolved against it: resolving `//evil.example/x` would
750
- // move the relay, with the origin's credentials, to another host.
751
- const target = new URL(origin);
752
- target.pathname = originPath + d.relay;
753
- target.search = url.search;
754
- const out = new Headers();
755
- for (const [name, value] of Object.entries(req.headers)) {
756
- // `expect` is the client's conversation with the door, which Node answered; fetch refuses to carry it
757
- if (value === undefined || HOP_BY_HOP.has(name) || name === "host" || name === "expect" || name === "accept-encoding" || core.consumed(name, req, arrival))
758
- continue;
759
- if (!cfg.trustProxy && (CLIENT_ADDRESS_HEADERS.has(name) || name.startsWith("x-forwarded-")))
760
- continue;
761
- out.set(name, Array.isArray(value) ? value.join(", ") : value);
762
- }
763
- out.set("accept-encoding", "identity");
764
- // Behind a trusted proxy the chain it sent is kept and the socket's address appended, as any proxy does; otherwise
765
- // whatever the client wrote in these headers is replaced.
766
- const inbound = (name) => (cfg.trustProxy ? (Array.isArray(req.headers[name]) ? req.headers[name].join(", ") : req.headers[name]) : undefined);
767
- const socketAddress = req.socket.remoteAddress ?? "unknown";
768
- const chain = inbound("x-forwarded-for");
769
- out.set("x-forwarded-for", chain ? `${chain}, ${socketAddress}` : socketAddress);
770
- out.set("x-forwarded-host", inbound("x-forwarded-host") || req.headers.host || "");
771
- out.set("x-forwarded-proto", inbound("x-forwarded-proto") || "http");
772
- if (!cfg.trustProxy)
773
- out.set("x-real-ip", socketAddress);
774
- out.set(RECEIPT_HEADER, receiptId);
775
- out.set(CLASS_HEADER, arrival.class);
776
- for (const [h, v] of Object.entries(originHeaders))
777
- out.set(h, v);
778
- upstream = await f(target, { method, headers: out, ...(method === "GET" || method === "HEAD" ? {} : { body: new Uint8Array(d.body) }), redirect: "manual", signal: AbortSignal.timeout(originCfg.timeoutMs) });
779
- const got = await readStream(upstream.body, cfg.maxResponseBytes);
780
- const back = {};
781
- upstream.headers.forEach((v, k) => { if (!HOP_BY_HOP.has(k) && k !== "content-length" && k !== "content-encoding" && k !== "set-cookie")
782
- back[k] = v; });
783
- // every cookie the origin set, not the last one: `forEach` gives them one at a time under the same name
784
- const cookies = upstream.headers.getSetCookie();
785
- if (cookies.length)
786
- back["set-cookie"] = cookies;
787
- // A redirect to the origin's own host would take the client's next request around the door: it is rewritten to a
788
- // path on the door, which the client follows back through it, whatever the scheme or port. A path under the
789
- // origin's path loses that prefix; any other path, including one the parser normalised out of it (`/shop/../admin`),
790
- // is kept as it is, so the request still arrives at the door and meets its route and policy there.
791
- if (typeof back.location === "string") {
792
- try {
793
- const loc = new URL(back.location, target);
794
- if (loc.hostname === origin.hostname) {
795
- const inside = loc.pathname === originPath || loc.pathname.startsWith(`${originPath}/`);
796
- back.location = (inside ? loc.pathname.slice(originPath.length) || "/" : loc.pathname) + loc.search + loc.hash;
797
- }
798
- }
799
- catch { /* not a URL: relayed as the origin sent it */ }
800
- }
801
- const contentType = typeof back["content-type"] === "string" ? { contentType: back["content-type"] } : {};
802
- // The origin has answered either way, so the request happened: a response too large to relay is still recorded
803
- // as executed, by its size, so that nobody retries a refund on the strength of the 502 the client gets.
804
- const result = "body" in got
805
- ? { status: upstream.status, ...contentType, bodyBytes: got.body.length, bodyDigest: sha256Hex(got.body) }
806
- : { status: upstream.status, ...contentType, bodyBytes: got.bytes, bodyOversized: true };
807
- if ("body" in got)
808
- answer = { status: upstream.status, headers: back, body: got.body };
809
- execution = { status: upstream.status >= 500 ? "failed" : "executed", result, resultDigest: digestOf(result), provenance: "observed" };
810
- }
811
- catch (e) {
812
- // The request may have reached the origin unless the connection was refused or the host did not resolve: a
813
- // timeout while the origin works, a reset, or a body that stops after the headers all leave the outcome unknown,
814
- // and the client is told not to retry rather than that the origin could not be reached.
815
- const message = String(e instanceof Error ? e.message : e);
816
- notSent = !upstream && unreached(e);
817
- 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" };
818
- }
819
- }
820
- const recorded = await core.record(d, execution);
122
+ const relayed = await relayToOrigin(core, cfg, d, req, target, f);
123
+ const recorded = await core.record(d, relayed.execution);
821
124
  if (!recorded)
822
- return sendAnswer(res, core.unrecorded(d, execution, notSent));
823
- const mark = core.mark(d, recorded.logPending);
824
- switch (execution.status) {
825
- case "denied":
826
- case "withheld":
827
- return sendAnswer(res, core.refusal(d, recorded.logPending));
828
- case "error":
829
- return sendAnswer(res, notSent
830
- ? json(502, mark, { error: "the origin could not be reached", detail: execution.error, receipt: receiptId })
831
- : 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 }));
832
- default: {
833
- if (!answer)
834
- 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 }));
835
- res.writeHead(answer.status, { ...answer.headers, ...mark });
836
- res.end(answer.body);
837
- }
838
- }
125
+ return sendAnswer(res, core.unrecorded(d, relayed.execution, relayed.notSent));
126
+ const answer = relayedAnswer(core, cfg, d, relayed, recorded.logPending);
127
+ res.writeHead(answer.status, answer.headers);
128
+ res.end(answer.body);
839
129
  }
840
130
  return {
841
131
  keyid: core.keyid,