@webdecoy/node 0.1.1 → 0.2.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.mjs CHANGED
@@ -79,6 +79,34 @@ var WebDecoyClient = class {
79
79
  throw error;
80
80
  }
81
81
  }
82
+ /**
83
+ * Send violation events to the ingest service
84
+ */
85
+ async sendViolations(events) {
86
+ try {
87
+ await this.axios.post("/api/v1/sdk/violations/batch", { events });
88
+ } catch (error) {
89
+ if (this.config.debug) {
90
+ console.error("[WebDecoy] Failed to send violations:", error);
91
+ }
92
+ }
93
+ }
94
+ /**
95
+ * Get IP enrichment data from the ingest service
96
+ */
97
+ async getIPEnrichment(ip) {
98
+ try {
99
+ const response = await this.axios.get(
100
+ `/api/v1/sdk/ip/${encodeURIComponent(ip)}/enrichment`
101
+ );
102
+ return response.data;
103
+ } catch (error) {
104
+ if (this.config.debug) {
105
+ console.error("[WebDecoy] Failed to get IP enrichment:", error);
106
+ }
107
+ return null;
108
+ }
109
+ }
82
110
  /**
83
111
  * Validate the API key by making a test request
84
112
  */
@@ -234,16 +262,179 @@ function analyzeRequest(metadata) {
234
262
  };
235
263
  }
236
264
 
265
+ // src/rules/rule-engine.ts
266
+ var RuleEngine = class {
267
+ constructor(rules) {
268
+ this.rules = rules;
269
+ }
270
+ /**
271
+ * Evaluate all rules against the request context.
272
+ * First DENY or THROTTLE result wins. Violations are recorded for all non-ALLOW results.
273
+ */
274
+ evaluate(context) {
275
+ const violations = [];
276
+ let decidingResult = null;
277
+ for (const rule of this.rules) {
278
+ const result = rule.evaluate(context);
279
+ if (result.action !== "ALLOW") {
280
+ violations.push({
281
+ rule: result.rule,
282
+ action: result.action,
283
+ ip: context.ip,
284
+ path: context.path,
285
+ method: context.method,
286
+ userAgent: context.userAgent,
287
+ reason: result.reason,
288
+ metadata: result.metadata,
289
+ dryRun: result.metadata?.dryRun === true,
290
+ timestamp: new Date(context.timestamp).toISOString()
291
+ });
292
+ if (!decidingResult && !result.metadata?.dryRun) {
293
+ decidingResult = result;
294
+ }
295
+ }
296
+ }
297
+ if (decidingResult) {
298
+ return {
299
+ action: decidingResult.action,
300
+ rule: decidingResult.rule,
301
+ reason: decidingResult.reason,
302
+ metadata: decidingResult.metadata,
303
+ violations
304
+ };
305
+ }
306
+ return {
307
+ action: "ALLOW",
308
+ violations
309
+ };
310
+ }
311
+ /**
312
+ * Clean up all rule resources
313
+ */
314
+ destroy() {
315
+ for (const rule of this.rules) {
316
+ rule.destroy?.();
317
+ }
318
+ }
319
+ };
320
+
321
+ // src/violation-reporter.ts
322
+ var ViolationReporter = class {
323
+ constructor(client, config = {}) {
324
+ this.buffer = [];
325
+ this.flushing = false;
326
+ this.client = client;
327
+ this.maxBufferSize = config.maxBufferSize ?? 50;
328
+ this.debug = config.debug ?? false;
329
+ const flushInterval = config.flushInterval ?? 5e3;
330
+ this.flushTimer = setInterval(() => this.flush(), flushInterval);
331
+ if (this.flushTimer.unref) {
332
+ this.flushTimer.unref();
333
+ }
334
+ }
335
+ /**
336
+ * Add violations to the buffer. Auto-flushes when buffer reaches maxBufferSize.
337
+ */
338
+ report(violations) {
339
+ this.buffer.push(...violations);
340
+ if (this.buffer.length >= this.maxBufferSize) {
341
+ this.flush().catch(() => {
342
+ });
343
+ }
344
+ }
345
+ /**
346
+ * Flush buffered violations to the backend
347
+ */
348
+ async flush() {
349
+ if (this.flushing || this.buffer.length === 0) return;
350
+ this.flushing = true;
351
+ const events = this.buffer.splice(0, this.buffer.length);
352
+ try {
353
+ for (let i = 0; i < events.length; i += 100) {
354
+ const batch = events.slice(i, i + 100);
355
+ await this.client.sendViolations(batch);
356
+ if (this.debug) {
357
+ console.log(`[WebDecoy] Flushed ${batch.length} violation events`);
358
+ }
359
+ }
360
+ } catch (error) {
361
+ if (this.debug) {
362
+ console.error("[WebDecoy] Failed to flush violations:", error);
363
+ }
364
+ } finally {
365
+ this.flushing = false;
366
+ }
367
+ }
368
+ /**
369
+ * Flush remaining events and stop the timer
370
+ */
371
+ async destroy() {
372
+ clearInterval(this.flushTimer);
373
+ await this.flush();
374
+ }
375
+ };
376
+
377
+ // src/ip-enrichment.ts
378
+ var IPEnrichmentClient = class {
379
+ constructor(client, ttlMs = 36e5) {
380
+ this.cache = /* @__PURE__ */ new Map();
381
+ this.pending = /* @__PURE__ */ new Map();
382
+ this.client = client;
383
+ this.ttlMs = ttlMs;
384
+ }
385
+ /**
386
+ * Get enrichment data for an IP address.
387
+ * Returns cached data if available (1h TTL), otherwise fetches from API.
388
+ * Returns null if enrichment fails (fail-open).
389
+ */
390
+ async enrich(ip) {
391
+ const cached = this.cache.get(ip);
392
+ if (cached && cached.expiresAt > Date.now()) {
393
+ return cached.data;
394
+ }
395
+ const inflight = this.pending.get(ip);
396
+ if (inflight) {
397
+ return inflight;
398
+ }
399
+ const promise = this.fetchAndCache(ip);
400
+ this.pending.set(ip, promise);
401
+ try {
402
+ return await promise;
403
+ } finally {
404
+ this.pending.delete(ip);
405
+ }
406
+ }
407
+ async fetchAndCache(ip) {
408
+ const data = await this.client.getIPEnrichment(ip);
409
+ if (data) {
410
+ this.cache.set(ip, {
411
+ data,
412
+ expiresAt: Date.now() + this.ttlMs
413
+ });
414
+ }
415
+ return data;
416
+ }
417
+ /**
418
+ * Clear the cache
419
+ */
420
+ clearCache() {
421
+ this.cache.clear();
422
+ }
423
+ };
424
+
237
425
  // src/sdk.ts
