@agent-custody/receipts 0.16.10 → 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.
Files changed (78) hide show
  1. package/README.md +32 -12
  2. package/dist/approval-requests.d.ts +114 -0
  3. package/dist/approval-requests.js +198 -0
  4. package/dist/approval.d.ts +8 -0
  5. package/dist/approval.js +10 -3
  6. package/dist/check.js +14 -0
  7. package/dist/cli.js +184 -5
  8. package/dist/completeness.d.ts +11 -2
  9. package/dist/completeness.js +45 -9
  10. package/dist/config.d.ts +6 -0
  11. package/dist/config.js +19 -1
  12. package/dist/console-page.js +87 -2
  13. package/dist/console.js +72 -0
  14. package/dist/crypto.d.ts +2 -0
  15. package/dist/crypto.js +2 -1
  16. package/dist/delegation.d.ts +1 -1
  17. package/dist/delegation.js +19 -2
  18. package/dist/did-key.d.ts +2 -0
  19. package/dist/did-key.js +21 -1
  20. package/dist/door-app.js +1 -1
  21. package/dist/door-core.d.ts +385 -0
  22. package/dist/door-core.js +757 -0
  23. package/dist/door-error-rates.d.ts +102 -0
  24. package/dist/door-error-rates.js +178 -0
  25. package/dist/door-form.d.ts +7 -2
  26. package/dist/door-form.js +52 -4
  27. package/dist/door-measure.d.ts +153 -0
  28. package/dist/door-measure.js +325 -0
  29. package/dist/door-signals.d.ts +414 -0
  30. package/dist/door-signals.js +555 -0
  31. package/dist/door-test-set.d.ts +43 -0
  32. package/dist/door-test-set.js +117 -0
  33. package/dist/door-worker.d.ts +148 -0
  34. package/dist/door-worker.js +283 -0
  35. package/dist/door.d.ts +11 -293
  36. package/dist/door.js +45 -755
  37. package/dist/gateway-http.d.ts +1 -6
  38. package/dist/gateway-http.js +2 -19
  39. package/dist/gateway.js +24 -3
  40. package/dist/grant-header.d.ts +8 -0
  41. package/dist/grant-header.js +19 -0
  42. package/dist/index.d.ts +11 -2
  43. package/dist/index.js +6 -1
  44. package/dist/issue.d.ts +2 -16
  45. package/dist/issue.js +2 -12
  46. package/dist/lock.d.ts +5 -0
  47. package/dist/lock.js +1 -1
  48. package/dist/log-http.d.ts +37 -0
  49. package/dist/log-http.js +74 -0
  50. package/dist/log-sink.d.ts +3 -37
  51. package/dist/log-sink.js +5 -71
  52. package/dist/log.d.ts +2 -27
  53. package/dist/log.js +2 -173
  54. package/dist/merkle.d.ts +27 -0
  55. package/dist/merkle.js +175 -0
  56. package/dist/object-issuer.d.ts +29 -0
  57. package/dist/object-issuer.js +172 -0
  58. package/dist/receipt-pending.d.ts +16 -0
  59. package/dist/receipt-pending.js +14 -0
  60. package/dist/web-bot-auth.d.ts +26 -6
  61. package/dist/web-bot-auth.js +116 -56
  62. package/docs/approvals.md +33 -0
  63. package/docs/completeness.md +44 -5
  64. package/docs/console.md +11 -4
  65. package/docs/door-error-rates.md +490 -0
  66. package/docs/door-languages.md +3 -1
  67. package/docs/door-middleware.md +6 -1
  68. package/docs/door-quickstart.md +53 -17
  69. package/docs/door-signals.md +117 -7
  70. package/docs/door-worker.md +94 -0
  71. package/docs/door.md +41 -12
  72. package/docs/github-action.md +2 -2
  73. package/docs/tutorials.md +6 -0
  74. package/docs/verification.md +1 -1
  75. package/package.json +4 -1
  76. package/vectors/audit.json +27 -27
  77. package/vectors/canonical.json +5 -5
  78. package/vectors/receipts.json +1645 -1549
