agent-traffic-gate 0.0.0-stage → 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,64 @@
1
+ // Put each request in one class, from strongest evidence to weakest:
2
+ // signed-agent a signature verified against keys fetched from the agent's own URL (or a payment network)
3
+ // verified-bot a known crawler's user agent, from an address on that operator's published IP list
4
+ // spoofed claims to be a known bot or a known signer, and the proof fails
5
+ // claimed-bot claims a known bot whose operator publishes no IP list (cannot be checked)
6
+ // automation announces itself as a script, crawler or headless browser, with no proof
7
+ // unknown nothing says it is automated (most people, and well-disguised bots)
8
+ import { claimedBot, looksAutomated, BOTS, OPERATORS } from 'ai-traffic-insights/bots';
9
+ import { parseIp, cidrSetFromJson } from 'ai-traffic-insights/ip';
10
+ import { knownSigner } from './agents.js';
11
+
12
+ export const CLASSES = ['signed-agent', 'verified-bot', 'spoofed', 'claimed-bot', 'automation', 'unknown'];
13
+
14
+ /**
15
+ * Bot IP lists from JSON you already have (for edge runtimes), as { url: json }.
16
+ * In Node, loadBotRanges() downloads and caches them for you.
17
+ */
18
+ export function botRangesFromJson(map) {
19
+ const out = new Map();
20
+ for (const [url, json] of Object.entries(map)) { const { set } = cidrSetFromJson(json); out.set(url, { set }); }
21
+ return out;
22
+ }
23
+
24
+ /** Node only: download (and cache for a day) every official IP list. */
25
+ export async function loadBotRanges(opts = {}) {
26
+ const { loadRanges } = await import('ai-traffic-insights');
27
+ return loadRanges(opts);
28
+ }
29
+
30
+ function ipCheck(bot, ip, ranges) {
31
+ const lists = (bot.ranges || []).map((u) => ranges?.get(u)?.set).filter(Boolean);
32
+ if (!lists.length) return 'unknown';
33
+ const p = parseIp(ip);
34
+ return p && lists.some((s) => s.has(p)) ? 'verified' : 'spoofed';
35
+ }
36
+
37
+ /**
38
+ * classify({ ua, ip, verification, ranges })
39
+ * verification: result of verifier.verify(request); ranges: Map from loadBotRanges / botRangesFromJson.
40
+ */
41
+ export function classify({ ua, ip, verification, ranges }) {
42
+ const v = verification || { status: 'unsigned', verified: false };
43
+ if (v.verified) {
44
+ return { class: 'signed-agent', id: v.agent.id || v.agent.identity, name: v.agent.name, operator: v.agent.operator, intent: v.agent.intent, evidence: `signature verified against ${v.agent.identity}${v.agent.bound ? ' (directory signed by the same key)' : ''}` };
45
+ }
46
+ const bot = claimedBot(ua);
47
+ // A signature that names a well-known signer but fails is a spoofing attempt; a fetch failure is not.
48
+ const claimedSigner = (v.claimed || []).map((u) => { try { return knownSigner(new URL(u).origin + '/') || knownSigner(u); } catch { return null; } }).find(Boolean);
49
+ if (claimedSigner && ['invalid', 'unknown-key', 'replay', 'expired', 'too-long', 'bad-alg'].includes(v.status)) {
50
+ return { class: 'spoofed', id: claimedSigner.id, name: claimedSigner.name, operator: claimedSigner.operator, evidence: `claims to be ${claimedSigner.name} but the signature failed: ${v.reason}` };
51
+ }
52
+ if (bot) {
53
+ const check = ip ? ipCheck(bot, ip, ranges) : 'unknown';
54
+ const op = OPERATORS[bot.operator]?.name || bot.operator;
55
+ if (check === 'verified') return { class: 'verified-bot', id: bot.id, name: bot.id, operator: op, kind: bot.kind, evidence: `user agent ${bot.id}, address on ${op}'s published list` };
56
+ if (check === 'spoofed') return { class: 'spoofed', id: bot.id, name: bot.id, operator: op, kind: bot.kind, evidence: `user agent says ${bot.id}, but ${ip} is not on ${op}'s published list` };
57
+ return { class: 'claimed-bot', id: bot.id, name: bot.id, operator: op, kind: bot.kind, evidence: bot.ranges?.length ? `user agent says ${bot.id}; IP lists not loaded, so it was not checked` : `user agent says ${bot.id}; ${op} publishes no IP list` };
58
+ }
59
+ if (v.status !== 'unsigned' && v.status !== 'ignored') return { class: 'automation', id: null, evidence: `signed but not verified (${v.status}${v.reason ? `: ${v.reason}` : ''})` };
60
+ if (looksAutomated(ua)) return { class: 'automation', id: null, evidence: ua ? 'user agent looks like a script or crawler' : 'no user agent' };
61
+ return { class: 'unknown', id: null, evidence: 'no sign of automation' };
62
+ }
63
+
64
+ export { BOTS };
@@ -0,0 +1,237 @@
1
+ // Key discovery for Web Bot Auth (draft-ietf-webbotauth-httpsig-protocol-01, Section 5.5 and Appendix B).
2
+ // A Signature-Agent URL is fetched directly as a JWK Set. Rules followed here:
3
+ // - HTTPS only, no credentials or fragment, no automatic redirects, only 200 counts;
4
+ // - a bare origin ("https://chatgpt.com", the legacy form) resolves to its well-known directory first
5
+ // and falls back to the URL itself only on 404/410, as Cloudflare's reference verifier does;
6
+ // - at the well-known URI the media type must be application/http-message-signatures-directory+json
7
+ // and any kid must equal the key's thumbprint;
8
+ // - an optional directory signature (tag "http-message-signatures-directory") is checked when present;
9
+ // - keys are cached per (URL, keyid); a failed refresh never evicts a good cache entry;
10
+ // - fetches are bounded (size, key count, timeout) and private addresses are refused (SSRF).
11
+ import { parseDictionary, SfvError } from './sfv.js';
12
+ import { jwkThumbprint, algFromJwk, responseSignatureBase, verifyBytes, checkContentDigest, describeRequest, parseSignatureHeaders, SigError } from './httpsig.js';
13
+ import { headerGetter } from './util.js';
14
+
15
+ export const WELL_KNOWN = '/.well-known/http-message-signatures-directory';
16
+ export const MEDIA_TYPE = 'application/http-message-signatures-directory+json';
17
+ const MAX_BYTES = 64 * 1024;
18
+ const MAX_KEYS = 100;
19
+
20
+ /** Is this host a literal private, loopback or link-local address (or localhost)? */
21
+ export function isPrivateHost(host) {
22
+ const h = host.replace(/^\[|\]$/g, '').toLowerCase();
23
+ if (h === 'localhost' || h.endsWith('.localhost') || h.endsWith('.local') || h.endsWith('.internal')) return true;
24
+ const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h);
25
+ if (v4) {
26
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
27
+ return a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224;
28
+ }
29
+ if (h.includes(':')) return h === '::1' || h === '::' || /^f[cd]/.test(h) || /^fe[89ab]/.test(h) || h.startsWith('::ffff:');
30
+ return false;
31
+ }
32
+
33
+ /** Normalise a Signature-Agent URL to the identifier the draft uses (query dropped). */
34
+ export function normalizeAgentUrl(u) {
35
+ const url = new URL(u);
36
+ url.search = '';
37
+ url.hash = '';
38
+ url.hostname = url.hostname.toLowerCase();
39
+ return url.href;
40
+ }
41
+
42
+ /** Parse a Signature-Agent header: dictionary (current) or bare string (legacy). */
43
+ export function parseSignatureAgent(value) {
44
+ if (value == null) return null;
45
+ const v = String(value).trim();
46
+ if (v.startsWith('"')) {
47
+ const m = /^"((?:[^"\\]|\\.)*)"$/.exec(v);
48
+ if (!m) return { kind: 'invalid', error: 'legacy Signature-Agent is not a valid string', entries: [] };
49
+ return { kind: 'legacy', entries: [{ label: null, uri: m[1].replace(/\\(.)/g, '$1') }] };
50
+ }
51
+ let dict;
52
+ try { dict = parseDictionary(v); } catch (e) { return { kind: 'invalid', error: e.message, entries: [] }; }
53
+ const entries = [];
54
+ const ignored = [];
55
+ for (const [label, [uri, params]] of dict) {
56
+ if (params.size) { ignored.push({ label, reason: 'members must not carry parameters' }); continue; }
57
+ if (typeof uri !== 'string') { ignored.push({ label, reason: 'member is not a string' }); continue; }
58
+ entries.push({ label, uri });
59
+ }
60
+ return { kind: 'current', entries, ignored };
61
+ }
62
+
63
+ function checkUrl(u) {
64
+ let url;
65
+ try { url = new URL(u); } catch { throw new SigError('bad-agent', `Signature-Agent ${u} is not a URL`); }
66
+ if (url.protocol !== 'https:') throw new SigError('bad-agent', 'Signature-Agent must use https');
67
+ if (url.username || url.password || url.hash) throw new SigError('bad-agent', 'Signature-Agent must not carry credentials or a fragment');
68
+ if (isPrivateHost(url.hostname)) throw new SigError('bad-agent', 'Signature-Agent points to a private address');
69
+ return url;
70
+ }
71
+
72
+ async function boundedFetch(url, { fetchImpl = globalThis.fetch, timeoutMs = 5000 } = {}) {
73
+ const ctl = new AbortController();
74
+ const t = setTimeout(() => ctl.abort(), timeoutMs);
75
+ try {
76
+ const r = await fetchImpl(url, { redirect: 'manual', signal: ctl.signal, headers: { accept: `${MEDIA_TYPE}, application/jwk-set+json;q=0.9, application/json;q=0.8` } });
77
+ let body = '';
78
+ if (r.status === 200) {
79
+ if (r.body?.getReader) {
80
+ const reader = r.body.getReader();
81
+ const chunks = [];
82
+ let size = 0;
83
+ for (;;) {
84
+ const { done, value } = await reader.read();
85
+ if (done) break;
86
+ size += value.length;
87
+ if (size > MAX_BYTES) { reader.cancel().catch(() => {}); throw new SigError('directory', `directory is larger than ${MAX_BYTES} bytes`); }
88
+ chunks.push(value);
89
+ }
90
+ const all = new Uint8Array(size);
91
+ let o = 0;
92
+ for (const c of chunks) { all.set(c, o); o += c.length; }
93
+ body = new TextDecoder().decode(all);
94
+ } else {
95
+ body = await r.text();
96
+ if (body.length > MAX_BYTES) throw new SigError('directory', `directory is larger than ${MAX_BYTES} bytes`);
97
+ }
98
+ }
99
+ return { status: r.status, headers: r.headers, body };
100
+ } catch (e) {
101
+ if (e instanceof SigError) throw e;
102
+ throw new SigError('directory', e.name === 'AbortError' ? `timed out fetching ${url}` : `could not fetch ${url}: ${e.message}`);
103
+ } finally { clearTimeout(t); }
104
+ }
105
+
106
+ /**
107
+ * Check a fetched directory response: JWKS shape, media type at the well-known URI,
108
+ * kid = thumbprint there, and the optional directory signature.
109
+ * Returns { keys: [{ jwk, thumbprint, alg }], bound, problems: [], maxAge }
110
+ */
111
+ export async function checkDirectory({ url, status, headers, body }, { now = Math.floor(Date.now() / 1000) } = {}) {
112
+ const problems = [];
113
+ const get = headerGetter(headers);
114
+ const target = new URL(url);
115
+ const wellKnown = target.pathname === WELL_KNOWN;
116
+ if (status !== 200) throw new SigError('directory', `directory returned HTTP ${status}${status >= 300 && status < 400 ? ' (redirects are not followed)' : ''}`);
117
+ const type = (get('content-type') || '').split(';')[0].trim().toLowerCase();
118
+ if (wellKnown && type !== MEDIA_TYPE) problems.push(`media type is "${type || 'missing'}", the draft requires ${MEDIA_TYPE} at the well-known URI`);
119
+ let json;
120
+ try { json = JSON.parse(body); } catch { throw new SigError('directory', 'directory is not valid JSON'); }
121
+ if (!json || !Array.isArray(json.keys)) throw new SigError('directory', 'directory is not a JWK Set (no "keys" array)');
122
+ if (json.keys.length > MAX_KEYS) throw new SigError('directory', `directory has more than ${MAX_KEYS} keys`);
123
+ const keys = [];
124
+ for (const [i, jwk] of json.keys.entries()) {
125
+ if (!jwk || typeof jwk !== 'object') { problems.push(`key ${i} is not an object`); continue; }
126
+ if (jwk.d || jwk.p || jwk.k) { problems.push(`key ${i} contains private key material; it must be removed and the key replaced`); continue; }
127
+ let thumbprint;
128
+ try { thumbprint = await jwkThumbprint(jwk); } catch (e) { problems.push(`key ${i}: ${e.message}`); continue; }
129
+ if (wellKnown && jwk.kid != null && jwk.kid !== thumbprint) problems.push(`key ${i} has kid "${jwk.kid}" but its thumbprint is ${thumbprint}; at the well-known URI they must match`);
130
+ if (jwk.use && jwk.use !== 'sig') problems.push(`key ${i} has use "${jwk.use}", expected "sig"`);
131
+ if (typeof jwk.exp === 'number' && jwk.exp < now) { problems.push(`key ${i} expired (exp ${new Date(jwk.exp * 1000).toISOString()})`); continue; }
132
+ if (typeof jwk.nbf === 'number' && jwk.nbf > now) { problems.push(`key ${i} is not valid yet (nbf ${new Date(jwk.nbf * 1000).toISOString()})`); continue; }
133
+ keys.push({ jwk, thumbprint, alg: algFromJwk(jwk) });
134
+ }
135
+ if (!keys.length) problems.push('no usable keys');
136
+
137
+ // Optional possession proof: the directory signs its own response.
138
+ let bound = false;
139
+ if (get('signature-input') && get('signature')) {
140
+ const res = { status, header: get };
141
+ const reqMsg = describeRequest({ method: 'GET', url, headers: {} });
142
+ let entries = [];
143
+ try { entries = parseSignatureHeaders(res); } catch (e) { problems.push(`directory signature headers are malformed: ${e.message}`); }
144
+ for (const e of entries.filter((x) => x.params.tag === 'http-message-signatures-directory')) {
145
+ const key = keys.find((k) => k.thumbprint === e.params.keyid);
146
+ if (!key) { problems.push(`directory signature ${e.label} uses a key not in the directory`); continue; }
147
+ if (!e.names.includes('content-digest') || !e.covered.some((c) => c === '"@authority";req')) { problems.push(`directory signature ${e.label} must cover "@authority";req and content-digest`); continue; }
148
+ if (typeof e.params.created !== 'number' || e.params.created > now + 60) { problems.push(`directory signature ${e.label} is dated in the future`); continue; }
149
+ if (typeof e.params.expires === 'number' && e.params.expires < now) { problems.push(`directory signature ${e.label} has expired`); continue; }
150
+ const digest = await checkContentDigest(get('content-digest') || '', body);
151
+ if (!digest.ok) { problems.push(`directory ${digest.reason}`); continue; }
152
+ try {
153
+ const base = responseSignatureBase(res, reqMsg, e.member);
154
+ if (await verifyBytes(e.params.alg || key.alg, key.jwk, base, e.signature)) bound = true;
155
+ else problems.push(`directory signature ${e.label} does not verify`);
156
+ } catch (err) { problems.push(`directory signature ${e.label}: ${err.message}`); }
157
+ }
158
+ }
159
+ const cc = get('cache-control') || '';
160
+ const ma = /max-age=(\d+)/.exec(cc);
161
+ return { keys, bound, problems, maxAge: ma ? Number(ma[1]) : null, wellKnown };
162
+ }
163
+
164
+ /** Caching key resolver: resolve(signatureAgentUrl, keyid) -> { key, url, bound } */
165
+ /** Node only: refuse hosts whose DNS answers include a private address (SSRF via DNS). */
166
+ export async function nodeDnsGuard(host) {
167
+ if (!globalThis.process?.versions?.node) return;
168
+ let lookup;
169
+ try { ({ lookup } = await import('node:dns/promises')); } catch { return; } // edge runtimes that mimic process
170
+
171
+ let addrs;
172
+ try { addrs = await lookup(host, { all: true }); } catch (e) { throw new SigError('directory', `cannot resolve ${host} (${e.code || e.message})`); }
173
+ if (addrs.some((a) => isPrivateHost(a.address))) throw new SigError('bad-agent', `${host} resolves to a private address`);
174
+ }
175
+
176
+ export function createDirectoryResolver({ fetchImpl, strict = false, allow = null, maxEntries = 1000, dnsGuard = null, timeoutMs = 5000, minTtl = 300, maxTtl = 86400, defaultTtl = 3600, negativeTtl = 60, now = () => Math.floor(Date.now() / 1000), log = () => {} } = {}) {
177
+ const cache = new Map(); // url -> { keys, bound, until, url }
178
+ const failures = new Map(); // url -> until
179
+ const inflight = new Map();
180
+
181
+ const allowed = (u) => !allow || allow.some((a) => (a.includes('/') ? u.href.startsWith(a) : u.hostname === a || u.hostname.endsWith(`.${a}`)));
182
+
183
+ async function load(sent) {
184
+ const url = checkUrl(sent);
185
+ if (!allowed(url)) throw new SigError('bad-agent', `${url.hostname} is not on this gate's list of signers to fetch keys from`);
186
+ if (dnsGuard) await dnsGuard(url.hostname);
187
+ const candidates = [];
188
+ if (url.pathname === '/' && !url.search) { const w = new URL(url); w.pathname = WELL_KNOWN; candidates.push(w.href); }
189
+ candidates.push(url.href);
190
+ let lastErr;
191
+ for (const [i, c] of candidates.entries()) {
192
+ const r = await boundedFetch(c, { fetchImpl, timeoutMs });
193
+ if (i === 0 && candidates.length > 1 && (r.status === 404 || r.status === 410)) { lastErr = new SigError('directory', `no directory at ${c}`); continue; }
194
+ const d = await checkDirectory({ url: c, ...r }, { now: now() });
195
+ for (const p of d.problems) log(`${c}: ${p}`);
196
+ if (strict && d.problems.length) throw new SigError('directory', `directory at ${c} does not follow the draft: ${d.problems.join('; ')}`);
197
+ const ttl = Math.min(maxTtl, Math.max(minTtl, d.maxAge ?? defaultTtl));
198
+ return { url: normalizeAgentUrl(c), sent, keys: d.keys, bound: d.bound, problems: d.problems, fetchedAt: now(), until: now() + ttl };
199
+ }
200
+ throw lastErr;
201
+ }
202
+
203
+ async function entry(sent, { refresh = false } = {}) {
204
+ const cached = cache.get(sent);
205
+ if (cached && cached.until > now() && !refresh) return cached;
206
+ const f = failures.get(sent);
207
+ if (f && f > now() && !cached) throw new SigError('directory', `directory for ${sent} failed recently; not retrying yet`);
208
+ if (inflight.has(sent)) return inflight.get(sent);
209
+ const p = load(sent).then((e) => {
210
+ // Bound memory: drop the oldest entry when the cache is full (attackers can send many URLs).
211
+ if (!cache.has(sent) && cache.size >= maxEntries) cache.delete(cache.keys().next().value);
212
+ cache.set(sent, e); failures.delete(sent); return e;
213
+ }, (err) => {
214
+ if (failures.size >= maxEntries) failures.delete(failures.keys().next().value);
215
+ failures.set(sent, now() + negativeTtl);
216
+ if (cached) { log(`${sent}: refresh failed (${err.message}); keeping cached keys`); return cached; }
217
+ throw err;
218
+ }).finally(() => inflight.delete(sent));
219
+ inflight.set(sent, p);
220
+ return p;
221
+ }
222
+
223
+ return {
224
+ cache,
225
+ async resolve(sent, keyid) {
226
+ let e = await entry(sent);
227
+ let key = e.keys.find((k) => k.thumbprint === keyid || k.jwk.kid === keyid);
228
+ // An unknown keyid may mean the agent rotated keys. Refetch, but at most once a minute per URL,
229
+ // so random keyids cannot make us hammer someone's directory.
230
+ if (!key && now() - e.fetchedAt >= 60) { e = await entry(sent, { refresh: true }); key = e.keys.find((k) => k.thumbprint === keyid || k.jwk.kid === keyid); }
231
+ if (!key) throw new SigError('unknown-key', `key ${keyid} is not published at ${e.url}`);
232
+ return { key, url: e.url, bound: e.bound, problems: e.problems };
233
+ },
234
+ };
235
+ }
236
+
237
+ export { SfvError };
package/src/gate.js ADDED
@@ -0,0 +1,112 @@
1
+ import { createVerifier, memoryNonceStore } from './verify.js';
2
+ import { classify } from './classify.js';
3
+ import { STORE_POLICY, decide, memoryLimiter, validatePolicy } from './policy.js';
4
+ import { headerGetter } from './util.js';
5
+
6
+ // What we ask unsigned automation to send (RFC 9421 Section 5.1, Accept-Signature).
7
+ export const ACCEPT_SIGNATURE = 'sig1=("@authority" "@method" "@path" "signature-agent";key="sig1");created;expires;keyid;tag="web-bot-auth"';
8
+
9
+ // Where the client address comes from. Only trust a header your own proxy or CDN sets.
10
+ const IP_HEADERS = {
11
+ 'cf-connecting-ip': (h) => h('cf-connecting-ip'),
12
+ 'x-vercel-forwarded-for': (h) => (h('x-vercel-forwarded-for') || '').split(',')[0].trim() || null,
13
+ 'x-real-ip': (h) => h('x-real-ip'),
14
+ 'fastly-client-ip': (h) => h('fastly-client-ip'),
15
+ 'x-forwarded-for': (h) => (h('x-forwarded-for') || '').split(',')[0].trim() || null,
16
+ };
17
+
18
+ /**
19
+ * createGate(opts)
20
+ * policy: STORE_POLICY (default) or your own
21
+ * profiles, staticKeys, tapKeys, fetchImpl, clockSkew: passed to the verifier
22
+ * ranges: official bot IP lists (loadBotRanges() in Node, botRangesFromJson() at the edge)
23
+ * ipFrom: 'cf-connecting-ip' | 'x-vercel-forwarded-for' | 'x-real-ip' | 'fastly-client-ip' | 'x-forwarded-for' | (request) => ip
24
+ * limiter, nonceStore: shared stores (memory by default; use Redis or KV with several servers)
25
+ * challenge: async (request, info) => Response | null (hand off to your CDN or CAPTCHA; default: a strict rate limit)
26
+ * onDecision: (info) => void (logging)
27
+ * mode: 'enforce' (default) | 'monitor' (decide and log, but let everything through)
28
+ */
29
+ export function createGate(opts = {}) {
30
+ const policy = opts.policy || STORE_POLICY;
31
+ const problems = validatePolicy(policy);
32
+ if (problems.length) throw new Error(`policy problems: ${problems.join('; ')}`);
33
+ const nonceStore = opts.nonceStore || memoryNonceStore();
34
+ const verifier = opts.verifier || createVerifier({ ...opts, nonceStore });
35
+ const limiter = opts.limiter || memoryLimiter();
36
+ const now = opts.now || (() => Math.floor(Date.now() / 1000));
37
+ const ipOf = typeof opts.ipFrom === 'function' ? opts.ipFrom : opts.ipFrom ? (r) => IP_HEADERS[opts.ipFrom](headerGetter(r.headers)) : () => null;
38
+ const mode = opts.mode || 'enforce';
39
+
40
+ async function check(request, { ip } = {}) {
41
+ const h = headerGetter(request.headers);
42
+ const url = new URL(request.url);
43
+ const addr = ip ?? ipOf(request);
44
+ const verification = await verifier.verify(request);
45
+ const c = classify({ ua: h('user-agent'), ip: addr, verification, ranges: opts.ranges });
46
+ let d = decide(policy, { path: url.pathname, query: url.search }, c);
47
+ if (d.action === 'challenge' && !opts.challenge) d = { ...d, action: 'limit', limit: { count: 10, window: 60 }, reason: `${d.reason} (no challenge handler: strict rate limit)` };
48
+ let limitState = null;
49
+ if (d.action === 'limit') {
50
+ limitState = await limiter.hit(`${c.class}|${c.id || addr || 'unknown'}`, d.limit, now());
51
+ if (!limitState.ok) d = { ...d, action: 'too-many', reason: `${d.reason}: over ${d.limit.count} per ${d.limit.window}s` };
52
+ }
53
+ const info = { ip: addr, path: url.pathname, class: c.class, id: c.id, name: c.name || null, operator: c.operator || null, intent: c.intent || null, evidence: c.evidence, action: d.action, area: d.area, reason: d.reason, signature: verification.status, mode };
54
+ if (opts.onDecision) try { opts.onDecision(info); } catch { /* logging must not break requests */ }
55
+ return { info, classification: c, verification, decision: d, limitState };
56
+ }
57
+
58
+ function responseFor(r) {
59
+ const { decision: d, info } = r;
60
+ const base = { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', 'x-agent-class': info.class };
61
+ if (d.action === 'block') return new Response('Automated access to this page is not allowed.\n', { status: 403, headers: base });
62
+ if (d.action === 'require-signature') return new Response('This page needs a signed request from a verifiable agent (Web Bot Auth).\n', { status: 403, headers: { ...base, 'accept-signature': ACCEPT_SIGNATURE } });
63
+ if (d.action === 'too-many') return new Response('Too many requests.\n', { status: 429, headers: { ...base, 'retry-after': String(r.limitState?.reset ?? 60), ...(info.class === 'automation' || info.class === 'claimed-bot' ? { 'accept-signature': ACCEPT_SIGNATURE } : {}) } });
64
+ return null;
65
+ }
66
+
67
+ return {
68
+ policy,
69
+ verifier,
70
+ check,
71
+ /** Fetch-style handler (Cloudflare Workers, Vercel/Next.js middleware, Hono, Bun, Deno). */
72
+ fetch(handler) {
73
+ return async (request, ...rest) => {
74
+ const r = await check(request);
75
+ if (mode === 'enforce') {
76
+ if (r.decision.action === 'challenge' && opts.challenge) { const res = await opts.challenge(request, r.info); if (res) return res; }
77
+ const block = responseFor(r);
78
+ if (block) return block;
79
+ }
80
+ const headers = new Headers(request.headers);
81
+ headers.set('x-agent-class', r.info.class);
82
+ if (r.info.id) headers.set('x-agent-id', r.info.id);
83
+ if (r.info.intent) headers.set('x-agent-intent', r.info.intent);
84
+ return handler(new Request(request, { headers }), ...rest);
85
+ };
86
+ },
87
+ /** Express / Connect / Node http middleware. Set trust proxy in Express, or pass ipFrom. */
88
+ express() {
89
+ return (req, res, next) => {
90
+ const proto = req.protocol || (req.socket?.encrypted ? 'https' : 'http');
91
+ const request = { method: req.method, url: `${proto}://${req.headers.host}${req.originalUrl || req.url}`, headers: req.headers };
92
+ const ip = opts.ipFrom ? undefined : (req.ip || req.socket?.remoteAddress || null);
93
+ check(request, { ip }).then(async (r) => {
94
+ req.agent = r.info;
95
+ if (mode === 'enforce') {
96
+ if (r.decision.action === 'challenge' && opts.challenge) { const out = await opts.challenge(request, r.info); if (out) return sendFetchResponse(res, out); }
97
+ const block = responseFor(r);
98
+ if (block) return sendFetchResponse(res, block);
99
+ }
100
+ next();
101
+ }, next);
102
+ };
103
+ },
104
+ responseFor,
105
+ };
106
+ }
107
+
108
+ async function sendFetchResponse(res, response) {
109
+ res.statusCode = response.status;
110
+ response.headers.forEach((v, k) => res.setHeader(k, v));
111
+ res.end(await response.text());
112
+ }
package/src/httpsig.js ADDED
@@ -0,0 +1,232 @@
1
+ // HTTP Message Signatures (RFC 9421): signature base, verification and signing.
2
+ import { parseDictionary, parseList, parseItem, serializeInnerList, serializeDictionary, serializeList, serializeItem, serializeBareItem, Token, ByteSeq, SfvError } from './sfv.js';
3
+ import { utf8, b64encode, b64url, b64urlDecode, subtle, sha256, headerGetter } from './util.js';
4
+
5
+ export class SigError extends Error { constructor(code, msg) { super(msg); this.code = code; } }
6
+
7
+ // Algorithms from the HTTP Signature Algorithms registry. Shared-secret HMAC is refused:
8
+ // Web Bot Auth forbids it ("Implementations MUST NOT use shared HMAC").
9
+ export const ALGORITHMS = {
10
+ ed25519: { import: { name: 'Ed25519' }, verify: { name: 'Ed25519' } },
11
+ 'rsa-pss-sha512': { import: { name: 'RSA-PSS', hash: 'SHA-512' }, verify: { name: 'RSA-PSS', saltLength: 64 } },
12
+ 'rsa-v1_5-sha256': { import: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, verify: { name: 'RSASSA-PKCS1-v1_5' } },
13
+ 'ecdsa-p256-sha256': { import: { name: 'ECDSA', namedCurve: 'P-256' }, verify: { name: 'ECDSA', hash: 'SHA-256' } },
14
+ 'ecdsa-p384-sha384': { import: { name: 'ECDSA', namedCurve: 'P-384' }, verify: { name: 'ECDSA', hash: 'SHA-384' } },
15
+ };
16
+
17
+ /** Which signature algorithm a JWK implies, when the signature does not say. */
18
+ export function algFromJwk(jwk) {
19
+ if (jwk.kty === 'OKP' && jwk.crv === 'Ed25519') return 'ed25519';
20
+ if (jwk.kty === 'EC' && jwk.crv === 'P-256') return 'ecdsa-p256-sha256';
21
+ if (jwk.kty === 'EC' && jwk.crv === 'P-384') return 'ecdsa-p384-sha384';
22
+ if (jwk.kty === 'RSA' && (jwk.alg === 'PS512')) return 'rsa-pss-sha512';
23
+ if (jwk.kty === 'RSA' && (jwk.alg === 'RS256')) return 'rsa-v1_5-sha256';
24
+ return null;
25
+ }
26
+
27
+ /** RFC 7638 / RFC 8037 JWK SHA-256 thumbprint, base64url. */
28
+ export async function jwkThumbprint(jwk) {
29
+ const req = { RSA: ['e', 'kty', 'n'], EC: ['crv', 'kty', 'x', 'y'], OKP: ['crv', 'kty', 'x'], oct: ['k', 'kty'] }[jwk.kty];
30
+ if (!req) throw new SigError('bad-key', `unsupported key type ${jwk.kty}`);
31
+ const obj = {};
32
+ for (const k of req) { if (typeof jwk[k] !== 'string') throw new SigError('bad-key', `JWK is missing ${k}`); obj[k] = jwk[k]; }
33
+ return b64url(await sha256(utf8(JSON.stringify(obj))));
34
+ }
35
+
36
+ const publicOnly = (jwk) => { const { d, p, q, dp, dq, qi, k, ...pub } = jwk; return pub; };
37
+
38
+ export async function importPublicKey(jwk, alg) {
39
+ const a = ALGORITHMS[alg];
40
+ if (!a) throw new SigError('bad-alg', `algorithm ${alg} is not supported`);
41
+ if (jwk.kty === 'oct') throw new SigError('bad-alg', 'shared-secret keys are not allowed');
42
+ const { alg: _a, use, key_ops, kid, nbf, exp, ...clean } = publicOnly(jwk);
43
+ return subtle().importKey('jwk', clean, a.import, false, ['verify']);
44
+ }
45
+
46
+ export async function importPrivateKey(jwk, alg) {
47
+ const a = ALGORITHMS[alg];
48
+ if (!a) throw new SigError('bad-alg', `algorithm ${alg} is not supported`);
49
+ const { alg: _a, use, key_ops, kid, ...clean } = jwk;
50
+ return subtle().importKey('jwk', clean, a.import, false, ['sign']);
51
+ }
52
+
53
+ /**
54
+ * A request in the shape the signature code needs.
55
+ * Accepts a Fetch Request, or { method, url, headers, body? } with headers as Headers, Map or object.
56
+ */
57
+ export function describeRequest(req) {
58
+ const url = new URL(req.url);
59
+ return { method: (req.method || 'GET').toUpperCase(), url, header: headerGetter(req.headers), body: req.body ?? null };
60
+ }
61
+
62
+ const DEFAULT_PORT = { 'http:': '80', 'https:': '443' };
63
+ function authority(url) { return url.port && url.port !== DEFAULT_PORT[url.protocol] ? `${url.hostname.toLowerCase()}:${url.port}` : url.hostname.toLowerCase(); }
64
+
65
+ // RFC 9421 Section 2.2.8: query parameter names and values are decoded, then re-encoded.
66
+ const QP_SAFE = /[A-Za-z0-9*\-._]/;
67
+ function qpEncode(s) { let o = ''; for (const b of utf8(s)) { const c = String.fromCharCode(b); o += QP_SAFE.test(c) ? c : `%${b.toString(16).toUpperCase().padStart(2, '0')}`; } return o; }
68
+ function qpDecode(s) { try { return decodeURIComponent(s.replace(/\+/g, ' ')); } catch { return s; } }
69
+
70
+ function derived(name, params, msg) {
71
+ const { url, method } = msg;
72
+ switch (name) {
73
+ case '@method': return method;
74
+ case '@target-uri': return url.href;
75
+ case '@authority': return authority(url);
76
+ case '@scheme': return url.protocol.slice(0, -1).toLowerCase();
77
+ case '@request-target': return `${url.pathname || '/'}${url.search}`;
78
+ case '@path': return url.pathname || '/';
79
+ case '@query': return url.search ? url.search : '?';
80
+ case '@query-param': {
81
+ const want = params.get('name');
82
+ if (typeof want !== 'string') throw new SigError('bad-component', '@query-param needs a name parameter');
83
+ const hits = url.search.slice(1).split('&').filter(Boolean).map((p) => p.split('=')).filter(([k]) => qpDecode(k) === want);
84
+ if (hits.length !== 1) throw new SigError('missing-component', `query parameter ${want} appears ${hits.length} times`);
85
+ return qpEncode(qpDecode(hits[0].slice(1).join('=')));
86
+ }
87
+ case '@status': throw new SigError('bad-component', '@status is only for responses');
88
+ default: throw new SigError('bad-component', `unknown derived component ${name}`);
89
+ }
90
+ }
91
+
92
+ function fieldValue(name, params, msg) {
93
+ const raw = msg.header(name);
94
+ if (raw == null) throw new SigError('missing-component', `the ${name} header is covered but missing`);
95
+ const value = String(raw).replace(/\r?\n[ \t]+/g, ' ').trim();
96
+ if (params.has('key')) {
97
+ const key = params.get('key');
98
+ let dict;
99
+ try { dict = parseDictionary(value); } catch (e) { throw new SigError('bad-component', `${name} is not a valid dictionary: ${e.message}`); }
100
+ if (!dict.has(key)) throw new SigError('missing-component', `${name} has no member ${key}`);
101
+ const m = dict.get(key);
102
+ return Array.isArray(m[0]) ? serializeInnerList(m) : serializeItem(m);
103
+ }
104
+ if (params.has('sf')) {
105
+ for (const parse of [parseDictionary, parseList, parseItem]) {
106
+ try { const v = parse(value); return parse === parseDictionary ? serializeDictionary(v) : parse === parseList ? serializeList(v) : serializeItem(v); } catch { /* try next type */ }
107
+ }
108
+ throw new SigError('bad-component', `${name} is not a structured field`);
109
+ }
110
+ if (params.has('bs')) return value.split(/,\s*/).map((v) => `:${b64encode(utf8(v.trim()))}:`).join(', ');
111
+ return value;
112
+ }
113
+
114
+ /** Build the RFC 9421 signature base for a request from a parsed Signature-Input member. */
115
+ export function signatureBase(msg, member) {
116
+ const [items, params] = member;
117
+ const lines = [];
118
+ const seen = new Set();
119
+ for (const [name, p] of items) {
120
+ if (typeof name !== 'string') throw new SigError('bad-input', 'component identifiers must be strings');
121
+ const id = serializeItem([name, p]);
122
+ if (seen.has(id)) throw new SigError('bad-input', `component ${id} is listed twice`);
123
+ seen.add(id);
124
+ if (p.has('req')) throw new SigError('bad-component', ';req is only for responses');
125
+ const value = name.startsWith('@') ? derived(name, p, msg) : fieldValue(name.toLowerCase(), p, msg);
126
+ if (/[\r\n]/.test(value)) throw new SigError('bad-component', 'component values cannot contain line breaks');
127
+ lines.push(`${id}: ${value}`);
128
+ }
129
+ lines.push(`"@signature-params": ${serializeInnerList([items, params])}`);
130
+ return lines.join('\n');
131
+ }
132
+
133
+ /** Signature base for a response, for checking a key directory's own signature. */
134
+ export function responseSignatureBase(res, reqMsg, member) {
135
+ const [items, params] = member;
136
+ const lines = [];
137
+ for (const [name, p] of items) {
138
+ const id = serializeItem([name, p]);
139
+ let value;
140
+ if (p.has('req')) {
141
+ const q = new Map(p); q.delete('req');
142
+ value = name.startsWith('@') ? derived(name, q, reqMsg) : fieldValue(name.toLowerCase(), q, reqMsg);
143
+ } else if (name === '@status') value = String(res.status);
144
+ else if (name.startsWith('@')) throw new SigError('bad-component', `${name} cannot be used on a response without ;req`);
145
+ else value = fieldValue(name.toLowerCase(), p, res);
146
+ lines.push(`${id}: ${value}`);
147
+ }
148
+ lines.push(`"@signature-params": ${serializeInnerList([items, params])}`);
149
+ return lines.join('\n');
150
+ }
151
+
152
+ // Importing a key costs more than verifying with it, so keep imported keys (bounded).
153
+ const keyCache = new Map();
154
+ async function cachedPublicKey(jwk, alg) {
155
+ const id = `${alg}|${jwk.kty}|${jwk.crv || ''}|${jwk.x || ''}|${jwk.y || ''}|${jwk.n || ''}|${jwk.e || ''}`;
156
+ let k = keyCache.get(id);
157
+ if (!k) { k = await importPublicKey(jwk, alg); if (keyCache.size > 500) keyCache.clear(); keyCache.set(id, k); }
158
+ return k;
159
+ }
160
+
161
+ export async function verifyBytes(alg, jwk, base, sigBytes) {
162
+ const key = await cachedPublicKey(jwk, alg);
163
+ return subtle().verify(ALGORITHMS[alg].verify, key, sigBytes, utf8(base));
164
+ }
165
+
166
+ /** Parse Signature-Input and Signature into labelled entries. Throws SigError('malformed') on bad syntax. */
167
+ export function parseSignatureHeaders(msg) {
168
+ const si = msg.header('signature-input');
169
+ const sg = msg.header('signature');
170
+ if (!si && !sg) return null;
171
+ if (!si || !sg) throw new SigError('malformed', `${si ? 'Signature' : 'Signature-Input'} header is missing`);
172
+ let inputs; let sigs;
173
+ try { inputs = parseDictionary(si); sigs = parseDictionary(sg); } catch (e) { throw new SigError('malformed', `could not parse signature headers: ${e.message}`); }
174
+ const out = [];
175
+ for (const [label, member] of inputs) {
176
+ if (!Array.isArray(member[0])) throw new SigError('malformed', `Signature-Input ${label} is not an inner list`);
177
+ const sig = sigs.get(label);
178
+ const params = Object.fromEntries([...member[1]].map(([k, v]) => [k, v instanceof Token ? v.value : v]));
179
+ out.push({ label, member, params, covered: member[0].map(([n, p]) => serializeItem([n, p])), names: member[0].map(([n]) => n), signature: sig && sig[0] instanceof ByteSeq ? sig[0].bytes : null });
180
+ }
181
+ return out;
182
+ }
183
+
184
+ /** Check a Content-Digest header against the body (sha-256 or sha-512). */
185
+ export async function checkContentDigest(header, body) {
186
+ let dict;
187
+ try { dict = parseDictionary(header); } catch { return { ok: false, reason: 'Content-Digest is not a valid dictionary' }; }
188
+ const bytes = typeof body === 'string' ? utf8(body) : body instanceof Uint8Array ? body : new Uint8Array(body);
189
+ for (const [alg, [v]] of dict) {
190
+ if (!(v instanceof ByteSeq)) continue;
191
+ const name = { 'sha-256': 'SHA-256', 'sha-512': 'SHA-512' }[alg];
192
+ if (!name) continue;
193
+ const got = new Uint8Array(await subtle().digest(name, bytes));
194
+ const ok = got.length === v.bytes.length && got.every((b, i) => b === v.bytes[i]);
195
+ return { ok, reason: ok ? null : `Content-Digest ${alg} does not match the body` };
196
+ }
197
+ return { ok: false, reason: 'Content-Digest has no sha-256 or sha-512 value' };
198
+ }
199
+
200
+ /**
201
+ * Sign a request (for agent builders and for testing a gate).
202
+ * opts: { jwk (private), alg?, keyid?, label='sig1', signatureAgent (URL), created, expires, nonce, tag='web-bot-auth', components }
203
+ * Returns headers to add: Signature, Signature-Input, Signature-Agent.
204
+ */
205
+ export async function signRequest(req, opts) {
206
+ const msg = describeRequest(req);
207
+ const alg = opts.alg || algFromJwk(opts.jwk);
208
+ if (!alg) throw new SigError('bad-alg', 'cannot tell the algorithm from this key; pass alg');
209
+ const label = opts.label || 'sig1';
210
+ const created = opts.created ?? Math.floor(Date.now() / 1000);
211
+ const expires = opts.expires ?? created + 300;
212
+ const extra = {};
213
+ if (opts.signatureAgent) extra['signature-agent'] = `${label}=${serializeBareItem(opts.signatureAgent)}`;
214
+ const components = (opts.components || ['@authority', ...(opts.signatureAgent ? [['signature-agent', { key: label }]] : [])]).map((c) => (Array.isArray(c) ? [c[0], new Map(Object.entries(c[1]).map(([k, v]) => [k, v]))] : [c, new Map()]));
215
+ const params = new Map([['created', created], ['expires', expires], ['keyid', opts.keyid || await jwkThumbprint(publicOnly(opts.jwk))], ['alg', alg]]);
216
+ if (opts.nonce) params.set('nonce', opts.nonce);
217
+ params.set('tag', opts.tag || 'web-bot-auth');
218
+ const member = [components, params];
219
+ const merged = { ...Object.fromEntries([...headerEntries(req.headers)]), ...extra };
220
+ const base = signatureBase({ ...msg, header: headerGetter(merged) }, member);
221
+ const key = await importPrivateKey(opts.jwk, alg);
222
+ const sig = new Uint8Array(await subtle().sign(ALGORITHMS[alg].verify, key, utf8(base)));
223
+ return { ...extra, 'signature-input': `${label}=${serializeInnerList(member)}`, signature: `${label}=:${b64encode(sig)}:`, base };
224
+ }
225
+
226
+ function* headerEntries(h) {
227
+ if (!h) return;
228
+ if (typeof h.entries === 'function') yield* h.entries();
229
+ else yield* Object.entries(h);
230
+ }
231
+
232
+ export { SfvError, b64urlDecode };