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