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.
@@ -14,14 +14,125 @@
14
14
  * limitations under the License.
15
15
  */
16
16
 
17
- const MAX_STRING_MATCH_LENGTH = 2048;
17
+
18
+ // Search window for a single-run matcher call (literal-prefixed regexes), mirroring libyara's
19
+ // YR_RE_SCAN_LIMIT (4096). Full-buffer scans are unbounded, and text verification compares bytes
20
+ // at the candidate offset directly, so it needs no window.
21
+ const MAX_RE_SCAN_LIMIT = 4096;
18
22
  export const MAX_MATCHES = 100;
23
+ const DEFAULT_MATCH_LIMITS = { maxMatches: MAX_MATCHES };
24
+
25
+ /**
26
+ * Extract Intercept-only `reject(name, ...)` and `rejectRECapture(name, ...)` modifiers from a
27
+ * definition's modifier text.
28
+ *
29
+ * Both forms are matched in one pass so each name stays bound to the buffer its modifier selects:
30
+ * `reject` passes the full match, `rejectRECapture` passes capture group 1 (falling back to the
31
+ * full match when the pattern has no participating group). The optional group is required rather
32
+ * than a `reject|rejectRECapture` alternation, which would match `reject` first and then fail to
33
+ * match the `(`.
34
+ *
35
+ * Names are captured verbatim: YARA identifiers are case-sensitive, so lowercasing the modifier
36
+ * text before extraction would break `reject(MyFilter)`.
37
+ */
38
+ function extractRejectRules(modifiers) {
39
+ const reject = [];
40
+ const rejectCapture = [];
41
+
42
+ if (!modifiers) return { reject, rejectCapture, modifiers: modifiers ?? "" };
43
+
44
+ const pattern = /\breject(RECapture)?\s*\(([^)]*)\)/gi;
45
+ let match;
46
+ while ((match = pattern.exec(modifiers)) !== null) {
47
+ const target = match[1] ? rejectCapture : reject;
48
+ for (const candidate of match[2].split(",")) {
49
+ const name = candidate.trim();
50
+ if (name && !target.includes(name)) target.push(name);
51
+ }
52
+ }
53
+
54
+ return {
55
+ reject,
56
+ rejectCapture,
57
+ modifiers: modifiers.replace(/\breject(RECapture)?\s*\([^)]*\)/gi, " "),
58
+ };
59
+ }
60
+
61
+ // `d` (hasIndices) supplies capture positions. It is never user-controlled: rule flags are
62
+ // filtered down to `s`/`i`, and this flag is added only when capture output is requested. If an
63
+ // engine lacks it, values are still reported and positions fall back to null.
64
+ const SUPPORTS_INDICES = (() => {
65
+ try {
66
+ new RegExp("", "d");
67
+ return true;
68
+ } catch {
69
+ return false;
70
+ }
71
+ })();
72
+
73
+ /** Byte offset of every UTF-16 index in `text`; lets positions stay O(1) once built. */
74
+ function buildByteOffsets(text) {
75
+ const byteOf = new Uint32Array(text.length + 1);
76
+ let bytes = 0;
77
+
78
+ for (let i = 0; i < text.length; i++) {
79
+ byteOf[i] = bytes;
80
+ const codePoint = text.codePointAt(i);
81
+ bytes += codePoint < 0x80 ? 1 : codePoint < 0x800 ? 2 : codePoint < 0x10000 ? 3 : 4;
82
+ if (codePoint > 0xffff) {
83
+ byteOf[i + 1] = bytes;
84
+ i += 1;
85
+ }
86
+ }
87
+
88
+ byteOf[text.length] = bytes;
89
+ return byteOf;
90
+ }
91
+
92
+ /**
93
+ * Name of the first capture group, so the numbered entry can carry the name JS exposes only through
94
+ * `match.groups`. Scans the pattern once, skipping escapes, character classes, and non-capturing
95
+ * groups (`(?:`, lookarounds).
96
+ */
97
+ function firstCaptureGroupName(pattern) {
98
+ let inClass = false;
99
+
100
+ for (let i = 0; i < pattern.length; i++) {
101
+ const char = pattern[i];
102
+
103
+ if (char === "\\") {
104
+ i += 1;
105
+ continue;
106
+ }
107
+ if (inClass) {
108
+ if (char === "]") inClass = false;
109
+ continue;
110
+ }
111
+ if (char === "[") {
112
+ inClass = true;
113
+ continue;
114
+ }
115
+ if (char !== "(") continue;
116
+
117
+ if (pattern[i + 1] !== "?") return undefined;
118
+
119
+ const isNamed = pattern[i + 2] === "<" && pattern[i + 3] !== "=" && pattern[i + 3] !== "!";
120
+ if (!isNamed) continue; // (?:, (?=, (?!, (?<=, (?<!
121
+
122
+ const end = pattern.indexOf(">", i + 3);
123
+ return end === -1 ? undefined : pattern.slice(i + 3, end);
124
+ }
125
+
126
+ return undefined;
127
+ }
19
128
 
