@agent-custody/receipts 0.16.9 → 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.
- package/README.md +24 -9
- package/dist/approval-requests.d.ts +114 -0
- package/dist/approval-requests.js +198 -0
- package/dist/approval.d.ts +8 -0
- package/dist/approval.js +10 -3
- package/dist/check.js +2 -0
- package/dist/cli.js +96 -16
- package/dist/completeness.d.ts +28 -2
- package/dist/completeness.js +102 -9
- package/dist/config.d.ts +3 -0
- package/dist/config.js +6 -1
- package/dist/console-page.js +87 -2
- package/dist/console.js +72 -0
- package/dist/crypto.d.ts +2 -0
- package/dist/crypto.js +2 -1
- package/dist/delegation.d.ts +1 -1
- package/dist/delegation.js +19 -2
- package/dist/did-key.d.ts +11 -0
- package/dist/did-key.js +86 -0
- package/dist/door-app.d.ts +3 -0
- package/dist/door-app.js +10 -0
- package/dist/door-core.d.ts +373 -0
- package/dist/door-core.js +743 -0
- package/dist/door-form.d.ts +6 -0
- package/dist/door-form.js +97 -0
- package/dist/door-worker.d.ts +133 -0
- package/dist/door-worker.js +259 -0
- package/dist/door.d.ts +18 -294
- package/dist/door.js +62 -722
- package/dist/gateway-http.d.ts +1 -6
- package/dist/gateway-http.js +2 -19
- package/dist/gateway.js +24 -3
- package/dist/grant-header.d.ts +8 -0
- package/dist/grant-header.js +19 -0
- package/dist/index.d.ts +7 -4
- package/dist/index.js +5 -2
- package/dist/issue.d.ts +2 -16
- package/dist/issue.js +2 -12
- package/dist/log-http.d.ts +37 -0
- package/dist/log-http.js +74 -0
- package/dist/log-sink.d.ts +3 -37
- package/dist/log-sink.js +5 -71
- package/dist/log.d.ts +2 -27
- package/dist/log.js +2 -173
- package/dist/merkle.d.ts +27 -0
- package/dist/merkle.js +175 -0
- package/dist/object-issuer.d.ts +29 -0
- package/dist/object-issuer.js +172 -0
- package/dist/receipt-pending.d.ts +16 -0
- package/dist/receipt-pending.js +14 -0
- package/dist/web-bot-auth.d.ts +26 -6
- package/dist/web-bot-auth.js +116 -56
- package/docs/approvals.md +33 -0
- package/docs/completeness.md +82 -12
- package/docs/console.md +11 -4
- package/docs/door-middleware.md +11 -0
- package/docs/door-quickstart.md +53 -17
- package/docs/door-signals.md +5 -5
- package/docs/door-worker.md +81 -0
- package/docs/door.md +38 -8
- package/docs/github-action.md +2 -2
- package/docs/threat-model.md +1 -1
- package/docs/tutorials.md +5 -0
- package/docs/verification.md +1 -1
- package/package.json +3 -1
- package/vectors/audit.json +27 -27
- package/vectors/canonical.json +5 -5
- package/vectors/receipts.json +1645 -1549
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { DoorConfig } from "./config.ts";
|
|
2
|
+
export declare const FORM_SCRIPT_PATH = "/.well-known/agent-custody-door/form.js";
|
|
3
|
+
type Challenge = NonNullable<DoorConfig["challenge"]>;
|
|
4
|
+
/** The browser script for a door's challenge config. Public: it carries the provider, the site key, the header, and the action. */
|
|
5
|
+
export declare function formScript(challenge: Challenge): string;
|
|
6
|
+
export {};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
export const FORM_SCRIPT_PATH = "/.well-known/agent-custody-door/form.js";
|
|
2
|
+
const PROVIDER_SCRIPT = {
|
|
3
|
+
turnstile: "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",
|
|
4
|
+
hcaptcha: "https://js.hcaptcha.com/1/api.js?render=explicit",
|
|
5
|
+
};
|
|
6
|
+
/** The browser script for a door's challenge config. Public: it carries the provider, the site key, the header, and the action. */
|
|
7
|
+
export function formScript(challenge) {
|
|
8
|
+
const settings = { provider: challenge.provider, siteKey: challenge.siteKey, header: challenge.header, src: PROVIDER_SCRIPT[challenge.provider], ...(challenge.action ? { action: challenge.action } : {}) };
|
|
9
|
+
return `// agent-custody door: form protector. Load it with a script tag, src ${FORM_SCRIPT_PATH} and defer; data-forms on the tag selects the forms.
|
|
10
|
+
(() => {
|
|
11
|
+
"use strict";
|
|
12
|
+
const settings = ${JSON.stringify(settings).replace(/</g, "\\u003c")};
|
|
13
|
+
const tag = document.currentScript;
|
|
14
|
+
const selector = (tag && tag.dataset.forms) || "form";
|
|
15
|
+
// the widget's own copies of the token: the door reads it from the header, and a body field would reach the receipt
|
|
16
|
+
const tokenFields = ["cf-turnstile-response", "h-captcha-response", "g-recaptcha-response"];
|
|
17
|
+
const api = () => (settings.provider === "turnstile" ? window.turnstile : window.hcaptcha);
|
|
18
|
+
|
|
19
|
+
const protect = (form) => {
|
|
20
|
+
if ((form.getAttribute("method") || "get").toLowerCase() !== "post") return;
|
|
21
|
+
const target = new URL(form.getAttribute("action") || location.href, location.href);
|
|
22
|
+
if (target.origin !== location.origin) return;
|
|
23
|
+
const box = document.createElement("div");
|
|
24
|
+
box.className = "agent-custody-challenge";
|
|
25
|
+
const note = document.createElement("p");
|
|
26
|
+
note.className = "agent-custody-challenge-note";
|
|
27
|
+
note.setAttribute("role", "status");
|
|
28
|
+
const button = form.querySelector('[type="submit"], button:not([type])');
|
|
29
|
+
if (button) button.before(box, note);
|
|
30
|
+
else form.append(box, note);
|
|
31
|
+
const options = { sitekey: settings.siteKey };
|
|
32
|
+
if (settings.provider === "turnstile") {
|
|
33
|
+
options["response-field"] = false;
|
|
34
|
+
if (settings.action) options.action = settings.action;
|
|
35
|
+
}
|
|
36
|
+
const widget = api().render(box, options);
|
|
37
|
+
let sending = false;
|
|
38
|
+
form.addEventListener("submit", async (event) => {
|
|
39
|
+
// a button's formaction, formmethod, and formenctype override the form's; a GET or another site's action goes natively
|
|
40
|
+
const via = event.submitter;
|
|
41
|
+
const attr = (name, fallback) => (via && via.hasAttribute && via.hasAttribute(name) ? via.getAttribute(name) : fallback);
|
|
42
|
+
const method = (attr("formmethod", form.getAttribute("method")) || "get").toLowerCase();
|
|
43
|
+
const to = new URL(attr("formaction", form.getAttribute("action")) || location.href, location.href);
|
|
44
|
+
if (method !== "post" || to.origin !== location.origin) {
|
|
45
|
+
// the browser reads the fields after this event: a disabled field is left out, so the token does not go along
|
|
46
|
+
for (const name of tokenFields) form.querySelectorAll('[name="' + name + '"]').forEach((el) => { el.disabled = true; });
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
event.preventDefault();
|
|
50
|
+
if (sending) return;
|
|
51
|
+
const token = api().getResponse(widget);
|
|
52
|
+
if (!token) {
|
|
53
|
+
note.textContent = "Complete the check above, then send the form again.";
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
sending = true;
|
|
57
|
+
note.textContent = "";
|
|
58
|
+
const data = new FormData(form, event.submitter || undefined);
|
|
59
|
+
for (const field of tokenFields) data.delete(field);
|
|
60
|
+
const multipart = (attr("formenctype", form.getAttribute("enctype")) || "").toLowerCase() === "multipart/form-data";
|
|
61
|
+
try {
|
|
62
|
+
const res = await fetch(to, { method: "POST", body: multipart ? data : new URLSearchParams(data), headers: { [settings.header]: token }, credentials: "same-origin", signal: AbortSignal.timeout(30000) });
|
|
63
|
+
if (res.redirected) return location.assign(res.url);
|
|
64
|
+
const type = res.headers.get("content-type") || "";
|
|
65
|
+
if (res.status === 403 && type.includes("application/json")) {
|
|
66
|
+
const refusal = await res.json().catch(() => ({}));
|
|
67
|
+
note.textContent = refusal.challenge ? "The check did not pass. Complete it again, then send the form." : "This form was refused (receipt " + (refusal.receipt || "none") + ").";
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
const body = await res.text();
|
|
71
|
+
if (type.includes("text/html")) {
|
|
72
|
+
document.open();
|
|
73
|
+
document.write(body);
|
|
74
|
+
document.close();
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
note.textContent = res.ok ? "Sent." : "The form was not sent: HTTP " + res.status + ".";
|
|
78
|
+
} catch (error) {
|
|
79
|
+
// a failure after the door relayed the form (a redirect to another site, a timeout) looks the same as one before
|
|
80
|
+
note.textContent = "The answer did not arrive, and the form may have been sent. Check before you send it again.";
|
|
81
|
+
} finally {
|
|
82
|
+
sending = false;
|
|
83
|
+
// a token serves one request
|
|
84
|
+
api().reset(widget);
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const start = () => document.querySelectorAll(selector).forEach(protect);
|
|
90
|
+
const loader = document.createElement("script");
|
|
91
|
+
loader.src = settings.src;
|
|
92
|
+
loader.async = true;
|
|
93
|
+
loader.onload = () => (document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", start) : start());
|
|
94
|
+
document.head.append(loader);
|
|
95
|
+
})();
|
|
96
|
+
`;
|
|
97
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { type DoorConfig } from "./config.ts";
|
|
2
|
+
import { type PublicKeyRef } from "./crypto.ts";
|
|
3
|
+
import { type DoorIO, type DoorRequest, type ObservedFact } from "./door-core.ts";
|
|
4
|
+
import { type ObjectStore } from "./object-issuer.ts";
|
|
5
|
+
import type { NonceStore } from "./web-bot-auth.ts";
|
|
6
|
+
/** What the Worker needs of an R2 bucket binding. */
|
|
7
|
+
export interface R2BucketLike {
|
|
8
|
+
put(key: string, value: string): Promise<unknown>;
|
|
9
|
+
get(key: string): Promise<{
|
|
10
|
+
text(): Promise<string>;
|
|
11
|
+
} | null>;
|
|
12
|
+
list(options: {
|
|
13
|
+
prefix: string;
|
|
14
|
+
cursor?: string;
|
|
15
|
+
}): Promise<{
|
|
16
|
+
objects: {
|
|
17
|
+
key: string;
|
|
18
|
+
}[];
|
|
19
|
+
truncated: boolean;
|
|
20
|
+
cursor?: string;
|
|
21
|
+
}>;
|
|
22
|
+
delete(key: string): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
/** What the Worker needs of a Durable Object namespace binding. */
|
|
25
|
+
export interface DurableObjectNamespaceLike {
|
|
26
|
+
idFromName(name: string): unknown;
|
|
27
|
+
get(id: never): {
|
|
28
|
+
fetch(url: string, init: RequestInit): Promise<Response>;
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/** What a Durable Object is given of its own state. */
|
|
32
|
+
export interface DurableObjectStateLike {
|
|
33
|
+
storage: {
|
|
34
|
+
get(key: string): Promise<unknown>;
|
|
35
|
+
put(key: string, value: unknown): Promise<void>;
|
|
36
|
+
setAlarm(at: number): Promise<void>;
|
|
37
|
+
deleteAll(): Promise<void>;
|
|
38
|
+
};
|
|
39
|
+
blockConcurrencyWhile<T>(f: () => Promise<T>): Promise<T>;
|
|
40
|
+
}
|
|
41
|
+
/** The Worker's bindings. Any other string binding is a secret the door config may name (`challenge.secretEnv`, `captureKeyEnv`, `origin.headerEnv`). */
|
|
42
|
+
export interface DoorWorkerEnv {
|
|
43
|
+
/** the door config as JSON: routes, policy mode, precommit, capture, challenge, webBotAuth, limits. Not the fields that name files */
|
|
44
|
+
DOOR_CONFIG: string;
|
|
45
|
+
/** the Cedar policy text */
|
|
46
|
+
DOOR_POLICY: string;
|
|
47
|
+
/** where allowed requests go */
|
|
48
|
+
ORIGIN_URL: string;
|
|
49
|
+
/** the hosted log (or any agent-custody log) */
|
|
50
|
+
LOG_URL: string;
|
|
51
|
+
/** the log's public keys, SPKI PEM, pinned: every append's answer is checked against them before a request is relayed */
|
|
52
|
+
LOG_KEYS: string;
|
|
53
|
+
/** the tenant's log id, which every tree head must name */
|
|
54
|
+
LOG_ID?: string;
|
|
55
|
+
/** "true": send the log leaf hashes only */
|
|
56
|
+
LOG_HASH_ONLY?: string;
|
|
57
|
+
/** principal keys whose grants are a passport, SPKI PEM */
|
|
58
|
+
TRUSTED_PRINCIPAL_KEYS?: string;
|
|
59
|
+
/** a JSON array of revoked grant digests, as in a gateway's or door's `revokedGrants` file */
|
|
60
|
+
REVOKED_GRANTS?: string;
|
|
61
|
+
/** secret: the door's signing key, PKCS8 PEM (`agent-custody keygen`) */
|
|
62
|
+
DOOR_KEY: string;
|
|
63
|
+
/** secret: the log token */
|
|
64
|
+
LOG_TOKEN?: string;
|
|
65
|
+
/** the bucket the receipt bundles, authorizations, salts, and outbox go to */
|
|
66
|
+
RECEIPTS: R2BucketLike;
|
|
67
|
+
/** the `DoorNonce` Durable Object namespace that remembers Web Bot Auth nonces for every isolate; needed with `webBotAuth` */
|
|
68
|
+
NONCES?: DurableObjectNamespaceLike;
|
|
69
|
+
[binding: string]: unknown;
|
|
70
|
+
}
|
|
71
|
+
/** What a request's `cf` object may carry; only Bot Management is read, and only where the zone has it. */
|
|
72
|
+
interface CfProperties {
|
|
73
|
+
botManagement?: {
|
|
74
|
+
score?: unknown;
|
|
75
|
+
verifiedBot?: unknown;
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** the fact the Worker records when Cloudflare Bot Management scored the request */
|
|
79
|
+
export declare const CLOUDFLARE_FACT = "cloudflare";
|
|
80
|
+
/** Every SPKI PEM block in a variable. */
|
|
81
|
+
export declare function pemKeys(text: string | undefined): PublicKeyRef[];
|
|
82
|
+
/**
|
|
83
|
+
* The door config from the Worker's bindings, checked by the same schema as a Node door's. The fields that name files
|
|
84
|
+
* are refused in DOOR_CONFIG, and the placeholders put in their place say where the Worker gets each one; nothing reads them.
|
|
85
|
+
*/
|
|
86
|
+
export declare function workerDoorConfig(env: DoorWorkerEnv): DoorConfig;
|
|
87
|
+
/** An R2 bucket as the object store the issuer writes to; a listing follows the bucket's cursor to the end. */
|
|
88
|
+
export declare function r2Store(bucket: R2BucketLike): ObjectStore;
|
|
89
|
+
/**
|
|
90
|
+
* Web Bot Auth nonces in Durable Objects, one object per `<agent> <keyid> <nonce>`: every isolate that claims a key
|
|
91
|
+
* reaches the same object, wherever it runs, and that object answers one claim at a time. An object that cannot be
|
|
92
|
+
* reached, or answers anything but a claim, throws, and the verifier calls the signature `unavailable`.
|
|
93
|
+
*/
|
|
94
|
+
export declare function durableNonceStore(ns: DurableObjectNamespaceLike, timeoutMs?: number): NonceStore;
|
|
95
|
+
/**
|
|
96
|
+
* The Durable Object behind `durableNonceStore`: it holds one nonce until the signature it came with could no longer be
|
|
97
|
+
* accepted, and a minute more, then an alarm empties it. Claims are answered one at a time, so of two arrivals with one
|
|
98
|
+
* nonce, one is `claimed` and the other `replayed`.
|
|
99
|
+
*/
|
|
100
|
+
export declare class DoorNonce {
|
|
101
|
+
state: DurableObjectStateLike;
|
|
102
|
+
constructor(state: DurableObjectStateLike);
|
|
103
|
+
fetch(request: Request): Promise<Response>;
|
|
104
|
+
alarm(): Promise<void>;
|
|
105
|
+
}
|
|
106
|
+
/** The door's I/O from the Worker's bindings: the key from a secret, the policy and keys from variables, receipts to R2 and the log. */
|
|
107
|
+
export declare function workerDoorIO(env: DoorWorkerEnv, f: typeof fetch): DoorIO;
|
|
108
|
+
/**
|
|
109
|
+
* The request as the door reads it: the target, the headers as fetch joins them, and the client's address as Cloudflare
|
|
110
|
+
* gives it. The host is the request URL's, which Cloudflare builds from the client's `Host`: it is the authority a Web
|
|
111
|
+
* Bot Auth signature covers. Cloudflare's own headers (`cf-*`, `cdn-loop`) are its, not the client's: they are not
|
|
112
|
+
* relayed, and `cdn-loop` sent on to a subrequest would count as a loop.
|
|
113
|
+
*/
|
|
114
|
+
export declare function doorRequestOf(request: Request): DoorRequest;
|
|
115
|
+
/** Cloudflare Bot Management's score and verified-bot flag, when the zone has it and they are what Cloudflare documents; nothing otherwise. Cloudflare does not sign them: they enter as observed. */
|
|
116
|
+
export declare function cloudflareFacts(cf: CfProperties | undefined): Record<string, ObservedFact>;
|
|
117
|
+
export interface DoorWorkerOptions {
|
|
118
|
+
/** the fetch for the origin, the log, the challenge provider, and Web Bot Auth directories; the Worker's own by default */
|
|
119
|
+
fetch?: typeof fetch;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* The Worker: `fetch` decides, relays or refuses, and receipts each request; `scheduled` (a cron trigger) appends the
|
|
123
|
+
* receipts whose log append was pending. The door is built on the first request of an isolate from that request's
|
|
124
|
+
* bindings, and built again on the next request if that failed, so a config error answers 500 with the reason and
|
|
125
|
+
* relays nothing.
|
|
126
|
+
*/
|
|
127
|
+
export declare function createDoorWorker(options?: DoorWorkerOptions): {
|
|
128
|
+
fetch(request: Request, env: DoorWorkerEnv): Promise<Response>;
|
|
129
|
+
scheduled(_event: unknown, env: DoorWorkerEnv, ctx: {
|
|
130
|
+
waitUntil(p: Promise<unknown>): void;
|
|
131
|
+
}): Promise<void>;
|
|
132
|
+
};
|
|
133
|
+
export {};
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
// The door as a Cloudflare Worker: the same decision core as the Node door (door-core.ts), with its I/O from the Worker's
|
|
2
|
+
// bindings. The signing key and the log token are secrets; the door config, the policy, the origin, and the log are
|
|
3
|
+
// variables; receipts go to an R2 bucket and to the log over HTTP; Web Bot Auth nonces go to a Durable Object. Built for workerd by scripts/build-door-worker.ts,
|
|
4
|
+
// deployed from deploy/door/cloudflare-worker/.
|
|
5
|
+
import { createPrivateKey, createPublicKey } from "node:crypto";
|
|
6
|
+
import { DoorConfigSchema } from "./config.js";
|
|
7
|
+
import { keyidOf, publicKeyFromPem } from "./crypto.js";
|
|
8
|
+
import { createDoorCoreWith, DOOR_VERSION, jsonAnswer, readStream, RECEIPT_HEADER, relayedAnswer, relayToOrigin } from "./door-core.js";
|
|
9
|
+
import { FORM_SCRIPT_PATH, formScript } from "./door-form.js";
|
|
10
|
+
import { httpLog } from "./log-http.js";
|
|
11
|
+
import { createObjectIssuer } from "./object-issuer.js";
|
|
12
|
+
/** the fact the Worker records when Cloudflare Bot Management scored the request */
|
|
13
|
+
export const CLOUDFLARE_FACT = "cloudflare";
|
|
14
|
+
/** Config fields that name files or a Node door's modes: in a Worker each comes from a binding, or does not apply. */
|
|
15
|
+
const NOT_IN_A_WORKER = {
|
|
16
|
+
identity: "the signing key is the DOOR_KEY secret",
|
|
17
|
+
policyFile: "the policy is the DOOR_POLICY variable",
|
|
18
|
+
receiptsDir: "receipts go to the RECEIPTS bucket",
|
|
19
|
+
logFile: "the log is LOG_URL",
|
|
20
|
+
log: "the log is LOG_URL, LOG_KEYS, LOG_ID, LOG_TOKEN",
|
|
21
|
+
trustedPrincipalKeys: "trusted principal keys are the TRUSTED_PRINCIPAL_KEYS variable",
|
|
22
|
+
revokedGrants: "revoked grants are the REVOKED_GRANTS variable",
|
|
23
|
+
authz: "a Worker relays; nginx and Envoy ask a Node door",
|
|
24
|
+
trustProxy: "the Worker reads the client's address from Cloudflare (CF-Connecting-IP)",
|
|
25
|
+
partner: "a partner engine needs its verdict key on disk; not supported in a Worker yet",
|
|
26
|
+
otel: "export is not supported in a Worker yet",
|
|
27
|
+
splunk: "export is not supported in a Worker yet",
|
|
28
|
+
};
|
|
29
|
+
/** Every SPKI PEM block in a variable. */
|
|
30
|
+
export function pemKeys(text) {
|
|
31
|
+
return [...(text ?? "").matchAll(/-----BEGIN PUBLIC KEY-----[\s\S]+?-----END PUBLIC KEY-----/g)].map((m) => publicKeyFromPem(m[0]));
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The door config from the Worker's bindings, checked by the same schema as a Node door's. The fields that name files
|
|
35
|
+
* are refused in DOOR_CONFIG, and the placeholders put in their place say where the Worker gets each one; nothing reads them.
|
|
36
|
+
*/
|
|
37
|
+
export function workerDoorConfig(env) {
|
|
38
|
+
for (const name of ["DOOR_CONFIG", "DOOR_POLICY", "ORIGIN_URL", "LOG_URL", "LOG_KEYS", "DOOR_KEY"])
|
|
39
|
+
if (typeof env[name] !== "string" || !env[name])
|
|
40
|
+
throw new Error(`the Worker needs ${name}`);
|
|
41
|
+
if (!env.RECEIPTS)
|
|
42
|
+
throw new Error("the Worker needs the RECEIPTS bucket binding");
|
|
43
|
+
const raw = JSON.parse(env.DOOR_CONFIG);
|
|
44
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
45
|
+
throw new Error("DOOR_CONFIG must be a JSON object");
|
|
46
|
+
for (const [field, why] of Object.entries(NOT_IN_A_WORKER))
|
|
47
|
+
if (Object.hasOwn(raw, field))
|
|
48
|
+
throw new Error(`DOOR_CONFIG has ${field}, which a Worker does not take: ${why}`);
|
|
49
|
+
const origin = (raw.origin ?? {});
|
|
50
|
+
if (Object.hasOwn(origin, "url"))
|
|
51
|
+
throw new Error("DOOR_CONFIG has origin.url: the origin is the ORIGIN_URL variable");
|
|
52
|
+
if (raw.webBotAuth && !env.NONCES)
|
|
53
|
+
throw new Error("DOOR_CONFIG has webBotAuth, which needs the NONCES Durable Object binding: one isolate's memory cannot refuse a signature replayed to another");
|
|
54
|
+
return DoorConfigSchema.parse({
|
|
55
|
+
...raw,
|
|
56
|
+
identity: { keyFile: "(the DOOR_KEY secret)" },
|
|
57
|
+
policyFile: "(the DOOR_POLICY variable)",
|
|
58
|
+
receiptsDir: "(the RECEIPTS bucket)",
|
|
59
|
+
log: { url: env.LOG_URL, keys: ["(the LOG_KEYS variable)"], ...(env.LOG_ID ? { logId: env.LOG_ID } : {}) },
|
|
60
|
+
origin: { ...origin, url: env.ORIGIN_URL },
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/** An R2 bucket as the object store the issuer writes to; a listing follows the bucket's cursor to the end. */
|
|
64
|
+
export function r2Store(bucket) {
|
|
65
|
+
return {
|
|
66
|
+
put: async (key, text) => void (await bucket.put(key, text)),
|
|
67
|
+
get: async (key) => (await bucket.get(key))?.text() ?? null,
|
|
68
|
+
async list(prefix) {
|
|
69
|
+
const keys = [];
|
|
70
|
+
let cursor;
|
|
71
|
+
do {
|
|
72
|
+
const page = await bucket.list({ prefix, ...(cursor ? { cursor } : {}) });
|
|
73
|
+
keys.push(...page.objects.map((o) => o.key));
|
|
74
|
+
cursor = page.truncated ? page.cursor : undefined;
|
|
75
|
+
} while (cursor);
|
|
76
|
+
return keys;
|
|
77
|
+
},
|
|
78
|
+
delete: (key) => bucket.delete(key),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/** how long the door waits for the nonce store before it calls a signature `unavailable` */
|
|
82
|
+
const NONCE_STORE_TIMEOUT_MS = 3000;
|
|
83
|
+
/**
|
|
84
|
+
* Web Bot Auth nonces in Durable Objects, one object per `<agent> <keyid> <nonce>`: every isolate that claims a key
|
|
85
|
+
* reaches the same object, wherever it runs, and that object answers one claim at a time. An object that cannot be
|
|
86
|
+
* reached, or answers anything but a claim, throws, and the verifier calls the signature `unavailable`.
|
|
87
|
+
*/
|
|
88
|
+
export function durableNonceStore(ns, timeoutMs = NONCE_STORE_TIMEOUT_MS) {
|
|
89
|
+
return {
|
|
90
|
+
async claim(key, until) {
|
|
91
|
+
const stub = ns.get(ns.idFromName(key));
|
|
92
|
+
const res = await stub.fetch("https://door-nonce/claim", { method: "POST", body: JSON.stringify({ until }), signal: AbortSignal.timeout(timeoutMs) });
|
|
93
|
+
const body = (await res.json().catch(() => null));
|
|
94
|
+
if (!res.ok || (body?.claim !== "claimed" && body?.claim !== "replayed"))
|
|
95
|
+
throw new Error(`the nonce object answered ${res.status}${body?.claim === undefined ? "" : ` ${String(body.claim)}`}`);
|
|
96
|
+
return body.claim;
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* how much longer than the isolate's deadline the object holds a nonce: `until` is on the isolate's clock and the object
|
|
102
|
+
* reads its own, so an object whose clock runs ahead would otherwise forget a nonce the isolate still accepts
|
|
103
|
+
*/
|
|
104
|
+
const NONCE_CLOCK_MARGIN_MS = 60_000;
|
|
105
|
+
/**
|
|
106
|
+
* The Durable Object behind `durableNonceStore`: it holds one nonce until the signature it came with could no longer be
|
|
107
|
+
* accepted, and a minute more, then an alarm empties it. Claims are answered one at a time, so of two arrivals with one
|
|
108
|
+
* nonce, one is `claimed` and the other `replayed`.
|
|
109
|
+
*/
|
|
110
|
+
export class DoorNonce {
|
|
111
|
+
state;
|
|
112
|
+
constructor(state) {
|
|
113
|
+
this.state = state;
|
|
114
|
+
}
|
|
115
|
+
async fetch(request) {
|
|
116
|
+
const { until } = (await request.json());
|
|
117
|
+
if (typeof until !== "number" || !Number.isFinite(until))
|
|
118
|
+
return Response.json({ error: "until must be a time in milliseconds" }, { status: 400 });
|
|
119
|
+
const claim = await this.state.blockConcurrencyWhile(async () => {
|
|
120
|
+
const held = await this.state.storage.get("until");
|
|
121
|
+
if (typeof held === "number" && held > Date.now())
|
|
122
|
+
return "replayed";
|
|
123
|
+
await this.state.storage.put("until", until + NONCE_CLOCK_MARGIN_MS);
|
|
124
|
+
await this.state.storage.setAlarm(until + NONCE_CLOCK_MARGIN_MS);
|
|
125
|
+
return "claimed";
|
|
126
|
+
});
|
|
127
|
+
return Response.json({ claim });
|
|
128
|
+
}
|
|
129
|
+
async alarm() {
|
|
130
|
+
await this.state.storage.deleteAll();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/** The door's I/O from the Worker's bindings: the key from a secret, the policy and keys from variables, receipts to R2 and the log. */
|
|
134
|
+
export function workerDoorIO(env, f) {
|
|
135
|
+
const privateKey = createPrivateKey(env.DOOR_KEY);
|
|
136
|
+
const publicKey = createPublicKey(privateKey);
|
|
137
|
+
const key = { privateKey, publicKey, keyid: keyidOf(publicKey) };
|
|
138
|
+
const logKeys = pemKeys(env.LOG_KEYS);
|
|
139
|
+
if (!logKeys.length)
|
|
140
|
+
throw new Error("LOG_KEYS holds no public key");
|
|
141
|
+
const list = env.REVOKED_GRANTS ? JSON.parse(env.REVOKED_GRANTS) : [];
|
|
142
|
+
if (!Array.isArray(list))
|
|
143
|
+
throw new Error("REVOKED_GRANTS must be a JSON array of grant digests");
|
|
144
|
+
const revoked = new Set(list.filter((d) => typeof d === "string"));
|
|
145
|
+
const sink = httpLog(env.LOG_URL, { keys: logKeys, fetch: f, ...(env.LOG_TOKEN ? { token: env.LOG_TOKEN } : {}), ...(env.LOG_ID ? { logId: env.LOG_ID } : {}), ...(env.LOG_HASH_ONLY === "true" ? { hashOnly: true } : {}) });
|
|
146
|
+
const store = r2Store(env.RECEIPTS);
|
|
147
|
+
return {
|
|
148
|
+
key,
|
|
149
|
+
trustedPrincipalKeys: pemKeys(env.TRUSTED_PRINCIPAL_KEYS),
|
|
150
|
+
readPolicy: () => ({ text: env.DOOR_POLICY, key: "DOOR_POLICY" }),
|
|
151
|
+
policySource: "the DOOR_POLICY variable",
|
|
152
|
+
revoked: (digests) => (!digests.some((d) => revoked.has(d)) ? null : revoked.has(digests[0]) ? "the grant has been revoked" : "a grant above it in its chain has been revoked"),
|
|
153
|
+
secret: (name) => (typeof env[name] === "string" ? env[name] : undefined),
|
|
154
|
+
issuer: (capture) => createObjectIssuer(key, store, sink, { capture }),
|
|
155
|
+
fetch: f,
|
|
156
|
+
timers: false,
|
|
157
|
+
...(env.NONCES ? { nonceStore: durableNonceStore(env.NONCES) } : {}),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* The request as the door reads it: the target, the headers as fetch joins them, and the client's address as Cloudflare
|
|
162
|
+
* gives it. The host is the request URL's, which Cloudflare builds from the client's `Host`: it is the authority a Web
|
|
163
|
+
* Bot Auth signature covers. Cloudflare's own headers (`cf-*`, `cdn-loop`) are its, not the client's: they are not
|
|
164
|
+
* relayed, and `cdn-loop` sent on to a subrequest would count as a loop.
|
|
165
|
+
*/
|
|
166
|
+
export function doorRequestOf(request) {
|
|
167
|
+
const url = new URL(request.url);
|
|
168
|
+
const headers = {};
|
|
169
|
+
request.headers.forEach((v, k) => { if (!k.startsWith("cf-") && k !== "cdn-loop")
|
|
170
|
+
headers[k] = v; });
|
|
171
|
+
headers.host = url.host;
|
|
172
|
+
return { method: request.method, url: url.pathname + url.search, headers, socket: { remoteAddress: request.headers.get("cf-connecting-ip") ?? undefined } };
|
|
173
|
+
}
|
|
174
|
+
/** Cloudflare Bot Management's score and verified-bot flag, when the zone has it and they are what Cloudflare documents; nothing otherwise. Cloudflare does not sign them: they enter as observed. */
|
|
175
|
+
export function cloudflareFacts(cf) {
|
|
176
|
+
const bm = cf?.botManagement;
|
|
177
|
+
if (!bm || !Number.isSafeInteger(bm.score) || typeof bm.verifiedBot !== "boolean")
|
|
178
|
+
return {};
|
|
179
|
+
return { [CLOUDFLARE_FACT]: { tool: "cloudflare.botManagement", value: { score: bm.score, verifiedBot: bm.verifiedBot } } };
|
|
180
|
+
}
|
|
181
|
+
const NULL_BODY_STATUS = new Set([101, 204, 205, 304]);
|
|
182
|
+
function toResponse(a) {
|
|
183
|
+
const headers = new Headers();
|
|
184
|
+
for (const [k, v] of Object.entries(a.headers))
|
|
185
|
+
for (const one of Array.isArray(v) ? v : [v])
|
|
186
|
+
headers.append(k, one);
|
|
187
|
+
return new Response(NULL_BODY_STATUS.has(a.status) ? null : typeof a.body === "string" ? a.body : new Uint8Array(a.body), { status: a.status, headers });
|
|
188
|
+
}
|
|
189
|
+
const answer = (a) => toResponse(a);
|
|
190
|
+
/**
|
|
191
|
+
* The Worker: `fetch` decides, relays or refuses, and receipts each request; `scheduled` (a cron trigger) appends the
|
|
192
|
+
* receipts whose log append was pending. The door is built on the first request of an isolate from that request's
|
|
193
|
+
* bindings, and built again on the next request if that failed, so a config error answers 500 with the reason and
|
|
194
|
+
* relays nothing.
|
|
195
|
+
*/
|
|
196
|
+
export function createDoorWorker(options = {}) {
|
|
197
|
+
let door;
|
|
198
|
+
const build = (env) => {
|
|
199
|
+
if (door)
|
|
200
|
+
return door;
|
|
201
|
+
const cfg = workerDoorConfig(env);
|
|
202
|
+
const f = options.fetch ?? ((input, init) => fetch(input, init));
|
|
203
|
+
const core = createDoorCoreWith(cfg, workerDoorIO(env, f), "cloudflare-worker");
|
|
204
|
+
const headers = { ...(cfg.origin.headers ?? {}) };
|
|
205
|
+
for (const [header, binding] of Object.entries(cfg.origin.headerEnv ?? {})) {
|
|
206
|
+
const v = env[binding];
|
|
207
|
+
if (typeof v !== "string" || !v)
|
|
208
|
+
throw new Error(`origin: the secret ${binding} is not set`);
|
|
209
|
+
headers[header] = v;
|
|
210
|
+
}
|
|
211
|
+
door = { core, cfg, target: { url: new URL(cfg.origin.url), headers, timeoutMs: cfg.origin.timeoutMs } };
|
|
212
|
+
return door;
|
|
213
|
+
};
|
|
214
|
+
return {
|
|
215
|
+
async fetch(request, env) {
|
|
216
|
+
let d;
|
|
217
|
+
try {
|
|
218
|
+
d = build(env);
|
|
219
|
+
}
|
|
220
|
+
catch (e) {
|
|
221
|
+
console.error(`agent-custody door: the Worker cannot serve: ${e instanceof Error ? e.message : String(e)}`);
|
|
222
|
+
return answer(jsonAnswer(500, {}, { error: "the door is not configured, so nothing was relayed", detail: e instanceof Error ? e.message : String(e) }));
|
|
223
|
+
}
|
|
224
|
+
const { core, cfg } = d;
|
|
225
|
+
const url = new URL(request.url);
|
|
226
|
+
if (request.method === "GET" && url.pathname === "/.well-known/agent-custody-door")
|
|
227
|
+
return answer(jsonAnswer(200, {}, { keyid: core.keyid, policyDigest: core.policyDigest(), version: DOOR_VERSION, pendingReceipts: core.pendingReceipts() }));
|
|
228
|
+
if (request.method === "GET" && url.pathname === FORM_SCRIPT_PATH) {
|
|
229
|
+
if (!cfg.challenge)
|
|
230
|
+
return answer(jsonAnswer(404, {}, { error: "this door has no challenge configured, so it has no form protector" }));
|
|
231
|
+
return new Response(formScript(cfg.challenge), { headers: { "content-type": "text/javascript; charset=utf-8", "cache-control": "public, max-age=300", "x-content-type-options": "nosniff" } });
|
|
232
|
+
}
|
|
233
|
+
if (!core.admit())
|
|
234
|
+
return answer(core.busy());
|
|
235
|
+
const receiptId = crypto.randomUUID();
|
|
236
|
+
try {
|
|
237
|
+
const req = doorRequestOf(request);
|
|
238
|
+
const decision = await core.decide(req, receiptId, (max) => readStream(request.body, max), undefined, cloudflareFacts(request.cf));
|
|
239
|
+
const relayed = await relayToOrigin(core, cfg, decision, req, { ...d.target, proto: url.protocol.slice(0, -1) }, options.fetch ?? ((input, init) => fetch(input, init)));
|
|
240
|
+
const recorded = await core.record(decision, relayed.execution);
|
|
241
|
+
if (!recorded)
|
|
242
|
+
return answer(core.unrecorded(decision, relayed.execution, relayed.notSent));
|
|
243
|
+
return toResponse(relayedAnswer(core, cfg, decision, relayed, recorded.logPending));
|
|
244
|
+
}
|
|
245
|
+
catch (e) {
|
|
246
|
+
console.error(`agent-custody door: ${e instanceof Error ? e.message : String(e)}`);
|
|
247
|
+
return answer(jsonAnswer(500, { [RECEIPT_HEADER]: receiptId }, { error: "the door failed before it could answer; whether the origin acted on the request is unknown", receipt: receiptId }));
|
|
248
|
+
}
|
|
249
|
+
finally {
|
|
250
|
+
core.release();
|
|
251
|
+
}
|
|
252
|
+
},
|
|
253
|
+
async scheduled(_event, env, ctx) {
|
|
254
|
+
const d = build(env);
|
|
255
|
+
ctx.waitUntil(d.core.flushOutbox().then((r) => { if (r.sent || r.pending || r.error)
|
|
256
|
+
console.error(`agent-custody door: outbox: ${r.sent} sent, ${r.pending} pending${r.error ? `; ${r.error}` : ""}`); }));
|
|
257
|
+
},
|
|
258
|
+
};
|
|
259
|
+
}
|