@agent-custody/receipts 0.16.6 → 0.16.8

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 (45) hide show
  1. package/README.md +24 -9
  2. package/dist/capture.d.ts +2 -0
  3. package/dist/capture.js +13 -2
  4. package/dist/check.d.ts +1 -1
  5. package/dist/check.js +34 -10
  6. package/dist/cli.js +34 -3
  7. package/dist/config.d.ts +32 -2
  8. package/dist/config.js +68 -4
  9. package/dist/door-app.d.ts +28 -0
  10. package/dist/door-app.js +244 -0
  11. package/dist/door-partner.d.ts +66 -0
  12. package/dist/door-partner.js +94 -0
  13. package/dist/door.d.ts +139 -10
  14. package/dist/door.js +297 -137
  15. package/dist/gateway-http.d.ts +1 -1
  16. package/dist/index.d.ts +4 -2
  17. package/dist/index.js +2 -1
  18. package/dist/perathos.js +3 -2
  19. package/dist/policy.d.ts +11 -0
  20. package/dist/policy.js +41 -1
  21. package/dist/receipt.d.ts +4 -1
  22. package/dist/refunds-init.d.ts +37 -0
  23. package/dist/refunds-init.js +193 -0
  24. package/dist/rest.d.ts +2 -0
  25. package/dist/rest.js +18 -2
  26. package/dist/verify.js +44 -4
  27. package/dist/web-bot-auth.d.ts +105 -0
  28. package/dist/web-bot-auth.js +508 -0
  29. package/docs/door-languages.md +168 -0
  30. package/docs/door-middleware.md +216 -0
  31. package/docs/door-quickstart.md +1 -1
  32. package/docs/door-signals.md +42 -5
  33. package/docs/door.md +124 -15
  34. package/docs/egress.md +2 -0
  35. package/docs/github-action.md +2 -2
  36. package/docs/perathos.md +13 -10
  37. package/docs/policies.md +1 -1
  38. package/docs/sdk.md +11 -0
  39. package/docs/tutorials.md +5 -0
  40. package/docs/usage.md +5 -5
  41. package/docs/verification.md +2 -0
  42. package/package.json +7 -1
  43. package/vectors/audit.json +27 -27
  44. package/vectors/canonical.json +5 -5
  45. package/vectors/receipts.json +1701 -1210
