@rebilder/agent-detect 0.1.1 → 0.3.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/CHANGELOG.md ADDED
@@ -0,0 +1,33 @@
1
+ # @rebilder/agent-detect changelog
2
+
3
+ Notable changes to `@rebilder/agent-detect`. Dates are the day each version reached npm.
4
+
5
+ ## Unreleased
6
+
7
+ ## 0.3.0 (2026-09-28)
8
+
9
+ - **Requires Node.js 22 or later.** `engines.node` moves from `>=20.11.0` to `>=22`; Node.js 20 reached end of life in April 2026. Edge runtimes are unaffected.
10
+ - Detects more AI agents and crawlers, each pattern taken from the vendor's own documentation:
11
+ - `Applebot` is a crawler (platform `applebot`), so the gateway serves it your HTML like Googlebot. `Applebot-Extended` is a robots.txt token that never crawls, so it has no pattern.
12
+ - `meta-externalagent` and `meta-externalfetcher` are agents (platform `meta`).
13
+ - `Amazonbot` is an agent (platform `amazon`).
14
+ - `DuckAssistBot` is an agent (platform `duckduckgo`).
15
+ - `MistralAI-User` is an agent (platform `mistral`).
16
+ - `AgentPlatform` gains `applebot`, `meta`, `amazon`, `duckduckgo` and `mistral`. An exhaustive `switch` over `AgentPlatform` needs the new cases. Identified agents on these platforms now take the gateway's markdown path when a source answers, the same as GPTBot or ClaudeBot.
17
+ - README lists every recognized User-Agent. Better package description and keywords. This changelog now ships in the package.
18
+
19
+ ## 0.2.0 (2026-08-26)
20
+
21
+ - Detects Microsoft's `adidxbot` (Bing Ads landing-page checks) as `bingbot` and `MicrosoftPreview` (link previews in Microsoft products) as the new `microsoft-preview` platform, both as crawlers.
22
+ - Exports `acceptsMarkdownHeader`, the `Accept` predicate `detect()` itself uses. A wildcard is not a request for markdown.
23
+
24
+ ## 0.1.1 (2026-08-11)
25
+
26
+ - Package metadata points at rebilder.com for help instead of a private repository. No code change.
27
+
28
+ ## 0.1.0 (2026-08-10)
29
+
30
+ First release.
31
+
32
+ - `detect()`: synchronous classification into agent, person, crawler or protocol client from `Accept: text/markdown`, Web Bot Auth headers, protocol routes and User-Agent, with the signals that fired and a confidence. Known search crawlers always classify as crawlers.
33
+ - `verifyWebBotAuth()`: RFC 9421 Ed25519 signature verification against a key registry you supply. No network calls; hostile input returns a reason and never throws.
package/README.md CHANGED
@@ -1,16 +1,16 @@
1
1
  # @rebilder/agent-detect
2
2
 
3
- Agent identification from request headers. Given a request's headers (and optionally its URL), `detect()` classifies who is asking — an AI agent, a human in a browser, a search crawler, or a protocol client — and, where possible, which platform it is. The package also ships `verifyWebBotAuth()` — cryptographic Web Bot Auth verification as a **separate async step** (see § Verification below).
3
+ Tell AI agents, search crawlers and people apart from a request's headers, and verify Web Bot Auth signatures when you need proof of identity. It has no dependencies, makes no network calls and runs at the edge.
4
4
 
5
- **Pure compute. Zero runtime dependencies. Framework-agnostic.** No network calls. `detect()` does no crypto and is safe on the edge hot path (well under the 50ms p95 budget; it is a handful of string scans); `verifyWebBotAuth()` is pure crypto (ambient WebCrypto) over an injected key registry — still zero network, zero deps.
5
+ `@rebilder/gateway` uses it to decide who gets markdown. Use it directly to classify requests in your own server or analytics.
6
6
 
7
- ## What this package does — and does not — do
7
+ ## Install
8
8
 
9
- - **`detect()` does:** parse and classify. Accept negotiation, Web Bot Auth header *parsing* (`Signature-Agent`, `Signature`, `Signature-Input`), protocol-route matching, User-Agent heuristics. It is synchronous and NEVER verifies: its `verified` field is always `false`.
10
- - **`verifyWebBotAuth()` does:** cryptographically verify a Web Bot Auth signature chain (RFC 9421 Ed25519 message signatures) against a **caller-injected key registry** — a distinct async step for the paths that need cryptographic identity (preference payloads, protocol transactions).
11
- - **Neither does:** network I/O. There is no key-directory fetching anywhere in this package — the registry is data the operator injects (see § Verification for why it ships empty). Do not gate anything security-sensitive on an unverified platform claim.
9
+ ```sh
10
+ npm install @rebilder/agent-detect
11
+ ```
12
12
 
