sekant-intercept-js 1.0.1 → 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,62 +170,237 @@ export function compileYaraLike(definition) {
56
170
  throw new Error("Unsupported definition: " + definition);
57
171
  }
58
172
 
59
- function addOptionsToMatcher(matcher) {
60
- return (data, offset = -1, maxLength = MAX_STRING_MATCH_LENGTH) => {
61
- // If offset is specified, slice the data accordingly and limit length for matching
62
- const singleRun = offset >= 0;
63
- // Start 1 byte before to do fullword checks if needed
64
- offset = Math.max(0, offset - 1);
65
- data = singleRun ? data.slice(offset, offset + maxLength) : data;
66
- return matcher(data, singleRun ? offset : -1);
67
- };
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);
177
+
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));
183
+ return scan;
68
184
  }
69
185
 
70
186
  // ╭─────────────────────────────╮
71
187
  // │ REGEX MATCHER │
72
188
  // ╰─────────────────────────────╯
73
- function makeRegexMatcher(definition) {
74
- const mods = definition.split("/").pop().toLowerCase() ?? "";
75
- 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] ?? "";
76
269
  const isPrivate = /\bprivate\b/.test(mods);
77
- const pattern = definition.slice(1, definition.lastIndexOf("/"));
78
- const nocase = regexFlags.includes("i");
79
- 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" : "");
80
274
  const literalPrefix = getRegexPrefix(pattern, nocase);
81
- 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
+ }
310
+
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
+ }
82
331
 
83
- const matcher = (data, offset = -1) => {
84
- const encoder = new TextEncoder();
85
- const text = new TextDecoder().decode(data);
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);
86
359
  const results = [];
87
- const singleRun = offset >= 0;
88
- offset = offset < 0 ? 0 : offset;
360
+ re.lastIndex = 0;
89
361
  let m;
90
- while ((m = re.exec(text)) !== null && results.length < MAX_MATCHES) {
91
- const byteIndex = encoder.encode(text.slice(0, m.index)).length;
92
- 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));
93
364
  re.lastIndex = m.index + 1; // Move forward to find overlapping matches
94
- if (singleRun) break;
95
365
  }
96
366
  return results;
97
367
  };
98
368
 
99
- 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 };
100
375
  }
101
376
 
102
377
  function getRegexPrefix(pattern, nocase = false) {
103
- // Remove leading ^ if present
104
- pattern = pattern.replace(/^\^/, "");
105
- 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;
106
382
 
107
- // Match literal prefix before first meta pattern
108
- // const match = pattern.match(/^((?:\\.|[^\\[\]()|*+?{}.])+)/);
109
383
  // Match literal prefix: either escaped chars (\. \? etc) or non-special chars
110
- const match = pattern.match(/^((?:\\[^bBdDwWsSAZzGnrtfv0u]|[^\\[\]()|*+?{}.])+)/);
384
+ const match = haystack.match(/^((?:\\[^bBdDwWsSAZzGnrtfv0u]|[^\\[\]()|*+?{}.^$])+)/);
111
385
  if (!match || match.length < 2) return "";
112
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
+
113
402
  // Unescape hex sequences like \x41 → A
114
- 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)));
115
404
 
116
405
  // Unescape escaped characters like \. → .
117
406
  return prefix.replace(/\\(.)/g, "$1");
@@ -180,56 +469,74 @@ function makeTextMatcher(text, opts) {
180
469
  }
181
470
  }
182
471
 
183
- const matcher = (data, offset = -1) => {
184
- let matches = [];
472
+ const matcher = (data, offset = -1, exactIndex = -1) => {
185
473
  const singleRun = offset >= 0;
186
- 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 = [];
187
477
 
188
478
  for (const { bytes, isWide } of patterns) {
189
- if (opts.xor) {
190
- const xorMatches = findXorMatches(data, bytes, opts.xor, opts.allowKey0, singleRun);
191
- matches.push(...xorMatches.map((m) => ({ ...m, length: bytes.length, isWide })));
192
- } else {
193
- const plainMatches = findPlainMatches(data, bytes, opts.nocase, singleRun);
194
- matches.push(...plainMatches.map((m) => ({ ...m, length: bytes.length, isWide })));
195
- }
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 })));
196
483
  }
197
484
 
198
485
  if (opts.fullword) {
199
486
  matches = matches.filter((m) => isFullWordMatch(data, m.offset, m.length));
200
487
  }
201
488
 
202
- // Adjust the offsets for the original data if offset was specified
203
- matches.forEach((m) => {
204
- m.offset += offset;
205
- });
206
-
207
489
  return matches;
208
490
  };
209
491
 
210
- 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 ?? [] };
211
518
  }
212
519
 
213
520
  // ╭─────────────────────────────╮
214
521
  // │ XOR-AWARE MATCHING │
215
522
  // ╰─────────────────────────────╯