@@ -0,0 +1,244 @@
1
+ // The door in-process: the same decision loop as the proxy, run inside a Node site instead of in front of it. Express
2
+ // (or any Connect-style server) takes it as middleware, `app.use(door("door.json"))`; a fetch-style route handler, as
3
+ // Next.js App Router routes are, takes it as a wrapper, `export const POST = guard.route(handler)`. Neither framework is
4
+ // imported: the middleware is typed on `node:http` and the wrapper on the fetch `Request` and `Response`, so the receipts
5
+ // package depends on neither and works with any version that hands it those.
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import { Readable } from "node:stream";
8
+ import { loadDoorConfig } from "./config.js";
9
+ import { digestOf } from "./crypto.js";
10
+ import { CLASS_HEADER, RECEIPT_HEADER, createDoorCore, readBody, readStream, sendAnswer } from "./door.js";
11
+ /** The receipt's `issuer.framework` for an arrival the middleware decided */
12
+ export const MIDDLEWARE_FRAMEWORK = "node-middleware";
13
+ /** The receipt's `issuer.framework` for an arrival a wrapped route handler decided */
14
+ export const ROUTE_FRAMEWORK = "fetch-route";
15
+ /** What a passed request's receipt records of the app's answer: its status, its content type, and the bytes the app wrote, by size and digest. */
16
+ function answered(status, contentType, bytes, digest) {
17
+ const result = { status, ...(typeof contentType === "string" ? { contentType } : {}), bodyBytes: bytes, bodyDigest: digest };
18
+ return { status: status >= 500 ? "failed" : "executed", result, resultDigest: digestOf(result), provenance: "observed" };
19
+ }
20
+ const mayHaveActed = (what) => ({ status: "error", error: `${what}; the app may have acted on the request`, provenance: "observed" });
21
+ /**
22
+ * Makes a request whose body the door read readable again, so that what runs after the door (`express.json()`, a
23
+ * multipart parser, `for await (const chunk of req)`) reads the bytes the door decided on. Only the members that read
24
+ * the body move to the copy; every other event, `close` and `aborted` among them, stays on the request.
25
+ */
26
+ function replayBody(req, body) {
27
+ const copy = Readable.from(body.length ? [body] : []);
28
+ const flow = new Set(["data", "end", "readable", "pause", "resume"]);
29
+ const target = req;
30
+ for (const name of ["on", "addListener", "once", "prependListener", "prependOnceListener", "removeListener", "off"]) {
31
+ const own = req[name].bind(req);
32
+ const moved = copy[name].bind(copy);
33
+ target[name] = (event, listener) => {
34
+ (flow.has(event) ? moved : own)(event, listener);
35
+ return req;
36
+ };
37
+ }
38
+ for (const name of ["read", "pipe", "unpipe", "pause", "resume", "isPaused", "setEncoding"]) {
39
+ const fn = copy[name].bind(copy);
40
+ target[name] = (...a) => {
41
+ const r = fn(...a);
42
+ return r === copy ? req : r;
43
+ };
44
+ }
45
+ target[Symbol.asyncIterator] = () => copy[Symbol.asyncIterator]();
46
+ Object.defineProperty(req, "readable", { configurable: true, get: () => copy.readable });
47
+ Object.defineProperty(req, "readableEnded", { configurable: true, get: () => copy.readableEnded });
48
+ }
49
+ /** The request as the app receives it: the door's credentials gone, the receipt id and the class set, in `headers` and `rawHeaders` alike. */
50
+ function passHeaders(core, req, arrival, receiptId) {
51
+ const gone = new Set(Object.keys(req.headers).filter((name) => core.consumed(name, req, arrival)));
52
+ gone.add(RECEIPT_HEADER).add(CLASS_HEADER);
53
+ for (const name of gone)
54
+ delete req.headers[name];
55
+ req.headers[RECEIPT_HEADER] = receiptId;
56
+ req.headers[CLASS_HEADER] = arrival.class;
57
+ const raw = [];
58
+ for (let i = 0; i + 1 < req.rawHeaders.length; i += 2)
59
+ if (!gone.has(req.rawHeaders[i].toLowerCase()))
60
+ raw.push(req.rawHeaders[i], req.rawHeaders[i + 1]);
61
+ raw.push(RECEIPT_HEADER, receiptId, CLASS_HEADER, arrival.class);
62
+ req.rawHeaders = raw;
63
+ // Node builds headersDistinct from rawHeaders with the parser's original count, which no longer matches raw.
64
+ const distinct = {};
65
+ for (let i = 0; i + 1 < raw.length; i += 2)
66
+ (distinct[raw[i].toLowerCase()] ??= []).push(raw[i + 1]);
67
+ Object.defineProperty(req, "headersDistinct", { configurable: true, enumerable: true, value: distinct });
68
+ }
69
+ /** Hashes every byte the app writes, as it writes it; the answer streams as it would without the door. */
70
+ function watchAnswer(res) {
71
+ const hash = createHash("sha256");
72
+ let bytes = 0;
73
+ const see = (chunk, encoding) => {
74
+ if (chunk === undefined || chunk === null || typeof chunk === "function")
75
+ return;
76
+ const b = typeof chunk === "string" ? Buffer.from(chunk, typeof encoding === "string" ? encoding : "utf8") : Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
77
+ hash.update(b);
78
+ bytes += b.length;
79
+ };
80
+ const write = res.write;
81
+ const end = res.end;
82
+ res.write = function (chunk, ...rest) {
83
+ see(chunk, rest[0]);
84
+ return write.call(this, chunk, ...rest);
85
+ };
86
+ res.end = function (chunk, ...rest) {
87
+ see(chunk, rest[0]);
88
+ return end.call(this, chunk, ...rest);
89
+ };
90
+ return () => ({ bytes, digest: hash.digest("hex") });
91
+ }
92
+ /**
93
+ * The fetch request as the door reads it. Without a socket the address is the proxy's `X-Forwarded-For` under
94
+ * `trustProxy`, else `unknown`. Without a `Host` field (a `Request` built in code) the authority is the URL's.
95
+ */
96
+ function fetchRequest(request) {
97
+ const url = new URL(request.url);
98
+ const headers = { host: url.host };
99
+ request.headers.forEach((v, k) => { headers[k] = v; });
100
+ return { method: request.method, url: url.pathname + url.search, headers, socket: {} };
101
+ }
102
+ const toResponse = (a) => new Response(a.body, { status: a.status, headers: a.headers });
103
+ /**
104
+ * The door in-process, from a door config without `origin` (a path, read with `loadDoorConfig`, or a config already
105
+ * loaded). Throws at once on a config the door cannot serve: a missing key, a policy that does not parse, an `origin`, `authz`.
106
+ */
107
+ export function door(config, options = {}) {
108
+ const cfg = typeof config === "string" ? loadDoorConfig(config) : config;
109
+ if (cfg.origin)
110
+ throw new Error("the in-process door passes an allowed request to the app it runs in, so its config names no origin; origin.url is for the door proxy (`agent-custody door`)");
111
+ if (cfg.authz)
112
+ throw new Error("the in-process door passes an allowed request to the app it runs in; authz is for the door answering nginx or Envoy checks (`agent-custody door`)");
113
+ const core = createDoorCore(cfg, { ...options, autoFlush: options.autoFlush ?? true }, MIDDLEWARE_FRAMEWORK);
114
+ const middleware = (req, res, next) => {
115
+ if (!core.admit()) {
116
+ req.resume();
117
+ return sendAnswer(res, core.busy());
118
+ }
119
+ let released = false;
120
+ const release = () => {
121
+ if (!released)
122
+ core.release();
123
+ released = true;
124
+ };
125
+ const receiptId = randomUUID();
126
+ res.setHeader(RECEIPT_HEADER, receiptId);
127
+ void (async () => {
128
+ const d = await core.decide(req, receiptId, (max) => readBody(req, max), MIDDLEWARE_FRAMEWORK);
129
+ if (d.refused) {
130
+ const recorded = await core.record(d, d.refused.execution);
131
+ sendAnswer(res, recorded ? core.refusal(d, recorded.logPending) : core.unrecorded(d, d.refused.execution, false));
132
+ return release();
133
+ }
134
+ // The receipt of a passed request is written once the app has answered, so the answer cannot say whether the log
135
+ // took it: there is no X-Agent-Custody-Log-Pending here, and the outbox holds what the log did not take.
136
+ for (const [h, v] of Object.entries(core.mark(d, false)))
137
+ res.setHeader(h, v);
138
+ passHeaders(core, req, d.arrival, receiptId);
139
+ replayBody(req, d.body);
140
+ const seen = watchAnswer(res);
141
+ let settled = false;
142
+ const settle = (finished) => {
143
+ if (settled)
144
+ return;
145
+ settled = true;
146
+ const { bytes, digest } = seen();
147
+ const execution = finished ? answered(res.statusCode, res.getHeader("content-type"), bytes, digest) : mayHaveActed(`the connection closed before the app finished its answer${res.headersSent ? ` (it had sent ${res.statusCode})` : ""}`);
148
+ void core.record(d, execution).finally(release);
149
+ };
150
+ res.once("finish", () => settle(true));
151
+ res.once("close", () => settle(res.writableFinished));
152
+ next();
153
+ })().catch((e) => {
154
+ release();
155
+ next(e);
156
+ });
157
+ };
158
+ const route = (handler) => async (request, ...rest) => {
159
+ if (!core.admit()) {
160
+ await request.body?.cancel().catch(() => undefined);
161
+ return toResponse(core.busy());
162
+ }
163
+ let release = true;
164
+ try {
165
+ const receiptId = randomUUID();
166
+ const seen = fetchRequest(request);
167
+ // The door reads a copy of the body; the handler reads the request itself, as it would without the door.
168
+ const copy = request.clone();
169
+ const d = await core.decide(seen, receiptId, (max) => readStream(copy.body, max), ROUTE_FRAMEWORK);
170
+ if (d.refused) {
171
+ await request.body?.cancel().catch(() => undefined);
172
+ const recorded = await core.record(d, d.refused.execution);
173
+ return toResponse(recorded ? core.refusal(d, recorded.logPending) : core.unrecorded(d, d.refused.execution, false));
174
+ }
175
+ const passed = new Headers(request.headers);
176
+ for (const name of Object.keys(seen.headers))
177
+ if (core.consumed(name, seen, d.arrival))
178
+ passed.delete(name);
179
+ passed.set(RECEIPT_HEADER, receiptId);
180
+ passed.set(CLASS_HEADER, d.arrival.class);
181
+ // The request the framework made keeps its own type (a NextRequest's `nextUrl`, `cookies`); its headers are
182
+ // changed in place. A framework that seals them gets a plain Request with the same body in its place.
183
+ let onward = request;
184
+ try {
185
+ for (const name of [...request.headers.keys()])
186
+ if (!passed.has(name))
187
+ request.headers.delete(name);
188
+ passed.forEach((v, k) => request.headers.set(k, v));
189
+ }
190
+ catch {
191
+ onward = new Request(request, { headers: passed });
192
+ }
193
+ let response;
194
+ try {
195
+ response = await handler(onward, ...rest);
196
+ }
197
+ catch (e) {
198
+ await core.record(d, mayHaveActed(`the handler threw: ${e instanceof Error ? e.message : String(e)}`));
199
+ throw e;
200
+ }
201
+ const headers = new Headers(response.headers);
202
+ for (const [h, v] of Object.entries(core.mark(d, false)))
203
+ headers.set(h, v);
204
+ const contentType = response.headers.get("content-type") ?? undefined;
205
+ if (!response.body) {
206
+ await core.record(d, answered(response.status, contentType, 0, createHash("sha256").digest("hex")));
207
+ return new Response(null, { status: response.status, statusText: response.statusText, headers });
208
+ }
209
+ // The answer streams to the client while a second branch of it is hashed; the receipt is written when the app's
210
+ // body has ended, or records that it did not.
211
+ const [toClient, toDigest] = response.body.tee();
212
+ release = false;
213
+ void (async () => {
214
+ const hash = createHash("sha256");
215
+ let bytes = 0;
216
+ let execution;
217
+ try {
218
+ for await (const chunk of toDigest) {
219
+ hash.update(chunk);
220
+ bytes += chunk.length;
221
+ }
222
+ execution = answered(response.status, contentType, bytes, hash.digest("hex"));
223
+ }
224
+ catch (e) {
225
+ execution = mayHaveActed(`the app's answer (${response.status}) stopped after ${bytes} bytes: ${e instanceof Error ? e.message : String(e)}`);
226
+ }
227
+ await core.record(d, execution);
228
+ })().finally(() => core.release());
229
+ return new Response(toClient, { status: response.status, statusText: response.statusText, headers });
230
+ }
231
+ finally {
232
+ if (release)
233
+ core.release();
234
+ }
235
+ };
236
+ return Object.assign(middleware, {
237
+ route,
238
+ keyid: core.keyid,
239
+ policyDigest: core.policyDigest,
240
+ flushOutbox: core.flushOutbox,
241
+ pendingReceipts: core.pendingReceipts,
242
+ close: core.close,
243
+ });
244
+ }
@@ -0,0 +1,66 @@
1
+ import type { DoorConfig } from "./config.ts";
2
+ import { type Envelope, type KeyPair, type PublicKeyRef } from "./crypto.ts";
3
+ /** the fact a verified verdict is recorded as, and the policy reads as `context.facts.partner` */
4
+ export declare const PARTNER_FACT = "partner";
5
+ export declare const PARTNER_TOOL = "door.partner";
6
+ export type PartnerConfig = NonNullable<DoorConfig["partner"]>;
7
+ /** What the engine signs: its name, its verdict, and a score when it gives one. An integer, since Cedar has no floats. */
8
+ export interface PartnerVerdict {
9
+ engine: string;
10
+ verdict: string;
11
+ score?: number;
12
+ }
13
+ /**
14
+ * What became of the question, in the arrival fact. `verified`: the verdict's signature verified under the configured
15
+ * key and binds this receipt and route. `rejected`: the engine answered, and the answer was not a verdict signed for this
16
+ * arrival. `unavailable`: no answer in time, an error status, a redirect, or too many questions already waiting.
17
+ */
18
+ export interface ArrivalPartner {
19
+ engine: string;
20
+ outcome: "verified" | "rejected" | "unavailable";
21
+ error?: string;
22
+ }
23
+ /** What the door tells the engine about an arrival. Never the query, the body, the grant, or a cookie. */
24
+ export interface PartnerQuestion {
25
+ receiptId: string;
26
+ route: string;
27
+ method: string;
28
+ path: string;
29
+ remote: string;
30
+ class: string;
31
+ /** the request headers a door receipt records: user-agent, content-type, accept, host */
32
+ headers: Record<string, string>;
33
+ }
34
+ /** The engine's answer: the verdict and its signature. */
35
+ export interface PartnerAnswer {
36
+ verdict: PartnerVerdict;
37
+ signature: Envelope;
38
+ }
39
+ export type PartnerResult = {
40
+ check: ArrivalPartner;
41
+ verdict?: undefined;
42
+ } | {
43
+ check: ArrivalPartner & {
44
+ outcome: "verified";
45
+ };
46
+ verdict: PartnerVerdict;
47
+ signature: Envelope;
48
+ };
49
+ /** For engines and their adapters: the signature over a verdict for the receipt and route the door named. */
50
+ export declare function signVerdict(verdict: PartnerVerdict, key: KeyPair, receiptId: string, route: string): Envelope;
51
+ /**
52
+ * Checks an engine's answer for one arrival: a verdict of the configured engine, signed under `key` for this receipt
53
+ * and route, in exactly the plain attestation form (so the receipt can carry the envelope in clear beside the verdict).
54
+ */
55
+ export declare function checkPartnerAnswer(answer: unknown, key: PublicKeyRef, expected: {
56
+ engine: string;
57
+ receiptId: string;
58
+ route: string;
59
+ }): PartnerResult;
60
+ export interface PartnerEngine {
61
+ /** whether arrivals on this route are asked about */
62
+ applies(route: string): boolean;
63
+ ask(question: PartnerQuestion): Promise<PartnerResult>;
64
+ }
65
+ /** The engine as the door config names it. Every question carries `AbortSignal.timeout`, follows no redirect, and reads at most `maxResponseBytes`. */
66
+ export declare function createPartnerEngine(cfg: PartnerConfig, f: typeof fetch): PartnerEngine;
@@ -0,0 +1,94 @@
1
+ import { isPlainEnvelope } from "./capture.js";
2
+ import { digestOf, dsseSign, loadPublicKey } from "./crypto.js";
3
+ import { checkUpstream, UPSTREAM_TYPE } from "./upstream.js";
4
+ import { readCapped } from "./web-bot-auth.js";
5
+ /** the fact a verified verdict is recorded as, and the policy reads as `context.facts.partner` */
6
+ export const PARTNER_FACT = "partner";
7
+ export const PARTNER_TOOL = "door.partner";
8
+ /** For engines and their adapters: the signature over a verdict for the receipt and route the door named. */
9
+ export function signVerdict(verdict, key, receiptId, route) {
10
+ const payload = { receiptId, tool: route, contentDigest: digestOf(verdict) };
11
+ return dsseSign(UPSTREAM_TYPE, payload, key);
12
+ }
13
+ const VERDICT = /^[A-Za-z0-9_.:-]{1,64}$/;
14
+ const isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
15
+ /** The verdict as the door records it, or why it is not one: exactly engine, verdict, and an optional integer score. */
16
+ function verdictOf(v, engine) {
17
+ if (!isObject(v))
18
+ return "the answer carries no verdict object";
19
+ if (Object.keys(v).some((k) => k !== "engine" && k !== "verdict" && k !== "score"))
20
+ return "the verdict carries fields other than engine, verdict, and score";
21
+ if (v.engine !== engine)
22
+ return `the verdict does not name engine ${engine}`;
23
+ if (typeof v.verdict !== "string" || !VERDICT.test(v.verdict))
24
+ return "the verdict is not a short word (letters, digits, _ . : -, at most 64)";
25
+ if (v.score !== undefined && !Number.isSafeInteger(v.score))
26
+ return "the score is not an integer";
27
+ return { engine, verdict: v.verdict, ...(v.score !== undefined ? { score: v.score } : {}) };
28
+ }
29
+ /**
30
+ * Checks an engine's answer for one arrival: a verdict of the configured engine, signed under `key` for this receipt
31
+ * and route, in exactly the plain attestation form (so the receipt can carry the envelope in clear beside the verdict).
32
+ */
33
+ export function checkPartnerAnswer(answer, key, expected) {
34
+ const { engine } = expected;
35
+ const rejected = (error) => ({ check: { engine, outcome: "rejected", error } });
36
+ if (!isObject(answer))
37
+ return rejected("the answer is not an object with a verdict and a signature");
38
+ const verdict = verdictOf(answer.verdict, engine);
39
+ if (typeof verdict === "string")
40
+ return rejected(verdict);
41
+ const digest = digestOf(verdict);
42
+ const signature = answer.signature;
43
+ const signed = checkUpstream(signature, [key], { receiptId: expected.receiptId, tool: expected.route, contentDigest: digest });
44
+ if (!signed.ok)
45
+ return rejected(`the verdict's signature does not hold: ${signed.error}`);
46
+ if (!isPlainEnvelope(signature, expected.receiptId, expected.route, digest))
47
+ return rejected("the signature envelope carries more than the attestation of this verdict");
48
+ return { check: { engine, outcome: "verified" }, verdict, signature };
49
+ }
50
+ /** The engine as the door config names it. Every question carries `AbortSignal.timeout`, follows no redirect, and reads at most `maxResponseBytes`. */
51
+ export function createPartnerEngine(cfg, f) {
52
+ const key = loadPublicKey(cfg.keyFile);
53
+ const all = cfg.routes.includes("*");
54
+ const routes = new Set(cfg.routes);
55
+ const { engine } = cfg;
56
+ const unavailable = (error) => ({ check: { engine, outcome: "unavailable", error } });
57
+ let inFlight = 0;
58
+ return {
59
+ applies: (route) => all || routes.has(route),
60
+ async ask(question) {
61
+ // every asked arrival waits on the engine, so the questions at once are bounded; past that, no verdict
62
+ if (inFlight >= cfg.maxInFlight)
63
+ return unavailable(`${cfg.maxInFlight} questions are already waiting on the engine`);
64
+ inFlight++;
65
+ try {
66
+ let body;
67
+ try {
68
+ const res = await f(cfg.url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify(question), redirect: "manual", signal: AbortSignal.timeout(cfg.timeoutMs) });
69
+ if (res.status >= 300 && res.status < 400)
70
+ return unavailable(`the engine answered a redirect (${res.status}), which the door does not follow`);
71
+ if (!res.ok)
72
+ return unavailable(`the engine answered ${res.status}`);
73
+ body = await readCapped(res, cfg.maxResponseBytes);
74
+ }
75
+ catch (e) {
76
+ return unavailable(`the engine did not answer: ${e instanceof Error ? e.message : String(e)}`);
77
+ }
78
+ if (body === null)
79
+ return { check: { engine, outcome: "rejected", error: `the answer is larger than ${cfg.maxResponseBytes} bytes` } };
80
+ let answer;
81
+ try {
82
+ answer = JSON.parse(body.toString("utf8"));
83
+ }
84
+ catch {
85
+ return { check: { engine, outcome: "rejected", error: "the answer is not JSON" } };
86
+ }
87
+ return checkPartnerAnswer(answer, key, { engine, receiptId: question.receiptId, route: question.route });
88
+ }
89
+ finally {
90
+ inFlight--;
91
+ }
92
+ },
93
+ };
94
+ }
package/dist/door.d.ts CHANGED
@@ -1,10 +1,13 @@
1
- import { type IncomingMessage, type ServerResponse } from "node:http";
1
+ import { type IncomingHttpHeaders, type IncomingMessage, type ServerResponse } from "node:http";
2
2
  import type { DoorConfig, DoorRouteConfig } from "./config.ts";
