@webdecoy/node 0.4.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,229 @@
1
+ /**
2
+ * The edge validator's verdict, as the origin sees it (#481).
3
+ *
4
+ * WHY THIS MODULE EXISTS
5
+ *
6
+ * The Cloudflare clearance worker has set `x-wd-clearance` on every forwarded
7
+ * request since the validator shipped, and nothing has ever read it. Grepping the
8
+ * header across the monorepo, this SDK and the WordPress plugin returned only the
9
+ * worker that writes it, its own tests, and one documentation page. We shipped a
10
+ * tag no customer could act on, then documented it as "watch the header in your
11
+ * logs."
12
+ *
13
+ * That gap matters more than it sounds. On a scoped route the gate's only options
14
+ * were pass or challenge, and a challenge on public content is a 403 to every
15
+ * client that cannot run JavaScript — search crawlers included. Reading the tag
16
+ * gives the application a third option it owns: log it, meter it, skip an
17
+ * expensive query, serve something cheaper. That is the first "yes" a cautious
18
+ * operator can give.
19
+ *
20
+ * WHAT IT IS NOT
21
+ *
22
+ * These values are advisory context, not authentication. They are only meaningful
23
+ * for requests that actually passed through the edge validator, and the validator
24
+ * strips inbound copies precisely so that the origin can attribute them to us.
25
+ * A request that reaches the origin WITHOUT passing through the proxy — straight
26
+ * to the origin IP, or a route that does not match — can carry anything. Treat
27
+ * `present: false` as "no information", never as "not a bot", and keep the origin
28
+ * unreachable except through the proxy if you intend to branch on this.
29
+ */
30
+ /** Header the edge validator uses for its clearance verdict. */
31
+ declare const EDGE_CLEARANCE_HEADER = "x-wd-clearance";
32
+ /** Header the edge validator uses for the sensor's client classification. */
33
+ declare const EDGE_CLASS_HEADER = "x-wd-class";
34
+ /**
35
+ * What the edge sensor concluded the client is.
36
+ *
37
+ * - `verified` — an identity something other than the client has attested
38
+ * (Cloudflare's verified-bot signal). **Never degrade these.** This is
39
+ * Googlebot and friends, and quietly serving them less is how a customer loses
40
+ * search presence and blames you six weeks later.
41
+ * - `crawler` — self-declares as a crawler, unproven. Real-but-unverified
42
+ * crawlers and forged ones both land here.
43
+ * - `script` — an HTTP client library, a Chromium user agent sending no client
44
+ * hints, or no user agent at all. Not a browser.
45
+ * - `browser` — nothing that distinguishes a non-human fired. A statement about
46
+ * our signals, not a certificate.
47
+ */
48
+ type EdgeClass = 'verified' | 'crawler' | 'script' | 'browser';
49
+ /**
50
+ * The edge's annotations on one request, typed.
51
+ *
52
+ * Every field is optional except `present`, because the edge validator may not be
53
+ * in front of this request at all — and the difference between "the edge said
54
+ * browser" and "there is no edge here" is the difference between a safe
55
+ * optimisation and a security hole.
56
+ */
57
+ interface EdgeVerdict {
58
+ /**
59
+ * True when the edge validator annotated this request. False means no
60
+ * information — not "human", not "safe".
61
+ */
62
+ present: boolean;
63
+ /**
64
+ * The clearance verdict, e.g. `valid`, `missing`, `verified-bot`,
65
+ * `signed-agent`, `machine`, `insufficient-trust`. Free-form on purpose: the
66
+ * validator gains labels faster than an SDK release can enumerate them, and an
67
+ * unknown label must not become `undefined`.
68
+ */
69
+ clearance?: string;
70
+ /** The sensor's classification, when it classified this request. */
71
+ class?: EdgeClass;
72
+ /** `class === 'verified'`. Convenience so callers need no string literals. */
73
+ isVerified: boolean;
74
+ /** `class === 'crawler'`. */
75
+ isCrawler: boolean;
76
+ /** `class === 'script'`. */
77
+ isScript: boolean;
78
+ /** `class === 'browser'`. */
79
+ isBrowser: boolean;
80
+ /**
81
+ * True for a class that is not a browser and is not attested — `script` or
82
+ * `crawler`.
83
+ *
84
+ * This is the predicate most applications actually want, and it deliberately
85
+ * excludes `verified`: the common intent is "cheapen this response", and the one
86
+ * population you must never cheapen for is the one whose identity was proven.
87
+ */
88
+ isUnattestedNonBrowser: boolean;
89
+ }
90
+ /**
91
+ * Read the edge validator's annotations out of a request's headers.
92
+ *
93
+ * Accepts the header bag the SDK already carries on `RequestMetadata` — lowercase
94
+ * keys — and tolerates mixed case, since adapters differ on normalisation.
95
+ *
96
+ * An unrecognised class value is dropped rather than passed through. The set is
97
+ * closed and small; a value outside it means either a version skew or something
98
+ * that is not our worker, and in both cases silence beats a value a caller might
99
+ * branch on.
100
+ */
101
+ declare function readEdgeVerdict(headers: Record<string, string> | undefined): EdgeVerdict;
102
+
103
+ /**
104
+ * Web Bot Auth verification — public types.
105
+ *
106
+ * A local verifier for the WebDecoy Web Bot Auth profile (RFC 9421 HTTP
107
+ * Message Signatures, tag "web-bot-auth"). It answers one question about an
108
+ * inbound request: is it a *cryptographically verified* AI agent, an
109
+ * *impersonator* forging a known agent's identity, an unverifiable *claim*,
110
+ * or plain traffic carrying no agent signature at all?
111
+ *
112
+ * The verdict taxonomy mirrors the server-side verifier in the ingest service
113
+ * (WebDecoy/app#320) so the SDK, the edge validator, and the backend all speak
114
+ * the same language.
115
+ */
116
+ /** The four possible outcomes of Web Bot Auth verification. */
117
+ type AgentStatus =
118
+ /** No Web Bot Auth signature on the request. Ordinary traffic. */
119
+ 'none'
120
+ /** Signature verified against a curated agent's published key. Trustworthy. */
121
+ | 'verified'
122
+ /**
123
+ * A signature claiming a **known** agent's key that did **not** verify (bad
124
+ * signature, or outside its created/expires window). A forgery attempt —
125
+ * deny-able, tripwire-grade.
126
+ */
127
+ | 'impersonation'
128
+ /**
129
+ * A signature is present but cannot be verified against any curated agent
130
+ * (unknown keyid, or an unsupported / malformed signature). An unverifiable
131
+ * claim — not proof of an agent, not proof of a forgery.
132
+ */
133
+ | 'claimed';
134
+ /**
135
+ * Category an agent falls into, used for allow/deny policy. Matches the
136
+ * category taxonomy used by the edge validator and backend curation.
137
+ */
138
+ type AgentCategory = 'ai_crawlers' | 'search_engines' | 'monitoring' | string;
139
+ /** The result of verifying one request. */
140
+ interface AgentVerdict {
141
+ /** Verification outcome. */
142
+ status: AgentStatus;
143
+ /** Human display name of the matched agent (e.g. "OpenAI"). Only on `verified`. */
144
+ agentName?: string;
145
+ /** Category of the matched agent. Only on `verified`. */
146
+ category?: AgentCategory;
147
+ /** The JWK thumbprint keyid the signature claimed. Present on verified/impersonation/claimed. */
148
+ keyId?: string;
149
+ /** Signature algorithm used (e.g. "ed25519", "rsa-pss-sha512"). Only on `verified`. */
150
+ algorithm?: string;
151
+ /**
152
+ * How the verdict was reached — always `'signature'` for now (Web Bot Auth
153
+ * cryptographic verification). Kept for parity with the ingest verifier,
154
+ * which also reports `ip_rdns` / `claimed` methods it derives from other
155
+ * signals unavailable in-process.
156
+ */
157
+ method?: 'signature';
158
+ /** Short, non-sensitive reason string for non-verified outcomes (diagnostics). */
159
+ reason?: string;
160
+ }
161
+ /** A curated, trusted signing agent whose directory the SDK will fetch. */
162
+ interface SignedAgentDirectory {
163
+ /** Display name, e.g. "OpenAI". */
164
+ name: string;
165
+ /** Category for allow/deny policy. */
166
+ category: AgentCategory;
167
+ /**
168
+ * Origin (scheme + host) whose well-known HTTP Message Signatures directory
169
+ * publishes the agent's keys, e.g. `https://operator.openai.com`. The
170
+ * `/.well-known/http-message-signatures-directory` path is appended
171
+ * automatically. A full URL ending in a path is also accepted verbatim.
172
+ */
173
+ directory: string;
174
+ }
175
+ /** Options for {@link createAgentVerifier}. */
176
+ interface AgentVerifierOptions {
177
+ /**
178
+ * Trusted agent directories to verify against. Defaults to
179
+ * {@link DEFAULT_SIGNED_AGENT_DIRECTORIES}. Only origins in this list are
180
+ * ever fetched — the request's own `Signature-Agent` header is never used to
181
+ * choose a fetch target, so there is no SSRF surface.
182
+ */
183
+ directories?: SignedAgentDirectory[];
184
+ /**
185
+ * How long a fetched directory stays fresh, in milliseconds. After this the
186
+ * cached keys are still served (stale-while-revalidate) while a background
187
+ * refresh runs, so the warm path never blocks on the network.
188
+ * @default 21600000 (6 hours)
189
+ */
190
+ cacheTtlMs?: number;
191
+ /**
192
+ * Per-directory fetch timeout in milliseconds.
193
+ * @default 5000
194
+ */
195
+ fetchTimeoutMs?: number;
196
+ /**
197
+ * Clock-skew tolerance in seconds applied to a signature's created/expires
198
+ * window.
199
+ * @default 300 (5 minutes)
200
+ */
201
+ toleranceSec?: number;
202
+ /** Emit debug logging to the console. @default false */
203
+ debug?: boolean;
204
+ /**
205
+ * Injectable fetch, primarily for tests. Defaults to the global `fetch`.
206
+ */
207
+ fetchImpl?: typeof fetch;
208
+ }
209
+ /**
210
+ * A request to verify. Either a WHATWG {@link Request} (the natural shape on
211
+ * Vercel Edge / Next.js middleware and Cloudflare Workers) or a plain object
212
+ * carrying the method, absolute URL, and headers.
213
+ */
214
+ type AgentRequestInput = Request | {
215
+ method: string;
216
+ /** Absolute request URL, e.g. `https://example.com/path?q=1`. */
217
+ url: string;
218
+ /** Headers as a WHATWG `Headers` or a plain (lowercased-key) record. */
219
+ headers: Headers | Record<string, string>;
220
+ };
221
+
1
222
  /**
2
223
  * Rules Engine Types
3
224
  * Core interfaces for the WebDecoy rules engine
4
225
  */