216
- function findXorMatches(data, pattern, keyRange, allowKey0 = true, singleRun = false) {
523
+ function findXorMatches(data, pattern, keyRange, allowKey0 = true, start = 0, end = data.length, singleRun = false, exactIndex = -1) {
217
524
  const [minKey, maxKey] = keyRange;
218
525
  const matches = [];
219
526
  const pLen = pattern.length;
220
- const dLen = data.length;
221
- 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
+ }
222
536
 
223
537
  for (let candidateKey = minKey; candidateKey <= maxKey; candidateKey++) {
224
- for (let i = 0; i <= dLen - pLen; i++) {
225
- let ok = true;
226
- for (let j = 0; j < pLen; j++) {
227
- if ((data[i + j] ^ candidateKey) !== pattern[j]) {
228
- ok = false;
229
- break;
230
- }
231
- }
232
- if (ok) {
538
+ for (let i = start; i + pLen <= end; i++) {
539
+ if (matchXorAt(data, i, pattern, candidateKey)) {
233
540
  matches.push({ offset: i, key: candidateKey });
234
541
  if (singleRun) break;
235
542
  }
@@ -241,20 +548,49 @@ function findXorMatches(data, pattern, keyRange, allowKey0 = true, singleRun = f
241
548
  // ╭─────────────────────────────╮
242
549
  // │ PLAIN MATCHING │
243
550
  // ╰─────────────────────────────╯
244
- function findPlainMatches(data, pattern, nocase = false, singleRun = false) {
551
+ function findPlainMatches(data, pattern, nocase = false, start = 0, end = data.length, singleRun = false, exactIndex = -1) {
245
552
  const matches = [];
246
553
  const pLen = pattern.length;
247
- const dLen = data.length;
248
- outer: for (let i = 0; i <= dLen - pLen; i++) {
249
- for (let j = 0; j < pLen; j++) {
250
- 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;
251
566
  }
252
- matches.push({ offset: i });
253
- if (singleRun) break;
254
567
  }
255
568
  return matches;
256
569
  }
257
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
+
258
594
  function lowercaseByte(b) {
259
595
  if (b >= 0x41 && b <= 0x5a) {
260
596
  return b + 0x20;
@@ -313,17 +649,18 @@ function parseXorRange(mods) {
313
649
  // Global constant for max jump range when not specified
314
650
  const MAX_HEX_JUMP = 10000;
315
651
 
316
- function makeHexMatcher(hexBody, mods) {
652
+ function makeHexMatcher(hexBody, mods, limits) {
317
653
  // Parse hex body into regex pattern
318
654
  let pattern = "";
319
655
  hexBody = hexBody?.toUpperCase().replace(/[^0-9A-F?~|()[\-\]]/g, "") || ""; // Trim invalid chars
320
656
  const parts = hexBody.match(/\[\d*(-\d*)?\]|\(.*\)|~?[0-9A-F?]{2}/g) || [];
321
- const isPrivate = /\bprivate\b/.test(mods);
657
+ const { reject, rejectCapture, modifiers } = extractRejectRules(mods);
658
+ const isPrivate = /\bprivate\b/.test(modifiers);
322
659
 
323
660
  if (parts.length === 0) {
324
661
  // Empty pattern matches nothing
325
662
  const matcher = (data) => [];
326
- return { matcher, type: "hex", private: isPrivate };
663
+ return { matcher, type: "hex", private: isPrivate, reject, rejectCapture };
327
664
  }
328
665
 
329
666
  for (const token of parts) {
@@ -364,7 +701,10 @@ function makeHexMatcher(hexBody, mods) {
364
701
 
365
702
  const matches = [];
366
703
  let m;
367
- while ((m = regex.exec(hexString)) !== null && matches.length < MAX_MATCHES) {
704
+ // Same shared-instance hazard as the regex matcher: `regex` lives as long as the matcher, so
705
+ // reset before each run (the MAX_MATCHES cap can leave `lastIndex` mid-string).
706
+ regex.lastIndex = 0;
707
+ while ((m = regex.exec(hexString)) !== null && matches.length < limits.maxMatches) {
368
708
  // Convert hex string offset to byte offset
369
709
  if (m.index % 2 !== 0) {
370
710
  // Skip to next aligned position to check
@@ -376,13 +716,13 @@ function makeHexMatcher(hexBody, mods) {
376
716
  // // Skip non-aligned length matches
377
717
  // continue;
378
718
  // }
379
- matches.push({ offset: m.index / 2 });
719
+ matches.push({ offset: m.index / 2, length: Math.ceil(m[0].length / 2) });
380
720
  regex.lastIndex = m.index + 2; // Move forward to find overlapping matches
381
721
  }
382
722
  return matches;
383
723
  };
384
724
 
385
- return { matcher, type: "hex", private: isPrivate };
725
+ return { matcher, type: "hex", private: isPrivate, reject, rejectCapture };
386
726
  }
387
727
 
388
728
  // function addAllOverlappingMatches(regex, text, textIndex = 0, matches = [], indexStep = 1) {