3
3
  import { type Envelope, type PublicKeyRef } from "./crypto.ts";
4
4
  import { type Delegation } from "./delegation.ts";
5
5
  import { type FlushResult } from "./issue.ts";
6
+ import { type SignatureCheck, type SignedRequest } from "./web-bot-auth.ts";
7
+ import { type ArrivalPartner } from "./door-partner.ts";
6
8
  import { type LogSink } from "./log-sink.ts";
7
9
  import { type ReceiptExporter } from "./otel.ts";
10
+ import type { AuthorizationBundle, ReceiptPredicate } from "./receipt.ts";
8
11
  export declare const DOOR_VERSION = "0.1.0";
9
12
  /** on every answer the door gives: the receipt that records the decision */
10
13
  export declare const RECEIPT_HEADER = "x-agent-custody-receipt";
@@ -14,17 +17,31 @@ export declare const CLASS_HEADER = "x-agent-custody-class";
14
17
  export declare const ARRIVAL_FACT = "arrival";
15
18
  /** the header an agent may use to name itself without a grant; recorded as claimed, never checked */
16
19
  export declare const AGENT_HEADER = "x-agent-custody-agent";
20
+ /** in authz mode: the original request's method and target, as nginx `auth_request` and Envoy `ext_authz` are configured to send them */
21
+ export declare const ORIGINAL_METHOD_HEADER = "x-original-method";
22
+ export declare const ORIGINAL_URI_HEADER = "x-original-uri";
23
+ /** the reason an allowed authz receipt carries: the door decided, and the proxy, not the door, relays */
24
+ export declare 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";
17
25
  export type ArrivalClass = "verified" | "claimed" | "unknown";