226
+
5
227
  /**
6
228
  * Context available to rules during evaluation
7
229
  */
@@ -20,6 +242,19 @@ interface RuleContext {
20
242
  timestamp: number;
21
243
  /** IP enrichment data (populated async when available) */
22
244
  enrichment?: IPEnrichmentData;
245
+ /**
246
+ * Web Bot Auth verdict (populated async before evaluation when a
247
+ * {@link https://github.com/WebDecoy/app/issues/323 webBotAuth} rule is
248
+ * present). Lets a synchronous rule act on cryptographic agent verification.
249
+ */
250
+ agent?: AgentVerdict;
251
+ /**
252
+ * The edge validator's annotations on this request (#481), parsed from
253
+ * `x-wd-clearance` and `x-wd-class`. Always populated — `present: false` when
254
+ * the edge did not front this request. Filter expressions read it as
255
+ * `edge.class`, `edge.clearance` and `edge.present`.
256
+ */
257
+ edge?: EdgeVerdict;
23
258
  }
24
259
  /**
25
260
  * Result of evaluating a single rule
@@ -108,6 +343,13 @@ interface ViolationEvent {
108
343
  userAgent?: string;
109
344
  /** Reason for the violation */
110
345
  reason?: string;
346
+ /**
347
+ * The request's wd_clearance token, when present. Lets the backend bind a
348
+ * tripwire hit to the actor's device fingerprint and deny it — the same
349
+ * durable lockout a decoy hit produces (enforcement issue #136). Only carried
350
+ * for deception rules (tripwires); undefined otherwise.
351
+ */
352
+ clearance?: string;
111
353
  /** Additional metadata */
