@webdecoy/node 0.7.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.mts 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 };
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 };
package/dist/index.js CHANGED
@@ -30,6 +30,7 @@ __export(index_exports, {
30
30
  EDGE_CLASS_HEADER: () => EDGE_CLASS_HEADER,
31
31
  EDGE_CLEARANCE_HEADER: () => EDGE_CLEARANCE_HEADER,
32
32
  FilterRule: () => FilterRule,
33
+ HONEYTOKEN_BASE_PATH: () => HONEYTOKEN_BASE_PATH,
33
34
  InMemoryChallengeStore: () => InMemoryChallengeStore,
34
35
  InMemoryFingerprintStore: () => InMemoryFingerprintStore,
35
36
  InMemoryRateLimiter: () => InMemoryRateLimiter2,
@@ -47,13 +48,16 @@ __export(index_exports, {
47
48
  createCaptchaEndpoints: () => createCaptchaEndpoints,
48
49
  filter: () => filter,
49
50
  honeytoken: () => honeytoken,
51
+ injectHoneytokenLink: () => injectHoneytokenLink,
50
52
  isDatacenterIP: () => isDatacenterIP2,
53
+ isInjectableHtml: () => isInjectableHtml,
51
54
  isMobileUA: () => isMobileUA,
52
55
  parseUserAgent: () => parseUserAgent,
53
56
  rateLimit: () => rateLimit,
54
57
  readEdgeVerdict: () => readEdgeVerdict,
55
58
  recommend: () => recommend,
56
59
  resolveSecret: () => resolveSecret,
60
+ siteHoneytoken: () => siteHoneytoken,
57
61
  tripwire: () => tripwire,
58
62
  webBotAuth: () => webBotAuth
59
63
  });
@@ -351,6 +355,16 @@ var RuleEngine = class {
351
355
  constructor(rules) {
352
356
  this.rules = rules;
353
357
  }
358
+ /**
359
+ * Append a rule after construction.
360
+ *
361
+ * Exists for signals that cannot be known synchronously at construction —
362
+ * currently the site honeytoken (#482), whose path is derived by async HMAC.
363
+ * Evaluation order is append order, matching the constructor.
364
+ */
365
+ add(rule) {
366
+ this.rules.push(rule);
367
+ }
354
368
  /**
355
369
  * Evaluate all rules against the request context.
356
370
  * First DENY or THROTTLE result wins. Violations are recorded for all non-ALLOW results.
@@ -1178,6 +1192,78 @@ function honeytoken(options = {}) {
1178
1192
  return { path, linkHtml };
1179
1193
  }
1180
1194
 
1195
+ // src/rules/honeytoken-site.ts
1196
+ var HONEYTOKEN_BASE_PATH = "/__wd";
1197
+ var TOKEN_LEN = 12;
1198
+ function utcDay(offsetDays = 0) {
1199
+ const d = new Date(Date.now() + offsetDays * 864e5);
1200
+ return d.toISOString().slice(0, 10);
1201
+ }
1202
+ function escapeHtml(v) {
1203
+ return v.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1204
+ }
1205
+ function linkFor(path, text) {
1206
+ text = escapeHtml(text);
1207
+ return `<a href="${path}" aria-hidden="true" tabindex="-1" rel="nofollow noindex" style="position:absolute;left:-9999px;top:auto;width:1px;height:1px;overflow:hidden">${text}</a>`;
1208
+ }
1209
+ var HIDDEN_STYLE = {
1210
+ position: "absolute",
1211
+ left: "-9999px",
1212
+ top: "auto",
1213
+ width: "1px",
1214
+ height: "1px",
1215
+ overflow: "hidden"
1216
+ };
1217
+ function propsFor(path, text) {
1218
+ return {
1219
+ href: path,
1220
+ rel: "nofollow noindex",
1221
+ tabIndex: -1,
1222
+ "aria-hidden": "true",
1223
+ style: HIDDEN_STYLE,
1224
+ text
1225
+ };
1226
+ }
1227
+ async function siteHoneytoken(options) {
1228
+ const base = (options.basePath ?? HONEYTOKEN_BASE_PATH).replace(/\/+$/, "");
1229
+ const text = options.text ?? ".";
1230
+ const derive = async (label) => `${base}/${(await hmacSha256Hex(options.secret, label)).slice(0, TOKEN_LEN)}`;
1231
+ if (!options.rotate) {
1232
+ const path = await derive("stable");
1233
+ return {
1234
+ primaryPath: path,
1235
+ activePaths: [path],
1236
+ linkHtml: linkFor(path, text),
1237
+ linkProps: propsFor(path, text)
1238
+ };
1239
+ }
1240
+ const today = await derive(`day:${utcDay(0)}`);
1241
+ const yesterday = await derive(`day:${utcDay(-1)}`);
1242
+ return {
1243
+ primaryPath: today,
1244
+ // Yesterday stays armed so a crawler that read the page before midnight and
1245
+ // follows the link after it still trips.
1246
+ activePaths: Array.from(/* @__PURE__ */ new Set([today, yesterday])),
1247
+ linkHtml: linkFor(today, text),
1248
+ linkProps: propsFor(today, text)
1249
+ };
1250
+ }
1251
+ function injectHoneytokenLink(html, linkHtml) {
1252
+ if (!html || html.includes(linkHtml)) return html;
1253
+ const lower = html.toLowerCase();
1254
+ for (const close of ["</body>", "</html>"]) {
1255
+ const at = lower.lastIndexOf(close);
1256
+ if (at !== -1) {
1257
+ return html.slice(0, at) + linkHtml + html.slice(at);
1258
+ }
1259
+ }
1260
+ return html;
1261
+ }
1262
+ function isInjectableHtml(contentType) {
1263
+ if (!contentType) return false;
1264
+ return contentType.toLowerCase().split(";")[0].trim() === "text/html";
1265
+ }
1266
+
1181
1267
  // src/rules/index.ts