18
26
  /** What the door observed about one arrival. Every field is the door's own observation; none is the caller's claim about itself except `declared`, which says so. */
19
27
  export interface Arrival {
20
28
  class: ArrivalClass;
21
- /** the agent named in a verified grant, else the name the caller declared, else "unknown" */
29
+ /** the agent named in a verified grant, else the signature agent of a verified signature, else the name the caller declared, else "unknown" */
22
30
  subject: string;
23
- /** what became of the grant header: a trusted grant in scope for this route, one out of scope, one that did not verify, or none */
24
- grant: "verified" | "out-of-scope" | "invalid" | "absent";
31
+ /**
32
+ * What became of the grant header: a trusted grant in scope for this route, one out of scope, one that did not verify,
33
+ * one presented by another agent (`wrong-sender`: the request is signed by a signature agent the grant does not name),
34
+ * or none.
35
+ */
36
+ grant: "verified" | "out-of-scope" | "invalid" | "wrong-sender" | "absent";
25
37
  grantError?: string;
26
- /** an RFC 9421 `Signature-Input` header was present; the door does not check it yet */
27
- signature: boolean;
38
+ /** What became of an RFC 9421 signature tagged `web-bot-auth`: see `SignatureCheck`. `unchecked` when the door has no `webBotAuth` config */
39
+ signature: SignatureCheck["outcome"];
40
+ /** the `Signature-Agent` origin; checked only when `signature` is `verified` */
41
+ signatureAgent?: string;
42
+ /** the signature's keyid, the RFC 7638 thumbprint of the agent's key; checked only when `signature` is `verified` */
43
+ signatureKeyid?: string;
44
+ signatureError?: string;
28
45
  /** the agent name from the `x-agent-custody-agent` header, when sent; a claim */
29
46
  declared?: string;
30
47
  remote: string;
@@ -35,6 +52,8 @@ export interface Arrival {
35
52
  rate?: ArrivalRate;
36
53
  /** what became of the challenge token, when the door is configured to challenge; absent otherwise, and from `classifyArrival` alone */
37
54
  challenge?: ArrivalChallenge;
55
+ /** what became of the question to the partner engine, when the door asks one about this route; absent otherwise, and from `classifyArrival` alone. The verdict itself is the `partner` fact, present only when `outcome` is `verified` */
56
+ partner?: ArrivalPartner;
38
57
  }
39
58
  /**
40
59
  * The outcome of a human challenge. `passed`: the provider confirmed the token, so the provider judged a person present
@@ -111,12 +130,17 @@ export interface RateTracker {
111
130
  export declare function createRateTracker(now?: () => number, limits?: RateTrackerLimits): RateTracker;
112
131
  export interface Classified {
113
132
  arrival: Arrival;
114
- /** set when the arrival is verified: the grant, as presented */
133
+ /** set when the arrival is verified by a grant: the grant, as presented */
115
134
  delegation?: {
116
135
  envelope: Envelope;
117
136
  grant: Delegation;
118
137
  principalKeyid: string;
119
138
  };
139
+ /** set when a verified signature names the arrival's agent: alone, or bound to the grant that names the same agent */
140
+ signer?: {
141
+ agent: string;
142
+ keyid: string;
143
+ };
120
144
  }
