@arifbiswas/git-pre-push 1.0.10 → 1.0.11

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.
@@ -0,0 +1,602 @@
1
+ /**
2
+ * Malware detection engine.
3
+ *
4
+ * Every finding carries a verdict:
5
+ * - CONFIRMED: the file matches a proof-level signature that legitimate code
6
+ * never produces (known sample hash, a known campaign marker next to an
7
+ * obfuscated loader, a payload hidden behind hundreds of spaces, a script
8
+ * disguised as a font/image, an IDE task that runs a font with node, ...).
9
+ * Only CONFIRMED findings are ever removed automatically.
10
+ * - SUSPECT: looks dangerous but legitimate code can look like this too.
11
+ * Reported to the user, never touched.
12
+ *
13
+ * Signatures are built from real samples caught on 2026-11-12:
14
+ * - tailwind.js with an obfuscated loader appended after ~500 spaces on the
15
+ * last line, starting with global['!']='9-5756'
16
+ * - fa-solid-900.woff2 that was actually obfuscator.io JavaScript starting
17
+ * with global['!']='9-0777-1'
18
+ * - .vscode/tasks.json with runOn: folderOpen running `node <font>.woff2`
19
+ */
20
+
21
+ const crypto = require('crypto');
22
+
23
+ const CONFIRMED = 'CONFIRMED';
24
+ const SUSPECT = 'SUSPECT';
25
+
26
+ // SHA-256 of whole files known to be malware.
27
+ const KNOWN_MALWARE_HASHES = {
28
+ e375610a40d37d682679d4cf68ebadee918cd31a467227867bccfcd2d7786767:
29
+ 'Fake font loader (fa-solid-900.woff2, global[\'!\']=\'9-0777-1\')',
30
+ '03a0b5963a46f05cbd928cba0f0b818fe9976b0a01501f7230f645415c3244a9':
31
+ 'Infected tailwind.js (hidden global[\'!\']=\'9-5756\' loader)'
32
+ };
33
+
34
+ // global['!']='9-5756' / global["!"]="9-0777-1"
35
+ const CAMPAIGN_MARKER_RE = /global\s*\[\s*(['"])!\1\s*\]\s*=\s*(['"])[\w.-]{1,40}\2/g;
36
+
37
+ // Signs of an obfuscated loader. Two or more distinct hits = obfuscated.
38
+ const OBFUSCATION_INDICATORS = [
39
+ /_\$_[0-9a-f]{4}\b/i,
40
+ /\b_0x[0-9a-f]{4,6}\b/i,
41
+ /String\.fromCharCode\s*\(/,
42
+ /\\x[0-9a-f]{2}/i,
43
+ /global\s*\[[^\]]{1,60}\]\s*=\s*require\b/,
44
+ /\beval\s*\(/,
45
+ /\bnew\s+Function\s*\(|\bFunction\s*\(\s*['"`]/,
46
+ /\[\s*['"]constructor['"]\s*\]/,
47
+ /\.split\(\s*(['"])[^'"]{0,8}\1\s*\)\s*\.join\(/,
48
+ /while\s*\(\s*!!\s*\[\s*\]\s*\)/
49
+ ];
50
+
51
+ // Run-something-from-the-internet one-liners.
52
+ const DOWNLOAD_EXEC_RE = new RegExp([
53
+ /(curl|wget)\b[^|\n]*\|\s*(sudo\s+)?(ba|z)?sh\b/.source,
54
+ /(iwr|invoke-webrequest|irm|invoke-restmethod)\b[^|\n]*\|\s*iex\b/.source,
55
+ /iex\s*\(\s*(new-object\s+net\.webclient|iwr|irm|invoke-webrequest)/.source,
56
+ /powershell(\.exe)?\s[^\n]*-e(nc|ncodedcommand)?\s+[A-Za-z0-9+/=]{20,}/.source,
57
+ /certutil(\.exe)?\s+-urlcache/.source,
58
+ /mshta(\.exe)?\s+https?:/.source
59
+ ].join('|'), 'i');
60
+
61
+ // Binary asset formats that are never meant to be executed by an interpreter.
62
+ const NON_EXECUTABLE_EXT = 'woff2?|ttf|otf|eot|png|jpe?g|gif|ico|bmp|webp|mp3|mp4|wav|pdf';
63
+
64
+ // `node public/fonts/fa-solid-900.woff2`, `python logo.png`, ...
65
+ const INTERPRETER_ON_ASSET_RE = new RegExp(
66
+ '(?:^|[\\s(&|;"\'])(node|nodejs|bun|deno(?:\\s+run)?|python[0-9.]*|ruby|perl|php|bash|sh|zsh|' +
67
+ 'powershell(?:\\.exe)?|pwsh|wscript|cscript|osascript)\\s+((?:-[-\\w=]+\\s+)*)["\']?' +
68
+ '([^\\s"\'|&;<>()]+\\.(?:' + NON_EXECUTABLE_EXT + '))(?=$|[\\s"\'|&;<>)])',
69
+ 'gi'
70
+ );
71
+
72
+ // Flags after which the next token is inline code / a module, not a file to run.
73
+ const INLINE_CODE_FLAG_RE = /(^|\s)(-e|-p|-c|-pe|-ne|-m|-r|-i|--eval|--print|--require|--import|--loader|--command)(\s|=|$)/i;
74
+
75
+ /** Finds `<interpreter> <asset file>` in a command line, or null. */
76
+ function findInterpreterOnAsset(command) {
77
+ INTERPRETER_ON_ASSET_RE.lastIndex = 0;
78
+ let m;
79
+ while ((m = INTERPRETER_ON_ASSET_RE.exec(command)) !== null) {
80
+ if (INLINE_CODE_FLAG_RE.test(m[2] || '')) continue;
81
+ return { text: m[0].replace(/^[\s(&|;"']/, ''), file: m[3] };
82
+ }
83
+ return null;
84
+ }
85
+
86
+ // Magic bytes for binary formats that attackers use as disguises.
87
+ const MAGIC = {
88
+ woff: [Buffer.from('wOFF')],
89
+ woff2: [Buffer.from('wOF2')],
90
+ ttf: [Buffer.from([0x00, 0x01, 0x00, 0x00]), Buffer.from('true'), Buffer.from('OTTO'), Buffer.from('ttcf')],
91
+ otf: [Buffer.from('OTTO'), Buffer.from([0x00, 0x01, 0x00, 0x00])],
92
+ png: [Buffer.from([0x89, 0x50, 0x4e, 0x47])],
93
+ jpg: [Buffer.from([0xff, 0xd8, 0xff])],
94
+ jpeg: [Buffer.from([0xff, 0xd8, 0xff])],
95
+ gif: [Buffer.from('GIF8')],
96
+ ico: [Buffer.from([0x00, 0x00, 0x01, 0x00]), Buffer.from([0x00, 0x00, 0x02, 0x00])],
97
+ bmp: [Buffer.from('BM')],
98
+ webp: [Buffer.from('RIFF')],
99
+ pdf: [Buffer.from('%PDF')],
100
+ mp3: [Buffer.from('ID3'), Buffer.from([0xff, 0xfb]), Buffer.from([0xff, 0xf3]), Buffer.from([0xff, 0xf2])],
101
+ wav: [Buffer.from('RIFF')]
102
+ };
103
+
104
+ const LFS_POINTER_PREFIX = 'version https://git-lfs.github.com/spec/v1';
105
+
106
+ // Things a script needs to actually do damage.
107
+ const EXECUTION_TOKENS_RE = /require\s*\(|\beval\s*\(|\bFunction\s*\(|child_process|global\s*\[|process\.|fromCharCode|\bimport\s*\(/;
108
+
109
+ const MAX_TEXT_SCAN_BYTES = 8 * 1024 * 1024;
110
+
111
+ function sha256(buffer) {
112
+ return crypto.createHash('sha256').update(buffer).digest('hex');
113
+ }
114
+
115
+ function extOf(filePath) {
116
+ const base = filePath.replace(/\\/g, '/').split('/').pop() || '';
117
+ const idx = base.lastIndexOf('.');
118
+ return idx > 0 ? base.slice(idx + 1).toLowerCase() : '';
119
+ }
120
+
121
+ function isProbablyBinary(buffer) {
122
+ const len = Math.min(buffer.length, 8000);
123
+ for (let i = 0; i < len; i++) {
124
+ if (buffer[i] === 0) return true;
125
+ }
126
+ return false;
127
+ }
128
+
129
+ function countObfuscationIndicators(text) {
130
+ let hits = 0;
131
+ for (const re of OBFUSCATION_INDICATORS) {
132
+ if (re.test(text)) hits++;
133
+ }
134
+ return hits;
135
+ }
136
+
137
+ function lineNumberAt(text, index) {
138
+ let line = 1;
139
+ for (let i = 0; i < index && i < text.length; i++) {
140
+ if (text.charCodeAt(i) === 10) line++;
141
+ }
142
+ return line;
143
+ }
144
+
145
+ /** Printable preview that can't inject terminal escape codes. */
146
+ function preview(text, max = 120) {
147
+ const clean = String(text).replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, '?').replace(/\s+/g, ' ').trim();
148
+ return clean.length > max ? clean.slice(0, max) + '…' : clean;
149
+ }
150
+
151
+ /** End of the line containing `index` (before \r\n or \n). */
152
+ function lineEnd(text, index) {
153
+ let end = text.indexOf('\n', index);
154
+ if (end === -1) end = text.length;
155
+ if (end > 0 && text[end - 1] === '\r') end--;
156
+ return end;
157
+ }
158
+
159
+ function lineStart(text, index) {
160
+ const nl = text.lastIndexOf('\n', index - 1);
161
+ return nl === -1 ? 0 : nl + 1;
162
+ }
163
+
164
+ /**
165
+ * Parses JSON with comments and trailing commas (VS Code style).
166
+ * Returns null when it cannot be parsed.
167
+ */
168
+ function parseJsonc(text) {
169
+ const src = text.replace(/^/, '');
170
+ let out = '';
171
+ let inStr = false;
172
+ for (let i = 0; i < src.length; i++) {
173
+ const c = src[i];
174
+ if (inStr) {
175
+ out += c;
176
+ if (c === '\\') { out += src[i + 1] || ''; i++; continue; }
177
+ if (c === '"') inStr = false;
178
+ continue;
179
+ }
180
+ if (c === '"') { inStr = true; out += c; continue; }
181
+ if (c === '/' && src[i + 1] === '/') {
182
+ while (i < src.length && src[i] !== '\n') i++;
183
+ out += '\n';
184
+ continue;
185
+ }
186
+ if (c === '/' && src[i + 1] === '*') {
187
+ i += 2;
188
+ while (i < src.length && !(src[i] === '*' && src[i + 1] === '/')) i++;
189
+ i++;
190
+ continue;
191
+ }
192
+ out += c;
193
+ }
194
+
195
+ // Drop trailing commas outside strings.
196
+ let cleaned = '';
197
+ inStr = false;
198
+ for (let i = 0; i < out.length; i++) {
199
+ const c = out[i];
200
+ if (inStr) {
201
+ cleaned += c;
202
+ if (c === '\\') { cleaned += out[i + 1] || ''; i++; continue; }
203
+ if (c === '"') inStr = false;
204
+ continue;
205
+ }
206
+ if (c === '"') { inStr = true; cleaned += c; continue; }
207
+ if (c === ',') {
208
+ let j = i + 1;
209
+ while (j < out.length && /\s/.test(out[j])) j++;
210
+ if (out[j] === '}' || out[j] === ']') continue;
211
+ }
212
+ cleaned += c;
213
+ }
214
+
215
+ try {
216
+ return JSON.parse(cleaned);
217
+ } catch (_) {
218
+ return null;
219
+ }
220
+ }
221
+
222
+ function makeFinding(filePath, fields) {
223
+ return {
224
+ filePath,
225
+ verdict: CONFIRMED,
226
+ severity: 'CRITICAL',
227
+ remedy: { type: 'manual' },
228
+ ...fields
229
+ };
230
+ }
231
+
232
+ // ---------------------------------------------------------------------------
233
+ // Individual detectors
234
+ // ---------------------------------------------------------------------------
235
+
236
+ function detectKnownHash(filePath, buffer) {
237
+ const hash = sha256(buffer);
238
+ const known = KNOWN_MALWARE_HASHES[hash];
239
+ if (!known) return [];
240
+ return [makeFinding(filePath, {
241
+ id: 'known-sample',
242
+ name: 'Known malware sample (exact SHA-256 match)',
243
+ description: known,
244
+ line: `sha256:${hash}`,
245
+ remedy: { type: 'quarantine' }
246
+ })];
247
+ }
248
+
249
+ /** A script pretending to be a font / image. */
250
+ function detectDisguisedScript(filePath, buffer) {
251
+ const ext = extOf(filePath);
252
+ const magics = MAGIC[ext];
253
+ if (!magics || buffer.length < 16) return [];
254
+
255
+ if (magics.some(m => buffer.subarray(0, m.length).equals(m))) return [];
256
+
257
+ const head = buffer.subarray(0, 8192).toString('latin1');
258
+ if (head.startsWith(LFS_POINTER_PREFIX)) return [];
259
+
260
+ // Must be text...
261
+ let printable = 0;
262
+ const sample = buffer.subarray(0, 8192);
263
+ for (const b of sample) {
264
+ if (b === 9 || b === 10 || b === 13 || (b >= 32 && b < 127)) printable++;
265
+ }
266
+ if (printable / sample.length < 0.97) return [];
267
+
268
+ // ...that is a program which can actually execute something.
269
+ const text = buffer.length > MAX_TEXT_SCAN_BYTES
270
+ ? head
271
+ : buffer.toString('latin1');
272
+ const keywordHits = (text.match(/\b(function|var|let|const|return|typeof|while|try|catch)\b/g) || []).length;
273
+ if (keywordHits < 3 || !EXECUTION_TOKENS_RE.test(text)) return [];
274
+
275
+ return [makeFinding(filePath, {
276
+ id: 'disguised-script',
277
+ name: `Script disguised as .${ext} file`,
278
+ description: `File has a .${ext} name but is not a .${ext} file: it is executable JavaScript. ` +
279
+ 'This is how fake-font / fake-image loaders hide malware.',
280
+ line: preview(text),
281
+ lineNumber: 1,
282
+ remedy: { type: 'quarantine' }
283
+ })];
284
+ }
285
+
286
+ /**
287
+ * Payload hidden at the end of a normal-looking line behind a wall of spaces,
288
+ * so it is off-screen in every editor.
289
+ */
290
+ function detectPaddedPayload(filePath, text) {
291
+ const findings = [];
292
+ const re = /[ \t]{120,}(?=\S)/g;
293
+ let m;
294
+ while ((m = re.exec(text)) !== null) {
295
+ const padStart = m.index;
296
+ const payloadStart = padStart + m[0].length;
297
+ const end = lineEnd(text, payloadStart);
298
+ const payload = text.slice(payloadStart, end);
299
+ if (payload.length < 200) continue;
300
+
301
+ CAMPAIGN_MARKER_RE.lastIndex = 0;
302
+ const hasMarker = CAMPAIGN_MARKER_RE.test(payload);
303
+ const indicators = countObfuscationIndicators(payload);
304
+ if (!hasMarker && indicators < 2) continue;
305
+
306
+ const ls = lineStart(text, padStart);
307
+ const visible = text.slice(ls, padStart);
308
+ findings.push(makeFinding(filePath, {
309
+ id: 'padded-payload',
310
+ name: hasMarker
311
+ ? 'Hidden malware loader (global[\'!\'] campaign) behind whitespace padding'
312
+ : 'Obfuscated code hidden behind whitespace padding',
313
+ description: `${m[0].length} spaces push ${payload.length} characters of obfuscated code off-screen ` +
314
+ `on line ${lineNumberAt(text, padStart)}. Legitimate code is never hidden like this.`,
315
+ line: preview(payload),
316
+ lineNumber: lineNumberAt(text, padStart),
317
+ remedy: {
318
+ type: 'strip',
319
+ // Remove padding + payload; keep the visible part of the line.
320
+ start: visible.trim() ? padStart : ls,
321
+ end
322
+ }
323
+ }));
324
+ re.lastIndex = end;
325
+ }
326
+ return findings;
327
+ }
328
+
329
+ /** global['!']='...' marker of the loader family, next to obfuscated code. */
330
+ function detectCampaignMarker(filePath, text) {
331
+ const findings = [];
332
+ CAMPAIGN_MARKER_RE.lastIndex = 0;
333
+ let m;
334
+ while ((m = CAMPAIGN_MARKER_RE.exec(text)) !== null) {
335
+ const after = text.slice(m.index, m.index + 20000);
336
+ if (countObfuscationIndicators(after) < 2) continue;
337
+
338
+ const before = text.slice(0, m.index);
339
+ const atFileStart = before.replace(/^/, '').trim() === '';
340
+ const ls = lineStart(text, m.index);
341
+ const linePrefix = text.slice(ls, m.index);
342
+ const end = lineEnd(text, m.index);
343
+
344
+ let remedy;
345
+ if (atFileStart) {
346
+ remedy = { type: 'quarantine' };
347
+ } else if (/[ \t]{20,}$/.test(linePrefix) || linePrefix.trim() === '') {
348
+ const padStart = ls + linePrefix.search(/[ \t]*$/);
349
+ remedy = { type: 'strip', start: linePrefix.trim() ? padStart : ls, end };
350
+ } else {
351
+ remedy = { type: 'manual' };
352
+ }
353
+
354
+ findings.push(makeFinding(filePath, {
355
+ id: 'campaign-marker',
356
+ name: `Malware loader marker ${preview(m[0], 40)}`,
357
+ description: atFileStart
358
+ ? 'Whole file is an obfuscated malware loader (global[\'!\'] campaign).'
359
+ : 'Obfuscated malware loader (global[\'!\'] campaign) injected into this file.',
360
+ line: preview(text.slice(m.index, m.index + 160)),
361
+ lineNumber: lineNumberAt(text, m.index),
362
+ remedy
363
+ }));
364
+ }
365
+ return findings;
366
+ }
367
+
368
+ function commandStringsOfTask(task) {
369
+ const parts = [];
370
+ const add = (t) => {
371
+ if (!t || typeof t !== 'object') return;
372
+ const cmd = typeof t.command === 'string' ? t.command
373
+ : (t.command && typeof t.command.value === 'string' ? t.command.value : '');
374
+ const args = Array.isArray(t.args)
375
+ ? t.args.map(a => (typeof a === 'string' ? a : (a && a.value) || '')).join(' ')
376
+ : '';
377
+ if (cmd || args) parts.push(`${cmd} ${args}`.trim());
378
+ };
379
+ add(task);
380
+ add(task.osx);
381
+ add(task.linux);
382
+ add(task.windows);
383
+ return parts;
384
+ }
385
+
386
+ /** .vscode/tasks.json that runs something automatically on folder open. */
387
+ function detectAutoRunTask(filePath, text) {
388
+ const findings = [];
389
+ if (!/folderOpen/i.test(text)) return findings;
390
+
391
+ const parsed = parseJsonc(text);
392
+ const tasks = parsed && Array.isArray(parsed.tasks) ? parsed.tasks : null;
393
+
394
+ if (!tasks) {
395
+ // Unparseable: fall back to whole-file regex, only quarantine on proof.
396
+ const asset = findInterpreterOnAsset(text);
397
+ const dl = text.match(DOWNLOAD_EXEC_RE);
398
+ if (asset || dl) {
399
+ findings.push(makeFinding(filePath, {
400
+ id: 'autorun-task',
401
+ name: 'IDE auto-run task executes malware on folder open',
402
+ description: asset
403
+ ? `Opening the folder runs "${preview(asset.text, 80)}": a non-script file executed as code.`
404
+ : 'Opening the folder downloads and executes remote code.',
405
+ line: preview(asset ? asset.text : dl[0]),
406
+ remedy: { type: 'quarantine' }
407
+ }));
408
+ }
409
+ return findings;
410
+ }
411
+
412
+ tasks.forEach((task, index) => {
413
+ if (!task || !task.runOptions || task.runOptions.runOn !== 'folderOpen') return;
414
+ const cmds = commandStringsOfTask(task);
415
+ const joined = cmds.join(' ; ');
416
+ const asset = findInterpreterOnAsset(joined);
417
+ const dl = joined.match(DOWNLOAD_EXEC_RE);
418
+ const label = task.label || `task #${index + 1}`;
419
+
420
+ if (asset || dl) {
421
+ findings.push(makeFinding(filePath, {
422
+ id: 'autorun-task',
423
+ name: 'IDE auto-run task executes malware on folder open',
424
+ description: asset
425
+ ? `Task "${preview(label, 60)}" runs "${preview(asset.text, 80)}" automatically when the folder is opened: ` +
426
+ 'a font/image file executed as code.'
427
+ : `Task "${preview(label, 60)}" downloads and executes remote code when the folder is opened.`,
428
+ line: preview(joined),
429
+ remedy: { type: 'remove-task', index, label: task.label || null }
430
+ }));
431
+ } else {
432
+ findings.push(makeFinding(filePath, {
433
+ id: 'autorun-task-suspect',
434
+ verdict: SUSPECT,
435
+ severity: 'WARNING',
436
+ name: 'IDE task runs automatically on folder open',
437
+ description: `Task "${preview(label, 60)}" runs as soon as the folder is opened in VS Code / Cursor. Check it is yours.`,
438
+ line: preview(joined)
439
+ }));
440
+ }
441
+ });
442
+
443
+ return findings;
444
+ }
445
+
446
+ const LIFECYCLE_SCRIPTS = ['preinstall', 'install', 'postinstall', 'prepare', 'prepublish', 'preprepare', 'postprepare'];
447
+
448
+ /** package.json scripts that execute a font/image or pipe the internet into a shell. */
449
+ function detectPackageJson(filePath, text) {
450
+ const findings = [];
451
+ let pkg;
452
+ try {
453
+ pkg = JSON.parse(text.replace(/^/, ''));
454
+ } catch (_) {
455
+ return findings;
456
+ }
457
+ if (!pkg || typeof pkg.scripts !== 'object' || !pkg.scripts) return findings;
458
+
459
+ for (const [name, cmd] of Object.entries(pkg.scripts)) {
460
+ if (typeof cmd !== 'string') continue;
461
+ const isLifecycle = LIFECYCLE_SCRIPTS.includes(name);
462
+ const asset = findInterpreterOnAsset(cmd);
463
+ if (asset) {
464
+ findings.push(makeFinding(filePath, {
465
+ id: 'npm-script-asset',
466
+ name: `npm script "${preview(name, 40)}" executes a non-script file`,
467
+ description: `"${preview(asset.text, 80)}" runs a font/image file as code` +
468
+ (isLifecycle ? ' automatically on npm install.' : '.'),
469
+ line: preview(cmd),
470
+ remedy: isLifecycle ? { type: 'remove-script', name } : { type: 'manual' }
471
+ }));
472
+ continue;
473
+ }
474
+ if (isLifecycle && DOWNLOAD_EXEC_RE.test(cmd)) {
475
+ findings.push(makeFinding(filePath, {
476
+ id: 'npm-script-download',
477
+ verdict: SUSPECT,
478
+ severity: 'WARNING',
479
+ name: `npm "${preview(name, 40)}" script downloads and runs remote code`,
480
+ description: 'Runs on every npm install. Some installers do this legitimately; verify the URL.',
481
+ line: preview(cmd)
482
+ }));
483
+ }
484
+ }
485
+ return findings;
486
+ }
487
+
488
+ /** obfuscator.io-style string-array rotation loader (not proof on its own). */
489
+ function detectObfuscatorLoader(filePath, text) {
490
+ if (!/while\s*\(\s*!!\s*\[\s*\]\s*\)\s*\{\s*try\s*\{/.test(text)) return [];
491
+ if (!/\[\s*['"]push['"]\s*\]\s*\(/.test(text) || !/\[\s*['"]shift['"]\s*\]\s*\(/.test(text)) return [];
492
+ const hexIds = (text.match(/\b_0x[0-9a-f]{4,6}\b/gi) || []).length;
493
+ if (hexIds < 30) return [];
494
+ return [makeFinding(filePath, {
495
+ id: 'obfuscated-loader',
496
+ verdict: SUSPECT,
497
+ severity: 'WARNING',
498
+ name: 'Heavily obfuscated JavaScript (obfuscator.io loader)',
499
+ description: 'Code is deliberately unreadable. Malware loaders look like this; a few commercial libraries do too.',
500
+ line: preview(text.slice(text.search(/while\s*\(\s*!!/), text.search(/while\s*\(\s*!!/) + 120)),
501
+ lineNumber: lineNumberAt(text, text.search(/while\s*\(\s*!!/))
502
+ })];
503
+ }
504
+
505
+ // ---------------------------------------------------------------------------
506
+
507
+ const REMEDY_RANK = { quarantine: 4, 'remove-task': 3, 'remove-script': 3, strip: 2, manual: 1, covered: 0 };
508
+
509
+ /**
510
+ * Removes duplicate findings: one strip per range, and if anything wants the
511
+ * whole file quarantined, that wins for CONFIRMED findings.
512
+ */
513
+ function consolidate(findings) {
514
+ const confirmed = findings.filter(f => f.verdict === CONFIRMED);
515
+ const suspect = findings.filter(f => f.verdict !== CONFIRMED);
516
+
517
+ const out = [];
518
+ for (const f of confirmed) {
519
+ if (f.remedy.type === 'strip') {
520
+ const overlap = out.find(o => o.remedy.type === 'strip' &&
521
+ o.remedy.start <= f.remedy.end && f.remedy.start <= o.remedy.end);
522
+ if (overlap) {
523
+ overlap.remedy.start = Math.min(overlap.remedy.start, f.remedy.start);
524
+ overlap.remedy.end = Math.max(overlap.remedy.end, f.remedy.end);
525
+ if (f.id === 'padded-payload') {
526
+ overlap.name = f.name;
527
+ overlap.description = f.description;
528
+ }
529
+ continue;
530
+ }
531
+ }
532
+ if (f.id === 'campaign-marker' && f.remedy.type === 'manual') {
533
+ // Marker inside a payload that another rule already strips.
534
+ const covered = confirmed.some(o => o !== f && o.remedy.type === 'strip' && o.lineNumber === f.lineNumber);
535
+ if (covered) continue;
536
+ }
537
+ out.push(f);
538
+ }
539
+
540
+ // A known infected file that still holds legitimate code (payload appended
541
+ // to a real file) is repaired by the strip, not deleted.
542
+ const known = out.find(f => f.id === 'known-sample');
543
+ if (known && out.some(f => f.remedy.type === 'strip')) {
544
+ known.remedy = { type: 'covered' };
545
+ }
546
+
547
+ // Suspect findings on a file that is confirmed malware add nothing.
548
+ const confirmedFiles = new Set(out.map(f => f.filePath));
549
+ return out.concat(suspect.filter(f => !confirmedFiles.has(f.filePath) || f.id === 'autorun-task-suspect'));
550
+ }
551
+
552
+ /**
553
+ * Inspects one file.
554
+ * @param {string} filePath repo-relative path (used for extension / config detection)
555
+ * @param {Buffer|string} content
556
+ * @returns {Array<object>} findings
557
+ */
558
+ function detectMalware(filePath, content) {
559
+ if (content == null) return [];
560
+ const buffer = Buffer.isBuffer(content) ? content : Buffer.from(String(content), 'latin1');
561
+ if (buffer.length === 0) return [];
562
+
563
+ const normalized = filePath.replace(/\\/g, '/');
564
+ const findings = [];
565
+
566
+ findings.push(...detectKnownHash(normalized, buffer));
567
+ findings.push(...detectDisguisedScript(normalized, buffer));
568
+
569
+ if (buffer.length <= MAX_TEXT_SCAN_BYTES && !isProbablyBinary(buffer)) {
570
+ const text = buffer.toString('latin1');
571
+ findings.push(...detectPaddedPayload(normalized, text));
572
+ findings.push(...detectCampaignMarker(normalized, text));
573
+
574
+ if (/(^|\/)\.vscode\/tasks\.json$/i.test(normalized) || /(^|\/)\.cursor\/tasks\.json$/i.test(normalized)) {
575
+ findings.push(...detectAutoRunTask(normalized, text));
576
+ }
577
+ if (/(^|\/)package\.json$/i.test(normalized)) {
578
+ findings.push(...detectPackageJson(normalized, text));
579
+ }
580
+ if (/\.(c|m)?jsx?$|\.tsx?$|\.woff2?$|\.ttf$|\.otf$/i.test(normalized)) {
581
+ findings.push(...detectObfuscatorLoader(normalized, text));
582
+ }
583
+ }
584
+
585
+ const merged = consolidate(findings);
586
+ // A quarantined file only needs one entry per rule; keep the strongest remedy first.
587
+ merged.sort((a, b) => (REMEDY_RANK[b.remedy.type] || 0) - (REMEDY_RANK[a.remedy.type] || 0));
588
+ return merged;
589
+ }
590
+
591
+ module.exports = {
592
+ CONFIRMED,
593
+ SUSPECT,
594
+ KNOWN_MALWARE_HASHES,
595
+ CAMPAIGN_MARKER_RE,
596
+ INTERPRETER_ON_ASSET_RE,
597
+ findInterpreterOnAsset,
598
+ detectMalware,
599
+ parseJsonc,
600
+ sha256,
601
+ preview
602
+ };