112
354
  metadata?: Record<string, any>;
113
355
  /** Whether this was a dry run */
@@ -207,6 +449,12 @@ interface WebDecoyConfig {
207
449
  * Rules are evaluated in order; first DENY/THROTTLE wins
208
450
  */
209
451
  rules?: Rule[];
452
+ /**
453
+ * Options for local Web Bot Auth agent verification (used by `detectBot()`
454
+ * and the `webBotAuth()` rule) — trusted directories, cache TTL, etc.
455
+ * Defaults are sensible; override only to curate your own agent allowlist.
456
+ */
457
+ webBotAuth?: AgentVerifierOptions;
210
458
  }
211
459
  /**
212
460
  * TLS connection information from the request
@@ -303,6 +551,21 @@ interface ProtectResult {
303
551
  error?: string;
304
552
  /** Rule engine result (if rules were evaluated) */
305
553
  ruleResult?: RuleEngineResult;
554
+ /**
555
+ * Web Bot Auth verdict, present when a `webBotAuth()` rule triggered the
556
+ * local agent verification for this request. Lets middleware treat a
557
+ * `verified` agent specially (e.g. allow) without re-verifying.
558
+ */
559
+ agent?: AgentVerdict;
560
+ /**
561
+ * What the edge validator said about this request (#481), parsed from
562
+ * `x-wd-clearance` and `x-wd-class`.
563
+ *
564
+ * Always present. Check `edge.present` before branching: false means the edge
565
+ * did not front this request, which is no information rather than a clean bill
566
+ * of health.
567
+ */
568
+ edge?: EdgeVerdict;
306
569
  }