121
145
  /**
122
146
  * The record of the call keeps what arrived; the policy reads a copy Cedar accepts. Cedar has no `null` and no
@@ -156,20 +180,49 @@ export declare function normalizePath(pathname: string): {
156
180
  } | {
157
181
  problem: string;
158
182
  };
183
+ /** What the door reads of a request: its method, its target, its headers, and the socket's address. A Node `IncomingMessage` is one; the in-process door builds one from a fetch `Request`. */
184
+ export interface DoorRequest {
185
+ method?: string | undefined;
186
+ url?: string | undefined;
187
+ headers: IncomingHttpHeaders;
188
+ /** every value of each field, as Node keeps them; read for an HTTP message signature */
189
+ headersDistinct?: Record<string, string[] | undefined>;
190
+ socket: {
191
+ remoteAddress?: string | undefined;
192
+ };
193
+ }
194
+ /**
195
+ * The original request an authz check asks about, from `X-Original-Method` and `X-Original-URI`, with the check's own
196
+ * headers and address. The check request's own method and path are the proxy's (nginx sends GET to a fixed location),
197
+ * so both headers are required, and a check without them is refused rather than decided on the proxy's request.
198
+ */
199
+ export declare function authzTarget(req: DoorRequest): DoorRequest | {
200
+ problem: string;
201
+ };
159
202
  /** 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. */
