@webdecoy/node 0.6.0 → 0.8.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,105 +1,3 @@
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
1
  /**
104
2
  * Web Bot Auth verification — public types.
105
3
  *
@@ -219,6 +117,108 @@ type AgentRequestInput = Request | {
219
117
  headers: Headers | Record<string, string>;
220
118
  };
221
119
 
120
+ /**
121
+ * The edge validator's verdict, as the origin sees it (#481).
122
+ *
123
+ * WHY THIS MODULE EXISTS
124
+ *
125
+ * The Cloudflare clearance worker has set `x-wd-clearance` on every forwarded
126
+ * request since the validator shipped, and nothing has ever read it. Grepping the
127
+ * header across the monorepo, this SDK and the WordPress plugin returned only the
128
+ * worker that writes it, its own tests, and one documentation page. We shipped a
129
+ * tag no customer could act on, then documented it as "watch the header in your
130
+ * logs."
131
+ *
132
+ * That gap matters more than it sounds. On a scoped route the gate's only options
133
+ * were pass or challenge, and a challenge on public content is a 403 to every
134
+ * client that cannot run JavaScript — search crawlers included. Reading the tag
135
+ * gives the application a third option it owns: log it, meter it, skip an
136
+ * expensive query, serve something cheaper. That is the first "yes" a cautious
137
+ * operator can give.
138
+ *
139
+ * WHAT IT IS NOT
140
+ *
141
+ * These values are advisory context, not authentication. They are only meaningful
142
+ * for requests that actually passed through the edge validator, and the validator
143
+ * strips inbound copies precisely so that the origin can attribute them to us.
144
+ * A request that reaches the origin WITHOUT passing through the proxy — straight
145
+ * to the origin IP, or a route that does not match — can carry anything. Treat
146
+ * `present: false` as "no information", never as "not a bot", and keep the origin
147
+ * unreachable except through the proxy if you intend to branch on this.
148
+ */
149
+ /** Header the edge validator uses for its clearance verdict. */
150
+ declare const EDGE_CLEARANCE_HEADER = "x-wd-clearance";
151
+ /** Header the edge validator uses for the sensor's client classification. */
152
+ declare const EDGE_CLASS_HEADER = "x-wd-class";
153
+ /**
154
+ * What the edge sensor concluded the client is.
155
+ *
156
+ * - `verified` — an identity something other than the client has attested
157
+ * (Cloudflare's verified-bot signal). **Never degrade these.** This is
158
+ * Googlebot and friends, and quietly serving them less is how a customer loses
159
+ * search presence and blames you six weeks later.
160
+ * - `crawler` — self-declares as a crawler, unproven. Real-but-unverified
161
+ * crawlers and forged ones both land here.
162
+ * - `script` — an HTTP client library, a Chromium user agent sending no client
163
+ * hints, or no user agent at all. Not a browser.
164
+ * - `browser` — nothing that distinguishes a non-human fired. A statement about
165
+ * our signals, not a certificate.
166
+ */
167
+ type EdgeClass = 'verified' | 'crawler' | 'script' | 'browser';
168
+ /**
169
+ * The edge's annotations on one request, typed.
170
+ *
171
+ * Every field is optional except `present`, because the edge validator may not be
172
+ * in front of this request at all — and the difference between "the edge said
173
+ * browser" and "there is no edge here" is the difference between a safe
174
+ * optimisation and a security hole.
175
+ */
176
+ interface EdgeVerdict {
177
+ /**
178
+ * True when the edge validator annotated this request. False means no
179
+ * information — not "human", not "safe".
180
+ */
181
+ present: boolean;
182
+ /**
183
+ * The clearance verdict, e.g. `valid`, `missing`, `verified-bot`,
184
+ * `signed-agent`, `machine`, `insufficient-trust`. Free-form on purpose: the
185
+ * validator gains labels faster than an SDK release can enumerate them, and an
186
+ * unknown label must not become `undefined`.
187
+ */
188
+ clearance?: string;
189
+ /** The sensor's classification, when it classified this request. */
190
+ class?: EdgeClass;
191
+ /** `class === 'verified'`. Convenience so callers need no string literals. */
192
+ isVerified: boolean;
193
+ /** `class === 'crawler'`. */
194
+ isCrawler: boolean;
195
+ /** `class === 'script'`. */
196
+ isScript: boolean;
197
+ /** `class === 'browser'`. */
198
+ isBrowser: boolean;
199
+ /**
200
+ * True for a class that is not a browser and is not attested — `script` or
201
+ * `crawler`.
202
+ *
203
+ * This is the predicate most applications actually want, and it deliberately
204
+ * excludes `verified`: the common intent is "cheapen this response", and the one
205
+ * population you must never cheapen for is the one whose identity was proven.
206
+ */
207
+ isUnattestedNonBrowser: boolean;
208
+ }
209
+ /**
210
+ * Read the edge validator's annotations out of a request's headers.
211
+ *
212
+ * Accepts the header bag the SDK already carries on `RequestMetadata` — lowercase
213
+ * keys — and tolerates mixed case, since adapters differ on normalisation.
214
+ *
215
+ * An unrecognised class value is dropped rather than passed through. The set is
216
+ * closed and small; a value outside it means either a version skew or something
217
+ * that is not our worker, and in both cases silence beats a value a caller might
218
+ * branch on.
219
+ */
220
+ declare function readEdgeVerdict(headers: Record<string, string> | undefined): EdgeVerdict;
221
+
222
222
  /**
223
223
  * Rules Engine Types
224
224
  * Core interfaces for the WebDecoy rules engine
@@ -624,11 +624,6 @@ declare class WebDecoyClient {
624
624
  validateAPIKey(): Promise<boolean>;
625
625
  }
626
626
 
627
- /**
628
- * Web Decoy SDK
629
- * Main SDK class for bot detection and protection
630
- */
631
-
632
627
  declare class WebDecoy {
633
628
  private client;
634
629
  private config;
@@ -651,6 +646,15 @@ declare class WebDecoy {
651
646
  * webBotAuth() rules are present.
652
647
  */
653
648
  evaluateRulesAsync(metadata: RequestMetadata): Promise<RuleEngineResult | null>;
649
+ /**
650
+ * Register a rule after construction.
651
+ *
652
+ * For signals whose definition is not available synchronously — the site
653
+ * honeytoken's path is derived by async HMAC, so the adapter arms it once the
654
+ * derivation settles. Creates the engine if there was none, so an SDK built
655
+ * with `rules: []` can still gain one.
656
+ */
657
+ addRule(rule: Rule): void;
654
658
  /** Build the base (synchronous) rule context from request metadata. */
655
659
  private buildContext;
656
660
  /**
@@ -742,6 +746,14 @@ declare class WebDecoy {
742
746
  declare class RuleEngine {
743
747
  private rules;
744
748
  constructor(rules: Rule[]);
749
+ /**
750
+ * Append a rule after construction.
751
+ *
752
+ * Exists for signals that cannot be known synchronously at construction —
753
+ * currently the site honeytoken (#482), whose path is derived by async HMAC.
754
+ * Evaluation order is append order, matching the constructor.
755
+ */
756
+ add(rule: Rule): void;
745
757
  /**
746
758
  * Evaluate all rules against the request context.
747
759
  * First DENY or THROTTLE result wins. Violations are recorded for all non-ALLOW results.
@@ -912,6 +924,114 @@ interface Honeytoken {
912
924
  */
913
925
  declare function honeytoken(options?: HoneytokenOptions): Honeytoken;
914
926
 
927
+ /**
928
+ * Site honeytoken — a stable, derivable trap the adapters can inject for you
929
+ * (#482).
930
+ *
931
+ * WHY THIS EXISTS ALONGSIDE honeytoken()
932
+ *
933
+ * `honeytoken()` mints a RANDOM path per call. That is fine when a developer
934
+ * holds the returned object and wires both halves themselves, and useless for
935
+ * automatic injection: the adapter would advertise a different path on every
936
+ * request, and on a second replica the tripwire armed there would not match the
937
+ * link served here. A crawler that followed the bait would trip nothing.
938
+ *
939
+ * So the token is DERIVED, exactly as the WordPress plugin derives it: HMAC of a
940
+ * label under a per-site secret. Every process with the same secret computes the
941
+ * same path without coordinating, and nothing extra is stored.
942
+ *
943
+ * WHY THIS MATTERS AT ALL
944
+ *
945
+ * A trap hit is the only detection in this product that needs no score, no
946
+ * JavaScript, no fingerprint and no IP — the client asked for a path that exists
947
+ * nowhere and is linked only from an element no human can see.
948
+ *
949
+ * That is not a stylistic preference, it is arithmetic. The unified score weights
950
+ * honeypot hits at 38% and user-agent at 1%, because a user agent is trivially
951
+ * spoofed. Measured against production: every `sdk` detection ever recorded
952
+ * scored 0, while `sdk_tripwire` averaged 52.5. And `sdk_tripwire` had FOUR rows
953
+ * in total, because the SDK generated a honeytoken and then asked the developer
954
+ * to place the link. WordPress injects it itself and has coverage.
955
+ */
956
+ /** Base path for honeytoken tripwires. Mirrors the WordPress plugin. */
957
+ declare const HONEYTOKEN_BASE_PATH = "/__wd";
958
+ interface SiteHoneytokenOptions {
959
+ /**
960
+ * Secret the token is derived from. Must be stable across every process
961
+ * serving the site, or replicas advertise paths each other has not armed.
962
+ * The SDK passes the API key, which is already exactly that.
963
+ */
964
+ secret: string;
965
+ /** Base path. Default `/__wd`. */
966
+ basePath?: string;
967
+ /**
968
+ * Rotate the token daily, keeping yesterday's armed as a grace window.
969
+ *
970
+ * Off by default. Rotation is only safe when every armed path is served from
971
+ * the same clock, and a page cached by a CDN can outlive the grace window —
972
+ * at which point the trap silently stops catching anything, which is worse
973
+ * than a static path a determined attacker could eventually notice.
974
+ */
975
+ rotate?: boolean;
976
+ /** Visually-hidden link text. Default `.`. */
977
+ text?: string;
978
+ }
979
+ /**
980
+ * The link as data rather than markup, so a JSX or template caller can render an
981
+ * anchor directly instead of reaching for `dangerouslySetInnerHTML`. Same
982
+ * attributes as `linkHtml`, which stays for string-templating environments.
983
+ */
984
+ interface HoneytokenLinkProps {
985
+ href: string;
986
+ rel: string;
987
+ tabIndex: number;
988
+ 'aria-hidden': 'true';
989
+ style: Record<string, string>;
990
+ text: string;
991
+ }
992
+ interface SiteHoneytoken {
993
+ /** The path advertised in the injected link. */
994
+ primaryPath: string;
995
+ /**
996
+ * Every path that must be armed as a tripwire right now — today and
997
+ * yesterday when rotating, so a crawler part-way through a crawl still trips.
998
+ */
999
+ activePaths: string[];
1000
+ /** The hidden `<a>` to inject, for string-templating environments. */
1001
+ linkHtml: string;
1002
+ /** The same link as props, for JSX — avoids innerHTML entirely. */
1003
+ linkProps: HoneytokenLinkProps;
1004
+ }
1005
+ /**
1006
+ * Derive the site's honeytoken.
1007
+ *
1008
+ * Async because the derivation is WebCrypto HMAC, which keeps this usable on
1009
+ * edge runtimes where `node:crypto` does not exist. Callers are expected to
1010
+ * resolve it once and reuse the result.
1011
+ */
1012
+ declare function siteHoneytoken(options: SiteHoneytokenOptions): Promise<SiteHoneytoken>;
1013
+ /**
1014
+ * Insert the hidden link into an HTML document.
1015
+ *
1016
+ * Returns the input unchanged when there is nowhere sensible to put it, which is
1017
+ * the correct outcome for a fragment, a JSON body mislabelled as HTML, or a
1018
+ * document that already carries the link.
1019
+ *
1020
+ * Injection targets `</body>` and falls back to `</html>`. It deliberately does
1021
+ * NOT append to arbitrary markup: putting an anchor after `</html>` is invalid,
1022
+ * and some parsers relocate it in ways that could make it visible — a visible
1023
+ * trap catches customers, not crawlers.
1024
+ */
1025
+ declare function injectHoneytokenLink(html: string, linkHtml: string): string;
1026
+ /**
1027
+ * Whether a response's content type is a full HTML document we may rewrite.
1028
+ *
1029
+ * Anything else is left alone: JSON, streams, images, downloads. Injecting an
1030
+ * anchor into a JSON body would corrupt it, and corrupting a customer's API
1031
+ * response is a far worse failure than a missed detection.
1032
+ */
1033
+ declare function isInjectableHtml(contentType: string | undefined | null): boolean;
1034
+
915
1035
  /**
916
1036
  * Rules Engine - Barrel exports
917
1037
  */
@@ -1760,4 +1880,4 @@ declare function createCaptchaEndpoints(options?: CaptchaEndpointsOptions): {
1760
1880
  };
1761
1881
  type CaptchaEndpoints = ReturnType<typeof createCaptchaEndpoints>;
1762
1882
 
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 };
1883
+ 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, HONEYTOKEN_BASE_PATH, type Honeytoken, type HoneytokenLinkProps, 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 SiteHoneytoken, type SiteHoneytokenOptions, 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, injectHoneytokenLink, isDatacenterIP, isInjectableHtml, isMobileUA, parseUserAgent, rateLimit, readEdgeVerdict, recommend, resolveSecret, siteHoneytoken, tripwire, webBotAuth };