@webdecoy/node 0.18.3 → 0.18.5

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.
@@ -2503,8 +2503,22 @@ function isTestTriggerUserAgent(userAgent) {
2503
2503
  }
2504
2504
 
2505
2505
  // src/client.ts
2506
+ var WebDecoyUnavailableError = class extends Error {
2507
+ constructor(retryAt) {
2508
+ super("WebDecoy is temporarily unavailable; requests are paused");
2509
+ this.retryAt = retryAt;
2510
+ this.name = "WebDecoyUnavailableError";
2511
+ Object.setPrototypeOf(this, new.target.prototype);
2512
+ }
2513
+ };
2514
+ var PAUSE_BASE_MS = 1e3;
2515
+ var PAUSE_MAX_MS = 6e4;
2516
+ var RETRY_AFTER_MAX_MS = 3e5;
2506
2517
  var WebDecoyClient = class {
2507
2518
  constructor(config) {
2519
+ /** No request is made before this time (epoch ms). */
2520
+ this.pausedUntil = 0;
2521
+ this.consecutiveFailures = 0;
2508
2522
  this.config = config;
2509
2523
  this.baseUrl = config.apiUrl.replace(/\/+$/, "");
2510
2524
  this.headers = {
@@ -2518,7 +2532,30 @@ var WebDecoyClient = class {
2518
2532
  );
2519
2533
  }
2520
2534
  }
2535
+ /**
2536
+ * Whether a request would be attempted right now. False while paused after
2537
+ * WebDecoy refused work (429, 5xx) or did not answer, so a caller with
2538
+ * something to keep (a buffer) can hold it rather than lose it.
2539
+ */
2540
+ isAvailable(now = Date.now()) {
2541
+ return now >= this.pausedUntil;
2542
+ }
2543
+ /**
2544
+ * Pause every call to WebDecoy after a refusal or no answer: the Retry-After
2545
+ * when one was given, otherwise 1s doubling per consecutive failure up to
2546
+ * 60s. Without this, each request during an outage waited out the full
2547
+ * timeout in the caller's request path.
2548
+ */
2549
+ pause(retryAfter) {
2550
+ const seconds = retryAfter ? Number(retryAfter) : NaN;
2551
+ const ms = Number.isFinite(seconds) && seconds > 0 ? Math.min(Math.max(seconds * 1e3, PAUSE_BASE_MS), RETRY_AFTER_MAX_MS) : Math.min(PAUSE_BASE_MS * 2 ** this.consecutiveFailures, PAUSE_MAX_MS);
2552
+ this.consecutiveFailures++;
2553
+ this.pausedUntil = Date.now() + ms;
2554
+ }
2521
2555
  async request(method, path, body) {
2556
+ if (!this.isAvailable()) {
2557
+ throw new WebDecoyUnavailableError(this.pausedUntil);
2558
+ }
2522
2559
  const controller = new AbortController();
2523
2560
  const timer = setTimeout(() => controller.abort(), this.config.timeout);
2524
2561
  if (typeof timer.unref === "function") {
@@ -2546,8 +2583,14 @@ var WebDecoyClient = class {
2546
2583
  if (this.config.debug) {
2547
2584
  console.log("[WebDecoy] Response:", { status: response.status, data });
2548
2585
  }
2586
+ if (response.status === 429 || response.status >= 500) {
2587
+ this.pause(response.headers.get("retry-after"));
2588
+ } else {
2589
+ this.consecutiveFailures = 0;
2590
+ }
2549
2591
  return { status: response.status, data };
2550
2592
  } catch (error) {
2593
+ this.pause(null);
2551
2594
  if (this.config.debug) {
2552
2595
  console.error("[WebDecoy] Error:", {
2553
2596
  message: error instanceof Error ? error.message : String(error)
@@ -2613,7 +2656,7 @@ var WebDecoyClient = class {
2613
2656
  async sendAIReferrals(batch) {
2614
2657
  try {
2615
2658
  const response = await this.request("POST", "/api/v1/sdk/ai-referrals", batch);
2616
- return response.status < 500;
2659
+ return response.status < 500 && response.status !== 429;
2617
2660
  } catch (error) {
2618
2661
  if (this.config.debug) {
2619
2662
  console.error("[WebDecoy] Failed to send AI referrals:", error);
@@ -2804,6 +2847,7 @@ function analyzeRequest(metadata) {
2804
2847
  }
2805
2848
 
2806
2849
  // src/violation-reporter.ts
2850
+ var MAX_BUFFERED_VIOLATIONS = 1e3;
2807
2851
  var ViolationReporter = class {
2808
2852
  constructor(client, config = {}) {
2809
2853
  this.buffer = [];
@@ -2822,6 +2866,9 @@ var ViolationReporter = class {
2822
2866
  */
2823
2867
  report(violations) {
2824
2868
  this.buffer.push(...violations);
2869
+ if (this.buffer.length > MAX_BUFFERED_VIOLATIONS) {
2870
+ this.buffer.splice(0, this.buffer.length - MAX_BUFFERED_VIOLATIONS);
2871
+ }
2825
2872
  if (this.buffer.length >= this.maxBufferSize) {
2826
2873
  this.flush().catch(() => {
2827
2874
  });
@@ -2831,7 +2878,7 @@ var ViolationReporter = class {
2831
2878
  * Flush buffered violations to the backend
2832
2879
  */
2833
2880
  async flush() {
2834
- if (this.flushing || this.buffer.length === 0) return;
2881
+ if (this.flushing || this.buffer.length === 0 || !this.client.isAvailable()) return;
2835
2882
  this.flushing = true;
2836
2883
  const events = this.buffer.splice(0, this.buffer.length);
2837
2884
  try {
@@ -2966,8 +3013,9 @@ ${landing}`;
2966
3013
  if (entry) {
2967
3014
  entry.count++;
2968
3015
  } else {
3016
+ if (this.pending && this.counts.size >= MAX_ENTRIES) return;
2969
3017
  this.counts.set(key, { platform, path: landing, count: 1 });
2970
- if (this.counts.size >= MAX_ENTRIES) void this.flush();
3018
+ if (this.counts.size >= MAX_ENTRIES && !this.pending) void this.flush();
2971
3019
  }
2972
3020
  } catch {
2973
3021
  }
@@ -2997,6 +3045,7 @@ ${landing}`;
2997
3045
  };
2998
3046
 
2999
3047
  // src/ip-enrichment.ts
3048
+ var MAX_ENRICHMENT_ENTRIES = 1e4;
3000
3049
  var IPEnrichmentClient = class {
3001
3050
  constructor(client, ttlMs = 36e5) {
3002
3051
  this.cache = /* @__PURE__ */ new Map();
@@ -3029,10 +3078,15 @@ var IPEnrichmentClient = class {
3029
3078
  async fetchAndCache(ip) {
3030
3079
  const data = await this.client.getIPEnrichment(ip);
3031
3080
  if (data) {
3081
+ this.cache.delete(ip);
3032
3082
  this.cache.set(ip, {
3033
3083
  data,
3034
3084
  expiresAt: Date.now() + this.ttlMs
3035
3085
  });
3086
+ if (this.cache.size > MAX_ENRICHMENT_ENTRIES) {
3087
+ const oldest = this.cache.keys().next();
3088
+ if (!oldest.done) this.cache.delete(oldest.value);
3089
+ }
3036
3090
  }
3037
3091
  return data;
3038
3092
  }
@@ -3455,7 +3509,8 @@ var WebDecoy = class {
3455
3509
  if (this.decisionCache) this.decisionCache.set(key, decision);
3456
3510
  return decision;
3457
3511
  } catch (error) {
3458
- this.log.error("Protection error", {
3512
+ const log = error instanceof WebDecoyUnavailableError ? this.log.debug.bind(this.log) : this.log.error.bind(this.log);
3513
+ log("Protection error", {
3459
3514
  error: error instanceof Error ? error.message : String(error)
3460
3515
  });
3461
3516
  return new Decision({
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { R as Rule, a as RuleContext, b as RuleResult, c as RuleEngineResult, d as RateLimitConfig, F as FilterConfig, T as TripwireConfig, B as BotRuleConfig, e as BotAgent, f as BotCategory, A as AgentCategory, g as RateLimitStore, h as RateLimitConsume, i as RateLimitOutcome, W as WebDecoy, P as ProtectResult, D as Decision, j as WebDecoyConfig, k as ProtectOptions, l as AgentVerifierOptions, m as AgentRequestInput, n as AgentVerdict, S as SignedAgentDirectory } from './sdk-CIlgQzZt.mjs';
2
- export { o as AgentStatus, p as BOT_CATEGORIES, q as BOT_REGISTRY, r as BotVerdict, C as Characteristic, s as Conclusion, t as DEFAULT_CHARACTERISTICS, u as DecisionCache, v as DecisionCacheOptions, w as DecisionInit, E as EDGE_CLASS_HEADER, x as EDGE_CLEARANCE_HEADER, y as EdgeClass, z as EdgeVerdict, I as IPEnrichmentData, L as LocalAnalysis, G as LogFields, H as Logger, M as MemoryRateLimitStore, J as RequestMetadata, K as RuleOutcome, N as RuleState, O as SDKDetectionRequest, Q as SDKDetectionResponse, U as Span, V as SyncRateLimitStore, X as TLSInfo, Y as Tracer, Z as ViolationEvent, _ as classifyUserAgent, $ as consoleLogger, a0 as deriveKey, a1 as fromPino, a2 as matchUserAgent, a3 as newDecisionId, a4 as readEdgeVerdict, a5 as silentLogger } from './sdk-CIlgQzZt.mjs';
1
+ import { R as Rule, a as RuleContext, b as RuleResult, c as RuleEngineResult, d as RateLimitConfig, F as FilterConfig, T as TripwireConfig, B as BotRuleConfig, e as BotAgent, f as BotCategory, A as AgentCategory, g as RateLimitStore, h as RateLimitConsume, i as RateLimitOutcome, W as WebDecoy, P as ProtectResult, D as Decision, j as WebDecoyConfig, k as ProtectOptions, l as AgentVerifierOptions, m as AgentRequestInput, n as AgentVerdict, S as SignedAgentDirectory } from './sdk-CSHYCT9a.mjs';
2
+ export { o as AgentStatus, p as BOT_CATEGORIES, q as BOT_REGISTRY, r as BotVerdict, C as Characteristic, s as Conclusion, t as DEFAULT_CHARACTERISTICS, u as DecisionCache, v as DecisionCacheOptions, w as DecisionInit, E as EDGE_CLASS_HEADER, x as EDGE_CLEARANCE_HEADER, y as EdgeClass, z as EdgeVerdict, I as IPEnrichmentData, L as LocalAnalysis, G as LogFields, H as Logger, M as MemoryRateLimitStore, J as RequestMetadata, K as RuleOutcome, N as RuleState, O as SDKDetectionRequest, Q as SDKDetectionResponse, U as Span, V as SyncRateLimitStore, X as TLSInfo, Y as Tracer, Z as ViolationEvent, _ as classifyUserAgent, $ as consoleLogger, a0 as deriveKey, a1 as fromPino, a2 as matchUserAgent, a3 as newDecisionId, a4 as readEdgeVerdict, a5 as silentLogger } from './sdk-CSHYCT9a.mjs';
3
3
 
4
4
  /**
5
5
  * The reserved test trigger.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { R as Rule, a as RuleContext, b as RuleResult, c as RuleEngineResult, d as RateLimitConfig, F as FilterConfig, T as TripwireConfig, B as BotRuleConfig, e as BotAgent, f as BotCategory, A as AgentCategory, g as RateLimitStore, h as RateLimitConsume, i as RateLimitOutcome, W as WebDecoy, P as ProtectResult, D as Decision, j as WebDecoyConfig, k as ProtectOptions, l as AgentVerifierOptions, m as AgentRequestInput, n as AgentVerdict, S as SignedAgentDirectory } from './sdk-CIlgQzZt.js';
2
- export { o as AgentStatus, p as BOT_CATEGORIES, q as BOT_REGISTRY, r as BotVerdict, C as Characteristic, s as Conclusion, t as DEFAULT_CHARACTERISTICS, u as DecisionCache, v as DecisionCacheOptions, w as DecisionInit, E as EDGE_CLASS_HEADER, x as EDGE_CLEARANCE_HEADER, y as EdgeClass, z as EdgeVerdict, I as IPEnrichmentData, L as LocalAnalysis, G as LogFields, H as Logger, M as MemoryRateLimitStore, J as RequestMetadata, K as RuleOutcome, N as RuleState, O as SDKDetectionRequest, Q as SDKDetectionResponse, U as Span, V as SyncRateLimitStore, X as TLSInfo, Y as Tracer, Z as ViolationEvent, _ as classifyUserAgent, $ as consoleLogger, a0 as deriveKey, a1 as fromPino, a2 as matchUserAgent, a3 as newDecisionId, a4 as readEdgeVerdict, a5 as silentLogger } from './sdk-CIlgQzZt.js';
1
+ import { R as Rule, a as RuleContext, b as RuleResult, c as RuleEngineResult, d as RateLimitConfig, F as FilterConfig, T as TripwireConfig, B as BotRuleConfig, e as BotAgent, f as BotCategory, A as AgentCategory, g as RateLimitStore, h as RateLimitConsume, i as RateLimitOutcome, W as WebDecoy, P as ProtectResult, D as Decision, j as WebDecoyConfig, k as ProtectOptions, l as AgentVerifierOptions, m as AgentRequestInput, n as AgentVerdict, S as SignedAgentDirectory } from './sdk-CSHYCT9a.js';
2
+ export { o as AgentStatus, p as BOT_CATEGORIES, q as BOT_REGISTRY, r as BotVerdict, C as Characteristic, s as Conclusion, t as DEFAULT_CHARACTERISTICS, u as DecisionCache, v as DecisionCacheOptions, w as DecisionInit, E as EDGE_CLASS_HEADER, x as EDGE_CLEARANCE_HEADER, y as EdgeClass, z as EdgeVerdict, I as IPEnrichmentData, L as LocalAnalysis, G as LogFields, H as Logger, M as MemoryRateLimitStore, J as RequestMetadata, K as RuleOutcome, N as RuleState, O as SDKDetectionRequest, Q as SDKDetectionResponse, U as Span, V as SyncRateLimitStore, X as TLSInfo, Y as Tracer, Z as ViolationEvent, _ as classifyUserAgent, $ as consoleLogger, a0 as deriveKey, a1 as fromPino, a2 as matchUserAgent, a3 as newDecisionId, a4 as readEdgeVerdict, a5 as silentLogger } from './sdk-CSHYCT9a.js';
3
3
 
4
4
  /**
5
5
  * The reserved test trigger.
package/dist/index.js CHANGED
@@ -103,8 +103,22 @@ __export(index_exports, {
103
103
  module.exports = __toCommonJS(index_exports);
104
104
 
105
105
  // src/client.ts
106
+ var WebDecoyUnavailableError = class extends Error {
107
+ constructor(retryAt) {
108
+ super("WebDecoy is temporarily unavailable; requests are paused");
109
+ this.retryAt = retryAt;
110
+ this.name = "WebDecoyUnavailableError";
111
+ Object.setPrototypeOf(this, new.target.prototype);
112
+ }
113
+ };
114
+ var PAUSE_BASE_MS = 1e3;
115
+ var PAUSE_MAX_MS = 6e4;
116
+ var RETRY_AFTER_MAX_MS = 3e5;
106
117
  var WebDecoyClient = class {
107
118
  constructor(config) {
119
+ /** No request is made before this time (epoch ms). */
120
+ this.pausedUntil = 0;
121
+ this.consecutiveFailures = 0;
108
122
  this.config = config;
109
123
  this.baseUrl = config.apiUrl.replace(/\/+$/, "");
110
124
  this.headers = {
@@ -118,7 +132,30 @@ var WebDecoyClient = class {
118
132
  );
119
133
  }
120
134
  }
135
+ /**
136
+ * Whether a request would be attempted right now. False while paused after
137
+ * WebDecoy refused work (429, 5xx) or did not answer, so a caller with
138
+ * something to keep (a buffer) can hold it rather than lose it.
139
+ */
140
+ isAvailable(now = Date.now()) {
141
+ return now >= this.pausedUntil;
142
+ }
143
+ /**
144
+ * Pause every call to WebDecoy after a refusal or no answer: the Retry-After
145
+ * when one was given, otherwise 1s doubling per consecutive failure up to
146
+ * 60s. Without this, each request during an outage waited out the full
147
+ * timeout in the caller's request path.
148
+ */
149
+ pause(retryAfter) {
150
+ const seconds = retryAfter ? Number(retryAfter) : NaN;
151
+ const ms = Number.isFinite(seconds) && seconds > 0 ? Math.min(Math.max(seconds * 1e3, PAUSE_BASE_MS), RETRY_AFTER_MAX_MS) : Math.min(PAUSE_BASE_MS * 2 ** this.consecutiveFailures, PAUSE_MAX_MS);
152
+ this.consecutiveFailures++;
153
+ this.pausedUntil = Date.now() + ms;
154
+ }
121
155
  async request(method, path, body) {
156
+ if (!this.isAvailable()) {
157
+ throw new WebDecoyUnavailableError(this.pausedUntil);
158
+ }
122
159
  const controller = new AbortController();
123
160
  const timer = setTimeout(() => controller.abort(), this.config.timeout);
124
161
  if (typeof timer.unref === "function") {
@@ -146,8 +183,14 @@ var WebDecoyClient = class {
146
183
  if (this.config.debug) {
147
184
  console.log("[WebDecoy] Response:", { status: response.status, data });
148
185
  }
186
+ if (response.status === 429 || response.status >= 500) {
187
+ this.pause(response.headers.get("retry-after"));
188
+ } else {
189
+ this.consecutiveFailures = 0;
190
+ }
149
191
  return { status: response.status, data };
150
192
  } catch (error) {
193
+ this.pause(null);
151
194
  if (this.config.debug) {
152
195
  console.error("[WebDecoy] Error:", {
153
196
  message: error instanceof Error ? error.message : String(error)
@@ -213,7 +256,7 @@ var WebDecoyClient = class {
213
256
  async sendAIReferrals(batch) {
214
257
  try {
215
258
  const response = await this.request("POST", "/api/v1/sdk/ai-referrals", batch);
216
- return response.status < 500;
259
+ return response.status < 500 && response.status !== 429;
217
260
  } catch (error) {
218
261
  if (this.config.debug) {
219
262
  console.error("[WebDecoy] Failed to send AI referrals:", error);
@@ -2082,6 +2125,7 @@ function bots(config = {}) {
2082
2125
  }
2083
2126
 
2084
2127
  // src/violation-reporter.ts
2128
+ var MAX_BUFFERED_VIOLATIONS = 1e3;
2085
2129
  var ViolationReporter = class {
2086
2130
  constructor(client, config = {}) {
2087
2131
  this.buffer = [];
@@ -2100,6 +2144,9 @@ var ViolationReporter = class {
2100
2144
  */
2101
2145
  report(violations) {
2102
2146
  this.buffer.push(...violations);
2147
+ if (this.buffer.length > MAX_BUFFERED_VIOLATIONS) {
2148
+ this.buffer.splice(0, this.buffer.length - MAX_BUFFERED_VIOLATIONS);
2149
+ }
2103
2150
  if (this.buffer.length >= this.maxBufferSize) {
2104
2151
  this.flush().catch(() => {
2105
2152
  });
@@ -2109,7 +2156,7 @@ var ViolationReporter = class {
2109
2156
  * Flush buffered violations to the backend
2110
2157
  */
2111
2158
  async flush() {
2112
- if (this.flushing || this.buffer.length === 0) return;
2159
+ if (this.flushing || this.buffer.length === 0 || !this.client.isAvailable()) return;
2113
2160
  this.flushing = true;
2114
2161
  const events = this.buffer.splice(0, this.buffer.length);
2115
2162
  try {
@@ -2244,8 +2291,9 @@ ${landing}`;
2244
2291
  if (entry) {
2245
2292
  entry.count++;
2246
2293
  } else {
2294
+ if (this.pending && this.counts.size >= MAX_ENTRIES) return;
2247
2295
  this.counts.set(key, { platform, path: landing, count: 1 });
2248
- if (this.counts.size >= MAX_ENTRIES) void this.flush();
2296
+ if (this.counts.size >= MAX_ENTRIES && !this.pending) void this.flush();
2249
2297
  }
2250
2298
  } catch {
2251
2299
  }
@@ -2275,6 +2323,7 @@ ${landing}`;
2275
2323
  };
2276
2324
 
2277
2325
  // src/ip-enrichment.ts
2326
+ var MAX_ENRICHMENT_ENTRIES = 1e4;
2278
2327
  var IPEnrichmentClient = class {
2279
2328
  constructor(client, ttlMs = 36e5) {
2280
2329
  this.cache = /* @__PURE__ */ new Map();
@@ -2307,10 +2356,15 @@ var IPEnrichmentClient = class {
2307
2356
  async fetchAndCache(ip) {
2308
2357
  const data = await this.client.getIPEnrichment(ip);
2309
2358
  if (data) {
2359
+ this.cache.delete(ip);
2310
2360
  this.cache.set(ip, {
2311
2361
  data,
2312
2362
  expiresAt: Date.now() + this.ttlMs
2313
2363
  });
2364
+ if (this.cache.size > MAX_ENRICHMENT_ENTRIES) {
2365
+ const oldest = this.cache.keys().next();
2366
+ if (!oldest.done) this.cache.delete(oldest.value);
2367
+ }
2314
2368
  }
2315
2369
  return data;
2316
2370
  }
@@ -3559,7 +3613,8 @@ var WebDecoy = class {
3559
3613
  if (this.decisionCache) this.decisionCache.set(key, decision);
3560
3614
  return decision;
3561
3615
  } catch (error) {
3562
- this.log.error("Protection error", {
3616
+ const log = error instanceof WebDecoyUnavailableError ? this.log.debug.bind(this.log) : this.log.error.bind(this.log);
3617
+ log("Protection error", {
3563
3618
  error: error instanceof Error ? error.message : String(error)
3564
3619
  });
3565
3620
  return new Decision({
package/dist/index.mjs CHANGED
@@ -54,7 +54,7 @@ import {
54
54
  tripwire,
55
55
  upstashRateLimitStore,
56
56
  webBotAuth
57
- } from "./chunk-QP3WOPWJ.mjs";
57
+ } from "./chunk-5WMRRJ4A.mjs";
58
58
 
59
59
  // src/client-ip.ts
60
60
  var IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
@@ -1284,7 +1284,23 @@ declare class WebDecoyClient {
1284
1284
  private config;
1285
1285
  private baseUrl;
1286
1286
  private headers;
1287
+ /** No request is made before this time (epoch ms). */
1288
+ private pausedUntil;
1289
+ private consecutiveFailures;
1287
1290
  constructor(config: ClientConfig);
1291
+ /**
1292
+ * Whether a request would be attempted right now. False while paused after
1293
+ * WebDecoy refused work (429, 5xx) or did not answer, so a caller with
1294
+ * something to keep (a buffer) can hold it rather than lose it.
1295
+ */
1296
+ isAvailable(now?: number): boolean;
1297
+ /**
1298
+ * Pause every call to WebDecoy after a refusal or no answer: the Retry-After
1299
+ * when one was given, otherwise 1s doubling per consecutive failure up to
1300
+ * 60s. Without this, each request during an outage waited out the full
1301
+ * timeout in the caller's request path.
1302
+ */
1303
+ private pause;
1288
1304
  private request;
1289
1305
  /**
1290
1306
  * Send a detection request to the ingest service
@@ -1284,7 +1284,23 @@ declare class WebDecoyClient {
1284
1284
  private config;
1285
1285
  private baseUrl;
1286
1286
  private headers;
1287
+ /** No request is made before this time (epoch ms). */
1288
+ private pausedUntil;
1289
+ private consecutiveFailures;
1287
1290
  constructor(config: ClientConfig);
1291
+ /**
1292
+ * Whether a request would be attempted right now. False while paused after
1293
+ * WebDecoy refused work (429, 5xx) or did not answer, so a caller with
1294
+ * something to keep (a buffer) can hold it rather than lose it.
1295
+ */
1296
+ isAvailable(now?: number): boolean;
1297
+ /**
1298
+ * Pause every call to WebDecoy after a refusal or no answer: the Retry-After
1299
+ * when one was given, otherwise 1s doubling per consecutive failure up to
1300
+ * 60s. Without this, each request during an outage waited out the full
1301
+ * timeout in the caller's request path.
1302
+ */
1303
+ private pause;
1288
1304
  private request;
1289
1305
  /**
1290
1306
  * Send a detection request to the ingest service
@@ -1,4 +1,4 @@
1
- import { j as WebDecoyConfig, J as RequestMetadata, W as WebDecoy, P as ProtectResult, N as RuleState } from './sdk-CIlgQzZt.mjs';
1
+ import { j as WebDecoyConfig, J as RequestMetadata, W as WebDecoy, P as ProtectResult, N as RuleState } from './sdk-CSHYCT9a.mjs';
2
2
 
3
3
  /**
4
4
  * Testing utilities, for the application's test suite rather than ours.
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { j as WebDecoyConfig, J as RequestMetadata, W as WebDecoy, P as ProtectResult, N as RuleState } from './sdk-CIlgQzZt.js';
1
+ import { j as WebDecoyConfig, J as RequestMetadata, W as WebDecoy, P as ProtectResult, N as RuleState } from './sdk-CSHYCT9a.js';
2
2
 
3
3
  /**
4
4
  * Testing utilities, for the application's test suite rather than ours.
package/dist/testing.js CHANGED
@@ -33,8 +33,22 @@ __export(testing_exports, {
33
33
  module.exports = __toCommonJS(testing_exports);
34
34
 
35
35
  // src/client.ts
36
+ var WebDecoyUnavailableError = class extends Error {
37
+ constructor(retryAt) {
38
+ super("WebDecoy is temporarily unavailable; requests are paused");
39
+ this.retryAt = retryAt;
40
+ this.name = "WebDecoyUnavailableError";
41
+ Object.setPrototypeOf(this, new.target.prototype);
42
+ }
43
+ };
44
+ var PAUSE_BASE_MS = 1e3;
45
+ var PAUSE_MAX_MS = 6e4;
46
+ var RETRY_AFTER_MAX_MS = 3e5;
36
47
  var WebDecoyClient = class {
37
48
  constructor(config) {
49
+ /** No request is made before this time (epoch ms). */
50
+ this.pausedUntil = 0;
51
+ this.consecutiveFailures = 0;
38
52
  this.config = config;
39
53
  this.baseUrl = config.apiUrl.replace(/\/+$/, "");
40
54
  this.headers = {
@@ -48,7 +62,30 @@ var WebDecoyClient = class {
48
62
  );
49
63
  }
50
64
  }
65
+ /**
66
+ * Whether a request would be attempted right now. False while paused after
67
+ * WebDecoy refused work (429, 5xx) or did not answer, so a caller with
68
+ * something to keep (a buffer) can hold it rather than lose it.
69
+ */
70
+ isAvailable(now = Date.now()) {
71
+ return now >= this.pausedUntil;
72
+ }
73
+ /**
74
+ * Pause every call to WebDecoy after a refusal or no answer: the Retry-After
75
+ * when one was given, otherwise 1s doubling per consecutive failure up to
76
+ * 60s. Without this, each request during an outage waited out the full
77
+ * timeout in the caller's request path.
78
+ */
79
+ pause(retryAfter) {
80
+ const seconds = retryAfter ? Number(retryAfter) : NaN;
81
+ const ms = Number.isFinite(seconds) && seconds > 0 ? Math.min(Math.max(seconds * 1e3, PAUSE_BASE_MS), RETRY_AFTER_MAX_MS) : Math.min(PAUSE_BASE_MS * 2 ** this.consecutiveFailures, PAUSE_MAX_MS);
82
+ this.consecutiveFailures++;
83
+ this.pausedUntil = Date.now() + ms;
84
+ }
51
85
  async request(method, path, body) {
86
+ if (!this.isAvailable()) {
87
+ throw new WebDecoyUnavailableError(this.pausedUntil);
88
+ }
52
89
  const controller = new AbortController();
53
90
  const timer = setTimeout(() => controller.abort(), this.config.timeout);
54
91
  if (typeof timer.unref === "function") {
@@ -76,8 +113,14 @@ var WebDecoyClient = class {
76
113
  if (this.config.debug) {
77
114
  console.log("[WebDecoy] Response:", { status: response.status, data });
78
115
  }
116
+ if (response.status === 429 || response.status >= 500) {
117
+ this.pause(response.headers.get("retry-after"));
118
+ } else {
119
+ this.consecutiveFailures = 0;
120
+ }
79
121
  return { status: response.status, data };
80
122
  } catch (error) {
123
+ this.pause(null);
81
124
  if (this.config.debug) {
82
125
  console.error("[WebDecoy] Error:", {
83
126
  message: error instanceof Error ? error.message : String(error)
@@ -143,7 +186,7 @@ var WebDecoyClient = class {
143
186
  async sendAIReferrals(batch) {
144
187
  try {
145
188
  const response = await this.request("POST", "/api/v1/sdk/ai-referrals", batch);
146
- return response.status < 500;
189
+ return response.status < 500 && response.status !== 429;
147
190
  } catch (error) {
148
191
  if (this.config.debug) {
149
192
  console.error("[WebDecoy] Failed to send AI referrals:", error);
@@ -837,6 +880,7 @@ function tripwire(config = {}) {
837
880
  }
838
881
 
839
882
  // src/violation-reporter.ts
883
+ var MAX_BUFFERED_VIOLATIONS = 1e3;
840
884
  var ViolationReporter = class {
841
885
  constructor(client, config = {}) {
842
886
  this.buffer = [];
@@ -855,6 +899,9 @@ var ViolationReporter = class {
855
899
  */
856
900
  report(violations) {
857
901
  this.buffer.push(...violations);
902
+ if (this.buffer.length > MAX_BUFFERED_VIOLATIONS) {
903
+ this.buffer.splice(0, this.buffer.length - MAX_BUFFERED_VIOLATIONS);
904
+ }
858
905
  if (this.buffer.length >= this.maxBufferSize) {
859
906
  this.flush().catch(() => {
860
907
  });
@@ -864,7 +911,7 @@ var ViolationReporter = class {
864
911
  * Flush buffered violations to the backend
865
912
  */
866
913
  async flush() {
867
- if (this.flushing || this.buffer.length === 0) return;
914
+ if (this.flushing || this.buffer.length === 0 || !this.client.isAvailable()) return;
868
915
  this.flushing = true;
869
916
  const events = this.buffer.splice(0, this.buffer.length);
870
917
  try {
@@ -999,8 +1046,9 @@ ${landing}`;
999
1046
  if (entry) {
1000
1047
  entry.count++;
1001
1048
  } else {
1049
+ if (this.pending && this.counts.size >= MAX_ENTRIES) return;
1002
1050
  this.counts.set(key, { platform, path: landing, count: 1 });
1003
- if (this.counts.size >= MAX_ENTRIES) void this.flush();
1051
+ if (this.counts.size >= MAX_ENTRIES && !this.pending) void this.flush();
1004
1052
  }
1005
1053
  } catch {
1006
1054
  }
@@ -1030,6 +1078,7 @@ ${landing}`;
1030
1078
  };
1031
1079
 
1032
1080
  // src/ip-enrichment.ts
1081
+ var MAX_ENRICHMENT_ENTRIES = 1e4;
1033
1082
  var IPEnrichmentClient = class {
1034
1083
  constructor(client, ttlMs = 36e5) {
1035
1084
  this.cache = /* @__PURE__ */ new Map();
@@ -1062,10 +1111,15 @@ var IPEnrichmentClient = class {
1062
1111
  async fetchAndCache(ip) {
1063
1112
  const data = await this.client.getIPEnrichment(ip);
1064
1113
  if (data) {
1114
+ this.cache.delete(ip);
1065
1115
  this.cache.set(ip, {
1066
1116
  data,
1067
1117
  expiresAt: Date.now() + this.ttlMs
1068
1118
  });
1119
+ if (this.cache.size > MAX_ENRICHMENT_ENTRIES) {
1120
+ const oldest = this.cache.keys().next();
1121
+ if (!oldest.done) this.cache.delete(oldest.value);
1122
+ }
1069
1123
  }
1070
1124
  return data;
1071
1125
  }
@@ -2302,7 +2356,8 @@ var WebDecoy = class {
2302
2356
  if (this.decisionCache) this.decisionCache.set(key, decision);
2303
2357
  return decision;
2304
2358
  } catch (error) {
2305
- this.log.error("Protection error", {
2359
+ const log = error instanceof WebDecoyUnavailableError ? this.log.debug.bind(this.log) : this.log.error.bind(this.log);
2360
+ log("Protection error", {
2306
2361
  error: error instanceof Error ? error.message : String(error)
2307
2362
  });
2308
2363
  return new Decision({
package/dist/testing.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  WebDecoy,
3
3
  silentLogger
4
- } from "./chunk-QP3WOPWJ.mjs";
4
+ } from "./chunk-5WMRRJ4A.mjs";
5
5
 
6
6
  // src/testing.ts
7
7
  function request(over = {}) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webdecoy/node",
3
- "version": "0.18.3",
3
+ "version": "0.18.5",
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",