160
203
  export declare function matchRoute(routes: DoorRouteConfig[], unmatched: string, method: string, pathname: string): string;
161
204
  /**
162
205
  * The arrival's address: the socket's, or with trustProxy the last address in `X-Forwarded-For`, the one the proxy in
163
206
  * front of the door appended. Everything before it was sent by the client, which may write what it likes there.
164
207
  */
165
- export declare function remoteOf(req: IncomingMessage, trustProxy: boolean): string;
208
+ export declare function remoteOf(req: DoorRequest, trustProxy: boolean): string;
209
+ /**
210
+ * The request as RFC 9421 reads it: the target as received, the `Host` as the authority, and every value of each field.
211
+ * A request without `headersDistinct` (a fetch request, which joins repeated fields with ", ") gives each field's value as
212
+ * it holds it.
213
+ */
214
+ export declare function signedRequestOf(req: DoorRequest): SignedRequest;
166
215
  /**
167
216
  * What the arrival presented, checked where it can be. A grant signed by a trusted principal, in its window, naming this
168
217
  * route among its scopes, makes the arrival `verified` and its principal attested. A grant that is out of scope, expired,
169
218
  * or signed by a stranger leaves the arrival `claimed`: it asserted an identity the door could not accept for this route.
170
- * An `x-agent-custody-agent` header or an HTTP signature header alone is `claimed`. Nothing at all is `unknown`.
219
+ * Without a grant, a Web Bot Auth signature the door verified (`signature`, from `createWebBotAuthVerifier`) makes the
220
+ * arrival `verified` as its signature agent. With both, the signature binds the grant to its sender when the grant names
221
+ * that signature agent; a grant presented under another agent's signature is `wrong-sender` and the arrival `claimed`.
222
+ * An `x-agent-custody-agent` header or a signature that did not verify alone is `claimed`. Nothing at all is `unknown`.
223
+ * Without `signature`, a `Signature-Input` header is recorded as `unchecked`.
171
224
  */
