@agent-custody/receipts 0.16.11 → 0.16.12

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.
@@ -0,0 +1,117 @@
1
+ // A labelled test set for the door: arrivals built to be one known kind each, decided by the real door core, with no
2
+ // network. The origin and the signature agent's directory are stand-ins in memory. The labels are true by construction,
3
+ // so the error rates measured on it say what the door's checks do with each kind, not how common each kind is.
4
+ import { generateKeyPairSync, randomUUID, sign } from "node:crypto";
5
+ import { mkdirSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { DoorConfigSchema } from "./config.js";
8
+ import { generateKeyPair } from "./crypto.js";
9
+ import { createDelegation } from "./delegation.js";
10
+ import { createDoorCoreWith, relayToOrigin } from "./door-core.js";
11
+ import { grantHeader } from "./grant-header.js";
12
+ import { createIssuer } from "./issue.js";
13
+ import { DIRECTORY_MEDIA_TYPE, DIRECTORY_PATH, jwkThumbprint, parseDictionary, signatureBase } from "./web-bot-auth.js";
14
+ const SITE = "shop.test";
15
+ const AGENT_ORIGIN = "https://crawler.test";
16
+ const BROWSER_UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
17
+ const POLICY = `permit(principal, action == Action::"api", resource) when { context.facts.arrival.class == "verified" };
18
+ permit(principal, action == Action::"account", resource) when { context.facts.arrival.class == "verified" };`;
19
+ const grant = (k, agent, scopes, fromMs, toMs) => grantHeader(createDelegation(k, { version: "0.1", principal: "shop-owner", agent, scopes, issuedAt: new Date(Date.now() + fromMs).toISOString(), expiresAt: new Date(Date.now() + toMs).toISOString() }));
20
+ function signed(key, x, nonce, path) {
21
+ const created = Math.floor(Date.now() / 1000);
22
+ const headers = { "signature-agent": `crawler="${AGENT_ORIGIN}"` };
23
+ headers["signature-input"] = `sig1=("@authority" "signature-agent";key="crawler");created=${created};expires=${created + 60};keyid="${jwkThumbprint(x)}";alg="ed25519";nonce="${nonce}";tag="web-bot-auth"`;
24
+ const base = signatureBase({ method: "GET", target: path, authority: SITE, header: (h) => (Object.hasOwn(headers, h) ? [headers[h]] : undefined) }, parseDictionary(headers["signature-input"]).get("sig1"));
25
+ headers.signature = `sig1=:${sign(null, Buffer.from(base), key).toString("base64")}:`;
26
+ return headers;
27
+ }
28
+ const PATH = "/api/orders";
29
+ /** The kinds in the published test set, in the order the page lists them. */
30
+ export const DOOR_TEST_KINDS = [
31
+ { kind: "browser", automated: false, genuine: null, describes: "a person's browser: a current Chrome user agent and an HTML accept header, nothing else", build: () => ({ headers: { "user-agent": BROWSER_UA, accept: "text/html" } }) },
32
+ { kind: "script", automated: true, genuine: null, describes: "a program that presents nothing: a curl user agent", build: () => ({ headers: { "user-agent": "curl/8.7.1", accept: "*/*" } }) },
33
+ { kind: "script-as-browser", automated: true, genuine: null, describes: "a program that sends the browser's headers, byte for byte", build: () => ({ headers: { "user-agent": BROWSER_UA, accept: "text/html" } }) },
34
+ { kind: "granted-agent", automated: true, genuine: true, describes: "an agent with a grant from a trusted principal, in its window, for this route", build: (k) => ({ headers: { "x-agent-custody-grant": grant(k.principal, "buyer-bot", ["api"], -1000, 3600_000) } }) },
35
+ { kind: "signed-agent", automated: true, genuine: true, describes: "an agent with a Web Bot Auth signature its listed directory's key verifies, with a fresh nonce", build: (k, n) => ({ headers: signed(k.agent.privateKey, k.agent.x, `signed-${n}`, PATH) }) },
36
+ { kind: "declared-name", automated: true, genuine: false, describes: "a program that names an agent in `x-agent-custody-agent` and presents nothing else", build: () => ({ headers: { "x-agent-custody-agent": "buyer-bot" } }) },
37
+ { kind: "forged-signature", automated: true, genuine: false, describes: "a Web Bot Auth signature in the agent's name and keyid, made with another key", build: (k, n) => ({ headers: signed(k.impostor, k.agent.x, `forged-${n}`, PATH) }) },
38
+ { kind: "replayed-signature", automated: true, genuine: false, describes: "the agent's own valid signature, sent a second time by someone who saw it", build: (k, n) => { const h = signed(k.agent.privateKey, k.agent.x, `replayed-${n}`, PATH); return { headers: h, prime: h }; } },
39
+ { kind: "untrusted-grant", automated: true, genuine: false, describes: "a well-formed grant signed by a principal key the door does not trust", build: (k) => ({ headers: { "x-agent-custody-grant": grant(k.stranger, "buyer-bot", ["api"], -1000, 3600_000) } }) },
40
+ { kind: "expired-grant", automated: true, genuine: false, describes: "a trusted principal's grant whose window ended a minute ago", build: (k) => ({ headers: { "x-agent-custody-grant": grant(k.principal, "buyer-bot", ["api"], -3600_000, -60_000) } }) },
41
+ { kind: "out-of-scope-grant", automated: true, genuine: false, describes: "a trusted principal's grant for another route", build: (k) => ({ headers: { "x-agent-custody-grant": grant(k.principal, "buyer-bot", ["account"], -1000, 3600_000) } }) },
42
+ { kind: "grant-under-other-signature", automated: true, genuine: false, describes: "a valid grant for one agent, sent under another agent's verified signature", build: (k, n) => ({ headers: { ...signed(k.agent.privateKey, k.agent.x, `wrong-sender-${n}`, PATH), "x-agent-custody-grant": grant(k.principal, "buyer-bot", ["api"], -1000, 3600_000) } }) },
43
+ ];
44
+ /** Builds the test set in `dir`: `perKind` labelled arrivals of each kind, their receipts and log, and `labels.jsonl`. */
45
+ export async function buildDoorTestSet(dir, opts) {
46
+ const receiptsDir = join(dir, "receipts");
47
+ const logFile = join(dir, "log.jsonl");
48
+ mkdirSync(receiptsDir, { recursive: true });
49
+ const doorKey = generateKeyPair();
50
+ const agent = generateKeyPairSync("ed25519");
51
+ const keys = {
52
+ principal: generateKeyPair(),
53
+ stranger: generateKeyPair(),
54
+ agent: { privateKey: agent.privateKey, x: agent.publicKey.export({ format: "jwk" }).x },
55
+ impostor: generateKeyPairSync("ed25519").privateKey,
56
+ };
57
+ const directory = JSON.stringify({ keys: [{ kty: "OKP", crv: "Ed25519", x: keys.agent.x }] });
58
+ const cfg = DoorConfigSchema.parse({
59
+ identity: { keyFile: "unread" },
60
+ policyFile: "unread",
61
+ receiptsDir,
62
+ logFile,
63
+ routes: [{ name: "api", path: "/api/*", methods: ["GET"] }, { name: "account", path: "/account/*", methods: ["GET"] }],
64
+ webBotAuth: { agents: [AGENT_ORIGIN], authorities: [SITE] },
65
+ });
66
+ const stand = async (input) => {
67
+ const u = new URL(input instanceof Request ? input.url : String(input));
68
+ if (u.origin === AGENT_ORIGIN && u.pathname === DIRECTORY_PATH)
69
+ return new Response(directory, { headers: { "content-type": DIRECTORY_MEDIA_TYPE } });
70
+ return new Response(JSON.stringify({ ok: true }), { status: 200, headers: { "content-type": "application/json" } });
71
+ };
72
+ const io = {
73
+ key: doorKey,
74
+ trustedPrincipalKeys: [keys.principal],
75
+ readPolicy: () => ({ text: POLICY, key: "test-set" }),
76
+ policySource: "the test set's policy",
77
+ revoked: () => null,
78
+ secret: () => undefined,
79
+ issuer: (capture) => createIssuer(doorKey, receiptsDir, logFile, { capture }),
80
+ fetch: stand,
81
+ timers: false,
82
+ };
83
+ const core = createDoorCoreWith(cfg, io, "test-set");
84
+ const target = { url: new URL("https://origin.test"), headers: {}, timeoutMs: 5000, proto: "https" };
85
+ const send = async (headers, remote) => {
86
+ const req = { method: "GET", url: PATH, headers: { host: SITE, ...headers }, socket: { remoteAddress: remote } };
87
+ const d = await core.decide(req, randomUUID(), async () => ({ body: Buffer.alloc(0) }));
88
+ const relayed = await relayToOrigin(core, cfg, d, req, target, stand);
89
+ await core.record(d, relayed.execution);
90
+ return d.receiptId;
91
+ };
92
+ const labels = [];
93
+ try {
94
+ let i = 0;
95
+ for (const t of opts.kinds ?? DOOR_TEST_KINDS) {
96
+ for (let n = 0; n < opts.perKind; n++, i++) {
97
+ const built = t.build(keys, n);
98
+ // a documentation address per arrival, so the rate counter never ties one kind to another
99
+ const remote = `198.51.100.${i % 250}`;
100
+ if (built.prime)
101
+ await send(built.prime, remote);
102
+ labels.push({ receiptId: await send(built.headers, remote), kind: t.kind, automated: t.automated, genuine: t.genuine, source: "test-set" });
103
+ }
104
+ }
105
+ }
106
+ finally {
107
+ core.close();
108
+ }
109
+ const labelsFile = join(dir, "labels.jsonl");
110
+ writeFileSync(labelsFile, labels.map((l) => JSON.stringify(l)).join("\n") + "\n");
111
+ return { receiptsDir, logFile, labelsFile, labels, doorKey, principalKey: keys.principal };
112
+ }
113
+ /** The kinds as a Markdown table: what each arrival is, and what the labels say it is. */
114
+ export function formatTestKinds(kinds = DOOR_TEST_KINDS) {
115
+ const yes = (b) => (b === null ? "names no agent" : b ? "yes" : "no");
116
+ return ["| kind | what arrives | a program | genuine |", "| --- | --- | --- | --- |", ...kinds.map((k) => `| \`${k.kind}\` | ${k.describes} | ${k.automated ? "yes" : "no"} | ${yes(k.genuine)} |`), ""].join("\n");
117
+ }
@@ -1,6 +1,7 @@
1
1
  import { type DoorConfig } from "./config.ts";
2
2
  import { type PublicKeyRef } from "./crypto.ts";
3
3
  import { type DoorIO, type DoorRequest, type ObservedFact } from "./door-core.ts";
4
+ import type { TlsObservation } from "./door-signals.ts";
4
5
  import { type ObjectStore } from "./object-issuer.ts";
5
6
  import type { NonceStore } from "./web-bot-auth.ts";
6
7
  /** What the Worker needs of an R2 bucket binding. */
@@ -68,12 +69,20 @@ export interface DoorWorkerEnv {
68
69
  NONCES?: DurableObjectNamespaceLike;
69
70
  [binding: string]: unknown;
70
71
  }
71
- /** What a request's `cf` object may carry; only Bot Management is read, and only where the zone has it. */
72
+ /** What a request's `cf` object may carry: Bot Management, only where the zone has it, and what Cloudflare saw of the TLS handshake. */
72
73
  interface CfProperties {
73
74
  botManagement?: {
74
75
  score?: unknown;
75
76
  verifiedBot?: unknown;
77
+ ja4?: unknown;
76
78
  };
79
+ tlsVersion?: unknown;
80
+ tlsCipher?: unknown;
81
+ tlsClientExtensionsSha1?: unknown;
82
+ tlsClientHelloLength?: unknown;
83
+ httpProtocol?: unknown;
84
+ asn?: unknown;
85
+ asOrganization?: unknown;
77
86
  }
78
87
  /** the fact the Worker records when Cloudflare Bot Management scored the request */
79
88
  export declare const CLOUDFLARE_FACT = "cloudflare";
@@ -112,6 +121,12 @@ export declare function workerDoorIO(env: DoorWorkerEnv, f: typeof fetch): DoorI
112
121
  * relayed, and `cdn-loop` sent on to a subrequest would count as a loop.
113
122
  */
114
123
  export declare function doorRequestOf(request: Request): DoorRequest;
124
+ /**
125
+ * What Cloudflare saw of the client's TLS handshake, for the door's TLS fingerprint: the JA4 where the zone has Bot
126
+ * Management, and the version, the cipher, the extensions hash, and the ClientHello length that every zone gets. Only
127
+ * strings of a bounded length are taken; the door's signal code checks their shape.
128
+ */
129
+ export declare function cloudflareTls(cf: CfProperties | undefined): TlsObservation | undefined;
115
130
  /** 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
131
  export declare function cloudflareFacts(cf: CfProperties | undefined): Record<string, ObservedFact>;
117
132
  export interface DoorWorkerOptions {
@@ -49,6 +49,8 @@ export function workerDoorConfig(env) {
49
49
  const origin = (raw.origin ?? {});
50
50
  if (Object.hasOwn(origin, "url"))
51
51
  throw new Error("DOOR_CONFIG has origin.url: the origin is the ORIGIN_URL variable");
52
+ if (raw.behaviour && typeof raw.behaviour === "object" && Object.hasOwn(raw.behaviour, "tlsHeader"))
53
+ throw new Error("DOOR_CONFIG has behaviour.tlsHeader, which a Worker does not take: the Worker reads the TLS fingerprint from Cloudflare (request.cf)");
52
54
  if (raw.webBotAuth && !env.NONCES)
53
55
  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
56
  return DoorConfigSchema.parse({
@@ -169,7 +171,29 @@ export function doorRequestOf(request) {
169
171
  request.headers.forEach((v, k) => { if (!k.startsWith("cf-") && k !== "cdn-loop")
170
172
  headers[k] = v; });
171
173
  headers.host = url.host;
172
- return { method: request.method, url: url.pathname + url.search, headers, socket: { remoteAddress: request.headers.get("cf-connecting-ip") ?? undefined } };
174
+ const cf = request.cf;
175
+ const tls = cloudflareTls(cf);
176
+ // what every zone gets of the connection and of the address's network; the door's signal code checks their shape
177
+ const http = typeof cf?.httpProtocol === "string" && cf.httpProtocol.length <= 16 ? cf.httpProtocol : undefined;
178
+ const network = { ...(typeof cf?.asn === "number" ? { asn: cf.asn } : {}), ...(typeof cf?.asOrganization === "string" ? { organization: cf.asOrganization.slice(0, 256) } : {}) };
179
+ return { method: request.method, url: url.pathname + url.search, headers, transport: { secure: url.protocol === "https:", ...(tls ? { tls } : {}), ...(http ? { http } : {}), ...(Object.keys(network).length ? { network } : {}) }, socket: { remoteAddress: request.headers.get("cf-connecting-ip") ?? undefined } };
180
+ }
181
+ /**
182
+ * What Cloudflare saw of the client's TLS handshake, for the door's TLS fingerprint: the JA4 where the zone has Bot
183
+ * Management, and the version, the cipher, the extensions hash, and the ClientHello length that every zone gets. Only
184
+ * strings of a bounded length are taken; the door's signal code checks their shape.
185
+ */
186
+ export function cloudflareTls(cf) {
187
+ if (!cf || typeof cf !== "object")
188
+ return undefined;
189
+ const text = (v) => (typeof v === "string" && v !== "" && v.length <= 64 ? v : undefined);
190
+ const ja4 = text(cf.botManagement?.ja4);
191
+ const negotiated = text(cf.tlsVersion);
192
+ const cipher = text(cf.tlsCipher);
193
+ const extensionsSha1 = text(cf.tlsClientExtensionsSha1);
194
+ const length = typeof cf.tlsClientHelloLength === "number" ? cf.tlsClientHelloLength : /^\d{1,5}$/.test(text(cf.tlsClientHelloLength) ?? "") ? Number(cf.tlsClientHelloLength) : undefined;
195
+ const out = { ...(ja4 ? { ja4 } : {}), ...(negotiated ? { negotiated } : {}), ...(cipher ? { cipher } : {}), ...(extensionsSha1 ? { extensionsSha1 } : {}), ...(length !== undefined ? { helloLength: length } : {}) };
196
+ return Object.keys(out).length ? out : undefined;
173
197
  }
174
198
  /** 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
199
  export function cloudflareFacts(cf) {
@@ -228,7 +252,7 @@ export function createDoorWorker(options = {}) {
228
252
  if (request.method === "GET" && url.pathname === FORM_SCRIPT_PATH) {
229
253
  if (!cfg.challenge)
230
254
  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" } });
255
+ return new Response(formScript(cfg.challenge, !!cfg.behaviour), { headers: { "content-type": "text/javascript; charset=utf-8", "cache-control": "public, max-age=300", "x-content-type-options": "nosniff" } });
232
256
  }
233
257
  if (!core.admit())
234
258
  return answer(core.busy());
package/dist/door.js CHANGED
@@ -133,7 +133,7 @@ export async function createDoorHost(cfg, options = {}) {
133
133
  handle,
134
134
  flushOutbox: core.flushOutbox,
135
135
  pendingReceipts: core.pendingReceipts,
136
- formScript: () => (cfg.challenge ? formScript(cfg.challenge) : null),
136
+ formScript: () => (cfg.challenge ? formScript(cfg.challenge, !!cfg.behaviour) : null),
137
137
  async close() {
138
138
  core.close();
139
139
  },
@@ -178,7 +178,7 @@ function createAuthzHost(cfg, options) {
178
178
  handle,
179
179
  flushOutbox: core.flushOutbox,
180
180
  pendingReceipts: core.pendingReceipts,
181
- formScript: () => (cfg.challenge ? formScript(cfg.challenge) : null),
181
+ formScript: () => (cfg.challenge ? formScript(cfg.challenge, !!cfg.behaviour) : null),
182
182
  async close() {
183
183
  core.close();
184
184
  },
package/dist/index.d.ts CHANGED
@@ -21,6 +21,14 @@ export type { PerathosCheck, PerathosOptions, PerathosReport } from "./perathos.
21
21
  export { loadAcsGuardianConfig } from "./config.ts";
22
22
  export type { AcsGuardianConfig } from "./config.ts";
23
23
  export { FORM_SCRIPT_PATH, formScript } from "./door-form.ts";
24
+ export { FLAG_SIGNALS, FORM_REPORT_HEADER, createHistoryTracker, flagOf, observationOf, signalsOf } from "./door-signals.ts";
25
+ export type { ArrivalBehaviour, ArrivalFingerprint, FlagSignal, FormSignals, HeaderFingerprint, HistoryTracker, NavigationSignals, Observation, Signals, SourceHistory, TimingSignals, TlsFingerprint, TlsObservation } from "./door-signals.ts";
26
+ export { LABELS, LABEL_QUESTIONS, LABEL_USES, createMeasure, flagValues, formatMeasure, formatRate, intervalText, isName, labelsFromReceipts, measure, parseLabelledRecord, percent, rateOf, ratePercent, thresholds } from "./door-measure.ts";
27
+ export type { FlagMeasure, FlagValues, Label, LabelExport, LabelQuestion, LabelUse, LabelledRecord, Measure, MeasureResult, Rate, SetMeasure, SideMeasure } from "./door-measure.ts";
28
+ export { challengeLabels, DOOR_QUESTIONS, DoorLabelSchema, doorErrorRates, formatErrorRates, LABEL_SOURCES, parseLabels, readDoorArrivals, wilson } from "./door-error-rates.ts";
29
+ export type { DoorArrivals, DoorLabel, DoorQuestion, ErrorRateRow, LabelSource } from "./door-error-rates.ts";
30
+ export { buildDoorTestSet, DOOR_TEST_KINDS, formatTestKinds } from "./door-test-set.ts";
31
+ export type { DoorTestSet, TestKind } from "./door-test-set.ts";
24
32
  export type { Arrival, ArrivalChallenge, ArrivalClass, ArrivalRate, ChallengeCheck, Classified, DoorHost, DoorOptions, DoorRequest, DoorServerOptions, RateTracker, RateTrackerLimits, RunningDoor } from "./door.ts";
25
33
  export type { NonceState, NonceStore, SignatureCheck, SignedRequest, WebBotAuthOptions, WebBotAuthVerifier } from "./web-bot-auth.ts";
26
34
  export * from "./capture.ts";
package/dist/index.js CHANGED
@@ -15,6 +15,10 @@ export { ACS_ERROR, ACS_GUARDIAN_VERSION, ACS_METHODS, ACS_RECEIPT_KEY, ACS_STEP
15
15
  export { formatPerathosReport, PERATHOS_RECEIPT_V1, perathosHead, perathosReceiptHash, verifyPerathosLog } from "./perathos.js";
16
16
  export { loadAcsGuardianConfig } from "./config.js";
17
17
  export { FORM_SCRIPT_PATH, formScript } from "./door-form.js";
18
+ export { FLAG_SIGNALS, FORM_REPORT_HEADER, createHistoryTracker, flagOf, observationOf, signalsOf } from "./door-signals.js";
19
+ export { LABELS, LABEL_QUESTIONS, LABEL_USES, createMeasure, flagValues, formatMeasure, formatRate, intervalText, isName, labelsFromReceipts, measure, parseLabelledRecord, percent, rateOf, ratePercent, thresholds } from "./door-measure.js";
20
+ export { challengeLabels, DOOR_QUESTIONS, DoorLabelSchema, doorErrorRates, formatErrorRates, LABEL_SOURCES, parseLabels, readDoorArrivals, wilson } from "./door-error-rates.js";
21
+ export { buildDoorTestSet, DOOR_TEST_KINDS, formatTestKinds } from "./door-test-set.js";
18
22
  export * from "./capture.js";
19
23
  export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.js";
20
24
  export { deliverMail, founderNote, PortalStore, portalHandler, readSession, readSessionVia, sendFollowUps, servePortal, signSession, SsoRefusedError, stripeRequest, verifyStripeSignature } from "./portal.js";
package/dist/lock.d.ts CHANGED
@@ -1,3 +1,8 @@
1
+ /** Moves the lock away only if it is still the file that was judged stale. One breaker at a time holds `<lock>.break`. */
2
+ export declare function breakLock(lockFile: string, judged: {
3
+ token: string | undefined;
4
+ ino: number;
5
+ }): void;
1
6
  /**
2
7
  * Takes the lock with an exclusive create, and returns its release. The release removes the file only when it still
3
8
  * holds this call's token, so a holder whose lock was broken never removes the lock of the next holder. Returns
package/dist/lock.js CHANGED
@@ -38,7 +38,7 @@ function judge(lockFile, staleMs) {
38
38
  }
39
39
  }
40
40
  /** Moves the lock away only if it is still the file that was judged stale. One breaker at a time holds `<lock>.break`. */
41
- function breakLock(lockFile, judged) {
41
+ export function breakLock(lockFile, judged) {
42
42
  const breaker = `${lockFile}.break`;
43
43
  try {
44
44
  closeSync(openSync(breaker, "wx", 0o600));