307
570
  /**
308
571
  * Options for the protect() method
@@ -318,7 +581,11 @@ interface ProtectOptions {
318
581
 
319
582
  /**
320
583
  * Web Decoy API Client
321
- * Handles communication with the ingest service
584
+ * Handles communication with the ingest service.
585
+ *
586
+ * Uses the Web-standard `fetch` API (no axios, no `node:` imports) so the SDK
587
+ * runs in Node >= 18 and edge runtimes (Vercel Edge Middleware, Cloudflare
588
+ * Workers) alike.
322
589
  */
323
590
 
324
591
  interface ClientConfig {
@@ -326,12 +593,19 @@ interface ClientConfig {
326
593
  apiUrl: string;
327
594
  timeout: number;
328
595
  debug: boolean;
596
+ /**
597
+ * Kept for API compatibility; the fetch transport does not support disabling
598
+ * TLS verification. For local self-signed certs in Node, trust the CA
599
+ * instead: `NODE_EXTRA_CA_CERTS=/path/to/ca.pem`.
600
+ */
329
601
  tlsRejectUnauthorized: boolean;
330
602
  }
331
603
  declare class WebDecoyClient {
332
- private axios;
333
604
  private config;
605
+ private baseUrl;
606
+ private headers;
334
607
  constructor(config: ClientConfig);
608
+ private request;
335
609
  /**
336
610
  * Send a detection request to the ingest service
337
611
  */
@@ -362,6 +636,9 @@ declare class WebDecoy {
362
636
  private violationReporter;
363
637
  private ipEnrichmentClient;
364
638
  private _hasFilterRules;
639
+ private _hasAgentRules;
640
+ private agentVerifier;
641
+ private readonly webBotAuthOptions?;
365
642
  constructor(config: WebDecoyConfig);
366
643
  /**
367
644
  * Evaluate rules against request metadata (synchronous).
@@ -369,14 +646,54 @@ declare class WebDecoy {
369
646
  */
370
647
  evaluateRules(metadata: RequestMetadata): RuleEngineResult | null;
371
648
  /**
372
- * Evaluate rules with async IP enrichment pre-fetch.
373
- * Use this instead of evaluateRules() when filter rules are present.
649
+ * Evaluate rules with async pre-fetch (IP enrichment, Web Bot Auth
650
+ * verification). Use this instead of evaluateRules() when filter rules or
651
+ * webBotAuth() rules are present.
374
652
  */
375
653
  evaluateRulesAsync(metadata: RequestMetadata): Promise<RuleEngineResult | null>;
654
+ /** Build the base (synchronous) rule context from request metadata. */
655
+ private buildContext;
656
+ /**
657
+ * Build a rule context with async signals resolved: IP enrichment (for
658
+ * filter rules) and the Web Bot Auth verdict (for webBotAuth() rules).
659
+ */
660
+ private buildAsyncContext;
661
+ /** Evaluate rules against a prepared context and report any violations. */
662
+ private runRules;
663
+ /** Lazily construct the shared Web Bot Auth verifier (one directory cache). */
664
+ private getAgentVerifier;
665
+ /**
666
+ * Verify a request's Web Bot Auth signature locally, deriving the request
667
+ * URL/authority from its metadata. Returns undefined when the request lacks
668
+ * the host information needed to verify (verdict is then simply absent).
669
+ */
670
+ private computeAgentVerdict;
671
+ /**
672
+ * Verify an inbound request's Web Bot Auth signature locally (RFC 9421, tag
673
+ * "web-bot-auth"). Returns whether it is a cryptographically `verified`
674
+ * agent, an `impersonation` of a known one, an unverifiable `claimed`
675
+ * signature, or `none`. No network on the warm path.
676
+ *
677
+ * Accepts a WHATWG `Request` (edge/Next.js) or a `{ method, url, headers }`
678
+ * object (Node).
679
+ *
680
+ * @example
681
+ * ```ts
682
+ * const verdict = await webdecoy.detectBot(request);
683
+ * if (verdict.status === 'impersonation') return new Response('Forbidden', { status: 403 });
684
+ * if (verdict.status === 'verified') console.log('verified agent:', verdict.agentName);
685
+ * ```
686
+ */
687
+ detectBot(request: AgentRequestInput): Promise<AgentVerdict>;
376
688
  /**
377
689
  * Whether this SDK instance has filter rules that need async enrichment
378
690
  */
379
691
  get hasFilterRules(): boolean;
692
+ /**
693
+ * Whether this SDK instance has Web Bot Auth rules that need async
694
+ * verification before evaluation.
695
+ */
696
+ get hasAgentRules(): boolean;
380
697
  /**
381
698
  * Protect a request by checking it against Web Decoy's bot detection
382
699
  *
@@ -385,6 +702,7 @@ declare class WebDecoy {
385
702
  * @returns Protection result with decision and detection details
386
703
  */
387
704
  protect(metadata: RequestMetadata, options?: ProtectOptions): Promise<ProtectResult>;
705
+ private decide;
388
706
  /**
389
707
  * Validate the API key configuration
390
708
  * Useful for testing integration during setup
@@ -496,6 +814,67 @@ declare class TripwireRule implements Rule {
496
814
  evaluate(context: RuleContext): RuleResult;
497
815
  }
498
816
 
817
+ /**
818
+ * Web Bot Auth rule (WebDecoy/app#323).
819
+ *
820
+ * Acts on the Web Bot Auth verdict the SDK computes before rule evaluation
821
+ * (`context.agent`). Its headline job is to make **impersonation deny-able in
822
+ * middleware**: a request forging a known agent's identity (a signature that
823
+ * claims a curated agent's key but fails cryptographic verification) is a
824
+ * tripwire-grade signal, denied by default.
825
+ *
826
+ * Verification itself is async (it may touch a directory cache), so — like the
827
+ * filter rules and their IP enrichment — the verdict is precomputed into the
828
+ * context and this rule stays synchronous.
829
+ */
830
+
831
+ interface WebBotAuthConfig {
832
+ /**
833
+ * Action when a request **impersonates** a known agent (signature matched a
834
+ * curated key but failed verification / window). Default `'DENY'`.
835
+ */
836
+ onImpersonation?: 'DENY' | 'THROTTLE' | 'ALLOW';
837
+ /**
838
+ * Action when a Web Bot Auth signature is present but **unverifiable**
839
+ * (unknown keyid, malformed). Default `'ALLOW'` — an unknown signer is not
840
+ * proof of abuse; leave the decision to detection/other rules. Set `'DENY'`
841
+ * to require that every signed agent be one you trust.
842
+ */
843
+ onClaimed?: 'DENY' | 'THROTTLE' | 'ALLOW';
844
+ /**
845
+ * Restrict which categories of **verified** agents this rule treats as
846
+ * acceptable. When set, a verified agent whose category is not listed is
847
+ * handled per {@link onClaimed} (i.e. its signature checks out, but you
848
+ * don't want that kind of agent). When omitted, all verified agents pass.
849
+ */
850
+ allowCategories?: AgentCategory[];
851
+ /** Log the violation but never block. Default `false`. */
852
+ dryRun?: boolean;
853
+ }
854
+ declare class WebBotAuthRule implements Rule {
855
+ readonly name = "web-bot-auth";
856
+ private readonly onImpersonation;
857
+ private readonly onClaimed;
858
+ private readonly allowCategories?;
859
+ private readonly dryRun;
860
+ constructor(config?: WebBotAuthConfig);
861
+ evaluate(context: RuleContext): RuleResult;
862
+ private act;
863
+ private allow;
864
+ }
865
+ /**
866
+ * Deny requests that impersonate a verified AI agent (default), acting on the
867
+ * SDK's local Web Bot Auth verification.
868
+ *
869
+ * @example
870
+ * ```ts
871
+ * import { WebDecoy, webBotAuth } from '@webdecoy/node';
872
+ *
873
+ * const wd = new WebDecoy({ rules: [webBotAuth()] });
874
+ * ```
875
+ */
876
+ declare function webBotAuth(config?: WebBotAuthConfig): WebBotAuthRule;
877
+
499
878
  /**
500
879
  * Honeytoken generator (F4 — deception layer)
501
880
  *
@@ -591,6 +970,115 @@ declare function filter(config: FilterConfig): Rule;
591
970
  */
592
971
  declare function tripwire(config?: TripwireConfig): Rule;
593
972
 
973
+ /**
974
+ * AgentVerifier — the public entry point for local Web Bot Auth verification.
975
+ *
976
+ * Wraps the cached directory client and the signature core into a single
977
+ * `verify(request)` call returning an {@link AgentVerdict}. Designed for the
978
+ * hot path of edge/Node middleware: warm verification is a header parse, one
979
+ * map lookup, and one WebCrypto verify — no network, well under the 5ms p95
980
+ * budget in the acceptance criteria.
981
+ */
982
+
983
+ declare class AgentVerifier {
984
+ private readonly cache;
985
+ private readonly toleranceSec;
986
+ constructor(options?: AgentVerifierOptions);
987
+ /** Pre-fetch trusted directories so the first request verifies warm. */
988
+ warmup(): void;
989
+ /** Verify a request's Web Bot Auth signature (if any) locally. */
990
+ verify(request: AgentRequestInput): Promise<AgentVerdict>;
991
+ /** Cached-key count (diagnostics/tests). */
992
+ get cachedKeyCount(): number;
993
+ }
994
+ /** Convenience factory mirroring the SDK's other `create*` helpers. */
995
+ declare function createAgentVerifier(options?: AgentVerifierOptions): AgentVerifier;
996
+
997
+ /**
998
+ * RFC 9421 HTTP Message Signatures — the Web Bot Auth verification core.
999
+ *
1000
+ * Verifies signatures tagged `web-bot-auth`: parse `Signature-Input` /
1001
+ * `Signature`, rebuild the signature base for each covered-component set, and
1002
+ * check the raw signature with WebCrypto against a key resolved by its JWK
1003
+ * thumbprint keyid. Adapted from the WebDecoy edge validator
1004
+ * (`edge/clearance-worker/src/web-bot-auth.ts`), generalized to resolve keys
1005
+ * from a directory cache instead of a pushed key list.
1006
+ *
1007
+ * Zero dependencies, Edge-runtime safe: only `crypto.subtle`, `TextEncoder`,
1008
+ * `atob`, and `URL` are used.
1009
+ */
1010
+ /** A verification key resolved from a trusted directory, ready for WebCrypto. */
1011
+ interface VerificationKey {
1012
+ cryptoKey: CryptoKey;
1013
+ /** WebCrypto verify params (e.g. `{ name: 'Ed25519' }`). */
1014
+ verifyParams: AlgorithmIdentifier | RsaPssParams;
1015
+ /** Human-readable algorithm label, e.g. "ed25519". */
1016
+ algorithm: string;
1017
+ /** Display name of the owning agent. */
1018
+ name: string;
1019
+ /** Category of the owning agent. */
1020
+ category: string;
1021
+ /** Key validity bounds in Unix seconds, if the directory published them. */
1022
+ nbf?: number;
1023
+ exp?: number;
1024
+ }
1025
+ /** Resolves a JWK-thumbprint keyid to a verification key, or undefined if unknown. */
1026
+ type KeyResolver = (keyId: string) => Promise<VerificationKey | undefined>;
1027
+
1028
+ /**
1029
+ * Cached Web Bot Auth directory client.
1030
+ *
1031
+ * Fetches the JWK sets of a **curated** set of trusted agent directories,
1032
+ * imports their keys into WebCrypto, and indexes them by JWK-thumbprint keyid
1033
+ * so signatures resolve in O(1) with zero network on the warm path.
1034
+ *
1035
+ * Security posture — the reason this is curated-only:
1036
+ * a request's own `Signature-Agent` header is **never** used to choose a fetch
1037
+ * target, so an attacker cannot make the middleware fetch an arbitrary URL
1038
+ * (no SSRF). Only the origins in {@link AgentVerifierOptions.directories} are
1039
+ * ever contacted. This mirrors the backend curation
1040
+ * (`backend/internal/services/signed_agents.go`).
1041
+ *
1042
+ * Freshness — stale-while-revalidate: once populated, an expired cache keeps
1043
+ * serving its keys while a background refresh runs, so verification latency is
1044
+ * never coupled to a directory fetch. A cold cache (never populated) blocks
1045
+ * once to fetch, then backs off briefly if every directory is unreachable so a
1046
+ * degraded network can't be hammered per request.
1047
+ */
1048
+
1049
+ /**
1050
+ * The default curated allowlist. These are the agents that sign production
1051
+ * traffic today; kept in lock-step with the backend's curated list.
1052
+ */
1053
+ declare const DEFAULT_SIGNED_AGENT_DIRECTORIES: SignedAgentDirectory[];
1054
+ interface DirectoryCacheOptions {
1055
+ directories: SignedAgentDirectory[];
1056
+ cacheTtlMs: number;
1057
+ fetchTimeoutMs: number;
1058
+ debug: boolean;
1059
+ fetchImpl: typeof fetch;
1060
+ }
1061
+ declare class DirectoryCache {
1062
+ private readonly opts;
1063
+ private keys;
1064
+ private refreshedAt;
1065
+ private nextColdRetryAt;
1066
+ private inflight;
1067
+ constructor(opts: DirectoryCacheOptions);
1068
+ /** Resolve a keyid to a verification key, fetching/refreshing as needed. */
1069
+ resolveKey: KeyResolver;
1070
+ /** Kick off a fetch without blocking — call at startup to warm the cache. */
1071
+ prime(): void;
1072
+ /** Number of keys currently cached (diagnostics/tests). */
1073
+ get size(): number;
1074
+ private ensureFresh;
1075
+ /** Re-fetch every directory. De-duplicated: concurrent callers share one run. */
1076
+ refresh(): Promise<void>;
1077
+ private doRefresh;
1078
+ private fetchDirectory;
1079
+ private debug;
1080
+ }
1081
+
594
1082
  /**
595
1083
  * Detection engine types.
596
1084
  *
@@ -1134,9 +1622,9 @@ declare class PoWManager {
1134
1622
  /** Difficulty scaled by IP reputation and request rate (4..6). */
1135
1623
  scaleDifficulty(siteKey: string, ip: string): number;
1136
1624
  /** Generate and store a signed challenge. */
1137
- generate(siteKey: string, ip: string, difficulty?: number): ChallengeData;
1625
+ generate(siteKey: string, ip: string, difficulty?: number): Promise<ChallengeData>;
1138
1626
  /** Verify a submitted solution. `signalsHash` binds it to the signals. */
1139
- verify(solution: PoWSolution, siteKey: string, signalsHash?: string | null): PoWVerification;
1627
+ verify(solution: PoWSolution, siteKey: string, signalsHash?: string | null): Promise<PoWVerification>;
1140
1628
  }
1141
1629
 
1142
1630
  /**
@@ -1167,9 +1655,9 @@ declare class TokenManager {
1167
1655
  private readonly store;
1168
1656
  constructor(options: TokenManagerOptions);
1169
1657
  /** Issue a signed, IP-bound token for a passing request. */
1170
- issue(ip: string, siteKey: string, score: number): string;
1658
+ issue(ip: string, siteKey: string, score: number): Promise<string>;
1171
1659
  /** Verify a token: signature, expiry, replay, and optional IP binding. */
1172
- verify(token: string, ip?: string | null): TokenVerification;
1660
+ verify(token: string, ip?: string | null): Promise<TokenVerification>;
1173
1661
  }
1174
1662
 
1175
1663
  /**
@@ -1202,18 +1690,18 @@ declare class Captcha {
1202
1690
  private readonly trustedJA4Headers;
1203
1691
  constructor(options?: CaptchaOptions);
1204
1692
  /** Issue a PoW challenge for the client to solve (difficulty auto-scaled). */
1205
- issueChallenge(siteKey: string, ip: string, difficulty?: number): ChallengeData;
1693
+ issueChallenge(siteKey: string, ip: string, difficulty?: number): Promise<ChallengeData>;
1206
1694
  /**
1207
1695
  * Verify a submission: checks the signals commitment, verifies PoW, scores the
1208
1696
  * signals, and issues a session token on success. Mirrors `runVerification`.
1209
1697
  */
1210
- verify(input: VerifyInput): VerifyResult;
1698
+ verify(input: VerifyInput): Promise<VerifyResult>;
1211
1699
  /** Invisible-mode scoring — same pipeline, returns a compact result + action. */
1212
1700
  score(input: VerifyInput & {
1213
1701
  action?: string;
1214
- }): ScoreResult;
1702
+ }): Promise<ScoreResult>;
1215
1703
  /** Verify a previously issued token (single-use, optionally IP-bound). */