172
- export declare function classifyArrival(req: IncomingMessage, trusted: PublicKeyRef[], route: string, trustProxy: boolean, at: string): Classified;
225
+ export declare function classifyArrival(req: DoorRequest, trusted: PublicKeyRef[], route: string, trustProxy: boolean, at: string, signature?: SignatureCheck): Classified;
173
226
  export interface DoorOptions {
174
227
  /** the log to append to, in place of the one the config names; for embedding and tests */
175
228
  log?: LogSink;
@@ -187,8 +240,83 @@ export interface DoorHost {
187
240
  pendingReceipts(): number;
188
241
  close(): Promise<void>;
189
242
  }
243
+ /** The body as the door read it: whole, or how many bytes had arrived when it passed the limit. */
244
+ export type BodyRead = {
245
+ body: Buffer;
246
+ } | {
247
+ oversized: true;
248
+ bytes: number;
249
+ };
250
+ /** The body, or how many bytes had arrived when it passed the limit; the rest is drained and dropped. */
251
+ export declare function readBody(req: IncomingMessage, max: number): Promise<BodyRead>;
252
+ /** A fetch body, or how many bytes had arrived when it passed the limit; the rest is not read. */
253
+ export declare function readStream(stream: ReadableStream<Uint8Array> | null, max: number): Promise<BodyRead>;
190
254
  /** The query as own properties: a parameter named `constructor` or `__proto__` is a parameter, never an inherited member or the prototype. */
191
255
  export declare function queryOf(url: URL): Record<string, string | string[]>;
256
+ type Execution = ReceiptPredicate["execution"];
257
+ type ReceiptHead = Omit<ReceiptPredicate, "session" | "model" | "execution" | "authorization">;
258
+ /** One arrival as the door decided it, before anything was relayed or passed on. */
259
+ export interface DoorDecision {
260
+ receiptId: string;
261
+ arrival: Arrival;
262
+ method: string;
263
+ url: URL;
264
+ route: string;
265
+ /** the path decoded and encoded once, the form the origin is sent; absent when the path did not decode cleanly */
266
+ relay?: string;
267
+ /** the body, or null when it passed `maxBodyBytes` */
268
+ body: Buffer | null;
269
+ /** set when the door refuses the arrival: what the receipt records, and the status the arrival is answered */
270
+ refused?: {
271
+ execution: Execution;
272
+ status: number;
273
+ };
274
+ head: ReceiptHead;
275
+ authorization?: AuthorizationBundle;
276
+ }
277
+ /** An answer the door gives itself, in place of the origin's or the app's. */
278
+ export interface DoorAnswer {
279
+ status: number;
280
+ headers: Record<string, string>;
281
+ body: string;
282
+ }
283
+ /**
284
+ * The door's decision loop, shared by the proxy and the in-process door: classify the arrival, read its body, run the
285
+ * policy, commit the authorization of a request that can change something, and write the receipt once the outcome is
286
+ * known. What happens between the decision and the receipt, relaying to an origin or passing the request to the app in
287
+ * the same process, is the caller's.
288
+ */
289
+ export interface DoorCore {
290
+ keyid: string;
291
+ policyDigest(): string;
292
+ /** false when `maxInFlight` arrivals are already being handled: answer `busy()` before the body is read. Every admitted arrival is released */
293
+ admit(): boolean;
294
+ release(): void;
295
+ busy(): DoorAnswer;
296
+ /** `framework`, when given, is the receipt's `issuer.framework` in place of the core's. `read` is null when the door never sees the body (an authz check): the receipt then records none */
297
+ decide(req: DoorRequest, receiptId: string, read: ((max: number) => Promise<BodyRead>) | null, framework?: string): Promise<DoorDecision>;
298
+ /** a header the door consumed and never passes on: the grant (and `Authorization` when it carried it), the declared agent, the challenge token */
299
+ consumed(name: string, req: DoorRequest, arrival: Arrival): boolean;
300
+ /** writes the receipt; null when it could not be written, after saying why on stderr */
301
+ record(d: DoorDecision, execution: Execution): Promise<{
302
+ logPending: boolean;
303
+ } | null>;
304
+ /** the door's headers on every answer */
305
+ mark(d: DoorDecision, logPending: boolean): Record<string, string>;
306
+ /** the answer to an arrival the door refused */
307
+ refusal(d: DoorDecision, logPending: boolean): DoorAnswer;
308
+ /** the answer when the receipt could not be written: what happened, so that nobody retries a refund that went through */
309
+ unrecorded(d: DoorDecision, execution: Execution, notSent: boolean): DoorAnswer;
310
+ flushOutbox(): Promise<FlushResult>;
311
+ pendingReceipts(): number;
312
+ close(): void;
313
+ }
314
+ /** The decision loop for a door config; `framework` is the receipt's `issuer.framework`. Throws when the config cannot be served. */
315
+ export declare function createDoorCore(cfg: DoorConfig, options: Omit<DoorOptions, "fetch"> & {
316
+ fetch?: typeof fetch;
317
+ }, framework: string): DoorCore;
318
+ export declare const sendAnswer: (res: ServerResponse, a: DoorAnswer) => void;
319
+ /** 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. */
192
320
  export declare function createDoorHost(cfg: DoorConfig, options?: DoorOptions): Promise<DoorHost>;
193
321
  export interface DoorServerOptions {
194
322
  port: number;
@@ -201,3 +329,4 @@ export interface RunningDoor {
201
329
  }
202
330
  /** Serves a door host over plain HTTP. Bind to loopback or put TLS in front. `GET /.well-known/agent-custody-door` answers the key id and the policy digest. */
203
331
  export declare function serveDoor(host: DoorHost, opts: DoorServerOptions): Promise<RunningDoor>;
332
+ export {};