sekant-intercept-js 1.0.2 → 1.0.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.
@@ -26,7 +26,7 @@
26
26
  */
27
27
 
28
28
  import { AhoCorasick } from "./ahocorasickEngine.mjs";
29
- import { parseYaraRuleGroup } from "./yaraRuleCompiler.mjs";
29
+ import { parseYaraRuleGroup, parseInterceptFilterRuleGroup } from "./yaraRuleCompiler.mjs";
30
30
  import { createScanFacts, evaluateCondition } from "./yaraConditionsMatch.mjs";
31
31
  import { parseConditionToAST } from "./yaraConditionParser.mjs";
32
32
  import { parsePEYara, createPEModule } from "./peModule.mjs";
@@ -39,6 +39,27 @@ import { createPerformanceTracker } from "./performanceInstrumentation.mjs";
39
39
  import { MAX_MATCHES } from "./yaraStringMatch.mjs";
40
40
  import { isValidModuleName } from "./interceptCustomModules.mjs";
41
41
 
42
+ /**
43
+ * Longest candidate buffer handed to filter rules. Longer matches keep the candidate and skip
44
+ * filtering, so a filter never decides on a truncated prefix.
45
+ */
46
+ export const MAX_FILTER_RULE_BUFFER_SIZE = 4096;
47
+
48
+ const FILTER_MODULE_BUILTINS = new Set(["string", "time", "math", "hash"]);
49
+
50
+ function hasRejectFilters(strDef) {
51
+ return Boolean(strDef?.reject?.length || strDef?.rejectCapture?.length);
52
+ }
53
+
54
+ function hashBytes(bytes) {
55
+ let hash = 0x811c9dc5;
56
+ for (let i = 0; i < bytes.length; i++) {
57
+ hash ^= bytes[i];
58
+ hash = Math.imul(hash, 0x01000193) >>> 0;
59
+ }
60
+ return hash;
61
+ }
62
+
42
63
  /**
43
64
  * InterceptScanner - A JavaScript implementation of YARA rule scanning engine
44
65
  *
@@ -102,17 +123,29 @@ import { isValidModuleName } from "./interceptCustomModules.mjs";
102
123
  * @property {boolean} autoParsePE - Automatically parse PE files (default: true)
103
124
  * @property {boolean} autoParseELF - Automatically parse ELF files (default: true)
104
125
  * @property {number} maxFileSize - Maximum file size for filesize operator (default: 1MB)
126
+ * @property {number} maxMatches - Maximum matches recorded per string (default: 100)
105
127
  * @property {Object} modules - Available YARA modules (string, time, pe, elf, math, hash)
106
128
  */