13
- ## API
13
+ ## Classify a request
14
14
 
15
15
  ```ts
16
16
  import { detect } from '@rebilder/agent-detect'
@@ -22,104 +22,85 @@ const result = detect({
22
22
  })
23
23
  // {
24
24
  // kind: 'agent' | 'human' | 'crawler' | 'protocol',
25
- // platform: 'claude-code' | 'opencode' | 'claude' | 'chatgpt' | 'gemini'
26
- // | 'perplexity' | 'googlebot' | 'bingbot' | 'unknown' | null,
27
- // verified: boolean, // ALWAYS false from detect() — verification is the separate
28
- // // async verifyWebBotAuth() step (§ Verification)
25
+ // platform: 'chatgpt' | 'claude' | 'gemini' | 'perplexity' | 'googlebot' | … | null,
26
+ // verified: false, // detect() never verifies; see verifyWebBotAuth()
29
27
  // acceptsMarkdown: boolean, // Accept explicitly lists text/markdown with q > 0
30
- // signals: string[], // ordered checks that fired, e.g. ['accept:text/markdown', 'ua:claude-code']
28
+ // signals: string[], // the checks that fired, e.g. ['accept:text/markdown', 'ua:claude-code']
31
29
  // confidence: 'high' | 'medium' | 'low',
32
30
  // }
33
31
  ```
34
32
 
35
- ## Verification (Web Bot Auth) — `verifyWebBotAuth()`
33
+ `detect()` is synchronous string scanning. Checks run cheapest first, and the highest-precedence one decides:
36
34
 
37
- Agent verification, before accepting preference payloads or protocol transactions. A separate **async** step — `detect()` stays synchronous, parse-only, and unchanged:
35
+ 1. **`Accept: text/markdown`**, listed explicitly with `q > 0`: an agent, high confidence. Claude Code and OpenCode send it.
36
+ 2. **Web Bot Auth headers**: `Signature-Agent` (for example `"https://chatgpt.com"`) names the platform, high confidence. A bare `Signature` and `Signature-Input` pair is an unidentified agent, medium confidence.
37
+ 3. **Protocol routes**: `/.well-known/ucp`, `/.well-known/acp`, `/mcp` and `/acp/*` are protocol clients.
38
+ 4. **User-Agent**, as a fallback capped at medium confidence.
39
+ 5. **Default**: a person.
38
40
 
39
- ```ts
40
- import { verifyWebBotAuth, KNOWN_AGENT_DIRECTORY, type AgentKeyRegistry } from '@rebilder/agent-detect'
41
+ **Crawlers always classify as crawlers.** A search crawler gets `kind: 'crawler'` even when it sends `Accept: text/markdown`, so the gateway serves it your canonical HTML.
41
42
 
42
- const result = await verifyWebBotAuth(
43
- { headers: req.headers, url: req.url, method: req.method }, // same DetectInput shape
44
- { keys: registry }, // INJECTED keys — no network, ever
45
- )
46
- // { verified: true, platform: 'chatgpt', keyid: '…' }
47
- // { verified: false, reason: 'no-signature' | 'unknown-agent' | 'unknown-key' | 'expired'
48
- // | 'created-in-future' | 'bad-signature' | 'malformed' | 'unsupported-alg',
49
- // keyid?: '…' } // keyid included once parsing got that far
50
- ```
43
+ ### Known User-Agents
51
44
 
52
- What it checks (Web Bot Auth profile over RFC 9421):
45
+ | Kind | Tokens | Platform |
46
+ |---|---|---|
47
+ | Agent | `claude-code`, `opencode` | `claude-code`, `opencode` |
48
+ | Agent | `ChatGPT-User`, `OAI-SearchBot`, `GPTBot` | `chatgpt` |
49
+ | Agent | `PerplexityBot`, `Perplexity-User` | `perplexity` |
50
+ | Agent | `Gemini`, `Google-Extended` | `gemini` |
51
+ | Agent | `ClaudeBot`, `Claude-User`, `claude-web`, `anthropic-ai` | `claude` |
52
+ | Agent | `meta-externalagent`, `meta-externalfetcher` | `meta` |
53
+ | Agent | `Amazonbot` | `amazon` |
54
+ | Agent | `DuckAssistBot` | `duckduckgo` |
55
+ | Agent | `MistralAI-User` | `mistral` |
56
+ | Crawler | `Googlebot` | `googlebot` |
57
+ | Crawler | `bingbot`, `adidxbot` | `bingbot` |
58
+ | Crawler | `MicrosoftPreview` | `microsoft-preview` |
59
+ | Crawler | `Applebot` | `applebot` |
53
60
 