20
129
  /**
21
130
  * Compile a YARA-like string definition into a matcher function.
22
131
  * Supports: text, wide, ascii, xor, base64/base64wide, regex, hex, fullword, nocase
132
+ * @param {Object} [limits] - Shared `{ maxMatches }` object; read live on every match run
133
+ * @param {Object} [options] - `{ includeCaptures }`; capture offsets are regex-only
23
134
  */
24
- export function compileYaraLike(definition) {
135
+ export function compileYaraLike(definition, limits = DEFAULT_MATCH_LIMITS, options = {}) {
25
136
  definition = definition.trim();
26
137
 
27
138
  const isRegex = definition.startsWith("/");
@@ -29,13 +140,14 @@ export function compileYaraLike(definition) {
29
140
  const quoteMatch = definition.match(/^"(.*)"(.*)$/);
30
141
 
31
142
  if (isRegex) {
32
- return makeRegexMatcher(definition);
143
+ return makeRegexMatcher(definition, limits, options);
33
144
  } else if (isHex) {
34
145
  const mods = definition.slice(definition.lastIndexOf("}") + 1);
35
- return makeHexMatcher(definition.slice(1, definition.lastIndexOf("}")).trim(), mods);
146
+ return makeHexMatcher(definition.slice(1, definition.lastIndexOf("}")).trim(), mods, limits);
36
147
  } else if (quoteMatch) {
37
148
  const [, text, modsRaw] = quoteMatch;
38
- const mods = modsRaw.toLowerCase();
149
+ const { reject, rejectCapture, modifiers: modsWithoutReject } = extractRejectRules(modsRaw);
150
+ const mods = modsWithoutReject.toLowerCase();
39
151
 
40
152
  const opts = {
41
153
  wide: /\bwide\b/.test(mods),
@@ -48,6 +160,8 @@ export function compileYaraLike(definition) {
48
160
  fullword: /\bfullword\b/.test(mods),
49
161
  nocase: /\bnocase\b/.test(mods),
50
162
  private: /\bprivate\b/.test(mods),
163
+ reject,
164
+ rejectCapture,
51
165
  };
52
166
 
53
167
  return makeTextMatcher(text, opts);
@@ -56,73 +170,237 @@ export function compileYaraLike(definition) {
56
170
  throw new Error("Unsupported definition: " + definition);
57
171
  }
58
172
 
59
- function addOptionsToMatcher(matcher) {
60
- // Public contract: `offset < 0` scans the whole buffer, otherwise the search window starts at
61
- // `offset` (one byte earlier, so fullword checks at the window start can see the preceding byte).
62
- const scan = (data, offset = -1, maxLength = MAX_STRING_MATCH_LENGTH, exactIndex = -1) => {
63
- if (offset < 0) return matcher(data, -1);
64
- const start = Math.max(0, offset - 1);
65
- return matcher(data.slice(start, start + maxLength), start, exactIndex < 0 ? -1 : exactIndex - start);
66
- };
173
+ function addOptionsToMatcher(matcher, verifyAt) {
174
+ // Public contract: `offset < 0` scans the whole buffer, otherwise the search starts at `offset`
175
+ // and a single run returns at most one match per pattern.
176
+ const scan = (data, offset = -1) => matcher(data, offset, -1);
67
177
 
68
- // Aho-Corasick candidates ask "is there a match starting exactly here?", which a window scan
69
- // cannot answer — its first match may be a neighbouring occurrence.
70
- scan.verifyAt = (data, offset) => scan(data, offset, MAX_STRING_MATCH_LENGTH, offset);
178
+ // Aho-Corasick candidates ask "is there a match starting exactly here?", which a forward scan
179
+ // cannot answer without also returning a neighbouring occurrence. Types with a direct
180
+ // implementation pass `verifyAt`; `hint` carries the candidate's XOR key so no key search is
181
+ // needed.
182
+ scan.verifyAt = verifyAt ?? ((data, offset) => matcher(data, offset, offset));
71
183
  return scan;
72
184
  }
73
185
 
74
186
  // ╭─────────────────────────────╮
75
187
  // │ REGEX MATCHER │
76
188
  // ╰─────────────────────────────╯
77
- function makeRegexMatcher(definition) {
78
- const mods = definition.split("/").pop().toLowerCase() ?? "";
79
- const regexFlags = mods.split(" ")[0];
189
+ const textDecoder = new TextDecoder();
190
+
191
+ // Decoded views of scanned buffers, so a scan with many Aho-Corasick candidates decodes the
192
+ // buffer once instead of once per candidate.
193
+ const decodedBuffers = new WeakMap();
194
+ const asciiBuffers = new WeakMap();
195
+
196
+ /**
197
+ * True when every byte is ASCII, which guarantees that byte offsets and decoded character indices
198
+ * coincide. Purely binary buffers fail this on the first high byte, so they never pay for a
199
+ * whole-buffer decode they cannot use.
200
+ */
201
+ function isAsciiBuffer(data) {
202
+ let ascii = asciiBuffers.get(data);
203
+ if (ascii === undefined) {
204
+ ascii = true;
205
+ for (let i = 0; i < data.length; i++) {
206
+ if (data[i] >= 0x80) {
207
+ ascii = false;
208
+ break;
209
+ }
210
+ }
211
+ asciiBuffers.set(data, ascii);
212
+ }
213
+ return ascii;
214
+ }
215
+
216
+ function makeDecoded(text, byteLength) {
217
+ return {
218
+ text,
219
+ // One code unit per byte means byte offsets and character indices are interchangeable.
220
+ identity: text.length === byteLength,
221
+ byteOf: null,
222
+ };
223
+ }
224
+
225
+ function getDecodedBuffer(data) {
226
+ let decoded = decodedBuffers.get(data);
227
+ if (decoded === undefined) {
228
+ decoded = makeDecoded(textDecoder.decode(data), data.length);
229
+ decodedBuffers.set(data, decoded);
230
+ }
231
+ return decoded;
232
+ }
233
+
234
+ /**
235
+ * Decodes the bytes from `offset` onward. Candidates are byte offsets, so verifying inside a
236
+ * window that starts at the candidate keeps the match anchored to those bytes even when the
237
+ * buffer is not valid UTF-8 (where a decoded offset would not line up with a byte offset).
238
+ */
239
+ function decodeWindow(data, offset) {
240
+ const end = Math.min(data.length, offset + MAX_RE_SCAN_LIMIT);
241
+ return makeDecoded(textDecoder.decode(data.subarray(offset, end)), end - offset);
242
+ }
243
+
244
+ /** Lazily builds the char-index -> byte-offset table for buffers that are not one-to-one. */
245
+ function byteOffsetsOf(decoded) {
246
+ if (!decoded.identity && decoded.byteOf === null) {
247
+ decoded.byteOf = buildByteOffsets(decoded.text);
248
+ }
249
+ return decoded;
250
+ }
251
+
252
+ function byteAt(decoded, charIndex) {
253
+ return decoded.identity ? charIndex : byteOffsetsOf(decoded).byteOf[charIndex];
254
+ }
255
+
256
+ function makeRegexMatcher(definition, limits, options = {}) {
257
+ const lastSlash = definition.lastIndexOf("/");
258
+ const suffix = definition.slice(lastSlash + 1);
259
+ const { reject, rejectCapture, modifiers } = extractRejectRules(suffix);
260
+ const wantsCapture = rejectCapture.length > 0;
261
+ // `includeCaptures` is the only switch for capture output. It needs no regex flag: `exec` already
262
+ // materializes every group, so reading group 1 back is free.
263
+ const wantsCaptureOutput = options.includeCaptures === true;
264
+ const wantsIndices = wantsCaptureOutput && SUPPORTS_INDICES;
265
+ const mods = modifiers.toLowerCase();
266
+ // Flags are only valid immediately after the closing slash; space-separated words after that are
267
+ // modifiers. YARA treats `/foo/i` and `/foo/ nocase` as equivalent.
268
+ const regexFlags = mods.match(/^([a-z]*)/)?.[1] ?? "";
80
269
  const isPrivate = /\bprivate\b/.test(mods);
81
- const pattern = definition.slice(1, definition.lastIndexOf("/"));
82
- const nocase = regexFlags.includes("i");
83
- const flags = "g" + (regexFlags.includes("s") ? "s" : "") + (nocase ? "i" : "");
270
+ const pattern = definition.slice(1, lastSlash);
271
+ const nocase = regexFlags.includes("i") || /\bnocase\b/.test(mods);
272
+ const commonFlags =
273
+ (regexFlags.includes("s") ? "s" : "") + (nocase ? "i" : "") + (wantsIndices ? "d" : "");
84
274
  const literalPrefix = getRegexPrefix(pattern, nocase);
85
- const re = new RegExp(pattern, flags);
275
+ const firstGroupName = wantsCaptureOutput ? firstCaptureGroupName(pattern) : undefined;
276
+ const re = new RegExp(pattern, "g" + commonFlags);
277
+ // Sticky twin answers "does a match start exactly at this character?".
278
+ const reAt = new RegExp(pattern, "y" + commonFlags);
279
+
280
+ /** Builds a match record; `base` is the byte offset the decoded text starts at. */
281
+ const buildEntry = (m, decoded, base = 0) => {
282
+ const startByte = base + byteAt(decoded, m.index);
283
+ const entry = {
284
+ offset: startByte,
285
+ length: base + byteAt(decoded, m.index + m[0].length) - startByte,
286
+ };
287
+ // The reject gate needs only the capture *value*, so no indices flag is involved. Absent,
288
+ // non-participating, and empty groups all fall back to the full match.
289
+ if (wantsCapture && typeof m[1] === "string" && m[1] !== "") {
290
+ Object.defineProperty(entry, "capture", { value: m[1], enumerable: false });
291
+ }
292
+ // Capture output carries only group 1 — the group rejectRECapture uses — so the other
293
+ // groups' substrings become collectable as soon as the iteration ends.
294
+ if (wantsCaptureOutput) {
295
+ if (m.length > 1) {
296
+ const capture =
297
+ firstGroupName === undefined
298
+ ? { index: 1, value: typeof m[1] === "string" ? m[1] : null }
299
+ : { index: 1, name: firstGroupName, value: typeof m[1] === "string" ? m[1] : null };
300
+
301
+ const span = wantsIndices ? m.indices?.[1] : null;
302
+ if (span) {
303
+ const startByte = base + byteAt(decoded, span[0]);
304
+ capture.offset = startByte;
305
+ capture.length = base + byteAt(decoded, span[1]) - startByte;
306
+ } else {
307
+ capture.offset = null;
308
+ capture.length = null;
309
+ }
86
310
 
87
- const matcher = (data, offset = -1, exactIndex = -1) => {
88
- const encoder = new TextEncoder();
89
- const text = new TextDecoder().decode(data);
311
+ entry.captures = [capture];
312
+ } else {
313
+ entry.captures = [];
314
+ }
315
+ }
316
+ return entry;
317
+ };
318
+
319
+ // `re`/`reAt` outlive a call: they run once per Aho-Corasick candidate plus once per full scan,
320
+ // and an early `break` (or the MAX_MATCHES cap) leaves `lastIndex` mid-text. Position them
321
+ // explicitly on entry instead of inheriting the previous run's position.
322
+
323
+ /** Candidates ask "is there a match starting exactly at this byte offset?". */
324
+ const verifyAt = (data, offset) => {
325
+ if (isAsciiBuffer(data)) {
326
+ const decoded = getDecodedBuffer(data);
327
+ reAt.lastIndex = offset;
328
+ const m = reAt.exec(decoded.text);
329
+ return m === null ? [] : [buildEntry(m, decoded)];
330
+ }
331
+
332
+ // Non-ASCII: a decoded index is not the candidate's byte offset, so verify inside the
333
+ // candidate's own bytes.
334
+ const window = decodeWindow(data, offset);
335
+ reAt.lastIndex = 0;
336
+ const m = reAt.exec(window.text);
337
+ return m === null ? [] : [buildEntry(m, window, offset)];
338
+ };
339
+
340
+ /** Single run from `offset`: at most one match, bounded by the verification window. */
341
+ const firstMatchFrom = (data, offset) => {
342
+ if (isAsciiBuffer(data)) {
343
+ const decoded = getDecodedBuffer(data);
344
+ const limit = offset + MAX_RE_SCAN_LIMIT;
345
+ re.lastIndex = offset;
346
+ const m = re.exec(decoded.text);
347
+ return m === null || m.index > limit ? [] : [buildEntry(m, decoded)];
348
+ }
349
+
350
+ const window = decodeWindow(data, offset);
351
+ re.lastIndex = 0;
352
+ const m = re.exec(window.text);
353
+ return m === null ? [] : [buildEntry(m, window, offset)];
354
+ };
355
+
356
+ /** Full-buffer scan: overlapping matches, capped by the shared match limit. */
357
+ const scanAll = (data) => {
358
+ const decoded = getDecodedBuffer(data);
90
359
  const results = [];
91
- const singleRun = offset >= 0;
92
- const exact = exactIndex >= 0;
93
- // `re` outlives a call: the matcher runs once per Aho-Corasick candidate plus once per full
94
- // scan, and an early `break` (or the MAX_MATCHES cap) leaves `lastIndex` mid-text. Position it
95
- // explicitly on entry instead of inheriting the previous run's position.
96
- const runIndex = exact ? exactIndex : 0;
97
- offset = offset < 0 ? 0 : offset;
98
- re.lastIndex = runIndex;
360
+ re.lastIndex = 0;
99
361
  let m;
100
- while ((m = re.exec(text)) !== null && results.length < MAX_MATCHES) {
101
- if (exact && m.index !== runIndex) break; // prefix hit the regex rejects
102
- const byteIndex = encoder.encode(text.slice(0, m.index)).length;
103
- results.push({ offset: byteIndex + offset, length: encoder.encode(m[0]).length });
362
+ while ((m = re.exec(decoded.text)) !== null && results.length < limits.maxMatches) {
363
+ results.push(buildEntry(m, decoded));
104
364
  re.lastIndex = m.index + 1; // Move forward to find overlapping matches
105
- if (singleRun) break;
106
365
  }
107
366
  return results;
108
367
  };
109
368
 
110
- return { matcher: addOptionsToMatcher(matcher), literalPrefix, type: "regex", nocase, private: isPrivate };
369
+ const matcher = (data, offset = -1, exactIndex = -1) => {
370
+ if (exactIndex >= 0) return verifyAt(data, exactIndex);
371
+ return offset < 0 ? scanAll(data) : firstMatchFrom(data, offset);
372
+ };
373
+
374
+ return { matcher: addOptionsToMatcher(matcher, verifyAt), literalPrefix, type: "regex", nocase, private: isPrivate, reject, rejectCapture };
111
375
  }
112
376
 
113
377
  function getRegexPrefix(pattern, nocase = false) {
114
- // Remove leading ^ if present
115
- pattern = pattern.replace(/^\^/, "");
116
- pattern = nocase ? pattern.toLowerCase() : pattern;
378
+ // `^`/`$` anchor to the buffer, so a buffer-wide scan is the only sound way to honour them.
379
+ if (pattern.startsWith("^")) return "";
380
+
381
+ const haystack = nocase ? pattern.toLowerCase() : pattern;
117
382
 
118
- // Match literal prefix before first meta pattern
119
- // const match = pattern.match(/^((?:\\.|[^\\[\]()|*+?{}.])+)/);
120
383
  // Match literal prefix: either escaped chars (\. \? etc) or non-special chars
121
- const match = pattern.match(/^((?:\\[^bBdDwWsSAZzGnrtfv0u]|[^\\[\]()|*+?{}.])+)/);
384
+ const match = haystack.match(/^((?:\\[^bBdDwWsSAZzGnrtfv0u]|[^\\[\]()|*+?{}.^$])+)/);
122
385
  if (!match || match.length < 2) return "";
123
386
 
387
+ let literal = match[1];
388
+ const following = haystack.slice(literal.length);
389
+
390
+ // An anchor right after the literal is buffer-relative, or unreachable mid-pattern.
391
+ if (following.startsWith("$") || following.startsWith("^")) return "";
392
+
393
+ // A trailing alternation means the literal is one branch among several: it is not a prefix of
394
+ // every match, so the whole buffer has to be scanned.
395
+ if (following.startsWith("|")) return "";
396
+
397
+ // `https?`, `abc*` and `abc{0,2}` make the last literal character optional.
398
+ if (/^[?*]/.test(following) || /^\{0[,}]/.test(following)) {
399
+ literal = literal.slice(0, -1);
400
+ }
401
+
124
402
  // Unescape hex sequences like \x41 → A
125
- let prefix = match[1].replace(/\\x([0-9A-Fa-f]{2})/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
403
+ let prefix = literal.replace(/\\x([0-9A-Fa-f]{2})/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
126
404
 
127
405
  // Unescape escaped characters like \. → .
128
406
  return prefix.replace(/\\(.)/g, "$1");
@@ -192,60 +470,74 @@ function makeTextMatcher(text, opts) {
192
470
  }
193
471
 
194
472
  const matcher = (data, offset = -1, exactIndex = -1) => {
195
- let matches = [];
196
473
  const singleRun = offset >= 0;
197
- // `exactIndex` (relative to the slice) restricts a single run to the candidate's own byte.
198
- const runIndex = exactIndex >= 0 ? exactIndex : -1;
199
- offset = offset < 0 ? 0 : offset;
474
+ const start = offset < 0 ? 0 : offset;
475
+ const end = offset < 0 ? data.length : Math.min(data.length, offset + MAX_RE_SCAN_LIMIT);
476
+ let matches = [];
200
477
 
201
478
  for (const { bytes, isWide } of patterns) {
202
- if (opts.xor) {
203
- const xorMatches = findXorMatches(data, bytes, opts.xor, opts.allowKey0, singleRun, runIndex);
204
- matches.push(...xorMatches.map((m) => ({ ...m, length: bytes.length, isWide })));
205
- } else {
206
- const plainMatches = findPlainMatches(data, bytes, opts.nocase, singleRun, runIndex);
207
- matches.push(...plainMatches.map((m) => ({ ...m, length: bytes.length, isWide })));
208
- }
479
+ const found = opts.xor
480
+ ? findXorMatches(data, bytes, opts.xor, opts.allowKey0, start, end, singleRun, exactIndex)
481
+ : findPlainMatches(data, bytes, opts.nocase, start, end, singleRun, exactIndex);
482
+ matches.push(...found.map((m) => ({ ...m, length: bytes.length, isWide })));
209
483
  }
210
484
 
211
485
  if (opts.fullword) {
212
486
  matches = matches.filter((m) => isFullWordMatch(data, m.offset, m.length));
213
487
  }
214
488
 
215
- // Adjust the offsets for the original data if offset was specified
216
- matches.forEach((m) => {
217
- m.offset += offset;
218
- });
219
-
220
489
  return matches;
221
490
  };
222
491
 
223
- return { matcher: addOptionsToMatcher(matcher), patterns, type: "text", xor: opts.xor, nocase: opts.nocase, private: opts.private };
492
+ /**
493
+ * Exact-position verification. Aho-Corasick already located the literal, so this only has to
494
+ * compare the pattern's bytes at that offset: no window slice and no forward rescan.
495
+ */
496
+ const verifyAt = (data, offset, hint) => {
497
+ const xorKey = hint === undefined ? undefined : hint.xorKey;
498
+ // An XOR candidate without its key needs the key search after all.
499
+ if (opts.xor && xorKey === undefined) return matcher(data, offset, offset);
500
+
501
+ const matches = [];
502
+ for (const { bytes, isWide } of patterns) {
503
+ if (bytes.length === 0 || offset + bytes.length > data.length) continue;
504
+ if (opts.xor) {
505
+ if (!matchXorAt(data, offset, bytes, xorKey)) continue;
506
+ matches.push({ offset, key: xorKey, length: bytes.length, isWide });
507
+ } else if (matchPlainAt(data, offset, bytes, opts.nocase)) {
508
+ matches.push({ offset, length: bytes.length, isWide });
509
+ }
510
+ }
511
+
512
+ return opts.fullword
513
+ ? matches.filter((m) => isFullWordMatch(data, m.offset, m.length))
514
+ : matches;
515
+ };
516
+
517
+ return { matcher: addOptionsToMatcher(matcher, verifyAt), patterns, type: "text", xor: opts.xor, nocase: opts.nocase, private: opts.private, reject: opts.reject ?? [], rejectCapture: opts.rejectCapture ?? [] };
224
518
  }
225
519
 
226
520
  // ╭─────────────────────────────╮
227
521
  // │ XOR-AWARE MATCHING │
228
522
  // ╰─────────────────────────────╯
229
- function findXorMatches(data, pattern, keyRange, allowKey0 = true, singleRun = false, exactIndex = -1) {
523
+ function findXorMatches(data, pattern, keyRange, allowKey0 = true, start = 0, end = data.length, singleRun = false, exactIndex = -1) {
230
524
  const [minKey, maxKey] = keyRange;
231
525
  const matches = [];
232
526
  const pLen = pattern.length;
233
- const dLen = data.length;
234
- const from = exactIndex >= 0 ? exactIndex : 0;
235
- if (pLen === 0 || pLen > dLen) return matches;
527
+ if (pLen === 0 || pLen > data.length) return matches;
528
+
529
+ // An exact run only accepts the requested offset, which is a single comparison per key.
530
+ if (exactIndex >= 0) {
531
+ for (let candidateKey = minKey; candidateKey <= maxKey; candidateKey++) {
532
+ if (matchXorAt(data, exactIndex, pattern, candidateKey)) matches.push({ offset: exactIndex, key: candidateKey });
533
+ }
534
+ return matches;
535
+ }
236
536
 
237
537
  for (let candidateKey = minKey; candidateKey <= maxKey; candidateKey++) {
238
- for (let i = from; i <= dLen - pLen; i++) {
239
- let ok = true;
240
- for (let j = 0; j < pLen; j++) {
241
- if ((data[i + j] ^ candidateKey) !== pattern[j]) {
242
- ok = false;
243
- break;
244
- }
245
- }
246
- if (ok) {
247
- // An exact run only accepts the requested offset; a later hit belongs to another candidate.
248
- if (exactIndex < 0 || i === exactIndex) matches.push({ offset: i, key: candidateKey });
538
+ for (let i = start; i + pLen <= end; i++) {
539
+ if (matchXorAt(data, i, pattern, candidateKey)) {
540
+ matches.push({ offset: i, key: candidateKey });
249
541
  if (singleRun) break;
250
542
  }
251
543
  }
@@ -256,22 +548,49 @@ function findXorMatches(data, pattern, keyRange, allowKey0 = true, singleRun = f
256
548
  // ╭─────────────────────────────╮
257
549
  // │ PLAIN MATCHING │
258
550
  // ╰─────────────────────────────╯
259
- function findPlainMatches(data, pattern, nocase = false, singleRun = false, exactIndex = -1) {
551
+ function findPlainMatches(data, pattern, nocase = false, start = 0, end = data.length, singleRun = false, exactIndex = -1) {
260
552
  const matches = [];
261
553
  const pLen = pattern.length;
262
- const dLen = data.length;
263
- const from = exactIndex >= 0 ? exactIndex : 0;
264
- outer: for (let i = from; i <= dLen - pLen; i++) {
265
- for (let j = 0; j < pLen; j++) {
266
- if ((nocase ? lowercaseByte(data[i + j]) : data[i + j]) !== pattern[j]) continue outer;
554
+ if (pLen > data.length) return matches;
555
+
556
+ // An exact run only accepts the requested offset, which is a single comparison.
557
+ if (exactIndex >= 0) {
558
+ if (matchPlainAt(data, exactIndex, pattern, nocase)) matches.push({ offset: exactIndex });
559
+ return matches;
560
+ }
561
+
562
+ for (let i = start; i + pLen <= end; i++) {
563
+ if (matchPlainAt(data, i, pattern, nocase)) {
564
+ matches.push({ offset: i });
565
+ if (singleRun) break;
267
566
  }
268
- // An exact run only accepts the requested offset; a later hit belongs to another candidate.
269
- if (exactIndex < 0 || i === exactIndex) matches.push({ offset: i });
270
- if (singleRun) break;
271
567
  }
272
568
  return matches;
273
569
  }
274
570
 
571
+ /** Compares a literal pattern against `data` starting exactly at `offset`. */
572
+ function matchPlainAt(data, offset, pattern, nocase) {
573
+ const pLen = pattern.length;
574
+ if (offset + pLen > data.length) return false;
575
+
576
+ for (let j = 0; j < pLen; j++) {
577
+ const byte = data[offset + j];
578
+ if ((nocase ? lowercaseByte(byte) : byte) !== pattern[j]) return false;
579
+ }
580
+ return true;
581
+ }
582
+
583
+ /** Compares a literal pattern against `data` after applying a single-byte XOR key. */
584
+ function matchXorAt(data, offset, pattern, key) {
585
+ const pLen = pattern.length;
586
+ if (offset + pLen > data.length) return false;
587
+
588
+ for (let j = 0; j < pLen; j++) {
589
+ if ((data[offset + j] ^ key) !== pattern[j]) return false;
590
+ }
591
+ return true;
592
+ }
593
+
275
594
  function lowercaseByte(b) {
276
595
  if (b >= 0x41 && b <= 0x5a) {
277
596
  return b + 0x20;
@@ -330,17 +649,18 @@ function parseXorRange(mods) {
330
649
  // Global constant for max jump range when not specified
331
650
  const MAX_HEX_JUMP = 10000;
332
651
 
333
- function makeHexMatcher(hexBody, mods) {
652
+ function makeHexMatcher(hexBody, mods, limits) {
334
653
  // Parse hex body into regex pattern
335
654
  let pattern = "";
336
655
  hexBody = hexBody?.toUpperCase().replace(/[^0-9A-F?~|()[\-\]]/g, "") || ""; // Trim invalid chars
337
656
  const parts = hexBody.match(/\[\d*(-\d*)?\]|\(.*\)|~?[0-9A-F?]{2}/g) || [];
338
- const isPrivate = /\bprivate\b/.test(mods);
657
+ const { reject, rejectCapture, modifiers } = extractRejectRules(mods);
658
+ const isPrivate = /\bprivate\b/.test(modifiers);
339
659
 
340
660
  if (parts.length === 0) {
341
661
  // Empty pattern matches nothing
342
662
  const matcher = (data) => [];
343
- return { matcher, type: "hex", private: isPrivate };
663
+ return { matcher, type: "hex", private: isPrivate, reject, rejectCapture };
344
664
  }
345
665
 
346
666
  for (const token of parts) {
@@ -384,7 +704,7 @@ function makeHexMatcher(hexBody, mods) {
384
704
  // Same shared-instance hazard as the regex matcher: `regex` lives as long as the matcher, so
385
705
  // reset before each run (the MAX_MATCHES cap can leave `lastIndex` mid-string).
386
706
  regex.lastIndex = 0;
387
- while ((m = regex.exec(hexString)) !== null && matches.length < MAX_MATCHES) {
707
+ while ((m = regex.exec(hexString)) !== null && matches.length < limits.maxMatches) {
388
708
  // Convert hex string offset to byte offset
389
709
  if (m.index % 2 !== 0) {
390
710
  // Skip to next aligned position to check
@@ -402,7 +722,7 @@ function makeHexMatcher(hexBody, mods) {
402
722
  return matches;
403
723
  };
404
724
 
405
- return { matcher, type: "hex", private: isPrivate };
725
+ return { matcher, type: "hex", private: isPrivate, reject, rejectCapture };
406
726
  }
407
727
 
408
728
  // function addAllOverlappingMatches(regex, text, textIndex = 0, matches = [], indexStep = 1) {