@webdecoy/node 0.18.2 → 0.18.4

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.
@@ -775,22 +775,73 @@ var DEFAULT_TRIPWIRE_PATHS = [
775
775
  "/actuator/env",
776
776
  "/.vscode/sftp.json"
777
777
  ];
778
- function normalizePath(path) {
779
- return path.split("?")[0].split("#")[0];
778
+ function canonicalizeTripwirePath(path) {
779
+ const noQuery = path.split("?")[0].split("#")[0];
780
+ return cleanSlashesAndDots(decodePercentAscii(noQuery));
781
+ }
782
+ function decodePercentAscii(s) {
783
+ for (let i = 0; i < 4; i++) {
784
+ const next = decodePercentAsciiOnce(s);
785
+ if (next === s) break;
786
+ s = next;
787
+ }
788
+ return s;
789
+ }
790
+ function decodePercentAsciiOnce(s) {
791
+ if (!s.includes("%")) return s;
792
+ let out = "";
793
+ for (let i = 0; i < s.length; i++) {
794
+ if (s[i] === "%" && i + 2 < s.length) {
795
+ const hi = unhexNibble(s.charCodeAt(i + 1));
796
+ const lo = unhexNibble(s.charCodeAt(i + 2));
797
+ if (hi >= 0 && lo >= 0) {
798
+ const v = hi << 4 | lo;
799
+ if (v < 128) {
800
+ out += String.fromCharCode(v);
801
+ i += 2;
802
+ continue;
803
+ }
804
+ }
805
+ }
806
+ out += s[i];
807
+ }
808
+ return out;
809
+ }
810
+ function unhexNibble(c) {
811
+ if (c >= 48 && c <= 57) return c - 48;
812
+ if (c >= 97 && c <= 102) return c - 97 + 10;
813
+ if (c >= 65 && c <= 70) return c - 65 + 10;
814
+ return -1;
815
+ }
816
+ function cleanSlashesAndDots(s) {
817
+ if (s === "") return s;
818
+ const hadTrailing = s.length > 1 && s[s.length - 1] === "/";
819
+ const stack = [];
820
+ for (const p of s.split("/")) {
821
+ if (p === "" || p === ".") continue;
822
+ if (p === "..") {
823
+ if (stack.length > 0) stack.pop();
824
+ continue;
825
+ }
826
+ stack.push(p);
827
+ }
828
+ let res = "/" + stack.join("/");
829
+ if (hadTrailing && res !== "/") res += "/";
830
+ return res;
780
831
  }
781
832
  var TripwireRule = class {
782
833
  constructor(config = {}) {
783
834
  this.name = "tripwire";
784
835
  const paths = [...config.paths ?? []];
785
836
  if (config.includeDefaults ?? true) paths.push(...DEFAULT_TRIPWIRE_PATHS);
786
- this.exact = new Set(paths);
787
- this.prefixes = config.prefixes ?? [];
837
+ this.exact = new Set(paths.map(canonicalizeTripwirePath));
838
+ this.prefixes = (config.prefixes ?? []).map(canonicalizeTripwirePath);
788
839
  this.patterns = config.patterns ?? [];
789
840
  this.action = config.action ?? "DENY";
790
841
  this.dryRun = config.dryRun ?? false;
791
842
  }
792
843
  evaluate(context) {
793
- const path = normalizePath(context.path);
844
+ const path = canonicalizeTripwirePath(context.path);
794
845
  const hit = this.exact.has(path) || this.prefixes.some((prefix) => path.startsWith(prefix)) || this.patterns.some((re) => re.test(path));
795
846
  if (hit) {
796
847
  return {
@@ -2452,8 +2503,22 @@ function isTestTriggerUserAgent(userAgent) {
2452
2503
  }
2453
2504
 
2454
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;
2455
2517
  var WebDecoyClient = class {
2456
2518
  constructor(config) {
2519
+ /** No request is made before this time (epoch ms). */
2520
+ this.pausedUntil = 0;
2521
+ this.consecutiveFailures = 0;
2457
2522
  this.config = config;
2458
2523
  this.baseUrl = config.apiUrl.replace(/\/+$/, "");
2459
2524
  this.headers = {
@@ -2467,7 +2532,30 @@ var WebDecoyClient = class {
2467
2532
  );
2468
2533
  }
2469
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
+ }
2470
2555
  async request(method, path, body) {
2556
+ if (!this.isAvailable()) {
2557
+ throw new WebDecoyUnavailableError(this.pausedUntil);
2558
+ }
2471
2559
  const controller = new AbortController();
2472
2560
  const timer = setTimeout(() => controller.abort(), this.config.timeout);
2473
2561
  if (typeof timer.unref === "function") {
@@ -2495,8 +2583,14 @@ var WebDecoyClient = class {
2495
2583
  if (this.config.debug) {
2496
2584
  console.log("[WebDecoy] Response:", { status: response.status, data });
2497
2585
  }
2586
+ if (response.status === 429 || response.status >= 500) {
2587
+ this.pause(response.headers.get("retry-after"));
2588
+ } else {
2589
+ this.consecutiveFailures = 0;
2590
+ }
2498
2591
  return { status: response.status, data };
2499
2592
  } catch (error) {
2593
+ this.pause(null);
2500
2594
  if (this.config.debug) {
2501
2595
  console.error("[WebDecoy] Error:", {
2502
2596
  message: error instanceof Error ? error.message : String(error)
@@ -2562,7 +2656,7 @@ var WebDecoyClient = class {
2562
2656
  async sendAIReferrals(batch) {
2563
2657
  try {
2564
2658
  const response = await this.request("POST", "/api/v1/sdk/ai-referrals", batch);
2565
- return response.status < 500;
2659
+ return response.status < 500 && response.status !== 429;
2566
2660
  } catch (error) {
2567
2661
  if (this.config.debug) {
2568
2662
  console.error("[WebDecoy] Failed to send AI referrals:", error);
@@ -2753,6 +2847,7 @@ function analyzeRequest(metadata) {
2753
2847
  }
2754
2848
 
2755
2849
  // src/violation-reporter.ts
2850
+ var MAX_BUFFERED_VIOLATIONS = 1e3;
2756
2851
  var ViolationReporter = class {
2757
2852
  constructor(client, config = {}) {
2758
2853
  this.buffer = [];
@@ -2771,6 +2866,9 @@ var ViolationReporter = class {
2771
2866
  */
2772
2867
  report(violations) {
2773
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
+ }
2774
2872
  if (this.buffer.length >= this.maxBufferSize) {
2775
2873
  this.flush().catch(() => {
2776
2874
  });
@@ -2780,7 +2878,7 @@ var ViolationReporter = class {
2780
2878
  * Flush buffered violations to the backend
2781
2879
  */
2782
2880
  async flush() {
2783
- if (this.flushing || this.buffer.length === 0) return;
2881
+ if (this.flushing || this.buffer.length === 0 || !this.client.isAvailable()) return;
2784
2882
  this.flushing = true;
2785
2883
  const events = this.buffer.splice(0, this.buffer.length);
2786
2884
  try {
@@ -2915,8 +3013,9 @@ ${landing}`;
2915
3013
  if (entry) {
2916
3014
  entry.count++;
2917
3015
  } else {
3016
+ if (this.pending && this.counts.size >= MAX_ENTRIES) return;
2918
3017
  this.counts.set(key, { platform, path: landing, count: 1 });
2919
- if (this.counts.size >= MAX_ENTRIES) void this.flush();
3018
+ if (this.counts.size >= MAX_ENTRIES && !this.pending) void this.flush();
2920
3019
  }
2921
3020
  } catch {
2922
3021
  }
@@ -2946,6 +3045,7 @@ ${landing}`;
2946
3045
  };
2947
3046
 
2948
3047
  // src/ip-enrichment.ts
3048
+ var MAX_ENRICHMENT_ENTRIES = 1e4;
2949
3049
  var IPEnrichmentClient = class {
2950
3050
  constructor(client, ttlMs = 36e5) {
2951
3051
  this.cache = /* @__PURE__ */ new Map();
@@ -2978,10 +3078,15 @@ var IPEnrichmentClient = class {
2978
3078
  async fetchAndCache(ip) {
2979
3079
  const data = await this.client.getIPEnrichment(ip);
2980
3080
  if (data) {
3081
+ this.cache.delete(ip);
2981
3082
  this.cache.set(ip, {
2982
3083
  data,
2983
3084
  expiresAt: Date.now() + this.ttlMs
2984
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
+ }
2985
3090
  }
2986
3091
  return data;
2987
3092
  }
@@ -3404,7 +3509,8 @@ var WebDecoy = class {
3404
3509
  if (this.decisionCache) this.decisionCache.set(key, decision);
3405
3510
  return decision;
3406
3511
  } catch (error) {
3407
- 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", {
3408
3514
  error: error instanceof Error ? error.message : String(error)
3409
3515
  });
3410
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);
@@ -1180,22 +1223,73 @@ var DEFAULT_TRIPWIRE_PATHS = [
1180
1223
  "/actuator/env",
1181
1224
  "/.vscode/sftp.json"
1182
1225
  ];
1183
- function normalizePath(path) {
1184
- return path.split("?")[0].split("#")[0];
1226
+ function canonicalizeTripwirePath(path) {
1227
+ const noQuery = path.split("?")[0].split("#")[0];
1228
+ return cleanSlashesAndDots(decodePercentAscii(noQuery));
1229
+ }
1230
+ function decodePercentAscii(s) {
1231
+ for (let i = 0; i < 4; i++) {
1232
+ const next = decodePercentAsciiOnce(s);
1233
+ if (next === s) break;
1234
+ s = next;
1235
+ }
1236
+ return s;
1237
+ }
1238
+ function decodePercentAsciiOnce(s) {
1239
+ if (!s.includes("%")) return s;
1240
+ let out = "";
1241
+ for (let i = 0; i < s.length; i++) {
1242
+ if (s[i] === "%" && i + 2 < s.length) {
1243
+ const hi = unhexNibble(s.charCodeAt(i + 1));
1244
+ const lo = unhexNibble(s.charCodeAt(i + 2));
1245
+ if (hi >= 0 && lo >= 0) {
1246
+ const v = hi << 4 | lo;
1247
+ if (v < 128) {
1248
+ out += String.fromCharCode(v);
1249
+ i += 2;
1250
+ continue;
1251
+ }
1252
+ }
1253
+ }
1254
+ out += s[i];
1255
+ }
1256
+ return out;
1257
+ }
1258
+ function unhexNibble(c) {
1259
+ if (c >= 48 && c <= 57) return c - 48;
1260
+ if (c >= 97 && c <= 102) return c - 97 + 10;
1261
+ if (c >= 65 && c <= 70) return c - 65 + 10;
1262
+ return -1;
1263
+ }
1264
+ function cleanSlashesAndDots(s) {
1265
+ if (s === "") return s;
1266
+ const hadTrailing = s.length > 1 && s[s.length - 1] === "/";
1267
+ const stack = [];
1268
+ for (const p of s.split("/")) {
1269
+ if (p === "" || p === ".") continue;
1270
+ if (p === "..") {
1271
+ if (stack.length > 0) stack.pop();
1272
+ continue;
1273
+ }
1274
+ stack.push(p);
1275
+ }
1276
+ let res = "/" + stack.join("/");
1277
+ if (hadTrailing && res !== "/") res += "/";
1278
+ return res;
1185
1279
  }
1186
1280
  var TripwireRule = class {
1187
1281
  constructor(config = {}) {
1188
1282
  this.name = "tripwire";
1189
1283
  const paths = [...config.paths ?? []];
1190
1284
  if (config.includeDefaults ?? true) paths.push(...DEFAULT_TRIPWIRE_PATHS);
1191
- this.exact = new Set(paths);
1192
- this.prefixes = config.prefixes ?? [];
1285
+ this.exact = new Set(paths.map(canonicalizeTripwirePath));
1286
+ this.prefixes = (config.prefixes ?? []).map(canonicalizeTripwirePath);
1193
1287
  this.patterns = config.patterns ?? [];
1194
1288
  this.action = config.action ?? "DENY";
1195
1289
  this.dryRun = config.dryRun ?? false;
1196
1290
  }
1197
1291
  evaluate(context) {
1198
- const path = normalizePath(context.path);
1292
+ const path = canonicalizeTripwirePath(context.path);
1199
1293
  const hit = this.exact.has(path) || this.prefixes.some((prefix) => path.startsWith(prefix)) || this.patterns.some((re) => re.test(path));
1200
1294
  if (hit) {
1201
1295
  return {
@@ -2031,6 +2125,7 @@ function bots(config = {}) {
2031
2125
  }
2032
2126
 
2033
2127
  // src/violation-reporter.ts
2128
+ var MAX_BUFFERED_VIOLATIONS = 1e3;
2034
2129
  var ViolationReporter = class {
2035
2130
  constructor(client, config = {}) {
2036
2131
  this.buffer = [];
@@ -2049,6 +2144,9 @@ var ViolationReporter = class {
2049
2144
  */
2050
2145
  report(violations) {
2051
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
+ }
2052
2150
  if (this.buffer.length >= this.maxBufferSize) {
2053
2151
  this.flush().catch(() => {
2054
2152
  });
@@ -2058,7 +2156,7 @@ var ViolationReporter = class {
2058
2156
  * Flush buffered violations to the backend
2059
2157
  */
2060
2158
  async flush() {
2061
- if (this.flushing || this.buffer.length === 0) return;
2159
+ if (this.flushing || this.buffer.length === 0 || !this.client.isAvailable()) return;
2062
2160
  this.flushing = true;
2063
2161
  const events = this.buffer.splice(0, this.buffer.length);
2064
2162
  try {
@@ -2193,8 +2291,9 @@ ${landing}`;
2193
2291
  if (entry) {
2194
2292
  entry.count++;
2195
2293
  } else {
2294
+ if (this.pending && this.counts.size >= MAX_ENTRIES) return;
2196
2295
  this.counts.set(key, { platform, path: landing, count: 1 });
2197
- if (this.counts.size >= MAX_ENTRIES) void this.flush();
2296
+ if (this.counts.size >= MAX_ENTRIES && !this.pending) void this.flush();
2198
2297
  }
2199
2298
  } catch {
2200
2299
  }
@@ -2224,6 +2323,7 @@ ${landing}`;
2224
2323
  };
2225
2324
 
2226
2325
  // src/ip-enrichment.ts
2326
+ var MAX_ENRICHMENT_ENTRIES = 1e4;
2227
2327
  var IPEnrichmentClient = class {
2228
2328
  constructor(client, ttlMs = 36e5) {
2229
2329
  this.cache = /* @__PURE__ */ new Map();
@@ -2256,10 +2356,15 @@ var IPEnrichmentClient = class {
2256
2356
  async fetchAndCache(ip) {
2257
2357
  const data = await this.client.getIPEnrichment(ip);
2258
2358
  if (data) {
2359
+ this.cache.delete(ip);
2259
2360
  this.cache.set(ip, {
2260
2361
  data,
2261
2362
  expiresAt: Date.now() + this.ttlMs
2262
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
+ }
2263
2368
  }
2264
2369
  return data;
2265
2370
  }
@@ -3508,7 +3613,8 @@ var WebDecoy = class {
3508
3613
  if (this.decisionCache) this.decisionCache.set(key, decision);
3509
3614
  return decision;
3510
3615
  } catch (error) {
3511
- 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", {
3512
3618
  error: error instanceof Error ? error.message : String(error)
3513
3619
  });
3514
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-JV5P2YEA.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);
@@ -445,22 +488,73 @@ var DEFAULT_TRIPWIRE_PATHS = [
445
488
  "/actuator/env",
446
489
  "/.vscode/sftp.json"
447
490
  ];
448
- function normalizePath(path) {
449
- return path.split("?")[0].split("#")[0];
491
+ function canonicalizeTripwirePath(path) {
492
+ const noQuery = path.split("?")[0].split("#")[0];
493
+ return cleanSlashesAndDots(decodePercentAscii(noQuery));
494
+ }
495
+ function decodePercentAscii(s) {
496
+ for (let i = 0; i < 4; i++) {
497
+ const next = decodePercentAsciiOnce(s);
498
+ if (next === s) break;
499
+ s = next;
500
+ }
501
+ return s;
502
+ }
503
+ function decodePercentAsciiOnce(s) {
504
+ if (!s.includes("%")) return s;
505
+ let out = "";
506
+ for (let i = 0; i < s.length; i++) {
507
+ if (s[i] === "%" && i + 2 < s.length) {
508
+ const hi = unhexNibble(s.charCodeAt(i + 1));
509
+ const lo = unhexNibble(s.charCodeAt(i + 2));
510
+ if (hi >= 0 && lo >= 0) {
511
+ const v = hi << 4 | lo;
512
+ if (v < 128) {
513
+ out += String.fromCharCode(v);
514
+ i += 2;
515
+ continue;
516
+ }
517
+ }
518
+ }
519
+ out += s[i];
520
+ }
521
+ return out;
522
+ }
523
+ function unhexNibble(c) {
524
+ if (c >= 48 && c <= 57) return c - 48;
525
+ if (c >= 97 && c <= 102) return c - 97 + 10;
526
+ if (c >= 65 && c <= 70) return c - 65 + 10;
527
+ return -1;
528
+ }
529
+ function cleanSlashesAndDots(s) {
530
+ if (s === "") return s;
531
+ const hadTrailing = s.length > 1 && s[s.length - 1] === "/";
532
+ const stack = [];
533
+ for (const p of s.split("/")) {
534
+ if (p === "" || p === ".") continue;
535
+ if (p === "..") {
536
+ if (stack.length > 0) stack.pop();
537
+ continue;
538
+ }
539
+ stack.push(p);
540
+ }
541
+ let res = "/" + stack.join("/");
542
+ if (hadTrailing && res !== "/") res += "/";
543
+ return res;
450
544
  }
451
545
  var TripwireRule = class {
452
546
  constructor(config = {}) {
453
547
  this.name = "tripwire";
454
548
  const paths = [...config.paths ?? []];
455
549
  if (config.includeDefaults ?? true) paths.push(...DEFAULT_TRIPWIRE_PATHS);
456
- this.exact = new Set(paths);
457
- this.prefixes = config.prefixes ?? [];
550
+ this.exact = new Set(paths.map(canonicalizeTripwirePath));
551
+ this.prefixes = (config.prefixes ?? []).map(canonicalizeTripwirePath);
458
552
  this.patterns = config.patterns ?? [];
459
553
  this.action = config.action ?? "DENY";
460
554
  this.dryRun = config.dryRun ?? false;
461
555
  }
462
556
  evaluate(context) {
463
- const path = normalizePath(context.path);
557
+ const path = canonicalizeTripwirePath(context.path);
464
558
  const hit = this.exact.has(path) || this.prefixes.some((prefix) => path.startsWith(prefix)) || this.patterns.some((re) => re.test(path));
465
559
  if (hit) {
466
560
  return {
@@ -786,6 +880,7 @@ function tripwire(config = {}) {
786
880
  }
787
881
 
788
882
  // src/violation-reporter.ts
883
+ var MAX_BUFFERED_VIOLATIONS = 1e3;
789
884
  var ViolationReporter = class {
790
885
  constructor(client, config = {}) {
791
886
  this.buffer = [];
@@ -804,6 +899,9 @@ var ViolationReporter = class {
804
899
  */
805
900
  report(violations) {
806
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
+ }
807
905
  if (this.buffer.length >= this.maxBufferSize) {
808
906
  this.flush().catch(() => {
809
907
  });
@@ -813,7 +911,7 @@ var ViolationReporter = class {
813
911
  * Flush buffered violations to the backend
814
912
  */
815
913
  async flush() {
816
- if (this.flushing || this.buffer.length === 0) return;
914
+ if (this.flushing || this.buffer.length === 0 || !this.client.isAvailable()) return;
817
915
  this.flushing = true;
818
916
  const events = this.buffer.splice(0, this.buffer.length);
819
917
  try {
@@ -948,8 +1046,9 @@ ${landing}`;
948
1046
  if (entry) {
949
1047
  entry.count++;
950
1048
  } else {
1049
+ if (this.pending && this.counts.size >= MAX_ENTRIES) return;
951
1050
  this.counts.set(key, { platform, path: landing, count: 1 });
952
- if (this.counts.size >= MAX_ENTRIES) void this.flush();
1051
+ if (this.counts.size >= MAX_ENTRIES && !this.pending) void this.flush();
953
1052
  }
954
1053
  } catch {
955
1054
  }
@@ -979,6 +1078,7 @@ ${landing}`;
979
1078
  };
980
1079
 
981
1080
  // src/ip-enrichment.ts
1081
+ var MAX_ENRICHMENT_ENTRIES = 1e4;
982
1082
  var IPEnrichmentClient = class {
983
1083
  constructor(client, ttlMs = 36e5) {
984
1084
  this.cache = /* @__PURE__ */ new Map();
@@ -1011,10 +1111,15 @@ var IPEnrichmentClient = class {
1011
1111
  async fetchAndCache(ip) {
1012
1112
  const data = await this.client.getIPEnrichment(ip);
1013
1113
  if (data) {
1114
+ this.cache.delete(ip);
1014
1115
  this.cache.set(ip, {
1015
1116
  data,
1016
1117
  expiresAt: Date.now() + this.ttlMs
1017
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
+ }
1018
1123
  }
1019
1124
  return data;
1020
1125
  }
@@ -2251,7 +2356,8 @@ var WebDecoy = class {
2251
2356
  if (this.decisionCache) this.decisionCache.set(key, decision);
2252
2357
  return decision;
2253
2358
  } catch (error) {
2254
- 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", {
2255
2361
  error: error instanceof Error ? error.message : String(error)
2256
2362
  });
2257
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-JV5P2YEA.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.2",
3
+ "version": "0.18.4",
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",