54
- - `Signature` + `Signature-Input` parse as structured fields; the first member with a matching signature entry is used → else `no-signature` / `malformed`
55
- - covered components include **`@authority` and `signature-agent`** (anti-replay: the signature is pinned to this host and this identity) → else `malformed`
56
- - `alg`, when present, is `ed25519` → else `unsupported-alg`
57
- - `Signature-Agent` origin resolves to a registry entry → else `unknown-agent`; `keyid` resolves to one of that entry's keys → else `unknown-key`
58
- - `created` / `expires` are present, ordered, and within **±300s clock skew** (`CLOCK_SKEW_SECONDS`) of `options.now` → else `created-in-future` / `expired`
59
- - the Ed25519 signature verifies (WebCrypto `subtle`) over the RFC 9421 signature base, whose `"@signature-params"` line reuses the agent's **exact** `Signature-Input` serialization → else `bad-signature`
61
+ Copilot has no User-Agent of its own; it answers from Bing's index, so it arrives as `bingbot`. `Applebot-Extended` is a robots.txt token that never crawls, so it has no pattern.
60
62
 
61
- **Constant behavior on hostile input: it never throws.** Every malformed, truncated, or adversarial header resolves to `{ verified: false, reason }`.
63
+ A User-Agent is a claim, not proof. Use it to choose a format for the same content. Anything that depends on who the caller really is needs a verified signature.
62
64
 
63
- ### The key registry — honesty first
65
+ ## Check the Accept header
64
66
 
65
67
  ```ts
66
- type AgentKeyRegistry = {
67
- [origin: string]: { // Signature-Agent origin, e.g. 'https://chatgpt.com' (bare hosts accepted)
68
- platform: AgentPlatform
69
- keys: { keyid: string; alg: 'ed25519'; publicKeyJwk: { kty: 'OKP'; crv: 'Ed25519'; x: string } }[]
70
- }
71
- }
72
- ```
73
-
74
- `KNOWN_AGENT_DIRECTORY` (src/directory.ts) is the built-in registry and it **ships empty — deliberately**. We do not embed "known" production keys for OpenAI/Anthropic/Perplexity etc., because we have not fetched and pinned them from the platforms' published key directories, and invented key material would make verification silently meaningless. With the directory empty, every signed request resolves to `unknown-agent` — the honest answer when no trusted key is on file.
75
-
76
- **Operators populate the registry**: platforms publish signing keys at well-known HTTP message signature directories (e.g. `/.well-known/http-message-signatures-directory`). Fetch those **offline** — never on the request hot path — pin the Ed25519 public JWKs into your registry (any `AgentKeyRegistry` object works), and refresh on key rotation. A refresh script that snapshots published directories is future work.
77
-
78
- Tests use **self-generated Ed25519 keypairs** (WebCrypto, generated at test time) as vectors — pass/fail paths, tampered payloads, expiry windows, wrong keys, unknown keyids are all asserted deterministically against a fixed clock (`tests/verify.test.ts`).
79
-
80
- ## Detection order (cheapest first)
81
-
82
- Every check that fires is recorded in `signals`; the highest-precedence one classifies.
68
+ import { acceptsMarkdownHeader } from '@rebilder/agent-detect'
83
69
 
84
- 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
- 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
- 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`, `bingbot` → `crawler`/`bingbot`.
88
- 5. **Default** → `human`. High confidence when a browserish Accept (`text/html`) or UA (`Mozilla/`) is present; low otherwise (empty or garbage headers).
89
-
90
- **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
-
92
- ## The UA-heuristics caveat (Hard Rule 3)
70
+ acceptsMarkdownHeader('text/markdown') // true
71
+ acceptsMarkdownHeader('text/html,text/markdown') // true
72
+ acceptsMarkdownHeader('text/markdown;q=0') // false: a refusal
73
+ acceptsMarkdownHeader('*/*') // false: see below
74
+ acceptsMarkdownHeader(null) // false
75
+ ```
93
76
 
94
- 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.
77
+ This is the predicate `detect()` uses. A wildcard is not a request for markdown: only an explicit `text/markdown` range counts. Use it wherever you report on negotiation, so the report and the serving decision agree.
95
78
 
96
- ## Fixture discipline (the moat)
79
+ ## Verify Web Bot Auth
97
80
 