107
129
  export class InterceptScanner {
108
130
  constructor(options = {}) {
109
131
  this.compiledRules = [];
132
+ this.compiledFilterRules = [];
133
+ this.filterIndex = new Map();
134
+ this.filterDiagnostics = [];
135
+ this.filterScanDiagnostics = null;
136
+ this.filterDecisionCache = new Map();
137
+ this.filterModuleCache = new Map();
110
138
  this.ac = null;
139
+ this.needsCandidateDedupe = false;
111
140
  this.autoParsePE = true; // Automatically parse PE files
112
141
  this.autoParseELF = true; // Automatically parse ELF files
113
142
  this.maxFileSize = 1024 * 1024; // 1MB default limit for filesize operator
114
143
  this.setModules(options.modules);
115
144
  this.customModules = options.modules || {};
145
+ this.matchLimits = { maxMatches: options.maxMatches ?? MAX_MATCHES };
146
+ // Opt-in capture-group offsets on regex matches. YARA's match record has no capture data, so
147
+ // the default output stays YARA-shaped.
148
+ this.includeCaptures = options.includeCaptures === true;
116
149
  const timingOptions = {
117
150
  enabled: options.timing?.enabled ?? options.timing?.enableTiming ?? options.enableTiming ?? false,
118
151
  autoPrint: options.timing?.autoPrint ?? options.autoPrint ?? false,
@@ -129,8 +162,23 @@ export class InterceptScanner {
129
162
  const tracker = this.timingTracker;
130
163
  const timingEnabled = tracker?.isEnabled();
131
164
  const start = timingEnabled ? tracker.now() : 0;
132
- this.compiledRules = parseYaraRuleGroup(rulesText, this.compiledRules || []);
165
+
166
+ const filterGroup = parseInterceptFilterRuleGroup(rulesText, this.compiledFilterRules || [], {
167
+ limits: this.matchLimits,
168
+ availableModules: this.getAvailableModuleNames(),
169
+ includeCaptures: this.includeCaptures,
170
+ });
171
+ this.compiledFilterRules = filterGroup.rules;
172
+ this.filterDiagnostics = filterGroup.diagnostics || [];
173
+ this.compiledRules = parseYaraRuleGroup(rulesText, this.compiledRules || [], {
174
+ limits: this.matchLimits,
175
+ includeCaptures: this.includeCaptures,
176
+ });
177
+ this.validateFilterRegistry();
178
+ this.rebuildFilterIndex();
179
+
133
180
  this.ac = null; // Reset AC automaton to force rebuild
181
+ this.needsCandidateDedupe = InterceptScanner.hasMultiPatternStrings(this.compiledRules);
134
182
 
135
183
  if (timingEnabled) {
136
184
  tracker.recordCompile(tracker.now() - start);
@@ -152,7 +200,14 @@ export class InterceptScanner {
152
200
  */
153
201
  clearRules() {
154
202
  this.compiledRules = [];
203
+ this.compiledFilterRules = [];
204
+ this.filterIndex = new Map();
205
+ this.filterDiagnostics = [];
206
+ this.filterScanDiagnostics = null;
207
+ this.filterDecisionCache = new Map();
208
+ this.filterModuleCache = new Map();
155
209
  this.ac = null;
210
+ this.needsCandidateDedupe = false;
156
211
  }
157
212
 
158
213
  /**
@@ -191,6 +246,17 @@ export class InterceptScanner {
191
246
  return Array.from(unique.values());
192
247
  }
193
248
 
249
+ /**
250
+ * Whether a string definition expands into several patterns (ascii + wide, base64 permutations).
251
+ * The Aho-Corasick engine already collapses repeated hits of one pattern, so only multi-pattern
252
+ * strings can report the same offset twice.
253
+ */
254
+ static hasMultiPatternStrings(rules) {
255
+ return rules.some((rule) =>
256
+ Object.values(rule.strings ?? {}).some((strDef) => (strDef.patterns?.length ?? 0) > 1)
257
+ );
258
+ }
259
+
194
260
  /**
195
261
  * Verify candidates with full string matchers
196
262
  * @param {Array} candidates - Candidate matches
@@ -200,20 +266,21 @@ export class InterceptScanner {
200
266
  */
201
267
  verifyCandidates(candidates, data, rules) {
202
268
  const verified = [];
269
+ const rulesById = new Map(rules.map((rule) => [rule.id, rule]));
203
270
 
204
271
  for (const candidate of candidates) {
205
- const rule = rules.find((r) => r.id === candidate.id);
272
+ const rule = rulesById.get(candidate.id);
206
273
  if (!rule) continue;
207
274
 
208
275
  const strDef = rule.strings[candidate.varName];
209
276
  if (!strDef || !strDef.matcher) continue;
210
277
 
211
278
  // For text and regex with literal prefix, verify at the candidate offset. `verifyAt` demands
212
- // a match starting exactly there; the plain window-scan form would also return a neighbouring
213
- // occurrence, which duplicates that match and loses this candidate's own.
279
+ // a match starting exactly there; a forward scan would also return a neighbouring occurrence,
280
+ // which duplicates that match and loses this candidate's own.
214
281
  if (strDef.type === "text" || (strDef.type === "regex" && strDef.literalPrefix)) {
215
282
  const matches = typeof strDef.matcher.verifyAt === "function"
216
- ? strDef.matcher.verifyAt(data, candidate.offset)
283
+ ? strDef.matcher.verifyAt(data, candidate.offset, candidate)
217
284
  : strDef.matcher(data, candidate.offset);
218
285
  if (matches && matches.length > 0) {
219
286
  verified.push({
@@ -231,14 +298,17 @@ export class InterceptScanner {
231
298
  }
232
299
 
233
300
  /**
234
- * Build string match results per rule
301
+ * Build string match results per rule. Reject filters are applied here, before any facts are
302
+ * produced, so `#a`, `@a`, and `$a at N` only see surviving matches.
235
303
  * @param {Array} verifiedCandidates - Verified matches
236
304
  * @param {Array} rules - Compiled rules
237
305
  * @param {Uint8Array} data - File data
238
- * @returns {Object} String matches organized by rule
306
+ * @param {Object} metadata - Scan metadata to pass to custom modules
307
+ * @returns {Promise<Object>} String matches organized by rule
239
308
  */
240
- buildStringMatches(verifiedCandidates, rules, data) {
309
+ async buildStringMatches(verifiedCandidates, rules, data, metadata = {}) {
241
310
  const ruleMatches = {};
311
+ const rulesById = new Map(rules.map((rule) => [rule.id, rule]));
242
312
 
243
313
  // Initialize match structure for each rule
244
314
  for (const rule of rules) {
@@ -272,14 +342,24 @@ export class InterceptScanner {
272
342
  const lookupKey = ruleMatches[candidate.id][finalKey] ? finalKey : (finalKey.startsWith('$') ? finalKey : `\$${finalKey}`);
273
343
 
274
344
  const matchInfo = ruleMatches[candidate.id][lookupKey];
345
+ const ownerRule = rulesById.get(candidate.id);
346
+ const strDef = ownerRule?.strings?.[candidate.varName];
275
347
 
276
348
  if (candidate.matches && candidate.matches.length > 0) {
349
+ const keptMatches = hasRejectFilters(strDef)
350
+ ? await this.filterMatches(strDef, candidate.matches, data, metadata, {
351
+ ruleName: ownerRule?.name,
352
+ varName: candidate.varName,
353
+ })
354
+ : candidate.matches;
355
+ if (keptMatches.length === 0) continue;
356
+
277
357
  // Has detailed match information
278
- const prunedList = candidate.matches.length > MAX_MATCHES ? candidate.matches.slice(0, MAX_MATCHES) : candidate.matches;
358
+ const prunedList = keptMatches.length > this.maxMatches ? keptMatches.slice(0, this.maxMatches) : keptMatches;
279
359
  matchInfo.matched = true;
280
360
  matchInfo.count += prunedList.length;
281
361
  matchInfo.matches.push(...prunedList);
282
- matchInfo.offsets.push(...candidate.matches.map((m) => m.offset));
362
+ matchInfo.offsets.push(...prunedList.map((m) => m.offset));
283
363
  // if (prunedList[0].length) {
284
364
  // matchInfo.length = prunedList[0].length;
285
365
  // }
@@ -303,6 +383,9 @@ export class InterceptScanner {
303
383
  for (const rule of rules) {
304
384
  for (const [varName, strDef] of Object.entries(rule.strings)) {
305
385
  if (strDef.type === "text" || (strDef.type === "regex" && strDef.literalPrefix?.length > 0)) continue; // Should be part of AC verified candidates
386
+ // String definitions that failed to compile carry no matcher; their warning was emitted at
387
+ // compile time, and the string simply never matches.
388
+ if (!strDef.matcher) continue;
306
389
 
307
390
  // Handle key lookup (handle $.anon for anonymous)
308
391
  const finalKey = varName.startsWith('.') ? `\$${varName}` : varName;
@@ -319,8 +402,11 @@ export class InterceptScanner {
319
402
 
320
403
  // Run full matcher over entire data (-1 means find ALL matches, not verify at offset 0)
321
404
  let matches = strDef.type === "hex" && dataAsHexString !== null ? strDef.matcher(dataAsHexString, -1) : strDef.matcher(data, -1);
405
+ if (hasRejectFilters(strDef) && matches && matches.length > 0) {
406
+ matches = await this.filterMatches(strDef, matches, data, metadata, { ruleName: rule.name, varName });
407
+ }
322
408
  if (matches && matches.length > 0) {
323
- const prunedList = matches.length > MAX_MATCHES ? matches.slice(0, MAX_MATCHES) : matches;
409
+ const prunedList = matches.length > this.maxMatches ? matches.slice(0, this.maxMatches) : matches;
324
410
  matchInfo.matched = true;
325
411
  matchInfo.count += prunedList.length;
326
412
  if (matchInfo.matches.length === 0) {
@@ -328,7 +414,7 @@ export class InterceptScanner {
328
414
  } else {
329
415
  matchInfo.matches.push(...prunedList);
330
416
  }
331
- matchInfo.offsets.push(...matches.map((m) => m.offset));
417
+ matchInfo.offsets.push(...prunedList.map((m) => m.offset));
332
418
  // if (prunedList[0].length) {
333
419
  // matchInfo.length = prunedList[0].length;
334
420
  // }
@@ -339,6 +425,360 @@ export class InterceptScanner {
339
425
  return ruleMatches;
340
426
  }
341
427
 
428
+ /**
429
+ * Reject filter registry / gate helpers
430
+ */
431
+
432
+ validateFilterRegistry() {
433
+ const ruleNames = new Set(this.compiledRules.map((rule) => rule.name));
434
+ for (const filter of this.compiledFilterRules) {
435
+ if (ruleNames.has(filter.name)) {
436
+ throw new Error(`Filter rule "${filter.name}" collides with a rule of the same name`);
437
+ }
438
+ }
439
+
440
+ const filterNames = new Set(this.compiledFilterRules.map((filter) => filter.name));
441
+ for (const rule of this.compiledRules) {
442
+ for (const [varName, strDef] of Object.entries(rule.strings || {})) {
443
+ for (const filterName of [...(strDef.reject ?? []), ...(strDef.rejectCapture ?? [])]) {
444
+ if (!filterNames.has(filterName)) {
445
+ this.filterDiagnostics.push({
446
+ code: "unknown-filter-rule",
447
+ severity: "warning",
448
+ message: `String ${varName} in rule "${rule.name}" references unknown filter rule "${filterName}"`,
449
+ rule: rule.name,
450
+ string: varName,
451
+ filter: filterName,
452
+ });
453
+ }
454
+ }
455
+ }
456
+ }
457
+ }
458
+
459
+ rebuildFilterIndex() {
460
+ this.filterIndex = new Map(this.compiledFilterRules.map((rule) => [rule.name, rule]));
461
+ }
462
+
463
+ /**
464
+ * Module keywords available to filter conditions. Custom modules are addressed by the keyword
465
+ * their `getName()` returns, which need not match the key they were registered under.
466
+ */
467
+ getAvailableModuleNames() {
468
+ const names = new Set(Object.keys(this.modules || {}));
469
+ for (const moduleValue of Object.values(this.modules || {})) {
470
+ if (typeof moduleValue?.getName === "function") {
471
+ names.add(moduleValue.getName());
472
+ }
473
+ }
474
+ return [...names];
475
+ }
476
+
477
+ ensureFilterScanDiagnostics() {
478
+ if (!this.filterScanDiagnostics) {
479
+ this.filterScanDiagnostics = { oversized: new Map(), errors: new Map(), rejections: new Map() };
480
+ }
481
+ return this.filterScanDiagnostics;
482
+ }
483
+
484
+ resetFilterScanState() {
485
+ this.filterScanDiagnostics = { oversized: new Map(), errors: new Map(), rejections: new Map() };
486
+ this.filterDecisionCache = new Map();
487
+ this.filterModuleCache = new Map();
488
+ }
489
+
490
+ async filterMatches(strDef, matches, data, metadata, context = {}) {
491
+ if (!hasRejectFilters(strDef)) return matches;
492
+
493
+ const kept = [];
494
+ for (const match of matches) {
495
+ if (await this.isRejectedMatch(strDef, match, data, metadata, context)) continue;
496
+ kept.push(match);
497
+ }
498
+ return kept;
499
+ }
500
+
501
+ async isRejectedMatch(strDef, match, data, metadata, { ruleName, varName } = {}) {
502
+ const entries = [
503
+ ...(strDef?.reject ?? []).map((name) => ({ name, capture: false })),
504
+ ...(strDef?.rejectCapture ?? []).map((name) => ({ name, capture: true })),
505
+ ];
506
+ if (entries.length === 0) return false;
507
+
508
+ const length = match?.length ?? 0;
509
+ if (length <= 0) return false;
510
+
511
+ const diagnostics = this.ensureFilterScanDiagnostics();
512
+
513
+ if (length > MAX_FILTER_RULE_BUFFER_SIZE) {
514
+ const key = `${ruleName}:${varName}:${match.offset}:${length}`;
515
+ if (!diagnostics.oversized.has(key)) {
516
+ diagnostics.oversized.set(key, {
517
+ code: "filter-buffer-too-large",
518
+ severity: "warning",
519
+ message: `Candidate for ${varName} in rule "${ruleName}" is ${length} bytes, exceeding MAX_FILTER_RULE_BUFFER_SIZE (${MAX_FILTER_RULE_BUFFER_SIZE}); filters were skipped`,
520
+ rule: ruleName,
521
+ string: varName,
522
+ });
523
+ }
524
+ return false;
525
+ }
526
+
527
+ const fullBuffer = data.subarray(match.offset, match.offset + length);
528
+
529
+ for (const { name: filterName, capture } of entries) {
530
+ const filter = this.filterIndex.get(filterName);
531
+ if (!filter) continue; // Unknown names are ignored (diagnosed at compile time)
532
+
533
+ // `rejectRECapture` passes capture group 1 when the pattern has a participating, non-empty
534
+ // group; every other case falls back to the full match.
535
+ const buffer = capture && typeof match.capture === "string"
536
+ ? new TextEncoder().encode(match.capture)
537
+ : fullBuffer;
538
+
539
+ if (await this.getFilterDecision(filter, buffer, metadata)) {
540
+ diagnostics.rejections.set(filterName, (diagnostics.rejections.get(filterName) ?? 0) + 1);
541
+ return true;
542
+ }
543
+ }
544
+
545
+ return false;
546
+ }
547
+
548
+ async getFilterDecision(filter, buffer, metadata) {
549
+ const cacheKey = `${filter.name}:${buffer.length}:${hashBytes(buffer)}`;
550
+ const cached = this.filterDecisionCache.get(cacheKey);
551
+ if (cached && cached.buffer.length === buffer.length && cached.buffer.every((byte, i) => byte === buffer[i])) {
552
+ return cached.rejected;
553
+ }
554
+
555
+ const rejected = await this.evaluateFilterRule(filter, buffer, metadata);
556
+ this.filterDecisionCache.set(cacheKey, { buffer, rejected });
557
+ return rejected;
558
+ }
559
+
560
+ async evaluateFilterRule(filter, buffer, metadata = {}) {
561
+ try {
562
+ const stringMatches = this.matchFilterStrings(filter, buffer);
563
+ const modules = await this.createFilterModules(filter, buffer, metadata);
564
+ const scanFacts = createScanFacts(buffer, stringMatches, modules, {
565
+ entrypoint: 0,
566
+ filesize: buffer.length,
567
+ isFileSizeCapped: false,
568
+ maxFileSize: this.maxFileSize,
569
+ matchedRules: {},
570
+ metadata: { ruleName: filter.name },
571
+ });
572
+
573
+ let ast = filter.conditionAST;
574
+ if (!ast) {
575
+ try {
576
+ ast = this.parseSimpleCondition(filter.condition, scanFacts.strings);
577
+ } catch {
578
+ ast = { type: "boolean", value: false };
579
+ }
580
+ filter.conditionAST = ast;
581
+ }
582
+
583
+ return (await evaluateCondition(ast, scanFacts)) === true;
584
+ } catch (error) {
585
+ this.recordFilterError(filter.name, error);
586
+ return false;
587
+ }
588
+ }
589
+
590
+ matchFilterStrings(filter, buffer) {
591
+ const stringMatches = {};
592
+
593
+ for (const [varName, strDef] of Object.entries(filter.strings || {})) {
594
+ if (typeof strDef.matcher !== "function") {
595
+ stringMatches[varName] = [];
596
+ continue;
597
+ }
598
+
599
+ try {
600
+ const matches = strDef.matcher(buffer, -1);
601
+ stringMatches[varName] = Array.isArray(matches) ? matches : [];
602
+ } catch (error) {
603
+ this.recordFilterError(filter.name, error);
604
+ stringMatches[varName] = [];
605
+ }
606
+ }
607
+
608
+ return stringMatches;
609
+ }
610
+
611
+ async createFilterModules(filter, buffer, metadata = {}) {
612
+ const modules = {
613
+ string: this.modules.string,
614
+ time: this.modules.time,
615
+ math: createMathModule(buffer),
616
+ hash: createHashModule(buffer),
617
+ };
618
+
619
+ const usedModules = filter.usedModules ?? [];
620
+ if (usedModules.length === 0) return modules;
621
+
622
+ // Custom modules are resolved by their `getName()` keyword, not their registration key.
623
+ const customModules = new Map();
624
+ for (const moduleValue of Object.values(this.modules || {})) {
625
+ if (typeof moduleValue?.getName === "function") {
626
+ customModules.set(moduleValue.getName(), moduleValue);
627
+ }
628
+ }
629
+
630
+ for (const moduleName of usedModules) {
631
+ if (FILTER_MODULE_BUILTINS.has(moduleName)) continue;
632
+
633
+ const moduleValue = customModules.get(moduleName);
634
+ if (!moduleValue) continue;
635
+
636
+ const cacheKey = `${moduleName}:${buffer.length}:${hashBytes(buffer)}`;
637
+ if (this.filterModuleCache.has(cacheKey)) {
638
+ modules[moduleName] = this.filterModuleCache.get(cacheKey);
639
+ continue;
640
+ }
641
+
642
+ if (typeof moduleValue.isLoaded === "function" && !moduleValue.isLoaded() && typeof moduleValue.load === "function") {
643
+ await moduleValue.load();
644
+ }
645
+
646
+ let moduleObject = moduleValue;
647
+ if (typeof moduleValue.initialize === "function" && typeof moduleValue.createModule === "function") {
648
+ const interimResults = await moduleValue.initialize(buffer, {
649
+ ...(metadata || {}),
650
+ filesize: buffer.length,
651
+ hasPE: false,
652
+ hasELF: false,
653
+ timestamp: Date.now(),
654
+ });
655
+ moduleObject = moduleValue.createModule(interimResults);
656
+ }
657
+
658
+ this.filterModuleCache.set(cacheKey, moduleObject);
659
+ modules[moduleName] = moduleObject;
660
+ }
661
+
662
+ return modules;
663
+ }
664
+
665
+ recordFilterError(filterName, error) {
666
+ const diagnostics = this.ensureFilterScanDiagnostics();
667
+ const message = error?.message ?? String(error);
668
+ const key = `${filterName}:${message}`;
669
+ if (diagnostics.errors.has(key)) return;
670
+
671
+ diagnostics.errors.set(key, {
672
+ code: "filter-error",
673
+ severity: "warning",
674
+ message: `Filter rule "${filterName}" failed and was treated as not rejecting: ${message}`,
675
+ filter: filterName,
676
+ });
677
+ }
678
+
679
+ attachResultDiagnostics(results) {
680
+ const diagnostics = [...this.filterDiagnostics];
681
+
682
+ if (this.filterScanDiagnostics) {
683
+ diagnostics.push(...this.filterScanDiagnostics.errors.values());
684
+ diagnostics.push(...this.filterScanDiagnostics.oversized.values());
685
+ for (const [filterName, count] of this.filterScanDiagnostics.rejections) {
686
+ diagnostics.push({
687
+ code: "filter-rejection-count",
688
+ severity: "info",
689
+ message: `Filter rule "${filterName}" rejected ${count} candidate(s)`,
690
+ filter: filterName,
691
+ });
692
+ }
693
+ }
694
+
695
+ Object.defineProperty(results, "diagnostics", {
696
+ value: diagnostics,
697
+ enumerable: false,
698
+ configurable: true,
699
+ });
700
+
701
+ return results;
702
+ }
703
+
704
+ /**
705
+ * Evaluate named filter rules against a buffer directly.
706
+ *
707
+ * Result shape matches `scan()` (matched rules only). Unknown names are skipped silently.
708
+ * Custom modules are initialized from the supplied metadata, exactly as `scan()` does.
709
+ *
710
+ * @param {Uint8Array|string} data - Buffer to evaluate
711
+ * @param {Object} metadata - Scan metadata for custom modules
712
+ * @param {string[]} ruleNames - Filter rule names to evaluate
713
+ * @returns {Promise<Array>} Matched filter rules
714
+ */
715
+ async scanFilterRules(data, metadata = {}, ruleNames = []) {
716
+ if (typeof data === "string") {
717
+ data = new TextEncoder().encode(data);
718
+ }
719
+
720
+ this.resetFilterScanState();
721
+
722
+ const matchedRules = [];
723
+
724
+ for (const filterName of Array.isArray(ruleNames) ? ruleNames : []) {
725
+ const filter = this.filterIndex.get(filterName);
726
+ if (!filter) continue;
727
+
728
+ let scanFacts = null;
729
+ let matched = false;
730
+
731
+ try {
732
+ const stringMatches = this.matchFilterStrings(filter, data);
733
+ const modules = await this.createFilterModules(filter, data, metadata);
734
+ scanFacts = createScanFacts(data, stringMatches, modules, {
735
+ entrypoint: 0,
736
+ filesize: data.length,
737
+ isFileSizeCapped: data.length >= this.maxFileSize,
738
+ maxFileSize: this.maxFileSize,
739
+ matchedRules: {},
740
+ metadata: { ruleName: filter.name },
741
+ });
742
+
743
+ let ast = filter.conditionAST;
744
+ if (!ast) {
745
+ try {
746
+ ast = this.parseSimpleCondition(filter.condition, scanFacts.strings);
747
+ } catch {
748
+ ast = { type: "boolean", value: false };
749
+ }
750
+ filter.conditionAST = ast;
751
+ }
752
+
753
+ matched = (await evaluateCondition(ast, scanFacts)) === true;
754
+ } catch (error) {
755
+ this.recordFilterError(filter.name, error);
756
+ matched = false;
757
+ }
758
+
759
+ if (matched && scanFacts) {
760
+ const filteredStrings = {};
761
+ for (const [key, value] of Object.entries(scanFacts.strings)) {
762
+ // Anonymous strings surface as `.anon_N` in raw facts; drop them and private strings,
763
+ // matching the normal rule output shape.
764
+ if (key.startsWith(".") || key.startsWith("$.")) continue;
765
+ if (value.private || filter.strings[key]?.private) continue;
766
+ filteredStrings[key] = value;
767
+ }
768
+
769
+ matchedRules.push({
770
+ rule: filter.name,
771
+ namespace: "default",
772
+ tags: filter.tags || [],
773
+ metadata: filter.metadata || {},
774
+ strings: filteredStrings,
775
+ });
776
+ }
777
+ }
778
+
779
+ return this.attachResultDiagnostics(matchedRules);
780
+ }
781
+
342
782
  /**
343
783
  * Evaluate rule conditions
344
784
  * @param {Object} ruleMatches - String matches per rule
@@ -716,6 +1156,8 @@ export class InterceptScanner {
716
1156
  data = encoder.encode(data);
717
1157
  }
718
1158
 
1159
+ this.resetFilterScanState();
1160
+
719
1161
  if (!this.compiledRules || this.compiledRules.length === 0) {
720
1162
  if (timingEnabled && scanTiming) {
721
1163
  scanTiming.total = tracker.now() - totalStart;
@@ -724,7 +1166,7 @@ export class InterceptScanner {
724
1166
  } else if (tracker) {
725
1167
  tracker.clearScan();
726
1168
  }
727
- return [];
1169
+ return this.attachResultDiagnostics([]);
728
1170
  }
729
1171
 
730
1172
  // Phase 1: Fast candidate detection with Aho-Corasick
@@ -745,7 +1187,9 @@ export class InterceptScanner {
745
1187
  }
746
1188
 
747
1189
  const dedupeStart = timingEnabled ? tracker.now() : 0;
748
- const unique = this.deduplicateCandidates(candidates);
1190
+ const unique = this.needsCandidateDedupe
1191
+ ? this.deduplicateCandidates(candidates)
1192
+ : candidates;
749
1193
  if (timingEnabled && scanTiming) {
750
1194
  tracker.accumulateStep(scanTiming.steps, "deduplicate", tracker.now() - dedupeStart);
751
1195
  }
@@ -757,7 +1201,7 @@ export class InterceptScanner {
757
1201
  }
758
1202
 
759
1203
  const buildStart = timingEnabled ? tracker.now() : 0;
760
- const ruleMatches = this.buildStringMatches(verified, this.compiledRules, data);
1204
+ const ruleMatches = await this.buildStringMatches(verified, this.compiledRules, data, metadata);
761
1205
  if (timingEnabled && scanTiming) {
762
1206
  tracker.accumulateStep(scanTiming.steps, "buildMatches", tracker.now() - buildStart);
763
1207
  }
@@ -790,7 +1234,7 @@ export class InterceptScanner {
790
1234
  tracker.clearScan();
791
1235
  }
792
1236
 
793
- return results;
1237
+ return this.attachResultDiagnostics(results);
794
1238
  }
795
1239
 
796
1240
  /**
@@ -801,6 +1245,16 @@ export class InterceptScanner {
801
1245
  this.maxFileSize = size;
802
1246
  }
803
1247
 
1248
+ // Backed by `matchLimits`, the object shared with compiled string matchers, so changing the
1249
+ // cap takes effect for rules that were already compiled.
1250
+ get maxMatches() {
1251
+ return this.matchLimits.maxMatches;
1252
+ }
1253
+
1254
+ set maxMatches(value) {
1255
+ this.matchLimits.maxMatches = value;
1256
+ }
1257
+
804
1258
  /**
805
1259
  * Get statistics about loaded rules
806
1260
  * @returns {Object} Rule statistics
@@ -808,6 +1262,7 @@ export class InterceptScanner {
808
1262
  getStats() {
809
1263
  return {
810
1264
  totalRules: this.compiledRules.length,
1265
+ totalFilterRules: this.compiledFilterRules.length,
811
1266
  ruleNames: this.compiledRules.map((r) => r.name),
812
1267
  rulesWithStrings: this.compiledRules.filter((r) => Object.keys(r.strings).length > 0).length,
813
1268
  totalStrings: this.compiledRules.reduce((sum, r) => sum + Object.keys(r.strings).length, 0),
@@ -828,8 +1283,7 @@ export class InterceptScanner {
828
1283
  * Clear all loaded rules
829
1284
  */
830
1285
  clear() {
831
- this.compiledRules = [];
832
- this.ac = null;
1286
+ this.clearRules();
833
1287
  // Reset existing modules
834
1288
  this.setModules(this.customModules);
835
1289
  }