@rebilder/agent-detect 0.1.1 → 0.2.0
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 +49 -3
- package/dist/index.cjs +20 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +39 -3
- package/dist/index.d.ts +39 -3
- package/dist/index.js +20 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -23,7 +23,8 @@ const result = detect({
|
|
|
23
23
|
// {
|
|
24
24
|
// kind: 'agent' | 'human' | 'crawler' | 'protocol',
|
|
25
25
|
// platform: 'claude-code' | 'opencode' | 'claude' | 'chatgpt' | 'gemini'
|
|
26
|
-
// | 'perplexity' | 'googlebot' | 'bingbot' | '
|
|
26
|
+
// | 'perplexity' | 'googlebot' | 'bingbot' | 'microsoft-preview'
|
|
27
|
+
// | 'unknown' | null,
|
|
27
28
|
// verified: boolean, // ALWAYS false from detect() — verification is the separate
|
|
28
29
|
// // async verifyWebBotAuth() step (§ Verification)
|
|
29
30
|
// acceptsMarkdown: boolean, // Accept explicitly lists text/markdown with q > 0
|
|
@@ -32,6 +33,33 @@ const result = detect({
|
|
|
32
33
|
// }
|
|
33
34
|
```
|
|
34
35
|
|
|
36
|
+
### `acceptsMarkdownHeader(accept)`
|
|
37
|
+
|
|
38
|
+
The Accept predicate `detect()` itself uses, over a raw header string:
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
import { acceptsMarkdownHeader } from '@rebilder/agent-detect'
|
|
42
|
+
|
|
43
|
+
acceptsMarkdownHeader('text/markdown') // true
|
|
44
|
+
acceptsMarkdownHeader('text/html,text/markdown') // true
|
|
45
|
+
acceptsMarkdownHeader('text/markdown;q=0') // false — a refusal
|
|
46
|
+
acceptsMarkdownHeader('*/*') // false — see below
|
|
47
|
+
acceptsMarkdownHeader(null) // false
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
**A wildcard range is not a request for markdown**, and that is deliberate
|
|
51
|
+
rather than an oversight in the parser. Under ordinary HTTP content
|
|
52
|
+
negotiation `*/*` accepts everything; this package reads only an EXPLICIT
|
|
53
|
+
range, because the interesting fact about agent traffic is precisely how few
|
|
54
|
+
requests name the format they want.
|
|
55
|
+
|
|
56
|
+
It is exported so that anything REPORTING on negotiation asks the question
|
|
57
|
+
with the same code that ANSWERED it. The Console's content-negotiation panel
|
|
58
|
+
counts how many agent requests asked for markdown; computing that with a
|
|
59
|
+
lookalike (a SQL `LIKE`, a second regex) would let the report drift from the
|
|
60
|
+
serving decision and describe a gateway that does not exist. Also re-exported
|
|
61
|
+
from `@rebilder/gateway`, so a consumer needs only the public package.
|
|
62
|
+
|
|
35
63
|
## Verification (Web Bot Auth) — `verifyWebBotAuth()`
|
|
36
64
|
|
|
37
65
|
Agent verification, before accepting preference payloads or protocol transactions. A separate **async** step — `detect()` stays synchronous, parse-only, and unchanged:
|
|
@@ -84,11 +112,29 @@ Every check that fires is recorded in `signals`; the highest-precedence one clas
|
|
|
84
112
|
1. **`Accept: text/markdown`** (explicit in the list, q-values honored, `q=0` excluded) → `agent`, `acceptsMarkdown: true`, high confidence. Claude Code and OpenCode send this. Platform attribution comes from Signature-Agent or UA if present, else `'unknown'`.
|
|
85
113
|
2. **Web Bot Auth headers** — `Signature-Agent` (e.g. `"https://chatgpt.com"` → `chatgpt`) → `agent`, high confidence; a bare `Signature` + `Signature-Input` pair → `agent`/`unknown`, medium confidence. Parsed only by `detect()`; `verified` stays `false` here — cryptographic verification is the separate async `verifyWebBotAuth()` step (§ Verification).
|
|
86
114
|
3. **Protocol route** on the URL pathname — `/.well-known/ucp`, `/.well-known/acp`, `/mcp`, `/acp/*` (each also matching subpaths) → `protocol`.
|
|
87
|
-
4. **UA heuristics** — *fallback only*, capped at **medium** confidence. Known agent UAs: `claude-code`, `opencode`, `ChatGPT-User`, `OAI-SearchBot`, `GPTBot`, `PerplexityBot`, `Perplexity-User`, `Gemini`/`Google-Extended`, `anthropic-ai`/`claude-web` (plus `ClaudeBot`/`Claude-User`). Crawler UAs: `Googlebot` → `crawler`/`googlebot
|
|
115
|
+
4. **UA heuristics** — *fallback only*, capped at **medium** confidence. Known agent UAs: `claude-code`, `opencode`, `ChatGPT-User`, `OAI-SearchBot`, `GPTBot`, `PerplexityBot`, `Perplexity-User`, `Gemini`/`Google-Extended`, `anthropic-ai`/`claude-web` (plus `ClaudeBot`/`Claude-User`). Crawler UAs: `Googlebot` → `crawler`/`googlebot`; `bingbot` and `adidxbot` → `crawler`/`bingbot`; `MicrosoftPreview` → `crawler`/`microsoft-preview`.
|
|
88
116
|
5. **Default** → `human`. High confidence when a browserish Accept (`text/html`) or UA (`Mozilla/`) is present; low otherwise (empty or garbage headers).
|
|
89
117
|
|
|
90
118
|
**One deliberate exception to the ordering (cloaking guardrail):** a known crawler UA always classifies as `crawler`, even if other signals fired. Googlebot must receive canonical HTML, never markdown — even if a request claiming to be Googlebot sends `Accept: text/markdown`. (`acceptsMarkdown` still reports the header fact; `kind: 'crawler'` pins the serving path.)
|
|
91
119
|
|
|
120
|
+
## Microsoft, Bing, and Copilot
|
|
121
|
+
|
|
122
|
+
**There is no `copilot` platform, and that is the accurate answer rather than a gap.** Microsoft Copilot answers from Bing's index and has no user agent of its own; its fetches arrive as `bingbot`, which is why Microsoft's own guidance for being reachable by Copilot is "allow bingbot". A `copilot` entry keyed on a UA token would be a rule that never fires, backed by a fixture nobody ever observed — and this corpus is worth something only because every sample in it is real.
|
|
123
|
+
|
|
124
|
+
Copilot *does* exist as a **referrer** platform in `@rebilder/events` (`copilot.microsoft.com` → `copilot`), because an AI-referred human genuinely does arrive from it. So a merchant sees Copilot on the arrivals side and `bingbot` on the fetch side, and neither number is invented.
|
|
125
|
+
|
|
126
|
+
Three Microsoft tokens are detected, all as `crawler`:
|
|
127
|
+
|
|
128
|
+
| Token | Platform | What it is |
|
|
129
|
+
|---|---|---|
|
|
130
|
+
| `bingbot` | `bingbot` | Bing's crawler — and the Copilot path |
|
|
131
|
+
| `adidxbot` | `bingbot` | Bing Ads landing-page quality crawler |
|
|
132
|
+
| `MicrosoftPreview` | `microsoft-preview` | Link unfurling in Microsoft products (Teams, Outlook) |
|
|
133
|
+
|
|
134
|
+
All three sit in the crawler table rather than the agent table, and the asymmetry is deliberate: misclassifying a crawler as an agent serves it markdown, which is the cloaking fact pattern; misclassifying an agent as a crawler only costs that caller a markdown response it can still request with `Accept`. `adidxbot` audits ad landing pages for policy compliance, so serving it anything but the canonical page is the worst outcome available here.
|
|
135
|
+
|
|
136
|
+
`MicrosoftPreview` gets its own platform rather than folding into `bingbot` because it is not Bing and not an assistant — attributing it to `bingbot` would inflate a merchant's Bing figure with traffic that never touched the index.
|
|
137
|
+
|
|
92
138
|
## The UA-heuristics caveat (Hard Rule 3)
|
|
93
139
|
|
|
94
140
|
UA sniffing alone **never justifies substantive content differences** — different prices, claims, or availability by requester is cloaking. UA-derived classifications are therefore capped at `medium` confidence, and downstream consumers (the gateway) may use them only to pick a *format transformation of the same substance* (e.g. markdown rendering of the canonical page). Anything substantive — preference-payload personalization in particular — requires cryptographic identity: a `verified: true` result from `verifyWebBotAuth()` (§ Verification), never a parsed claim.
|
|
@@ -109,7 +155,7 @@ UA sniffing alone **never justifies substantive content differences** — differ
|
|
|
109
155
|
|
|
110
156
|
- **Every newly observed agent gets a fixture.** New headers, new signatures, new UA strings — capture them here first, then teach the detector. Treat this corpus like data, not test scaffolding.
|
|
111
157
|
- The test suite (`tests/fixtures.test.ts`) automatically loads every fixture file and asserts every sample, so adding a fixture *is* adding a regression test.
|
|
112
|
-
- Fixtures grow with observation; the current set was seeded from known agent header shapes and will be replaced/extended with captures from live traffic.
|
|
158
|
+
- Fixtures grow with observation; the current set was seeded from known agent header shapes and will be replaced/extended with captures from live traffic. Where a sample is transcribed from a platform's published crawler documentation rather than captured from our own traffic, the fixture's `description` says so — `bingbot.json` is the current example. **A UA string nobody has published and nobody has observed does not go in this directory**, however plausible it looks.
|
|
113
159
|
|
|
114
160
|
## Scripts
|
|
115
161
|
|
package/dist/index.cjs
CHANGED
|
@@ -33,6 +33,10 @@ function parseAccept(accept) {
|
|
|
33
33
|
function acceptsMediaType(ranges, mediaType) {
|
|
34
34
|
return ranges.some((range) => range.type === mediaType && range.q > 0);
|
|
35
35
|
}
|
|
36
|
+
function acceptsMarkdownHeader(accept) {
|
|
37
|
+
if (accept === null || accept === void 0 || accept.trim().length === 0) return false;
|
|
38
|
+
return acceptsMediaType(parseAccept(accept), "text/markdown");
|
|
39
|
+
}
|
|
36
40
|
function parseSignatureAgentHost(value) {
|
|
37
41
|
const first = value.split(",")[0] ?? "";
|
|
38
42
|
const unquoted = first.trim().replace(/^"/, "").replace(/"$/, "").trim();
|
|
@@ -75,7 +79,15 @@ function matchProtocolRoute(pathname) {
|
|
|
75
79
|
}
|
|
76
80
|
var CRAWLER_UA = [
|
|
77
81
|
{ pattern: "googlebot", platform: "googlebot" },
|
|
78
|
-
{ pattern: "bingbot", platform: "bingbot" }
|
|
82
|
+
{ pattern: "bingbot", platform: "bingbot" },
|
|
83
|
+
// Bing Ads landing-page quality crawler. Its own UA points at
|
|
84
|
+
// bing.com/bingbot.htm, so it is attributed to the bingbot platform.
|
|
85
|
+
{ pattern: "adidxbot", platform: "bingbot" },
|
|
86
|
+
// Microsoft product previews (link unfurling in Teams, Outlook, and the
|
|
87
|
+
// like). A separate platform because it is not Bing and not an assistant:
|
|
88
|
+
// attributing it to `bingbot` would inflate a merchant's Bing figure with
|
|
89
|
+
// traffic that never touched the index.
|
|
90
|
+
{ pattern: "microsoftpreview", platform: "microsoft-preview" }
|
|
79
91
|
];
|
|
80
92
|
var AGENT_UA = [
|
|
81
93
|
{ pattern: "claude-code", platform: "claude-code" },
|
|
@@ -141,7 +153,12 @@ function detect(input) {
|
|
|
141
153
|
};
|
|
142
154
|
}
|
|
143
155
|
if (protocolRoute !== null) {
|
|
144
|
-
return {
|
|
156
|
+
return {
|
|
157
|
+
...base,
|
|
158
|
+
kind: "protocol",
|
|
159
|
+
platform: agentUaMatch?.platform ?? null,
|
|
160
|
+
confidence: "high"
|
|
161
|
+
};
|
|
145
162
|
}
|
|
146
163
|
if (agentUaMatch !== void 0) {
|
|
147
164
|
return { ...base, kind: "agent", platform: agentUaMatch.platform, confidence: "medium" };
|
|
@@ -442,6 +459,7 @@ var KNOWN_AGENT_DIRECTORY = {
|
|
|
442
459
|
|
|
443
460
|
exports.CLOCK_SKEW_SECONDS = CLOCK_SKEW_SECONDS;
|
|
444
461
|
exports.KNOWN_AGENT_DIRECTORY = KNOWN_AGENT_DIRECTORY;
|
|
462
|
+
exports.acceptsMarkdownHeader = acceptsMarkdownHeader;
|
|
445
463
|
exports.detect = detect;
|
|
446
464
|
exports.verifyWebBotAuth = verifyWebBotAuth;
|
|
447
465
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/detect.ts","../src/verify.ts","../src/directory.ts"],"names":["headerValue"],"mappings":";;;AAOA,SAAS,WAAA,CACP,SACA,IAAA,EACoB;AACpB,EAAA,MAAM,MAAA,GAAS,KAAK,WAAA,EAAY;AAChC,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,OAAO,CAAA,EAAG;AAClD,IAAA,IAAI,GAAA,CAAI,WAAA,EAAY,KAAM,MAAA,IAAU,UAAU,MAAA,EAAW;AACzD,IAAA,OAAO,MAAM,OAAA,CAAQ,KAAK,IAAI,KAAA,CAAM,IAAA,CAAK,IAAI,CAAA,GAAI,KAAA;AAAA,EACnD;AACA,EAAA,OAAO,MAAA;AACT;AAWA,SAAS,YAAY,MAAA,EAA8B;AACjD,EAAA,MAAM,SAAuB,EAAC;AAC9B,EAAA,KAAA,MAAW,IAAA,IAAQ,MAAA,CAAO,KAAA,CAAM,GAAG,CAAA,EAAG;AACpC,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,IAAA,EAA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AA,IAAI,eAAe,MAAA,KAAW,EAAA,EAAI,OAAO,OAAA,CAAQ,iBAAiB,KAAK,CAAA;AAEvE,EAAA,IAAI,SAAA;AACJ,EAAA,IAAI;AACF,IAAA,SAAA,GAAY,MAAM,OAAO,MAAA,CAAO,SAAA;AAAA,MAC9B,KAAA;AAAA,MACA,GAAA,CAAI,YAAA;AAAA,MACJ,EAAE,MAAM,SAAA,EAAU;AAAA,MAClB,KAAA;AAAA,MACA,CAAC,QAAQ;AAAA,KACX;AAAA,EACF,CAAA,CAAA,MAAQ;AAEN,IAAA,OAAO,OAAA,CAAQ,eAAe,KAAK,CAAA;AAAA,EACrC;AAEA,EAAA,IAAI,EAAA,GAAK,KAAA;AACT,EAAA,IAAI;AACF,IAAA,EAAA,GAAK,MAAM,OAAO,MAAA,CAAO,MAAA;AAAA,MACvB,SAAA;AAAA,MACA,SAAA;AAAA,MACA,cAAA;AAAA,MACA,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,IAAI;AAAA,KAC/B;AAAA,EACF,CAAA,CAAA,MAAQ;AACN,IAAA,EAAA,GAAK,KAAA;AAAA,EACP;AACA,EAAA,IAAI,CAAC,EAAA,EAAI,OAAO,OAAA,CAAQ,iBAAiB,KAAK,CAAA;AAE9C,EAAA,OAAO,EAAE,QAAA,EAAU,IAAA,EAAM,QAAA,EAAU,KAAA,CAAM,UAAU,KAAA,EAAM;AAC3D;;;ACvcO,IAAM,qBAAA,GAA0C;AAAA;AAAA;AAGvD","file":"index.cjs","sourcesContent":["import type { AgentPlatform, DetectInput, DetectionResult } from './types'\n\n// ---------------------------------------------------------------------------\n// Header utilities\n// ---------------------------------------------------------------------------\n\n/** Case-insensitive header lookup. Array values are comma-joined (RFC 9110). */\nfunction headerValue(\n headers: Record<string, string | string[] | undefined>,\n name: string,\n): string | undefined {\n const target = name.toLowerCase()\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== target || value === undefined) continue\n return Array.isArray(value) ? value.join(', ') : value\n }\n return undefined\n}\n\n// ---------------------------------------------------------------------------\n// Accept parsing (media ranges with q-values)\n// ---------------------------------------------------------------------------\n\ninterface MediaRange {\n type: string\n q: number\n}\n\nfunction parseAccept(accept: string): MediaRange[] {\n const ranges: MediaRange[] = []\n for (const part of accept.split(',')) {\n const segments = part.trim().split(';')\n const type = (segments[0] ?? '').trim().toLowerCase()\n if (type.length === 0) continue\n let q = 1\n for (const segment of segments.slice(1)) {\n const eq = segment.indexOf('=')\n if (eq === -1) continue\n const key = segment.slice(0, eq).trim().toLowerCase()\n const value = segment.slice(eq + 1).trim()\n if (key === 'q') {\n const parsed = Number(value)\n if (Number.isFinite(parsed)) q = parsed\n }\n }\n ranges.push({ type, q })\n }\n return ranges\n}\n\n/** Explicit (non-wildcard) media type present with q > 0. */\nfunction acceptsMediaType(ranges: MediaRange[], mediaType: string): boolean {\n return ranges.some((range) => range.type === mediaType && range.q > 0)\n}\n\n// ---------------------------------------------------------------------------\n// Web Bot Auth (Signature-Agent / Signature / Signature-Input)\n// ---------------------------------------------------------------------------\n\n/**\n * Extract the host from a Signature-Agent structured-field value, e.g.\n * `\"https://chatgpt.com\"` -> `chatgpt.com`. No verification — parse only.\n */\nfunction parseSignatureAgentHost(value: string): string | null {\n const first = value.split(',')[0] ?? ''\n const unquoted = first.trim().replace(/^\"/, '').replace(/\"$/, '').trim()\n if (unquoted.length === 0) return null\n try {\n return new URL(unquoted).hostname.toLowerCase()\n } catch {\n return unquoted.toLowerCase()\n }\n}\n\nconst SIGNATURE_AGENT_PLATFORMS: ReadonlyArray<readonly [string, AgentPlatform]> = [\n ['chatgpt.com', 'chatgpt'],\n ['openai.com', 'chatgpt'],\n ['claude.ai', 'claude'],\n ['anthropic.com', 'claude'],\n ['perplexity.ai', 'perplexity'],\n ['gemini.google.com', 'gemini'],\n]\n\nfunction platformForSignatureAgentHost(host: string): AgentPlatform {\n for (const [domain, platform] of SIGNATURE_AGENT_PLATFORMS) {\n if (host === domain || host.endsWith(`.${domain}`)) return platform\n }\n return 'unknown'\n}\n\n// ---------------------------------------------------------------------------\n// Protocol routes\n// ---------------------------------------------------------------------------\n\nconst PROTOCOL_ROUTES = ['/.well-known/ucp', '/.well-known/acp', '/mcp', '/acp'] as const\n\nfunction pathnameOf(url: string): string {\n try {\n return new URL(url).pathname\n } catch {\n const stripped = url.split('#')[0]?.split('?')[0] ?? ''\n return stripped\n }\n}\n\nfunction matchProtocolRoute(pathname: string): string | null {\n const path = pathname.toLowerCase().replace(/\\/+$/, '') || '/'\n for (const route of PROTOCOL_ROUTES) {\n if (path === route || path.startsWith(`${route}/`)) return route\n }\n return null\n}\n\n// ---------------------------------------------------------------------------\n// User-Agent heuristics (fallback only — see README: UA alone never justifies\n// substantive content differences; confidence is capped at 'medium')\n// ---------------------------------------------------------------------------\n\ninterface UaEntry {\n pattern: string\n platform: AgentPlatform\n}\n\n/**\n * Crawler UAs are checked before everything else: a known crawler is always\n * classified 'crawler' regardless of other signals (cloaking guardrail —\n * Googlebot must receive canonical HTML, never markdown).\n */\nconst CRAWLER_UA: readonly UaEntry[] = [\n { pattern: 'googlebot', platform: 'googlebot' },\n { pattern: 'bingbot', platform: 'bingbot' },\n]\n\n/** Order matters: more specific tokens before broader ones. */\nconst AGENT_UA: readonly UaEntry[] = [\n { pattern: 'claude-code', platform: 'claude-code' },\n { pattern: 'opencode', platform: 'opencode' },\n { pattern: 'chatgpt-user', platform: 'chatgpt' },\n { pattern: 'oai-searchbot', platform: 'chatgpt' },\n { pattern: 'gptbot', platform: 'chatgpt' },\n { pattern: 'perplexitybot', platform: 'perplexity' },\n { pattern: 'perplexity-user', platform: 'perplexity' },\n { pattern: 'google-extended', platform: 'gemini' },\n { pattern: 'gemini', platform: 'gemini' },\n { pattern: 'claude-web', platform: 'claude' },\n { pattern: 'claudebot', platform: 'claude' },\n { pattern: 'claude-user', platform: 'claude' },\n { pattern: 'anthropic-ai', platform: 'claude' },\n]\n\nfunction findUaEntry(ua: string, table: readonly UaEntry[]): UaEntry | undefined {\n return table.find((entry) => ua.includes(entry.pattern))\n}\n\n// ---------------------------------------------------------------------------\n// detect()\n// ---------------------------------------------------------------------------\n\n/**\n * Classify a request from its headers (and optionally URL). Pure compute:\n * no network, no crypto. Checks run cheapest-first; every check that fires\n * is recorded in `signals`, and the highest-precedence one classifies.\n *\n * Precedence: crawler UA (guardrail) > Accept: text/markdown >\n * Signature-Agent / Web Bot Auth headers > protocol route > agent UA > human.\n */\nexport function detect(input: DetectInput): DetectionResult {\n const headers = input.headers ?? {}\n const signals: string[] = []\n\n // Gather raw evidence once.\n const acceptRaw = headerValue(headers, 'accept')\n const ranges = acceptRaw === undefined ? [] : parseAccept(acceptRaw)\n const acceptsMarkdown = acceptsMediaType(ranges, 'text/markdown')\n const acceptsHtml = acceptsMediaType(ranges, 'text/html')\n\n const ua = (headerValue(headers, 'user-agent') ?? '').toLowerCase()\n const crawlerMatch = findUaEntry(ua, CRAWLER_UA)\n const agentUaMatch = crawlerMatch === undefined ? findUaEntry(ua, AGENT_UA) : undefined\n\n const signatureAgentRaw = headerValue(headers, 'signature-agent')\n const signatureAgentHost =\n signatureAgentRaw === undefined ? null : parseSignatureAgentHost(signatureAgentRaw)\n const hasSignaturePair =\n headerValue(headers, 'signature') !== undefined &&\n headerValue(headers, 'signature-input') !== undefined\n\n const protocolRoute = input.url === undefined ? null : matchProtocolRoute(pathnameOf(input.url))\n\n // Record fired checks in detection order.\n if (acceptsMarkdown) signals.push('accept:text/markdown')\n if (signatureAgentHost !== null) signals.push(`signature-agent:${signatureAgentHost}`)\n if (hasSignaturePair) signals.push('web-bot-auth:signature')\n if (protocolRoute !== null) signals.push(`protocol:${protocolRoute}`)\n if (crawlerMatch !== undefined) signals.push(`ua:${crawlerMatch.pattern}`)\n if (agentUaMatch !== undefined) signals.push(`ua:${agentUaMatch.pattern}`)\n\n const base = { verified: false as const, acceptsMarkdown, signals }\n\n // 0. Cloaking guardrail: a known crawler UA always classifies as crawler,\n // even if other signals fired. Googlebot never takes the agent path.\n if (crawlerMatch !== undefined) {\n return { ...base, kind: 'crawler', platform: crawlerMatch.platform, confidence: 'medium' }\n }\n\n // 1. Accept: text/markdown — the cheapest, most explicit agent signal.\n // Platform attribution prefers Signature-Agent (a stated identity) over UA.\n if (acceptsMarkdown) {\n const signaturePlatform =\n signatureAgentHost !== null ? platformForSignatureAgentHost(signatureAgentHost) : null\n const platform = signaturePlatform ?? agentUaMatch?.platform ?? 'unknown'\n return { ...base, kind: 'agent', platform, confidence: 'high' }\n }\n\n // 2. Web Bot Auth headers — parse only here; cryptographic verification is\n // the separate async verifyWebBotAuth() step (src/verify.ts).\n if (signatureAgentHost !== null) {\n return {\n ...base,\n kind: 'agent',\n platform: platformForSignatureAgentHost(signatureAgentHost),\n confidence: 'high',\n }\n }\n if (hasSignaturePair) {\n return {\n ...base,\n kind: 'agent',\n platform: agentUaMatch?.platform ?? 'unknown',\n confidence: 'medium',\n }\n }\n\n // 3. Protocol route hit.\n if (protocolRoute !== null) {\n return { ...base, kind: 'protocol', platform: agentUaMatch?.platform ?? null, confidence: 'high' }\n }\n\n // 4. UA heuristics — fallback only, capped at medium confidence.\n if (agentUaMatch !== undefined) {\n return { ...base, kind: 'agent', platform: agentUaMatch.platform, confidence: 'medium' }\n }\n\n // 5. Default: human. High confidence only with a browserish Accept/UA.\n if (acceptsHtml) signals.push('accept:text/html')\n else if (ua.includes('mozilla/')) signals.push('ua:browser')\n const browserish = acceptsHtml || ua.includes('mozilla/')\n return { ...base, kind: 'human', platform: null, confidence: browserish ? 'high' : 'low' }\n}\n","/**\n * Web Bot Auth verification — the Phase 3 async counterpart to detect().\n *\n * PURE CRYPTO WITH INJECTED KEYS. This module verifies RFC 9421-style HTTP\n * message signatures (Signature-Input / Signature / Signature-Agent) against\n * a caller-provided key registry. It NEVER fetches a key directory, never\n * touches the network, never reads the environment — the registry is\n * dependency-injected, so the hot path stays within the edge budget\n * (CLAUDE.md Conventions: no network calls on the hot path). Key directory\n * refresh is an offline/operator concern (see README § Verification).\n *\n * detect() stays synchronous and unchanged: it parses these headers as\n * identity *signals* only and always reports `verified: false`. Paths that\n * need cryptographic identity (preference payloads, protocol transactions —\n * ROADMAP Phase 3 P0) call verifyWebBotAuth() as a separate async step.\n *\n * Failure behavior is constant: malformed, hostile, or garbage input NEVER\n * throws — every path resolves to `{ verified: false, reason }`.\n */\n\nimport type { AgentPlatform, DetectInput } from './types'\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/** Why verification did not succeed. */\nexport type VerificationFailureReason =\n | 'no-signature' // no Signature + Signature-Input header pair on the request\n | 'unknown-agent' // no Signature-Agent header, or its origin is not in the registry\n | 'unknown-key' // keyid not found for that agent, or the registry key material is unusable\n | 'expired' // `expires` is more than the allowed clock skew in the past\n | 'created-in-future' // `created` is more than the allowed clock skew in the future\n | 'bad-signature' // signature bytes do not verify over the reconstructed base\n | 'malformed' // unparseable/unsupported headers, or a covered component we cannot reconstruct\n | 'unsupported-alg' // signature declares an algorithm other than ed25519\n\nexport interface VerificationResult {\n verified: boolean\n /** The registry entry's platform, set only when verified. */\n platform?: AgentPlatform\n /** The keyid parsed from Signature-Input, set once parsing got that far. */\n keyid?: string\n /** Set exactly when `verified` is false. */\n reason?: VerificationFailureReason\n}\n\n/** An Ed25519 public key in JWK form (RFC 8037: OKP / Ed25519 / x). */\nexport interface Ed25519PublicJwk {\n kty: 'OKP'\n crv: 'Ed25519'\n /** base64url-encoded public key bytes. */\n x: string\n}\n\nexport interface AgentPublicKey {\n /** Matches the `keyid` parameter the agent sends in Signature-Input. */\n keyid: string\n /** ed25519 is the only algorithm supported in v0. */\n alg: 'ed25519'\n publicKeyJwk: Ed25519PublicJwk\n}\n\nexport interface AgentKeyRegistryEntry {\n /** The platform this origin's keys attest to. */\n platform: AgentPlatform\n keys: AgentPublicKey[]\n}\n\n/**\n * Key registry keyed by the agent's Signature-Agent origin, e.g.\n * `\"https://chatgpt.com\"`. Bare hosts (`\"chatgpt.com\"`) are accepted and\n * normalized to the https origin. See KNOWN_AGENT_DIRECTORY (src/directory.ts)\n * for the shape — it ships EMPTY; operators populate it from the platforms'\n * published key directories.\n */\nexport type AgentKeyRegistry = Record<string, AgentKeyRegistryEntry>\n\nexport interface VerifyWebBotAuthOptions {\n /** The injected key registry. Verification is pure crypto over these keys. */\n keys: AgentKeyRegistry\n /** Clock override for tests/replays. Defaults to `new Date()`. */\n now?: Date\n /**\n * Deliberately impossible to set: this function performs NO network I/O.\n * Key directory fetch/refresh happens offline, outside this module.\n */\n fetchImpl?: never\n}\n\n/** Allowed clock skew for `created` / `expires`, in seconds (±). */\nexport const CLOCK_SKEW_SECONDS = 300\n\n// ---------------------------------------------------------------------------\n// Header + structured-field parsing (RFC 8941 subset, RFC 9421 shapes)\n// ---------------------------------------------------------------------------\n\n/** Case-insensitive header lookup; array values comma-joined (RFC 9110). */\nfunction headerValue(\n headers: Record<string, string | string[] | undefined>,\n name: string,\n): string | undefined {\n const target = name.toLowerCase()\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== target || value === undefined) continue\n return Array.isArray(value) ? value.join(', ') : value\n }\n return undefined\n}\n\nconst KEY_CHAR = /[a-zA-Z0-9_.*-]/\nconst PARAM_VALUE_END = /[;,\\s]/\n\ninterface Scanner {\n s: string\n i: number\n}\n\nfunction skipOws(sc: Scanner): void {\n while (sc.i < sc.s.length && (sc.s[sc.i] === ' ' || sc.s[sc.i] === '\\t')) sc.i++\n}\n\n/** Reads an sf-key at the cursor; null when none is present. */\nfunction readKey(sc: Scanner): string | null {\n const start = sc.i\n while (sc.i < sc.s.length && KEY_CHAR.test(sc.s[sc.i] as string)) sc.i++\n return sc.i > start ? sc.s.slice(start, sc.i) : null\n}\n\n/** Reads a quoted sf-string at the cursor (cursor on the opening quote). */\nfunction readQuoted(sc: Scanner): string | null {\n if (sc.s[sc.i] !== '\"') return null\n sc.i++\n let out = ''\n while (sc.i < sc.s.length) {\n const ch = sc.s[sc.i] as string\n if (ch === '\\\\') {\n if (sc.i + 1 >= sc.s.length) return null\n out += sc.s[sc.i + 1] as string\n sc.i += 2\n continue\n }\n if (ch === '\"') {\n sc.i++\n return out\n }\n out += ch\n sc.i++\n }\n return null // unterminated\n}\n\n/** Reads `;name[=value]` parameters into a map. Null on malformed input. */\nfunction readParams(sc: Scanner): Map<string, string | number | true> | null {\n const params = new Map<string, string | number | true>()\n while (sc.i < sc.s.length && sc.s[sc.i] === ';') {\n sc.i++\n skipOws(sc)\n const name = readKey(sc)\n if (name === null) return null\n let value: string | number | true = true\n if (sc.s[sc.i] === '=') {\n sc.i++\n if (sc.s[sc.i] === '\"') {\n const quoted = readQuoted(sc)\n if (quoted === null) return null\n value = quoted\n } else {\n const start = sc.i\n while (sc.i < sc.s.length && !PARAM_VALUE_END.test(sc.s[sc.i] as string)) sc.i++\n const token = sc.s.slice(start, sc.i)\n if (token.length === 0) return null\n value = /^-?\\d+$/.test(token) ? Number(token) : token\n }\n }\n params.set(name, value)\n }\n return params\n}\n\ninterface SignatureInputMember {\n label: string\n /** Covered component names, as sent (lowercased at use time). */\n components: string[]\n params: Map<string, string | number | true>\n /**\n * The EXACT serialization after `label=` — reused verbatim as the\n * `\"@signature-params\"` line of the signature base, so no re-serialization\n * ambiguity can break verification.\n */\n raw: string\n}\n\n/**\n * Parses a Signature-Input dictionary:\n * `sig1=(\"@authority\" \"signature-agent\");created=...;keyid=\"...\", sig2=...`\n * Returns null on any malformed member. Components carrying their own\n * parameters (e.g. `\"@query-param\";name=\"q\"`) are unsupported in v0 →\n * treated as malformed.\n */\nfunction parseSignatureInput(value: string): SignatureInputMember[] | null {\n const sc: Scanner = { s: value, i: 0 }\n const members: SignatureInputMember[] = []\n skipOws(sc)\n while (sc.i < sc.s.length) {\n const label = readKey(sc)\n if (label === null || sc.s[sc.i] !== '=') return null\n sc.i++\n if (sc.s[sc.i] !== '(') return null\n const rawStart = sc.i\n sc.i++\n const components: string[] = []\n for (;;) {\n skipOws(sc)\n if (sc.i >= sc.s.length) return null\n if (sc.s[sc.i] === ')') {\n sc.i++\n break\n }\n const component = readQuoted(sc)\n if (component === null) return null\n if (sc.s[sc.i] === ';') return null // per-component parameters: unsupported in v0\n components.push(component)\n }\n const params = readParams(sc)\n if (params === null) return null\n members.push({ label, components, params, raw: sc.s.slice(rawStart, sc.i) })\n skipOws(sc)\n if (sc.i >= sc.s.length) break\n if (sc.s[sc.i] !== ',') return null\n sc.i++\n skipOws(sc)\n }\n return members\n}\n\n/**\n * Parses a Signature dictionary of byte sequences:\n * `sig1=:BASE64==:, sig2=:...:` → label → base64 payload.\n */\nfunction parseSignatureDict(value: string): Map<string, string> | null {\n const sc: Scanner = { s: value, i: 0 }\n const out = new Map<string, string>()\n skipOws(sc)\n while (sc.i < sc.s.length) {\n const label = readKey(sc)\n if (label === null || sc.s[sc.i] !== '=') return null\n sc.i++\n if (sc.s[sc.i] !== ':') return null\n sc.i++\n const start = sc.i\n while (sc.i < sc.s.length && sc.s[sc.i] !== ':') sc.i++\n if (sc.i >= sc.s.length) return null // unterminated byte sequence\n out.set(label, sc.s.slice(start, sc.i))\n sc.i++\n if (readParams(sc) === null) return null // tolerate (and ignore) member params\n skipOws(sc)\n if (sc.i >= sc.s.length) break\n if (sc.s[sc.i] !== ',') return null\n sc.i++\n skipOws(sc)\n }\n return out\n}\n\n// ---------------------------------------------------------------------------\n// Origins, base64, component values\n// ---------------------------------------------------------------------------\n\n/** Normalizes an origin-ish string (\"https://x.com\", \"x.com\") to a URL origin. */\nfunction normalizeOrigin(value: string): string | null {\n const trimmed = value.trim()\n if (trimmed.length === 0) return null\n const candidate = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`\n try {\n return new URL(candidate).origin.toLowerCase()\n } catch {\n return null\n }\n}\n\n/** First item of the Signature-Agent list, unquoted → normalized origin. */\nfunction signatureAgentOrigin(raw: string): string | null {\n const first = raw.split(',')[0] ?? ''\n const sc: Scanner = { s: first.trim(), i: 0 }\n const unquoted = sc.s[0] === '\"' ? readQuoted(sc) : sc.s\n if (unquoted === null || unquoted.length === 0) return null\n return normalizeOrigin(unquoted)\n}\n\n/** Registry lookup with origin normalization on the registry keys too. */\nfunction registryEntryFor(\n keys: AgentKeyRegistry,\n origin: string,\n): AgentKeyRegistryEntry | undefined {\n for (const [registryOrigin, entry] of Object.entries(keys)) {\n if (normalizeOrigin(registryOrigin) === origin) return entry\n }\n return undefined\n}\n\nconst BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/\n\nfunction base64Decode(value: string): Uint8Array<ArrayBuffer> | null {\n if (!BASE64_RE.test(value) || value.length % 4 !== 0) return null\n try {\n const binary = atob(value)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n return bytes\n } catch {\n return null\n }\n}\n\n/**\n * Resolves one covered component's value for the signature base. Returns\n * null when the component cannot be reconstructed from the input (missing\n * header, missing/unparseable URL, unsupported derived component) — which\n * verifyWebBotAuth reports as 'malformed'.\n */\nfunction componentValue(name: string, input: DetectInput): string | null {\n if (name.startsWith('@')) {\n if (name === '@method') {\n return input.method === undefined ? null : input.method.toUpperCase()\n }\n if (input.url === undefined) return null\n let url: URL\n try {\n url = new URL(input.url)\n } catch {\n return null\n }\n switch (name) {\n case '@authority':\n return url.host\n case '@scheme':\n return url.protocol.replace(/:$/, '')\n case '@target-uri':\n return url.href\n case '@path':\n return url.pathname\n case '@query':\n return url.search === '' ? '?' : url.search\n case '@request-target':\n return url.pathname + url.search\n default:\n return null // unsupported derived component in v0\n }\n }\n const value = headerValue(input.headers ?? {}, name)\n return value === undefined ? null : value.trim()\n}\n\n// ---------------------------------------------------------------------------\n// verifyWebBotAuth()\n// ---------------------------------------------------------------------------\n\nfunction failure(reason: VerificationFailureReason, keyid?: string): VerificationResult {\n return keyid === undefined ? { verified: false, reason } : { verified: false, keyid, reason }\n}\n\n/**\n * Verify a request's Web Bot Auth signature chain against an injected key\n * registry. Async (WebCrypto) but pure: no network, no environment, no\n * global state. Never throws — every failure resolves to\n * `{ verified: false, reason }`.\n *\n * Requirements enforced (Web Bot Auth profile over RFC 9421):\n * - `Signature` + `Signature-Input` present, structured-field parseable\n * - covered components include `@authority` AND `signature-agent`\n * (anti-replay: the signature is pinned to this host and this identity)\n * - `keyid`, `created`, `expires` parameters present; `created <= expires`;\n * both within ±CLOCK_SKEW_SECONDS of `options.now`\n * - `alg`, when present, is `ed25519`\n * - `Signature-Agent` origin resolves to a registry entry; `keyid` resolves\n * to one of that entry's keys\n * - Ed25519 signature verifies (WebCrypto subtle) over the RFC 9421\n * signature base, whose `\"@signature-params\"` line reuses the exact\n * serialization the agent sent\n */\nexport async function verifyWebBotAuth(\n input: DetectInput,\n options: VerifyWebBotAuthOptions,\n): Promise<VerificationResult> {\n try {\n return await verifyInner(input, options)\n } catch {\n // Constant behavior on hostile input: never throw.\n return failure('malformed')\n }\n}\n\nasync function verifyInner(\n input: DetectInput,\n options: VerifyWebBotAuthOptions,\n): Promise<VerificationResult> {\n const headers = input.headers ?? {}\n const signatureRaw = headerValue(headers, 'signature')\n const signatureInputRaw = headerValue(headers, 'signature-input')\n if (signatureRaw === undefined || signatureInputRaw === undefined) {\n return failure('no-signature')\n }\n\n const members = parseSignatureInput(signatureInputRaw)\n const signatures = parseSignatureDict(signatureRaw)\n if (members === null || signatures === null || members.length === 0) {\n return failure('malformed')\n }\n\n // First Signature-Input member with a matching Signature entry.\n const member = members.find((candidate) => signatures.has(candidate.label))\n if (member === undefined) return failure('malformed')\n const signatureB64 = signatures.get(member.label) as string\n\n // Anti-replay: the signature must pin the authority and the agent identity.\n const covered = member.components.map((component) => component.toLowerCase())\n if (!covered.includes('@authority') || !covered.includes('signature-agent')) {\n return failure('malformed')\n }\n\n const alg = member.params.get('alg')\n if (alg !== undefined && alg !== 'ed25519') return failure('unsupported-alg')\n\n const keyidParam = member.params.get('keyid')\n const keyid = typeof keyidParam === 'string' && keyidParam.length > 0 ? keyidParam : undefined\n\n // Agent identity → registry entry.\n const signatureAgentRaw = headerValue(headers, 'signature-agent')\n if (signatureAgentRaw === undefined) return failure('unknown-agent', keyid)\n const origin = signatureAgentOrigin(signatureAgentRaw)\n if (origin === null) return failure('unknown-agent', keyid)\n const entry = registryEntryFor(options.keys, origin)\n if (entry === undefined) return failure('unknown-agent', keyid)\n\n // keyid → registry key.\n if (keyid === undefined) return failure('malformed')\n const key = entry.keys.find((candidate) => candidate.keyid === keyid)\n if (key === undefined) return failure('unknown-key', keyid)\n if (key.alg !== 'ed25519') return failure('unsupported-alg', keyid)\n\n // Validity window (±CLOCK_SKEW_SECONDS).\n const created = member.params.get('created')\n const expires = member.params.get('expires')\n if (typeof created !== 'number' || !Number.isInteger(created)) return failure('malformed', keyid)\n if (typeof expires !== 'number' || !Number.isInteger(expires)) return failure('malformed', keyid)\n if (created > expires) return failure('malformed', keyid)\n const nowSeconds = Math.floor((options.now ?? new Date()).getTime() / 1000)\n if (created - CLOCK_SKEW_SECONDS > nowSeconds) return failure('created-in-future', keyid)\n if (expires + CLOCK_SKEW_SECONDS < nowSeconds) return failure('expired', keyid)\n\n // Signature base (RFC 9421 § 2.5): one line per covered component, then\n // \"@signature-params\" with the agent's exact Signature-Input serialization.\n const lines: string[] = []\n for (const component of covered) {\n const value = componentValue(component, input)\n if (value === null) return failure('malformed', keyid)\n lines.push(`\"${component}\": ${value}`)\n }\n lines.push(`\"@signature-params\": ${member.raw}`)\n const base = lines.join('\\n')\n\n const signatureBytes = base64Decode(signatureB64)\n if (signatureBytes === null) return failure('malformed', keyid)\n if (signatureBytes.length !== 64) return failure('bad-signature', keyid)\n\n let cryptoKey: CryptoKey\n try {\n cryptoKey = await crypto.subtle.importKey(\n 'jwk',\n key.publicKeyJwk,\n { name: 'Ed25519' },\n false,\n ['verify'],\n )\n } catch {\n // Registry key material is unusable — an operator/registry problem.\n return failure('unknown-key', keyid)\n }\n\n let ok = false\n try {\n ok = await crypto.subtle.verify(\n 'Ed25519',\n cryptoKey,\n signatureBytes,\n new TextEncoder().encode(base),\n )\n } catch {\n ok = false\n }\n if (!ok) return failure('bad-signature', keyid)\n\n return { verified: true, platform: entry.platform, keyid }\n}\n","/**\n * KNOWN_AGENT_DIRECTORY — the built-in Web Bot Auth key registry.\n *\n * THIS IS A DATA MODULE, AND IT SHIPS EMPTY — DELIBERATELY. We do not embed\n * \"known\" production public keys for OpenAI, Anthropic, Perplexity, etc.,\n * because we have not fetched and pinned them from the platforms' published\n * key directories, and inventing key material would make verification\n * silently meaningless (a fabricated key either verifies nothing or, worse,\n * verifies the wrong thing). Honesty over completeness.\n *\n * How this gets populated (operator responsibility, README § Verification):\n * agent platforms publish their signing keys at well-known HTTP message\n * signature directories (e.g. `https://<platform>/.well-known/\n * http-message-signatures-directory`). Operators fetch those OFFLINE — never\n * on the request hot path — pin the Ed25519 public keys here (or in their own\n * registry object; any `AgentKeyRegistry` works), and refresh on key\n * rotation. A refresh script that snapshots the published directories into\n * this module is future work (ROADMAP parking-lot material).\n *\n * Shape of a populated entry (this example is NOT a real key):\n *\n * 'https://chatgpt.com': {\n * platform: 'chatgpt',\n * keys: [\n * {\n * keyid: 'poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U', // JWK thumbprint the agent sends\n * alg: 'ed25519',\n * publicKeyJwk: { kty: 'OKP', crv: 'Ed25519', x: '<base64url public key bytes>' },\n * },\n * ],\n * },\n *\n * With the directory empty, verifyWebBotAuth() resolves every signed request\n * to `{ verified: false, reason: 'unknown-agent' }` — the honest answer when\n * no trusted key is on file.\n */\n\nimport type { AgentKeyRegistry } from './verify'\n\nexport const KNOWN_AGENT_DIRECTORY: AgentKeyRegistry = {\n // Intentionally empty — see the module header. Operators populate this (or\n // pass their own registry) from the platforms' published key directories.\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/detect.ts","../src/verify.ts","../src/directory.ts"],"names":["headerValue"],"mappings":";;;AAOA,SAAS,WAAA,CACP,SACA,IAAA,EACoB;AACpB,EAAA,MAAM,MAA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MAClB,KAAA;AAAA,MACA,CAAC,QAAQ;AAAA,KACX;AAAA,EACF,CAAA,CAAA,MAAQ;AAEN,IAAA,OAAO,OAAA,CAAQ,eAAe,KAAK,CAAA;AAAA,EACrC;AAEA,EAAA,IAAI,EAAA,GAAK,KAAA;AACT,EAAA,IAAI;AACF,IAAA,EAAA,GAAK,MAAM,OAAO,MAAA,CAAO,MAAA;AAAA,MACvB,SAAA;AAAA,MACA,SAAA;AAAA,MACA,cAAA;AAAA,MACA,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,IAAI;AAAA,KAC/B;AAAA,EACF,CAAA,CAAA,MAAQ;AACN,IAAA,EAAA,GAAK,KAAA;AAAA,EACP;AACA,EAAA,IAAI,CAAC,EAAA,EAAI,OAAO,OAAA,CAAQ,iBAAiB,KAAK,CAAA;AAE9C,EAAA,OAAO,EAAE,QAAA,EAAU,IAAA,EAAM,QAAA,EAAU,KAAA,CAAM,UAAU,KAAA,EAAM;AAC3D;;;ACvcO,IAAM,qBAAA,GAA0C;AAAA;AAAA;AAGvD","file":"index.cjs","sourcesContent":["import type { AgentPlatform, DetectInput, DetectionResult } from './types'\n\n// ---------------------------------------------------------------------------\n// Header utilities\n// ---------------------------------------------------------------------------\n\n/** Case-insensitive header lookup. Array values are comma-joined (RFC 9110). */\nfunction headerValue(\n headers: Record<string, string | string[] | undefined>,\n name: string,\n): string | undefined {\n const target = name.toLowerCase()\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== target || value === undefined) continue\n return Array.isArray(value) ? value.join(', ') : value\n }\n return undefined\n}\n\n// ---------------------------------------------------------------------------\n// Accept parsing (media ranges with q-values)\n// ---------------------------------------------------------------------------\n\ninterface MediaRange {\n type: string\n q: number\n}\n\nfunction parseAccept(accept: string): MediaRange[] {\n const ranges: MediaRange[] = []\n for (const part of accept.split(',')) {\n const segments = part.trim().split(';')\n const type = (segments[0] ?? '').trim().toLowerCase()\n if (type.length === 0) continue\n let q = 1\n for (const segment of segments.slice(1)) {\n const eq = segment.indexOf('=')\n if (eq === -1) continue\n const key = segment.slice(0, eq).trim().toLowerCase()\n const value = segment.slice(eq + 1).trim()\n if (key === 'q') {\n const parsed = Number(value)\n if (Number.isFinite(parsed)) q = parsed\n }\n }\n ranges.push({ type, q })\n }\n return ranges\n}\n\n/** Explicit (non-wildcard) media type present with q > 0. */\nfunction acceptsMediaType(ranges: MediaRange[], mediaType: string): boolean {\n return ranges.some((range) => range.type === mediaType && range.q > 0)\n}\n\n/**\n * Does this raw `Accept` header EXPLICITLY ask for `text/markdown`?\n *\n * Exported because the answer is a fact about the serving decision, and a\n * second implementation of it would be free to disagree with the first. The\n * Console's Accept panel reports how many agent requests asked for markdown;\n * if that number were computed by a SQL `LIKE` it would quietly drift from\n * what `detect()` actually did, and the panel would be describing a gateway\n * that does not exist.\n *\n * A WILDCARD RANGE DOES NOT COUNT, and that is the whole point of the panel.\n * Under ordinary HTTP content negotiation a wildcard accepts everything, but\n * this standard reads only an EXPLICIT range: an agent sending the catch-all\n * range has expressed no preference, and counting it as \"asked for markdown\"\n * would turn the honest headline (\"almost nobody asks; we serve it anyway\")\n * into a meaningless one where almost everybody asks.\n *\n * `text/markdown;q=0` is a refusal and returns false, same as `detect()`.\n */\nexport function acceptsMarkdownHeader(accept: string | null | undefined): boolean {\n if (accept === null || accept === undefined || accept.trim().length === 0) return false\n return acceptsMediaType(parseAccept(accept), 'text/markdown')\n}\n\n// ---------------------------------------------------------------------------\n// Web Bot Auth (Signature-Agent / Signature / Signature-Input)\n// ---------------------------------------------------------------------------\n\n/**\n * Extract the host from a Signature-Agent structured-field value, e.g.\n * `\"https://chatgpt.com\"` -> `chatgpt.com`. No verification — parse only.\n */\nfunction parseSignatureAgentHost(value: string): string | null {\n const first = value.split(',')[0] ?? ''\n const unquoted = first.trim().replace(/^\"/, '').replace(/\"$/, '').trim()\n if (unquoted.length === 0) return null\n try {\n return new URL(unquoted).hostname.toLowerCase()\n } catch {\n return unquoted.toLowerCase()\n }\n}\n\nconst SIGNATURE_AGENT_PLATFORMS: ReadonlyArray<readonly [string, AgentPlatform]> = [\n ['chatgpt.com', 'chatgpt'],\n ['openai.com', 'chatgpt'],\n ['claude.ai', 'claude'],\n ['anthropic.com', 'claude'],\n ['perplexity.ai', 'perplexity'],\n ['gemini.google.com', 'gemini'],\n]\n\nfunction platformForSignatureAgentHost(host: string): AgentPlatform {\n for (const [domain, platform] of SIGNATURE_AGENT_PLATFORMS) {\n if (host === domain || host.endsWith(`.${domain}`)) return platform\n }\n return 'unknown'\n}\n\n// ---------------------------------------------------------------------------\n// Protocol routes\n// ---------------------------------------------------------------------------\n\nconst PROTOCOL_ROUTES = ['/.well-known/ucp', '/.well-known/acp', '/mcp', '/acp'] as const\n\nfunction pathnameOf(url: string): string {\n try {\n return new URL(url).pathname\n } catch {\n const stripped = url.split('#')[0]?.split('?')[0] ?? ''\n return stripped\n }\n}\n\nfunction matchProtocolRoute(pathname: string): string | null {\n const path = pathname.toLowerCase().replace(/\\/+$/, '') || '/'\n for (const route of PROTOCOL_ROUTES) {\n if (path === route || path.startsWith(`${route}/`)) return route\n }\n return null\n}\n\n// ---------------------------------------------------------------------------\n// User-Agent heuristics (fallback only — see README: UA alone never justifies\n// substantive content differences; confidence is capped at 'medium')\n// ---------------------------------------------------------------------------\n\ninterface UaEntry {\n pattern: string\n platform: AgentPlatform\n}\n\n/**\n * Crawler UAs are checked before everything else: a known crawler is always\n * classified 'crawler' regardless of other signals (cloaking guardrail —\n * Googlebot must receive canonical HTML, never markdown).\n *\n * Every Microsoft fetcher below belongs in THIS table rather than `AGENT_UA`,\n * and the asymmetry is deliberate. Misclassifying a crawler as an agent serves\n * it markdown, which is the cloaking fact pattern; misclassifying an agent as\n * a crawler only costs that caller a markdown response it can still get by\n * asking for one with `Accept`. When a Microsoft token is ambiguous, crawler\n * is the side to be wrong on — and `adidxbot` in particular audits ad landing\n * pages for policy compliance, so serving it anything but the canonical page\n * is the single worst outcome available here.\n */\nconst CRAWLER_UA: readonly UaEntry[] = [\n { pattern: 'googlebot', platform: 'googlebot' },\n { pattern: 'bingbot', platform: 'bingbot' },\n // Bing Ads landing-page quality crawler. Its own UA points at\n // bing.com/bingbot.htm, so it is attributed to the bingbot platform.\n { pattern: 'adidxbot', platform: 'bingbot' },\n // Microsoft product previews (link unfurling in Teams, Outlook, and the\n // like). A separate platform because it is not Bing and not an assistant:\n // attributing it to `bingbot` would inflate a merchant's Bing figure with\n // traffic that never touched the index.\n { pattern: 'microsoftpreview', platform: 'microsoft-preview' },\n]\n\n/** Order matters: more specific tokens before broader ones. */\nconst AGENT_UA: readonly UaEntry[] = [\n { pattern: 'claude-code', platform: 'claude-code' },\n { pattern: 'opencode', platform: 'opencode' },\n { pattern: 'chatgpt-user', platform: 'chatgpt' },\n { pattern: 'oai-searchbot', platform: 'chatgpt' },\n { pattern: 'gptbot', platform: 'chatgpt' },\n { pattern: 'perplexitybot', platform: 'perplexity' },\n { pattern: 'perplexity-user', platform: 'perplexity' },\n { pattern: 'google-extended', platform: 'gemini' },\n { pattern: 'gemini', platform: 'gemini' },\n { pattern: 'claude-web', platform: 'claude' },\n { pattern: 'claudebot', platform: 'claude' },\n { pattern: 'claude-user', platform: 'claude' },\n { pattern: 'anthropic-ai', platform: 'claude' },\n]\n\nfunction findUaEntry(ua: string, table: readonly UaEntry[]): UaEntry | undefined {\n return table.find((entry) => ua.includes(entry.pattern))\n}\n\n// ---------------------------------------------------------------------------\n// detect()\n// ---------------------------------------------------------------------------\n\n/**\n * Classify a request from its headers (and optionally URL). Pure compute:\n * no network, no crypto. Checks run cheapest-first; every check that fires\n * is recorded in `signals`, and the highest-precedence one classifies.\n *\n * Precedence: crawler UA (guardrail) > Accept: text/markdown >\n * Signature-Agent / Web Bot Auth headers > protocol route > agent UA > human.\n */\nexport function detect(input: DetectInput): DetectionResult {\n const headers = input.headers ?? {}\n const signals: string[] = []\n\n // Gather raw evidence once.\n const acceptRaw = headerValue(headers, 'accept')\n const ranges = acceptRaw === undefined ? [] : parseAccept(acceptRaw)\n const acceptsMarkdown = acceptsMediaType(ranges, 'text/markdown')\n const acceptsHtml = acceptsMediaType(ranges, 'text/html')\n\n const ua = (headerValue(headers, 'user-agent') ?? '').toLowerCase()\n const crawlerMatch = findUaEntry(ua, CRAWLER_UA)\n const agentUaMatch = crawlerMatch === undefined ? findUaEntry(ua, AGENT_UA) : undefined\n\n const signatureAgentRaw = headerValue(headers, 'signature-agent')\n const signatureAgentHost =\n signatureAgentRaw === undefined ? null : parseSignatureAgentHost(signatureAgentRaw)\n const hasSignaturePair =\n headerValue(headers, 'signature') !== undefined &&\n headerValue(headers, 'signature-input') !== undefined\n\n const protocolRoute = input.url === undefined ? null : matchProtocolRoute(pathnameOf(input.url))\n\n // Record fired checks in detection order.\n if (acceptsMarkdown) signals.push('accept:text/markdown')\n if (signatureAgentHost !== null) signals.push(`signature-agent:${signatureAgentHost}`)\n if (hasSignaturePair) signals.push('web-bot-auth:signature')\n if (protocolRoute !== null) signals.push(`protocol:${protocolRoute}`)\n if (crawlerMatch !== undefined) signals.push(`ua:${crawlerMatch.pattern}`)\n if (agentUaMatch !== undefined) signals.push(`ua:${agentUaMatch.pattern}`)\n\n const base = { verified: false as const, acceptsMarkdown, signals }\n\n // 0. Cloaking guardrail: a known crawler UA always classifies as crawler,\n // even if other signals fired. Googlebot never takes the agent path.\n if (crawlerMatch !== undefined) {\n return { ...base, kind: 'crawler', platform: crawlerMatch.platform, confidence: 'medium' }\n }\n\n // 1. Accept: text/markdown — the cheapest, most explicit agent signal.\n // Platform attribution prefers Signature-Agent (a stated identity) over UA.\n if (acceptsMarkdown) {\n const signaturePlatform =\n signatureAgentHost !== null ? platformForSignatureAgentHost(signatureAgentHost) : null\n const platform = signaturePlatform ?? agentUaMatch?.platform ?? 'unknown'\n return { ...base, kind: 'agent', platform, confidence: 'high' }\n }\n\n // 2. Web Bot Auth headers — parse only here; cryptographic verification is\n // the separate async verifyWebBotAuth() step (src/verify.ts).\n if (signatureAgentHost !== null) {\n return {\n ...base,\n kind: 'agent',\n platform: platformForSignatureAgentHost(signatureAgentHost),\n confidence: 'high',\n }\n }\n if (hasSignaturePair) {\n return {\n ...base,\n kind: 'agent',\n platform: agentUaMatch?.platform ?? 'unknown',\n confidence: 'medium',\n }\n }\n\n // 3. Protocol route hit.\n if (protocolRoute !== null) {\n return {\n ...base,\n kind: 'protocol',\n platform: agentUaMatch?.platform ?? null,\n confidence: 'high',\n }\n }\n\n // 4. UA heuristics — fallback only, capped at medium confidence.\n if (agentUaMatch !== undefined) {\n return { ...base, kind: 'agent', platform: agentUaMatch.platform, confidence: 'medium' }\n }\n\n // 5. Default: human. High confidence only with a browserish Accept/UA.\n if (acceptsHtml) signals.push('accept:text/html')\n else if (ua.includes('mozilla/')) signals.push('ua:browser')\n const browserish = acceptsHtml || ua.includes('mozilla/')\n return { ...base, kind: 'human', platform: null, confidence: browserish ? 'high' : 'low' }\n}\n","/**\n * Web Bot Auth verification — the Phase 3 async counterpart to detect().\n *\n * PURE CRYPTO WITH INJECTED KEYS. This module verifies RFC 9421-style HTTP\n * message signatures (Signature-Input / Signature / Signature-Agent) against\n * a caller-provided key registry. It NEVER fetches a key directory, never\n * touches the network, never reads the environment — the registry is\n * dependency-injected, so the hot path stays within the edge budget\n * (CLAUDE.md Conventions: no network calls on the hot path). Key directory\n * refresh is an offline/operator concern (see README § Verification).\n *\n * detect() stays synchronous and unchanged: it parses these headers as\n * identity *signals* only and always reports `verified: false`. Paths that\n * need cryptographic identity (preference payloads, protocol transactions —\n * ROADMAP Phase 3 P0) call verifyWebBotAuth() as a separate async step.\n *\n * Failure behavior is constant: malformed, hostile, or garbage input NEVER\n * throws — every path resolves to `{ verified: false, reason }`.\n */\n\nimport type { AgentPlatform, DetectInput } from './types'\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/** Why verification did not succeed. */\nexport type VerificationFailureReason =\n | 'no-signature' // no Signature + Signature-Input header pair on the request\n | 'unknown-agent' // no Signature-Agent header, or its origin is not in the registry\n | 'unknown-key' // keyid not found for that agent, or the registry key material is unusable\n | 'expired' // `expires` is more than the allowed clock skew in the past\n | 'created-in-future' // `created` is more than the allowed clock skew in the future\n | 'bad-signature' // signature bytes do not verify over the reconstructed base\n | 'malformed' // unparseable/unsupported headers, or a covered component we cannot reconstruct\n | 'unsupported-alg' // signature declares an algorithm other than ed25519\n\nexport interface VerificationResult {\n verified: boolean\n /** The registry entry's platform, set only when verified. */\n platform?: AgentPlatform\n /** The keyid parsed from Signature-Input, set once parsing got that far. */\n keyid?: string\n /** Set exactly when `verified` is false. */\n reason?: VerificationFailureReason\n}\n\n/** An Ed25519 public key in JWK form (RFC 8037: OKP / Ed25519 / x). */\nexport interface Ed25519PublicJwk {\n kty: 'OKP'\n crv: 'Ed25519'\n /** base64url-encoded public key bytes. */\n x: string\n}\n\nexport interface AgentPublicKey {\n /** Matches the `keyid` parameter the agent sends in Signature-Input. */\n keyid: string\n /** ed25519 is the only algorithm supported in v0. */\n alg: 'ed25519'\n publicKeyJwk: Ed25519PublicJwk\n}\n\nexport interface AgentKeyRegistryEntry {\n /** The platform this origin's keys attest to. */\n platform: AgentPlatform\n keys: AgentPublicKey[]\n}\n\n/**\n * Key registry keyed by the agent's Signature-Agent origin, e.g.\n * `\"https://chatgpt.com\"`. Bare hosts (`\"chatgpt.com\"`) are accepted and\n * normalized to the https origin. See KNOWN_AGENT_DIRECTORY (src/directory.ts)\n * for the shape — it ships EMPTY; operators populate it from the platforms'\n * published key directories.\n */\nexport type AgentKeyRegistry = Record<string, AgentKeyRegistryEntry>\n\nexport interface VerifyWebBotAuthOptions {\n /** The injected key registry. Verification is pure crypto over these keys. */\n keys: AgentKeyRegistry\n /** Clock override for tests/replays. Defaults to `new Date()`. */\n now?: Date\n /**\n * Deliberately impossible to set: this function performs NO network I/O.\n * Key directory fetch/refresh happens offline, outside this module.\n */\n fetchImpl?: never\n}\n\n/** Allowed clock skew for `created` / `expires`, in seconds (±). */\nexport const CLOCK_SKEW_SECONDS = 300\n\n// ---------------------------------------------------------------------------\n// Header + structured-field parsing (RFC 8941 subset, RFC 9421 shapes)\n// ---------------------------------------------------------------------------\n\n/** Case-insensitive header lookup; array values comma-joined (RFC 9110). */\nfunction headerValue(\n headers: Record<string, string | string[] | undefined>,\n name: string,\n): string | undefined {\n const target = name.toLowerCase()\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== target || value === undefined) continue\n return Array.isArray(value) ? value.join(', ') : value\n }\n return undefined\n}\n\nconst KEY_CHAR = /[a-zA-Z0-9_.*-]/\nconst PARAM_VALUE_END = /[;,\\s]/\n\ninterface Scanner {\n s: string\n i: number\n}\n\nfunction skipOws(sc: Scanner): void {\n while (sc.i < sc.s.length && (sc.s[sc.i] === ' ' || sc.s[sc.i] === '\\t')) sc.i++\n}\n\n/** Reads an sf-key at the cursor; null when none is present. */\nfunction readKey(sc: Scanner): string | null {\n const start = sc.i\n while (sc.i < sc.s.length && KEY_CHAR.test(sc.s[sc.i] as string)) sc.i++\n return sc.i > start ? sc.s.slice(start, sc.i) : null\n}\n\n/** Reads a quoted sf-string at the cursor (cursor on the opening quote). */\nfunction readQuoted(sc: Scanner): string | null {\n if (sc.s[sc.i] !== '\"') return null\n sc.i++\n let out = ''\n while (sc.i < sc.s.length) {\n const ch = sc.s[sc.i] as string\n if (ch === '\\\\') {\n if (sc.i + 1 >= sc.s.length) return null\n out += sc.s[sc.i + 1] as string\n sc.i += 2\n continue\n }\n if (ch === '\"') {\n sc.i++\n return out\n }\n out += ch\n sc.i++\n }\n return null // unterminated\n}\n\n/** Reads `;name[=value]` parameters into a map. Null on malformed input. */\nfunction readParams(sc: Scanner): Map<string, string | number | true> | null {\n const params = new Map<string, string | number | true>()\n while (sc.i < sc.s.length && sc.s[sc.i] === ';') {\n sc.i++\n skipOws(sc)\n const name = readKey(sc)\n if (name === null) return null\n let value: string | number | true = true\n if (sc.s[sc.i] === '=') {\n sc.i++\n if (sc.s[sc.i] === '\"') {\n const quoted = readQuoted(sc)\n if (quoted === null) return null\n value = quoted\n } else {\n const start = sc.i\n while (sc.i < sc.s.length && !PARAM_VALUE_END.test(sc.s[sc.i] as string)) sc.i++\n const token = sc.s.slice(start, sc.i)\n if (token.length === 0) return null\n value = /^-?\\d+$/.test(token) ? Number(token) : token\n }\n }\n params.set(name, value)\n }\n return params\n}\n\ninterface SignatureInputMember {\n label: string\n /** Covered component names, as sent (lowercased at use time). */\n components: string[]\n params: Map<string, string | number | true>\n /**\n * The EXACT serialization after `label=` — reused verbatim as the\n * `\"@signature-params\"` line of the signature base, so no re-serialization\n * ambiguity can break verification.\n */\n raw: string\n}\n\n/**\n * Parses a Signature-Input dictionary:\n * `sig1=(\"@authority\" \"signature-agent\");created=...;keyid=\"...\", sig2=...`\n * Returns null on any malformed member. Components carrying their own\n * parameters (e.g. `\"@query-param\";name=\"q\"`) are unsupported in v0 →\n * treated as malformed.\n */\nfunction parseSignatureInput(value: string): SignatureInputMember[] | null {\n const sc: Scanner = { s: value, i: 0 }\n const members: SignatureInputMember[] = []\n skipOws(sc)\n while (sc.i < sc.s.length) {\n const label = readKey(sc)\n if (label === null || sc.s[sc.i] !== '=') return null\n sc.i++\n if (sc.s[sc.i] !== '(') return null\n const rawStart = sc.i\n sc.i++\n const components: string[] = []\n for (;;) {\n skipOws(sc)\n if (sc.i >= sc.s.length) return null\n if (sc.s[sc.i] === ')') {\n sc.i++\n break\n }\n const component = readQuoted(sc)\n if (component === null) return null\n if (sc.s[sc.i] === ';') return null // per-component parameters: unsupported in v0\n components.push(component)\n }\n const params = readParams(sc)\n if (params === null) return null\n members.push({ label, components, params, raw: sc.s.slice(rawStart, sc.i) })\n skipOws(sc)\n if (sc.i >= sc.s.length) break\n if (sc.s[sc.i] !== ',') return null\n sc.i++\n skipOws(sc)\n }\n return members\n}\n\n/**\n * Parses a Signature dictionary of byte sequences:\n * `sig1=:BASE64==:, sig2=:...:` → label → base64 payload.\n */\nfunction parseSignatureDict(value: string): Map<string, string> | null {\n const sc: Scanner = { s: value, i: 0 }\n const out = new Map<string, string>()\n skipOws(sc)\n while (sc.i < sc.s.length) {\n const label = readKey(sc)\n if (label === null || sc.s[sc.i] !== '=') return null\n sc.i++\n if (sc.s[sc.i] !== ':') return null\n sc.i++\n const start = sc.i\n while (sc.i < sc.s.length && sc.s[sc.i] !== ':') sc.i++\n if (sc.i >= sc.s.length) return null // unterminated byte sequence\n out.set(label, sc.s.slice(start, sc.i))\n sc.i++\n if (readParams(sc) === null) return null // tolerate (and ignore) member params\n skipOws(sc)\n if (sc.i >= sc.s.length) break\n if (sc.s[sc.i] !== ',') return null\n sc.i++\n skipOws(sc)\n }\n return out\n}\n\n// ---------------------------------------------------------------------------\n// Origins, base64, component values\n// ---------------------------------------------------------------------------\n\n/** Normalizes an origin-ish string (\"https://x.com\", \"x.com\") to a URL origin. */\nfunction normalizeOrigin(value: string): string | null {\n const trimmed = value.trim()\n if (trimmed.length === 0) return null\n const candidate = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`\n try {\n return new URL(candidate).origin.toLowerCase()\n } catch {\n return null\n }\n}\n\n/** First item of the Signature-Agent list, unquoted → normalized origin. */\nfunction signatureAgentOrigin(raw: string): string | null {\n const first = raw.split(',')[0] ?? ''\n const sc: Scanner = { s: first.trim(), i: 0 }\n const unquoted = sc.s[0] === '\"' ? readQuoted(sc) : sc.s\n if (unquoted === null || unquoted.length === 0) return null\n return normalizeOrigin(unquoted)\n}\n\n/** Registry lookup with origin normalization on the registry keys too. */\nfunction registryEntryFor(\n keys: AgentKeyRegistry,\n origin: string,\n): AgentKeyRegistryEntry | undefined {\n for (const [registryOrigin, entry] of Object.entries(keys)) {\n if (normalizeOrigin(registryOrigin) === origin) return entry\n }\n return undefined\n}\n\nconst BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/\n\nfunction base64Decode(value: string): Uint8Array<ArrayBuffer> | null {\n if (!BASE64_RE.test(value) || value.length % 4 !== 0) return null\n try {\n const binary = atob(value)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n return bytes\n } catch {\n return null\n }\n}\n\n/**\n * Resolves one covered component's value for the signature base. Returns\n * null when the component cannot be reconstructed from the input (missing\n * header, missing/unparseable URL, unsupported derived component) — which\n * verifyWebBotAuth reports as 'malformed'.\n */\nfunction componentValue(name: string, input: DetectInput): string | null {\n if (name.startsWith('@')) {\n if (name === '@method') {\n return input.method === undefined ? null : input.method.toUpperCase()\n }\n if (input.url === undefined) return null\n let url: URL\n try {\n url = new URL(input.url)\n } catch {\n return null\n }\n switch (name) {\n case '@authority':\n return url.host\n case '@scheme':\n return url.protocol.replace(/:$/, '')\n case '@target-uri':\n return url.href\n case '@path':\n return url.pathname\n case '@query':\n return url.search === '' ? '?' : url.search\n case '@request-target':\n return url.pathname + url.search\n default:\n return null // unsupported derived component in v0\n }\n }\n const value = headerValue(input.headers ?? {}, name)\n return value === undefined ? null : value.trim()\n}\n\n// ---------------------------------------------------------------------------\n// verifyWebBotAuth()\n// ---------------------------------------------------------------------------\n\nfunction failure(reason: VerificationFailureReason, keyid?: string): VerificationResult {\n return keyid === undefined ? { verified: false, reason } : { verified: false, keyid, reason }\n}\n\n/**\n * Verify a request's Web Bot Auth signature chain against an injected key\n * registry. Async (WebCrypto) but pure: no network, no environment, no\n * global state. Never throws — every failure resolves to\n * `{ verified: false, reason }`.\n *\n * Requirements enforced (Web Bot Auth profile over RFC 9421):\n * - `Signature` + `Signature-Input` present, structured-field parseable\n * - covered components include `@authority` AND `signature-agent`\n * (anti-replay: the signature is pinned to this host and this identity)\n * - `keyid`, `created`, `expires` parameters present; `created <= expires`;\n * both within ±CLOCK_SKEW_SECONDS of `options.now`\n * - `alg`, when present, is `ed25519`\n * - `Signature-Agent` origin resolves to a registry entry; `keyid` resolves\n * to one of that entry's keys\n * - Ed25519 signature verifies (WebCrypto subtle) over the RFC 9421\n * signature base, whose `\"@signature-params\"` line reuses the exact\n * serialization the agent sent\n */\nexport async function verifyWebBotAuth(\n input: DetectInput,\n options: VerifyWebBotAuthOptions,\n): Promise<VerificationResult> {\n try {\n return await verifyInner(input, options)\n } catch {\n // Constant behavior on hostile input: never throw.\n return failure('malformed')\n }\n}\n\nasync function verifyInner(\n input: DetectInput,\n options: VerifyWebBotAuthOptions,\n): Promise<VerificationResult> {\n const headers = input.headers ?? {}\n const signatureRaw = headerValue(headers, 'signature')\n const signatureInputRaw = headerValue(headers, 'signature-input')\n if (signatureRaw === undefined || signatureInputRaw === undefined) {\n return failure('no-signature')\n }\n\n const members = parseSignatureInput(signatureInputRaw)\n const signatures = parseSignatureDict(signatureRaw)\n if (members === null || signatures === null || members.length === 0) {\n return failure('malformed')\n }\n\n // First Signature-Input member with a matching Signature entry.\n const member = members.find((candidate) => signatures.has(candidate.label))\n if (member === undefined) return failure('malformed')\n const signatureB64 = signatures.get(member.label) as string\n\n // Anti-replay: the signature must pin the authority and the agent identity.\n const covered = member.components.map((component) => component.toLowerCase())\n if (!covered.includes('@authority') || !covered.includes('signature-agent')) {\n return failure('malformed')\n }\n\n const alg = member.params.get('alg')\n if (alg !== undefined && alg !== 'ed25519') return failure('unsupported-alg')\n\n const keyidParam = member.params.get('keyid')\n const keyid = typeof keyidParam === 'string' && keyidParam.length > 0 ? keyidParam : undefined\n\n // Agent identity → registry entry.\n const signatureAgentRaw = headerValue(headers, 'signature-agent')\n if (signatureAgentRaw === undefined) return failure('unknown-agent', keyid)\n const origin = signatureAgentOrigin(signatureAgentRaw)\n if (origin === null) return failure('unknown-agent', keyid)\n const entry = registryEntryFor(options.keys, origin)\n if (entry === undefined) return failure('unknown-agent', keyid)\n\n // keyid → registry key.\n if (keyid === undefined) return failure('malformed')\n const key = entry.keys.find((candidate) => candidate.keyid === keyid)\n if (key === undefined) return failure('unknown-key', keyid)\n if (key.alg !== 'ed25519') return failure('unsupported-alg', keyid)\n\n // Validity window (±CLOCK_SKEW_SECONDS).\n const created = member.params.get('created')\n const expires = member.params.get('expires')\n if (typeof created !== 'number' || !Number.isInteger(created)) return failure('malformed', keyid)\n if (typeof expires !== 'number' || !Number.isInteger(expires)) return failure('malformed', keyid)\n if (created > expires) return failure('malformed', keyid)\n const nowSeconds = Math.floor((options.now ?? new Date()).getTime() / 1000)\n if (created - CLOCK_SKEW_SECONDS > nowSeconds) return failure('created-in-future', keyid)\n if (expires + CLOCK_SKEW_SECONDS < nowSeconds) return failure('expired', keyid)\n\n // Signature base (RFC 9421 § 2.5): one line per covered component, then\n // \"@signature-params\" with the agent's exact Signature-Input serialization.\n const lines: string[] = []\n for (const component of covered) {\n const value = componentValue(component, input)\n if (value === null) return failure('malformed', keyid)\n lines.push(`\"${component}\": ${value}`)\n }\n lines.push(`\"@signature-params\": ${member.raw}`)\n const base = lines.join('\\n')\n\n const signatureBytes = base64Decode(signatureB64)\n if (signatureBytes === null) return failure('malformed', keyid)\n if (signatureBytes.length !== 64) return failure('bad-signature', keyid)\n\n let cryptoKey: CryptoKey\n try {\n cryptoKey = await crypto.subtle.importKey(\n 'jwk',\n key.publicKeyJwk,\n { name: 'Ed25519' },\n false,\n ['verify'],\n )\n } catch {\n // Registry key material is unusable — an operator/registry problem.\n return failure('unknown-key', keyid)\n }\n\n let ok = false\n try {\n ok = await crypto.subtle.verify(\n 'Ed25519',\n cryptoKey,\n signatureBytes,\n new TextEncoder().encode(base),\n )\n } catch {\n ok = false\n }\n if (!ok) return failure('bad-signature', keyid)\n\n return { verified: true, platform: entry.platform, keyid }\n}\n","/**\n * KNOWN_AGENT_DIRECTORY — the built-in Web Bot Auth key registry.\n *\n * THIS IS A DATA MODULE, AND IT SHIPS EMPTY — DELIBERATELY. We do not embed\n * \"known\" production public keys for OpenAI, Anthropic, Perplexity, etc.,\n * because we have not fetched and pinned them from the platforms' published\n * key directories, and inventing key material would make verification\n * silently meaningless (a fabricated key either verifies nothing or, worse,\n * verifies the wrong thing). Honesty over completeness.\n *\n * How this gets populated (operator responsibility, README § Verification):\n * agent platforms publish their signing keys at well-known HTTP message\n * signature directories (e.g. `https://<platform>/.well-known/\n * http-message-signatures-directory`). Operators fetch those OFFLINE — never\n * on the request hot path — pin the Ed25519 public keys here (or in their own\n * registry object; any `AgentKeyRegistry` works), and refresh on key\n * rotation. A refresh script that snapshots the published directories into\n * this module is future work (ROADMAP parking-lot material).\n *\n * Shape of a populated entry (this example is NOT a real key):\n *\n * 'https://chatgpt.com': {\n * platform: 'chatgpt',\n * keys: [\n * {\n * keyid: 'poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U', // JWK thumbprint the agent sends\n * alg: 'ed25519',\n * publicKeyJwk: { kty: 'OKP', crv: 'Ed25519', x: '<base64url public key bytes>' },\n * },\n * ],\n * },\n *\n * With the directory empty, verifyWebBotAuth() resolves every signed request\n * to `{ verified: false, reason: 'unknown-agent' }` — the honest answer when\n * no trusted key is on file.\n */\n\nimport type { AgentKeyRegistry } from './verify'\n\nexport const KNOWN_AGENT_DIRECTORY: AgentKeyRegistry = {\n // Intentionally empty — see the module header. Operators populate this (or\n // pass their own registry) from the platforms' published key directories.\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,7 +1,23 @@
|
|
|
1
1
|
/** Coarse classification of who (or what) issued the request. */
|
|
2
2
|
type RequesterKind = 'agent' | 'human' | 'crawler' | 'protocol';
|
|
3
|
-
/**
|
|
4
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Known agent/crawler platforms. Grows as new agents are observed (add a
|
|
5
|
+
* fixture too).
|
|
6
|
+
*
|
|
7
|
+
* **There is deliberately no `copilot` member.** Microsoft Copilot has no
|
|
8
|
+
* distinct user agent: it is answered from Bing's index and its fetches arrive
|
|
9
|
+
* as `bingbot`, which is why Microsoft's own guidance for reaching Copilot is
|
|
10
|
+
* "allow bingbot". A `copilot` platform keyed on a UA token would be a rule
|
|
11
|
+
* that never fires and a fixture that was never observed — and the fixture
|
|
12
|
+
* corpus is only worth anything because every sample in it is real. Copilot
|
|
13
|
+
* DOES exist as a referrer platform in `@rebilder/events`
|
|
14
|
+
* (`copilot.microsoft.com`), because an AI-referred human genuinely does
|
|
15
|
+
* arrive from it. Agent fetch attributed to `bingbot`, human arrival
|
|
16
|
+
* attributed to `copilot`, and neither one invented.
|
|
17
|
+
*/
|
|
18
|
+
type AgentPlatform = 'claude-code' | 'opencode' | 'claude' | 'chatgpt' | 'gemini' | 'perplexity' | 'googlebot' | 'bingbot'
|
|
19
|
+
/** Microsoft's product-preview fetcher (`MicrosoftPreview/2.0`) — not Bing. */
|
|
20
|
+
| 'microsoft-preview' | 'unknown';
|
|
5
21
|
interface DetectInput {
|
|
6
22
|
/**
|
|
7
23
|
* Request headers. Lookup is case-insensitive; multi-value headers may be
|
|
@@ -35,6 +51,26 @@ interface DetectionResult {
|
|
|
35
51
|
confidence: 'high' | 'medium' | 'low';
|
|
36
52
|
}
|
|
37
53
|
|
|
54
|
+
/**
|
|
55
|
+
* Does this raw `Accept` header EXPLICITLY ask for `text/markdown`?
|
|
56
|
+
*
|
|
57
|
+
* Exported because the answer is a fact about the serving decision, and a
|
|
58
|
+
* second implementation of it would be free to disagree with the first. The
|
|
59
|
+
* Console's Accept panel reports how many agent requests asked for markdown;
|
|
60
|
+
* if that number were computed by a SQL `LIKE` it would quietly drift from
|
|
61
|
+
* what `detect()` actually did, and the panel would be describing a gateway
|
|
62
|
+
* that does not exist.
|
|
63
|
+
*
|
|
64
|
+
* A WILDCARD RANGE DOES NOT COUNT, and that is the whole point of the panel.
|
|
65
|
+
* Under ordinary HTTP content negotiation a wildcard accepts everything, but
|
|
66
|
+
* this standard reads only an EXPLICIT range: an agent sending the catch-all
|
|
67
|
+
* range has expressed no preference, and counting it as "asked for markdown"
|
|
68
|
+
* would turn the honest headline ("almost nobody asks; we serve it anyway")
|
|
69
|
+
* into a meaningless one where almost everybody asks.
|
|
70
|
+
*
|
|
71
|
+
* `text/markdown;q=0` is a refusal and returns false, same as `detect()`.
|
|
72
|
+
*/
|
|
73
|
+
declare function acceptsMarkdownHeader(accept: string | null | undefined): boolean;
|
|
38
74
|
/**
|
|
39
75
|
* Classify a request from its headers (and optionally URL). Pure compute:
|
|
40
76
|
* no network, no crypto. Checks run cheapest-first; every check that fires
|
|
@@ -176,4 +212,4 @@ declare function verifyWebBotAuth(input: DetectInput, options: VerifyWebBotAuthO
|
|
|
176
212
|
|
|
177
213
|
declare const KNOWN_AGENT_DIRECTORY: AgentKeyRegistry;
|
|
178
214
|
|
|
179
|
-
export { type AgentKeyRegistry, type AgentKeyRegistryEntry, type AgentPlatform, type AgentPublicKey, CLOCK_SKEW_SECONDS, type DetectInput, type DetectionResult, type Ed25519PublicJwk, KNOWN_AGENT_DIRECTORY, type RequesterKind, type VerificationFailureReason, type VerificationResult, type VerifyWebBotAuthOptions, detect, verifyWebBotAuth };
|
|
215
|
+
export { type AgentKeyRegistry, type AgentKeyRegistryEntry, type AgentPlatform, type AgentPublicKey, CLOCK_SKEW_SECONDS, type DetectInput, type DetectionResult, type Ed25519PublicJwk, KNOWN_AGENT_DIRECTORY, type RequesterKind, type VerificationFailureReason, type VerificationResult, type VerifyWebBotAuthOptions, acceptsMarkdownHeader, detect, verifyWebBotAuth };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,23 @@
|
|
|
1
1
|
/** Coarse classification of who (or what) issued the request. */
|
|
2
2
|
type RequesterKind = 'agent' | 'human' | 'crawler' | 'protocol';
|
|
3
|
-
/**
|
|
4
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Known agent/crawler platforms. Grows as new agents are observed (add a
|
|
5
|
+
* fixture too).
|
|
6
|
+
*
|
|
7
|
+
* **There is deliberately no `copilot` member.** Microsoft Copilot has no
|
|
8
|
+
* distinct user agent: it is answered from Bing's index and its fetches arrive
|
|
9
|
+
* as `bingbot`, which is why Microsoft's own guidance for reaching Copilot is
|
|
10
|
+
* "allow bingbot". A `copilot` platform keyed on a UA token would be a rule
|
|
11
|
+
* that never fires and a fixture that was never observed — and the fixture
|
|
12
|
+
* corpus is only worth anything because every sample in it is real. Copilot
|
|
13
|
+
* DOES exist as a referrer platform in `@rebilder/events`
|
|
14
|
+
* (`copilot.microsoft.com`), because an AI-referred human genuinely does
|
|
15
|
+
* arrive from it. Agent fetch attributed to `bingbot`, human arrival
|
|
16
|
+
* attributed to `copilot`, and neither one invented.
|
|
17
|
+
*/
|
|
18
|
+
type AgentPlatform = 'claude-code' | 'opencode' | 'claude' | 'chatgpt' | 'gemini' | 'perplexity' | 'googlebot' | 'bingbot'
|
|
19
|
+
/** Microsoft's product-preview fetcher (`MicrosoftPreview/2.0`) — not Bing. */
|
|
20
|
+
| 'microsoft-preview' | 'unknown';
|
|
5
21
|
interface DetectInput {
|
|
6
22
|
/**
|
|
7
23
|
* Request headers. Lookup is case-insensitive; multi-value headers may be
|
|
@@ -35,6 +51,26 @@ interface DetectionResult {
|
|
|
35
51
|
confidence: 'high' | 'medium' | 'low';
|
|
36
52
|
}
|
|
37
53
|
|
|
54
|
+
/**
|
|
55
|
+
* Does this raw `Accept` header EXPLICITLY ask for `text/markdown`?
|
|
56
|
+
*
|
|
57
|
+
* Exported because the answer is a fact about the serving decision, and a
|
|
58
|
+
* second implementation of it would be free to disagree with the first. The
|
|
59
|
+
* Console's Accept panel reports how many agent requests asked for markdown;
|
|
60
|
+
* if that number were computed by a SQL `LIKE` it would quietly drift from
|
|
61
|
+
* what `detect()` actually did, and the panel would be describing a gateway
|
|
62
|
+
* that does not exist.
|
|
63
|
+
*
|
|
64
|
+
* A WILDCARD RANGE DOES NOT COUNT, and that is the whole point of the panel.
|
|
65
|
+
* Under ordinary HTTP content negotiation a wildcard accepts everything, but
|
|
66
|
+
* this standard reads only an EXPLICIT range: an agent sending the catch-all
|
|
67
|
+
* range has expressed no preference, and counting it as "asked for markdown"
|
|
68
|
+
* would turn the honest headline ("almost nobody asks; we serve it anyway")
|
|
69
|
+
* into a meaningless one where almost everybody asks.
|
|
70
|
+
*
|
|
71
|
+
* `text/markdown;q=0` is a refusal and returns false, same as `detect()`.
|
|
72
|
+
*/
|
|
73
|
+
declare function acceptsMarkdownHeader(accept: string | null | undefined): boolean;
|
|
38
74
|
/**
|
|
39
75
|
* Classify a request from its headers (and optionally URL). Pure compute:
|
|
40
76
|
* no network, no crypto. Checks run cheapest-first; every check that fires
|
|
@@ -176,4 +212,4 @@ declare function verifyWebBotAuth(input: DetectInput, options: VerifyWebBotAuthO
|
|
|
176
212
|
|
|
177
213
|
declare const KNOWN_AGENT_DIRECTORY: AgentKeyRegistry;
|
|
178
214
|
|
|
179
|
-
export { type AgentKeyRegistry, type AgentKeyRegistryEntry, type AgentPlatform, type AgentPublicKey, CLOCK_SKEW_SECONDS, type DetectInput, type DetectionResult, type Ed25519PublicJwk, KNOWN_AGENT_DIRECTORY, type RequesterKind, type VerificationFailureReason, type VerificationResult, type VerifyWebBotAuthOptions, detect, verifyWebBotAuth };
|
|
215
|
+
export { type AgentKeyRegistry, type AgentKeyRegistryEntry, type AgentPlatform, type AgentPublicKey, CLOCK_SKEW_SECONDS, type DetectInput, type DetectionResult, type Ed25519PublicJwk, KNOWN_AGENT_DIRECTORY, type RequesterKind, type VerificationFailureReason, type VerificationResult, type VerifyWebBotAuthOptions, acceptsMarkdownHeader, detect, verifyWebBotAuth };
|
package/dist/index.js
CHANGED
|
@@ -31,6 +31,10 @@ function parseAccept(accept) {
|
|
|
31
31
|
function acceptsMediaType(ranges, mediaType) {
|
|
32
32
|
return ranges.some((range) => range.type === mediaType && range.q > 0);
|
|
33
33
|
}
|
|
34
|
+
function acceptsMarkdownHeader(accept) {
|
|
35
|
+
if (accept === null || accept === void 0 || accept.trim().length === 0) return false;
|
|
36
|
+
return acceptsMediaType(parseAccept(accept), "text/markdown");
|
|
37
|
+
}
|
|
34
38
|
function parseSignatureAgentHost(value) {
|
|
35
39
|
const first = value.split(",")[0] ?? "";
|
|
36
40
|
const unquoted = first.trim().replace(/^"/, "").replace(/"$/, "").trim();
|
|
@@ -73,7 +77,15 @@ function matchProtocolRoute(pathname) {
|
|
|
73
77
|
}
|
|
74
78
|
var CRAWLER_UA = [
|
|
75
79
|
{ pattern: "googlebot", platform: "googlebot" },
|
|
76
|
-
{ pattern: "bingbot", platform: "bingbot" }
|
|
80
|
+
{ pattern: "bingbot", platform: "bingbot" },
|
|
81
|
+
// Bing Ads landing-page quality crawler. Its own UA points at
|
|
82
|
+
// bing.com/bingbot.htm, so it is attributed to the bingbot platform.
|
|
83
|
+
{ pattern: "adidxbot", platform: "bingbot" },
|
|
84
|
+
// Microsoft product previews (link unfurling in Teams, Outlook, and the
|
|
85
|
+
// like). A separate platform because it is not Bing and not an assistant:
|
|
86
|
+
// attributing it to `bingbot` would inflate a merchant's Bing figure with
|
|
87
|
+
// traffic that never touched the index.
|
|
88
|
+
{ pattern: "microsoftpreview", platform: "microsoft-preview" }
|
|
77
89
|
];
|
|
78
90
|
var AGENT_UA = [
|
|
79
91
|
{ pattern: "claude-code", platform: "claude-code" },
|
|
@@ -139,7 +151,12 @@ function detect(input) {
|
|
|
139
151
|
};
|
|
140
152
|
}
|
|
141
153
|
if (protocolRoute !== null) {
|
|
142
|
-
return {
|
|
154
|
+
return {
|
|
155
|
+
...base,
|
|
156
|
+
kind: "protocol",
|
|
157
|
+
platform: agentUaMatch?.platform ?? null,
|
|
158
|
+
confidence: "high"
|
|
159
|
+
};
|
|
143
160
|
}
|
|
144
161
|
if (agentUaMatch !== void 0) {
|
|
145
162
|
return { ...base, kind: "agent", platform: agentUaMatch.platform, confidence: "medium" };
|
|
@@ -438,6 +455,6 @@ var KNOWN_AGENT_DIRECTORY = {
|
|
|
438
455
|
// pass their own registry) from the platforms' published key directories.
|
|
439
456
|
};
|
|
440
457
|
|
|
441
|
-
export { CLOCK_SKEW_SECONDS, KNOWN_AGENT_DIRECTORY, detect, verifyWebBotAuth };
|
|
458
|
+
export { CLOCK_SKEW_SECONDS, KNOWN_AGENT_DIRECTORY, acceptsMarkdownHeader, detect, verifyWebBotAuth };
|
|
442
459
|
//# sourceMappingURL=index.js.map
|
|
443
460
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/detect.ts","../src/verify.ts","../src/directory.ts"],"names":["headerValue"],"mappings":";AAOA,SAAS,WAAA,CACP,SACA,IAAA,EACoB;AACpB,EAAA,MAAM,MAAA,GAAS,KAAK,WAAA,EAAY;AAChC,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,OAAO,CAAA,EAAG;AAClD,IAAA,IAAI,GAAA,CAAI,WAAA,EAAY,KAAM,MAAA,IAAU,UAAU,MAAA,EAAW;AACzD,IAAA,OAAO,MAAM,OAAA,CAAQ,KAAK,IAAI,KAAA,CAAM,IAAA,CAAK,IAAI,CAAA,GAAI,KAAA;AAAA,EACnD;AACA,EAAA,OAAO,MAAA;AACT;AAWA,SAAS,YAAY,MAAA,EAA8B;AACjD,EAAA,MAAM,SAAuB,EAAC;AAC9B,EAAA,KAAA,MAAW,IAAA,IAAQ,MAAA,CAAO,KAAA,CAAM,GAAG,CAAA,EAAG;AACpC,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,IAAA,EAAK,CAAE,MAAM,GAAG,CAAA;AACtC,IAAA,MAAM,QAAQ,QAAA,CAAS,CAAC,KAAK,EAAA,EAAI,IAAA,GAAO,WAAA,EAAY;AACpD,IAAA,IAAI,IAAA,CAAK,WAAW,CAAA,EAAG;AACvB,IAAA,IAAI,CAAA,GAAI,CAAA;AACR,IAAA,KAAA,MAAW,OAAA,IAAW,QAAA,CAAS,KAAA,CAAM,CAAC,CAAA,EAAG;AACvC,MAAA,MAAM,EAAA,GAAK,OAAA,CAAQ,OAAA,CAAQ,GAAG,CAAA;AAC9B,MAAA,IAAI,OAAO,EAAA,EAAI;AACf,MAAA,MAAM,GAAA,GAAM,QAAQ,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,CAAE,IA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F,IAAA,EAAA,GAAK,MAAM,OAAO,MAAA,CAAO,MAAA;AAAA,MACvB,SAAA;AAAA,MACA,SAAA;AAAA,MACA,cAAA;AAAA,MACA,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,IAAI;AAAA,KAC/B;AAAA,EACF,CAAA,CAAA,MAAQ;AACN,IAAA,EAAA,GAAK,KAAA;AAAA,EACP;AACA,EAAA,IAAI,CAAC,EAAA,EAAI,OAAO,OAAA,CAAQ,iBAAiB,KAAK,CAAA;AAE9C,EAAA,OAAO,EAAE,QAAA,EAAU,IAAA,EAAM,QAAA,EAAU,KAAA,CAAM,UAAU,KAAA,EAAM;AAC3D;;;ACvcO,IAAM,qBAAA,GAA0C;AAAA;AAAA;AAGvD","file":"index.js","sourcesContent":["import type { AgentPlatform, DetectInput, DetectionResult } from './types'\n\n// ---------------------------------------------------------------------------\n// Header utilities\n// ---------------------------------------------------------------------------\n\n/** Case-insensitive header lookup. Array values are comma-joined (RFC 9110). */\nfunction headerValue(\n headers: Record<string, string | string[] | undefined>,\n name: string,\n): string | undefined {\n const target = name.toLowerCase()\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== target || value === undefined) continue\n return Array.isArray(value) ? value.join(', ') : value\n }\n return undefined\n}\n\n// ---------------------------------------------------------------------------\n// Accept parsing (media ranges with q-values)\n// ---------------------------------------------------------------------------\n\ninterface MediaRange {\n type: string\n q: number\n}\n\nfunction parseAccept(accept: string): MediaRange[] {\n const ranges: MediaRange[] = []\n for (const part of accept.split(',')) {\n const segments = part.trim().split(';')\n const type = (segments[0] ?? '').trim().toLowerCase()\n if (type.length === 0) continue\n let q = 1\n for (const segment of segments.slice(1)) {\n const eq = segment.indexOf('=')\n if (eq === -1) continue\n const key = segment.slice(0, eq).trim().toLowerCase()\n const value = segment.slice(eq + 1).trim()\n if (key === 'q') {\n const parsed = Number(value)\n if (Number.isFinite(parsed)) q = parsed\n }\n }\n ranges.push({ type, q })\n }\n return ranges\n}\n\n/** Explicit (non-wildcard) media type present with q > 0. */\nfunction acceptsMediaType(ranges: MediaRange[], mediaType: string): boolean {\n return ranges.some((range) => range.type === mediaType && range.q > 0)\n}\n\n// ---------------------------------------------------------------------------\n// Web Bot Auth (Signature-Agent / Signature / Signature-Input)\n// ---------------------------------------------------------------------------\n\n/**\n * Extract the host from a Signature-Agent structured-field value, e.g.\n * `\"https://chatgpt.com\"` -> `chatgpt.com`. No verification — parse only.\n */\nfunction parseSignatureAgentHost(value: string): string | null {\n const first = value.split(',')[0] ?? ''\n const unquoted = first.trim().replace(/^\"/, '').replace(/\"$/, '').trim()\n if (unquoted.length === 0) return null\n try {\n return new URL(unquoted).hostname.toLowerCase()\n } catch {\n return unquoted.toLowerCase()\n }\n}\n\nconst SIGNATURE_AGENT_PLATFORMS: ReadonlyArray<readonly [string, AgentPlatform]> = [\n ['chatgpt.com', 'chatgpt'],\n ['openai.com', 'chatgpt'],\n ['claude.ai', 'claude'],\n ['anthropic.com', 'claude'],\n ['perplexity.ai', 'perplexity'],\n ['gemini.google.com', 'gemini'],\n]\n\nfunction platformForSignatureAgentHost(host: string): AgentPlatform {\n for (const [domain, platform] of SIGNATURE_AGENT_PLATFORMS) {\n if (host === domain || host.endsWith(`.${domain}`)) return platform\n }\n return 'unknown'\n}\n\n// ---------------------------------------------------------------------------\n// Protocol routes\n// ---------------------------------------------------------------------------\n\nconst PROTOCOL_ROUTES = ['/.well-known/ucp', '/.well-known/acp', '/mcp', '/acp'] as const\n\nfunction pathnameOf(url: string): string {\n try {\n return new URL(url).pathname\n } catch {\n const stripped = url.split('#')[0]?.split('?')[0] ?? ''\n return stripped\n }\n}\n\nfunction matchProtocolRoute(pathname: string): string | null {\n const path = pathname.toLowerCase().replace(/\\/+$/, '') || '/'\n for (const route of PROTOCOL_ROUTES) {\n if (path === route || path.startsWith(`${route}/`)) return route\n }\n return null\n}\n\n// ---------------------------------------------------------------------------\n// User-Agent heuristics (fallback only — see README: UA alone never justifies\n// substantive content differences; confidence is capped at 'medium')\n// ---------------------------------------------------------------------------\n\ninterface UaEntry {\n pattern: string\n platform: AgentPlatform\n}\n\n/**\n * Crawler UAs are checked before everything else: a known crawler is always\n * classified 'crawler' regardless of other signals (cloaking guardrail —\n * Googlebot must receive canonical HTML, never markdown).\n */\nconst CRAWLER_UA: readonly UaEntry[] = [\n { pattern: 'googlebot', platform: 'googlebot' },\n { pattern: 'bingbot', platform: 'bingbot' },\n]\n\n/** Order matters: more specific tokens before broader ones. */\nconst AGENT_UA: readonly UaEntry[] = [\n { pattern: 'claude-code', platform: 'claude-code' },\n { pattern: 'opencode', platform: 'opencode' },\n { pattern: 'chatgpt-user', platform: 'chatgpt' },\n { pattern: 'oai-searchbot', platform: 'chatgpt' },\n { pattern: 'gptbot', platform: 'chatgpt' },\n { pattern: 'perplexitybot', platform: 'perplexity' },\n { pattern: 'perplexity-user', platform: 'perplexity' },\n { pattern: 'google-extended', platform: 'gemini' },\n { pattern: 'gemini', platform: 'gemini' },\n { pattern: 'claude-web', platform: 'claude' },\n { pattern: 'claudebot', platform: 'claude' },\n { pattern: 'claude-user', platform: 'claude' },\n { pattern: 'anthropic-ai', platform: 'claude' },\n]\n\nfunction findUaEntry(ua: string, table: readonly UaEntry[]): UaEntry | undefined {\n return table.find((entry) => ua.includes(entry.pattern))\n}\n\n// ---------------------------------------------------------------------------\n// detect()\n// ---------------------------------------------------------------------------\n\n/**\n * Classify a request from its headers (and optionally URL). Pure compute:\n * no network, no crypto. Checks run cheapest-first; every check that fires\n * is recorded in `signals`, and the highest-precedence one classifies.\n *\n * Precedence: crawler UA (guardrail) > Accept: text/markdown >\n * Signature-Agent / Web Bot Auth headers > protocol route > agent UA > human.\n */\nexport function detect(input: DetectInput): DetectionResult {\n const headers = input.headers ?? {}\n const signals: string[] = []\n\n // Gather raw evidence once.\n const acceptRaw = headerValue(headers, 'accept')\n const ranges = acceptRaw === undefined ? [] : parseAccept(acceptRaw)\n const acceptsMarkdown = acceptsMediaType(ranges, 'text/markdown')\n const acceptsHtml = acceptsMediaType(ranges, 'text/html')\n\n const ua = (headerValue(headers, 'user-agent') ?? '').toLowerCase()\n const crawlerMatch = findUaEntry(ua, CRAWLER_UA)\n const agentUaMatch = crawlerMatch === undefined ? findUaEntry(ua, AGENT_UA) : undefined\n\n const signatureAgentRaw = headerValue(headers, 'signature-agent')\n const signatureAgentHost =\n signatureAgentRaw === undefined ? null : parseSignatureAgentHost(signatureAgentRaw)\n const hasSignaturePair =\n headerValue(headers, 'signature') !== undefined &&\n headerValue(headers, 'signature-input') !== undefined\n\n const protocolRoute = input.url === undefined ? null : matchProtocolRoute(pathnameOf(input.url))\n\n // Record fired checks in detection order.\n if (acceptsMarkdown) signals.push('accept:text/markdown')\n if (signatureAgentHost !== null) signals.push(`signature-agent:${signatureAgentHost}`)\n if (hasSignaturePair) signals.push('web-bot-auth:signature')\n if (protocolRoute !== null) signals.push(`protocol:${protocolRoute}`)\n if (crawlerMatch !== undefined) signals.push(`ua:${crawlerMatch.pattern}`)\n if (agentUaMatch !== undefined) signals.push(`ua:${agentUaMatch.pattern}`)\n\n const base = { verified: false as const, acceptsMarkdown, signals }\n\n // 0. Cloaking guardrail: a known crawler UA always classifies as crawler,\n // even if other signals fired. Googlebot never takes the agent path.\n if (crawlerMatch !== undefined) {\n return { ...base, kind: 'crawler', platform: crawlerMatch.platform, confidence: 'medium' }\n }\n\n // 1. Accept: text/markdown — the cheapest, most explicit agent signal.\n // Platform attribution prefers Signature-Agent (a stated identity) over UA.\n if (acceptsMarkdown) {\n const signaturePlatform =\n signatureAgentHost !== null ? platformForSignatureAgentHost(signatureAgentHost) : null\n const platform = signaturePlatform ?? agentUaMatch?.platform ?? 'unknown'\n return { ...base, kind: 'agent', platform, confidence: 'high' }\n }\n\n // 2. Web Bot Auth headers — parse only here; cryptographic verification is\n // the separate async verifyWebBotAuth() step (src/verify.ts).\n if (signatureAgentHost !== null) {\n return {\n ...base,\n kind: 'agent',\n platform: platformForSignatureAgentHost(signatureAgentHost),\n confidence: 'high',\n }\n }\n if (hasSignaturePair) {\n return {\n ...base,\n kind: 'agent',\n platform: agentUaMatch?.platform ?? 'unknown',\n confidence: 'medium',\n }\n }\n\n // 3. Protocol route hit.\n if (protocolRoute !== null) {\n return { ...base, kind: 'protocol', platform: agentUaMatch?.platform ?? null, confidence: 'high' }\n }\n\n // 4. UA heuristics — fallback only, capped at medium confidence.\n if (agentUaMatch !== undefined) {\n return { ...base, kind: 'agent', platform: agentUaMatch.platform, confidence: 'medium' }\n }\n\n // 5. Default: human. High confidence only with a browserish Accept/UA.\n if (acceptsHtml) signals.push('accept:text/html')\n else if (ua.includes('mozilla/')) signals.push('ua:browser')\n const browserish = acceptsHtml || ua.includes('mozilla/')\n return { ...base, kind: 'human', platform: null, confidence: browserish ? 'high' : 'low' }\n}\n","/**\n * Web Bot Auth verification — the Phase 3 async counterpart to detect().\n *\n * PURE CRYPTO WITH INJECTED KEYS. This module verifies RFC 9421-style HTTP\n * message signatures (Signature-Input / Signature / Signature-Agent) against\n * a caller-provided key registry. It NEVER fetches a key directory, never\n * touches the network, never reads the environment — the registry is\n * dependency-injected, so the hot path stays within the edge budget\n * (CLAUDE.md Conventions: no network calls on the hot path). Key directory\n * refresh is an offline/operator concern (see README § Verification).\n *\n * detect() stays synchronous and unchanged: it parses these headers as\n * identity *signals* only and always reports `verified: false`. Paths that\n * need cryptographic identity (preference payloads, protocol transactions —\n * ROADMAP Phase 3 P0) call verifyWebBotAuth() as a separate async step.\n *\n * Failure behavior is constant: malformed, hostile, or garbage input NEVER\n * throws — every path resolves to `{ verified: false, reason }`.\n */\n\nimport type { AgentPlatform, DetectInput } from './types'\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/** Why verification did not succeed. */\nexport type VerificationFailureReason =\n | 'no-signature' // no Signature + Signature-Input header pair on the request\n | 'unknown-agent' // no Signature-Agent header, or its origin is not in the registry\n | 'unknown-key' // keyid not found for that agent, or the registry key material is unusable\n | 'expired' // `expires` is more than the allowed clock skew in the past\n | 'created-in-future' // `created` is more than the allowed clock skew in the future\n | 'bad-signature' // signature bytes do not verify over the reconstructed base\n | 'malformed' // unparseable/unsupported headers, or a covered component we cannot reconstruct\n | 'unsupported-alg' // signature declares an algorithm other than ed25519\n\nexport interface VerificationResult {\n verified: boolean\n /** The registry entry's platform, set only when verified. */\n platform?: AgentPlatform\n /** The keyid parsed from Signature-Input, set once parsing got that far. */\n keyid?: string\n /** Set exactly when `verified` is false. */\n reason?: VerificationFailureReason\n}\n\n/** An Ed25519 public key in JWK form (RFC 8037: OKP / Ed25519 / x). */\nexport interface Ed25519PublicJwk {\n kty: 'OKP'\n crv: 'Ed25519'\n /** base64url-encoded public key bytes. */\n x: string\n}\n\nexport interface AgentPublicKey {\n /** Matches the `keyid` parameter the agent sends in Signature-Input. */\n keyid: string\n /** ed25519 is the only algorithm supported in v0. */\n alg: 'ed25519'\n publicKeyJwk: Ed25519PublicJwk\n}\n\nexport interface AgentKeyRegistryEntry {\n /** The platform this origin's keys attest to. */\n platform: AgentPlatform\n keys: AgentPublicKey[]\n}\n\n/**\n * Key registry keyed by the agent's Signature-Agent origin, e.g.\n * `\"https://chatgpt.com\"`. Bare hosts (`\"chatgpt.com\"`) are accepted and\n * normalized to the https origin. See KNOWN_AGENT_DIRECTORY (src/directory.ts)\n * for the shape — it ships EMPTY; operators populate it from the platforms'\n * published key directories.\n */\nexport type AgentKeyRegistry = Record<string, AgentKeyRegistryEntry>\n\nexport interface VerifyWebBotAuthOptions {\n /** The injected key registry. Verification is pure crypto over these keys. */\n keys: AgentKeyRegistry\n /** Clock override for tests/replays. Defaults to `new Date()`. */\n now?: Date\n /**\n * Deliberately impossible to set: this function performs NO network I/O.\n * Key directory fetch/refresh happens offline, outside this module.\n */\n fetchImpl?: never\n}\n\n/** Allowed clock skew for `created` / `expires`, in seconds (±). */\nexport const CLOCK_SKEW_SECONDS = 300\n\n// ---------------------------------------------------------------------------\n// Header + structured-field parsing (RFC 8941 subset, RFC 9421 shapes)\n// ---------------------------------------------------------------------------\n\n/** Case-insensitive header lookup; array values comma-joined (RFC 9110). */\nfunction headerValue(\n headers: Record<string, string | string[] | undefined>,\n name: string,\n): string | undefined {\n const target = name.toLowerCase()\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== target || value === undefined) continue\n return Array.isArray(value) ? value.join(', ') : value\n }\n return undefined\n}\n\nconst KEY_CHAR = /[a-zA-Z0-9_.*-]/\nconst PARAM_VALUE_END = /[;,\\s]/\n\ninterface Scanner {\n s: string\n i: number\n}\n\nfunction skipOws(sc: Scanner): void {\n while (sc.i < sc.s.length && (sc.s[sc.i] === ' ' || sc.s[sc.i] === '\\t')) sc.i++\n}\n\n/** Reads an sf-key at the cursor; null when none is present. */\nfunction readKey(sc: Scanner): string | null {\n const start = sc.i\n while (sc.i < sc.s.length && KEY_CHAR.test(sc.s[sc.i] as string)) sc.i++\n return sc.i > start ? sc.s.slice(start, sc.i) : null\n}\n\n/** Reads a quoted sf-string at the cursor (cursor on the opening quote). */\nfunction readQuoted(sc: Scanner): string | null {\n if (sc.s[sc.i] !== '\"') return null\n sc.i++\n let out = ''\n while (sc.i < sc.s.length) {\n const ch = sc.s[sc.i] as string\n if (ch === '\\\\') {\n if (sc.i + 1 >= sc.s.length) return null\n out += sc.s[sc.i + 1] as string\n sc.i += 2\n continue\n }\n if (ch === '\"') {\n sc.i++\n return out\n }\n out += ch\n sc.i++\n }\n return null // unterminated\n}\n\n/** Reads `;name[=value]` parameters into a map. Null on malformed input. */\nfunction readParams(sc: Scanner): Map<string, string | number | true> | null {\n const params = new Map<string, string | number | true>()\n while (sc.i < sc.s.length && sc.s[sc.i] === ';') {\n sc.i++\n skipOws(sc)\n const name = readKey(sc)\n if (name === null) return null\n let value: string | number | true = true\n if (sc.s[sc.i] === '=') {\n sc.i++\n if (sc.s[sc.i] === '\"') {\n const quoted = readQuoted(sc)\n if (quoted === null) return null\n value = quoted\n } else {\n const start = sc.i\n while (sc.i < sc.s.length && !PARAM_VALUE_END.test(sc.s[sc.i] as string)) sc.i++\n const token = sc.s.slice(start, sc.i)\n if (token.length === 0) return null\n value = /^-?\\d+$/.test(token) ? Number(token) : token\n }\n }\n params.set(name, value)\n }\n return params\n}\n\ninterface SignatureInputMember {\n label: string\n /** Covered component names, as sent (lowercased at use time). */\n components: string[]\n params: Map<string, string | number | true>\n /**\n * The EXACT serialization after `label=` — reused verbatim as the\n * `\"@signature-params\"` line of the signature base, so no re-serialization\n * ambiguity can break verification.\n */\n raw: string\n}\n\n/**\n * Parses a Signature-Input dictionary:\n * `sig1=(\"@authority\" \"signature-agent\");created=...;keyid=\"...\", sig2=...`\n * Returns null on any malformed member. Components carrying their own\n * parameters (e.g. `\"@query-param\";name=\"q\"`) are unsupported in v0 →\n * treated as malformed.\n */\nfunction parseSignatureInput(value: string): SignatureInputMember[] | null {\n const sc: Scanner = { s: value, i: 0 }\n const members: SignatureInputMember[] = []\n skipOws(sc)\n while (sc.i < sc.s.length) {\n const label = readKey(sc)\n if (label === null || sc.s[sc.i] !== '=') return null\n sc.i++\n if (sc.s[sc.i] !== '(') return null\n const rawStart = sc.i\n sc.i++\n const components: string[] = []\n for (;;) {\n skipOws(sc)\n if (sc.i >= sc.s.length) return null\n if (sc.s[sc.i] === ')') {\n sc.i++\n break\n }\n const component = readQuoted(sc)\n if (component === null) return null\n if (sc.s[sc.i] === ';') return null // per-component parameters: unsupported in v0\n components.push(component)\n }\n const params = readParams(sc)\n if (params === null) return null\n members.push({ label, components, params, raw: sc.s.slice(rawStart, sc.i) })\n skipOws(sc)\n if (sc.i >= sc.s.length) break\n if (sc.s[sc.i] !== ',') return null\n sc.i++\n skipOws(sc)\n }\n return members\n}\n\n/**\n * Parses a Signature dictionary of byte sequences:\n * `sig1=:BASE64==:, sig2=:...:` → label → base64 payload.\n */\nfunction parseSignatureDict(value: string): Map<string, string> | null {\n const sc: Scanner = { s: value, i: 0 }\n const out = new Map<string, string>()\n skipOws(sc)\n while (sc.i < sc.s.length) {\n const label = readKey(sc)\n if (label === null || sc.s[sc.i] !== '=') return null\n sc.i++\n if (sc.s[sc.i] !== ':') return null\n sc.i++\n const start = sc.i\n while (sc.i < sc.s.length && sc.s[sc.i] !== ':') sc.i++\n if (sc.i >= sc.s.length) return null // unterminated byte sequence\n out.set(label, sc.s.slice(start, sc.i))\n sc.i++\n if (readParams(sc) === null) return null // tolerate (and ignore) member params\n skipOws(sc)\n if (sc.i >= sc.s.length) break\n if (sc.s[sc.i] !== ',') return null\n sc.i++\n skipOws(sc)\n }\n return out\n}\n\n// ---------------------------------------------------------------------------\n// Origins, base64, component values\n// ---------------------------------------------------------------------------\n\n/** Normalizes an origin-ish string (\"https://x.com\", \"x.com\") to a URL origin. */\nfunction normalizeOrigin(value: string): string | null {\n const trimmed = value.trim()\n if (trimmed.length === 0) return null\n const candidate = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`\n try {\n return new URL(candidate).origin.toLowerCase()\n } catch {\n return null\n }\n}\n\n/** First item of the Signature-Agent list, unquoted → normalized origin. */\nfunction signatureAgentOrigin(raw: string): string | null {\n const first = raw.split(',')[0] ?? ''\n const sc: Scanner = { s: first.trim(), i: 0 }\n const unquoted = sc.s[0] === '\"' ? readQuoted(sc) : sc.s\n if (unquoted === null || unquoted.length === 0) return null\n return normalizeOrigin(unquoted)\n}\n\n/** Registry lookup with origin normalization on the registry keys too. */\nfunction registryEntryFor(\n keys: AgentKeyRegistry,\n origin: string,\n): AgentKeyRegistryEntry | undefined {\n for (const [registryOrigin, entry] of Object.entries(keys)) {\n if (normalizeOrigin(registryOrigin) === origin) return entry\n }\n return undefined\n}\n\nconst BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/\n\nfunction base64Decode(value: string): Uint8Array<ArrayBuffer> | null {\n if (!BASE64_RE.test(value) || value.length % 4 !== 0) return null\n try {\n const binary = atob(value)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n return bytes\n } catch {\n return null\n }\n}\n\n/**\n * Resolves one covered component's value for the signature base. Returns\n * null when the component cannot be reconstructed from the input (missing\n * header, missing/unparseable URL, unsupported derived component) — which\n * verifyWebBotAuth reports as 'malformed'.\n */\nfunction componentValue(name: string, input: DetectInput): string | null {\n if (name.startsWith('@')) {\n if (name === '@method') {\n return input.method === undefined ? null : input.method.toUpperCase()\n }\n if (input.url === undefined) return null\n let url: URL\n try {\n url = new URL(input.url)\n } catch {\n return null\n }\n switch (name) {\n case '@authority':\n return url.host\n case '@scheme':\n return url.protocol.replace(/:$/, '')\n case '@target-uri':\n return url.href\n case '@path':\n return url.pathname\n case '@query':\n return url.search === '' ? '?' : url.search\n case '@request-target':\n return url.pathname + url.search\n default:\n return null // unsupported derived component in v0\n }\n }\n const value = headerValue(input.headers ?? {}, name)\n return value === undefined ? null : value.trim()\n}\n\n// ---------------------------------------------------------------------------\n// verifyWebBotAuth()\n// ---------------------------------------------------------------------------\n\nfunction failure(reason: VerificationFailureReason, keyid?: string): VerificationResult {\n return keyid === undefined ? { verified: false, reason } : { verified: false, keyid, reason }\n}\n\n/**\n * Verify a request's Web Bot Auth signature chain against an injected key\n * registry. Async (WebCrypto) but pure: no network, no environment, no\n * global state. Never throws — every failure resolves to\n * `{ verified: false, reason }`.\n *\n * Requirements enforced (Web Bot Auth profile over RFC 9421):\n * - `Signature` + `Signature-Input` present, structured-field parseable\n * - covered components include `@authority` AND `signature-agent`\n * (anti-replay: the signature is pinned to this host and this identity)\n * - `keyid`, `created`, `expires` parameters present; `created <= expires`;\n * both within ±CLOCK_SKEW_SECONDS of `options.now`\n * - `alg`, when present, is `ed25519`\n * - `Signature-Agent` origin resolves to a registry entry; `keyid` resolves\n * to one of that entry's keys\n * - Ed25519 signature verifies (WebCrypto subtle) over the RFC 9421\n * signature base, whose `\"@signature-params\"` line reuses the exact\n * serialization the agent sent\n */\nexport async function verifyWebBotAuth(\n input: DetectInput,\n options: VerifyWebBotAuthOptions,\n): Promise<VerificationResult> {\n try {\n return await verifyInner(input, options)\n } catch {\n // Constant behavior on hostile input: never throw.\n return failure('malformed')\n }\n}\n\nasync function verifyInner(\n input: DetectInput,\n options: VerifyWebBotAuthOptions,\n): Promise<VerificationResult> {\n const headers = input.headers ?? {}\n const signatureRaw = headerValue(headers, 'signature')\n const signatureInputRaw = headerValue(headers, 'signature-input')\n if (signatureRaw === undefined || signatureInputRaw === undefined) {\n return failure('no-signature')\n }\n\n const members = parseSignatureInput(signatureInputRaw)\n const signatures = parseSignatureDict(signatureRaw)\n if (members === null || signatures === null || members.length === 0) {\n return failure('malformed')\n }\n\n // First Signature-Input member with a matching Signature entry.\n const member = members.find((candidate) => signatures.has(candidate.label))\n if (member === undefined) return failure('malformed')\n const signatureB64 = signatures.get(member.label) as string\n\n // Anti-replay: the signature must pin the authority and the agent identity.\n const covered = member.components.map((component) => component.toLowerCase())\n if (!covered.includes('@authority') || !covered.includes('signature-agent')) {\n return failure('malformed')\n }\n\n const alg = member.params.get('alg')\n if (alg !== undefined && alg !== 'ed25519') return failure('unsupported-alg')\n\n const keyidParam = member.params.get('keyid')\n const keyid = typeof keyidParam === 'string' && keyidParam.length > 0 ? keyidParam : undefined\n\n // Agent identity → registry entry.\n const signatureAgentRaw = headerValue(headers, 'signature-agent')\n if (signatureAgentRaw === undefined) return failure('unknown-agent', keyid)\n const origin = signatureAgentOrigin(signatureAgentRaw)\n if (origin === null) return failure('unknown-agent', keyid)\n const entry = registryEntryFor(options.keys, origin)\n if (entry === undefined) return failure('unknown-agent', keyid)\n\n // keyid → registry key.\n if (keyid === undefined) return failure('malformed')\n const key = entry.keys.find((candidate) => candidate.keyid === keyid)\n if (key === undefined) return failure('unknown-key', keyid)\n if (key.alg !== 'ed25519') return failure('unsupported-alg', keyid)\n\n // Validity window (±CLOCK_SKEW_SECONDS).\n const created = member.params.get('created')\n const expires = member.params.get('expires')\n if (typeof created !== 'number' || !Number.isInteger(created)) return failure('malformed', keyid)\n if (typeof expires !== 'number' || !Number.isInteger(expires)) return failure('malformed', keyid)\n if (created > expires) return failure('malformed', keyid)\n const nowSeconds = Math.floor((options.now ?? new Date()).getTime() / 1000)\n if (created - CLOCK_SKEW_SECONDS > nowSeconds) return failure('created-in-future', keyid)\n if (expires + CLOCK_SKEW_SECONDS < nowSeconds) return failure('expired', keyid)\n\n // Signature base (RFC 9421 § 2.5): one line per covered component, then\n // \"@signature-params\" with the agent's exact Signature-Input serialization.\n const lines: string[] = []\n for (const component of covered) {\n const value = componentValue(component, input)\n if (value === null) return failure('malformed', keyid)\n lines.push(`\"${component}\": ${value}`)\n }\n lines.push(`\"@signature-params\": ${member.raw}`)\n const base = lines.join('\\n')\n\n const signatureBytes = base64Decode(signatureB64)\n if (signatureBytes === null) return failure('malformed', keyid)\n if (signatureBytes.length !== 64) return failure('bad-signature', keyid)\n\n let cryptoKey: CryptoKey\n try {\n cryptoKey = await crypto.subtle.importKey(\n 'jwk',\n key.publicKeyJwk,\n { name: 'Ed25519' },\n false,\n ['verify'],\n )\n } catch {\n // Registry key material is unusable — an operator/registry problem.\n return failure('unknown-key', keyid)\n }\n\n let ok = false\n try {\n ok = await crypto.subtle.verify(\n 'Ed25519',\n cryptoKey,\n signatureBytes,\n new TextEncoder().encode(base),\n )\n } catch {\n ok = false\n }\n if (!ok) return failure('bad-signature', keyid)\n\n return { verified: true, platform: entry.platform, keyid }\n}\n","/**\n * KNOWN_AGENT_DIRECTORY — the built-in Web Bot Auth key registry.\n *\n * THIS IS A DATA MODULE, AND IT SHIPS EMPTY — DELIBERATELY. We do not embed\n * \"known\" production public keys for OpenAI, Anthropic, Perplexity, etc.,\n * because we have not fetched and pinned them from the platforms' published\n * key directories, and inventing key material would make verification\n * silently meaningless (a fabricated key either verifies nothing or, worse,\n * verifies the wrong thing). Honesty over completeness.\n *\n * How this gets populated (operator responsibility, README § Verification):\n * agent platforms publish their signing keys at well-known HTTP message\n * signature directories (e.g. `https://<platform>/.well-known/\n * http-message-signatures-directory`). Operators fetch those OFFLINE — never\n * on the request hot path — pin the Ed25519 public keys here (or in their own\n * registry object; any `AgentKeyRegistry` works), and refresh on key\n * rotation. A refresh script that snapshots the published directories into\n * this module is future work (ROADMAP parking-lot material).\n *\n * Shape of a populated entry (this example is NOT a real key):\n *\n * 'https://chatgpt.com': {\n * platform: 'chatgpt',\n * keys: [\n * {\n * keyid: 'poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U', // JWK thumbprint the agent sends\n * alg: 'ed25519',\n * publicKeyJwk: { kty: 'OKP', crv: 'Ed25519', x: '<base64url public key bytes>' },\n * },\n * ],\n * },\n *\n * With the directory empty, verifyWebBotAuth() resolves every signed request\n * to `{ verified: false, reason: 'unknown-agent' }` — the honest answer when\n * no trusted key is on file.\n */\n\nimport type { AgentKeyRegistry } from './verify'\n\nexport const KNOWN_AGENT_DIRECTORY: AgentKeyRegistry = {\n // Intentionally empty — see the module header. Operators populate this (or\n // pass their own registry) from the platforms' published key directories.\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/detect.ts","../src/verify.ts","../src/directory.ts"],"names":["headerValue"],"mappings":";AAOA,SAAS,WAAA,CACP,SACA,IAAA,EACoB;AACpB,EAAA,MAAM,MAAA,GAAS,KAAK,WAAA,EAAY;AAChC,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,OAAO,CAAA,EAAG;AAClD,IAAA,IAAI,GAAA,CAAI,WAAA,EAAY,KAAM,MAAA,IAAU,UAAU,MAAA,EAAW;AACzD,IAAA,OAAO,MAAM,OAAA,CAAQ,KAAK,IAAI,KAAA,CAAM,IAAA,CAAK,IAAI,CAAA,GAAI,KAAA;AAAA,EACnD;AACA,EAAA,OAAO,MAAA;AACT;AAWA,SAAS,YAAY,MAAA,EAA8B;AACjD,EAAA,MAAM,SAAuB,EAAC;AAC9B,EAAA,KAAA,MAAW,IAAA,IAAQ,MAAA,CAAO,KAAA,CAAM,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I,OAAO,OAAA,CAAQ,iBAAiB,KAAK,CAAA;AAE9C,EAAA,OAAO,EAAE,QAAA,EAAU,IAAA,EAAM,QAAA,EAAU,KAAA,CAAM,UAAU,KAAA,EAAM;AAC3D;;;ACvcO,IAAM,qBAAA,GAA0C;AAAA;AAAA;AAGvD","file":"index.js","sourcesContent":["import type { AgentPlatform, DetectInput, DetectionResult } from './types'\n\n// ---------------------------------------------------------------------------\n// Header utilities\n// ---------------------------------------------------------------------------\n\n/** Case-insensitive header lookup. Array values are comma-joined (RFC 9110). */\nfunction headerValue(\n headers: Record<string, string | string[] | undefined>,\n name: string,\n): string | undefined {\n const target = name.toLowerCase()\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== target || value === undefined) continue\n return Array.isArray(value) ? value.join(', ') : value\n }\n return undefined\n}\n\n// ---------------------------------------------------------------------------\n// Accept parsing (media ranges with q-values)\n// ---------------------------------------------------------------------------\n\ninterface MediaRange {\n type: string\n q: number\n}\n\nfunction parseAccept(accept: string): MediaRange[] {\n const ranges: MediaRange[] = []\n for (const part of accept.split(',')) {\n const segments = part.trim().split(';')\n const type = (segments[0] ?? '').trim().toLowerCase()\n if (type.length === 0) continue\n let q = 1\n for (const segment of segments.slice(1)) {\n const eq = segment.indexOf('=')\n if (eq === -1) continue\n const key = segment.slice(0, eq).trim().toLowerCase()\n const value = segment.slice(eq + 1).trim()\n if (key === 'q') {\n const parsed = Number(value)\n if (Number.isFinite(parsed)) q = parsed\n }\n }\n ranges.push({ type, q })\n }\n return ranges\n}\n\n/** Explicit (non-wildcard) media type present with q > 0. */\nfunction acceptsMediaType(ranges: MediaRange[], mediaType: string): boolean {\n return ranges.some((range) => range.type === mediaType && range.q > 0)\n}\n\n/**\n * Does this raw `Accept` header EXPLICITLY ask for `text/markdown`?\n *\n * Exported because the answer is a fact about the serving decision, and a\n * second implementation of it would be free to disagree with the first. The\n * Console's Accept panel reports how many agent requests asked for markdown;\n * if that number were computed by a SQL `LIKE` it would quietly drift from\n * what `detect()` actually did, and the panel would be describing a gateway\n * that does not exist.\n *\n * A WILDCARD RANGE DOES NOT COUNT, and that is the whole point of the panel.\n * Under ordinary HTTP content negotiation a wildcard accepts everything, but\n * this standard reads only an EXPLICIT range: an agent sending the catch-all\n * range has expressed no preference, and counting it as \"asked for markdown\"\n * would turn the honest headline (\"almost nobody asks; we serve it anyway\")\n * into a meaningless one where almost everybody asks.\n *\n * `text/markdown;q=0` is a refusal and returns false, same as `detect()`.\n */\nexport function acceptsMarkdownHeader(accept: string | null | undefined): boolean {\n if (accept === null || accept === undefined || accept.trim().length === 0) return false\n return acceptsMediaType(parseAccept(accept), 'text/markdown')\n}\n\n// ---------------------------------------------------------------------------\n// Web Bot Auth (Signature-Agent / Signature / Signature-Input)\n// ---------------------------------------------------------------------------\n\n/**\n * Extract the host from a Signature-Agent structured-field value, e.g.\n * `\"https://chatgpt.com\"` -> `chatgpt.com`. No verification — parse only.\n */\nfunction parseSignatureAgentHost(value: string): string | null {\n const first = value.split(',')[0] ?? ''\n const unquoted = first.trim().replace(/^\"/, '').replace(/\"$/, '').trim()\n if (unquoted.length === 0) return null\n try {\n return new URL(unquoted).hostname.toLowerCase()\n } catch {\n return unquoted.toLowerCase()\n }\n}\n\nconst SIGNATURE_AGENT_PLATFORMS: ReadonlyArray<readonly [string, AgentPlatform]> = [\n ['chatgpt.com', 'chatgpt'],\n ['openai.com', 'chatgpt'],\n ['claude.ai', 'claude'],\n ['anthropic.com', 'claude'],\n ['perplexity.ai', 'perplexity'],\n ['gemini.google.com', 'gemini'],\n]\n\nfunction platformForSignatureAgentHost(host: string): AgentPlatform {\n for (const [domain, platform] of SIGNATURE_AGENT_PLATFORMS) {\n if (host === domain || host.endsWith(`.${domain}`)) return platform\n }\n return 'unknown'\n}\n\n// ---------------------------------------------------------------------------\n// Protocol routes\n// ---------------------------------------------------------------------------\n\nconst PROTOCOL_ROUTES = ['/.well-known/ucp', '/.well-known/acp', '/mcp', '/acp'] as const\n\nfunction pathnameOf(url: string): string {\n try {\n return new URL(url).pathname\n } catch {\n const stripped = url.split('#')[0]?.split('?')[0] ?? ''\n return stripped\n }\n}\n\nfunction matchProtocolRoute(pathname: string): string | null {\n const path = pathname.toLowerCase().replace(/\\/+$/, '') || '/'\n for (const route of PROTOCOL_ROUTES) {\n if (path === route || path.startsWith(`${route}/`)) return route\n }\n return null\n}\n\n// ---------------------------------------------------------------------------\n// User-Agent heuristics (fallback only — see README: UA alone never justifies\n// substantive content differences; confidence is capped at 'medium')\n// ---------------------------------------------------------------------------\n\ninterface UaEntry {\n pattern: string\n platform: AgentPlatform\n}\n\n/**\n * Crawler UAs are checked before everything else: a known crawler is always\n * classified 'crawler' regardless of other signals (cloaking guardrail —\n * Googlebot must receive canonical HTML, never markdown).\n *\n * Every Microsoft fetcher below belongs in THIS table rather than `AGENT_UA`,\n * and the asymmetry is deliberate. Misclassifying a crawler as an agent serves\n * it markdown, which is the cloaking fact pattern; misclassifying an agent as\n * a crawler only costs that caller a markdown response it can still get by\n * asking for one with `Accept`. When a Microsoft token is ambiguous, crawler\n * is the side to be wrong on — and `adidxbot` in particular audits ad landing\n * pages for policy compliance, so serving it anything but the canonical page\n * is the single worst outcome available here.\n */\nconst CRAWLER_UA: readonly UaEntry[] = [\n { pattern: 'googlebot', platform: 'googlebot' },\n { pattern: 'bingbot', platform: 'bingbot' },\n // Bing Ads landing-page quality crawler. Its own UA points at\n // bing.com/bingbot.htm, so it is attributed to the bingbot platform.\n { pattern: 'adidxbot', platform: 'bingbot' },\n // Microsoft product previews (link unfurling in Teams, Outlook, and the\n // like). A separate platform because it is not Bing and not an assistant:\n // attributing it to `bingbot` would inflate a merchant's Bing figure with\n // traffic that never touched the index.\n { pattern: 'microsoftpreview', platform: 'microsoft-preview' },\n]\n\n/** Order matters: more specific tokens before broader ones. */\nconst AGENT_UA: readonly UaEntry[] = [\n { pattern: 'claude-code', platform: 'claude-code' },\n { pattern: 'opencode', platform: 'opencode' },\n { pattern: 'chatgpt-user', platform: 'chatgpt' },\n { pattern: 'oai-searchbot', platform: 'chatgpt' },\n { pattern: 'gptbot', platform: 'chatgpt' },\n { pattern: 'perplexitybot', platform: 'perplexity' },\n { pattern: 'perplexity-user', platform: 'perplexity' },\n { pattern: 'google-extended', platform: 'gemini' },\n { pattern: 'gemini', platform: 'gemini' },\n { pattern: 'claude-web', platform: 'claude' },\n { pattern: 'claudebot', platform: 'claude' },\n { pattern: 'claude-user', platform: 'claude' },\n { pattern: 'anthropic-ai', platform: 'claude' },\n]\n\nfunction findUaEntry(ua: string, table: readonly UaEntry[]): UaEntry | undefined {\n return table.find((entry) => ua.includes(entry.pattern))\n}\n\n// ---------------------------------------------------------------------------\n// detect()\n// ---------------------------------------------------------------------------\n\n/**\n * Classify a request from its headers (and optionally URL). Pure compute:\n * no network, no crypto. Checks run cheapest-first; every check that fires\n * is recorded in `signals`, and the highest-precedence one classifies.\n *\n * Precedence: crawler UA (guardrail) > Accept: text/markdown >\n * Signature-Agent / Web Bot Auth headers > protocol route > agent UA > human.\n */\nexport function detect(input: DetectInput): DetectionResult {\n const headers = input.headers ?? {}\n const signals: string[] = []\n\n // Gather raw evidence once.\n const acceptRaw = headerValue(headers, 'accept')\n const ranges = acceptRaw === undefined ? [] : parseAccept(acceptRaw)\n const acceptsMarkdown = acceptsMediaType(ranges, 'text/markdown')\n const acceptsHtml = acceptsMediaType(ranges, 'text/html')\n\n const ua = (headerValue(headers, 'user-agent') ?? '').toLowerCase()\n const crawlerMatch = findUaEntry(ua, CRAWLER_UA)\n const agentUaMatch = crawlerMatch === undefined ? findUaEntry(ua, AGENT_UA) : undefined\n\n const signatureAgentRaw = headerValue(headers, 'signature-agent')\n const signatureAgentHost =\n signatureAgentRaw === undefined ? null : parseSignatureAgentHost(signatureAgentRaw)\n const hasSignaturePair =\n headerValue(headers, 'signature') !== undefined &&\n headerValue(headers, 'signature-input') !== undefined\n\n const protocolRoute = input.url === undefined ? null : matchProtocolRoute(pathnameOf(input.url))\n\n // Record fired checks in detection order.\n if (acceptsMarkdown) signals.push('accept:text/markdown')\n if (signatureAgentHost !== null) signals.push(`signature-agent:${signatureAgentHost}`)\n if (hasSignaturePair) signals.push('web-bot-auth:signature')\n if (protocolRoute !== null) signals.push(`protocol:${protocolRoute}`)\n if (crawlerMatch !== undefined) signals.push(`ua:${crawlerMatch.pattern}`)\n if (agentUaMatch !== undefined) signals.push(`ua:${agentUaMatch.pattern}`)\n\n const base = { verified: false as const, acceptsMarkdown, signals }\n\n // 0. Cloaking guardrail: a known crawler UA always classifies as crawler,\n // even if other signals fired. Googlebot never takes the agent path.\n if (crawlerMatch !== undefined) {\n return { ...base, kind: 'crawler', platform: crawlerMatch.platform, confidence: 'medium' }\n }\n\n // 1. Accept: text/markdown — the cheapest, most explicit agent signal.\n // Platform attribution prefers Signature-Agent (a stated identity) over UA.\n if (acceptsMarkdown) {\n const signaturePlatform =\n signatureAgentHost !== null ? platformForSignatureAgentHost(signatureAgentHost) : null\n const platform = signaturePlatform ?? agentUaMatch?.platform ?? 'unknown'\n return { ...base, kind: 'agent', platform, confidence: 'high' }\n }\n\n // 2. Web Bot Auth headers — parse only here; cryptographic verification is\n // the separate async verifyWebBotAuth() step (src/verify.ts).\n if (signatureAgentHost !== null) {\n return {\n ...base,\n kind: 'agent',\n platform: platformForSignatureAgentHost(signatureAgentHost),\n confidence: 'high',\n }\n }\n if (hasSignaturePair) {\n return {\n ...base,\n kind: 'agent',\n platform: agentUaMatch?.platform ?? 'unknown',\n confidence: 'medium',\n }\n }\n\n // 3. Protocol route hit.\n if (protocolRoute !== null) {\n return {\n ...base,\n kind: 'protocol',\n platform: agentUaMatch?.platform ?? null,\n confidence: 'high',\n }\n }\n\n // 4. UA heuristics — fallback only, capped at medium confidence.\n if (agentUaMatch !== undefined) {\n return { ...base, kind: 'agent', platform: agentUaMatch.platform, confidence: 'medium' }\n }\n\n // 5. Default: human. High confidence only with a browserish Accept/UA.\n if (acceptsHtml) signals.push('accept:text/html')\n else if (ua.includes('mozilla/')) signals.push('ua:browser')\n const browserish = acceptsHtml || ua.includes('mozilla/')\n return { ...base, kind: 'human', platform: null, confidence: browserish ? 'high' : 'low' }\n}\n","/**\n * Web Bot Auth verification — the Phase 3 async counterpart to detect().\n *\n * PURE CRYPTO WITH INJECTED KEYS. This module verifies RFC 9421-style HTTP\n * message signatures (Signature-Input / Signature / Signature-Agent) against\n * a caller-provided key registry. It NEVER fetches a key directory, never\n * touches the network, never reads the environment — the registry is\n * dependency-injected, so the hot path stays within the edge budget\n * (CLAUDE.md Conventions: no network calls on the hot path). Key directory\n * refresh is an offline/operator concern (see README § Verification).\n *\n * detect() stays synchronous and unchanged: it parses these headers as\n * identity *signals* only and always reports `verified: false`. Paths that\n * need cryptographic identity (preference payloads, protocol transactions —\n * ROADMAP Phase 3 P0) call verifyWebBotAuth() as a separate async step.\n *\n * Failure behavior is constant: malformed, hostile, or garbage input NEVER\n * throws — every path resolves to `{ verified: false, reason }`.\n */\n\nimport type { AgentPlatform, DetectInput } from './types'\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/** Why verification did not succeed. */\nexport type VerificationFailureReason =\n | 'no-signature' // no Signature + Signature-Input header pair on the request\n | 'unknown-agent' // no Signature-Agent header, or its origin is not in the registry\n | 'unknown-key' // keyid not found for that agent, or the registry key material is unusable\n | 'expired' // `expires` is more than the allowed clock skew in the past\n | 'created-in-future' // `created` is more than the allowed clock skew in the future\n | 'bad-signature' // signature bytes do not verify over the reconstructed base\n | 'malformed' // unparseable/unsupported headers, or a covered component we cannot reconstruct\n | 'unsupported-alg' // signature declares an algorithm other than ed25519\n\nexport interface VerificationResult {\n verified: boolean\n /** The registry entry's platform, set only when verified. */\n platform?: AgentPlatform\n /** The keyid parsed from Signature-Input, set once parsing got that far. */\n keyid?: string\n /** Set exactly when `verified` is false. */\n reason?: VerificationFailureReason\n}\n\n/** An Ed25519 public key in JWK form (RFC 8037: OKP / Ed25519 / x). */\nexport interface Ed25519PublicJwk {\n kty: 'OKP'\n crv: 'Ed25519'\n /** base64url-encoded public key bytes. */\n x: string\n}\n\nexport interface AgentPublicKey {\n /** Matches the `keyid` parameter the agent sends in Signature-Input. */\n keyid: string\n /** ed25519 is the only algorithm supported in v0. */\n alg: 'ed25519'\n publicKeyJwk: Ed25519PublicJwk\n}\n\nexport interface AgentKeyRegistryEntry {\n /** The platform this origin's keys attest to. */\n platform: AgentPlatform\n keys: AgentPublicKey[]\n}\n\n/**\n * Key registry keyed by the agent's Signature-Agent origin, e.g.\n * `\"https://chatgpt.com\"`. Bare hosts (`\"chatgpt.com\"`) are accepted and\n * normalized to the https origin. See KNOWN_AGENT_DIRECTORY (src/directory.ts)\n * for the shape — it ships EMPTY; operators populate it from the platforms'\n * published key directories.\n */\nexport type AgentKeyRegistry = Record<string, AgentKeyRegistryEntry>\n\nexport interface VerifyWebBotAuthOptions {\n /** The injected key registry. Verification is pure crypto over these keys. */\n keys: AgentKeyRegistry\n /** Clock override for tests/replays. Defaults to `new Date()`. */\n now?: Date\n /**\n * Deliberately impossible to set: this function performs NO network I/O.\n * Key directory fetch/refresh happens offline, outside this module.\n */\n fetchImpl?: never\n}\n\n/** Allowed clock skew for `created` / `expires`, in seconds (±). */\nexport const CLOCK_SKEW_SECONDS = 300\n\n// ---------------------------------------------------------------------------\n// Header + structured-field parsing (RFC 8941 subset, RFC 9421 shapes)\n// ---------------------------------------------------------------------------\n\n/** Case-insensitive header lookup; array values comma-joined (RFC 9110). */\nfunction headerValue(\n headers: Record<string, string | string[] | undefined>,\n name: string,\n): string | undefined {\n const target = name.toLowerCase()\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== target || value === undefined) continue\n return Array.isArray(value) ? value.join(', ') : value\n }\n return undefined\n}\n\nconst KEY_CHAR = /[a-zA-Z0-9_.*-]/\nconst PARAM_VALUE_END = /[;,\\s]/\n\ninterface Scanner {\n s: string\n i: number\n}\n\nfunction skipOws(sc: Scanner): void {\n while (sc.i < sc.s.length && (sc.s[sc.i] === ' ' || sc.s[sc.i] === '\\t')) sc.i++\n}\n\n/** Reads an sf-key at the cursor; null when none is present. */\nfunction readKey(sc: Scanner): string | null {\n const start = sc.i\n while (sc.i < sc.s.length && KEY_CHAR.test(sc.s[sc.i] as string)) sc.i++\n return sc.i > start ? sc.s.slice(start, sc.i) : null\n}\n\n/** Reads a quoted sf-string at the cursor (cursor on the opening quote). */\nfunction readQuoted(sc: Scanner): string | null {\n if (sc.s[sc.i] !== '\"') return null\n sc.i++\n let out = ''\n while (sc.i < sc.s.length) {\n const ch = sc.s[sc.i] as string\n if (ch === '\\\\') {\n if (sc.i + 1 >= sc.s.length) return null\n out += sc.s[sc.i + 1] as string\n sc.i += 2\n continue\n }\n if (ch === '\"') {\n sc.i++\n return out\n }\n out += ch\n sc.i++\n }\n return null // unterminated\n}\n\n/** Reads `;name[=value]` parameters into a map. Null on malformed input. */\nfunction readParams(sc: Scanner): Map<string, string | number | true> | null {\n const params = new Map<string, string | number | true>()\n while (sc.i < sc.s.length && sc.s[sc.i] === ';') {\n sc.i++\n skipOws(sc)\n const name = readKey(sc)\n if (name === null) return null\n let value: string | number | true = true\n if (sc.s[sc.i] === '=') {\n sc.i++\n if (sc.s[sc.i] === '\"') {\n const quoted = readQuoted(sc)\n if (quoted === null) return null\n value = quoted\n } else {\n const start = sc.i\n while (sc.i < sc.s.length && !PARAM_VALUE_END.test(sc.s[sc.i] as string)) sc.i++\n const token = sc.s.slice(start, sc.i)\n if (token.length === 0) return null\n value = /^-?\\d+$/.test(token) ? Number(token) : token\n }\n }\n params.set(name, value)\n }\n return params\n}\n\ninterface SignatureInputMember {\n label: string\n /** Covered component names, as sent (lowercased at use time). */\n components: string[]\n params: Map<string, string | number | true>\n /**\n * The EXACT serialization after `label=` — reused verbatim as the\n * `\"@signature-params\"` line of the signature base, so no re-serialization\n * ambiguity can break verification.\n */\n raw: string\n}\n\n/**\n * Parses a Signature-Input dictionary:\n * `sig1=(\"@authority\" \"signature-agent\");created=...;keyid=\"...\", sig2=...`\n * Returns null on any malformed member. Components carrying their own\n * parameters (e.g. `\"@query-param\";name=\"q\"`) are unsupported in v0 →\n * treated as malformed.\n */\nfunction parseSignatureInput(value: string): SignatureInputMember[] | null {\n const sc: Scanner = { s: value, i: 0 }\n const members: SignatureInputMember[] = []\n skipOws(sc)\n while (sc.i < sc.s.length) {\n const label = readKey(sc)\n if (label === null || sc.s[sc.i] !== '=') return null\n sc.i++\n if (sc.s[sc.i] !== '(') return null\n const rawStart = sc.i\n sc.i++\n const components: string[] = []\n for (;;) {\n skipOws(sc)\n if (sc.i >= sc.s.length) return null\n if (sc.s[sc.i] === ')') {\n sc.i++\n break\n }\n const component = readQuoted(sc)\n if (component === null) return null\n if (sc.s[sc.i] === ';') return null // per-component parameters: unsupported in v0\n components.push(component)\n }\n const params = readParams(sc)\n if (params === null) return null\n members.push({ label, components, params, raw: sc.s.slice(rawStart, sc.i) })\n skipOws(sc)\n if (sc.i >= sc.s.length) break\n if (sc.s[sc.i] !== ',') return null\n sc.i++\n skipOws(sc)\n }\n return members\n}\n\n/**\n * Parses a Signature dictionary of byte sequences:\n * `sig1=:BASE64==:, sig2=:...:` → label → base64 payload.\n */\nfunction parseSignatureDict(value: string): Map<string, string> | null {\n const sc: Scanner = { s: value, i: 0 }\n const out = new Map<string, string>()\n skipOws(sc)\n while (sc.i < sc.s.length) {\n const label = readKey(sc)\n if (label === null || sc.s[sc.i] !== '=') return null\n sc.i++\n if (sc.s[sc.i] !== ':') return null\n sc.i++\n const start = sc.i\n while (sc.i < sc.s.length && sc.s[sc.i] !== ':') sc.i++\n if (sc.i >= sc.s.length) return null // unterminated byte sequence\n out.set(label, sc.s.slice(start, sc.i))\n sc.i++\n if (readParams(sc) === null) return null // tolerate (and ignore) member params\n skipOws(sc)\n if (sc.i >= sc.s.length) break\n if (sc.s[sc.i] !== ',') return null\n sc.i++\n skipOws(sc)\n }\n return out\n}\n\n// ---------------------------------------------------------------------------\n// Origins, base64, component values\n// ---------------------------------------------------------------------------\n\n/** Normalizes an origin-ish string (\"https://x.com\", \"x.com\") to a URL origin. */\nfunction normalizeOrigin(value: string): string | null {\n const trimmed = value.trim()\n if (trimmed.length === 0) return null\n const candidate = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`\n try {\n return new URL(candidate).origin.toLowerCase()\n } catch {\n return null\n }\n}\n\n/** First item of the Signature-Agent list, unquoted → normalized origin. */\nfunction signatureAgentOrigin(raw: string): string | null {\n const first = raw.split(',')[0] ?? ''\n const sc: Scanner = { s: first.trim(), i: 0 }\n const unquoted = sc.s[0] === '\"' ? readQuoted(sc) : sc.s\n if (unquoted === null || unquoted.length === 0) return null\n return normalizeOrigin(unquoted)\n}\n\n/** Registry lookup with origin normalization on the registry keys too. */\nfunction registryEntryFor(\n keys: AgentKeyRegistry,\n origin: string,\n): AgentKeyRegistryEntry | undefined {\n for (const [registryOrigin, entry] of Object.entries(keys)) {\n if (normalizeOrigin(registryOrigin) === origin) return entry\n }\n return undefined\n}\n\nconst BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/\n\nfunction base64Decode(value: string): Uint8Array<ArrayBuffer> | null {\n if (!BASE64_RE.test(value) || value.length % 4 !== 0) return null\n try {\n const binary = atob(value)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n return bytes\n } catch {\n return null\n }\n}\n\n/**\n * Resolves one covered component's value for the signature base. Returns\n * null when the component cannot be reconstructed from the input (missing\n * header, missing/unparseable URL, unsupported derived component) — which\n * verifyWebBotAuth reports as 'malformed'.\n */\nfunction componentValue(name: string, input: DetectInput): string | null {\n if (name.startsWith('@')) {\n if (name === '@method') {\n return input.method === undefined ? null : input.method.toUpperCase()\n }\n if (input.url === undefined) return null\n let url: URL\n try {\n url = new URL(input.url)\n } catch {\n return null\n }\n switch (name) {\n case '@authority':\n return url.host\n case '@scheme':\n return url.protocol.replace(/:$/, '')\n case '@target-uri':\n return url.href\n case '@path':\n return url.pathname\n case '@query':\n return url.search === '' ? '?' : url.search\n case '@request-target':\n return url.pathname + url.search\n default:\n return null // unsupported derived component in v0\n }\n }\n const value = headerValue(input.headers ?? {}, name)\n return value === undefined ? null : value.trim()\n}\n\n// ---------------------------------------------------------------------------\n// verifyWebBotAuth()\n// ---------------------------------------------------------------------------\n\nfunction failure(reason: VerificationFailureReason, keyid?: string): VerificationResult {\n return keyid === undefined ? { verified: false, reason } : { verified: false, keyid, reason }\n}\n\n/**\n * Verify a request's Web Bot Auth signature chain against an injected key\n * registry. Async (WebCrypto) but pure: no network, no environment, no\n * global state. Never throws — every failure resolves to\n * `{ verified: false, reason }`.\n *\n * Requirements enforced (Web Bot Auth profile over RFC 9421):\n * - `Signature` + `Signature-Input` present, structured-field parseable\n * - covered components include `@authority` AND `signature-agent`\n * (anti-replay: the signature is pinned to this host and this identity)\n * - `keyid`, `created`, `expires` parameters present; `created <= expires`;\n * both within ±CLOCK_SKEW_SECONDS of `options.now`\n * - `alg`, when present, is `ed25519`\n * - `Signature-Agent` origin resolves to a registry entry; `keyid` resolves\n * to one of that entry's keys\n * - Ed25519 signature verifies (WebCrypto subtle) over the RFC 9421\n * signature base, whose `\"@signature-params\"` line reuses the exact\n * serialization the agent sent\n */\nexport async function verifyWebBotAuth(\n input: DetectInput,\n options: VerifyWebBotAuthOptions,\n): Promise<VerificationResult> {\n try {\n return await verifyInner(input, options)\n } catch {\n // Constant behavior on hostile input: never throw.\n return failure('malformed')\n }\n}\n\nasync function verifyInner(\n input: DetectInput,\n options: VerifyWebBotAuthOptions,\n): Promise<VerificationResult> {\n const headers = input.headers ?? {}\n const signatureRaw = headerValue(headers, 'signature')\n const signatureInputRaw = headerValue(headers, 'signature-input')\n if (signatureRaw === undefined || signatureInputRaw === undefined) {\n return failure('no-signature')\n }\n\n const members = parseSignatureInput(signatureInputRaw)\n const signatures = parseSignatureDict(signatureRaw)\n if (members === null || signatures === null || members.length === 0) {\n return failure('malformed')\n }\n\n // First Signature-Input member with a matching Signature entry.\n const member = members.find((candidate) => signatures.has(candidate.label))\n if (member === undefined) return failure('malformed')\n const signatureB64 = signatures.get(member.label) as string\n\n // Anti-replay: the signature must pin the authority and the agent identity.\n const covered = member.components.map((component) => component.toLowerCase())\n if (!covered.includes('@authority') || !covered.includes('signature-agent')) {\n return failure('malformed')\n }\n\n const alg = member.params.get('alg')\n if (alg !== undefined && alg !== 'ed25519') return failure('unsupported-alg')\n\n const keyidParam = member.params.get('keyid')\n const keyid = typeof keyidParam === 'string' && keyidParam.length > 0 ? keyidParam : undefined\n\n // Agent identity → registry entry.\n const signatureAgentRaw = headerValue(headers, 'signature-agent')\n if (signatureAgentRaw === undefined) return failure('unknown-agent', keyid)\n const origin = signatureAgentOrigin(signatureAgentRaw)\n if (origin === null) return failure('unknown-agent', keyid)\n const entry = registryEntryFor(options.keys, origin)\n if (entry === undefined) return failure('unknown-agent', keyid)\n\n // keyid → registry key.\n if (keyid === undefined) return failure('malformed')\n const key = entry.keys.find((candidate) => candidate.keyid === keyid)\n if (key === undefined) return failure('unknown-key', keyid)\n if (key.alg !== 'ed25519') return failure('unsupported-alg', keyid)\n\n // Validity window (±CLOCK_SKEW_SECONDS).\n const created = member.params.get('created')\n const expires = member.params.get('expires')\n if (typeof created !== 'number' || !Number.isInteger(created)) return failure('malformed', keyid)\n if (typeof expires !== 'number' || !Number.isInteger(expires)) return failure('malformed', keyid)\n if (created > expires) return failure('malformed', keyid)\n const nowSeconds = Math.floor((options.now ?? new Date()).getTime() / 1000)\n if (created - CLOCK_SKEW_SECONDS > nowSeconds) return failure('created-in-future', keyid)\n if (expires + CLOCK_SKEW_SECONDS < nowSeconds) return failure('expired', keyid)\n\n // Signature base (RFC 9421 § 2.5): one line per covered component, then\n // \"@signature-params\" with the agent's exact Signature-Input serialization.\n const lines: string[] = []\n for (const component of covered) {\n const value = componentValue(component, input)\n if (value === null) return failure('malformed', keyid)\n lines.push(`\"${component}\": ${value}`)\n }\n lines.push(`\"@signature-params\": ${member.raw}`)\n const base = lines.join('\\n')\n\n const signatureBytes = base64Decode(signatureB64)\n if (signatureBytes === null) return failure('malformed', keyid)\n if (signatureBytes.length !== 64) return failure('bad-signature', keyid)\n\n let cryptoKey: CryptoKey\n try {\n cryptoKey = await crypto.subtle.importKey(\n 'jwk',\n key.publicKeyJwk,\n { name: 'Ed25519' },\n false,\n ['verify'],\n )\n } catch {\n // Registry key material is unusable — an operator/registry problem.\n return failure('unknown-key', keyid)\n }\n\n let ok = false\n try {\n ok = await crypto.subtle.verify(\n 'Ed25519',\n cryptoKey,\n signatureBytes,\n new TextEncoder().encode(base),\n )\n } catch {\n ok = false\n }\n if (!ok) return failure('bad-signature', keyid)\n\n return { verified: true, platform: entry.platform, keyid }\n}\n","/**\n * KNOWN_AGENT_DIRECTORY — the built-in Web Bot Auth key registry.\n *\n * THIS IS A DATA MODULE, AND IT SHIPS EMPTY — DELIBERATELY. We do not embed\n * \"known\" production public keys for OpenAI, Anthropic, Perplexity, etc.,\n * because we have not fetched and pinned them from the platforms' published\n * key directories, and inventing key material would make verification\n * silently meaningless (a fabricated key either verifies nothing or, worse,\n * verifies the wrong thing). Honesty over completeness.\n *\n * How this gets populated (operator responsibility, README § Verification):\n * agent platforms publish their signing keys at well-known HTTP message\n * signature directories (e.g. `https://<platform>/.well-known/\n * http-message-signatures-directory`). Operators fetch those OFFLINE — never\n * on the request hot path — pin the Ed25519 public keys here (or in their own\n * registry object; any `AgentKeyRegistry` works), and refresh on key\n * rotation. A refresh script that snapshots the published directories into\n * this module is future work (ROADMAP parking-lot material).\n *\n * Shape of a populated entry (this example is NOT a real key):\n *\n * 'https://chatgpt.com': {\n * platform: 'chatgpt',\n * keys: [\n * {\n * keyid: 'poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U', // JWK thumbprint the agent sends\n * alg: 'ed25519',\n * publicKeyJwk: { kty: 'OKP', crv: 'Ed25519', x: '<base64url public key bytes>' },\n * },\n * ],\n * },\n *\n * With the directory empty, verifyWebBotAuth() resolves every signed request\n * to `{ verified: false, reason: 'unknown-agent' }` — the honest answer when\n * no trusted key is on file.\n */\n\nimport type { AgentKeyRegistry } from './verify'\n\nexport const KNOWN_AGENT_DIRECTORY: AgentKeyRegistry = {\n // Intentionally empty — see the module header. Operators populate this (or\n // pass their own registry) from the platforms' published key directories.\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rebilder/agent-detect",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Agent identification from request headers: Accept negotiation, Web Bot Auth signals, protocol routes, UA heuristics. Pure compute, zero runtime dependencies.",
|
|
6
6
|
"license": "Apache-2.0",
|