@@ -0,0 +1,555 @@
1
+ // The door's behavioural and fingerprint signals. Each signal is a pure function of an `Observation`, the record of what
2
+ // the door saw of one arrival, and of the source's `SourceHistory`. Nothing here does I/O, so a tool can replay recorded
3
+ // observations through the same functions and measure how often each flag is wrong. A signal is not a verdict: the door
4
+ // never refuses an arrival because of one. Only the operator's policy reads them, as `context.facts.arrival.fingerprint`
5
+ // and `context.facts.arrival.behaviour`. Every number is an integer, because Cedar has no floats.
6
+ import { sha256Hex } from "./crypto.js";
7
+ /** the request header in which the form protector script sends its form report; a claim by the client */
8
+ export const FORM_REPORT_HEADER = "x-agent-custody-form";
9
+ /** how long a source's arrivals and its last page load are remembered */
10
+ export const HISTORY_WINDOW_MS = 30 * 60_000;
11
+ /** arrival times kept per source, so the timing signals read at most one gap fewer */
12
+ export const HISTORY_MAX_ARRIVALS = 17;
13
+ /** `timing.regular` needs at least this many gaps */
14
+ export const TIMING_MIN_GAPS = 5;
15
+ /** `timing.regular`: the longest gap minus the shortest gap is at most this percentage of the median gap */
16
+ export const TIMING_REGULAR_SPREAD_PERCENT = 10;
17
+ /** `timing.regular` needs a median gap of at least this; faster arrivals are a burst, which `rate` counts */
18
+ export const TIMING_REGULAR_MIN_MEDIAN_MS = 100;
19
+ /** `form.fast` needs at least this many key presses */
20
+ export const FORM_FAST_MIN_KEYS = 8;
21
+ /** `form.fast`: the fill took less than this many milliseconds for each key press */
22
+ export const FORM_FAST_MS_PER_KEY = 20;
23
+ /** a form report longer than this is malformed */
24
+ export const MAX_FORM_REPORT = 96;
25
+ /** the largest fill time a form report can state: one day */
26
+ export const MAX_FORM_FILL_MS = 86_400_000;
27
+ /** the largest event count a form report can state */
28
+ export const MAX_FORM_EVENTS = 99_999;
29
+ /** header names read from one arrival; the rest are not counted or hashed */
30
+ export const MAX_HEADER_NAMES = 128;
31
+ /** a header name longer than this is cut */
32
+ export const MAX_HEADER_NAME_LENGTH = 64;
33
+ /** the User-Agent is read up to this length */
34
+ export const MAX_USER_AGENT = 512;
35
+ /** a TLS fingerprint value longer than this is cut, and is then malformed */
36
+ export const MAX_TLS_VALUE = 64;
37
+ /** the first major version of each browser family that sends `sec-fetch-site`, `sec-fetch-mode`, and `sec-fetch-dest` on every request to an https site */
38
+ export const SEC_FETCH_SINCE = { chromium: 80, firefox: 90, safari: 17 };
39
+ /** the Chromium major version from which `headers.mismatch` expects `sec-ch-ua` on every request to an https site */
40
+ export const SEC_CH_UA_SINCE = 100;
41
+ /** the major version of each browser family from which `tls.mismatch` expects TLS 1.3 and ALPN in the ClientHello */
42
+ export const TLS13_SINCE = { chromium: 70, firefox: 63, safari: 13 };
43
+ /** the header that every browser family sends on every request */
44
+ export const BROWSER_HEADERS = ["accept-language"];
45
+ /** the header that a browser from `SEC_FETCH_SINCE` sends on every POST, PUT, PATCH, and DELETE; its value can be `null` */
46
+ export const WRITE_HEADERS = ["origin"];
47
+ /** the `sec-fetch-dest` values of a navigation; `sec-fetch-mode: navigate` with another one is not a browser's */
48
+ export const NAVIGATE_DESTS = new Set(["document", "iframe", "frame", "embed", "object", "fencedframe"]);
49
+ /** how long `fingerprint.seen` counts arrivals with the same fingerprint */
50
+ export const SEEN_WINDOW_MS = 60_000;
51
+ /** a `sec-ch-ua` value is read up to this length */
52
+ export const MAX_CLIENT_HINT = 256;
53
+ export const SEC_FETCH_HEADERS = ["sec-fetch-site", "sec-fetch-mode", "sec-fetch-dest"];
54
+ /**
55
+ * Only the JA4 TLS client fingerprint is used here and in scripts/ja4.ts: it is BSD-3-Clause. JA4H, JA4S, JA4T, and
56
+ * the rest of JA4+ are under the FoxIO License 1.1, which restricts commercial use, so the header fingerprint is the
57
+ * door's own hash and not JA4H.
58
+ *
59
+ * JA4 fingerprints of known tools, each with the tool's family. Every value was recorded by the labelled capture
60
+ * (scripts/door-capture.ts, labelled/capture.meta.json), never taken from memory. A fingerprint belongs to one build of
61
+ * the tool's TLS library, so another version of the tool can have another fingerprint, and the table misses it.
62
+ */
63
+ export const KNOWN_TOOL_JA4 = new Map([
64
+ ["t13d4907h2_0d8feac7bc37_7395dae3b2f3", "curl"],
65
+ ["t13d171100_ab0a1bf427ad_e44827223d20", "python"],
66
+ ["t13d1912h2_9dc949149365_e5728521abd4", "go"],
67
+ ["t13d5212h1_b262b3658495_8e6e362c5eac", "node"],
68
+ // the same client when it resumes a session
69
+ ["t13d5213h1_b262b3658495_66863fb0a24c", "node"],
70
+ ["t13d1713h1_5b57614c22b0_6a3d802a7139", "bun"],
71
+ ]);
72
+ const one = (v, max) => {
73
+ const s = Array.isArray(v) ? v.join(", ") : v;
74
+ return typeof s === "string" && s !== "" ? s.slice(0, max) : undefined;
75
+ };
76
+ const lastOf = (v) => v?.split(",").pop()?.trim().toLowerCase() || undefined;
77
+ // a host without the default port of https or http, as `normalizeAuthority` of web-bot-auth.ts gives it
78
+ const authority = (host) => host.trim().toLowerCase().replace(/:(443|80)$/, "");
79
+ /**
80
+ * The relation of a `Referer` to the host that the request names. The scheme is not compared, because the door does
81
+ * not always know it, so a default port on one side and none on the other is the same host.
82
+ */
83
+ export function refererRelation(referer, host) {
84
+ if (!referer)
85
+ return "absent";
86
+ try {
87
+ return host !== undefined && authority(new URL(referer).host) === authority(host) ? "same-origin" : "cross-origin";
88
+ }
89
+ catch {
90
+ return "cross-origin";
91
+ }
92
+ }
93
+ /**
94
+ * The observation of one request. Every value is cut to a fixed length, so a hostile header cannot make it large. The
95
+ * TLS fingerprint comes from `transport`, or from `tlsHeader` when `trustProxy` is set; without both, a header that
96
+ * names a fingerprint is the client's word and is not read.
97
+ */
98
+ export function observationOf(req, at, method, path, opts = {}) {
99
+ const h = req.headers;
100
+ const tlsHeader = opts.trustProxy ? opts.tlsHeader?.toLowerCase() : undefined;
101
+ const own = new Set([...(opts.own ?? []), ...(opts.tlsHeader ? [opts.tlsHeader] : [])].map((n) => n.toLowerCase()));
102
+ let headers;
103
+ if (!opts.partialHeaders) {
104
+ const raw = req.rawHeaders;
105
+ const names = [];
106
+ const all = raw ? raw.filter((_, i) => i % 2 === 0) : Object.keys(h).filter((k) => h[k] !== undefined);
107
+ for (const name of all) {
108
+ if (names.length >= MAX_HEADER_NAMES)
109
+ break;
110
+ const n = String(name).toLowerCase().slice(0, MAX_HEADER_NAME_LENGTH);
111
+ if (!n.startsWith("x-agent-custody-") && !own.has(n))
112
+ names.push(n);
113
+ }
114
+ headers = { names, ordered: !!raw };
115
+ }
116
+ const forwardedProto = opts.trustProxy ? lastOf(one(h["x-forwarded-proto"], 64)) : undefined;
117
+ const secure = req.transport?.secure ?? (forwardedProto === "https" ? true : undefined);
118
+ const host = (opts.trustProxy ? lastOf(one(h["x-forwarded-host"], 512)) : undefined) ?? one(h.host, 512);
119
+ const headerJa4 = tlsHeader ? one(h[tlsHeader], MAX_TLS_VALUE + 1) : undefined;
120
+ const tls = headerJa4 !== undefined ? { ja4: headerJa4 } : req.transport?.tls;
121
+ const userAgent = one(h["user-agent"], MAX_USER_AGENT);
122
+ const accept = one(h.accept, 256);
123
+ const site = one(h["sec-fetch-site"], 32);
124
+ const mode = one(h["sec-fetch-mode"], 32);
125
+ const dest = one(h["sec-fetch-dest"], 32);
126
+ const user = one(h["sec-fetch-user"], 32);
127
+ const clientHints = one(h["sec-ch-ua"], MAX_CLIENT_HINT);
128
+ const { http, network } = req.transport ?? {};
129
+ const form = one(h[FORM_REPORT_HEADER], MAX_FORM_REPORT + 1);
130
+ return {
131
+ at,
132
+ method: method.toUpperCase().slice(0, 16),
133
+ path: path.slice(0, 2048),
134
+ ...(headers ? { headers } : {}),
135
+ ...(secure !== undefined ? { secure } : {}),
136
+ ...(userAgent !== undefined ? { userAgent } : {}),
137
+ ...(accept !== undefined ? { accept } : {}),
138
+ referer: refererRelation(one(h.referer, 2048), host),
139
+ origin: refererRelation(one(h.origin, 2048), host),
140
+ secFetch: { ...(site !== undefined ? { site } : {}), ...(mode !== undefined ? { mode } : {}), ...(dest !== undefined ? { dest } : {}), ...(user !== undefined ? { user } : {}) },
141
+ ...(clientHints !== undefined ? { clientHints } : {}),
142
+ ...(http !== undefined ? { http } : {}),
143
+ ...(network ? { network } : {}),
144
+ ...(tls ? { tls } : {}),
145
+ ...(form !== undefined ? { form } : {}),
146
+ };
147
+ }
148
+ /** the methods that `directWrite` and the `origin` rule read as a write */
149
+ export const STATE_CHANGING = new Set(["POST", "PUT", "PATCH", "DELETE"]);
150
+ /**
151
+ * AI agents that name themselves in the User-Agent, by product token. Each entry is from the vendor's own page, read on
152
+ * 2026-11-23, and never from memory. A token that a vendor documents for another purpose (an ads check, a crawl that the
153
+ * site owner asked for) is not here, and reads as a crawler. A claim: any client can send any of these names.
154
+ */
155
+ export const AI_AGENTS = new Map([
156
+ // https://developers.openai.com/api/docs/bots
157
+ ["GPTBot", { vendor: "openai", purpose: "training" }],
158
+ ["OAI-SearchBot", { vendor: "openai", purpose: "search" }],
159
+ ["ChatGPT-User", { vendor: "openai", purpose: "user" }],
160
+ // https://support.claude.com/en/articles/8896518-does-anthropic-crawl-data-from-the-web-and-how-can-site-owners-block-the-crawler
161
+ ["ClaudeBot", { vendor: "anthropic", purpose: "training" }],
162
+ ["Claude-SearchBot", { vendor: "anthropic", purpose: "search" }],
163
+ ["Claude-User", { vendor: "anthropic", purpose: "user" }],
164
+ // https://docs.perplexity.ai/guides/bots
165
+ ["PerplexityBot", { vendor: "perplexity", purpose: "search" }],
166
+ ["Perplexity-User", { vendor: "perplexity", purpose: "user" }],
167
+ // https://developers.google.com/search/docs/crawling-indexing/google-user-triggered-fetchers
168
+ ["Google-GeminiNotebook", { vendor: "google", purpose: "user" }],
169
+ ["Google-Agent", { vendor: "google", purpose: "user" }],
170
+ ]);
171
+ const AI_AGENT = new RegExp(`(?<![A-Za-z0-9-])(${[...AI_AGENTS.keys()].join("|")})(?![A-Za-z0-9-])`);
172
+ const TOOLS = [
173
+ [/HeadlessChrome\//, "headless-chrome"],
174
+ // a crawler names itself as a product token or gives its page; a phone model can hold "bot"
175
+ [/(?:bot|crawler|spider)\/|\+https?:/i, "crawler"],
176
+ [/^curl\//i, "curl"],
177
+ [/^wget\//i, "wget"],
178
+ [/^python-requests\//i, "python-requests"],
179
+ [/^python-urllib\//i, "python-urllib"],
180
+ [/^python-httpx\//i, "python-httpx"],
181
+ [/aiohttp\//i, "aiohttp"],
182
+ [/^go-http-client\//i, "go-http-client"],
183
+ [/^(node|node-fetch|undici)\b/i, "node"],
184
+ [/^axios\//i, "axios"],
185
+ [/^okhttp\//i, "okhttp"],
186
+ [/^(java|apache-httpclient)\//i, "java"],
187
+ [/^postmanruntime\//i, "postman"],
188
+ ];
189
+ /**
190
+ * The client family that the User-Agent states. A browser on iOS is `safari` whatever its name, because it runs
191
+ * WebKit; without a `Version/` token its version is unknown, and the rules that depend on a version do not apply.
192
+ */
193
+ export function statedClient(userAgent) {
194
+ const ua = (userAgent ?? "").slice(0, MAX_USER_AGENT).trim();
195
+ if (!ua)
196
+ return { kind: "unstated", family: "unstated" };
197
+ const agent = AI_AGENT.exec(ua);
198
+ if (agent)
199
+ return { kind: "agent", family: agent[1].toLowerCase(), ...AI_AGENTS.get(agent[1]) };
200
+ for (const [pattern, family] of TOOLS)
201
+ if (pattern.test(ua))
202
+ return { kind: "tool", family };
203
+ if (!ua.startsWith("Mozilla/5.0 "))
204
+ return { kind: "other", family: "other" };
205
+ const major = (pattern) => {
206
+ const m = pattern.exec(ua);
207
+ return m ? { version: Number(m[1]) } : {};
208
+ };
209
+ if (/(CriOS|FxiOS|EdgiOS)\//.test(ua))
210
+ return { kind: "browser", family: "safari", ...major(/Version\/(\d{1,4})/) };
211
+ if (/(Chrome|Chromium)\/\d/.test(ua))
212
+ return { kind: "browser", family: "chromium", ...major(/(?:Chrome|Chromium)\/(\d{1,4})/) };
213
+ if (ua.includes("Gecko/") && /Firefox\/\d/.test(ua))
214
+ return { kind: "browser", family: "firefox", ...major(/Firefox\/(\d{1,4})/) };
215
+ if (ua.includes("AppleWebKit/") && ua.includes("Safari/"))
216
+ return { kind: "browser", family: "safari", ...major(/Version\/(\d{1,4})/) };
217
+ return { kind: "other", family: "other" };
218
+ }
219
+ /**
220
+ * Chromium inside an application: it does not always send client hints, so `sec-ch-ua` is not expected. A false flag on
221
+ * a real browser costs more than a missed program, so a doubtful form is in this list. The forms: an Android WebView
222
+ * (`; wv)`), a WebView browser that drops that token (`Version/4.0 Chrome/110`), Electron, a browser that says it is
223
+ * like Chrome (Silk's `like Chrome/120`), and an application that names itself before `Chrome/`
224
+ * (`Claude/4.4212.0 Chrome/152.0.7977.167`). For the last form, the header model that scripts/door-rule-check.ts reads
225
+ * has such User-Agents, and none of their requests has `sec-ch-ua`.
226
+ */
227
+ const EMBEDDED_CHROMIUM = /; wv\)|Electron\/|Version\/\d{1,4}\.\d{1,4} Chrome\/|like Chrome\/|\(KHTML, like Gecko\) (?!Chrome\/|HeadlessChrome\/|Version\/)[^\s/]{1,64}\/\S{1,64} Chrome\//;
228
+ /**
229
+ * The header fingerprint. `mismatch` reads only rules that hold for every request of a browser family, so that a real
230
+ * browser is not flagged: `accept-language` always, and, when the host knows that the client used https, `sec-fetch-*`
231
+ * and (Chromium) `sec-ch-ua` from the versions in `SEC_FETCH_SINCE` and `SEC_CH_UA_SINCE`. Browsers send these only to
232
+ * an https site. On a write, a browser from `SEC_FETCH_SINCE` also sends `origin`, to any site. For an OPTIONS request and an upgrade, only `accept-language` is checked. A proxy in front of the door that drops one of
233
+ * these headers makes every browser a mismatch: the door records what it received.
234
+ */
235
+ export function headerFingerprint(o) {
236
+ const c = statedClient(o.userAgent);
237
+ const out = { client: c.kind, family: c.family, ...(c.version !== undefined ? { version: c.version } : {}), ...(c.vendor !== undefined ? { vendor: c.vendor, purpose: c.purpose } : {}), mismatch: false, hintsMismatch: false, fetchInvalid: false };
238
+ const http = typeof o.http === "string" ? /^HTTP\/(1\.0|1\.1|2|3)$/.exec(o.http) : null;
239
+ if (http)
240
+ out.http = http[1];
241
+ // A Chromium that is given another User-Agent keeps its own `sec-ch-ua`, so the two can name different browsers.
242
+ // The rule reads no brand name: in the labelled capture, headless Chrome sends the brands of Chrome.
243
+ if (typeof o.clientHints === "string") {
244
+ const version = /"Chromium";\s*v="(\d{1,4})"/.exec(o.clientHints.slice(0, MAX_CLIENT_HINT));
245
+ out.hints = version ? { version: Number(version[1]) } : {};
246
+ // Firefox and Safari send no `sec-ch-ua`; a Chromium sends the major version that its User-Agent states
247
+ out.hintsMismatch = c.kind === "browser" && (c.family !== "chromium" || (out.hints.version !== undefined && c.version !== undefined && out.hints.version !== c.version));
248
+ }
249
+ // From the Fetch Metadata specification, not from data: `sec-fetch-user` is sent only on a navigation, and a
250
+ // navigation has a document destination. `sec-fetch-site: none` on a write is not in the rule, because a browser
251
+ // extension sends it.
252
+ const fetchMode = o.secFetch?.mode?.toLowerCase();
253
+ const fetchDest = o.secFetch?.dest?.toLowerCase();
254
+ out.fetchInvalid = (o.secFetch?.user !== undefined && fetchMode !== "navigate") || (fetchMode === "navigate" && fetchDest !== undefined && !NAVIGATE_DESTS.has(fetchDest));
255
+ if (!o.headers)
256
+ return out;
257
+ const names = o.headers.names.slice(0, MAX_HEADER_NAMES).map((n) => String(n).toLowerCase().slice(0, MAX_HEADER_NAME_LENGTH));
258
+ if (o.headers.ordered)
259
+ out.order = sha256Hex(names.join("\n")).slice(0, 16);
260
+ out.count = names.length;
261
+ if (c.kind !== "browser")
262
+ return out;
263
+ const family = c.family;
264
+ const version = c.version ?? 0;
265
+ const present = new Set(names);
266
+ const expected = [...BROWSER_HEADERS];
267
+ if (STATE_CHANGING.has(o.method) && version >= SEC_FETCH_SINCE[family])
268
+ expected.push(...WRITE_HEADERS);
269
+ if (o.secure === true && o.method !== "OPTIONS" && !present.has("upgrade")) {
270
+ if (version >= SEC_FETCH_SINCE[family])
271
+ expected.push(...SEC_FETCH_HEADERS);
272
+ if (family === "chromium" && version >= SEC_CH_UA_SINCE && !EMBEDDED_CHROMIUM.test(o.userAgent ?? ""))
273
+ expected.push("sec-ch-ua");
274
+ }
275
+ const missing = expected.filter((n) => !present.has(n));
276
+ if (missing.length) {
277
+ out.mismatch = true;
278
+ out.missing = missing.join(" ");
279
+ }
280
+ return out;
281
+ }
282
+ // section a of a JA4: protocol, TLS version, SNI, cipher count, extension count, first ALPN; then two truncated hashes
283
+ const JA4 = /^([tqd])(13|12|11|10|s3|s2|d1|d2|d3|00)([di])(\d\d)(\d\d)([0-9A-Za-z]{2})_[0-9a-f]{12}_[0-9a-f]{12}$/;
284
+ const NEGOTIATED = { "TLSv1.3": "13", "TLSv1.2": "12", "TLSv1.1": "11", TLSv1: "10", SSLv3: "s3" };
285
+ const PROTOCOLS = { t: "tcp", q: "quic", d: "dtls" };
286
+ /**
287
+ * The TLS fingerprint, or undefined when the host gave nothing that has the right shape. `mismatch` needs no
288
+ * fingerprint database: a browser at or after `TLS13_SINCE` offers TLS 1.3 and sends ALPN, and the first section of a
289
+ * JA4 states both. A TLS-inspecting proxy between the person and the site (a company network, some antivirus products)
290
+ * sends its own ClientHello, so a real browser behind one can be a mismatch.
291
+ */
292
+ export function tlsFingerprint(o) {
293
+ const t = o.tls;
294
+ if (!t || typeof t !== "object")
295
+ return undefined;
296
+ const out = { malformed: false, mismatch: false, knownTool: false };
297
+ let seen = false;
298
+ if (t.ja4 !== undefined) {
299
+ seen = true;
300
+ const m = typeof t.ja4 === "string" && t.ja4.length <= MAX_TLS_VALUE ? JA4.exec(t.ja4) : null;
301
+ if (!m)
302
+ out.malformed = true;
303
+ else {
304
+ out.ja4 = m[0];
305
+ out.protocol = PROTOCOLS[m[1]];
306
+ out.version = m[2];
307
+ out.sni = m[3] === "d";
308
+ out.ciphers = Number(m[4]);
309
+ out.extensions = Number(m[5]);
310
+ out.alpn = m[6];
311
+ const c = statedClient(o.userAgent);
312
+ out.mismatch = c.kind === "browser" && c.version !== undefined && c.version >= TLS13_SINCE[c.family] && m[1] === "t" && (m[2] !== "13" || m[6] === "00");
313
+ out.knownTool = KNOWN_TOOL_JA4.has(m[0]);
314
+ }
315
+ }
316
+ if (typeof t.negotiated === "string" && Object.hasOwn(NEGOTIATED, t.negotiated)) {
317
+ seen = true;
318
+ out.negotiated = NEGOTIATED[t.negotiated];
319
+ }
320
+ if (typeof t.cipher === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(t.cipher)) {
321
+ seen = true;
322
+ out.cipher = t.cipher;
323
+ }
324
+ if (typeof t.extensionsSha1 === "string" && /^[A-Za-z0-9+/]{27}=$/.test(t.extensionsSha1)) {
325
+ seen = true;
326
+ out.extensionsSha1 = t.extensionsSha1;
327
+ }
328
+ if (Number.isSafeInteger(t.helloLength) && t.helloLength >= 0 && t.helloLength <= 65_535) {
329
+ seen = true;
330
+ out.helloLength = t.helloLength;
331
+ }
332
+ return seen ? out : undefined;
333
+ }
334
+ /**
335
+ * The key of an unverified source in the history: the address, and for IPv6 its /64, because one client uses many
336
+ * addresses of its /64 (privacy extensions). An IPv4-mapped address and anything that is not an IPv6 address stay as
337
+ * they are. The door keys by address alone, not by address and User-Agent: a client that changes its User-Agent would
338
+ * else look new each time. So clients behind one address (NAT) share one history.
339
+ */
340
+ export function historySource(address) {
341
+ const a = address.trim().toLowerCase().replace(/%.*$/, "");
342
+ if (!a.includes(":") || a.includes(".") || !/^[0-9a-f:]{2,39}$/.test(a))
343
+ return address;
344
+ const [head, tail, more] = a.split("::");
345
+ if (more !== undefined)
346
+ return address;
347
+ const left = head ? head.split(":") : [];
348
+ const right = tail ? tail.split(":") : [];
349
+ const groups = tail === undefined ? left : [...left, ...Array(Math.max(0, 8 - left.length - right.length)).fill("0"), ...right];
350
+ if (groups.length !== 8 || groups.some((g) => !/^[0-9a-f]{1,4}$/.test(g)))
351
+ return address;
352
+ return `${groups.slice(0, 4).map((g) => g.replace(/^0+(?=.)/, "")).join(":")}::/64`;
353
+ }
354
+ /** True when the arrival loads an HTML document: a GET that names `document` in `sec-fetch-dest`, or without that header accepts `text/html`. */
355
+ export function isPageLoad(o) {
356
+ if (o.method !== "GET")
357
+ return false;
358
+ const dest = o.secFetch?.dest;
359
+ return typeof dest === "string" ? dest.toLowerCase() === "document" : typeof o.accept === "string" && o.accept.toLowerCase().includes("text/html");
360
+ }
361
+ /**
362
+ * Keeps each source's history, with the same limits style as the rate tracker: at most `maxSources` keys, none longer
363
+ * than `maxKeyLength`, the least recently seen forgotten first, at most `HISTORY_MAX_ARRIVALS` times per source, and
364
+ * nothing older than `HISTORY_WINDOW_MS`. One process's memory: the history starts empty when the door starts, two doors
365
+ * do not share it, and in a Worker each isolate has its own. A source forgotten early starts again, so a client that
366
+ * sends from many new addresses can make another source look new. The time is `Observation.at`; a time that goes back
367
+ * is held at the last time seen. No timer runs: stale sources are dropped from `record`, at most once a minute.
368
+ */
369
+ export function createHistoryTracker(limits = {}) {
370
+ const maxSources = Math.max(1, limits.maxSources ?? 10_000);
371
+ const maxKeyLength = limits.maxKeyLength ?? 256;
372
+ // least recently seen first: a record moves its key to the end
373
+ const seen = new Map();
374
+ let last = -Infinity;
375
+ let swept = -Infinity;
376
+ return {
377
+ record(source, o) {
378
+ const key = source.length > maxKeyLength ? `sha256:${sha256Hex(source)}` : source;
379
+ const t = (last = Math.max(last, Number.isFinite(o.at) ? Math.floor(o.at) : 0));
380
+ const cutoff = t - HISTORY_WINDOW_MS;
381
+ if (t - swept >= 60_000) {
382
+ swept = t;
383
+ for (const [k, v] of seen)
384
+ if (v.times[v.times.length - 1] <= cutoff)
385
+ seen.delete(k);
386
+ }
387
+ const prior = seen.get(key);
388
+ const times = (prior?.times ?? []).filter((x) => x > cutoff);
389
+ times.push(t);
390
+ if (times.length > HISTORY_MAX_ARRIVALS)
391
+ times.splice(0, times.length - HISTORY_MAX_ARRIVALS);
392
+ const pageAt = prior?.pageAt !== undefined && prior.pageAt > cutoff ? prior.pageAt : undefined;
393
+ const page = isPageLoad(o);
394
+ const now = page ? t : pageAt;
395
+ const subresources = pageAt !== undefined ? (prior?.subresources ?? 0) : undefined;
396
+ const next = page ? 0 : subresources !== undefined ? Math.min(HISTORY_MAX_ARRIVALS, subresources + (o.method === "GET" ? 1 : 0)) : undefined;
397
+ seen.delete(key);
398
+ seen.set(key, { times, ...(now !== undefined ? { pageAt: now } : {}), ...(next !== undefined ? { subresources: next } : {}) });
399
+ while (seen.size > maxSources)
400
+ seen.delete(seen.keys().next().value);
401
+ return { times: [...times], ...(pageAt !== undefined ? { pageAt, subresources: subresources } : {}) };
402
+ },
403
+ size: () => seen.size,
404
+ };
405
+ }
406
+ /**
407
+ * The pace of the source. `regular` is true when there are at least `TIMING_MIN_GAPS` gaps, the median gap is at least
408
+ * `TIMING_REGULAR_MIN_MEDIAN_MS`, and the longest gap minus the shortest is at most `TIMING_REGULAR_SPREAD_PERCENT` of
409
+ * the median. A page that polls on a timer in a person's browser is regular too.
410
+ */
411
+ export function timingSignals(history) {
412
+ const times = (Array.isArray(history?.times) ? history.times : []).slice(-HISTORY_MAX_ARRIVALS);
413
+ const gaps = [];
414
+ for (let i = 1; i < times.length; i++) {
415
+ const gap = Math.floor(times[i] - times[i - 1]);
416
+ gaps.push(Number.isFinite(gap) && gap > 0 ? gap : 0);
417
+ }
418
+ if (gaps.length === 0)
419
+ return { gaps: 0, regular: false };
420
+ gaps.sort((a, b) => a - b);
421
+ const mid = gaps.length >> 1;
422
+ const median = gaps.length % 2 ? gaps[mid] : Math.floor((gaps[mid - 1] + gaps[mid]) / 2);
423
+ const spread = gaps[gaps.length - 1] - gaps[0];
424
+ const regular = gaps.length >= TIMING_MIN_GAPS && median >= TIMING_REGULAR_MIN_MEDIAN_MS && spread * 100 <= median * TIMING_REGULAR_SPREAD_PERCENT;
425
+ return { gaps: gaps.length, medianGapMs: median, minGapMs: gaps[0], maxGapMs: gaps[gaps.length - 1], regular };
426
+ }
427
+ const token = (v) => (typeof v !== "string" ? undefined : /^[a-z-]{1,24}$/.test(v.toLowerCase()) ? v.toLowerCase() : "other");
428
+ /**
429
+ * How the arrival fits the source's navigation. `directWrite` is true for every API client that never loads a page,
430
+ * a verified agent included. A person whose page load came from another address, another door process, or before the
431
+ * window is not flagged when the browser sends a same-origin `Referer`, a same-origin `Origin`, or
432
+ * `Sec-Fetch-Site: same-origin`; a site with `Referrer-Policy: no-referrer` still gets the last. The three headers are
433
+ * the client's word: a program can send them. A program that loads the page first is not flagged; `sincePageMs` is
434
+ * then the time that it took to read and fill the page.
435
+ */
436
+ export function navigationSignals(o, history) {
437
+ const pageAt = history?.pageAt;
438
+ const pageLoaded = typeof pageAt === "number" && o.at - pageAt <= HISTORY_WINDOW_MS;
439
+ const relation = (v) => (v === "same-origin" || v === "cross-origin" ? v : "absent");
440
+ const referer = relation(o.referer);
441
+ const origin = relation(o.origin);
442
+ const since = pageLoaded ? Math.floor(o.at - pageAt) : NaN;
443
+ const subresources = history?.subresources;
444
+ const site = token(o.secFetch?.site);
445
+ const mode = token(o.secFetch?.mode);
446
+ const dest = token(o.secFetch?.dest);
447
+ return {
448
+ pageLoaded,
449
+ ...(Number.isFinite(since) && since >= 0 ? { sincePageMs: since } : {}),
450
+ ...(pageLoaded && Number.isSafeInteger(subresources) && subresources >= 0 ? { subresources: Math.min(subresources, HISTORY_MAX_ARRIVALS) } : {}),
451
+ referer,
452
+ origin,
453
+ ...(site !== undefined ? { site } : {}),
454
+ ...(mode !== undefined ? { mode } : {}),
455
+ ...(dest !== undefined ? { dest } : {}),
456
+ directWrite: STATE_CHANGING.has(o.method) && !pageLoaded && referer !== "same-origin" && origin !== "same-origin" && site !== "same-origin",
457
+ };
458
+ }
459
+ const FORM_REPORT = /^v=2;ms=(\d{1,8});k=(\d{1,5});p=(\d{1,5});paste=([01]);trusted=([01]);mv=(\d{1,5});ks=(\d{1,8});rd=(\d{1,8})$/;
460
+ /** The form report from its header value, or null when the value is not exactly a report: its length, its fields, and its ranges are fixed. */
461
+ export function parseFormReport(value) {
462
+ if (typeof value !== "string" || value.length > MAX_FORM_REPORT)
463
+ return null;
464
+ const m = FORM_REPORT.exec(value);
465
+ if (!m)
466
+ return null;
467
+ const fillMs = Number(m[1]);
468
+ const [keySpreadMs, readyMs] = [Number(m[7]), Number(m[8])];
469
+ if (fillMs > MAX_FORM_FILL_MS || keySpreadMs > MAX_FORM_FILL_MS || readyMs > MAX_FORM_FILL_MS)
470
+ return null;
471
+ return { fillMs, keys: Number(m[2]), pointers: Number(m[3]), pasted: m[4] === "1", trusted: m[5] === "1", moves: Number(m[6]), keySpreadMs, readyMs };
472
+ }
473
+ /**
474
+ * What the form report says, or undefined when the arrival sent none. A claim by the client: a program can send any
475
+ * report, so the flags catch only a client that runs the script and does not act as a person does. `fast` is true when
476
+ * there are at least `FORM_FAST_MIN_KEYS` key presses and the fill took less than `FORM_FAST_MS_PER_KEY` for each; a
477
+ * device that types for a person (a security key, a scanner) is fast too. `noInput` is true when there is no key press
478
+ * and no pointer press. A malformed report sets no flag.
479
+ */
480
+ export function formSignals(o) {
481
+ if (o.form === undefined)
482
+ return undefined;
483
+ const r = parseFormReport(o.form);
484
+ if (!r)
485
+ return { report: "malformed", fast: false, noInput: false };
486
+ return { report: "claimed", ...r, fast: r.keys >= FORM_FAST_MIN_KEYS && r.fillMs < r.keys * FORM_FAST_MS_PER_KEY, noInput: r.keys === 0 && r.pointers === 0 };
487
+ }
488
+ /** The key of `fingerprint.seen`: the JA4 and the header order. Undefined when the arrival has neither. */
489
+ export function fingerprintKey(f) {
490
+ return f.tls?.ja4 === undefined && f.headers.order === undefined ? undefined : `${f.tls?.ja4 ?? ""}|${f.headers.order ?? ""}`;
491
+ }
492
+ /**
493
+ * Counts arrivals for each fingerprint across sources, so that a client that changes its address and keeps its TLS
494
+ * stack and header order is still counted as one. One process's memory, with the limits of the history: at most
495
+ * `maxKeys` fingerprints, the least recently seen forgotten first, and at most `maxPerKey` times for each, so the
496
+ * count stops there.
497
+ */
498
+ export function createSeenCounter(limits = {}) {
499
+ const maxKeys = Math.max(1, limits.maxKeys ?? 10_000);
500
+ const maxPerKey = Math.max(1, limits.maxPerKey ?? 1_000);
501
+ const seen = new Map();
502
+ let last = -Infinity;
503
+ return {
504
+ hit(key, at) {
505
+ const t = (last = Math.max(last, Number.isFinite(at) ? Math.floor(at) : 0));
506
+ const times = (seen.get(key) ?? []).filter((x) => x > t - SEEN_WINDOW_MS);
507
+ times.push(t);
508
+ if (times.length > maxPerKey)
509
+ times.splice(0, times.length - maxPerKey);
510
+ seen.delete(key);
511
+ seen.set(key, times);
512
+ while (seen.size > maxKeys)
513
+ seen.delete(seen.keys().next().value);
514
+ return times.length;
515
+ },
516
+ size: () => seen.size,
517
+ };
518
+ }
519
+ function networkOf(o) {
520
+ const n = o.network;
521
+ if (!n || typeof n !== "object")
522
+ return undefined;
523
+ const asn = Number.isSafeInteger(n.asn) && n.asn > 0 && n.asn <= 4_294_967_295 ? n.asn : undefined;
524
+ const organization = typeof n.organization === "string" && n.organization.trim() ? n.organization.trim().slice(0, 64) : undefined;
525
+ return asn === undefined && organization === undefined ? undefined : { ...(asn !== undefined ? { asn } : {}), ...(organization !== undefined ? { organization } : {}) };
526
+ }
527
+ /** Every signal of one arrival, from its observation and the history that `HistoryTracker.record` returned for it. */
528
+ export function signalsOf(o, history) {
529
+ const tls = tlsFingerprint(o);
530
+ const form = formSignals(o);
531
+ const network = networkOf(o);
532
+ return {
533
+ fingerprint: { headers: headerFingerprint(o), ...(tls ? { tls } : {}), ...(network ? { network } : {}) },
534
+ behaviour: { timing: timingSignals(history), navigation: navigationSignals(o, history), ...(form ? { form } : {}) },
535
+ };
536
+ }
537
+ /** The boolean signals that mark an arrival, by their path in the arrival fact. */
538
+ export const FLAG_SIGNALS = [
539
+ "fingerprint.headers.mismatch",
540
+ "fingerprint.headers.hintsMismatch",
541
+ "fingerprint.headers.fetchInvalid",
542
+ "fingerprint.tls.mismatch",
543
+ "fingerprint.tls.knownTool",
544
+ "behaviour.timing.regular",
545
+ "behaviour.navigation.directWrite",
546
+ "behaviour.form.fast",
547
+ "behaviour.form.noInput",
548
+ ];
549
+ /** The value of a flag in the signals, or undefined when its group is absent (no TLS fingerprint, no form report). */
550
+ export function flagOf(signals, name) {
551
+ let at = signals;
552
+ for (const part of name.split("."))
553
+ at = at && typeof at === "object" ? at[part] : undefined;
554
+ return typeof at === "boolean" ? at : undefined;
555
+ }
@@ -0,0 +1,43 @@
1
+ import { type KeyObject } from "node:crypto";
2
+ import { type KeyPair } from "./crypto.ts";
3
+ import type { DoorLabel } from "./door-error-rates.ts";
4
+ interface Keys {
5
+ principal: KeyPair;
6
+ stranger: KeyPair;
7
+ agent: {
8
+ privateKey: KeyObject;
9
+ x: string;
10
+ };
11
+ impostor: KeyObject;
12
+ }
13
+ /** One kind of arrival: what it really is, and how to build one. `prime` runs first and is not labelled. */
14
+ export interface TestKind {
15
+ kind: string;
16
+ automated: boolean;
17
+ genuine: boolean | null;
18
+ describes: string;
19
+ build: (k: Keys, n: number) => {
20
+ headers: Record<string, string>;
21
+ prime?: Record<string, string>;
22
+ };
23
+ }
24
+ /** The kinds in the published test set, in the order the page lists them. */
25
+ export declare const DOOR_TEST_KINDS: TestKind[];
26
+ export interface DoorTestSet {
27
+ receiptsDir: string;
28
+ logFile: string;
29
+ labelsFile: string;
30
+ labels: DoorLabel[];
31
+ /** the door's key; its public half verifies every receipt in the set */
32
+ doorKey: KeyPair;
33
+ /** the trusted principal's key, which signs the granted agents' grants */
34
+ principalKey: KeyPair;
35
+ }
36
+ /** Builds the test set in `dir`: `perKind` labelled arrivals of each kind, their receipts and log, and `labels.jsonl`. */
37
+ export declare function buildDoorTestSet(dir: string, opts: {
38
+ perKind: number;
39
+ kinds?: TestKind[];
40
+ }): Promise<DoorTestSet>;
41
+ /** The kinds as a Markdown table: what each arrival is, and what the labels say it is. */
42
+ export declare function formatTestKinds(kinds?: TestKind[]): string;
43
+ export {};