98
- `fixtures/*.json` is a corpus of **real observed header samples**, one file per agent:
81
+ ```ts
82
+ import { verifyWebBotAuth, type AgentKeyRegistry } from '@rebilder/agent-detect'
99
83
 
100
- ```json
101
- {
102
- "name": "claude-code",
103
- "description": "…",
104
- "samples": [
105
- { "headers": { "...": "..." }, "url": "…", "expected": { "kind": "agent", "platform": "claude-code", "acceptsMarkdown": true } }
106
- ]
107
- }
84
+ const result = await verifyWebBotAuth(
85
+ { headers: req.headers, url: req.url, method: req.method },
86
+ { keys: registry }, // your trusted keys; no network, ever
87
+ )
88
+ // { verified: true, platform: 'chatgpt', keyid: '…' }
89
+ // { verified: false, reason: 'no-signature' | 'unknown-agent' | 'unknown-key' | 'expired'
90
+ // | 'created-in-future' | 'bad-signature' | 'malformed' | 'unsupported-alg' }
108
91
  ```
109
92
 
110
- - **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
- - 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.
93
+ It checks RFC 9421 Ed25519 message signatures as profiled by Web Bot Auth: the signature must cover `@authority` and `signature-agent`, the agent and key must be in your registry, `created` and `expires` must fall within 300 seconds of now, and the signature must verify. It never throws; bad input returns `{ verified: false, reason }`.
113
94
 
114
- ## Scripts
95
+ `KNOWN_AGENT_DIRECTORY` starts empty. Add each platform's published signing keys to your `AgentKeyRegistry`, and refresh them outside the request path when they rotate:
115
96
 
97
+ ```ts
98
+ type AgentKeyRegistry = {
99
+ [origin: string]: { // Signature-Agent origin, e.g. 'https://chatgpt.com'
100
+ platform: AgentPlatform
101
+ keys: { keyid: string; alg: 'ed25519'; publicKeyJwk: { kty: 'OKP'; crv: 'Ed25519'; x: string } }[]
102
+ }
103
+ }
116
104
  ```
117
- pnpm --filter @rebilder/agent-detect lint # eslint (flat config)
118
- pnpm --filter @rebilder/agent-detect typecheck # tsc --noEmit (strict)
119
- pnpm --filter @rebilder/agent-detect test # vitest (fixture-driven + unit)
120
- ```
121
-
122
- ## Roadmap
123
105
 
124
- - **Classification** is parse-only and synchronous; `detect()`'s `verified` is always `false`.
125
- - **Verification** is `verifyWebBotAuth()` — pure Ed25519 crypto over an injected registry (§ Verification). Not yet shipped: key-directory refresh tooling (offline snapshot script) and verified-bot IP corroboration for crawlers.
106
+ Full docs: [rebilder.com/docs/classification](https://rebilder.com/docs/classification). Release notes are in `CHANGELOG.md` in this package. Licensed under Apache-2.0.
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,24 @@ 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" },
91
+ // Apple's search crawler for Spotlight, Siri and Safari suggestions, so it
92
+ // sits with Googlebot on the canonical-HTML side. Source:
93
+ // https://support.apple.com/en-us/119829 (UA "contains Applebot", e.g.
94
+ // `... Safari/605.1.15 (Applebot/0.1; +http://www.apple.com/go/applebot)`).
95
+ // `Applebot-Extended` is deliberately NOT a pattern: Apple documents it as a
96
+ // robots.txt token that "does not crawl webpages"; it only controls whether
97
+ // Applebot's crawl may train Apple's models, and it never arrives as a
98
+ // User-Agent of its own.
99
+ { pattern: "applebot", platform: "applebot" }
79
100
  ];
