@rebilder/agent-detect 0.1.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.
@@ -0,0 +1,179 @@
1
+ /** Coarse classification of who (or what) issued the request. */
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';
5
+ interface DetectInput {
6
+ /**
7
+ * Request headers. Lookup is case-insensitive; multi-value headers may be
8
+ * passed as arrays (they are treated as a comma-joined list, per RFC 9110).
9
+ */
10
+ headers: Record<string, string | string[] | undefined>;
11
+ /** Full URL or pathname; the pathname is used for protocol-route hits. */
12
+ url?: string;
13
+ /** HTTP method. Accepted for contract stability; not yet used for classification. */
14
+ method?: string;
15
+ }
16
+ interface DetectionResult {
17
+ kind: RequesterKind;
18
+ platform: AgentPlatform | null;
19
+ /**
20
+ * True only when a Web Bot Auth signature chain was cryptographically
21
+ * verified. detect() itself NEVER verifies (it is synchronous, parse-only)
22
+ * and always reports false here; verification is the separate async
23
+ * verifyWebBotAuth() step (src/verify.ts) that the paths needing
24
+ * cryptographic identity — preference payloads, protocol transactions —
25
+ * run explicitly with an injected key registry.
26
+ */
27
+ verified: boolean;
28
+ /** The Accept header explicitly includes text/markdown (with q > 0). */
29
+ acceptsMarkdown: boolean;
30
+ /**
31
+ * Ordered list of checks that fired, in detection order, e.g.
32
+ * ['accept:text/markdown', 'ua:claude-code'].
33
+ */
34
+ signals: string[];
35
+ confidence: 'high' | 'medium' | 'low';
36
+ }
37
+
38
+ /**
39
+ * Classify a request from its headers (and optionally URL). Pure compute:
40
+ * no network, no crypto. Checks run cheapest-first; every check that fires
41
+ * is recorded in `signals`, and the highest-precedence one classifies.
42
+ *
43
+ * Precedence: crawler UA (guardrail) > Accept: text/markdown >
44
+ * Signature-Agent / Web Bot Auth headers > protocol route > agent UA > human.
45
+ */
46
+ declare function detect(input: DetectInput): DetectionResult;
47
+
48
+ /**
49
+ * Web Bot Auth verification — the Phase 3 async counterpart to detect().
50
+ *
51
+ * PURE CRYPTO WITH INJECTED KEYS. This module verifies RFC 9421-style HTTP
52
+ * message signatures (Signature-Input / Signature / Signature-Agent) against
53
+ * a caller-provided key registry. It NEVER fetches a key directory, never
54
+ * touches the network, never reads the environment — the registry is
55
+ * dependency-injected, so the hot path stays within the edge budget
56
+ * (CLAUDE.md Conventions: no network calls on the hot path). Key directory
57
+ * refresh is an offline/operator concern (see README § Verification).
58
+ *
59
+ * detect() stays synchronous and unchanged: it parses these headers as
60
+ * identity *signals* only and always reports `verified: false`. Paths that
61
+ * need cryptographic identity (preference payloads, protocol transactions —
62
+ * ROADMAP Phase 3 P0) call verifyWebBotAuth() as a separate async step.
63
+ *
64
+ * Failure behavior is constant: malformed, hostile, or garbage input NEVER
65
+ * throws — every path resolves to `{ verified: false, reason }`.
66
+ */
67
+
68
+ /** Why verification did not succeed. */
69
+ type VerificationFailureReason = 'no-signature' | 'unknown-agent' | 'unknown-key' | 'expired' | 'created-in-future' | 'bad-signature' | 'malformed' | 'unsupported-alg';
70
+ interface VerificationResult {
71
+ verified: boolean;
72
+ /** The registry entry's platform, set only when verified. */
73
+ platform?: AgentPlatform;
74
+ /** The keyid parsed from Signature-Input, set once parsing got that far. */
75
+ keyid?: string;
76
+ /** Set exactly when `verified` is false. */
77
+ reason?: VerificationFailureReason;
78
+ }
79
+ /** An Ed25519 public key in JWK form (RFC 8037: OKP / Ed25519 / x). */
80
+ interface Ed25519PublicJwk {
81
+ kty: 'OKP';
82
+ crv: 'Ed25519';
83
+ /** base64url-encoded public key bytes. */
84
+ x: string;
85
+ }
86
+ interface AgentPublicKey {
87
+ /** Matches the `keyid` parameter the agent sends in Signature-Input. */
88
+ keyid: string;
89
+ /** ed25519 is the only algorithm supported in v0. */
90
+ alg: 'ed25519';
91
+ publicKeyJwk: Ed25519PublicJwk;
92
+ }
93
+ interface AgentKeyRegistryEntry {
94
+ /** The platform this origin's keys attest to. */
95
+ platform: AgentPlatform;
96
+ keys: AgentPublicKey[];
97
+ }
98
+ /**
99
+ * Key registry keyed by the agent's Signature-Agent origin, e.g.
100
+ * `"https://chatgpt.com"`. Bare hosts (`"chatgpt.com"`) are accepted and
101
+ * normalized to the https origin. See KNOWN_AGENT_DIRECTORY (src/directory.ts)
102
+ * for the shape — it ships EMPTY; operators populate it from the platforms'
103
+ * published key directories.
104
+ */
105
+ type AgentKeyRegistry = Record<string, AgentKeyRegistryEntry>;
106
+ interface VerifyWebBotAuthOptions {
107
+ /** The injected key registry. Verification is pure crypto over these keys. */
108
+ keys: AgentKeyRegistry;
109
+ /** Clock override for tests/replays. Defaults to `new Date()`. */
110
+ now?: Date;
111
+ /**
112
+ * Deliberately impossible to set: this function performs NO network I/O.
113
+ * Key directory fetch/refresh happens offline, outside this module.
114
+ */
115
+ fetchImpl?: never;
116
+ }
117
+ /** Allowed clock skew for `created` / `expires`, in seconds (±). */
118
+ declare const CLOCK_SKEW_SECONDS = 300;
119
+ /**
120
+ * Verify a request's Web Bot Auth signature chain against an injected key
121
+ * registry. Async (WebCrypto) but pure: no network, no environment, no
122
+ * global state. Never throws — every failure resolves to
123
+ * `{ verified: false, reason }`.
124
+ *
125
+ * Requirements enforced (Web Bot Auth profile over RFC 9421):
126
+ * - `Signature` + `Signature-Input` present, structured-field parseable
127
+ * - covered components include `@authority` AND `signature-agent`
128
+ * (anti-replay: the signature is pinned to this host and this identity)
129
+ * - `keyid`, `created`, `expires` parameters present; `created <= expires`;
130
+ * both within ±CLOCK_SKEW_SECONDS of `options.now`
131
+ * - `alg`, when present, is `ed25519`
132
+ * - `Signature-Agent` origin resolves to a registry entry; `keyid` resolves
133
+ * to one of that entry's keys
134
+ * - Ed25519 signature verifies (WebCrypto subtle) over the RFC 9421
135
+ * signature base, whose `"@signature-params"` line reuses the exact
136
+ * serialization the agent sent
137
+ */
138
+ declare function verifyWebBotAuth(input: DetectInput, options: VerifyWebBotAuthOptions): Promise<VerificationResult>;
139
+
140
+ /**
141
+ * KNOWN_AGENT_DIRECTORY — the built-in Web Bot Auth key registry.
142
+ *
143
+ * THIS IS A DATA MODULE, AND IT SHIPS EMPTY — DELIBERATELY. We do not embed
144
+ * "known" production public keys for OpenAI, Anthropic, Perplexity, etc.,
145
+ * because we have not fetched and pinned them from the platforms' published
146
+ * key directories, and inventing key material would make verification
147
+ * silently meaningless (a fabricated key either verifies nothing or, worse,
148
+ * verifies the wrong thing). Honesty over completeness.
149
+ *
150
+ * How this gets populated (operator responsibility, README § Verification):
151
+ * agent platforms publish their signing keys at well-known HTTP message
152
+ * signature directories (e.g. `https://<platform>/.well-known/
153
+ * http-message-signatures-directory`). Operators fetch those OFFLINE — never
154
+ * on the request hot path — pin the Ed25519 public keys here (or in their own
155
+ * registry object; any `AgentKeyRegistry` works), and refresh on key
156
+ * rotation. A refresh script that snapshots the published directories into
157
+ * this module is future work (ROADMAP parking-lot material).
158
+ *
159
+ * Shape of a populated entry (this example is NOT a real key):
160
+ *
161
+ * 'https://chatgpt.com': {
162
+ * platform: 'chatgpt',
163
+ * keys: [
164
+ * {
165
+ * keyid: 'poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U', // JWK thumbprint the agent sends
166
+ * alg: 'ed25519',
167
+ * publicKeyJwk: { kty: 'OKP', crv: 'Ed25519', x: '<base64url public key bytes>' },
168
+ * },
169
+ * ],
170
+ * },
171
+ *
172
+ * With the directory empty, verifyWebBotAuth() resolves every signed request
173
+ * to `{ verified: false, reason: 'unknown-agent' }` — the honest answer when
174
+ * no trusted key is on file.
175
+ */
176
+
177
+ declare const KNOWN_AGENT_DIRECTORY: AgentKeyRegistry;
178
+
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 };
@@ -0,0 +1,179 @@
1
+ /** Coarse classification of who (or what) issued the request. */
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';
5
+ interface DetectInput {
6
+ /**
7
+ * Request headers. Lookup is case-insensitive; multi-value headers may be
8
+ * passed as arrays (they are treated as a comma-joined list, per RFC 9110).
9
+ */
10
+ headers: Record<string, string | string[] | undefined>;
11
+ /** Full URL or pathname; the pathname is used for protocol-route hits. */
12
+ url?: string;
13
+ /** HTTP method. Accepted for contract stability; not yet used for classification. */
14
+ method?: string;
15
+ }
16
+ interface DetectionResult {
17
+ kind: RequesterKind;
18
+ platform: AgentPlatform | null;
19
+ /**
20
+ * True only when a Web Bot Auth signature chain was cryptographically
21
+ * verified. detect() itself NEVER verifies (it is synchronous, parse-only)
22
+ * and always reports false here; verification is the separate async
23
+ * verifyWebBotAuth() step (src/verify.ts) that the paths needing
24
+ * cryptographic identity — preference payloads, protocol transactions —
25
+ * run explicitly with an injected key registry.
26
+ */
27
+ verified: boolean;
28
+ /** The Accept header explicitly includes text/markdown (with q > 0). */
29
+ acceptsMarkdown: boolean;
30
+ /**
31
+ * Ordered list of checks that fired, in detection order, e.g.
32
+ * ['accept:text/markdown', 'ua:claude-code'].
33
+ */
34
+ signals: string[];
35
+ confidence: 'high' | 'medium' | 'low';
36
+ }
37
+
38
+ /**
39
+ * Classify a request from its headers (and optionally URL). Pure compute:
40
+ * no network, no crypto. Checks run cheapest-first; every check that fires
41
+ * is recorded in `signals`, and the highest-precedence one classifies.
42
+ *
43
+ * Precedence: crawler UA (guardrail) > Accept: text/markdown >
44
+ * Signature-Agent / Web Bot Auth headers > protocol route > agent UA > human.
45
+ */
46
+ declare function detect(input: DetectInput): DetectionResult;
47
+
48
+ /**
49
+ * Web Bot Auth verification — the Phase 3 async counterpart to detect().
50
+ *
51
+ * PURE CRYPTO WITH INJECTED KEYS. This module verifies RFC 9421-style HTTP
52
+ * message signatures (Signature-Input / Signature / Signature-Agent) against
53
+ * a caller-provided key registry. It NEVER fetches a key directory, never
54
+ * touches the network, never reads the environment — the registry is
55
+ * dependency-injected, so the hot path stays within the edge budget
56
+ * (CLAUDE.md Conventions: no network calls on the hot path). Key directory
57
+ * refresh is an offline/operator concern (see README § Verification).
58
+ *
59
+ * detect() stays synchronous and unchanged: it parses these headers as
60
+ * identity *signals* only and always reports `verified: false`. Paths that
61
+ * need cryptographic identity (preference payloads, protocol transactions —
62
+ * ROADMAP Phase 3 P0) call verifyWebBotAuth() as a separate async step.
63
+ *
64
+ * Failure behavior is constant: malformed, hostile, or garbage input NEVER
65
+ * throws — every path resolves to `{ verified: false, reason }`.
66
+ */
67
+
68
+ /** Why verification did not succeed. */
69
+ type VerificationFailureReason = 'no-signature' | 'unknown-agent' | 'unknown-key' | 'expired' | 'created-in-future' | 'bad-signature' | 'malformed' | 'unsupported-alg';
70
+ interface VerificationResult {
71
+ verified: boolean;
72
+ /** The registry entry's platform, set only when verified. */
73
+ platform?: AgentPlatform;
74
+ /** The keyid parsed from Signature-Input, set once parsing got that far. */
75
+ keyid?: string;
76
+ /** Set exactly when `verified` is false. */
77
+ reason?: VerificationFailureReason;
78
+ }
79
+ /** An Ed25519 public key in JWK form (RFC 8037: OKP / Ed25519 / x). */
80
+ interface Ed25519PublicJwk {
81
+ kty: 'OKP';
82
+ crv: 'Ed25519';
83
+ /** base64url-encoded public key bytes. */
84
+ x: string;
85
+ }
86
+ interface AgentPublicKey {
87
+ /** Matches the `keyid` parameter the agent sends in Signature-Input. */
88
+ keyid: string;
89
+ /** ed25519 is the only algorithm supported in v0. */
90
+ alg: 'ed25519';
91
+ publicKeyJwk: Ed25519PublicJwk;
92
+ }
93
+ interface AgentKeyRegistryEntry {
94
+ /** The platform this origin's keys attest to. */
95
+ platform: AgentPlatform;
96
+ keys: AgentPublicKey[];
97
+ }
98
+ /**
99
+ * Key registry keyed by the agent's Signature-Agent origin, e.g.
100
+ * `"https://chatgpt.com"`. Bare hosts (`"chatgpt.com"`) are accepted and
101
+ * normalized to the https origin. See KNOWN_AGENT_DIRECTORY (src/directory.ts)
102
+ * for the shape — it ships EMPTY; operators populate it from the platforms'
103
+ * published key directories.
104
+ */
105
+ type AgentKeyRegistry = Record<string, AgentKeyRegistryEntry>;
106
+ interface VerifyWebBotAuthOptions {
107
+ /** The injected key registry. Verification is pure crypto over these keys. */
108
+ keys: AgentKeyRegistry;
109
+ /** Clock override for tests/replays. Defaults to `new Date()`. */
110
+ now?: Date;
111
+ /**
112
+ * Deliberately impossible to set: this function performs NO network I/O.
113
+ * Key directory fetch/refresh happens offline, outside this module.
114
+ */
115
+ fetchImpl?: never;
116
+ }
117
+ /** Allowed clock skew for `created` / `expires`, in seconds (±). */
118
+ declare const CLOCK_SKEW_SECONDS = 300;
119
+ /**
120
+ * Verify a request's Web Bot Auth signature chain against an injected key
121
+ * registry. Async (WebCrypto) but pure: no network, no environment, no
122
+ * global state. Never throws — every failure resolves to
123
+ * `{ verified: false, reason }`.
124
+ *
125
+ * Requirements enforced (Web Bot Auth profile over RFC 9421):
126
+ * - `Signature` + `Signature-Input` present, structured-field parseable
127
+ * - covered components include `@authority` AND `signature-agent`
128
+ * (anti-replay: the signature is pinned to this host and this identity)
129
+ * - `keyid`, `created`, `expires` parameters present; `created <= expires`;
130
+ * both within ±CLOCK_SKEW_SECONDS of `options.now`
131
+ * - `alg`, when present, is `ed25519`
132
+ * - `Signature-Agent` origin resolves to a registry entry; `keyid` resolves
133
+ * to one of that entry's keys
134
+ * - Ed25519 signature verifies (WebCrypto subtle) over the RFC 9421
135
+ * signature base, whose `"@signature-params"` line reuses the exact
136
+ * serialization the agent sent
137
+ */
138
+ declare function verifyWebBotAuth(input: DetectInput, options: VerifyWebBotAuthOptions): Promise<VerificationResult>;
139
+
140
+ /**
141
+ * KNOWN_AGENT_DIRECTORY — the built-in Web Bot Auth key registry.
142
+ *
143
+ * THIS IS A DATA MODULE, AND IT SHIPS EMPTY — DELIBERATELY. We do not embed
144
+ * "known" production public keys for OpenAI, Anthropic, Perplexity, etc.,
145
+ * because we have not fetched and pinned them from the platforms' published
146
+ * key directories, and inventing key material would make verification
147
+ * silently meaningless (a fabricated key either verifies nothing or, worse,
148
+ * verifies the wrong thing). Honesty over completeness.
149
+ *
150
+ * How this gets populated (operator responsibility, README § Verification):
151
+ * agent platforms publish their signing keys at well-known HTTP message
152
+ * signature directories (e.g. `https://<platform>/.well-known/
153
+ * http-message-signatures-directory`). Operators fetch those OFFLINE — never
154
+ * on the request hot path — pin the Ed25519 public keys here (or in their own
155
+ * registry object; any `AgentKeyRegistry` works), and refresh on key
156
+ * rotation. A refresh script that snapshots the published directories into
157
+ * this module is future work (ROADMAP parking-lot material).
158
+ *
159
+ * Shape of a populated entry (this example is NOT a real key):
160
+ *
161
+ * 'https://chatgpt.com': {
162
+ * platform: 'chatgpt',
163
+ * keys: [
164
+ * {
165
+ * keyid: 'poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U', // JWK thumbprint the agent sends
166
+ * alg: 'ed25519',
167
+ * publicKeyJwk: { kty: 'OKP', crv: 'Ed25519', x: '<base64url public key bytes>' },
168
+ * },
169
+ * ],
170
+ * },
171
+ *
172
+ * With the directory empty, verifyWebBotAuth() resolves every signed request
173
+ * to `{ verified: false, reason: 'unknown-agent' }` — the honest answer when
174
+ * no trusted key is on file.
175
+ */
176
+
177
+ declare const KNOWN_AGENT_DIRECTORY: AgentKeyRegistry;
178
+
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 };