From 07f945591a7dc10389f23fec51b899db5d3833e0 Mon Sep 17 00:00:00 2001 From: Chris Portscheller Date: Fri, 24 Jul 2026 11:29:14 -0500 Subject: [PATCH] feat(agent): local Web Bot Auth verification in detectBot() (WebDecoy/app#323) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Verify inbound AI-agent signatures (RFC 9421 HTTP Message Signatures, tag "web-bot-auth") locally in middleware — on Node and every WinterCG edge runtime — with no API key and zero network on the warm path. - New agent/ module: a zero-dep RFC 8941 SFV parser, RFC 9421 signature-base construction, JWK-thumbprint keyids (RFC 7638/8037), and a cached, curated directory client (Ed25519 + RSA-PSS-SHA512 via WebCrypto). Curated-only, so a request's Signature-Agent header never selects a fetch target (no SSRF); stale-while-revalidate keeps the warm path off the network. - WebDecoy.detectBot(request) — returns a verdict (verified / impersonation / claimed / none) with agent name+category for verified agents. Accepts a WHATWG Request or { method, url, headers }. - webBotAuth() rule — denies impersonation of known agents by default; the verdict is precomputed async into RuleContext.agent (same pattern as filter rules + IP enrichment) so the sync rule can act on it. Surfaced on ProtectResult.agent. - Verdict taxonomy matches the ingest verifier (WebDecoy/app#320) and the edge validator; curated directory list tracks backend signed_agents.go. Tests: signed→verified, tamper/expiry→impersonation, unknown-key/host-unbound →claimed, none; warm-path p95 < 5ms; RFC 7638 thumbprint KAT; and full verification running inside a real Vercel Edge Runtime VM. --- CHANGELOG.md | 8 + README.md | 32 ++ docs/verify-ai-agents-web-bot-auth.md | 171 +++++++++++ packages/webdecoy/src/agent/directory.ts | 240 +++++++++++++++ packages/webdecoy/src/agent/index.ts | 19 ++ packages/webdecoy/src/agent/sfv.ts | 205 +++++++++++++ packages/webdecoy/src/agent/signature.ts | 274 ++++++++++++++++++ packages/webdecoy/src/agent/thumbprint.ts | 63 ++++ packages/webdecoy/src/agent/types.ts | 126 ++++++++ packages/webdecoy/src/agent/verifier.ts | 112 +++++++ .../webdecoy/src/agent/web-bot-auth.test.ts | 253 ++++++++++++++++ packages/webdecoy/src/edge-runtime.test.ts | 56 ++++ packages/webdecoy/src/index.ts | 20 ++ packages/webdecoy/src/rules/index.ts | 2 + packages/webdecoy/src/rules/types.ts | 8 + .../src/rules/web-bot-auth-rule.test.ts | 61 ++++ .../webdecoy/src/rules/web-bot-auth-rule.ts | 132 +++++++++ packages/webdecoy/src/sdk.ts | 178 ++++++++++-- packages/webdecoy/src/types.ts | 15 + 19 files changed, 1945 insertions(+), 30 deletions(-) create mode 100644 docs/verify-ai-agents-web-bot-auth.md create mode 100644 packages/webdecoy/src/agent/directory.ts create mode 100644 packages/webdecoy/src/agent/index.ts create mode 100644 packages/webdecoy/src/agent/sfv.ts create mode 100644 packages/webdecoy/src/agent/signature.ts create mode 100644 packages/webdecoy/src/agent/thumbprint.ts create mode 100644 packages/webdecoy/src/agent/types.ts create mode 100644 packages/webdecoy/src/agent/verifier.ts create mode 100644 packages/webdecoy/src/agent/web-bot-auth.test.ts create mode 100644 packages/webdecoy/src/rules/web-bot-auth-rule.test.ts create mode 100644 packages/webdecoy/src/rules/web-bot-auth-rule.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index da17717..eb47de9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- **Local Web Bot Auth verification** (RFC 9421 HTTP Message Signatures, tag `web-bot-auth`). + - `detectBot(request)` — verify an inbound request's agent signature and get a `verified` / `impersonation` / `claimed` / `none` verdict (with agent name/category for verified agents). Accepts a WHATWG `Request` or `{ method, url, headers }`. + - `webBotAuth()` rule — denies impersonation of known agents in the rules engine by default; `onImpersonation` / `onClaimed` / `allowCategories` options. + - Cached, curated directory client (Ed25519 + RSA-PSS-SHA512, JWK-thumbprint keyids); zero network on the warm path, no SSRF surface. Runs on Node and Vercel Edge / WinterCG runtimes. + - New exports: `AgentVerifier`, `createAgentVerifier`, `DirectoryCache`, `DEFAULT_SIGNED_AGENT_DIRECTORIES`, and types `AgentVerdict`, `AgentStatus`, `AgentCategory`, `WebBotAuthConfig`, `AgentVerifierOptions`, `SignedAgentDirectory`. +- Doc: "Verify AI agents with Web Bot Auth in Next.js" (`docs/verify-ai-agents-web-bot-auth.md`). + ## [0.4.0] - 2026-06-30 ### Added diff --git a/README.md b/README.md index f10ce06..44ea3cb 100644 --- a/README.md +++ b/README.md @@ -110,8 +110,36 @@ const wd = new WebDecoy({ - **`rateLimit({ max, window, algorithm?, action?, keyBy? })`** — fixed or sliding window, keyed by IP (or a custom function). No key. - **`tripwire({ paths?, prefixes?, patterns?, includeDefaults? })`** — deterministic honeypot-path detection. No key. +- **`webBotAuth({ onImpersonation?, onClaimed?, allowCategories? })`** — verify AI-agent signatures (Web Bot Auth / RFC 9421) locally; deny impersonators of known agents. No key. - **`filter({ expression, action? })`** — an expression language over IP reputation/geo (e.g. `ip.tor`, `ip.country in ["CN", "RU"]`). Requires an API key for enrichment. +## Verify AI agents (Web Bot Auth) + +AI agents like OpenAI's Operator now **cryptographically sign** their requests +([Web Bot Auth](https://datatracker.ietf.org/wg/webbotauth/about/), RFC 9421). +WebDecoy verifies those signatures **locally** — on Node and on the edge, with no +API key and no network on the warm path — so you can tell a real verified agent +from someone forging its identity. + +```typescript +import { WebDecoy } from '@webdecoy/node'; + +const wd = new WebDecoy(); + +const verdict = await wd.detectBot(request); // a WHATWG Request, or { method, url, headers } +// verdict.status: 'verified' | 'impersonation' | 'claimed' | 'none' +if (verdict.status === 'impersonation') return new Response('Forbidden', { status: 403 }); +if (verdict.status === 'verified') console.log('verified agent:', verdict.agentName, verdict.category); +``` + +Or drop it into the rules engine to deny impersonation automatically: + +```typescript +const wd = new WebDecoy({ rules: [webBotAuth()] }); // denies known-agent impersonation +``` + +Full guide: [**Verify AI agents with Web Bot Auth in Next.js**](docs/verify-ai-agents-web-bot-auth.md). + ## What counts as a false positive? The zero-false-positive claim is about *design*, and it holds if you know the edge cases: @@ -200,6 +228,10 @@ Deterministic honeypot-path detection. `tripwire()` returns a `Rule` for the `ru Additional local rules for the `rules` array. `filter()` requires an API key for IP enrichment. +### `webBotAuth(config?)` / `detectBot(request)` + +Local Web Bot Auth verification (RFC 9421). `webBotAuth()` returns a `Rule` that denies agent impersonation; `detectBot(request)` returns the verdict directly for custom handling. See the [Web Bot Auth guide](docs/verify-ai-agents-web-bot-auth.md). Exported types: `AgentVerdict`, `AgentStatus`, `AgentCategory`, `WebBotAuthConfig`, `AgentVerifierOptions`, `SignedAgentDirectory`. + ### `protect(metadata, options?): Promise` Full analysis of a request (platform feature). Returns a decision: diff --git a/docs/verify-ai-agents-web-bot-auth.md b/docs/verify-ai-agents-web-bot-auth.md new file mode 100644 index 0000000..8237cb9 --- /dev/null +++ b/docs/verify-ai-agents-web-bot-auth.md @@ -0,0 +1,171 @@ +# Verify AI agents with Web Bot Auth in Next.js + +AI agents that browse the web on a user's behalf — OpenAI's Operator, ChatGPT's +browsing tool, and a growing cohort behind the IETF +[`webbotauth`](https://datatracker.ietf.org/wg/webbotauth/about/) working group — +now **cryptographically sign** their requests using +[Web Bot Auth](https://datatracker.ietf.org/doc/draft-meunier-web-bot-auth-architecture/) +(RFC 9421 HTTP Message Signatures, tag `web-bot-auth`). A signed request proves +"this really is that agent," and an *unverifiable* signature that claims a known +agent's identity is a forgery you can block. + +`@webdecoy/node` verifies these signatures **locally, in your middleware** — on +Node and on every WinterCG edge runtime (Vercel Edge, Cloudflare Workers). No +API key, and **no network on the warm path**: trusted agent directories are +fetched once and cached, so a verification is a header parse, a map lookup, and +one WebCrypto check (well under 5 ms). + +> This is the same verification WebDecoy runs at ingest and at the edge — the +> SDK, the edge validator, and the backend all share the +> [`github.com/WebDecoy/web-bot-auth`](https://github.com/WebDecoy/web-bot-auth) +> profile and speak the same verdict taxonomy. + +## The verdict + +Every request resolves to one of four statuses: + +| `status` | Meaning | Typical action | +|---|---|---| +| `verified` | Signature validated against a trusted agent's published key. `agentName` and `category` are populated. | Allow (optionally with elevated trust) | +| `impersonation` | A signature claimed a **known** agent's key but failed verification (bad signature, or outside its validity window). A forgery. | **Deny** | +| `claimed` | A signature is present but unverifiable — an unknown/uncurated signer, or malformed. Not proof of an agent, nor of a forgery. | Let your other rules decide | +| `none` | No Web Bot Auth signature. Ordinary traffic. | Continue | + +## Option A — `detectBot()` in Next.js middleware + +`detectBot()` is the low-level primitive. It takes a WHATWG `Request` (what +Next.js middleware and Edge routes already hand you) and returns the verdict, so +you decide what to do: + +```typescript +// middleware.ts +import { NextRequest, NextResponse } from 'next/server'; +import { WebDecoy } from '@webdecoy/node'; + +const wd = new WebDecoy(); // no API key needed for local verification + +export async function middleware(req: NextRequest) { + const verdict = await wd.detectBot(req); + + switch (verdict.status) { + case 'impersonation': + // Someone is forging a known agent's identity — block it. + return new NextResponse('Forbidden', { status: 403 }); + + case 'verified': + // A real, cryptographically verified agent. Let it through and tag it + // for your route handlers. + const res = NextResponse.next(); + res.headers.set('x-verified-agent', verdict.agentName ?? ''); + res.headers.set('x-verified-agent-category', verdict.category ?? ''); + return res; + + default: + return NextResponse.next(); + } +} + +export const config = { matcher: ['/((?!_next/static|favicon.ico).*)'] }; +``` + +`detectBot()` also accepts a plain `{ method, url, headers }` object for +non-`Request` environments (Node HTTP, Express): + +```typescript +const verdict = await wd.detectBot({ + method: req.method, + url: `https://${req.headers.host}${req.url}`, + headers: req.headers as Record, +}); +``` + +## Option B — the `webBotAuth()` rule + +If you already use WebDecoy's rules engine, add `webBotAuth()` to your `rules` +array. It runs alongside your rate limits and tripwires and, by default, **denies +impersonation** — no branching code required. Verification happens automatically +before the rule evaluates. + +```typescript +// middleware.ts +import { withWebDecoy } from '@webdecoy/nextjs'; +import { webBotAuth, rateLimit } from '@webdecoy/node'; + +export default withWebDecoy({ + rules: [ + webBotAuth(), // deny agent impersonation + rateLimit({ max: 100, window: 60 }), + ], +}); + +export const config = { matcher: ['/api/:path*'] }; +``` + +An impersonation attempt is denied with a `403` before it reaches your app. The +verdict is also surfaced on `ProtectResult.agent` for `withBotProtection`/manual +`protect()` callers. + +### Rule options + +```typescript +webBotAuth({ + onImpersonation: 'DENY', // default; forged known-agent signature + onClaimed: 'ALLOW', // default; unverifiable/unknown signer + allowCategories: ['ai_crawlers'], // optional: only these verified categories pass + dryRun: false, // record the verdict but never block +}); +``` + +- Set `onClaimed: 'DENY'` to require that **every** signed request come from an + agent you trust (an unknown signer is then treated as a violation). +- `allowCategories` lets you accept, say, verified search engines but not + AI crawlers — a verified agent outside the list is handled per `onClaimed`. + +## Trusted directories (and why there's no SSRF) + +Verification is **curated**: the SDK only ever fetches the well-known directories +of agents on an allowlist — never a URL taken from the incoming request's +`Signature-Agent` header. That means a hostile request can't make your +middleware fetch an arbitrary origin (no SSRF), and the warm path stays on +in-memory keys. + +The default list tracks the agents that sign production traffic today (OpenAI +Operator, ChatGPT). Override it — for example to add your own signed crawlers — +via the constructor: + +```typescript +const wd = new WebDecoy({ + webBotAuth: { + directories: [ + { name: 'OpenAI', category: 'ai_crawlers', directory: 'https://operator.openai.com' }, + { name: 'Acme Crawler', category: 'monitoring', directory: 'https://crawler.acme.example' }, + ], + cacheTtlMs: 6 * 60 * 60 * 1000, // stale-while-revalidate; default 6h + }, +}); +``` + +A directory publishes its keys at +`/.well-known/http-message-signatures-directory` as a JWK Set (Ed25519 / OKP and +RSA supported). Keys are matched by their RFC 7638/8037 JWK thumbprint — the +value agents put in the signature's `keyid` — never by a mutable `kid` label. + +## Runtime support + +- **Vercel Edge Middleware / Cloudflare Workers** — verified against a real + Vercel Edge Runtime VM in the SDK's test suite. Uses only `crypto.subtle`, + `fetch`, `Request`/`Headers`, `URL`, and `atob` — no Node built-ins. +- **Node ≥ 18** — global `fetch` and WebCrypto Ed25519. + +## How it relates to the platform + +Local verification is free and needs no key. With a WebDecoy API key, verified +and impersonation verdicts also flow into your dashboard alongside TLS +fingerprinting, IP reputation, and detection analytics — so you can see *which* +agents visit and *who* tried to impersonate them over time. + +## See also + +- [`github.com/WebDecoy/web-bot-auth`](https://github.com/WebDecoy/web-bot-auth) — the underlying Go/TS profile +- [RFC 9421 — HTTP Message Signatures](https://www.rfc-editor.org/rfc/rfc9421) +- [IETF `webbotauth` working group](https://datatracker.ietf.org/wg/webbotauth/about/) diff --git a/packages/webdecoy/src/agent/directory.ts b/packages/webdecoy/src/agent/directory.ts new file mode 100644 index 0000000..8457b46 --- /dev/null +++ b/packages/webdecoy/src/agent/directory.ts @@ -0,0 +1,240 @@ +/** + * Cached Web Bot Auth directory client. + * + * Fetches the JWK sets of a **curated** set of trusted agent directories, + * imports their keys into WebCrypto, and indexes them by JWK-thumbprint keyid + * so signatures resolve in O(1) with zero network on the warm path. + * + * Security posture — the reason this is curated-only: + * a request's own `Signature-Agent` header is **never** used to choose a fetch + * target, so an attacker cannot make the middleware fetch an arbitrary URL + * (no SSRF). Only the origins in {@link AgentVerifierOptions.directories} are + * ever contacted. This mirrors the backend curation + * (`backend/internal/services/signed_agents.go`). + * + * Freshness — stale-while-revalidate: once populated, an expired cache keeps + * serving its keys while a background refresh runs, so verification latency is + * never coupled to a directory fetch. A cold cache (never populated) blocks + * once to fetch, then backs off briefly if every directory is unreachable so a + * degraded network can't be hammered per request. + */ + +import { jwkThumbprint, type JWK } from './thumbprint'; +import type { VerificationKey, KeyResolver } from './signature'; +import type { SignedAgentDirectory } from './types'; + +const WELL_KNOWN = '/.well-known/http-message-signatures-directory'; +const COLD_RETRY_BACKOFF_MS = 30_000; + +/** + * The default curated allowlist. These are the agents that sign production + * traffic today; kept in lock-step with the backend's curated list. + */ +export const DEFAULT_SIGNED_AGENT_DIRECTORIES: SignedAgentDirectory[] = [ + { name: 'OpenAI', category: 'ai_crawlers', directory: 'https://operator.openai.com' }, + { name: 'OpenAI ChatGPT', category: 'ai_crawlers', directory: 'https://chatgpt.com' }, +]; + +interface DirectoryCacheOptions { + directories: SignedAgentDirectory[]; + cacheTtlMs: number; + fetchTimeoutMs: number; + debug: boolean; + fetchImpl: typeof fetch; +} + +export class DirectoryCache { + private readonly opts: DirectoryCacheOptions; + private keys = new Map(); + private refreshedAt = 0; + private nextColdRetryAt = 0; + private inflight: Promise | null = null; + + constructor(opts: DirectoryCacheOptions) { + this.opts = opts; + } + + /** Resolve a keyid to a verification key, fetching/refreshing as needed. */ + resolveKey: KeyResolver = async (keyId: string) => { + await this.ensureFresh(); + return this.keys.get(keyId); + }; + + /** Kick off a fetch without blocking — call at startup to warm the cache. */ + prime(): void { + if (this.keys.size === 0 && Date.now() >= this.nextColdRetryAt) void this.refresh(); + } + + /** Number of keys currently cached (diagnostics/tests). */ + get size(): number { + return this.keys.size; + } + + private async ensureFresh(): Promise { + const now = Date.now(); + const stale = now - this.refreshedAt > this.opts.cacheTtlMs; + if (this.keys.size > 0) { + if (stale) void this.refresh(); // serve stale, revalidate in the background + return; + } + // Cold: block once to populate, unless we're backing off a recent failure. + if (now < this.nextColdRetryAt) return; + await this.refresh(); + } + + /** Re-fetch every directory. De-duplicated: concurrent callers share one run. */ + refresh(): Promise { + if (this.inflight) return this.inflight; + this.inflight = this.doRefresh().finally(() => { + this.inflight = null; + }); + return this.inflight; + } + + private async doRefresh(): Promise { + const results = await Promise.all( + this.opts.directories.map((src) => this.fetchDirectory(src)), + ); + + // Start from last-known-good so one flaky directory can't drop live keys. + const next = new Map(this.keys); + let fetchedAny = false; + for (const keys of results) { + if (keys === null) continue; + fetchedAny = true; + for (const k of keys) next.set(k.thumbprint, k.key); + } + + if (fetchedAny) { + this.keys = next; + this.refreshedAt = Date.now(); + this.nextColdRetryAt = 0; + this.debug(`refreshed: ${this.keys.size} key(s) across ${this.opts.directories.length} directories`); + } else if (this.keys.size === 0) { + // Every directory failed and we still have nothing — back off briefly. + this.nextColdRetryAt = Date.now() + COLD_RETRY_BACKOFF_MS; + this.debug('all directories unreachable; backing off cold retry'); + } + } + + private async fetchDirectory( + src: SignedAgentDirectory, + ): Promise<{ thumbprint: string; key: VerificationKey }[] | null> { + const url = directoryUrl(src.directory); + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), this.opts.fetchTimeoutMs); + try { + const res = await this.opts.fetchImpl(url, { + signal: controller.signal, + headers: { + Accept: + 'application/http-message-signatures-directory+json, application/jwk-set+json, application/json', + }, + redirect: 'follow', + }); + if (!res.ok) { + this.debug(`${src.name}: HTTP ${res.status}`); + return null; + } + const body = (await res.json()) as { keys?: JWK[] }; + if (!body || !Array.isArray(body.keys)) { + this.debug(`${src.name}: no keys in directory`); + return null; + } + const out: { thumbprint: string; key: VerificationKey }[] = []; + for (const jwk of body.keys) { + const resolved = await importKey(jwk, src); + if (resolved) out.push(resolved); + } + this.debug(`${src.name}: ${out.length} key(s)`); + return out; + } catch (err) { + this.debug(`${src.name}: fetch failed — ${(err as Error).message}`); + return null; + } finally { + clearTimeout(timer); + } + } + + private debug(msg: string): void { + if (this.opts.debug) console.log(`[WebDecoy][web-bot-auth] ${msg}`); + } +} + +/** Append the well-known path unless the directory string already carries one. */ +function directoryUrl(directory: string): string { + const u = new URL(directory); + if (u.pathname && u.pathname !== '/') return u.toString(); + u.pathname = WELL_KNOWN; + return u.toString(); +} + +/** + * Import a directory JWK into a verification key. Unsupported or malformed + * keys are skipped (a directory may legitimately publish key types outside + * this profile). + */ +async function importKey( + jwk: JWK, + src: SignedAgentDirectory, +): Promise<{ thumbprint: string; key: VerificationKey } | null> { + try { + let cryptoKey: CryptoKey; + let verifyParams: AlgorithmIdentifier | RsaPssParams; + let algorithm: string; + + if (jwk.kty === 'OKP') { + if (jwk.crv !== 'Ed25519' || !jwk.x) return null; + cryptoKey = await crypto.subtle.importKey( + 'jwk', + { kty: 'OKP', crv: 'Ed25519', x: jwk.x }, + { name: 'Ed25519' }, + false, + ['verify'], + ); + verifyParams = { name: 'Ed25519' }; + algorithm = 'ed25519'; + } else if (jwk.kty === 'RSA') { + if (!jwk.n || !jwk.e) return null; + cryptoKey = await crypto.subtle.importKey( + 'jwk', + { kty: 'RSA', n: jwk.n, e: jwk.e }, + { name: 'RSA-PSS', hash: 'SHA-512' }, + false, + ['verify'], + ); + // RFC 9421 rsa-pss-sha512: salt length equals the hash length (64 bytes). + verifyParams = { name: 'RSA-PSS', saltLength: 64 }; + algorithm = 'rsa-pss-sha512'; + } else { + return null; + } + + const thumbprint = await jwkThumbprint(jwk); + return { + thumbprint, + key: { + cryptoKey, + verifyParams, + algorithm, + name: src.name, + category: src.category, + nbf: normalizeEpoch(jwk.nbf), + exp: normalizeEpoch(jwk.exp), + }, + }; + } catch { + return null; + } +} + +/** + * Tolerate directory timestamps published in milliseconds — RFC 7517 + * NumericDate is seconds, but live deployments (including Cloudflare Research's + * example directory) publish `nbf` in milliseconds. Ported from the Go lib's + * `normalizeEpoch`. + */ +function normalizeEpoch(v: number | undefined): number | undefined { + if (v === undefined || v === 0) return undefined; + return v > 1_000_000_000_000 ? Math.floor(v / 1000) : v; +} diff --git a/packages/webdecoy/src/agent/index.ts b/packages/webdecoy/src/agent/index.ts new file mode 100644 index 0000000..e38a91a --- /dev/null +++ b/packages/webdecoy/src/agent/index.ts @@ -0,0 +1,19 @@ +/** + * Local Web Bot Auth verification for the WebDecoy SDK. + * + * Verify whether an inbound request carries a cryptographically valid AI-agent + * signature (RFC 9421, tag "web-bot-auth"), in-process, on Node and every + * WinterCG edge runtime — no network on the warm path. + */ + +export { AgentVerifier, createAgentVerifier } from './verifier'; +export { DirectoryCache, DEFAULT_SIGNED_AGENT_DIRECTORIES } from './directory'; + +export type { + AgentStatus, + AgentCategory, + AgentVerdict, + AgentRequestInput, + AgentVerifierOptions, + SignedAgentDirectory, +} from './types'; diff --git a/packages/webdecoy/src/agent/sfv.ts b/packages/webdecoy/src/agent/sfv.ts new file mode 100644 index 0000000..ce1c760 --- /dev/null +++ b/packages/webdecoy/src/agent/sfv.ts @@ -0,0 +1,205 @@ +/** + * RFC 8941 Structured Field Values — the subset Web Bot Auth headers use. + * + * `Signature-Input` is a dictionary of inner lists (the covered component + * identifiers) with parameters (keyid, created, expires, tag, alg…). + * `Signature` is a dictionary of byte-sequence values (the raw signatures). + * `Signature-Agent` is a dictionary whose members are strings. + * + * The parser preserves the **verbatim** text of each dictionary member's value + * (`DictEntry.raw`), which RFC 9421 requires to reconstruct the + * `@signature-params` line of the signature base byte-for-byte. + * + * Zero dependencies, Edge-runtime safe: only `atob` is used (for byte + * sequences). + */ + +export type BareItem = string | number | boolean; + +export interface Item { + value: BareItem; + params: Map; + /** Set only for byte-sequence items (`:base64:`). */ + bytes?: Uint8Array; +} + +export interface DictEntry { + key: string; + /** Verbatim value text after `key=` (before this member's own params for lists). */ + raw: string; + /** True when the value is an inner list `( … )`. */ + isList: boolean; + items: Item[]; + /** Parameters attached to the member (the inner list, or the single item). */ + params: Map; +} + +class Cursor { + constructor( + public s: string, + public i = 0, + ) {} + eof(): boolean { + return this.i >= this.s.length; + } + peek(): string { + return this.s[this.i]; + } + skipSP(): void { + while (!this.eof() && (this.peek() === ' ' || this.peek() === '\t')) this.i++; + } +} + +/** Parse an RFC 8941 dictionary header value. Throws on malformed input. */ +export function parseDictionary(input: string): DictEntry[] { + const p = new Cursor(input); + const out: DictEntry[] = []; + p.skipSP(); + while (!p.eof()) { + const key = parseKey(p); + const entry: DictEntry = { key, raw: '', isList: false, items: [], params: new Map() }; + if (!p.eof() && p.peek() === '=') { + p.i++; + const start = p.i; + if (!p.eof() && p.peek() === '(') { + entry.isList = true; + parseInnerList(p, entry); + } else { + entry.items.push(parseItem(p)); + entry.params = entry.items[0].params; + } + entry.raw = input.slice(start, p.i); + } else { + // A valueless member is boolean-true, with optional parameters. + entry.params = parseParams(p); + entry.items.push({ value: true, params: new Map() }); + entry.raw = '?1'; + } + out.push(entry); + p.skipSP(); + if (p.eof()) break; + if (p.peek() !== ',') throw new Error(`sfv: expected ',' at ${p.i}`); + p.i++; + p.skipSP(); + if (p.eof()) throw new Error('sfv: trailing comma'); + } + return out; +} + +function parseInnerList(p: Cursor, entry: DictEntry): void { + p.i++; // consume '(' + for (;;) { + p.skipSP(); + if (p.eof()) throw new Error('sfv: unterminated inner list'); + if (p.peek() === ')') { + p.i++; + break; + } + entry.items.push(parseItem(p)); + if (p.eof()) throw new Error('sfv: unterminated inner list'); + const c = p.peek(); + if (c !== ' ' && c !== ')') throw new Error(`sfv: bad inner list at ${p.i}`); + } + entry.params = parseParams(p); +} + +function parseItem(p: Cursor): Item { + const { value, bytes } = parseBareItem(p); + const params = parseParams(p); + return bytes ? { value, params, bytes } : { value, params }; +} + +function parseParams(p: Cursor): Map { + const params = new Map(); + while (!p.eof() && p.peek() === ';') { + p.i++; + p.skipSP(); + const key = parseKey(p); + let val: BareItem = true; + if (!p.eof() && p.peek() === '=') { + p.i++; + val = parseBareItem(p).value; + } + params.set(key, val); + } + return params; +} + +function parseKey(p: Cursor): string { + const c = p.peek(); + if (!c || !/[a-z*]/.test(c)) throw new Error(`sfv: invalid key at ${p.i}`); + const start = p.i; + while (!p.eof() && /[a-z0-9_\-.*]/.test(p.peek())) p.i++; + return p.s.slice(start, p.i); +} + +function parseBareItem(p: Cursor): { value: BareItem; bytes?: Uint8Array } { + const c = p.peek(); + if (c === '"') return { value: parseString(p) }; + if (c === ':') return { value: '', bytes: parseByteSequence(p) }; + if (c === '?') { + p.i++; + const b = p.s[p.i++]; + if (b === '1') return { value: true }; + if (b === '0') return { value: false }; + throw new Error('sfv: bad boolean'); + } + if (c === '-' || /[0-9]/.test(c)) return { value: parseNumber(p) }; + if (/[a-zA-Z*]/.test(c)) return { value: parseToken(p) }; + throw new Error(`sfv: invalid bare item at ${p.i}`); +} + +function parseString(p: Cursor): string { + p.i++; // opening quote + let out = ''; + while (!p.eof()) { + const c = p.s[p.i++]; + if (c === '"') return out; + if (c === '\\') { + const e = p.s[p.i++]; + if (e !== '"' && e !== '\\') throw new Error('sfv: bad escape'); + out += e; + } else { + const code = c.charCodeAt(0); + if (code < 0x20 || code > 0x7e) throw new Error('sfv: bad char in string'); + out += c; + } + } + throw new Error('sfv: unterminated string'); +} + +function parseByteSequence(p: Cursor): Uint8Array { + p.i++; // ':' + const start = p.i; + while (!p.eof() && p.peek() !== ':') p.i++; + if (p.eof()) throw new Error('sfv: unterminated byte sequence'); + const b64 = p.s.slice(start, p.i); + p.i++; // closing ':' + return base64StdToBytes(b64); +} + +function parseNumber(p: Cursor): number { + const start = p.i; + if (p.peek() === '-') p.i++; + while (!p.eof() && /[0-9]/.test(p.peek())) p.i++; + if (!p.eof() && p.peek() === '.') { + p.i++; + while (!p.eof() && /[0-9]/.test(p.peek())) p.i++; + } + return Number(p.s.slice(start, p.i)); +} + +function parseToken(p: Cursor): string { + const start = p.i; + p.i++; + while (!p.eof() && /[a-zA-Z0-9!#$%&'*+\-.^_`|~:/]/.test(p.peek())) p.i++; + return p.s.slice(start, p.i); +} + +/** Decode a standard (non-url) base64 string to bytes. */ +export function base64StdToBytes(s: string): Uint8Array { + const bin = atob(s); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); + return out; +} diff --git a/packages/webdecoy/src/agent/signature.ts b/packages/webdecoy/src/agent/signature.ts new file mode 100644 index 0000000..5ea11e7 --- /dev/null +++ b/packages/webdecoy/src/agent/signature.ts @@ -0,0 +1,274 @@ +/** + * RFC 9421 HTTP Message Signatures — the Web Bot Auth verification core. + * + * Verifies signatures tagged `web-bot-auth`: parse `Signature-Input` / + * `Signature`, rebuild the signature base for each covered-component set, and + * check the raw signature with WebCrypto against a key resolved by its JWK + * thumbprint keyid. Adapted from the WebDecoy edge validator + * (`edge/clearance-worker/src/web-bot-auth.ts`), generalized to resolve keys + * from a directory cache instead of a pushed key list. + * + * Zero dependencies, Edge-runtime safe: only `crypto.subtle`, `TextEncoder`, + * `atob`, and `URL` are used. + */ + +import { parseDictionary, type DictEntry, type BareItem } from './sfv'; + +const TAG = 'web-bot-auth'; +const encoder = new TextEncoder(); + +/** A verification key resolved from a trusted directory, ready for WebCrypto. */ +export interface VerificationKey { + cryptoKey: CryptoKey; + /** WebCrypto verify params (e.g. `{ name: 'Ed25519' }`). */ + verifyParams: AlgorithmIdentifier | RsaPssParams; + /** Human-readable algorithm label, e.g. "ed25519". */ + algorithm: string; + /** Display name of the owning agent. */ + name: string; + /** Category of the owning agent. */ + category: string; + /** Key validity bounds in Unix seconds, if the directory published them. */ + nbf?: number; + exp?: number; +} + +/** Resolves a JWK-thumbprint keyid to a verification key, or undefined if unknown. */ +export type KeyResolver = (keyId: string) => Promise; + +export type CoreOutcome = 'none' | 'verified' | 'impersonation' | 'claimed'; + +export interface CoreResult { + outcome: CoreOutcome; + keyId?: string; + key?: VerificationKey; + reason?: string; +} + +/** A normalized request the verifier operates on. */ +export interface NormalizedRequest { + method: string; + url: URL; + headers: Headers; +} + +interface Component { + name: string; + /** sf-dictionary member key, for `"signature-agent";key="…"`. */ + keyParam?: string; +} + +interface SigInputMember { + label: string; + components: Component[]; + params: Map; + /** Verbatim member text, for the `@signature-params` line. */ + raw: string; +} + +/** + * Verify every `web-bot-auth`-tagged signature on the request. Returns the + * highest-precedence outcome: verified > impersonation > claimed > none. + * + * - **verified**: a signature validated against a resolvable trusted key. + * - **impersonation**: a signature claimed a **known** key (resolvable) but + * failed crypto or fell outside its validity window — a forgery. + * - **claimed**: a signature is present but its keyid is unknown, or it is + * malformed / unsupported — unverifiable, but not proof of forgery. + * - **none**: no `web-bot-auth` signature at all. + */ +export async function verifyWebBotAuth( + req: NormalizedRequest, + resolveKey: KeyResolver, + toleranceSec: number, +): Promise { + const sigInput = req.headers.get('signature-input'); + const sigHeader = req.headers.get('signature'); + if (!sigInput && !sigHeader) return { outcome: 'none' }; + // A half-present signature is a malformed claim, not a confirmed forgery. + if (!sigInput || !sigHeader) return { outcome: 'claimed', reason: 'incomplete-signature' }; + + let members: SigInputMember[]; + let sigs: Map; + try { + members = parseSignatureInput(sigInput); + sigs = parseSignatureBytes(sigHeader); + } catch { + return { outcome: 'claimed', reason: 'malformed-signature' }; + } + + const now = Date.now() / 1000; + let best: CoreResult = { outcome: 'none' }; + + for (const m of members) { + if (m.params.get('tag') !== TAG) continue; + // Below this line every path yields at least 'claimed' — a web-bot-auth + // signature is present. A more specific claimed reason (unknown-key, + // uncoverable-component) can still replace this generic fallback. + if (best.outcome === 'none') best = { outcome: 'claimed', reason: 'unverifiable' }; + + const sig = sigs.get(m.label); + if (!sig) continue; + + const keyid = m.params.get('keyid'); + if (typeof keyid !== 'string') continue; + + // Must bind the host, per the profile. + if (!m.components.some((c) => c.name === '@authority' || c.name === '@target-uri')) continue; + + const key = await resolveKey(keyid); + if (!key) { + // Unknown agent — a claim we can't confirm or refute. + best = higher(best, { outcome: 'claimed', keyId: keyid, reason: 'unknown-key' }); + continue; + } + + // Known key: from here a failure is impersonation of a real agent. + const created = numeric(m.params.get('created')); + const expires = numeric(m.params.get('expires')); + if (expires !== undefined && now > expires + toleranceSec) { + best = higher(best, { outcome: 'impersonation', keyId: keyid, key, reason: 'expired' }); + continue; + } + if (created !== undefined && now + toleranceSec < created) { + best = higher(best, { outcome: 'impersonation', keyId: keyid, key, reason: 'not-yet-valid' }); + continue; + } + if (key.exp !== undefined && now > key.exp + toleranceSec) { + best = higher(best, { outcome: 'impersonation', keyId: keyid, key, reason: 'key-expired' }); + continue; + } + if (key.nbf !== undefined && now + toleranceSec < key.nbf) { + best = higher(best, { outcome: 'impersonation', keyId: keyid, key, reason: 'key-not-yet-valid' }); + continue; + } + + let base: string; + try { + base = buildSignatureBase(req, m); + } catch { + // A covered component we can't derive — can't confirm the forgery. + best = higher(best, { outcome: 'claimed', keyId: keyid, reason: 'uncoverable-component' }); + continue; + } + + let ok = false; + try { + ok = await crypto.subtle.verify( + key.verifyParams, + key.cryptoKey, + sig as BufferSource, + encoder.encode(base), + ); + } catch { + ok = false; + } + if (ok) { + return { outcome: 'verified', keyId: keyid, key }; + } + best = higher(best, { outcome: 'impersonation', keyId: keyid, key, reason: 'bad-signature' }); + } + + return best; +} + +const PRECEDENCE: Record = { none: 0, claimed: 1, impersonation: 2, verified: 3 }; +// `>=` so a later result of equal precedence (a more specific `claimed` +// reason) replaces an earlier generic one; a lower-precedence result never +// downgrades a higher one (impersonation survives a subsequent claim). +function higher(a: CoreResult, b: CoreResult): CoreResult { + return PRECEDENCE[b.outcome] >= PRECEDENCE[a.outcome] ? b : a; +} + +function numeric(v: BareItem | undefined): number | undefined { + return typeof v === 'number' ? v : undefined; +} + +// --- signature base (RFC 9421 §2.5, Web Bot Auth profile subset) --- + +function buildSignatureBase(req: NormalizedRequest, m: SigInputMember): string { + const lines: string[] = []; + for (const c of m.components) { + lines.push(`${serializeComponentId(c)}: ${componentValue(req, c)}`); + } + lines.push(`"@signature-params": ${m.raw.trim()}`); + return lines.join('\n'); +} + +function serializeComponentId(c: Component): string { + const base = `"${c.name.toLowerCase()}"`; + return c.keyParam !== undefined ? `${base};key="${c.keyParam}"` : base; +} + +function componentValue(req: NormalizedRequest, c: Component): string { + const name = c.name.toLowerCase(); + switch (name) { + case '@method': + return req.method.toUpperCase(); + case '@authority': + return canonicalAuthority(req.url); + case '@scheme': + return req.url.protocol.replace(/:$/, '').toLowerCase(); + case '@target-uri': + return `${req.url.protocol}//${canonicalAuthority(req.url)}${req.url.pathname}${req.url.search}`; + case '@path': + return req.url.pathname; + case '@query': + return req.url.search === '' ? '?' : req.url.search; + case 'signature-agent': { + const header = req.headers.get('signature-agent'); + if (header === null) throw new Error('signature-agent covered but absent'); + if (c.keyParam !== undefined) return dictMemberValue(header, c.keyParam); + return header.trim().replace(/\s+/g, ' '); + } + default: { + if (name.startsWith('@')) throw new Error(`unsupported derived component ${name}`); + const header = req.headers.get(name); + if (header === null) throw new Error(`covered header ${name} absent`); + return header.trim().replace(/\s+/g, ' '); + } + } +} + +function canonicalAuthority(url: URL): string { + const host = url.hostname.toLowerCase(); + const port = url.port; + if (!port) return host; + if ((url.protocol === 'https:' && port === '443') || (url.protocol === 'http:' && port === '80')) { + return host; + } + return `${host}:${port}`; +} + +/** Serialize one member of an sf-dictionary header value, per RFC 8941. */ +function dictMemberValue(header: string, key: string): string { + const dict = parseDictionary(header); + const found = dict.find((d) => d.key === key); + if (!found) throw new Error(`signature-agent has no member ${key}`); + return found.raw; +} + +// --- header parsing --- + +function parseSignatureInput(value: string): SigInputMember[] { + return parseDictionary(value).map((d: DictEntry) => { + if (!d.isList) throw new Error(`Signature-Input member ${d.key} is not an inner list`); + const components: Component[] = d.items.map((it) => { + if (typeof it.value !== 'string') throw new Error('component identifier is not a string'); + const keyParam = it.params.get('key'); + return { name: it.value, keyParam: typeof keyParam === 'string' ? keyParam : undefined }; + }); + return { label: d.key, components, params: d.params, raw: d.raw }; + }); +} + +function parseSignatureBytes(value: string): Map { + const out = new Map(); + for (const d of parseDictionary(value)) { + if (d.isList || d.items.length !== 1 || !d.items[0].bytes) { + throw new Error(`Signature member ${d.key} is not a byte sequence`); + } + out.set(d.key, d.items[0].bytes); + } + return out; +} diff --git a/packages/webdecoy/src/agent/thumbprint.ts b/packages/webdecoy/src/agent/thumbprint.ts new file mode 100644 index 0000000..2b9ad2a --- /dev/null +++ b/packages/webdecoy/src/agent/thumbprint.ts @@ -0,0 +1,63 @@ +/** + * JSON Web Key thumbprints (RFC 7638, plus the OKP variant from RFC 8037 + * Appendix A.3). + * + * Web Bot Auth uses the base64url-encoded JWK SHA-256 thumbprint of the + * signing key as the signature's `keyid`, so a verifier matches directory keys + * by comparing thumbprints — never by the JWK `kid` field. Ported from the Go + * `github.com/WebDecoy/web-bot-auth/thumbprint` package so the SDK, edge, and + * backend derive identical keyids. + */ + +export interface JWK { + kty: string; + crv?: string; + x?: string; + n?: string; + e?: string; + kid?: string; + use?: string; + nbf?: number; + exp?: number; +} + +const encoder = new TextEncoder(); + +/** RFC 7638 thumbprint of an RSA public JWK. `n`/`e` are base64url as published. */ +export async function rsaThumbprint(n: string, e: string): Promise { + return digest(`{"e":${JSON.stringify(e)},"kty":"RSA","n":${JSON.stringify(n)}}`); +} + +/** RFC 8037 A.3 thumbprint of an OKP public JWK (e.g. crv "Ed25519"). */ +export async function okpThumbprint(crv: string, x: string): Promise { + return digest(`{"crv":${JSON.stringify(crv)},"kty":"OKP","x":${JSON.stringify(x)}}`); +} + +/** + * Thumbprint of a JWK. Only the key types Web Bot Auth uses are supported + * (RSA and OKP); anything else throws. + */ +export async function jwkThumbprint(k: JWK): Promise { + switch (k.kty) { + case 'OKP': + if (!k.crv || !k.x) throw new Error('thumbprint: OKP JWK missing crv or x'); + return okpThumbprint(k.crv, k.x); + case 'RSA': + if (!k.n || !k.e) throw new Error('thumbprint: RSA JWK missing n or e'); + return rsaThumbprint(k.n, k.e); + default: + throw new Error(`thumbprint: unsupported kty ${JSON.stringify(k.kty)}`); + } +} + +async function digest(canonical: string): Promise { + const buf = await crypto.subtle.digest('SHA-256', encoder.encode(canonical)); + return base64urlBytes(new Uint8Array(buf)); +} + +/** base64url (unpadded) encoding of raw bytes. */ +function base64urlBytes(bytes: Uint8Array): string { + let binary = ''; + for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]); + return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} diff --git a/packages/webdecoy/src/agent/types.ts b/packages/webdecoy/src/agent/types.ts new file mode 100644 index 0000000..55a4e3e --- /dev/null +++ b/packages/webdecoy/src/agent/types.ts @@ -0,0 +1,126 @@ +/** + * Web Bot Auth verification — public types. + * + * A local verifier for the WebDecoy Web Bot Auth profile (RFC 9421 HTTP + * Message Signatures, tag "web-bot-auth"). It answers one question about an + * inbound request: is it a *cryptographically verified* AI agent, an + * *impersonator* forging a known agent's identity, an unverifiable *claim*, + * or plain traffic carrying no agent signature at all? + * + * The verdict taxonomy mirrors the server-side verifier in the ingest service + * (WebDecoy/app#320) so the SDK, the edge validator, and the backend all speak + * the same language. + */ + +/** The four possible outcomes of Web Bot Auth verification. */ +export type AgentStatus = + /** No Web Bot Auth signature on the request. Ordinary traffic. */ + | 'none' + /** Signature verified against a curated agent's published key. Trustworthy. */ + | 'verified' + /** + * A signature claiming a **known** agent's key that did **not** verify (bad + * signature, or outside its created/expires window). A forgery attempt — + * deny-able, tripwire-grade. + */ + | 'impersonation' + /** + * A signature is present but cannot be verified against any curated agent + * (unknown keyid, or an unsupported / malformed signature). An unverifiable + * claim — not proof of an agent, not proof of a forgery. + */ + | 'claimed'; + +/** + * Category an agent falls into, used for allow/deny policy. Matches the + * category taxonomy used by the edge validator and backend curation. + */ +export type AgentCategory = 'ai_crawlers' | 'search_engines' | 'monitoring' | string; + +/** The result of verifying one request. */ +export interface AgentVerdict { + /** Verification outcome. */ + status: AgentStatus; + /** Human display name of the matched agent (e.g. "OpenAI"). Only on `verified`. */ + agentName?: string; + /** Category of the matched agent. Only on `verified`. */ + category?: AgentCategory; + /** The JWK thumbprint keyid the signature claimed. Present on verified/impersonation/claimed. */ + keyId?: string; + /** Signature algorithm used (e.g. "ed25519", "rsa-pss-sha512"). Only on `verified`. */ + algorithm?: string; + /** + * How the verdict was reached — always `'signature'` for now (Web Bot Auth + * cryptographic verification). Kept for parity with the ingest verifier, + * which also reports `ip_rdns` / `claimed` methods it derives from other + * signals unavailable in-process. + */ + method?: 'signature'; + /** Short, non-sensitive reason string for non-verified outcomes (diagnostics). */ + reason?: string; +} + +/** A curated, trusted signing agent whose directory the SDK will fetch. */ +export interface SignedAgentDirectory { + /** Display name, e.g. "OpenAI". */ + name: string; + /** Category for allow/deny policy. */ + category: AgentCategory; + /** + * Origin (scheme + host) whose well-known HTTP Message Signatures directory + * publishes the agent's keys, e.g. `https://operator.openai.com`. The + * `/.well-known/http-message-signatures-directory` path is appended + * automatically. A full URL ending in a path is also accepted verbatim. + */ + directory: string; +} + +/** Options for {@link createAgentVerifier}. */ +export interface AgentVerifierOptions { + /** + * Trusted agent directories to verify against. Defaults to + * {@link DEFAULT_SIGNED_AGENT_DIRECTORIES}. Only origins in this list are + * ever fetched — the request's own `Signature-Agent` header is never used to + * choose a fetch target, so there is no SSRF surface. + */ + directories?: SignedAgentDirectory[]; + /** + * How long a fetched directory stays fresh, in milliseconds. After this the + * cached keys are still served (stale-while-revalidate) while a background + * refresh runs, so the warm path never blocks on the network. + * @default 21600000 (6 hours) + */ + cacheTtlMs?: number; + /** + * Per-directory fetch timeout in milliseconds. + * @default 5000 + */ + fetchTimeoutMs?: number; + /** + * Clock-skew tolerance in seconds applied to a signature's created/expires + * window. + * @default 300 (5 minutes) + */ + toleranceSec?: number; + /** Emit debug logging to the console. @default false */ + debug?: boolean; + /** + * Injectable fetch, primarily for tests. Defaults to the global `fetch`. + */ + fetchImpl?: typeof fetch; +} + +/** + * A request to verify. Either a WHATWG {@link Request} (the natural shape on + * Vercel Edge / Next.js middleware and Cloudflare Workers) or a plain object + * carrying the method, absolute URL, and headers. + */ +export type AgentRequestInput = + | Request + | { + method: string; + /** Absolute request URL, e.g. `https://example.com/path?q=1`. */ + url: string; + /** Headers as a WHATWG `Headers` or a plain (lowercased-key) record. */ + headers: Headers | Record; + }; diff --git a/packages/webdecoy/src/agent/verifier.ts b/packages/webdecoy/src/agent/verifier.ts new file mode 100644 index 0000000..3b477d3 --- /dev/null +++ b/packages/webdecoy/src/agent/verifier.ts @@ -0,0 +1,112 @@ +/** + * AgentVerifier — the public entry point for local Web Bot Auth verification. + * + * Wraps the cached directory client and the signature core into a single + * `verify(request)` call returning an {@link AgentVerdict}. Designed for the + * hot path of edge/Node middleware: warm verification is a header parse, one + * map lookup, and one WebCrypto verify — no network, well under the 5ms p95 + * budget in the acceptance criteria. + */ + +import { DirectoryCache, DEFAULT_SIGNED_AGENT_DIRECTORIES } from './directory'; +import { verifyWebBotAuth, type NormalizedRequest } from './signature'; +import type { AgentRequestInput, AgentVerdict, AgentVerifierOptions } from './types'; + +const DEFAULT_TTL_MS = 6 * 60 * 60 * 1000; +const DEFAULT_FETCH_TIMEOUT_MS = 5000; +const DEFAULT_TOLERANCE_SEC = 300; + +export class AgentVerifier { + private readonly cache: DirectoryCache; + private readonly toleranceSec: number; + + constructor(options: AgentVerifierOptions = {}) { + this.toleranceSec = options.toleranceSec ?? DEFAULT_TOLERANCE_SEC; + this.cache = new DirectoryCache({ + directories: options.directories ?? DEFAULT_SIGNED_AGENT_DIRECTORIES, + cacheTtlMs: options.cacheTtlMs ?? DEFAULT_TTL_MS, + fetchTimeoutMs: options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS, + debug: options.debug ?? false, + fetchImpl: options.fetchImpl ?? fetch, + }); + } + + /** Pre-fetch trusted directories so the first request verifies warm. */ + warmup(): void { + this.cache.prime(); + } + + /** Verify a request's Web Bot Auth signature (if any) locally. */ + async verify(request: AgentRequestInput): Promise { + let req: NormalizedRequest; + try { + req = normalize(request); + } catch { + // Can't even parse the request shape — treat as ordinary traffic rather + // than fabricate an agent verdict. + return { status: 'none' }; + } + + const result = await verifyWebBotAuth(req, this.cache.resolveKey, this.toleranceSec); + + switch (result.outcome) { + case 'verified': + return { + status: 'verified', + method: 'signature', + keyId: result.keyId, + agentName: result.key?.name, + category: result.key?.category, + algorithm: result.key?.algorithm, + }; + case 'impersonation': + return { + status: 'impersonation', + method: 'signature', + keyId: result.keyId, + agentName: result.key?.name, + category: result.key?.category, + reason: result.reason, + }; + case 'claimed': + return { status: 'claimed', keyId: result.keyId, reason: result.reason }; + default: + return { status: 'none' }; + } + } + + /** Cached-key count (diagnostics/tests). */ + get cachedKeyCount(): number { + return this.cache.size; + } +} + +/** Convenience factory mirroring the SDK's other `create*` helpers. */ +export function createAgentVerifier(options: AgentVerifierOptions = {}): AgentVerifier { + return new AgentVerifier(options); +} + +/** Normalize a WHATWG Request or a plain shape into `{ method, url, headers }`. */ +function normalize(input: AgentRequestInput): NormalizedRequest { + if (isRequest(input)) { + return { method: input.method, url: new URL(input.url), headers: input.headers }; + } + const headers = input.headers instanceof Headers ? input.headers : toHeaders(input.headers); + return { method: input.method, url: new URL(input.url), headers }; +} + +function isRequest(input: AgentRequestInput): input is Request { + return ( + typeof Request !== 'undefined' && + input instanceof Request && + typeof (input as Request).url === 'string' + ); +} + +function toHeaders(record: Record): Headers { + const h = new Headers(); + for (const [k, v] of Object.entries(record)) { + if (v !== undefined && v !== null) h.set(k, String(v)); + } + return h; +} diff --git a/packages/webdecoy/src/agent/web-bot-auth.test.ts b/packages/webdecoy/src/agent/web-bot-auth.test.ts new file mode 100644 index 0000000..c419f1b --- /dev/null +++ b/packages/webdecoy/src/agent/web-bot-auth.test.ts @@ -0,0 +1,253 @@ +/** + * Web Bot Auth local verification tests. + * + * Signatures are constructed here **independently** of the verifier: the + * RFC 9421 signature base is built by hand and signed with Node WebCrypto, so + * a bug in the verifier's own base construction (authority canonicalization, + * line format, @signature-params reconstruction) makes verification fail + * rather than pass. This pins the exact byte contract, not merely + * self-consistency. + */ + +import { AgentVerifier } from './verifier'; +import { jwkThumbprint, rsaThumbprint } from './thumbprint'; +import type { SignedAgentDirectory } from './types'; + +const enc = new TextEncoder(); + +function canonicalAuthority(u: URL): string { + const host = u.hostname.toLowerCase(); + if (!u.port) return host; + if ((u.protocol === 'https:' && u.port === '443') || (u.protocol === 'http:' && u.port === '80')) { + return host; + } + return `${host}:${u.port}`; +} + +function componentValue(name: string, u: URL, method: string): string { + switch (name) { + case '@authority': + return canonicalAuthority(u); + case '@method': + return method.toUpperCase(); + case '@path': + return u.pathname; + case '@target-uri': + return `${u.protocol}//${canonicalAuthority(u)}${u.pathname}${u.search}`; + default: + throw new Error(`test helper: unhandled component ${name}`); + } +} + +interface SignOpts { + privateKey: CryptoKey; + url: string; + method?: string; + components?: string[]; + keyid: string; + created?: number; + expires?: number; + tag?: string; + tamper?: boolean; + label?: string; +} + +/** Produce the Signature-Input / Signature header pair for a request. */ +async function signHeaders(opts: SignOpts): Promise> { + const u = new URL(opts.url); + const method = opts.method ?? 'GET'; + const components = opts.components ?? ['@authority']; + const now = Math.floor(Date.now() / 1000); + const created = opts.created ?? now; + const expires = opts.expires ?? created + 300; + const tag = opts.tag ?? 'web-bot-auth'; + const label = opts.label ?? 'sig1'; + + const inner = '(' + components.map((c) => `"${c}"`).join(' ') + ')'; + const params = `;created=${created};expires=${expires};keyid="${opts.keyid}";tag="${tag}"`; + const sigParamsValue = inner + params; + + const lines = components.map((c) => `"${c}": ${componentValue(c, u, method)}`); + lines.push(`"@signature-params": ${sigParamsValue}`); + const base = lines.join('\n'); + + const buf = await crypto.subtle.sign({ name: 'Ed25519' }, opts.privateKey, enc.encode(base)); + const bytes = new Uint8Array(buf); + if (opts.tamper) bytes[0] ^= 0xff; + const b64 = Buffer.from(bytes).toString('base64'); + + return { + 'signature-input': `${label}=${sigParamsValue}`, + signature: `${label}=:${b64}:`, + }; +} + +function mockDirectory(jwks: unknown): typeof fetch { + return (async () => + new Response(JSON.stringify(jwks), { + status: 200, + headers: { 'content-type': 'application/json' }, + })) as unknown as typeof fetch; +} + +const TEST_DIR: SignedAgentDirectory = { + name: 'TestBot', + category: 'ai_crawlers', + directory: 'https://bot.example', +}; + +async function fixture() { + const kp = (await crypto.subtle.generateKey({ name: 'Ed25519' }, true, [ + 'sign', + 'verify', + ])) as CryptoKeyPair; + const publicJwk = await crypto.subtle.exportKey('jwk', kp.publicKey); + // Directory JWKs carry only public material. + const dirJwk = { kty: 'OKP', crv: 'Ed25519', x: publicJwk.x }; + const keyid = await jwkThumbprint(dirJwk); + const verifier = new AgentVerifier({ + directories: [TEST_DIR], + fetchImpl: mockDirectory({ keys: [dirJwk] }), + }); + return { privateKey: kp.privateKey, keyid, verifier }; +} + +describe('AgentVerifier — Web Bot Auth', () => { + it('verifies a valid signature and surfaces the agent name/category', async () => { + const { privateKey, keyid, verifier } = await fixture(); + const headers = await signHeaders({ privateKey, keyid, url: 'https://bot.example/foo' }); + const req = new Request('https://bot.example/foo', { headers }); + + const verdict = await verifier.verify(req); + expect(verdict.status).toBe('verified'); + expect(verdict.agentName).toBe('TestBot'); + expect(verdict.category).toBe('ai_crawlers'); + expect(verdict.algorithm).toBe('ed25519'); + expect(verdict.method).toBe('signature'); + expect(verdict.keyId).toBe(keyid); + }); + + it('verifies a multi-component signature (@method @authority @path)', async () => { + const { privateKey, keyid, verifier } = await fixture(); + const headers = await signHeaders({ + privateKey, + keyid, + url: 'https://bot.example/api/data?x=1', + method: 'POST', + components: ['@method', '@authority', '@path'], + }); + const req = new Request('https://bot.example/api/data?x=1', { method: 'POST', headers }); + expect((await verifier.verify(req)).status).toBe('verified'); + }); + + it('flags a tampered signature over a known key as impersonation', async () => { + const { privateKey, keyid, verifier } = await fixture(); + const headers = await signHeaders({ + privateKey, + keyid, + url: 'https://bot.example/foo', + tamper: true, + }); + const req = new Request('https://bot.example/foo', { headers }); + const verdict = await verifier.verify(req); + expect(verdict.status).toBe('impersonation'); + expect(verdict.reason).toBe('bad-signature'); + }); + + it('flags an expired signature over a known key as impersonation', async () => { + const { privateKey, keyid, verifier } = await fixture(); + const created = Math.floor(Date.now() / 1000) - 4000; + const headers = await signHeaders({ + privateKey, + keyid, + url: 'https://bot.example/foo', + created, + expires: created + 300, // well outside the 300s tolerance + }); + const req = new Request('https://bot.example/foo', { headers }); + const verdict = await verifier.verify(req); + expect(verdict.status).toBe('impersonation'); + expect(verdict.reason).toBe('expired'); + }); + + it('treats a signature from an unknown key as an unverifiable claim', async () => { + const { privateKey, verifier } = await fixture(); + const headers = await signHeaders({ + privateKey, + keyid: 'ZmFrZS10aHVtYnByaW50LXVua25vd24', // not in the directory + url: 'https://bot.example/foo', + }); + const req = new Request('https://bot.example/foo', { headers }); + const verdict = await verifier.verify(req); + expect(verdict.status).toBe('claimed'); + expect(verdict.reason).toBe('unknown-key'); + }); + + it('treats a signature not binding the host as an unverifiable claim', async () => { + const { privateKey, keyid, verifier } = await fixture(); + // Sign over @method only — no @authority / @target-uri. The profile + // requires host binding, so the verifier must not accept it. + const headers = await signHeaders({ + privateKey, + keyid, + url: 'https://bot.example/foo', + components: ['@method'], + }); + const req = new Request('https://bot.example/foo', { headers }); + expect((await verifier.verify(req)).status).toBe('claimed'); + }); + + it('returns none for a half-present signature', async () => { + const { verifier } = await fixture(); + const req = new Request('https://bot.example/foo', { + headers: { 'signature-input': 'sig1=("@authority")' }, // no Signature header + }); + expect((await verifier.verify(req)).status).toBe('claimed'); + }); + + it('returns none for ordinary traffic (no signature)', async () => { + const { verifier } = await fixture(); + const req = new Request('https://bot.example/foo', { headers: { 'user-agent': 'Mozilla/5.0' } }); + expect((await verifier.verify(req)).status).toBe('none'); + }); + + it('accepts the plain { method, url, headers } request shape (Node path)', async () => { + const { privateKey, keyid, verifier } = await fixture(); + const headers = await signHeaders({ privateKey, keyid, url: 'https://bot.example/foo' }); + const verdict = await verifier.verify({ + method: 'GET', + url: 'https://bot.example/foo', + headers, + }); + expect(verdict.status).toBe('verified'); + }); + + it('does not fetch the network on the warm path and verifies in <5ms p95', async () => { + const { privateKey, keyid, verifier } = await fixture(); + const headers = await signHeaders({ privateKey, keyid, url: 'https://bot.example/foo' }); + const req = new Request('https://bot.example/foo', { headers }); + + // Warm the directory cache (one cold fetch), then verify repeatedly. + await verifier.verify(req); + + const N = 200; + const samples: number[] = []; + for (let i = 0; i < N; i++) { + const t0 = performance.now(); + await verifier.verify(req); + samples.push(performance.now() - t0); + } + samples.sort((a, b) => a - b); + const p95 = samples[Math.floor(N * 0.95)]; + expect(p95).toBeLessThan(5); + }); +}); + +describe('JWK thumbprint', () => { + it('matches the RFC 7638 §3.1 RSA known-answer', async () => { + // The canonical example from RFC 7638. + const n = + '0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw'; + expect(await rsaThumbprint(n, 'AQAB')).toBe('NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs'); + }); +}); diff --git a/packages/webdecoy/src/edge-runtime.test.ts b/packages/webdecoy/src/edge-runtime.test.ts index 16e6453..83cde78 100644 --- a/packages/webdecoy/src/edge-runtime.test.ts +++ b/packages/webdecoy/src/edge-runtime.test.ts @@ -73,6 +73,62 @@ describe('Edge Runtime compatibility', () => { expect(result.honeytokenPathOk).toBe(true); }); + it('verifies a Web Bot Auth signature via detectBot() in an Edge VM', async () => { + // Generate a key and sign a request in the Node test context, then verify + // it entirely inside the Edge VM (WebCrypto Ed25519 + directory cache). + const enc = new TextEncoder(); + const kp = (await crypto.subtle.generateKey({ name: 'Ed25519' }, true, [ + 'sign', + 'verify', + ])) as CryptoKeyPair; + const pub = await crypto.subtle.exportKey('jwk', kp.publicKey); + const dirJwk = { kty: 'OKP', crv: 'Ed25519', x: pub.x }; + + const digest = await crypto.subtle.digest( + 'SHA-256', + enc.encode(`{"crv":"Ed25519","kty":"OKP","x":${JSON.stringify(pub.x)}}`), + ); + const keyid = Buffer.from(new Uint8Array(digest)) + .toString('base64') + .replace(/\+/g, '-') + .replace(/\//g, '_') + .replace(/=+$/, ''); + + const created = Math.floor(Date.now() / 1000); + const sigParams = `("@authority");created=${created};expires=${created + 300};keyid="${keyid}";tag="web-bot-auth"`; + const base = `"@authority": bot.example\n"@signature-params": ${sigParams}`; + const sig = await crypto.subtle.sign({ name: 'Ed25519' }, kp.privateKey, enc.encode(base)); + const sigHeader = `sig1=:${Buffer.from(new Uint8Array(sig)).toString('base64')}:`; + const sigInput = `sig1=${sigParams}`; + + const bundle = bundleForEdge(); + const vm = new EdgeVM(); + vm.evaluate('var module = { exports: {} }; var exports = module.exports;'); + vm.evaluate(bundle); + + const result = await vm.evaluate>(` + (async () => { + const { createAgentVerifier } = module.exports; + const dirJwk = ${JSON.stringify(dirJwk)}; + const verifier = createAgentVerifier({ + directories: [{ name: 'EdgeBot', category: 'ai_crawlers', directory: 'https://bot.example' }], + fetchImpl: async () => new Response(JSON.stringify({ keys: [dirJwk] }), { status: 200 }), + }); + const req = new Request('https://bot.example/foo', { + headers: { + 'signature-input': ${JSON.stringify(sigInput)}, + 'signature': ${JSON.stringify(sigHeader)}, + }, + }); + const verdict = await verifier.verify(req); + return { status: verdict.status, name: verdict.agentName }; + })() + `); + + expect(result.status).toBe('verified'); + expect(result.name).toBe('EdgeBot'); + }); + it('captcha token issue/verify works in an Edge VM (Web Crypto path)', async () => { const bundle = bundleForEdge(); diff --git a/packages/webdecoy/src/index.ts b/packages/webdecoy/src/index.ts index 3e2c51d..36629e9 100644 --- a/packages/webdecoy/src/index.ts +++ b/packages/webdecoy/src/index.ts @@ -42,11 +42,13 @@ export { rateLimit, filter, tripwire, + webBotAuth, honeytoken, RuleEngine, RateLimitRule, FilterRule, TripwireRule, + WebBotAuthRule, DEFAULT_TRIPWIRE_PATHS, } from './rules'; @@ -58,12 +60,30 @@ export type { RateLimitConfig, FilterConfig, TripwireConfig, + WebBotAuthConfig, HoneytokenOptions, Honeytoken, ViolationEvent, IPEnrichmentData, } from './rules'; +// Local Web Bot Auth verification (RFC 9421, tag "web-bot-auth") +export { + AgentVerifier, + createAgentVerifier, + DirectoryCache, + DEFAULT_SIGNED_AGENT_DIRECTORIES, +} from './agent'; + +export type { + AgentStatus, + AgentCategory, + AgentVerdict, + AgentRequestInput, + AgentVerifierOptions, + SignedAgentDirectory, +} from './agent'; + // In-process detection engine (ported from FCaptcha) export { DetectionEngine, diff --git a/packages/webdecoy/src/rules/index.ts b/packages/webdecoy/src/rules/index.ts index b9c2e0d..6bbe5f2 100644 --- a/packages/webdecoy/src/rules/index.ts +++ b/packages/webdecoy/src/rules/index.ts @@ -6,6 +6,7 @@ export { RuleEngine } from './rule-engine'; export { RateLimitRule } from './rate-limit-rule'; export { FilterRule } from './filter-rule'; export { TripwireRule, DEFAULT_TRIPWIRE_PATHS } from './tripwire-rule'; +export { WebBotAuthRule, webBotAuth } from './web-bot-auth-rule'; export { honeytoken } from './honeytoken'; export { InMemoryRateLimiter } from './rate-limiter'; @@ -20,6 +21,7 @@ export type { ViolationEvent, IPEnrichmentData, } from './types'; +export type { WebBotAuthConfig } from './web-bot-auth-rule'; export type { HoneytokenOptions, Honeytoken } from './honeytoken'; import { RateLimitRule } from './rate-limit-rule'; diff --git a/packages/webdecoy/src/rules/types.ts b/packages/webdecoy/src/rules/types.ts index 21cdfd9..2e5a754 100644 --- a/packages/webdecoy/src/rules/types.ts +++ b/packages/webdecoy/src/rules/types.ts @@ -3,6 +3,8 @@ * Core interfaces for the WebDecoy rules engine */ +import type { AgentVerdict } from '../agent/types'; + /** * Context available to rules during evaluation */ @@ -21,6 +23,12 @@ export interface RuleContext { timestamp: number; /** IP enrichment data (populated async when available) */ enrichment?: IPEnrichmentData; + /** + * Web Bot Auth verdict (populated async before evaluation when a + * {@link https://github.com/WebDecoy/app/issues/323 webBotAuth} rule is + * present). Lets a synchronous rule act on cryptographic agent verification. + */ + agent?: AgentVerdict; } /** diff --git a/packages/webdecoy/src/rules/web-bot-auth-rule.test.ts b/packages/webdecoy/src/rules/web-bot-auth-rule.test.ts new file mode 100644 index 0000000..56e4e8f --- /dev/null +++ b/packages/webdecoy/src/rules/web-bot-auth-rule.test.ts @@ -0,0 +1,61 @@ +import { webBotAuth } from './web-bot-auth-rule'; +import type { RuleContext } from './types'; +import type { AgentVerdict } from '../agent/types'; + +function ctx(agent?: AgentVerdict): RuleContext { + return { + ip: '1.2.3.4', + path: '/', + method: 'GET', + headers: {}, + timestamp: Date.now(), + agent, + }; +} + +describe('webBotAuth rule', () => { + it('denies an impersonation by default', () => { + const r = webBotAuth().evaluate(ctx({ status: 'impersonation', keyId: 'k', reason: 'bad-signature' })); + expect(r.action).toBe('DENY'); + expect(r.rule).toBe('web-bot-auth'); + expect(r.metadata?.verdict).toBe('agent_impersonation'); + }); + + it('allows a verified agent', () => { + const r = webBotAuth().evaluate( + ctx({ status: 'verified', agentName: 'OpenAI', category: 'ai_crawlers', method: 'signature' }), + ); + expect(r.action).toBe('ALLOW'); + }); + + it('allows an unverifiable claim by default, denies it when onClaimed=DENY', () => { + const verdict: AgentVerdict = { status: 'claimed', keyId: 'k', reason: 'unknown-key' }; + expect(webBotAuth().evaluate(ctx(verdict)).action).toBe('ALLOW'); + expect(webBotAuth({ onClaimed: 'DENY' }).evaluate(ctx(verdict)).action).toBe('DENY'); + }); + + it('passes through when there is no agent verdict', () => { + expect(webBotAuth().evaluate(ctx()).action).toBe('ALLOW'); + expect(webBotAuth().evaluate(ctx({ status: 'none' })).action).toBe('ALLOW'); + }); + + it('honors dryRun — records the verdict but never blocks', () => { + const r = webBotAuth({ dryRun: true }).evaluate(ctx({ status: 'impersonation', reason: 'bad-signature' })); + expect(r.action).toBe('ALLOW'); + expect(r.metadata?.dryRun).toBe(true); + expect(r.metadata?.verdict).toBe('agent_impersonation'); + }); + + it('rejects a verified agent whose category is not allowed', () => { + const rule = webBotAuth({ allowCategories: ['search_engines'], onClaimed: 'DENY' }); + const r = rule.evaluate(ctx({ status: 'verified', agentName: 'OpenAI', category: 'ai_crawlers' })); + expect(r.action).toBe('DENY'); + expect(r.metadata?.verdict).toBe('agent_category_not_allowed'); + }); + + it('accepts a verified agent whose category is allowed', () => { + const rule = webBotAuth({ allowCategories: ['ai_crawlers'] }); + const r = rule.evaluate(ctx({ status: 'verified', agentName: 'OpenAI', category: 'ai_crawlers' })); + expect(r.action).toBe('ALLOW'); + }); +}); diff --git a/packages/webdecoy/src/rules/web-bot-auth-rule.ts b/packages/webdecoy/src/rules/web-bot-auth-rule.ts new file mode 100644 index 0000000..7c3eabf --- /dev/null +++ b/packages/webdecoy/src/rules/web-bot-auth-rule.ts @@ -0,0 +1,132 @@ +/** + * Web Bot Auth rule (WebDecoy/app#323). + * + * Acts on the Web Bot Auth verdict the SDK computes before rule evaluation + * (`context.agent`). Its headline job is to make **impersonation deny-able in + * middleware**: a request forging a known agent's identity (a signature that + * claims a curated agent's key but fails cryptographic verification) is a + * tripwire-grade signal, denied by default. + * + * Verification itself is async (it may touch a directory cache), so — like the + * filter rules and their IP enrichment — the verdict is precomputed into the + * context and this rule stays synchronous. + */ + +import type { Rule, RuleContext, RuleResult } from './types'; +import type { AgentCategory } from '../agent/types'; + +export interface WebBotAuthConfig { + /** + * Action when a request **impersonates** a known agent (signature matched a + * curated key but failed verification / window). Default `'DENY'`. + */ + onImpersonation?: 'DENY' | 'THROTTLE' | 'ALLOW'; + /** + * Action when a Web Bot Auth signature is present but **unverifiable** + * (unknown keyid, malformed). Default `'ALLOW'` — an unknown signer is not + * proof of abuse; leave the decision to detection/other rules. Set `'DENY'` + * to require that every signed agent be one you trust. + */ + onClaimed?: 'DENY' | 'THROTTLE' | 'ALLOW'; + /** + * Restrict which categories of **verified** agents this rule treats as + * acceptable. When set, a verified agent whose category is not listed is + * handled per {@link onClaimed} (i.e. its signature checks out, but you + * don't want that kind of agent). When omitted, all verified agents pass. + */ + allowCategories?: AgentCategory[]; + /** Log the violation but never block. Default `false`. */ + dryRun?: boolean; +} + +export class WebBotAuthRule implements Rule { + readonly name = 'web-bot-auth'; + private readonly onImpersonation: 'DENY' | 'THROTTLE' | 'ALLOW'; + private readonly onClaimed: 'DENY' | 'THROTTLE' | 'ALLOW'; + private readonly allowCategories?: Set; + private readonly dryRun: boolean; + + constructor(config: WebBotAuthConfig = {}) { + this.onImpersonation = config.onImpersonation ?? 'DENY'; + this.onClaimed = config.onClaimed ?? 'ALLOW'; + this.allowCategories = config.allowCategories ? new Set(config.allowCategories) : undefined; + this.dryRun = config.dryRun ?? false; + } + + evaluate(context: RuleContext): RuleResult { + const verdict = context.agent; + if (!verdict || verdict.status === 'none') return this.allow(); + + if (verdict.status === 'impersonation') { + return this.act(this.onImpersonation, 'agent_impersonation', { + agentName: verdict.agentName, + category: verdict.category, + keyId: verdict.keyId, + detail: verdict.reason, + }); + } + + if (verdict.status === 'claimed') { + return this.act(this.onClaimed, 'agent_unverifiable', { + keyId: verdict.keyId, + detail: verdict.reason, + }); + } + + // verified — pass, unless a category filter excludes it. + if (this.allowCategories && verdict.category && !this.allowCategories.has(verdict.category)) { + return this.act(this.onClaimed, 'agent_category_not_allowed', { + agentName: verdict.agentName, + category: verdict.category, + keyId: verdict.keyId, + }); + } + return this.allow(); + } + + private act( + action: 'DENY' | 'THROTTLE' | 'ALLOW', + verdict: string, + detail: Record, + ): RuleResult { + if (action === 'ALLOW') return this.allow(); + return { + action: this.dryRun ? 'ALLOW' : action, + rule: this.name, + reason: reasonFor(verdict), + metadata: { verdict, dryRun: this.dryRun, ...detail }, + }; + } + + private allow(): RuleResult { + return { action: 'ALLOW', rule: this.name }; + } +} + +function reasonFor(verdict: string): string { + switch (verdict) { + case 'agent_impersonation': + return 'Web Bot Auth signature failed verification (agent impersonation)'; + case 'agent_unverifiable': + return 'Web Bot Auth signature could not be verified'; + case 'agent_category_not_allowed': + return 'Verified agent category is not allowed'; + default: + return 'Web Bot Auth rule triggered'; + } +} + +/** + * Deny requests that impersonate a verified AI agent (default), acting on the + * SDK's local Web Bot Auth verification. + * + * @example + * ```ts + * import { WebDecoy, webBotAuth } from '@webdecoy/node'; + * + * const wd = new WebDecoy({ rules: [webBotAuth()] }); + * ``` + */ +export function webBotAuth(config: WebBotAuthConfig = {}): WebBotAuthRule { + return new WebBotAuthRule(config); +} diff --git a/packages/webdecoy/src/sdk.ts b/packages/webdecoy/src/sdk.ts index 1c91539..d061c99 100644 --- a/packages/webdecoy/src/sdk.ts +++ b/packages/webdecoy/src/sdk.ts @@ -8,6 +8,8 @@ import { analyzeRequest } from './local-analysis'; import { RuleEngine } from './rules/rule-engine'; import { ViolationReporter } from './violation-reporter'; import { IPEnrichmentClient } from './ip-enrichment'; +import { AgentVerifier } from './agent/verifier'; +import type { AgentRequestInput, AgentVerdict } from './agent/types'; import type { RuleContext, RuleEngineResult, ViolationEvent } from './rules/types'; import { WebDecoyConfig, @@ -19,13 +21,16 @@ import { export class WebDecoy { private client: WebDecoyClient | null; - private config: Omit, 'apiKey' | 'rules'> & { + private config: Omit, 'apiKey' | 'rules' | 'webBotAuth'> & { apiKey?: string; }; private ruleEngine: RuleEngine | null; private violationReporter: { report(violations: ViolationEvent[]): void; flush(): Promise; destroy(): Promise } | null = null; private ipEnrichmentClient: IPEnrichmentClient | null = null; private _hasFilterRules = false; + private _hasAgentRules = false; + private agentVerifier: AgentVerifier | null = null; + private readonly webBotAuthOptions?: WebDecoyConfig['webBotAuth']; constructor(config: WebDecoyConfig) { const hasApiKey = !!config.apiKey; @@ -66,6 +71,8 @@ export class WebDecoy { } } + this.webBotAuthOptions = config.webBotAuth; + // Initialize rule engine if rules are provided if (config.rules && config.rules.length > 0) { this.ruleEngine = new RuleEngine(config.rules); @@ -73,6 +80,13 @@ export class WebDecoy { this._hasFilterRules = config.rules.some( (r) => r.name.startsWith('filter:') ); + // Web Bot Auth rules need the agent verdict precomputed (async) before + // the synchronous rule can act on it — same pattern as filter rules. + this._hasAgentRules = config.rules.some((r) => r.name === 'web-bot-auth'); + if (this._hasAgentRules) { + // Warm the directory cache so the first protected request verifies warm. + this.getAgentVerifier().warmup(); + } } else { this.ruleEngine = null; } @@ -107,34 +121,23 @@ export class WebDecoy { */ evaluateRules(metadata: RequestMetadata): RuleEngineResult | null { if (!this.ruleEngine) return null; - - const context: RuleContext = { - ip: metadata.ip, - path: metadata.path, - method: metadata.method, - userAgent: metadata.user_agent, - headers: metadata.headers, - timestamp: metadata.timestamp || Date.now(), - }; - - const result = this.ruleEngine.evaluate(context); - - // Report violations asynchronously if reporter is attached - if (result.violations.length > 0 && this.violationReporter) { - this.violationReporter.report(result.violations); - } - - return result; + return this.runRules(this.buildContext(metadata)); } /** - * Evaluate rules with async IP enrichment pre-fetch. - * Use this instead of evaluateRules() when filter rules are present. + * Evaluate rules with async pre-fetch (IP enrichment, Web Bot Auth + * verification). Use this instead of evaluateRules() when filter rules or + * webBotAuth() rules are present. */ async evaluateRulesAsync(metadata: RequestMetadata): Promise { if (!this.ruleEngine) return null; + const context = await this.buildAsyncContext(metadata); + return this.runRules(context); + } - const context: RuleContext = { + /** Build the base (synchronous) rule context from request metadata. */ + private buildContext(metadata: RequestMetadata): RuleContext { + return { ip: metadata.ip, path: metadata.path, method: metadata.method, @@ -142,6 +145,14 @@ export class WebDecoy { headers: metadata.headers, timestamp: metadata.timestamp || Date.now(), }; + } + + /** + * Build a rule context with async signals resolved: IP enrichment (for + * filter rules) and the Web Bot Auth verdict (for webBotAuth() rules). + */ + private async buildAsyncContext(metadata: RequestMetadata): Promise { + const context = this.buildContext(metadata); // Pre-fetch IP enrichment if we have filter rules and an enrichment client if (this._hasFilterRules && this.ipEnrichmentClient) { @@ -151,16 +162,66 @@ export class WebDecoy { } } - const result = this.ruleEngine.evaluate(context); + // Verify Web Bot Auth signature locally so the sync rule can act on it. + if (this._hasAgentRules) { + context.agent = await this.computeAgentVerdict(metadata); + } - // Report violations asynchronously if reporter is attached + return context; + } + + /** Evaluate rules against a prepared context and report any violations. */ + private runRules(context: RuleContext): RuleEngineResult | null { + if (!this.ruleEngine) return null; + const result = this.ruleEngine.evaluate(context); if (result.violations.length > 0 && this.violationReporter) { this.violationReporter.report(result.violations); } - return result; } + /** Lazily construct the shared Web Bot Auth verifier (one directory cache). */ + private getAgentVerifier(): AgentVerifier { + if (!this.agentVerifier) { + this.agentVerifier = new AgentVerifier({ + debug: this.config.debug, + ...this.webBotAuthOptions, + }); + } + return this.agentVerifier; + } + + /** + * Verify a request's Web Bot Auth signature locally, deriving the request + * URL/authority from its metadata. Returns undefined when the request lacks + * the host information needed to verify (verdict is then simply absent). + */ + private async computeAgentVerdict(metadata: RequestMetadata): Promise { + const input = agentInputFromMetadata(metadata); + if (!input) return undefined; + return this.getAgentVerifier().verify(input); + } + + /** + * Verify an inbound request's Web Bot Auth signature locally (RFC 9421, tag + * "web-bot-auth"). Returns whether it is a cryptographically `verified` + * agent, an `impersonation` of a known one, an unverifiable `claimed` + * signature, or `none`. No network on the warm path. + * + * Accepts a WHATWG `Request` (edge/Next.js) or a `{ method, url, headers }` + * object (Node). + * + * @example + * ```ts + * const verdict = await webdecoy.detectBot(request); + * if (verdict.status === 'impersonation') return new Response('Forbidden', { status: 403 }); + * if (verdict.status === 'verified') console.log('verified agent:', verdict.agentName); + * ``` + */ + async detectBot(request: AgentRequestInput): Promise { + return this.getAgentVerifier().verify(request); + } + /** * Whether this SDK instance has filter rules that need async enrichment */ @@ -168,6 +229,14 @@ export class WebDecoy { return this._hasFilterRules; } + /** + * Whether this SDK instance has Web Bot Auth rules that need async + * verification before evaluation. + */ + get hasAgentRules(): boolean { + return this._hasAgentRules; + } + /** * Protect a request by checking it against Web Decoy's bot detection * @@ -190,11 +259,19 @@ export class WebDecoy { metadata.timestamp = Date.now(); } - // Evaluate rules first (if configured) - // Use async evaluation if filter rules exist (needs IP enrichment) - const ruleResult = this._hasFilterRules - ? await this.evaluateRulesAsync(metadata) - : this.evaluateRules(metadata); + // Evaluate rules first (if configured). Use async evaluation when a rule + // needs a pre-fetched signal — IP enrichment (filter rules) or Web Bot + // Auth verification (webBotAuth rules). Capture the agent verdict so it + // can be surfaced on the result for downstream allow decisions. + let ruleResult: RuleEngineResult | null; + let agentVerdict: AgentVerdict | undefined; + if (this.ruleEngine && (this._hasFilterRules || this._hasAgentRules)) { + const context = await this.buildAsyncContext(metadata); + agentVerdict = context.agent; + ruleResult = this.runRules(context); + } else { + ruleResult = this.evaluateRules(metadata); + } // If rules denied the request, return immediately without API call if (ruleResult && ruleResult.action === 'DENY') { @@ -209,6 +286,7 @@ export class WebDecoy { rule_enforced: true, }, ruleResult, + agent: agentVerdict, }; } @@ -225,6 +303,7 @@ export class WebDecoy { rule_enforced: true, }, ruleResult, + agent: agentVerdict, }; } @@ -241,6 +320,7 @@ export class WebDecoy { rule_enforced: false, }, ruleResult: ruleResult ?? undefined, + agent: agentVerdict, }; } @@ -284,6 +364,7 @@ export class WebDecoy { rule_enforced: false, }, ruleResult: ruleResult ?? undefined, + agent: agentVerdict, }; } @@ -306,6 +387,7 @@ export class WebDecoy { allowed, detection, ruleResult: ruleResult ?? undefined, + agent: agentVerdict, }; } catch (error) { // Log error if debug is enabled @@ -380,3 +462,39 @@ export class WebDecoy { } } } + +/** + * Reconstruct a Web Bot Auth verification input from request metadata. + * + * Signature verification needs the request's scheme, authority, and path. + * Metadata carries the path and headers but not a full URL, so the authority + * comes from the `Host` / `:authority` header and the scheme from + * `X-Forwarded-Proto` (defaulting to https). Returns null when no host is + * available — without it `@authority` can't be verified, so we simply skip + * agent verification rather than guess. + */ +function agentInputFromMetadata(metadata: RequestMetadata): AgentRequestInput | null { + const headers = metadata.headers || {}; + const host = + headers['host'] || + headers[':authority'] || + headers['x-forwarded-host'] || + headers['Host']; + if (!host) return null; + + const proto = headers['x-forwarded-proto'] || headers['X-Forwarded-Proto']; + const scheme = (proto ? proto.split(',')[0].trim() : 'https') || 'https'; + + const rawPath = metadata.path || '/'; + const path = rawPath.startsWith('/') ? rawPath : `/${rawPath}`; + + try { + return { + method: metadata.method, + url: `${scheme}://${host}${path}`, + headers, + }; + } catch { + return null; + } +} diff --git a/packages/webdecoy/src/types.ts b/packages/webdecoy/src/types.ts index a347dde..15c08ac 100644 --- a/packages/webdecoy/src/types.ts +++ b/packages/webdecoy/src/types.ts @@ -4,6 +4,7 @@ */ import type { Rule } from './rules/types'; +import type { AgentVerifierOptions, AgentVerdict } from './agent/types'; /** * Configuration options for the Web Decoy SDK @@ -59,6 +60,13 @@ export interface WebDecoyConfig { * Rules are evaluated in order; first DENY/THROTTLE wins */ rules?: Rule[]; + + /** + * Options for local Web Bot Auth agent verification (used by `detectBot()` + * and the `webBotAuth()` rule) — trusted directories, cache TTL, etc. + * Defaults are sensible; override only to curate your own agent allowlist. + */ + webBotAuth?: AgentVerifierOptions; } /** @@ -188,6 +196,13 @@ export interface ProtectResult { /** Rule engine result (if rules were evaluated) */ ruleResult?: import('./rules/types').RuleEngineResult; + + /** + * Web Bot Auth verdict, present when a `webBotAuth()` rule triggered the + * local agent verification for this request. Lets middleware treat a + * `verified` agent specially (e.g. allow) without re-verifying. + */ + agent?: AgentVerdict; } /**