@profullstack/threatcrush 0.13.74 → 0.13.77

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 @@
1
+ {"version":3,"sources":["../../../packages/av/src/node/locations.ts","../../../packages/av/src/node/walk.ts","../../../packages/av/src/node/scan-file.ts","../../../packages/av/src/magic.ts","../../../packages/av/src/rules.ts","../../../packages/av/src/sha256.ts","../../../packages/av/src/engine.ts","../../../packages/av/src/node/scan-worker.ts","../../../packages/av/src/node/clamav.ts","../../../packages/av/src/node/quarantine.ts","../../../packages/av/src/node/scan.ts","../../../packages/av/src/node/watch.ts","../src/av-worker.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { homedir, tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\nexport interface ScanTarget {\n path: string;\n /** How many directory levels to descend; Infinity for all. */\n depth: number;\n}\n\ntype Env = Record<string, string | undefined>;\n\n/**\n * Where malware actually lands on a home computer: downloads, the desktop,\n * temp folders and the places programs register to start at login. A quick\n * scan covers these in a minute or two instead of walking the whole disk.\n */\nexport function quickScanTargets(platform: NodeJS.Platform = process.platform, env: Env = process.env, home = homedir()): ScanTarget[] {\n const t: ScanTarget[] = [\n { path: join(home, 'Downloads'), depth: 3 },\n { path: join(home, 'Desktop'), depth: 2 },\n ];\n if (platform === 'win32') {\n const appData = env.APPDATA ?? join(home, 'AppData', 'Roaming');\n const local = env.LOCALAPPDATA ?? join(home, 'AppData', 'Local');\n const programData = env.ProgramData ?? env.PROGRAMDATA ?? 'C:\\\\ProgramData';\n t.push(\n { path: env.TEMP ?? join(local, 'Temp'), depth: 2 },\n { path: join(appData, 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup'), depth: 1 },\n { path: join(programData, 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'StartUp'), depth: 1 },\n // Droppers love %APPDATA%\\<random>\\payload.exe; two levels catches that without crawling every app's cache.\n { path: appData, depth: 2 },\n { path: local, depth: 1 },\n { path: join(env.PUBLIC ?? 'C:\\\\Users\\\\Public'), depth: 2 },\n );\n } else if (platform === 'darwin') {\n t.push(\n { path: join(home, 'Library', 'LaunchAgents'), depth: 1 },\n { path: '/Library/LaunchAgents', depth: 1 },\n { path: '/Library/LaunchDaemons', depth: 1 },\n { path: '/Users/Shared', depth: 2 },\n { path: '/tmp', depth: 2 },\n { path: tmpdir(), depth: 2 },\n );\n } else {\n t.push(\n { path: '/tmp', depth: 2 },\n { path: '/var/tmp', depth: 2 },\n { path: '/dev/shm', depth: 2 },\n { path: join(home, '.config', 'autostart'), depth: 1 },\n { path: join(home, '.config', 'systemd', 'user'), depth: 1 },\n { path: join(home, '.local', 'bin'), depth: 1 },\n { path: '/etc/cron.d', depth: 1 },\n { path: '/etc/systemd/system', depth: 1 },\n );\n }\n const seen = new Set<string>();\n return t.filter((x) => !seen.has(x.path) && (seen.add(x.path), existsSync(x.path)));\n}\n\n/** A full scan: the whole home folder, plus the quick-scan system locations. */\nexport function fullScanTargets(platform: NodeJS.Platform = process.platform, env: Env = process.env, home = homedir()): ScanTarget[] {\n const quick = quickScanTargets(platform, env, home).filter((x) => !x.path.startsWith(home));\n const extra: ScanTarget[] = platform === 'linux' ? [{ path: '/opt', depth: Infinity }, { path: '/usr/local/bin', depth: 1 }] : [];\n return [{ path: home, depth: Infinity }, ...quick, ...extra.filter((x) => existsSync(x.path))];\n}\n","import { lstat, opendir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { ScanTarget } from './locations';\n\n/**\n * Directories never worth walking: pseudo-filesystems, version-control\n * internals and package caches that are huge, rebuilt from the network, and\n * covered by `threatcrush scan --deps` instead.\n */\nexport const SKIP_DIR_NAMES = new Set([\n '.git', '.hg', '.svn', 'node_modules', '.pnpm-store', '.npm', '.yarn', '__pycache__', '.venv', 'venv',\n '.cargo', '.rustup', '.gradle', '.m2', '.cache', '.Trash', '$Recycle.Bin', 'System Volume Information',\n '.threatcrush',\n]);\nexport const SKIP_ROOTS = ['/proc', '/sys', '/dev/pts', '/run', '/snap'];\n\nexport interface WalkOptions {\n skipDirNames?: Set<string>;\n /** Called for each unreadable entry. */\n onSkip?: (path: string, reason: string) => void;\n signal?: AbortSignal;\n}\n\nexport interface WalkedFile {\n path: string;\n size: number;\n}\n\n/** Yield regular files under each target. Never follows symlinks. */\nexport async function* walkTargets(targets: ScanTarget[], opts: WalkOptions = {}): AsyncGenerator<WalkedFile> {\n const skip = opts.skipDirNames ?? SKIP_DIR_NAMES;\n const seen = new Set<string>();\n for (const t of targets) {\n let st;\n try {\n st = await lstat(t.path);\n } catch (e) {\n opts.onSkip?.(t.path, (e as NodeJS.ErrnoException).code ?? 'unreadable');\n continue;\n }\n if (st.isFile()) {\n if (!seen.has(t.path)) {\n seen.add(t.path);\n yield { path: t.path, size: st.size };\n }\n continue;\n }\n if (!st.isDirectory()) continue;\n const stack: Array<[string, number]> = [[t.path, 0]];\n while (stack.length) {\n if (opts.signal?.aborted) return;\n const [dir, depth] = stack.pop()!;\n if (SKIP_ROOTS.some((r) => dir === r || dir.startsWith(`${r}/`))) continue;\n let handle;\n try {\n handle = await opendir(dir);\n } catch (e) {\n opts.onSkip?.(dir, (e as NodeJS.ErrnoException).code ?? 'unreadable');\n continue;\n }\n for await (const ent of handle) {\n const p = join(dir, ent.name);\n if (ent.isSymbolicLink()) continue;\n if (ent.isDirectory()) {\n if (depth + 1 < t.depth && !skip.has(ent.name)) stack.push([p, depth + 1]);\n continue;\n }\n if (!ent.isFile() || seen.has(p)) continue;\n seen.add(p);\n try {\n const s = await lstat(p);\n yield { path: p, size: s.size };\n } catch (e) {\n opts.onSkip?.(p, (e as NodeJS.ErrnoException).code ?? 'unreadable');\n }\n }\n }\n }\n}\n\nexport interface WalkFilesOptions extends WalkOptions {\n /** Directories read at once. Default 8. */\n concurrency?: number;\n}\n\n/**\n * Yield regular-file paths under each target, reading several directories at\n * once and never stat-ing files (the scanner `fstat`s what it opens). Built\n * for full-disk scans of millions of files; {@link walkTargets} stays for\n * callers that want sizes.\n *\n * Overlapping targets are walked without listing a file twice: each directory\n * remembers how deep it was walked, and a deeper revisit only descends into\n * the part not seen before.\n */\nexport async function* walkFiles(targets: ScanTarget[], opts: WalkFilesOptions = {}): AsyncGenerator<string> {\n const skipNames = opts.skipDirNames ?? SKIP_DIR_NAMES;\n const limit = Math.max(1, opts.concurrency ?? 8);\n const HIGH_WATER = 8192;\n const visited = new Map<string, number>();\n const fileTargets = new Set<string>();\n // Deepest first, so a shallow target nested in a deep one is a pure revisit.\n const ordered = [...targets].sort((a, b) => (a.depth === b.depth ? 0 : b.depth > a.depth ? 1 : -1));\n\n // Single files first, so a directory walk that reaches one can leave it out.\n const dirs: ScanTarget[] = [];\n for (const t of ordered) {\n let st;\n try {\n st = await lstat(t.path);\n } catch (e) {\n opts.onSkip?.(t.path, (e as NodeJS.ErrnoException).code ?? 'unreadable');\n continue;\n }\n if (st.isFile()) {\n if (!fileTargets.has(t.path)) {\n fileTargets.add(t.path);\n yield t.path;\n }\n } else if (st.isDirectory() && t.depth >= 1) dirs.push(t);\n }\n\n for (const t of dirs) {\n const stack: Array<[string, number]> = [[t.path, t.depth]];\n const out: string[] = [];\n let active = 0;\n let wake: (() => void) | null = null;\n const notify = () => {\n const w = wake;\n wake = null;\n w?.();\n };\n\n const readDir = async (dir: string, remaining: number, filesToo: boolean) => {\n try {\n const handle = await opendir(dir, { bufferSize: 256 });\n for await (const ent of handle) {\n if (ent.isSymbolicLink()) continue;\n const p = join(dir, ent.name);\n if (ent.isDirectory()) {\n if (remaining > 1 && !skipNames.has(ent.name)) stack.push([p, remaining - 1]);\n } else if (filesToo && ent.isFile() && !fileTargets.has(p)) {\n out.push(p);\n if (out.length >= 512) notify();\n }\n }\n } catch (e) {\n opts.onSkip?.(dir, (e as NodeJS.ErrnoException).code ?? 'unreadable');\n } finally {\n active--;\n notify();\n }\n };\n\n for (;;) {\n if (opts.signal?.aborted) return;\n while (active < limit && stack.length && out.length < HIGH_WATER) {\n const [dir, remaining] = stack.pop()!;\n if (SKIP_ROOTS.some((r) => dir === r || dir.startsWith(`${r}/`))) continue;\n const before = visited.get(dir);\n if (before !== undefined && before >= remaining) continue;\n visited.set(dir, remaining);\n active++;\n void readDir(dir, remaining, before === undefined);\n }\n if (out.length) {\n for (const p of out.splice(0)) yield p;\n continue;\n }\n if (!active && !stack.length) break;\n await new Promise<void>((resolve) => {\n wake = resolve;\n });\n }\n }\n}\n","import { createHash } from 'node:crypto';\nimport { closeSync, constants, fstatSync, openSync, readSync } from 'node:fs';\nimport { scanBytes, type SignatureSet } from '../engine';\nimport type { AvFileResult } from '../types';\n\n/**\n * Scan one file with synchronous I/O. Meant for worker threads: a sync read\n * costs no libuv thread-pool hop (that pool is 4 threads per process, which\n * otherwise caps every async file read in the scan at 4 at a time), and\n * blocking a worker blocks nothing else.\n */\n\nexport type FileOutcome =\n | { kind: 'result'; result: AvFileResult }\n | { kind: 'skip'; path: string; reason: string }\n | { kind: 'none' };\n\nexport interface ScanFileOptions {\n /** Bytes of the file the heuristics see. */\n cap: number;\n /** Larger files are skipped, not hashed. */\n maxFile: number;\n signatures?: SignatureSet;\n}\n\nconst CHUNK = 1 << 20;\nconst OPEN_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\n\n// Reused across calls; one scanner per thread, and calls are serialised.\nlet head: Buffer = Buffer.allocUnsafe(64 * 1024);\nlet chunk: Buffer | null = null;\n\nexport async function scanFileSync(path: string, opts: ScanFileOptions): Promise<FileOutcome> {\n let fd: number;\n try {\n fd = openSync(path, OPEN_FLAGS);\n } catch (e) {\n const code = (e as NodeJS.ErrnoException).code ?? 'unreadable';\n // Gone between the directory listing and now, or a symlink swapped in: nothing to scan.\n if (code === 'ENOENT' || code === 'ELOOP') return { kind: 'none' };\n return { kind: 'result', result: errorResult(path, 0, code) };\n }\n let size = 0;\n try {\n const st = fstatSync(fd);\n if (!st.isFile() || st.size === 0) return { kind: 'none' };\n size = st.size;\n if (size > opts.maxFile) return { kind: 'skip', path, reason: `larger than ${Math.round(opts.maxFile / 1048576)} MB` };\n\n const want = Math.min(size, opts.cap);\n if (head.length < want) head = Buffer.allocUnsafe(Math.max(want, head.length * 2 > opts.cap ? want : head.length * 2));\n const hash = createHash('sha256');\n let filled = 0;\n while (filled < want) {\n const n = readSync(fd, head, filled, want - filled, null);\n if (n === 0) break;\n filled += n;\n }\n hash.update(head.subarray(0, filled));\n let total = filled;\n if (filled === want && size > want) {\n chunk ??= Buffer.allocUnsafe(CHUNK);\n for (;;) {\n const n = readSync(fd, chunk, 0, CHUNK, null);\n if (n === 0) break;\n hash.update(chunk.subarray(0, n));\n total += n;\n }\n }\n const result = await scanBytes(\n { name: path, bytes: head.subarray(0, filled), size: total, sha256: hash.digest('hex') },\n { signatures: opts.signatures },\n );\n return { kind: 'result', result };\n } catch (e) {\n const code = (e as NodeJS.ErrnoException).code ?? (e as Error).message;\n return { kind: 'result', result: errorResult(path, size, code) };\n } finally {\n try {\n closeSync(fd);\n } catch {\n /* already closed */\n }\n }\n}\n\nfunction errorResult(path: string, size: number, note: string): AvFileResult {\n return { path, size, sha256: null, kind: 'unknown', verdict: 'error', detections: [], note };\n}\n","import type { FileKind } from './types';\n\nconst starts = (b: Uint8Array, sig: number[], at = 0) =>\n b.length >= at + sig.length && sig.every((v, i) => b[at + i] === v);\n\n/** Identify a file from its first bytes. The name is never consulted. */\nexport function sniffKind(b: Uint8Array): FileKind {\n if (starts(b, [0x4d, 0x5a])) return 'pe';\n if (starts(b, [0x7f, 0x45, 0x4c, 0x46])) return 'elf';\n if (\n starts(b, [0xfe, 0xed, 0xfa, 0xce]) || starts(b, [0xfe, 0xed, 0xfa, 0xcf]) ||\n starts(b, [0xce, 0xfa, 0xed, 0xfe]) || starts(b, [0xcf, 0xfa, 0xed, 0xfe])\n ) return 'macho';\n // 0xCAFEBABE is both a Mach-O fat binary and a Java class; a fat binary has a\n // small architecture count where a class file has its version number.\n if (starts(b, [0xca, 0xfe, 0xba, 0xbe]) && b.length >= 8 && b[4] === 0 && b[5] === 0 && b[6] === 0 && b[7] > 0 && b[7] < 20) return 'macho';\n if (starts(b, [0x50, 0x4b, 0x03, 0x04]) || starts(b, [0x50, 0x4b, 0x05, 0x06])) return 'zip';\n if (starts(b, [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1])) return 'ole';\n if (starts(b, [0x25, 0x50, 0x44, 0x46, 0x2d])) return 'pdf';\n if (starts(b, [0x4c, 0x00, 0x00, 0x00, 0x01, 0x14, 0x02, 0x00])) return 'lnk';\n if (starts(b, [0x7b, 0x5c, 0x72, 0x74, 0x66])) return 'rtf';\n if (starts(b, [0x64, 0x65, 0x78, 0x0a])) return 'dex';\n if (starts(b, [0x23, 0x21])) return 'script';\n if (\n starts(b, [0xff, 0xd8, 0xff]) || starts(b, [0x89, 0x50, 0x4e, 0x47]) || starts(b, [0x47, 0x49, 0x46, 0x38]) ||\n (starts(b, [0x52, 0x49, 0x46, 0x46]) && starts(b, [0x57, 0x45, 0x42, 0x50], 8)) || starts(b, [0x42, 0x4d])\n ) return 'image';\n if (\n starts(b, [0x66, 0x74, 0x79, 0x70], 4) || starts(b, [0x49, 0x44, 0x33]) || starts(b, [0x1a, 0x45, 0xdf, 0xa3]) ||\n starts(b, [0x4f, 0x67, 0x67, 0x53]) || starts(b, [0x66, 0x4c, 0x61, 0x43])\n ) return 'media';\n if (\n starts(b, [0x1f, 0x8b]) || starts(b, [0x52, 0x61, 0x72, 0x21]) || starts(b, [0x37, 0x7a, 0xbc, 0xaf]) ||\n starts(b, [0xfd, 0x37, 0x7a, 0x58, 0x5a]) || starts(b, [0x28, 0xb5, 0x2f, 0xfd])\n ) return 'archive';\n if (looksLikeText(b)) return 'text';\n return 'unknown';\n}\n\nfunction looksLikeText(b: Uint8Array): boolean {\n const n = Math.min(b.length, 4096);\n if (n === 0) return true;\n let odd = 0;\n for (let i = 0; i < n; i++) {\n const c = b[i];\n if (c === 0) return false;\n if (c < 9 || (c > 13 && c < 32)) odd++;\n }\n return odd / n < 0.05;\n}\n\nexport const EXECUTABLE_KINDS: ReadonlySet<FileKind> = new Set(['pe', 'elf', 'macho']);\n\n/** Extensions people open expecting a document, picture or video. */\nexport const DOCUMENT_EXTENSIONS = new Set([\n 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'txt', 'rtf', 'csv',\n 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'heic', 'svg',\n 'mp3', 'mp4', 'mov', 'avi', 'mkv', 'wav', 'm4a',\n]);\n\n/** Extensions Windows (or a browser) will run when double-clicked. */\nexport const RUNNABLE_EXTENSIONS = new Set([\n 'exe', 'scr', 'com', 'pif', 'bat', 'cmd', 'msi', 'js', 'jse', 'vbs', 'vbe', 'wsf', 'hta', 'lnk', 'ps1', 'cpl', 'jar', 'apk', 'app', 'dmg', 'pkg', 'iso', 'img',\n]);\n\nexport function extOf(name: string): string {\n const base = name.split(/[\\\\/]/).pop() ?? name;\n const dot = base.lastIndexOf('.');\n return dot > 0 ? base.slice(dot + 1).toLowerCase() : '';\n}\n\nexport function baseName(name: string): string {\n return name.split(/[\\\\/]/).pop() ?? name;\n}\n","import { baseName, DOCUMENT_EXTENSIONS, EXECUTABLE_KINDS, extOf } from './magic';\nimport type { AvDetection, AvSeverity, FileKind } from './types';\n\n/**\n * CrushAV heuristic rules.\n *\n * Every rule here runs on bytes alone, so the same rules protect a Linux box,\n * a Windows laptop, a browser tab and a phone. Rules are scoped tightly to the\n * file types where the pattern means something: a reverse shell in a `.sh` is\n * an attack, the same line in a pentest write-up `.md` is homework. The bar for\n * `malicious` is \"a reasonable person would never want this file\"; anything\n * that legitimate software also does is at most `suspicious`.\n */\n\nexport interface RuleContext {\n name: string;\n ext: string;\n kind: FileKind;\n /** Actual file size (bytes may be truncated). */\n size: number;\n bytes: Uint8Array;\n /** Bytes as Latin-1, so every byte maps to one char. */\n text: string;\n /** UTF-16LE strings view for Windows binaries and shortcuts ('' otherwise). */\n wide: string;\n}\n\nexport interface AvRule {\n id: string;\n name: string;\n severity: AvSeverity;\n impact: AvDetection['impact'];\n description: string;\n /** Return true, or a detection override (e.g. upgraded impact), on a match. */\n test(ctx: RuleContext): boolean | Partial<AvDetection>;\n}\n\nexport const EICAR = 'X5O!P%@AP[4\\\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*';\n\nconst SCRIPT_EXTS = new Set(['ps1', 'psm1', 'bat', 'cmd', 'vbs', 'vbe', 'js', 'jse', 'wsf', 'hta', 'sh', 'bash', 'zsh', 'py', 'pl', 'rb', 'php', 'command', 'applescript', 'scpt']);\nconst WIN_SCRIPT_EXTS = new Set(['js', 'jse', 'vbs', 'vbe', 'wsf', 'hta']);\nconst WEB_EXTS = new Set(['html', 'htm', 'shtml', 'xhtml', 'svg', 'hta']);\nconst SERVER_SCRIPT_EXTS = new Set(['php', 'phtml', 'php3', 'php4', 'php5', 'php7', 'phar', 'asp', 'aspx', 'ashx', 'jsp', 'jspx']);\n\nconst isScript = (c: RuleContext) => c.kind === 'script' || SCRIPT_EXTS.has(c.ext);\n/**\n * Somewhere Windows would actually run PowerShell from. A `.js` file counts\n * only when it is a Windows Script Host script: a Node bundle that merely\n * contains the words (a security tool's own rules, say) is not one. Measured:\n * 49 false hits on bundled CLI builds before this guard.\n */\nconst POWERSHELL_HOST_EXTS = new Set(['ps1', 'psm1', 'bat', 'cmd', 'vbs', 'vbe', 'wsf', 'hta']);\nconst isWindowsScriptContext = (c: RuleContext) =>\n POWERSHELL_HOST_EXTS.has(c.ext) ||\n c.kind === 'lnk' ||\n (['js', 'jse'].includes(c.ext) && /ActiveXObject|WScript\\.|GetObject\\(\\s*[\"']winmgmts/i.test(c.text));\nconst NON_RUNNABLE_SOURCE_EXTS = new Set(['ts', 'tsx', 'mts', 'cts', 'md', 'markdown', 'rst', 'go', 'rs', 'c', 'h', 'cc', 'cpp', 'hpp', 'java', 'kt', 'cs', 'swift', 'scala']);\n/** Ransom notes are plain text or HTML, usually with no other extension. */\nconst NOTE_EXTS = new Set(['txt', 'html', 'htm', 'hta', 'rtf', '']);\nconst allText = (c: RuleContext) => (c.wide ? `${c.text}\\n${c.wide}` : c.text);\n\nconst RANSOM_COMMANDS = [\n /vssadmin(?:\\.exe)?[\"']?\\s+delete\\s+shadows/i,\n /wmic(?:\\.exe)?[\"']?\\s+shadowcopy\\s+delete/i,\n /wbadmin(?:\\.exe)?[\"']?\\s+delete\\s+(?:catalog|backup|systemstatebackup)/i,\n /bcdedit(?:\\.exe)?[\"']?\\s+\\/set\\s+\\{default\\}\\s+(?:recoveryenabled\\s+no|bootstatuspolicy\\s+ignoreallfailures)/i,\n /Get-WmiObject\\s+Win32_Shadowcopy\\s*\\|\\s*ForEach-Object\\s*\\{\\s*\\$_\\.Delete\\(\\)/i,\n];\n\nexport const RULES: AvRule[] = [\n {\n id: 'CrushAV.Test.EICAR',\n name: 'EICAR test file',\n severity: 'low',\n impact: 'malicious',\n description:\n 'The industry-standard harmless antivirus test file. It cannot do anything; it only proves the scanner works.',\n test: (c) => c.size <= 128 && c.text.trimStart().startsWith(EICAR),\n },\n {\n id: 'CrushAV.Disguise.ExecutableAsDocument',\n name: 'Program disguised as a document',\n severity: 'high',\n impact: 'malicious',\n description:\n 'This file is a program, but its name says it is a document, picture or video. Real documents never do this; it is how malware tricks people into running it. Do not open it.',\n test: (c) => EXECUTABLE_KINDS.has(c.kind) && DOCUMENT_EXTENSIONS.has(c.ext),\n },\n {\n id: 'CrushAV.Disguise.DoubleExtension',\n name: 'Fake file extension',\n severity: 'high',\n impact: 'suspicious',\n description:\n 'The name hides a runnable extension behind a harmless-looking one (like \"invoice.pdf.exe\"). Windows hides the last part by default, so this looks like a document but runs as a program.',\n test: (c) =>\n /\\.(?:pdf|docx?|xlsx?|pptx?|jpe?g|png|gif|txt|rtf|mp3|mp4|mov|zip)[\\s_.]*\\.(?:exe|scr|com|pif|bat|cmd|js|jse|vbs|vbe|wsf|hta|lnk|ps1|cpl)$/i.test(baseName(c.name)) ||\n /\\s{6,}\\.(?:exe|scr|com|pif|bat|cmd|js|vbs|hta|lnk)$/i.test(baseName(c.name)),\n },\n {\n id: 'CrushAV.Disguise.RightToLeftOverride',\n name: 'Reversed file name trick',\n severity: 'high',\n impact: 'malicious',\n description:\n 'The file name contains an invisible character that reverses the text after it, so \"photo‮gpj.exe\" displays as \"photoexe.jpg\". Legitimate files have no reason to do this.',\n test: (c) => baseName(c.name).includes('‮'),\n },\n {\n id: 'CrushAV.PowerShell.EncodedCommand',\n name: 'Hidden PowerShell command',\n severity: 'high',\n impact: 'suspicious',\n description:\n 'Runs PowerShell with a long base64-encoded command, which hides what it does. Malware droppers use this constantly; legitimate software rarely needs to.',\n test: (c) =>\n (isWindowsScriptContext(c) || c.kind === 'pe') &&\n /powershell(?:\\.exe)?[\"']?[^\\n]{0,120}?\\s-(?:e|ec|en|enc|enco|encod|encodedcommand)\\s+[\"']?[A-Za-z0-9+/]{80,}={0,2}/i.test(allText(c)),\n },\n {\n id: 'CrushAV.PowerShell.DownloadExecute',\n name: 'Downloads and runs code',\n severity: 'medium',\n impact: 'suspicious',\n description:\n 'Downloads code from the internet and runs it straight away. Some installers do this; if you did not expect this script, delete it.',\n test: (c) => {\n // Scripts and shortcuts only: in compiled binaries, short tokens like\n // \"iwr\" and \"IEX\" turn up in random bytes (measured: 5 hits in 4,118\n // Ubuntu /usr binaries). Binaries carrying PowerShell are still caught by\n // the encoded-command, shortcut and ransomware rules.\n if (!isWindowsScriptContext(c)) return false;\n const t = allText(c);\n const download =/(?:DownloadString|DownloadData|DownloadFile|Invoke-WebRequest|\\biwr\\b|Invoke-RestMethod|\\birm\\b|Net\\.WebClient|Start-BitsTransfer)/i.test(t);\n const execute = /(?:\\bIEX\\b|Invoke-Expression|\\|\\s*iex\\b|Start-Process|\\.Invoke\\(\\))/i.test(t);\n if (!download || !execute) return false;\n const stealthy =\n /-w(?:indowstyle)?\\s+h(?:idden)?\\b/i.test(t) && /-ex(?:ecutionpolicy)?\\s+bypass/i.test(t);\n return stealthy\n ? { impact: 'malicious', severity: 'high', description: 'Downloads code and runs it in a hidden window with security checks bypassed. This is how most Windows malware gets installed.' }\n : true;\n },\n },\n {\n id: 'CrushAV.Script.WindowsDropper',\n name: 'Script that downloads and runs programs',\n severity: 'high',\n impact: 'malicious',\n description:\n 'A Windows script (JS/VBS/HTA) that fetches something from the internet and launches it. Email attachments like this are malware droppers; nothing legitimate is delivered this way.',\n test: (c) => {\n if (!WIN_SCRIPT_EXTS.has(c.ext)) return false;\n const t = c.text;\n return (\n /WScript\\.Shell|Shell\\.Application/i.test(t) &&\n /\\.(?:Run|Exec|ShellExecute)\\s*\\(/i.test(t) &&\n /(?:MSXML2\\.(?:Server)?XMLHTTP|WinHttp\\.WinHttpRequest|ADODB\\.Stream|Microsoft\\.XMLHTTP)/i.test(t)\n );\n },\n },\n {\n id: 'CrushAV.Shortcut.LolbinLauncher',\n name: 'Booby-trapped shortcut',\n severity: 'high',\n impact: 'malicious',\n description:\n 'A Windows shortcut (.lnk) that launches PowerShell, mshta or a similar tool to fetch something from the internet. Shortcuts like this arrive in zip and ISO attachments to install malware.',\n test: (c) =>\n c.kind === 'lnk' &&\n /(?:powershell|mshta|wscript|cscript|rundll32|regsvr32|certutil|bitsadmin|cmd(?:\\.exe)?\\s*\\/c)/i.test(allText(c)) &&\n /(?:https?:\\/\\/|\\\\\\\\[\\w.-]+@SSL|-enc(?:odedcommand)?\\s)/i.test(allText(c)),\n },\n {\n id: 'CrushAV.Office.MacroInDocx',\n name: 'Macros hidden in a regular Office file',\n severity: 'high',\n impact: 'suspicious',\n description:\n 'This document carries macro code even though its type (.docx/.xlsx/.pptx) is not supposed to have any. That mismatch is a common way to sneak malicious macros past filters.',\n test: (c) => c.kind === 'zip' && ['docx', 'xlsx', 'pptx'].includes(c.ext) && c.text.includes('vbaProject.bin'),\n },\n {\n id: 'CrushAV.Office.AutoMacro',\n name: 'Office macro that runs on open and starts programs',\n severity: 'high',\n impact: 'malicious',\n description:\n 'An Office document whose macro runs automatically when opened and starts other programs or downloads files. Never click \"Enable content\" on this one.',\n test: (c) => {\n if (c.kind !== 'ole') return false;\n const t = allText(c);\n if (!/_VBA_PROJECT|VBA\\b/i.test(t)) return false;\n const auto = /(?:Auto_?Open|Document_Open|Workbook_Open|AutoExec|Auto_Close|Document_Close)/i.test(t);\n const act = /(?:\\bShell\\b|WScript\\.Shell|CreateObject|URLDownloadToFile|powershell|MSXML2)/i.test(t);\n if (auto && act) return true;\n if (auto) return { impact: 'suspicious', severity: 'medium', name: 'Office macro that runs on open', description: 'This document has a macro that runs automatically when opened. Only enable macros for documents you were expecting from someone you trust.' };\n return false;\n },\n },\n {\n id: 'CrushAV.Office.MacroEnabled',\n name: 'Document contains macros',\n severity: 'info',\n impact: 'info',\n description: 'This is a macro-enabled Office document. That is normal for some spreadsheets, but only enable macros if you trust the sender.',\n test: (c) => c.kind === 'zip' && ['docm', 'xlsm', 'pptm', 'dotm', 'xltm'].includes(c.ext) && c.text.includes('vbaProject.bin'),\n },\n {\n id: 'CrushAV.PDF.Launch',\n name: 'PDF that tries to start a program',\n severity: 'high',\n impact: 'suspicious',\n description: 'This PDF contains a /Launch action, which asks your PDF reader to run a program. Normal documents do not need that.',\n test: (c) => {\n if (c.kind !== 'pdf' || !/\\/Launch\\b/.test(c.text)) return false;\n return /(?:cmd\\.exe|powershell|mshta|\\.exe\\b|\\.bat\\b|\\.vbs\\b)/i.test(c.text)\n ? { impact: 'malicious', description: 'This PDF tries to start a Windows program (cmd, PowerShell or an .exe) when opened. That is an attack; do not open it.' }\n : true;\n },\n },\n {\n id: 'CrushAV.PDF.AutoJavaScript',\n name: 'PDF runs JavaScript on open',\n severity: 'info',\n impact: 'info',\n description: 'This PDF runs JavaScript when opened. Fillable forms do this legitimately, so it is shown for information only.',\n test: (c) => c.kind === 'pdf' && /\\/(?:OpenAction|AA)\\b/.test(c.text) && /\\/(?:JavaScript|JS)\\b/.test(c.text),\n },\n {\n id: 'CrushAV.Shell.ReverseShell',\n name: 'Remote-control backdoor (reverse shell)',\n severity: 'critical',\n impact: 'malicious',\n description: 'This script connects out to another computer and hands it a command line on this one. That gives a stranger full control of the machine.',\n test: (c) => {\n if (!isScript(c)) return false;\n const t = c.text;\n return (\n /bash\\s+-i\\s*>&\\s*\\/dev\\/tcp\\//.test(t) ||\n /\\/dev\\/tcp\\/\\d{1,3}(?:\\.\\d{1,3}){3}\\/\\d{2,5}\\s*0>&1/.test(t) ||\n /\\bnc(?:at)?\\s+(?:-\\w+\\s+)*-e\\s+\\/bin\\/(?:ba)?sh\\b/.test(t) ||\n /socket\\.socket\\([\\s\\S]{0,300}?(?:os\\.dup2|pty\\.spawn)\\([\\s\\S]{0,300}?\\/bin\\/(?:ba)?sh/.test(t) ||\n /New-Object\\s+System\\.Net\\.Sockets\\.TCPClient\\([\\s\\S]{0,600}?(?:\\bIEX\\b|Invoke-Expression)/i.test(t)\n );\n },\n },\n {\n id: 'CrushAV.Web.Webshell',\n name: 'Website backdoor (webshell)',\n severity: 'critical',\n impact: 'malicious',\n description: 'Server code that runs whatever a visitor sends it. Attackers plant these on hacked websites to keep control. Remove it and change your hosting passwords.',\n test: (c) => {\n if (!SERVER_SCRIPT_EXTS.has(c.ext)) return false;\n const t = c.text;\n return (\n /\\b(?:eval|assert|system|passthru|shell_exec|exec|popen|proc_open|create_function)\\s*\\(\\s*@?(?:(?:base64_decode|gzinflate|str_rot13|gzuncompress|stripslashes)\\s{0,4}\\(\\s{0,4}@?){0,4}\\$_(?:POST|GET|REQUEST|COOKIE)\\b/i.test(t) ||\n /\\beval\\s*\\(\\s*gz(?:inflate|uncompress)\\s*\\(\\s*base64_decode\\s*\\(/i.test(t) ||\n /Runtime\\.getRuntime\\(\\)\\.exec\\(\\s*request\\.getParameter/.test(t) ||\n /Request\\.(?:Form|QueryString|Item)\\[[^\\]]+\\][\\s\\S]{0,120}?(?:Process\\.Start|eval\\s*\\()/i.test(t)\n );\n },\n },\n {\n id: 'CrushAV.PUA.CoinMiner',\n name: 'Cryptocurrency miner',\n severity: 'high',\n impact: 'suspicious',\n description: 'Software that uses your computer to mine cryptocurrency for someone. If you did not install a miner yourself, it is stealing your electricity and slowing you down.',\n test: (c) => {\n // Source in compiled languages and docs only *mentions* miners (scanner rules, tests, write-ups).\n if (NON_RUNNABLE_SOURCE_EXTS.has(c.ext)) return false;\n const t = c.text;\n return /stratum2?\\+(?:tcp|ssl|tls):\\/\\//i.test(t) && /(?:xmrig|donate-level|cryptonight|randomx|nicehash|cpu-max-threads-hint)/i.test(t);\n },\n },\n {\n id: 'CrushAV.Ransomware.ShadowCopyWipe',\n name: 'Deletes backups (ransomware behaviour)',\n severity: 'critical',\n impact: 'malicious',\n description: 'This program deletes Windows backup copies and disables recovery, which is what ransomware does right before encrypting files. Disconnect from the network and do not run it.',\n test: (c) => {\n if (!(EXECUTABLE_KINDS.has(c.kind) || isWindowsScriptContext(c))) return false;\n const t = allText(c);\n const hits = RANSOM_COMMANDS.filter((r) => r.test(t)).length;\n if (hits >= 2) return true;\n if (hits === 1) return { impact: 'suspicious', severity: 'high', description: 'This program deletes Windows backup copies. Ransomware does this before encrypting files; a few admin tools do it on purpose. If you do not know what this is, do not run it.' };\n return false;\n },\n },\n {\n id: 'CrushAV.Ransomware.Note',\n name: 'Ransom note',\n severity: 'critical',\n impact: 'malicious',\n description: 'This looks like a ransom note, which ransomware leaves behind after encrypting files. Disconnect this computer from the network, do not pay, and check nomoreransom.org for a free decryptor.',\n test: (c) =>\n c.size <= 64 * 1024 &&\n c.kind === 'text' &&\n NOTE_EXTS.has(c.ext) &&\n /(?:all\\s+)?your\\s+(?:important\\s+|personal\\s+)?(?:files|documents|data)\\s+(?:have\\s+been|are|were)\\s+(?:encrypted|locked)/i.test(c.text) &&\n /(?:bitcoin|\\bBTC\\b|monero|\\.onion\\b|tor\\s+browser|decrypt(?:or|ion)\\s+(?:key|tool|software|program))/i.test(c.text),\n },\n {\n id: 'CrushAV.HackTool.CredentialDumper',\n name: 'Password-stealing tool',\n severity: 'high',\n impact: 'malicious',\n description: 'A tool that pulls saved passwords out of Windows memory (Mimikatz or a copy of it). Attackers use it to spread through networks.',\n test: (c) => (c.kind === 'pe' || c.ext === 'ps1') && /sekurlsa::(?:logonpasswords|wdigest|msv)|lsadump::(?:sam|dcsync|secrets)/i.test(allText(c)),\n },\n {\n id: 'CrushAV.macOS.PasswordPhishStealer',\n name: 'Mac password-stealing script',\n severity: 'critical',\n impact: 'malicious',\n description: 'Shows a fake macOS password prompt and then reaches for your keychain, browser data or wallets. This is how Mac stealers like AMOS work. Do not enter your password; delete it.',\n test: (c) => {\n if (!(isScript(c) || c.kind === 'macho')) return false;\n const t = c.text;\n return /display\\s+dialog[\\s\\S]{0,400}?with\\s+hidden\\s+answer/i.test(t) &&\n /(?:Library\\/Keychains|login\\.keychain|Cookies|Login Data|wallet|find-generic-password|dscl\\s+\\.\\s+-?authonly|curl\\s)/i.test(t);\n },\n },\n {\n id: 'CrushAV.Web.ClickFix',\n name: 'Fake \"verify you are human\" trick (ClickFix)',\n severity: 'critical',\n impact: 'malicious',\n description: 'A web page that secretly copies a command to your clipboard and tells you to paste it into Run or Terminal to \"verify\" yourself. Pasting it installs malware. Never paste commands a website gives you.',\n test: (c) => {\n if (!(WEB_EXTS.has(c.ext) || c.ext === 'js')) return false;\n const t = c.text;\n return /(?:navigator\\.clipboard\\.writeText|document\\.execCommand\\(\\s*[\"']copy)/.test(t) &&\n /(?:powershell|mshta|cmd(?:\\.exe)?\\s*\\/c|curl\\s[^\\n]{0,200}\\|\\s*(?:ba|z)?sh|osascript)/i.test(t) &&\n /(?:Win(?:dows)?\\s*(?:key\\s*)?\\+\\s*R|Windows\\s+key|Ctrl\\s*\\+\\s*V|Cmd\\s*\\+\\s*Space|verify\\s+you\\s+are\\s+(?:a\\s+)?human|I(?:'|&#39;)?m\\s+not\\s+a\\s+robot)/i.test(t);\n },\n },\n {\n id: 'CrushAV.Web.HtmlSmuggling',\n name: 'Web page that builds a hidden download',\n severity: 'high',\n impact: 'suspicious',\n description: 'This HTML or SVG file carries a large hidden file inside itself and saves it to your computer when opened. Attackers use this to sneak malware past email filters.',\n test: (c) => {\n if (!WEB_EXTS.has(c.ext)) return false;\n const t = c.text;\n return /new\\s+Blob\\s*\\(/.test(t) &&\n /(?:\\.download\\s*=|msSaveOrOpenBlob|msSaveBlob)/.test(t) &&\n /(?:atob\\s*\\(|base64)/.test(t) &&\n /[A-Za-z0-9+/]{20000}/.test(t);\n },\n },\n {\n id: 'CrushAV.Web.SvgRedirect',\n name: 'Image file that runs code',\n severity: 'medium',\n impact: 'suspicious',\n description: 'This SVG \"image\" contains a script that redirects you or decodes hidden content. Phishing emails use SVG attachments like this to send you to fake login pages.',\n test: (c) => c.ext === 'svg' && /<script\\b/i.test(c.text) && /(?:location(?:\\.href)?\\s*=|location\\.replace\\(|window\\.open\\(|atob\\s*\\()/.test(c.text),\n },\n];\n\n/** Build a rule context. `bytes` may be a prefix of the file. */\nexport function buildContext(name: string, bytes: Uint8Array, kind: FileKind, size: number): RuleContext {\n let text = '';\n // Node's native Latin-1 decode is exact ISO-8859-1 and makes one flat\n // string; it was half the CPU of a disk scan. (TextDecoder('latin1') is\n // windows-1252 and would change 0x80-0x9f, so browsers keep the loop.)\n const NodeBuffer = (globalThis as { Buffer?: { from(b: ArrayBufferLike, o: number, l: number): { toString(e: string): string } } }).Buffer;\n if (NodeBuffer) {\n text = NodeBuffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('latin1');\n } else {\n // Latin-1 decode in chunks; String.fromCharCode on a huge array overflows the stack.\n for (let i = 0; i < bytes.length; i += 0x8000) {\n text += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000) as unknown as number[]);\n }\n }\n let wide = '';\n if (kind === 'pe' || kind === 'lnk' || kind === 'ole') {\n const parts: string[] = [];\n let run = '';\n for (let i = 0; i + 1 < bytes.length; i += 2) {\n const lo = bytes[i];\n if (bytes[i + 1] === 0 && lo >= 0x20 && lo < 0x7f) run += String.fromCharCode(lo);\n else {\n if (run.length >= 4) parts.push(run);\n run = '';\n }\n }\n if (run.length >= 4) parts.push(run);\n wide = parts.join('\\n');\n }\n return { name, ext: extOf(name), kind, size, bytes, text, wide };\n}\n\nexport function runRules(ctx: RuleContext, rules: AvRule[] = RULES): AvDetection[] {\n const out: AvDetection[] = [];\n for (const r of rules) {\n let hit: boolean | Partial<AvDetection>;\n try {\n hit = r.test(ctx);\n } catch {\n continue;\n }\n if (!hit) continue;\n const base: AvDetection = { engine: 'heuristic', id: r.id, name: r.name, severity: r.severity, impact: r.impact, description: r.description };\n out.push(hit === true ? base : { ...base, ...hit });\n }\n return out;\n}\n","/**\n * SHA-256 that works everywhere CrushAV runs.\n *\n * Browsers and Node have WebCrypto, which is fast and preferred. React Native\n * (Hermes) does not, so a small pure-JS implementation is the fallback. It is\n * also incremental, so callers that stream a file can hash it chunk by chunk.\n */\n\nconst K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\n/** Incremental SHA-256: `update()` any number of chunks, then `hex()`. */\nexport class Sha256 {\n private h = new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n ]);\n private block = new Uint8Array(64);\n private blockLen = 0;\n private total = 0;\n private w = new Uint32Array(64);\n\n update(data: Uint8Array): this {\n let i = 0;\n this.total += data.length;\n if (this.blockLen > 0) {\n const take = Math.min(64 - this.blockLen, data.length);\n this.block.set(data.subarray(0, take), this.blockLen);\n this.blockLen += take;\n i = take;\n if (this.blockLen === 64) {\n this.compress(this.block, 0);\n this.blockLen = 0;\n }\n }\n for (; i + 64 <= data.length; i += 64) this.compress(data, i);\n if (i < data.length) {\n this.block.set(data.subarray(i), 0);\n this.blockLen = data.length - i;\n }\n return this;\n }\n\n hex(): string {\n const bitLen = this.total * 8;\n const pad = new Uint8Array(((this.blockLen < 56 ? 56 : 120) - this.blockLen) + 8);\n pad[0] = 0x80;\n const hi = Math.floor(bitLen / 0x100000000);\n const lo = bitLen >>> 0;\n const n = pad.length;\n pad[n - 8] = hi >>> 24; pad[n - 7] = hi >>> 16; pad[n - 6] = hi >>> 8; pad[n - 5] = hi;\n pad[n - 4] = lo >>> 24; pad[n - 3] = lo >>> 16; pad[n - 2] = lo >>> 8; pad[n - 1] = lo;\n this.total -= pad.length; // padding is not message length\n this.update(pad);\n let out = '';\n for (const v of this.h) out += v.toString(16).padStart(8, '0');\n return out;\n }\n\n private compress(d: Uint8Array, o: number): void {\n const w = this.w;\n for (let t = 0; t < 16; t++) {\n const j = o + t * 4;\n w[t] = (d[j] << 24) | (d[j + 1] << 16) | (d[j + 2] << 8) | d[j + 3];\n }\n for (let t = 16; t < 64; t++) {\n const a = w[t - 15], b = w[t - 2];\n const s0 = ((a >>> 7) | (a << 25)) ^ ((a >>> 18) | (a << 14)) ^ (a >>> 3);\n const s1 = ((b >>> 17) | (b << 15)) ^ ((b >>> 19) | (b << 13)) ^ (b >>> 10);\n w[t] = (w[t - 16] + s0 + w[t - 7] + s1) | 0;\n }\n let [a, b, c, dd, e, f, g, h] = this.h;\n for (let t = 0; t < 64; t++) {\n const S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));\n const ch = (e & f) ^ (~e & g);\n const t1 = (h + S1 + ch + K[t] + w[t]) | 0;\n const S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));\n const maj = (a & b) ^ (a & c) ^ (b & c);\n const t2 = (S0 + maj) | 0;\n h = g; g = f; f = e; e = (dd + t1) | 0; dd = c; c = b; b = a; a = (t1 + t2) | 0;\n }\n const H = this.h;\n H[0] += a; H[1] += b; H[2] += c; H[3] += dd; H[4] += e; H[5] += f; H[6] += g; H[7] += h;\n }\n}\n\n/** Hash bytes, using WebCrypto when the runtime has it. */\nexport async function sha256Hex(bytes: Uint8Array): Promise<string> {\n const subtle = (globalThis as { crypto?: { subtle?: SubtleCrypto } }).crypto?.subtle;\n if (subtle) {\n try {\n const buf = await subtle.digest('SHA-256', bytes as unknown as BufferSource);\n return Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, '0')).join('');\n } catch {\n /* fall through to JS */\n }\n }\n return new Sha256().update(bytes).hex();\n}\n\nexport const SHA256_RE = /^[0-9a-f]{64}$/;\n","import { sniffKind } from './magic';\nimport { buildContext, runRules, RULES, type AvRule } from './rules';\nimport { sha256Hex, SHA256_RE } from './sha256';\nimport type { AvDetection, AvFileResult, AvVerdict, HashReputation } from './types';\n\n/** Heuristics read at most this much of a file. Hashing always covers all of it. */\nexport const DEFAULT_HEURISTIC_BYTES = 16 * 1024 * 1024;\n\n/**\n * Exact-hash signatures: lower-case SHA-256 to malware name. Built-in entries\n * are test files only; real coverage comes from ClamAV and hash reputation,\n * and users can load their own list with {@link SignatureSet.load}.\n */\nexport class SignatureSet {\n private map = new Map<string, string>();\n\n constructor(entries: Iterable<[string, string]> = BUILTIN_SIGNATURES) {\n for (const [h, n] of entries) this.add(h, n);\n }\n\n add(sha256: string, name: string): void {\n const h = sha256.trim().toLowerCase();\n if (SHA256_RE.test(h)) this.map.set(h, name || 'Malware');\n }\n\n /** Load `sha256 [name]` lines; `#` starts a comment. Returns how many were added. */\n load(text: string): number {\n let n = 0;\n for (const raw of text.split(/\\r?\\n/)) {\n const line = raw.replace(/#.*/, '').trim();\n if (!line) continue;\n const [h, ...rest] = line.split(/[\\s,;]+/);\n if (SHA256_RE.test(h.toLowerCase())) {\n this.add(h, rest.join(' '));\n n++;\n }\n }\n return n;\n }\n\n get(sha256: string): string | undefined {\n return this.map.get(sha256.toLowerCase());\n }\n\n /** Every `[sha256, name]` pair, so a set can be rebuilt in a worker thread. */\n entries(): Array<[string, string]> {\n return [...this.map];\n }\n\n get size(): number {\n return this.map.size;\n }\n}\n\nexport const BUILTIN_SIGNATURES: Array<[string, string]> = [\n ['275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f', 'EICAR-Test-File'],\n];\n\nexport interface ScanBytesInput {\n /** Path or display name; only used for extension checks and display. */\n name: string;\n /** The file, or its first N bytes when it is large. */\n bytes: Uint8Array;\n /** Real size when `bytes` is a prefix. Defaults to bytes.length. */\n size?: number;\n /** Precomputed SHA-256 of the whole file (when bytes is a prefix, pass it). */\n sha256?: string | null;\n}\n\nexport interface ScanBytesOptions {\n rules?: AvRule[];\n signatures?: SignatureSet;\n}\n\nconst IMPACT_RANK = { info: 0, suspicious: 1, malicious: 2 } as const;\n\nexport function verdictOf(detections: AvDetection[]): AvVerdict {\n let worst = 0;\n for (const d of detections) worst = Math.max(worst, IMPACT_RANK[d.impact]);\n return worst === 2 ? 'malicious' : worst === 1 ? 'suspicious' : 'clean';\n}\n\n/** Scan one in-memory file with signatures and heuristics. Pure; no I/O. */\nexport async function scanBytes(input: ScanBytesInput, opts: ScanBytesOptions = {}): Promise<AvFileResult> {\n const size = input.size ?? input.bytes.length;\n const complete = input.bytes.length >= size;\n const sha256 = input.sha256 ?? (complete ? await sha256Hex(input.bytes) : null);\n const kind = sniffKind(input.bytes);\n const detections: AvDetection[] = [];\n\n const sigs = opts.signatures ?? DEFAULT_SIGNATURES;\n const known = sha256 ? sigs.get(sha256) : undefined;\n if (known) {\n detections.push({\n engine: 'signature',\n id: `CrushAV.Signature.${known.replace(/[^\\w.-]+/g, '_')}`,\n name: known,\n severity: known.startsWith('EICAR') ? 'low' : 'critical',\n impact: 'malicious',\n description: known.startsWith('EICAR')\n ? 'The harmless standard antivirus test file. Seeing this means the scanner works.'\n : `This exact file is known malware (${known}). Quarantine or delete it.`,\n });\n }\n\n const ctx = buildContext(input.name, input.bytes, kind, size);\n for (const d of runRules(ctx, opts.rules ?? RULES)) {\n // The signature already said EICAR; don't list it twice.\n if (known && d.id === 'CrushAV.Test.EICAR') continue;\n detections.push(d);\n }\n\n return {\n path: input.name,\n size,\n sha256,\n kind,\n verdict: verdictOf(detections),\n detections,\n note: complete ? undefined : `heuristics read the first ${Math.round(input.bytes.length / 1048576)} MB`,\n };\n}\n\nconst DEFAULT_SIGNATURES = new SignatureSet();\n\n/** Trust score at or above which CIRCL treats a hash as a known-good file. */\nexport const TRUSTED_SCORE = 50;\n\n/**\n * Fold hash reputation into a result.\n *\n * Known-malicious adds a detection. Known-good (in NSRL or a major distro's\n * package set) downgrades merely *suspicious* heuristics to info, because a\n * file shipped by Microsoft, Apple or Debian is not a dropper because it\n * contains the word \"powershell\". Malicious heuristics are left alone: a known\n * good program renamed to `.pdf` is still a trap.\n */\nexport function applyReputation(result: AvFileResult, rep: HashReputation | undefined): AvFileResult {\n if (!rep) return result;\n const detections = [...result.detections];\n if (rep.knownMalicious) {\n detections.push({\n engine: 'reputation',\n id: `CrushAV.Reputation.${(rep.malwareName ?? 'KnownMalware').replace(/[^\\w.-]+/g, '_')}`,\n name: rep.malwareName ?? 'Known malware',\n severity: 'critical',\n impact: 'malicious',\n description: `This exact file is listed as malware by ${rep.knownMalicious}. Quarantine or delete it.`,\n });\n } else if ((rep.trust ?? 0) >= TRUSTED_SCORE) {\n for (let i = 0; i < detections.length; i++) {\n const d = detections[i];\n if (d.engine === 'heuristic' && d.impact === 'suspicious') {\n detections[i] = { ...d, impact: 'info', description: `${d.description} (Downgraded: this exact file is a known, published file from a trusted software source.)` };\n }\n }\n }\n return { ...result, detections, verdict: verdictOf(detections) };\n}\n","import { parentPort, workerData } from 'node:worker_threads';\nimport { SignatureSet } from '../engine';\nimport { scanFileSync, type FileOutcome } from './scan-file';\n\n/** What {@link scanPaths} hands each worker at start. */\nexport interface ScanWorkerInit {\n cap: number;\n maxFile: number;\n /** Full signature list, built-ins included; omitted = the built-in set. */\n signatures?: Array<[string, string]>;\n}\n\nexport interface ScanWorkerRequest {\n id: number;\n files: string[];\n}\n\nexport interface ScanWorkerReply {\n id: number;\n out: FileOutcome[];\n}\n\n/**\n * Body of a CrushAV scan worker thread. A host bundles a file that calls this\n * and passes its path to `scanPaths({ workerScript })`.\n */\nexport function runScanWorker(): void {\n const port = parentPort;\n if (!port) throw new Error('runScanWorker must run inside a worker thread');\n const init = workerData as ScanWorkerInit;\n const opts = {\n cap: init.cap,\n maxFile: init.maxFile,\n signatures: init.signatures ? new SignatureSet(init.signatures) : undefined,\n };\n // Batches run one after another: the scanner reuses its read buffers.\n let chain: Promise<void> = Promise.resolve();\n port.on('message', (msg: ScanWorkerRequest) => {\n chain = chain.then(async () => {\n const out: FileOutcome[] = [];\n for (const f of msg.files) out.push(await scanFileSync(f, opts));\n port.postMessage({ id: msg.id, out } satisfies ScanWorkerReply);\n });\n });\n}\n","import { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdtemp, rm, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { delimiter, join } from 'node:path';\nimport type { AvDetection } from '../types';\n\n/**\n * ClamAV bridge. ClamAV (GPL, Cisco Talos) carries millions of signatures and\n * runs on Windows, macOS and Linux; CrushAV drives it as a separate program\n * when it is installed, so its signature database backs every desktop scan.\n */\n\nexport interface ClamInfo {\n available: boolean;\n /** Absolute path of the binary used. */\n binary: string | null;\n /** `clamdscan` talks to a running daemon (fast); `clamscan` loads the DB itself. */\n mode: 'clamdscan' | 'clamscan' | null;\n /** e.g. \"ClamAV 1.4.2/27447/Sat Nov 1 08:42:01 2026\" */\n version: string | null;\n /** Signature database date, when the version line has one. */\n signaturesDate: string | null;\n}\n\nconst WINDOWS_DIRS = ['C:\\\\Program Files\\\\ClamAV', 'C:\\\\Program Files (x86)\\\\ClamAV', 'C:\\\\ProgramData\\\\chocolatey\\\\bin'];\n\nexport function findBinary(name: string, env: NodeJS.ProcessEnv = process.env, platform = process.platform): string | null {\n const exe = platform === 'win32' ? `${name}.exe` : name;\n const dirs = (env.PATH ?? env.Path ?? '').split(delimiter).filter(Boolean);\n if (platform === 'win32') dirs.push(...WINDOWS_DIRS);\n if (platform === 'darwin') dirs.push('/opt/homebrew/bin', '/usr/local/bin');\n for (const d of dirs) {\n const p = join(d, exe);\n if (existsSync(p)) return p;\n }\n return null;\n}\n\nfunction run(bin: string, args: string[], timeoutMs: number, signal?: AbortSignal): Promise<{ code: number | null; stdout: string; stderr: string }> {\n return new Promise((resolve) => {\n const child = spawn(bin, args, { windowsHide: true, signal });\n let stdout = '';\n let stderr = '';\n child.stdout.on('data', (d) => (stdout += d));\n child.stderr.on('data', (d) => (stderr += d));\n const timer = setTimeout(() => child.kill(), timeoutMs);\n child.on('error', (e) => {\n clearTimeout(timer);\n resolve({ code: null, stdout, stderr: stderr || String(e) });\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n resolve({ code, stdout, stderr });\n });\n });\n}\n\nexport async function detectClamAV(): Promise<ClamInfo> {\n const none: ClamInfo = { available: false, binary: null, mode: null, version: null, signaturesDate: null };\n const clamscan = findBinary('clamscan');\n const clamdscan = findBinary('clamdscan');\n let mode: ClamInfo['mode'] = null;\n let binary: string | null = null;\n if (clamdscan) {\n // clamdscan exists without a daemon on many installs; --ping proves one is up.\n const ping = await run(clamdscan, ['--ping', '1'], 5000);\n if (ping.code === 0) {\n mode = 'clamdscan';\n binary = clamdscan;\n }\n }\n if (!binary && clamscan) {\n mode = 'clamscan';\n binary = clamscan;\n }\n if (!binary) return none;\n const v = await run(binary, ['--version'], 15000);\n const version = v.stdout.trim().split('\\n')[0] || null;\n const parts = version?.split('/') ?? [];\n return { available: v.code === 0, binary, mode, version, signaturesDate: parts.length >= 3 ? parts.slice(2).join('/').trim() : null };\n}\n\n/** Parse `path: Signature.Name FOUND` lines. Paths may contain \": \". */\nexport function parseClamOutput(stdout: string): Map<string, string[]> {\n const out = new Map<string, string[]>();\n for (const line of stdout.split(/\\r?\\n/)) {\n const m = /^(.*): (\\S+) FOUND$/.exec(line.trim());\n if (!m) continue;\n const list = out.get(m[1]) ?? [];\n list.push(m[2]);\n out.set(m[1], list);\n }\n return out;\n}\n\nexport function clamDetection(sig: string): AvDetection {\n const pua = /^PUA\\./i.test(sig);\n const heuristic = /^Heuristics\\./i.test(sig);\n return {\n engine: 'clamav',\n id: `ClamAV.${sig}`,\n name: sig,\n severity: pua ? 'medium' : heuristic ? 'medium' : /EICAR/i.test(sig) ? 'low' : 'critical',\n impact: pua || heuristic ? 'suspicious' : 'malicious',\n description: pua\n ? 'ClamAV flags this as a potentially unwanted program (adware, bundleware or a tool that can be misused).'\n : heuristic\n ? 'ClamAV heuristics flag this file as likely malicious, without an exact signature match.'\n : /EICAR/i.test(sig)\n ? 'The harmless antivirus test file, recognised by ClamAV too.'\n : `ClamAV recognises this file as malware (${sig}). Quarantine or delete it.`,\n };\n}\n\n/**\n * Scan many files in one ClamAV run (loading the database once).\n * Returns detections keyed by path, or an error string.\n */\nexport async function clamScanFiles(\n info: ClamInfo,\n files: string[],\n opts: { timeoutMs?: number; signal?: AbortSignal } = {},\n): Promise<{ detections: Map<string, AvDetection[]>; error: string | null }> {\n const detections = new Map<string, AvDetection[]>();\n if (!info.available || !info.binary || files.length === 0) return { detections, error: null };\n const dir = await mkdtemp(join(tmpdir(), 'crushav-'));\n const list = join(dir, 'files.txt');\n try {\n // Trailing newline: line readers that stop at EOF would otherwise drop the last file.\n await writeFile(list, `${files.join('\\n')}\\n`);\n const args = ['--no-summary', '--infected', '--stdout', `--file-list=${list}`];\n if (info.mode === 'clamdscan') args.push('--fdpass', '--multiscan');\n const r = await run(info.binary, args, opts.timeoutMs ?? 60 * 60 * 1000, opts.signal);\n // Exit codes: 0 clean, 1 found, 2 errors (some files unreadable is still 2).\n for (const [path, sigs] of parseClamOutput(r.stdout)) detections.set(path, sigs.map(clamDetection));\n const error = r.code === null || (r.code === 2 && detections.size === 0 && !r.stdout.trim()) ? (r.stderr.trim().split('\\n').pop() ?? 'clamav failed') : null;\n return { detections, error };\n } finally {\n await rm(dir, { recursive: true, force: true });\n }\n}\n\n/** How to install ClamAV on this platform, for messages. */\nexport function clamInstallHint(platform = process.platform): string {\n switch (platform) {\n case 'win32':\n return 'winget install Cisco.ClamAV (then run \"freshclam\" once)';\n case 'darwin':\n return 'brew install clamav && cp $(brew --prefix)/etc/clamav/freshclam.conf.sample $(brew --prefix)/etc/clamav/freshclam.conf && sed -i \"\" \"/^Example/d\" $(brew --prefix)/etc/clamav/freshclam.conf && freshclam';\n default:\n return 'sudo apt install clamav clamav-daemon (Fedora: sudo dnf install clamav clamd; Arch: sudo pacman -S clamav)';\n }\n}\n","import { createHash, randomBytes } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readdir, readFile, rm, unlink, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport type { AvDetection } from '../types';\n\n/**\n * Quarantine moves a file somewhere it cannot run. The bytes are XORed with a\n * fixed key so the stored copy is not a working executable, does not match\n * signatures (other scanners will not keep re-flagging it), and can be put\n * back exactly as it was.\n */\n\nconst KEY = 0xa5;\n\nexport interface QuarantineEntry {\n id: string;\n originalPath: string;\n sha256: string;\n size: number;\n detections: Array<Pick<AvDetection, 'id' | 'name' | 'engine' | 'impact'>>;\n quarantinedAt: string;\n}\n\nexport function quarantineDir(home = homedir()): string {\n return process.env.CRUSHAV_QUARANTINE_DIR ?? join(home, '.threatcrush', 'quarantine');\n}\n\nfunction xor(buf: Buffer): Buffer {\n const out = Buffer.allocUnsafe(buf.length);\n for (let i = 0; i < buf.length; i++) out[i] = buf[i] ^ KEY;\n return out;\n}\n\nexport async function quarantineFile(path: string, detections: AvDetection[] = [], dir = quarantineDir()): Promise<QuarantineEntry> {\n const data = await readFile(path);\n const sha256 = createHash('sha256').update(data).digest('hex');\n const id = `${new Date().toISOString().replace(/[-:T.Z]/g, '').slice(0, 14)}-${randomBytes(4).toString('hex')}`;\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const entry: QuarantineEntry = {\n id,\n originalPath: path,\n sha256,\n size: data.length,\n detections: detections.map(({ id: did, name, engine, impact }) => ({ id: did, name, engine, impact })),\n quarantinedAt: new Date().toISOString(),\n };\n const bin = join(dir, `${id}.bin`);\n await writeFile(bin, xor(data), { mode: 0o600 });\n // Verify the stored copy before deleting the original, so a full disk never loses the file.\n const check = xor(await readFile(bin));\n if (createHash('sha256').update(check).digest('hex') !== sha256) {\n await rm(bin, { force: true });\n throw new Error('quarantine copy did not verify; original left in place');\n }\n await writeFile(join(dir, `${id}.json`), JSON.stringify(entry, null, 2), { mode: 0o600 });\n await unlink(path);\n return entry;\n}\n\nexport async function listQuarantine(dir = quarantineDir()): Promise<QuarantineEntry[]> {\n if (!existsSync(dir)) return [];\n const out: QuarantineEntry[] = [];\n for (const f of await readdir(dir)) {\n if (!f.endsWith('.json')) continue;\n try {\n out.push(JSON.parse(await readFile(join(dir, f), 'utf8')) as QuarantineEntry);\n } catch {\n /* ignore a damaged record */\n }\n }\n return out.sort((a, b) => b.quarantinedAt.localeCompare(a.quarantinedAt));\n}\n\nasync function entryOf(id: string, dir: string): Promise<QuarantineEntry> {\n if (!/^[\\w-]+$/.test(id)) throw new Error(`bad quarantine id: ${id}`);\n const p = join(dir, `${id}.json`);\n if (!existsSync(p)) throw new Error(`no quarantined file with id ${id}`);\n return JSON.parse(await readFile(p, 'utf8')) as QuarantineEntry;\n}\n\n/** Put a file back. Refuses to overwrite anything already at the destination. */\nexport async function restoreQuarantined(id: string, to?: string, dir = quarantineDir()): Promise<string> {\n const entry = await entryOf(id, dir);\n const dest = to ?? entry.originalPath;\n const data = xor(await readFile(join(dir, `${id}.bin`)));\n await mkdir(dirname(dest), { recursive: true });\n // 'wx' creates exclusively: the existence check and the write are one atomic step.\n try {\n await writeFile(dest, data, { flag: 'wx' });\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === 'EEXIST') throw new Error(`${dest} already exists; pass another destination`);\n throw e;\n }\n await rm(join(dir, `${id}.bin`), { force: true });\n await rm(join(dir, `${id}.json`), { force: true });\n return dest;\n}\n\nexport async function deleteQuarantined(id: string, dir = quarantineDir()): Promise<void> {\n await entryOf(id, dir);\n await rm(join(dir, `${id}.bin`), { force: true });\n await rm(join(dir, `${id}.json`), { force: true });\n}\n","import { createHash } from 'node:crypto';\nimport { createReadStream, readFileSync, existsSync } from 'node:fs';\nimport { lstat } from 'node:fs/promises';\nimport { availableParallelism } from 'node:os';\nimport { Worker } from 'node:worker_threads';\nimport { applyReputation, DEFAULT_HEURISTIC_BYTES, scanBytes, SignatureSet } from '../engine';\nimport { lookupHashes } from '../reputation';\nimport { summarize } from '../summary';\nimport type { AvEngine, AvFileResult, AvSummary, HashReputation } from '../types';\nimport { verdictOf } from '../engine';\nimport { clamScanFiles, detectClamAV, type ClamInfo } from './clamav';\nimport type { ScanTarget } from './locations';\nimport type { FileOutcome } from './scan-file';\nimport type { ScanWorkerInit, ScanWorkerReply } from './scan-worker';\nimport { walkFiles } from './walk';\n\nexport interface ScanPathsOptions {\n /** Bytes of each file the heuristics read. */\n heuristicBytes?: number;\n /** Files above this are listed as skipped (not hashed). Default 1 GiB. */\n maxFileBytes?: number;\n /** 'auto' uses ClamAV when installed; 'off' never; 'require' errors without it. */\n clamav?: 'auto' | 'off' | 'require';\n /** Send SHA-256 hashes of risky files to the reputation API. */\n reputation?: boolean;\n lookupEndpoint?: string;\n userAgent?: string;\n signatures?: SignatureSet;\n /** Extra `sha256 name` signature file. */\n signatureFile?: string;\n /**\n * With `workerScript`: worker threads (default: one per CPU). Without: files\n * read at once on the calling thread (default 4).\n */\n concurrency?: number;\n /**\n * A file that calls `runScanWorker()` (bundled by the host). When set, files\n * are read, hashed and checked in parallel worker threads with blocking I/O,\n * which is many times faster on big trees. Without it everything runs on the\n * calling thread with async I/O (safe for an Electron main process).\n */\n workerScript?: string | URL;\n /**\n * Keep every clean result in `report.results` (default true). Set false for\n * big scans: clean files are only counted, so memory stays flat.\n */\n keepClean?: boolean;\n signal?: AbortSignal;\n onProgress?: (e: ScanProgress) => void;\n}\n\nexport type ScanProgress =\n | { type: 'file'; path: string; scanned: number; result: AvFileResult }\n | { type: 'skip'; path: string; reason: string }\n | { type: 'phase'; phase: 'walking' | 'reputation' | 'clamav' | 'done'; detail?: string };\n\nexport interface ScanReport {\n summary: AvSummary;\n results: AvFileResult[];\n clamav: ClamInfo | null;\n clamavError: string | null;\n skipped: Array<{ path: string; reason: string }>;\n}\n\n/** File kinds worth a reputation lookup: things that run, or carry code. */\nconst LOOKUP_KINDS = new Set(['pe', 'elf', 'macho', 'script', 'lnk', 'ole', 'zip', 'pdf', 'dex', 'rtf']);\nconst MAX_LOOKUPS = 5000;\n\n/** Stream a file once: full SHA-256 plus the first `cap` bytes for heuristics. */\nexport async function readForScan(path: string, size: number, cap: number): Promise<{ head: Uint8Array; sha256: string }> {\n const hash = createHash('sha256');\n const head = Buffer.allocUnsafe(Math.min(size, cap));\n let filled = 0;\n await new Promise<void>((resolve, reject) => {\n const s = createReadStream(path, { highWaterMark: 1 << 20 });\n s.on('data', (chunk) => {\n const c = chunk as Buffer;\n hash.update(c);\n if (filled < head.length) {\n const n = Math.min(head.length - filled, c.length);\n c.copy(head, filled, 0, n);\n filled += n;\n }\n });\n s.on('error', reject);\n s.on('end', () => resolve());\n });\n return { head: head.subarray(0, filled), sha256: hash.digest('hex') };\n}\n\n/** Scan files and folders. Never throws for a single bad file. */\nexport async function scanPaths(targets: ScanTarget[], opts: ScanPathsOptions = {}): Promise<ScanReport> {\n const started = new Date();\n const cap = opts.heuristicBytes ?? DEFAULT_HEURISTIC_BYTES;\n const maxFile = opts.maxFileBytes ?? 1024 ** 3;\n const keepClean = opts.keepClean !== false;\n const skipped: Array<{ path: string; reason: string }> = [];\n const skip = (path: string, reason: string) => {\n skipped.push({ path, reason });\n opts.onProgress?.({ type: 'skip', path, reason });\n };\n\n let signatures = opts.signatures;\n if (opts.signatureFile && existsSync(opts.signatureFile)) {\n signatures = signatures ?? new SignatureSet();\n signatures.load(readFileSync(opts.signatureFile, 'utf8'));\n }\n\n const clamav = opts.clamav === 'off' ? null : await detectClamAV();\n if (opts.clamav === 'require' && !clamav?.available) throw new Error('ClamAV is not installed (or clamscan is not on PATH)');\n // ClamAV re-reads every readable file, so it needs every path, clean or not.\n const clamFiles: string[] | null = clamav?.available ? [] : null;\n\n opts.onProgress?.({ type: 'phase', phase: 'walking' });\n const results: AvFileResult[] = [];\n let scanned = 0;\n let droppedClean = 0;\n let cleanLookupsKept = 0;\n\n const record = (r: AvFileResult) => {\n scanned++;\n if (clamFiles && r.verdict !== 'error') clamFiles.push(r.path);\n const keep =\n keepClean ||\n r.verdict !== 'clean' ||\n r.detections.length > 0 ||\n (r.sha256 !== null && LOOKUP_KINDS.has(r.kind) && cleanLookupsKept++ < MAX_LOOKUPS);\n if (keep) results.push(r);\n else droppedClean++;\n opts.onProgress?.({ type: 'file', path: r.path, scanned, result: r });\n };\n const take = (o: FileOutcome) => {\n if (o.kind === 'result') record(o.result);\n else if (o.kind === 'skip') skip(o.path, o.reason);\n };\n const walk = () => walkFiles(targets, { signal: opts.signal, onSkip: skip });\n\n if (opts.workerScript) {\n await scanInWorkers(walk(), {\n script: opts.workerScript,\n workers: Math.max(1, opts.concurrency ?? availableParallelism()),\n init: { cap, maxFile, signatures: signatures?.entries() },\n signal: opts.signal,\n take,\n });\n } else {\n const queue = new Set<Promise<void>>();\n const limit = Math.max(1, opts.concurrency ?? 4);\n const scanOne = async (path: string) => {\n let size: number;\n try {\n const st = await lstat(path);\n if (!st.isFile() || st.size === 0) return;\n size = st.size;\n } catch {\n return;\n }\n if (size > maxFile) return skip(path, `larger than ${Math.round(maxFile / 1048576)} MB`);\n try {\n const { head, sha256 } = await readForScan(path, size, cap);\n record(await scanBytes({ name: path, bytes: head, size, sha256 }, { signatures }));\n } catch (e) {\n const code = (e as NodeJS.ErrnoException).code ?? (e as Error).message;\n record({ path, size, sha256: null, kind: 'unknown', verdict: 'error', detections: [], note: code });\n }\n };\n for await (const path of walk()) {\n if (opts.signal?.aborted) break;\n const p: Promise<void> = scanOne(path).finally(() => queue.delete(p));\n queue.add(p);\n if (queue.size >= limit) await Promise.race(queue);\n }\n await Promise.all(queue);\n }\n\n const engines: AvEngine[] = ['signature', 'heuristic'];\n\n if (opts.reputation !== false && !opts.signal?.aborted) {\n const wanted = results\n .filter((r) => r.sha256 && (LOOKUP_KINDS.has(r.kind) || r.detections.length > 0))\n .slice(0, MAX_LOOKUPS);\n if (wanted.length) {\n opts.onProgress?.({ type: 'phase', phase: 'reputation', detail: `${wanted.length} hashes` });\n const reps = await lookupHashes(wanted.map((r) => r.sha256!), { endpoint: opts.lookupEndpoint, userAgent: opts.userAgent });\n if (reps.size || wanted.length) engines.push('reputation');\n applyAll(results, reps);\n }\n }\n\n let clamavError: string | null = null;\n if (clamav?.available && clamFiles && !opts.signal?.aborted) {\n opts.onProgress?.({ type: 'phase', phase: 'clamav', detail: `${clamFiles.length} files via ${clamav.mode}` });\n const { detections, error } = await clamScanFiles(clamav, clamFiles, { signal: opts.signal });\n clamavError = error;\n if (!error) engines.push('clamav');\n const byPath = new Map(results.map((r) => [r.path, r]));\n for (const [path, extra] of detections) {\n let r = byPath.get(path);\n if (!r) {\n // A clean file that was only counted: bring it back as a result.\n r = { path, size: 0, sha256: null, kind: 'unknown', verdict: 'clean', detections: [] };\n results.push(r);\n droppedClean--;\n }\n r.detections.push(...extra);\n r.verdict = verdictOf(r.detections);\n }\n }\n\n opts.onProgress?.({ type: 'phase', phase: 'done' });\n const summary = summarize(results, engines, started, skipped.length);\n summary.scanned += droppedClean;\n summary.clean += droppedClean;\n return { summary, results, clamav, clamavError, skipped };\n}\n\n/** Feed walked paths to a pool of scan workers in batches. */\nasync function scanInWorkers(\n paths: AsyncIterable<string>,\n o: { script: string | URL; workers: number; init: ScanWorkerInit; signal?: AbortSignal; take: (x: FileOutcome) => void },\n): Promise<void> {\n const BATCH = 64;\n const PER_WORKER = 2;\n let failure: Error | null = null;\n const waiting = new Map<number, { resolve: (out: FileOutcome[]) => void; reject: (e: Error) => void }>();\n const fail = (e: Error) => {\n failure ??= e;\n for (const w of waiting.values()) w.reject(e);\n waiting.clear();\n };\n const slots = Array.from({ length: o.workers }, () => {\n const worker = new Worker(o.script, { workerData: o.init });\n worker.on('message', (m: ScanWorkerReply) => {\n const w = waiting.get(m.id);\n waiting.delete(m.id);\n w?.resolve(m.out);\n });\n worker.on('error', fail);\n worker.on('exit', (code) => {\n if (code !== 0) fail(new Error(`scan worker exited with code ${code}`));\n });\n return { worker, busy: 0 };\n });\n\n let nextId = 0;\n const inflight = new Set<Promise<void>>();\n const send = (files: string[]) => {\n const slot = slots.reduce((a, b) => (b.busy < a.busy ? b : a));\n slot.busy++;\n const id = nextId++;\n const p: Promise<void> = new Promise<FileOutcome[]>((resolve, reject) => waiting.set(id, { resolve, reject }))\n .then((out) => {\n for (const x of out) o.take(x);\n })\n .finally(() => {\n slot.busy--;\n inflight.delete(p);\n });\n inflight.add(p);\n slot.worker.postMessage({ id, files });\n };\n\n try {\n let batch: string[] = [];\n for await (const path of paths) {\n if (failure) throw failure;\n if (o.signal?.aborted) break;\n batch.push(path);\n if (batch.length < BATCH) continue;\n send(batch);\n batch = [];\n while (inflight.size >= o.workers * PER_WORKER) await Promise.race(inflight);\n }\n if (batch.length && !o.signal?.aborted) send(batch);\n await Promise.all(inflight);\n if (failure) throw failure;\n } finally {\n // Swallow rejections from batches we are abandoning on the way out.\n for (const p of inflight) p.catch(() => {});\n slots.forEach((s) => s.worker.removeAllListeners('exit'));\n await Promise.all(slots.map((s) => s.worker.terminate()));\n }\n}\n\nfunction applyAll(results: AvFileResult[], reps: Map<string, HashReputation>): void {\n for (let i = 0; i < results.length; i++) {\n const r = results[i];\n if (r.sha256 && reps.has(r.sha256)) results[i] = applyReputation(r, reps.get(r.sha256));\n }\n}\n","import { watch, type FSWatcher } from 'node:fs';\nimport { lstat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { applyReputation, scanBytes, type SignatureSet } from '../engine';\nimport { lookupHashes } from '../reputation';\nimport type { AvFileResult } from '../types';\nimport type { ScanTarget } from './locations';\nimport { readForScan } from './scan';\nimport { SKIP_DIR_NAMES } from './walk';\n\nexport interface WatchOptions {\n /** Wait this long after the last change before scanning (downloads arrive in chunks). */\n settleMs?: number;\n heuristicBytes?: number;\n maxFileBytes?: number;\n reputation?: boolean;\n lookupEndpoint?: string;\n signatures?: SignatureSet;\n onResult: (r: AvFileResult) => void;\n onError?: (path: string, err: Error) => void;\n}\n\n/** Partial-download names browsers use while a file is still arriving. */\nconst IN_PROGRESS = /\\.(?:crdownload|part|partial|download|tmp)$/i;\n\n/**\n * Real-time protection: scan files as they appear or change under the\n * targets. Returns a stop function. Uses the OS file-change API (recursive\n * watching works on Windows, macOS and, from Node 20, Linux).\n */\nexport function watchTargets(targets: ScanTarget[], opts: WatchOptions): () => void {\n const settle = opts.settleMs ?? 1500;\n const timers = new Map<string, ReturnType<typeof setTimeout>>();\n const lastScanned = new Map<string, string>();\n const watchers: FSWatcher[] = [];\n\n const scan = async (path: string) => {\n timers.delete(path);\n try {\n const st = await lstat(path);\n if (!st.isFile() || st.size === 0 || st.size > (opts.maxFileBytes ?? 1024 ** 3)) return;\n const key = `${st.size}:${st.mtimeMs}`;\n if (lastScanned.get(path) === key) return;\n lastScanned.set(path, key);\n if (lastScanned.size > 10_000) lastScanned.delete(lastScanned.keys().next().value as string);\n const { head, sha256 } = await readForScan(path, st.size, opts.heuristicBytes ?? 16 * 1024 * 1024);\n let r = await scanBytes({ name: path, bytes: head, size: st.size, sha256 }, { signatures: opts.signatures });\n if (opts.reputation !== false) {\n const reps = await lookupHashes([sha256], { endpoint: opts.lookupEndpoint, timeoutMs: 8000 });\n r = applyReputation(r, reps.get(sha256));\n }\n opts.onResult(r);\n } catch (e) {\n const code = (e as NodeJS.ErrnoException).code;\n if (code !== 'ENOENT') opts.onError?.(path, e as Error);\n }\n };\n\n for (const t of targets) {\n try {\n const w = watch(t.path, { recursive: t.depth > 1, persistent: true }, (_event, file) => {\n if (!file) return;\n const rel = String(file);\n if (IN_PROGRESS.test(rel)) return;\n const parts = rel.split(/[\\\\/]/);\n if (parts.length > t.depth || parts.some((p) => SKIP_DIR_NAMES.has(p))) return;\n const full = join(t.path, rel);\n const prev = timers.get(full);\n if (prev) clearTimeout(prev);\n timers.set(full, setTimeout(() => void scan(full), settle));\n });\n w.on('error', (e) => opts.onError?.(t.path, e));\n watchers.push(w);\n } catch (e) {\n opts.onError?.(t.path, e as Error);\n }\n }\n\n return () => {\n for (const w of watchers) w.close();\n for (const tm of timers.values()) clearTimeout(tm);\n timers.clear();\n };\n}\n","// Worker-thread entry for `threatcrush av scan`: reads, hashes and checks files\n// in parallel. Built to dist/av-worker.js next to the CLI bundle.\nimport { runScanWorker } from '@threatcrush/av/node';\n\nrunScanWorker();\n"],"mappings":";;;AAAA,qBAA2B;AAC3B,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path","import_node_crypto","import_node_fs","import_promises","import_node_os","import_node_path","import_node_crypto","import_node_fs","import_promises","import_node_os","import_node_worker_threads","import_node_fs","import_promises","import_node_path"]}