238
426
  var WebDecoy = class {
239
427
  constructor(config) {
240
- if (!config.apiKey) {
241
- throw new Error("API key is required. Please provide a valid Web Decoy API key.");
242
- }
243
- if (!config.apiKey.startsWith("sk_live_") && !config.apiKey.startsWith("sk_test_")) {
244
- throw new Error(
245
- 'Invalid API key format. API key should start with "sk_live_" or "sk_test_".'
246
- );
428
+ this.violationReporter = null;
429
+ this.ipEnrichmentClient = null;
430
+ this._hasFilterRules = false;
431
+ const hasApiKey = !!config.apiKey;
432
+ if (hasApiKey) {
433
+ if (!config.apiKey.startsWith("sk_live_") && !config.apiKey.startsWith("sk_test_")) {
434
+ throw new Error(
435
+ 'Invalid API key format. API key should start with "sk_live_" or "sk_test_".'
436
+ );
437
+ }
247
438
  }
248
439
  this.config = {
249
440
  apiKey: config.apiKey,
@@ -254,21 +445,99 @@ var WebDecoy = class {
254
445
  debug: config.debug ?? false,
255
446
  tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true
256
447
  };
257
- this.client = new WebDecoyClient({
258
- apiKey: this.config.apiKey,
259
- apiUrl: this.config.apiUrl,
260
- timeout: this.config.timeout,
261
- debug: this.config.debug,
262
- tlsRejectUnauthorized: this.config.tlsRejectUnauthorized
263
- });
448
+ if (hasApiKey) {
449
+ this.client = new WebDecoyClient({
450
+ apiKey: config.apiKey,
451
+ apiUrl: this.config.apiUrl,
452
+ timeout: this.config.timeout,
453
+ debug: this.config.debug,
454
+ tlsRejectUnauthorized: this.config.tlsRejectUnauthorized
455
+ });
456
+ } else {
457
+ this.client = null;
458
+ if (this.config.debug) {
459
+ console.log("[WebDecoy] Running in local-only mode (no API key). Rules will still evaluate.");
460
+ }
461
+ }
462
+ if (config.rules && config.rules.length > 0) {
463
+ this.ruleEngine = new RuleEngine(config.rules);
464
+ this._hasFilterRules = config.rules.some(
465
+ (r) => r.name.startsWith("filter:")
466
+ );
467
+ } else {
468
+ this.ruleEngine = null;
469
+ }
470
+ if (this.client && this._hasFilterRules) {
471
+ this.ipEnrichmentClient = new IPEnrichmentClient(this.client);
472
+ }
473
+ if (this.client && this.ruleEngine) {
474
+ const reporter = new ViolationReporter(this.client, {
475
+ debug: this.config.debug
476
+ });
477
+ this.setViolationReporter(reporter);
478
+ }
264
479
  if (this.config.debug) {
265
480
  console.log("[WebDecoy] Initialized with config:", {
266
481
  apiUrl: this.config.apiUrl,
267
482
  enableTLSFingerprinting: this.config.enableTLSFingerprinting,
268
- threatScoreThreshold: this.config.threatScoreThreshold
483
+ threatScoreThreshold: this.config.threatScoreThreshold,
484
+ hasApiKey,
485
+ rulesCount: config.rules?.length ?? 0
269
486
  });
270
487
  }
271
488
  }
489
+ /**
490
+ * Evaluate rules against request metadata (synchronous).
491
+ * Returns null if no rules are configured.
492
+ */
493
+ evaluateRules(metadata) {
494
+ if (!this.ruleEngine) return null;
495
+ const context = {
496
+ ip: metadata.ip,
497
+ path: metadata.path,
498
+ method: metadata.method,
499
+ userAgent: metadata.user_agent,
500
+ headers: metadata.headers,
501
+ timestamp: metadata.timestamp || Date.now()
502
+ };
503
+ const result = this.ruleEngine.evaluate(context);
504
+ if (result.violations.length > 0 && this.violationReporter) {
505
+ this.violationReporter.report(result.violations);
506
+ }
507
+ return result;
508
+ }
509
+ /**
510
+ * Evaluate rules with async IP enrichment pre-fetch.
511
+ * Use this instead of evaluateRules() when filter rules are present.
512
+ */
513
+ async evaluateRulesAsync(metadata) {
514
+ if (!this.ruleEngine) return null;
515
+ const context = {
516
+ ip: metadata.ip,
517
+ path: metadata.path,
518
+ method: metadata.method,
519
+ userAgent: metadata.user_agent,
520
+ headers: metadata.headers,
521
+ timestamp: metadata.timestamp || Date.now()
522
+ };
523
+ if (this._hasFilterRules && this.ipEnrichmentClient) {
524
+ const enrichment = await this.ipEnrichmentClient.enrich(metadata.ip);
525
+ if (enrichment) {
526
+ context.enrichment = enrichment;
527
+ }
528
+ }
529
+ const result = this.ruleEngine.evaluate(context);
530
+ if (result.violations.length > 0 && this.violationReporter) {
531
+ this.violationReporter.report(result.violations);
532
+ }
533
+ return result;
534
+ }
535
+ /**
536
+ * Whether this SDK instance has filter rules that need async enrichment
537
+ */
538
+ get hasFilterRules() {
539
+ return this._hasFilterRules;
540
+ }
272
541
  /**
273
542
  * Protect a request by checking it against Web Decoy's bot detection
274
543
  *
@@ -284,6 +553,49 @@ var WebDecoy = class {
284
553
  if (!metadata.timestamp) {
285
554
  metadata.timestamp = Date.now();
286
555
  }
556
+ const ruleResult = this._hasFilterRules ? await this.evaluateRulesAsync(metadata) : this.evaluateRules(metadata);
557
+ if (ruleResult && ruleResult.action === "DENY") {
558
+ return {
559
+ allowed: false,
560
+ detection: {
561
+ decision: "block",
562
+ confidence: 100,
563
+ threat_level: "HIGH",
564
+ bot_detected: false,
565
+ detection_id: "rule_" + Date.now(),
566
+ rule_enforced: true
567
+ },
568
+ ruleResult
569
+ };
570
+ }
571
+ if (ruleResult && ruleResult.action === "THROTTLE") {
572
+ return {
573
+ allowed: false,
574
+ detection: {
575
+ decision: "block",
576
+ confidence: 100,
577
+ threat_level: "MEDIUM",
578
+ bot_detected: false,
579
+ detection_id: "rule_" + Date.now(),
580
+ rule_enforced: true
581
+ },
582
+ ruleResult
583
+ };
584
+ }
585
+ if (!this.client) {
586
+ return {
587
+ allowed: true,
588
+ detection: {
589
+ decision: "allow",
590
+ confidence: 0,
591
+ threat_level: "MINIMAL",
592
+ bot_detected: false,
593
+ detection_id: "local_" + Date.now(),
594
+ rule_enforced: false
595
+ },
596
+ ruleResult: ruleResult ?? void 0
597
+ };
598
+ }
287
599
  const localAnalysis = options.skipLocalAnalysis ? {
288
600
  suspicious_headers: false,
289
601
  missing_sec_ch_ua: false,
@@ -310,7 +622,8 @@ var WebDecoy = class {
310
622
  bot_detected: false,
311
623
  detection_id: "local_" + Date.now(),
312
624
  rule_enforced: false
313
- }
625
+ },
626
+ ruleResult: ruleResult ?? void 0
314
627
  };
315
628
  }
316
629
  const detection = await this.client.detect(detectionRequest);
@@ -325,7 +638,8 @@ var WebDecoy = class {
325
638
  }
326
639
  return {
327
640
  allowed,
328
- detection
641
+ detection,
642
+ ruleResult: ruleResult ?? void 0
329
643
  };
330
644
  } catch (error) {
331
645
  if (this.config.debug) {
@@ -351,6 +665,9 @@ var WebDecoy = class {
351
665
  * Useful for testing integration during setup
352
666
  */
353
667
  async validateConfig() {
668
+ if (!this.client) {
669
+ return { valid: false, error: "No API key configured" };
670
+ }
354
671
  try {
355
672
  const isValid = await this.client.validateAPIKey();
356
673
  return { valid: isValid };
@@ -361,13 +678,628 @@ var WebDecoy = class {
361
678
  };
362
679
  }
363
680
  }
681
+ /**
682
+ * Attach a violation reporter for sending violations to the backend.
683
+ * Called internally when apiKey is present and rules are configured.
684
+ */
685
+ setViolationReporter(reporter) {
686
+ this.violationReporter = reporter;
687
+ }
688
+ /**
689
+ * Get the API client (for use by violation reporter, enrichment, etc.)
690
+ */
691
+ getClient() {
692
+ return this.client;
693
+ }
364
694
  /**
365
695
  * Get the current configuration
366
696
  */
367
697
  getConfig() {
368
698
  return { ...this.config };
369
699
  }
700
+ /**
701
+ * Clean up resources (timers, flush pending violations)
702
+ */
703
+ async destroy() {
704
+ this.ruleEngine?.destroy();
705
+ if (this.violationReporter) {
706
+ await this.violationReporter.destroy();
707
+ }
708
+ }
709
+ };
710
+
711
+ // src/rules/rate-limiter.ts
712
+ var InMemoryRateLimiter = class {
713
+ constructor() {
714
+ this.fixedWindows = /* @__PURE__ */ new Map();
715
+ this.slidingWindows = /* @__PURE__ */ new Map();
716
+ this.cleanupTimer = setInterval(() => this.cleanup(), 6e4);
717
+ if (this.cleanupTimer.unref) {
718
+ this.cleanupTimer.unref();
719
+ }
720
+ }
721
+ /**
722
+ * Check and increment for fixed window algorithm
723
+ * Returns the current count after increment, and the window reset time
724
+ */
725
+ checkFixedWindow(key, max, windowMs) {
726
+ const now = Date.now();
727
+ const entry = this.fixedWindows.get(key);
728
+ if (!entry || now - entry.windowStart >= windowMs) {
729
+ this.fixedWindows.set(key, { count: 1, windowStart: now });
730
+ return { allowed: true, current: 1, resetAt: now + windowMs };
731
+ }
732
+ entry.count++;
733
+ const resetAt = entry.windowStart + windowMs;
734
+ if (entry.count > max) {
735
+ return { allowed: false, current: entry.count, resetAt };
736
+ }
737
+ return { allowed: true, current: entry.count, resetAt };
738
+ }
739
+ /**
740
+ * Check and increment for sliding window algorithm
741
+ * Returns the current count after adding the new timestamp
742
+ */
743
+ checkSlidingWindow(key, max, windowMs) {
744
+ const now = Date.now();
745
+ const cutoff = now - windowMs;
746
+ let timestamps = this.slidingWindows.get(key);
747
+ if (!timestamps) {
748
+ timestamps = [];
749
+ this.slidingWindows.set(key, timestamps);
750
+ }
751
+ while (timestamps.length > 0 && timestamps[0] <= cutoff) {
752
+ timestamps.shift();
753
+ }
754
+ timestamps.push(now);
755
+ const resetAt = timestamps.length > 0 ? timestamps[0] + windowMs : now + windowMs;
756
+ if (timestamps.length > max) {
757
+ return { allowed: false, current: timestamps.length, resetAt };
758
+ }
759
+ return { allowed: true, current: timestamps.length, resetAt };
760
+ }
761
+ /**
762
+ * Clean up expired entries from both maps
763
+ */
764
+ cleanup() {
765
+ const now = Date.now();
766
+ for (const [key, entry] of this.fixedWindows) {
767
+ if (now - entry.windowStart > 3e5) {
768
+ this.fixedWindows.delete(key);
769
+ }
770
+ }
771
+ for (const [key, timestamps] of this.slidingWindows) {
772
+ if (timestamps.length === 0) {
773
+ this.slidingWindows.delete(key);
774
+ continue;
775
+ }
776
+ const latest = timestamps[timestamps.length - 1];
777
+ if (now - latest > 3e5) {
778
+ this.slidingWindows.delete(key);
779
+ }
780
+ }
781
+ }
782
+ /**
783
+ * Release resources
784
+ */
785
+ destroy() {
786
+ clearInterval(this.cleanupTimer);
787
+ this.fixedWindows.clear();
788
+ this.slidingWindows.clear();
789
+ }
790
+ };
791
+
792
+ // src/rules/rate-limit-rule.ts
793
+ var RateLimitRule = class {
794
+ constructor(config) {
795
+ this.name = `rate-limit:${config.max}/${config.window}s`;
796
+ this.limiter = new InMemoryRateLimiter();
797
+ this.config = {
798
+ max: config.max,
799
+ window: config.window,
800
+ algorithm: config.algorithm ?? "fixed",
801
+ keyBy: config.keyBy,
802
+ action: config.action ?? "THROTTLE",
803
+ dryRun: config.dryRun ?? false
804
+ };
805
+ }
806
+ evaluate(context) {
807
+ const key = this.config.keyBy ? this.config.keyBy(context) : context.ip;
808
+ const windowMs = this.config.window * 1e3;
809
+ const result = this.config.algorithm === "sliding" ? this.limiter.checkSlidingWindow(key, this.config.max, windowMs) : this.limiter.checkFixedWindow(key, this.config.max, windowMs);
810
+ if (!result.allowed) {
811
+ const retryAfter = Math.ceil((result.resetAt - Date.now()) / 1e3);
812
+ return {
813
+ action: this.config.dryRun ? "ALLOW" : this.config.action,
814
+ rule: this.name,
815
+ reason: `Rate limit exceeded: ${result.current}/${this.config.max} requests in ${this.config.window}s window`,
816
+ metadata: {
817
+ current: result.current,
818
+ max: this.config.max,
819
+ window: this.config.window,
820
+ retryAfter: Math.max(retryAfter, 1),
821
+ dryRun: this.config.dryRun
822
+ }
823
+ };
824
+ }
825
+ return {
826
+ action: "ALLOW",
827
+ rule: this.name,
828
+ metadata: {
829
+ current: result.current,
830
+ max: this.config.max,
831
+ remaining: this.config.max - result.current
832
+ }
833
+ };
834
+ }
835
+ destroy() {
836
+ this.limiter.destroy();
837
+ }
838
+ };
839
+
840
+ // src/rules/filter/tokenizer.ts
841
+ var KEYWORDS = {
842
+ and: "AND" /* AND */,
843
+ or: "OR" /* OR */,
844
+ not: "NOT" /* NOT */,
845
+ in: "IN" /* IN */,
846
+ matches: "MATCHES" /* MATCHES */,
847
+ true: "BOOL" /* BOOL */,
848
+ false: "BOOL" /* BOOL */
849
+ };
850
+ var Tokenizer = class {
851
+ constructor(source) {
852
+ this.pos = 0;
853
+ this.tokens = [];
854
+ this.source = source;
855
+ }
856
+ tokenize() {
857
+ while (this.pos < this.source.length) {
858
+ this.skipWhitespace();
859
+ if (this.pos >= this.source.length) break;
860
+ const ch = this.source[this.pos];
861
+ if (ch === ".") {
862
+ this.tokens.push({ type: "DOT" /* DOT */, value: ".", position: this.pos });
863
+ this.pos++;
864
+ continue;
865
+ }
866
+ if (ch === "(") {
867
+ this.tokens.push({ type: "LPAREN" /* LPAREN */, value: "(", position: this.pos });
868
+ this.pos++;
869
+ continue;
870
+ }
871
+ if (ch === ")") {
872
+ this.tokens.push({ type: "RPAREN" /* RPAREN */, value: ")", position: this.pos });
873
+ this.pos++;
874
+ continue;
875
+ }
876
+ if (ch === "[") {
877
+ this.tokens.push({ type: "LBRACKET" /* LBRACKET */, value: "[", position: this.pos });
878
+ this.pos++;
879
+ continue;
880
+ }
881
+ if (ch === "]") {
882
+ this.tokens.push({ type: "RBRACKET" /* RBRACKET */, value: "]", position: this.pos });
883
+ this.pos++;
884
+ continue;
885
+ }
886
+ if (ch === ",") {
887
+ this.tokens.push({ type: "COMMA" /* COMMA */, value: ",", position: this.pos });
888
+ this.pos++;
889
+ continue;
890
+ }
891
+ if (ch === "=" && this.peek(1) === "=") {
892
+ this.tokens.push({ type: "EQ" /* EQ */, value: "==", position: this.pos });
893
+ this.pos += 2;
894
+ continue;
895
+ }
896
+ if (ch === "!" && this.peek(1) === "=") {
897
+ this.tokens.push({ type: "NEQ" /* NEQ */, value: "!=", position: this.pos });
898
+ this.pos += 2;
899
+ continue;
900
+ }
901
+ if (ch === ">" && this.peek(1) === "=") {
902
+ this.tokens.push({ type: "GTE" /* GTE */, value: ">=", position: this.pos });
903
+ this.pos += 2;
904
+ continue;
905
+ }
906
+ if (ch === "<" && this.peek(1) === "=") {
907
+ this.tokens.push({ type: "LTE" /* LTE */, value: "<=", position: this.pos });
908
+ this.pos += 2;
909
+ continue;
910
+ }
911
+ if (ch === ">") {
912
+ this.tokens.push({ type: "GT" /* GT */, value: ">", position: this.pos });
913
+ this.pos++;
914
+ continue;
915
+ }
916
+ if (ch === "<") {
917
+ this.tokens.push({ type: "LT" /* LT */, value: "<", position: this.pos });
918
+ this.pos++;
919
+ continue;
920
+ }
921
+ if (ch === '"' || ch === "'") {
922
+ this.readString(ch);
923
+ continue;
924
+ }
925
+ if (this.isDigit(ch) || ch === "-" && this.isDigit(this.peek(1))) {
926
+ this.readNumber();
927
+ continue;
928
+ }
929
+ if (this.isIdentStart(ch)) {
930
+ this.readIdent();
931
+ continue;
932
+ }
933
+ throw new Error(`Unexpected character '${ch}' at position ${this.pos}`);
934
+ }
935
+ this.tokens.push({ type: "EOF" /* EOF */, value: "", position: this.pos });
936
+ return this.tokens;
937
+ }
938
+ peek(offset) {
939
+ const idx = this.pos + offset;
940
+ return idx < this.source.length ? this.source[idx] : "";
941
+ }
942
+ skipWhitespace() {
943
+ while (this.pos < this.source.length && /\s/.test(this.source[this.pos])) {
944
+ this.pos++;
945
+ }
946
+ }
947
+ readString(quote) {
948
+ const start = this.pos;
949
+ this.pos++;
950
+ let value = "";
951
+ while (this.pos < this.source.length && this.source[this.pos] !== quote) {
952
+ if (this.source[this.pos] === "\\") {
953
+ this.pos++;
954
+ }
955
+ value += this.source[this.pos];
956
+ this.pos++;
957
+ }
958
+ if (this.pos >= this.source.length) {
959
+ throw new Error(`Unterminated string at position ${start}`);
960
+ }
961
+ this.pos++;
962
+ this.tokens.push({ type: "STRING" /* STRING */, value, position: start });
963
+ }
964
+ readNumber() {
965
+ const start = this.pos;
966
+ if (this.source[this.pos] === "-") this.pos++;
967
+ while (this.pos < this.source.length && this.isDigit(this.source[this.pos])) {
968
+ this.pos++;
969
+ }
970
+ if (this.pos < this.source.length && this.source[this.pos] === ".") {
971
+ this.pos++;
972
+ while (this.pos < this.source.length && this.isDigit(this.source[this.pos])) {
973
+ this.pos++;
974
+ }
975
+ }
976
+ this.tokens.push({ type: "NUMBER" /* NUMBER */, value: this.source.slice(start, this.pos), position: start });
977
+ }
978
+ readIdent() {
979
+ const start = this.pos;
980
+ while (this.pos < this.source.length && this.isIdentPart(this.source[this.pos])) {
981
+ this.pos++;
982
+ }
983
+ const value = this.source.slice(start, this.pos);
984
+ const keyword = KEYWORDS[value.toLowerCase()];
985
+ if (keyword) {
986
+ this.tokens.push({ type: keyword, value: value.toLowerCase(), position: start });
987
+ } else {
988
+ this.tokens.push({ type: "IDENT" /* IDENT */, value, position: start });
989
+ }
990
+ }
991
+ isDigit(ch) {
992
+ return ch >= "0" && ch <= "9";
993
+ }
994
+ isIdentStart(ch) {
995
+ return /[a-zA-Z_]/.test(ch);
996
+ }
997
+ isIdentPart(ch) {
998
+ return /[a-zA-Z0-9_]/.test(ch);
999
+ }
1000
+ };
1001
+
1002
+ // src/rules/filter/parser.ts
1003
+ var Parser = class {
1004
+ constructor(source) {
1005
+ this.pos = 0;
1006
+ this.tokens = new Tokenizer(source).tokenize();
1007
+ }
1008
+ parse() {
1009
+ const ast = this.orExpr();
1010
+ this.expect("EOF" /* EOF */, "Expected end of expression");
1011
+ return ast;
1012
+ }
1013
+ orExpr() {
1014
+ let left = this.andExpr();
1015
+ while (this.match("OR" /* OR */)) {
1016
+ const right = this.andExpr();
1017
+ left = { kind: "binary", op: "or", left, right };
1018
+ }
1019
+ return left;
1020
+ }
1021
+ andExpr() {
1022
+ let left = this.unary();
1023
+ while (this.match("AND" /* AND */)) {
1024
+ const right = this.unary();
1025
+ left = { kind: "binary", op: "and", left, right };
1026
+ }
1027
+ return left;
1028
+ }
1029
+ unary() {
1030
+ if (this.match("NOT" /* NOT */)) {
1031
+ if (this.check("IN" /* IN */)) {
1032
+ this.pos--;
1033
+ return this.comparison();
1034
+ }
1035
+ const operand = this.unary();
1036
+ return { kind: "unary", op: "not", operand };
1037
+ }
1038
+ return this.comparison();
1039
+ }
1040
+ comparison() {
1041
+ let left = this.primary();
1042
+ if (this.match("EQ" /* EQ */)) return { kind: "binary", op: "==", left, right: this.primary() };
1043
+ if (this.match("NEQ" /* NEQ */)) return { kind: "binary", op: "!=", left, right: this.primary() };
1044
+ if (this.match("GT" /* GT */)) return { kind: "binary", op: ">", left, right: this.primary() };
1045
+ if (this.match("GTE" /* GTE */)) return { kind: "binary", op: ">=", left, right: this.primary() };
1046
+ if (this.match("LT" /* LT */)) return { kind: "binary", op: "<", left, right: this.primary() };
1047
+ if (this.match("LTE" /* LTE */)) return { kind: "binary", op: "<=", left, right: this.primary() };
1048
+ if (this.match("IN" /* IN */)) return { kind: "binary", op: "in", left, right: this.primary() };
1049
+ if (this.match("MATCHES" /* MATCHES */)) return { kind: "binary", op: "matches", left, right: this.primary() };
1050
+ if (this.check("NOT" /* NOT */) && this.checkAhead("IN" /* IN */)) {
1051
+ this.advance();
1052
+ this.advance();
1053
+ return { kind: "binary", op: "not in", left, right: this.primary() };
1054
+ }
1055
+ return left;
1056
+ }
1057
+ primary() {
1058
+ if (this.check("BOOL" /* BOOL */)) {
1059
+ const token = this.advance();
1060
+ return { kind: "bool", value: token.value === "true" };
1061
+ }
1062
+ if (this.check("NUMBER" /* NUMBER */)) {
1063
+ const token = this.advance();
1064
+ return { kind: "number", value: parseFloat(token.value) };
1065
+ }
1066
+ if (this.check("STRING" /* STRING */)) {
1067
+ const token = this.advance();
1068
+ return { kind: "string", value: token.value };
1069
+ }
1070
+ if (this.match("LBRACKET" /* LBRACKET */)) {
1071
+ const elements = [];
1072
+ if (!this.check("RBRACKET" /* RBRACKET */)) {
1073
+ elements.push(this.primary());
1074
+ while (this.match("COMMA" /* COMMA */)) {
1075
+ elements.push(this.primary());
1076
+ }
1077
+ }
1078
+ this.expect("RBRACKET" /* RBRACKET */, 'Expected "]"');
1079
+ return { kind: "array", elements };
1080
+ }
1081
+ if (this.match("LPAREN" /* LPAREN */)) {
1082
+ const expr = this.orExpr();
1083
+ this.expect("RPAREN" /* RPAREN */, 'Expected ")"');
1084
+ return expr;
1085
+ }
1086
+ if (this.check("IDENT" /* IDENT */)) {
1087
+ const path = [this.advance().value];
1088
+ while (this.match("DOT" /* DOT */)) {
1089
+ if (!this.check("IDENT" /* IDENT */)) {
1090
+ throw new Error(`Expected identifier after "." at position ${this.current().position}`);
1091
+ }
1092
+ path.push(this.advance().value);
1093
+ }
1094
+ if (this.match("LPAREN" /* LPAREN */)) {
1095
+ const method = path.pop();
1096
+ const args = [];
1097
+ if (!this.check("RPAREN" /* RPAREN */)) {
1098
+ args.push(this.primary());
1099
+ while (this.match("COMMA" /* COMMA */)) {
1100
+ args.push(this.primary());
1101
+ }
1102
+ }
1103
+ this.expect("RPAREN" /* RPAREN */, 'Expected ")"');
1104
+ return { kind: "call", object: path, method, args };
1105
+ }
1106
+ return { kind: "property", path };
1107
+ }
1108
+ throw new Error(`Unexpected token "${this.current().value}" at position ${this.current().position}`);
1109
+ }
1110
+ // Helper methods
1111
+ current() {
1112
+ return this.tokens[this.pos];
1113
+ }
1114
+ advance() {
1115
+ return this.tokens[this.pos++];
1116
+ }
1117
+ check(type) {
1118
+ return this.current().type === type;
1119
+ }
1120
+ checkAhead(type) {
1121
+ return this.pos + 1 < this.tokens.length && this.tokens[this.pos + 1].type === type;
1122
+ }
1123
+ match(type) {
1124
+ if (this.check(type)) {
1125
+ this.advance();
1126
+ return true;
1127
+ }
1128
+ return false;
1129
+ }
1130
+ expect(type, message) {
1131
+ if (this.check(type)) return this.advance();
1132
+ throw new Error(`${message}, got "${this.current().value}" at position ${this.current().position}`);
1133
+ }
370
1134
  };
1135
+
1136
+ // src/rules/filter/evaluator.ts
1137
+ var MAX_REGEX_LENGTH = 500;
1138
+ function evaluate(node, context) {
1139
+ switch (node.kind) {
1140
+ case "bool":
1141
+ return node.value;
1142
+ case "number":
1143
+ return node.value;
1144
+ case "string":
1145
+ return node.value;
1146
+ case "array":
1147
+ return node.elements.map((el) => evaluate(el, context));
1148
+ case "property":
1149
+ return resolveProperty(node.path, context);
1150
+ case "call":
1151
+ return resolveCall(node.object, node.method, node.args, context);
1152
+ case "unary":
1153
+ return evaluateUnary(node.op, node.operand, context);
1154
+ case "binary":
1155
+ return evaluateBinary(node.op, node.left, node.right, context);
1156
+ }
1157
+ }
1158
+ function resolveProperty(path, context) {
1159
+ const namespace = path[0];
1160
+ const prop = path.slice(1).join(".");
1161
+ if (namespace === "ip") {
1162
+ const e = context.enrichment;
1163
+ if (!e) return void 0;
1164
+ if (prop === "vpn") return e.security.vpn;
1165
+ if (prop === "proxy") return e.security.proxy;
1166
+ if (prop === "tor") return e.security.tor;
1167
+ if (prop === "relay") return e.security.relay;
1168
+ if (prop === "hosting") return e.security.hosting;
1169
+ if (prop === "country") return e.location.country;
1170
+ if (prop === "country_name") return e.location.country_name;
1171
+ if (prop === "city") return e.location.city;
1172
+ if (prop === "timezone") return e.location.timezone;
1173
+ if (prop === "asn") return e.network.asn;
1174
+ if (prop === "asn_org") return e.network.asn_org;
1175
+ if (prop === "abuse_score") return e.reputation.abuse_score;
1176
+ if (prop === "total_reports") return e.reputation.total_reports;
1177
+ if (prop === "is_high_risk") return e.reputation.is_high_risk;
1178
+ return void 0;
1179
+ }
1180
+ if (namespace === "req") {
1181
+ if (prop === "path") return context.path;
1182
+ if (prop === "method") return context.method;
1183
+ if (prop === "ip") return context.ip;
1184
+ if (prop === "user_agent") return context.userAgent;
1185
+ return void 0;
1186
+ }
1187
+ if (path.length === 1) return void 0;
1188
+ return void 0;
1189
+ }
1190
+ function resolveCall(object, method, args, context) {
1191
+ const namespace = object[0];
1192
+ if (namespace === "req" && method === "header") {
1193
+ if (args.length !== 1) return void 0;
1194
+ const headerName = evaluate(args[0], context);
1195
+ if (typeof headerName !== "string") return void 0;
1196
+ return context.headers[headerName.toLowerCase()];
1197
+ }
1198
+ return void 0;
1199
+ }
1200
+ function evaluateUnary(op, operand, context) {
1201
+ const val = evaluate(operand, context);
1202
+ if (op === "not") {
1203
+ if (val === void 0) return false;
1204
+ return !val;
1205
+ }
1206
+ return void 0;
1207
+ }
1208
+ function evaluateBinary(op, left, right, context) {
1209
+ if (op === "and") {
1210
+ const l2 = evaluate(left, context);
1211
+ if (l2 === void 0 || l2 === false) return false;
1212
+ const r2 = evaluate(right, context);
1213
+ if (r2 === void 0) return false;
1214
+ return !!r2;
1215
+ }
1216
+ if (op === "or") {
1217
+ const l2 = evaluate(left, context);
1218
+ if (l2 === void 0 ? false : !!l2) return true;
1219
+ const r2 = evaluate(right, context);
1220
+ if (r2 === void 0) return false;
1221
+ return !!r2;
1222
+ }
1223
+ const l = evaluate(left, context);
1224
+ const r = evaluate(right, context);
1225
+ if (l === void 0 || r === void 0) return false;
1226
+ switch (op) {
1227
+ case "==":
1228
+ return l === r;
1229
+ case "!=":
1230
+ return l !== r;
1231
+ case ">":
1232
+ return typeof l === "number" && typeof r === "number" && l > r;
1233
+ case ">=":
1234
+ return typeof l === "number" && typeof r === "number" && l >= r;
1235
+ case "<":
1236
+ return typeof l === "number" && typeof r === "number" && l < r;
1237
+ case "<=":
1238
+ return typeof l === "number" && typeof r === "number" && l <= r;
1239
+ case "in": {
1240
+ if (!Array.isArray(r)) return false;
1241
+ return r.includes(l);
1242
+ }
1243
+ case "not in": {
1244
+ if (!Array.isArray(r)) return false;
1245
+ return !r.includes(l);
1246
+ }
1247
+ case "matches": {
1248
+ if (typeof l !== "string" || typeof r !== "string") return false;
1249
+ if (r.length > MAX_REGEX_LENGTH) return false;
1250
+ try {
1251
+ return new RegExp(r).test(l);
1252
+ } catch {
1253
+ return false;
1254
+ }
1255
+ }
1256
+ default:
1257
+ return false;
1258
+ }
1259
+ }
1260
+
1261
+ // src/rules/filter-rule.ts
1262
+ var FilterRule = class {
1263
+ constructor(config) {
1264
+ this.expression = config.expression;
1265
+ this.action = config.action ?? "DENY";
1266
+ this.dryRun = config.dryRun ?? false;
1267
+ this.name = `filter:${this.expression.slice(0, 50)}`;
1268
+ const parser = new Parser(config.expression);
1269
+ this.ast = parser.parse();
1270
+ }
1271
+ evaluate(context) {
1272
+ const result = evaluate(this.ast, context);
1273
+ if (result) {
1274
+ return {
1275
+ action: this.dryRun ? "ALLOW" : this.action,
1276
+ rule: this.name,
1277
+ reason: `Filter matched: ${this.expression}`,
1278
+ metadata: {
1279
+ expression: this.expression,
1280
+ dryRun: this.dryRun
1281
+ }
1282
+ };
1283
+ }
1284
+ return {
1285
+ action: "ALLOW",
1286
+ rule: this.name
1287
+ };
1288
+ }
1289
+ };
1290
+
1291
+ // src/rules/index.ts
1292
+ function rateLimit(config) {
1293
+ return new RateLimitRule(config);
1294
+ }
1295
+ function filter(config) {
1296
+ return new FilterRule(config);
1297
+ }
371
1298
  export {
372
- WebDecoy
1299
+ FilterRule,
1300
+ RateLimitRule,
1301
+ RuleEngine,
1302
+ WebDecoy,
1303
+ filter,
1304
+ rateLimit
373
1305
  };