80
101
  var AGENT_UA = [
81
102
  { pattern: "claude-code", platform: "claude-code" },
@@ -90,7 +111,24 @@ var AGENT_UA = [
90
111
  { pattern: "claude-web", platform: "claude" },
91
112
  { pattern: "claudebot", platform: "claude" },
92
113
  { pattern: "claude-user", platform: "claude" },
93
- { pattern: "anthropic-ai", platform: "claude" }
114
+ { pattern: "anthropic-ai", platform: "claude" },
115
+ // Meta's AI crawler (model training and Meta product indexing) and its
116
+ // user-initiated fetcher. Source, both tokens:
117
+ // https://developers.facebook.com/documentation/sharing/webmasters/web-crawlers
118
+ // (`meta-externalagent/1.1 (+...)`, `meta-externalfetcher/1.1 (+...)`).
119
+ { pattern: "meta-externalagent", platform: "meta" },
120
+ { pattern: "meta-externalfetcher", platform: "meta" },
121
+ // Source: https://developer.amazon.com/amazonbot
122
+ // (`Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Amazonbot/0.1) Chrome/W.X.Y.Z Safari/537.36`).
123
+ { pattern: "amazonbot", platform: "amazon" },
124
+ // DuckDuckGo's real-time fetcher for DuckAssist answers. Source:
125
+ // https://duckduckgo.com/duckduckgo-help-pages/results/duckassistbot
126
+ // (`DuckAssistBot/1.2; (+http://duckduckgo.com/duckassistbot.html)`).
127
+ { pattern: "duckassistbot", platform: "duckduckgo" },
128
+ // Mistral's user-initiated fetcher: it visits a page when a user's question
129
+ // needs it, and is not an automatic crawler. Source: https://docs.mistral.ai/robots
130
+ // (`Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; MistralAI-User/1.0; +https://docs.mistral.ai/robots)`).
131
+ { pattern: "mistralai-user", platform: "mistral" }
94
132
  ];
95
133
  function findUaEntry(ua, table) {
96
134
  return table.find((entry) => ua.includes(entry.pattern));
@@ -141,7 +179,12 @@ function detect(input) {
141
179
  };
142
180
  }
143
181
  if (protocolRoute !== null) {
144
- return { ...base, kind: "protocol", platform: agentUaMatch?.platform ?? null, confidence: "high" };
182
+ return {
183
+ ...base,
184
+ kind: "protocol",
185
+ platform: agentUaMatch?.platform ?? null,
186
+ confidence: "high"
187
+ };
145
188
  }
146
189
  if (agentUaMatch !== void 0) {
147
190
  return { ...base, kind: "agent", platform: agentUaMatch.platform, confidence: "medium" };
@@ -442,6 +485,7 @@ var KNOWN_AGENT_DIRECTORY = {
442
485
 
443
486
  exports.CLOCK_SKEW_SECONDS = CLOCK_SKEW_SECONDS;
444
487
  exports.KNOWN_AGENT_DIRECTORY = KNOWN_AGENT_DIRECTORY;
488
+ exports.acceptsMarkdownHeader = acceptsMarkdownHeader;
445
489
  exports.detect = detect;
446
490
  exports.verifyWebBotAuth = verifyWebBotAuth;
447
491
  //# sourceMappingURL=index.cjs.map
@@ -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,G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AAM,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,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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,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 // Apple's search crawler for Spotlight, Siri and Safari suggestions, so it\n // sits with Googlebot on the canonical-HTML side. Source:\n // https://support.apple.com/en-us/119829 (UA \"contains Applebot\", e.g.\n // `... Safari/605.1.15 (Applebot/0.1; +http://www.apple.com/go/applebot)`).\n // `Applebot-Extended` is deliberately NOT a pattern: Apple documents it as a\n // robots.txt token that \"does not crawl webpages\"; it only controls whether\n // Applebot's crawl may train Apple's models, and it never arrives as a\n // User-Agent of its own.\n { pattern: 'applebot', platform: 'applebot' },\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 // Meta's AI crawler (model training and Meta product indexing) and its\n // user-initiated fetcher. Source, both tokens:\n // https://developers.facebook.com/documentation/sharing/webmasters/web-crawlers\n // (`meta-externalagent/1.1 (+...)`, `meta-externalfetcher/1.1 (+...)`).\n { pattern: 'meta-externalagent', platform: 'meta' },\n { pattern: 'meta-externalfetcher', platform: 'meta' },\n // Source: https://developer.amazon.com/amazonbot\n // (`Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Amazonbot/0.1) Chrome/W.X.Y.Z Safari/537.36`).\n { pattern: 'amazonbot', platform: 'amazon' },\n // DuckDuckGo's real-time fetcher for DuckAssist answers. Source:\n // https://duckduckgo.com/duckduckgo-help-pages/results/duckassistbot\n // (`DuckAssistBot/1.2; (+http://duckduckgo.com/duckassistbot.html)`).\n { pattern: 'duckassistbot', platform: 'duckduckgo' },\n // Mistral's user-initiated fetcher: it visits a page when a user's question\n // needs it, and is not an automatic crawler. Source: https://docs.mistral.ai/robots\n // (`Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; MistralAI-User/1.0; +https://docs.mistral.ai/robots)`).\n { pattern: 'mistralai-user', platform: 'mistral' },\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,33 @@
1
1
  /** Coarse classification of who (or what) issued the request. */
2
2
  type RequesterKind = 'agent' | 'human' | 'crawler' | 'protocol';
3
- /** Known agent/crawler platforms. Grows as new agents are observed (add a fixture too). */
4
- type AgentPlatform = 'claude-code' | 'opencode' | 'claude' | 'chatgpt' | 'gemini' | 'perplexity' | 'googlebot' | 'bingbot' | 'unknown';
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'
21
+ /** Apple's search crawler (`Applebot`). A crawler: always served canonical HTML. */
22
+ | 'applebot'
23
+ /** Meta's AI crawler and user-initiated fetcher (`meta-externalagent`, `meta-externalfetcher`). */
24
+ | 'meta'
25
+ /** Amazon's crawler (`Amazonbot`). */
26
+ | 'amazon'
27
+ /** DuckDuckGo's DuckAssist fetcher (`DuckAssistBot`). */
28
+ | 'duckduckgo'
29
+ /** Mistral's user-initiated fetcher (`MistralAI-User`). */
30
+ | 'mistral' | 'unknown';
5
31
  interface DetectInput {
6
32
  /**
7
33
  * Request headers. Lookup is case-insensitive; multi-value headers may be
@@ -35,6 +61,26 @@ interface DetectionResult {
35
61
  confidence: 'high' | 'medium' | 'low';
36
62
  }
37
63
 
64
+ /**
65
+ * Does this raw `Accept` header EXPLICITLY ask for `text/markdown`?
66
+ *
67
+ * Exported because the answer is a fact about the serving decision, and a
68
+ * second implementation of it would be free to disagree with the first. The
69
+ * Console's Accept panel reports how many agent requests asked for markdown;
70
+ * if that number were computed by a SQL `LIKE` it would quietly drift from
71
+ * what `detect()` actually did, and the panel would be describing a gateway
72
+ * that does not exist.
73
+ *
74
+ * A WILDCARD RANGE DOES NOT COUNT, and that is the whole point of the panel.
75
+ * Under ordinary HTTP content negotiation a wildcard accepts everything, but
76
+ * this standard reads only an EXPLICIT range: an agent sending the catch-all
77
+ * range has expressed no preference, and counting it as "asked for markdown"
78
+ * would turn the honest headline ("almost nobody asks; we serve it anyway")
79
+ * into a meaningless one where almost everybody asks.
80
+ *
81
+ * `text/markdown;q=0` is a refusal and returns false, same as `detect()`.
82
+ */
83
+ declare function acceptsMarkdownHeader(accept: string | null | undefined): boolean;
38
84
  /**
39
85
  * Classify a request from its headers (and optionally URL). Pure compute:
40
86
  * no network, no crypto. Checks run cheapest-first; every check that fires
@@ -176,4 +222,4 @@ declare function verifyWebBotAuth(input: DetectInput, options: VerifyWebBotAuthO
176
222
 
177
223
  declare const KNOWN_AGENT_DIRECTORY: AgentKeyRegistry;
178
224
 
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 };
225
+ 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,33 @@
1
1
  /** Coarse classification of who (or what) issued the request. */
2
2
  type RequesterKind = 'agent' | 'human' | 'crawler' | 'protocol';
3
- /** Known agent/crawler platforms. Grows as new agents are observed (add a fixture too). */
4
- type AgentPlatform = 'claude-code' | 'opencode' | 'claude' | 'chatgpt' | 'gemini' | 'perplexity' | 'googlebot' | 'bingbot' | 'unknown';
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'
21
+ /** Apple's search crawler (`Applebot`). A crawler: always served canonical HTML. */
22
+ | 'applebot'
23
+ /** Meta's AI crawler and user-initiated fetcher (`meta-externalagent`, `meta-externalfetcher`). */
24
+ | 'meta'
25
+ /** Amazon's crawler (`Amazonbot`). */
26
+ | 'amazon'
27
+ /** DuckDuckGo's DuckAssist fetcher (`DuckAssistBot`). */
28
+ | 'duckduckgo'
29
+ /** Mistral's user-initiated fetcher (`MistralAI-User`). */
30
+ | 'mistral' | 'unknown';
5
31
  interface DetectInput {
6
32
  /**
7
33
  * Request headers. Lookup is case-insensitive; multi-value headers may be
@@ -35,6 +61,26 @@ interface DetectionResult {
35
61
  confidence: 'high' | 'medium' | 'low';
36
62
  }
37
63
 
64
+ /**
65
+ * Does this raw `Accept` header EXPLICITLY ask for `text/markdown`?
66
+ *
67
+ * Exported because the answer is a fact about the serving decision, and a
68
+ * second implementation of it would be free to disagree with the first. The
69
+ * Console's Accept panel reports how many agent requests asked for markdown;
70
+ * if that number were computed by a SQL `LIKE` it would quietly drift from
71
+ * what `detect()` actually did, and the panel would be describing a gateway
72
+ * that does not exist.
73
+ *
74
+ * A WILDCARD RANGE DOES NOT COUNT, and that is the whole point of the panel.
75
+ * Under ordinary HTTP content negotiation a wildcard accepts everything, but
76
+ * this standard reads only an EXPLICIT range: an agent sending the catch-all
77
+ * range has expressed no preference, and counting it as "asked for markdown"
78
+ * would turn the honest headline ("almost nobody asks; we serve it anyway")
79
+ * into a meaningless one where almost everybody asks.
80
+ *
81
+ * `text/markdown;q=0` is a refusal and returns false, same as `detect()`.
82
+ */
83
+ declare function acceptsMarkdownHeader(accept: string | null | undefined): boolean;
38
84
  /**
39
85
  * Classify a request from its headers (and optionally URL). Pure compute:
40
86
  * no network, no crypto. Checks run cheapest-first; every check that fires
@@ -176,4 +222,4 @@ declare function verifyWebBotAuth(input: DetectInput, options: VerifyWebBotAuthO
176
222
 
177
223
  declare const KNOWN_AGENT_DIRECTORY: AgentKeyRegistry;
178
224
 
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 };
225
+ 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,24 @@ 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" },
89
+ // Apple's search crawler for Spotlight, Siri and Safari suggestions, so it
90
+ // sits with Googlebot on the canonical-HTML side. Source:
91
+ // https://support.apple.com/en-us/119829 (UA "contains Applebot", e.g.
92
+ // `... Safari/605.1.15 (Applebot/0.1; +http://www.apple.com/go/applebot)`).
93
+ // `Applebot-Extended` is deliberately NOT a pattern: Apple documents it as a
94
+ // robots.txt token that "does not crawl webpages"; it only controls whether
95
+ // Applebot's crawl may train Apple's models, and it never arrives as a
96
+ // User-Agent of its own.
97
+ { pattern: "applebot", platform: "applebot" }
77
98
  ];
78
99
  var AGENT_UA = [
79
100
  { pattern: "claude-code", platform: "claude-code" },
@@ -88,7 +109,24 @@ var AGENT_UA = [
88
109
  { pattern: "claude-web", platform: "claude" },
89
110
  { pattern: "claudebot", platform: "claude" },
90
111
  { pattern: "claude-user", platform: "claude" },
91
- { pattern: "anthropic-ai", platform: "claude" }
112
+ { pattern: "anthropic-ai", platform: "claude" },
113
+ // Meta's AI crawler (model training and Meta product indexing) and its
114
+ // user-initiated fetcher. Source, both tokens:
115
+ // https://developers.facebook.com/documentation/sharing/webmasters/web-crawlers
116
+ // (`meta-externalagent/1.1 (+...)`, `meta-externalfetcher/1.1 (+...)`).
117
+ { pattern: "meta-externalagent", platform: "meta" },
118
+ { pattern: "meta-externalfetcher", platform: "meta" },
119
+ // Source: https://developer.amazon.com/amazonbot
120
+ // (`Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Amazonbot/0.1) Chrome/W.X.Y.Z Safari/537.36`).
121
+ { pattern: "amazonbot", platform: "amazon" },
122
+ // DuckDuckGo's real-time fetcher for DuckAssist answers. Source:
123
+ // https://duckduckgo.com/duckduckgo-help-pages/results/duckassistbot
124
+ // (`DuckAssistBot/1.2; (+http://duckduckgo.com/duckassistbot.html)`).
125
+ { pattern: "duckassistbot", platform: "duckduckgo" },
126
+ // Mistral's user-initiated fetcher: it visits a page when a user's question
127
+ // needs it, and is not an automatic crawler. Source: https://docs.mistral.ai/robots
128
+ // (`Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; MistralAI-User/1.0; +https://docs.mistral.ai/robots)`).
129
+ { pattern: "mistralai-user", platform: "mistral" }
92
130
  ];
93
131
  function findUaEntry(ua, table) {
94
132
  return table.find((entry) => ua.includes(entry.pattern));
@@ -139,7 +177,12 @@ function detect(input) {
139
177
  };
140
178
  }
141
179
  if (protocolRoute !== null) {
142
- return { ...base, kind: "protocol", platform: agentUaMatch?.platform ?? null, confidence: "high" };
180
+ return {
181
+ ...base,
182
+ kind: "protocol",
183
+ platform: agentUaMatch?.platform ?? null,
184
+ confidence: "high"
185
+ };
143
186
  }
144
187
  if (agentUaMatch !== void 0) {
145
188
  return { ...base, kind: "agent", platform: agentUaMatch.platform, confidence: "medium" };
@@ -438,6 +481,6 @@ var KNOWN_AGENT_DIRECTORY = {
438
481
  // pass their own registry) from the platforms' published key directories.
439
482
  };
440
483
 
441
- export { CLOCK_SKEW_SECONDS, KNOWN_AGENT_DIRECTORY, detect, verifyWebBotAuth };
484
+ export { CLOCK_SKEW_SECONDS, KNOWN_AGENT_DIRECTORY, acceptsMarkdownHeader, detect, verifyWebBotAuth };
442
485
  //# sourceMappingURL=index.js.map
443
486
  //# 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,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AiB,aAAa,YAAY,CAAA;AAChD,EAAA,IAAI,cAAA,KAAmB,IAAA,EAAM,OAAO,OAAA,CAAQ,aAAa,KAAK,CAAA;AAC9D,EAAA,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.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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C3D;;;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 // Apple's search crawler for Spotlight, Siri and Safari suggestions, so it\n // sits with Googlebot on the canonical-HTML side. Source:\n // https://support.apple.com/en-us/119829 (UA \"contains Applebot\", e.g.\n // `... Safari/605.1.15 (Applebot/0.1; +http://www.apple.com/go/applebot)`).\n // `Applebot-Extended` is deliberately NOT a pattern: Apple documents it as a\n // robots.txt token that \"does not crawl webpages\"; it only controls whether\n // Applebot's crawl may train Apple's models, and it never arrives as a\n // User-Agent of its own.\n { pattern: 'applebot', platform: 'applebot' },\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 // Meta's AI crawler (model training and Meta product indexing) and its\n // user-initiated fetcher. Source, both tokens:\n // https://developers.facebook.com/documentation/sharing/webmasters/web-crawlers\n // (`meta-externalagent/1.1 (+...)`, `meta-externalfetcher/1.1 (+...)`).\n { pattern: 'meta-externalagent', platform: 'meta' },\n { pattern: 'meta-externalfetcher', platform: 'meta' },\n // Source: https://developer.amazon.com/amazonbot\n // (`Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Amazonbot/0.1) Chrome/W.X.Y.Z Safari/537.36`).\n { pattern: 'amazonbot', platform: 'amazon' },\n // DuckDuckGo's real-time fetcher for DuckAssist answers. Source:\n // https://duckduckgo.com/duckduckgo-help-pages/results/duckassistbot\n // (`DuckAssistBot/1.2; (+http://duckduckgo.com/duckassistbot.html)`).\n { pattern: 'duckassistbot', platform: 'duckduckgo' },\n // Mistral's user-initiated fetcher: it visits a page when a user's question\n // needs it, and is not an automatic crawler. Source: https://docs.mistral.ai/robots\n // (`Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; MistralAI-User/1.0; +https://docs.mistral.ai/robots)`).\n { pattern: 'mistralai-user', platform: 'mistral' },\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,20 +1,25 @@
1
1
  {
2
2
  "name": "@rebilder/agent-detect",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
- "description": "Agent identification from request headers: Accept negotiation, Web Bot Auth signals, protocol routes, UA heuristics. Pure compute, zero runtime dependencies.",
5
+ "description": "Tell AI agents, search crawlers and people apart from request headers, and verify Web Bot Auth signatures. No dependencies; runs at the edge.",
6
6
  "license": "Apache-2.0",
7
- "homepage": "https://rebilder.com",
7
+ "homepage": "https://rebilder.com/docs/classification",
8
8
  "bugs": {
9
9
  "url": "https://rebilder.com/help",
10
10
  "email": "support@rebilder.com"
11
11
  },
12
12
  "keywords": [
13
- "agent",
13
+ "ai",
14
+ "ai-agents",
14
15
  "bot-detection",
15
16
  "user-agent",
17
+ "crawler",
16
18
  "web-bot-auth",
17
- "content-negotiation"
19
+ "http-message-signatures",
20
+ "content-negotiation",
21
+ "markdown",
22
+ "edge"
18
23
  ],
19
24
  "type": "module",
20
25
  "sideEffects": false,
@@ -23,7 +28,8 @@
23
28
  "types": "./dist/index.d.ts",
24
29
  "files": [
25
30
  "dist",
26
- "README.md"
31
+ "README.md",
32
+ "CHANGELOG.md"
27
33
  ],
28
34
  "exports": {
29
35
  ".": {
@@ -42,7 +48,7 @@
42
48
  "access": "public"
43
49
  },
44
50
  "engines": {
45
- "node": ">=20.11.0"
51
+ "node": ">=22"
46
52
  },
47
53
  "devDependencies": {
48
54
  "@types/node": "^26.1.2",