1216
- verifyToken(token: string, ip?: string | null): TokenVerification;
1704
+ verifyToken(token: string, ip?: string | null): Promise<TokenVerification>;
1217
1705
  }
1218
1706
 
1219
1707
  /**
@@ -1272,4 +1760,4 @@ declare function createCaptchaEndpoints(options?: CaptchaEndpointsOptions): {
1272
1760
  };
1273
1761
  type CaptchaEndpoints = ReturnType<typeof createCaptchaEndpoints>;
1274
1762
 
1275
- export { type BehavioralSignals, Captcha, type CaptchaEndpoints, type CaptchaEndpointsOptions, type CaptchaHttpResponse, type CaptchaOptions, type CaptchaRequest, type CategoryScores, type ChallengeData, type ChallengeStore, DEFAULT_TRIPWIRE_PATHS, DEFAULT_WEIGHTS, type Detection, type DetectionContext, DetectionEngine, type DetectionEngineOptions, type EnvironmentalSignals, type FilterConfig, FilterRule, type FingerprintStore, type FormAnalysisSignals, type Honeytoken, type HoneytokenOptions, type IPEnrichmentData, InMemoryChallengeStore, InMemoryFingerprintStore, InMemoryRateLimiter, InMemoryTokenStore, type LocalAnalysis, PoWManager, type PoWManagerOptions, type PoWOutcome, type PoWSolution, type PoWVerification, type ProtectOptions, type ProtectResult, type RateLimitConfig, RateLimitRule, type RateLimiter, type Recommendation, type RequestMetadata, type Rule, type RuleContext, RuleEngine, type RuleEngineResult, type RuleResult, type SDKDetectionRequest, type SDKDetectionResponse, type ScoreResult, type Signals, type StoredChallenge, type TLSInfo, type TemporalSignals, type TextareaKeyboardStats, TokenManager, type TokenManagerOptions, type TokenStore, type TokenVerification, type TripwireConfig, TripwireRule, type Verdict, type VerifyInput, type VerifyResult, type ViolationEvent, WebDecoy, type WebDecoyConfig, calculateCategoryScores, calculateFinalScore, createCaptchaEndpoints, filter, honeytoken, isDatacenterIP, isMobileUA, parseUserAgent, rateLimit, recommend, resolveSecret, tripwire };
1763
+ export { type AgentCategory, type AgentRequestInput, type AgentStatus, type AgentVerdict, AgentVerifier, type AgentVerifierOptions, type BehavioralSignals, Captcha, type CaptchaEndpoints, type CaptchaEndpointsOptions, type CaptchaHttpResponse, type CaptchaOptions, type CaptchaRequest, type CategoryScores, type ChallengeData, type ChallengeStore, DEFAULT_SIGNED_AGENT_DIRECTORIES, DEFAULT_TRIPWIRE_PATHS, DEFAULT_WEIGHTS, type Detection, type DetectionContext, DetectionEngine, type DetectionEngineOptions, DirectoryCache, EDGE_CLASS_HEADER, EDGE_CLEARANCE_HEADER, type EdgeClass, type EdgeVerdict, type EnvironmentalSignals, type FilterConfig, FilterRule, type FingerprintStore, type FormAnalysisSignals, type Honeytoken, type HoneytokenOptions, type IPEnrichmentData, InMemoryChallengeStore, InMemoryFingerprintStore, InMemoryRateLimiter, InMemoryTokenStore, type LocalAnalysis, PoWManager, type PoWManagerOptions, type PoWOutcome, type PoWSolution, type PoWVerification, type ProtectOptions, type ProtectResult, type RateLimitConfig, RateLimitRule, type RateLimiter, type Recommendation, type RequestMetadata, type Rule, type RuleContext, RuleEngine, type RuleEngineResult, type RuleResult, type SDKDetectionRequest, type SDKDetectionResponse, type ScoreResult, type Signals, type SignedAgentDirectory, type StoredChallenge, type TLSInfo, type TemporalSignals, type TextareaKeyboardStats, TokenManager, type TokenManagerOptions, type TokenStore, type TokenVerification, type TripwireConfig, TripwireRule, type Verdict, type VerifyInput, type VerifyResult, type ViolationEvent, type WebBotAuthConfig, WebBotAuthRule, WebDecoy, type WebDecoyConfig, calculateCategoryScores, calculateFinalScore, createAgentVerifier, createCaptchaEndpoints, filter, honeytoken, isDatacenterIP, isMobileUA, parseUserAgent, rateLimit, readEdgeVerdict, recommend, resolveSecret, tripwire, webBotAuth };