1182
1268
  function rateLimit(config) {
1183
1269
  return new RateLimitRule(config);
@@ -2013,6 +2099,23 @@ var WebDecoy = class {
2013
2099
  const context = await this.buildAsyncContext(metadata);
2014
2100
  return this.runRules(context);
2015
2101
  }
2102
+ /**
2103
+ * Register a rule after construction.
2104
+ *
2105
+ * For signals whose definition is not available synchronously — the site
2106
+ * honeytoken's path is derived by async HMAC, so the adapter arms it once the
2107
+ * derivation settles. Creates the engine if there was none, so an SDK built
2108
+ * with `rules: []` can still gain one.
2109
+ */
2110
+ addRule(rule) {
2111
+ if (!this.ruleEngine) {
2112
+ this.ruleEngine = new RuleEngine([rule]);
2113
+ } else {
2114
+ this.ruleEngine.add(rule);
2115
+ }
2116
+ if (rule.name.startsWith("filter:")) this._hasFilterRules = true;
2117
+ if (rule.name === "web-bot-auth") this._hasAgentRules = true;
2118
+ }
2016
2119
  /** Build the base (synchronous) rule context from request metadata. */
2017
2120
  buildContext(metadata) {
2018
2121
  return {
@@ -4281,6 +4384,7 @@ function createCaptchaEndpoints(options = {}) {
4281
4384
  EDGE_CLASS_HEADER,
4282
4385
  EDGE_CLEARANCE_HEADER,
4283
4386
  FilterRule,
4387
+ HONEYTOKEN_BASE_PATH,
4284
4388
  InMemoryChallengeStore,
4285
4389
  InMemoryFingerprintStore,
4286
4390
  InMemoryRateLimiter,
@@ -4298,13 +4402,16 @@ function createCaptchaEndpoints(options = {}) {
4298
4402
  createCaptchaEndpoints,
4299
4403
  filter,
4300
4404
  honeytoken,
4405
+ injectHoneytokenLink,
4301
4406
  isDatacenterIP,
4407
+ isInjectableHtml,
4302
4408
  isMobileUA,
4303
4409
  parseUserAgent,
4304
4410
  rateLimit,
4305
4411
  readEdgeVerdict,
4306
4412
  recommend,
4307
4413
  resolveSecret,
4414
+ siteHoneytoken,
4308
4415
  tripwire,
4309
4416
  webBotAuth
4310
4417
  });
package/dist/index.mjs CHANGED
@@ -290,6 +290,16 @@ var RuleEngine = class {
290
290
  constructor(rules) {
291
291
  this.rules = rules;
292
292
  }
293
+ /**
294
+ * Append a rule after construction.
295
+ *
296
+ * Exists for signals that cannot be known synchronously at construction —
297
+ * currently the site honeytoken (#482), whose path is derived by async HMAC.
298
+ * Evaluation order is append order, matching the constructor.
299
+ */
300
+ add(rule) {
301
+ this.rules.push(rule);
302
+ }
293
303
  /**
294
304
  * Evaluate all rules against the request context.
295
305
  * First DENY or THROTTLE result wins. Violations are recorded for all non-ALLOW results.
@@ -1117,6 +1127,78 @@ function honeytoken(options = {}) {
1117
1127
  return { path, linkHtml };
1118
1128
  }
1119
1129
 
1130
+ // src/rules/honeytoken-site.ts
1131
+ var HONEYTOKEN_BASE_PATH = "/__wd";
1132
+ var TOKEN_LEN = 12;
1133
+ function utcDay(offsetDays = 0) {
1134
+ const d = new Date(Date.now() + offsetDays * 864e5);
1135
+ return d.toISOString().slice(0, 10);
1136
+ }
1137
+ function escapeHtml(v) {
1138
+ return v.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1139
+ }
1140
+ function linkFor(path, text) {
1141
+ text = escapeHtml(text);
1142
+ return `<a href="${path}" aria-hidden="true" tabindex="-1" rel="nofollow noindex" style="position:absolute;left:-9999px;top:auto;width:1px;height:1px;overflow:hidden">${text}</a>`;
1143
+ }
1144
+ var HIDDEN_STYLE = {
1145
+ position: "absolute",
1146
+ left: "-9999px",
1147
+ top: "auto",
1148
+ width: "1px",
1149
+ height: "1px",
1150
+ overflow: "hidden"
1151
+ };
1152
+ function propsFor(path, text) {
1153
+ return {
1154
+ href: path,
1155
+ rel: "nofollow noindex",
1156
+ tabIndex: -1,
1157
+ "aria-hidden": "true",
1158
+ style: HIDDEN_STYLE,
1159
+ text
1160
+ };
1161
+ }
1162
+ async function siteHoneytoken(options) {
1163
+ const base = (options.basePath ?? HONEYTOKEN_BASE_PATH).replace(/\/+$/, "");
1164
+ const text = options.text ?? ".";
1165
+ const derive = async (label) => `${base}/${(await hmacSha256Hex(options.secret, label)).slice(0, TOKEN_LEN)}`;
1166
+ if (!options.rotate) {
1167
+ const path = await derive("stable");
1168
+ return {
1169
+ primaryPath: path,
1170
+ activePaths: [path],
1171
+ linkHtml: linkFor(path, text),
1172
+ linkProps: propsFor(path, text)
1173
+ };
1174
+ }
1175
+ const today = await derive(`day:${utcDay(0)}`);
1176
+ const yesterday = await derive(`day:${utcDay(-1)}`);
1177
+ return {
1178
+ primaryPath: today,
1179
+ // Yesterday stays armed so a crawler that read the page before midnight and
1180
+ // follows the link after it still trips.
1181
+ activePaths: Array.from(/* @__PURE__ */ new Set([today, yesterday])),
1182
+ linkHtml: linkFor(today, text),
1183
+ linkProps: propsFor(today, text)
1184
+ };
1185
+ }
1186
+ function injectHoneytokenLink(html, linkHtml) {
1187
+ if (!html || html.includes(linkHtml)) return html;
1188
+ const lower = html.toLowerCase();
1189
+ for (const close of ["</body>", "</html>"]) {
1190
+ const at = lower.lastIndexOf(close);
1191
+ if (at !== -1) {
1192
+ return html.slice(0, at) + linkHtml + html.slice(at);
1193
+ }
1194
+ }
1195
+ return html;
1196
+ }
1197
+ function isInjectableHtml(contentType) {
1198
+ if (!contentType) return false;
1199
+ return contentType.toLowerCase().split(";")[0].trim() === "text/html";
1200
+ }
1201
+
1120
1202
  // src/rules/index.ts
1121
1203
  function rateLimit(config) {
1122
1204
  return new RateLimitRule(config);
@@ -1952,6 +2034,23 @@ var WebDecoy = class {
1952
2034
  const context = await this.buildAsyncContext(metadata);
1953
2035
  return this.runRules(context);
1954
2036
  }
2037
+ /**
2038
+ * Register a rule after construction.
2039
+ *
2040
+ * For signals whose definition is not available synchronously — the site
2041
+ * honeytoken's path is derived by async HMAC, so the adapter arms it once the
2042
+ * derivation settles. Creates the engine if there was none, so an SDK built
2043
+ * with `rules: []` can still gain one.
2044
+ */
2045
+ addRule(rule) {
2046
+ if (!this.ruleEngine) {
2047
+ this.ruleEngine = new RuleEngine([rule]);
2048
+ } else {
2049
+ this.ruleEngine.add(rule);
2050
+ }
2051
+ if (rule.name.startsWith("filter:")) this._hasFilterRules = true;
2052
+ if (rule.name === "web-bot-auth") this._hasAgentRules = true;
2053
+ }
1955
2054
  /** Build the base (synchronous) rule context from request metadata. */
1956
2055
  buildContext(metadata) {
1957
2056
  return {
@@ -4219,6 +4318,7 @@ export {
4219
4318
  EDGE_CLASS_HEADER,
4220
4319
  EDGE_CLEARANCE_HEADER,
4221
4320
  FilterRule,
4321
+ HONEYTOKEN_BASE_PATH,
4222
4322
  InMemoryChallengeStore,
4223
4323
  InMemoryFingerprintStore,
4224
4324
  InMemoryRateLimiter2 as InMemoryRateLimiter,
@@ -4236,13 +4336,16 @@ export {
4236
4336
  createCaptchaEndpoints,
4237
4337
  filter,
4238
4338
  honeytoken,
4339
+ injectHoneytokenLink,
4239
4340
  isDatacenterIP2 as isDatacenterIP,
4341
+ isInjectableHtml,
4240
4342
  isMobileUA,
4241
4343
  parseUserAgent,
4242
4344
  rateLimit,
4243
4345
  readEdgeVerdict,
4244
4346
  recommend,
4245
4347
  resolveSecret,
4348
+ siteHoneytoken,
4246
4349
  tripwire,
4247
4350
  webBotAuth
4248
4351
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webdecoy/node",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Web Decoy SDK for Node.js - Bot detection with TLS fingerprinting",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",