/** * Keep refused files for review instead of losing them. * * Each quarantined file is written as `.quarantined` (no execute bit, no * original extension, mode 0600) next to `.json` with what was found and * where it came from, under `quarantine.path//`. */ import type { MalwareScanResult, MalwareSurface } from '@stacksjs/types' import type { ScanInput } from './input' import { chmod, mkdir, readdir, readFile, rm } from 'node:fs/promises' import { isAbsolute, join, resolve } from 'node:path' import process from 'node:process' import { malwareConfig } from './config' import { toChunks } from './input' export interface QuarantineMeta { surface?: MalwareSurface /** Client file name, kept for the reviewer. */ originalName?: string /** Where the file would have been stored, e.g. `disk:path`. */ intendedPath?: string /** Free-form context: user id, request id, message id. */ context?: Record } export interface QuarantineRecord extends QuarantineMeta { id: string quarantinedAt: string verdict: MalwareScanResult['verdict'] signature?: string driver: string bytes: number sha256: string /** Absolute path of the stored bytes. */ file: string } export function quarantineRoot(): string { const path = malwareConfig().quarantine.path return isAbsolute(path) ? path : resolve(process.cwd(), path) } /** * Store a refused file in quarantine. Returns `null` when quarantine is * disabled. A stream that has already been read cannot be quarantined: pass * bytes, a Blob or a path. */ export async function quarantine(input: ScanInput, result: MalwareScanResult, meta: QuarantineMeta = {}): Promise { const config = malwareConfig() if (!config.quarantine.enabled) return null const now = new Date() const id = `${now.toISOString().replace(/[-:.TZ]/g, '').slice(0, 14)}-${crypto.randomUUID().slice(0, 8)}` const dir = join(quarantineRoot(), now.toISOString().slice(0, 10)) await mkdir(dir, { recursive: true, mode: 0o700 }) const file = join(dir, `${id}.quarantined`) const hasher = new Bun.CryptoHasher('sha256') const sink = Bun.file(file).writer() let bytes = 0 try { for await (const chunk of toChunks(input)) { hasher.update(chunk) bytes += chunk.byteLength sink.write(chunk) await sink.flush() } } finally { await sink.end() } await chmod(file, 0o600) const record: QuarantineRecord = { id, quarantinedAt: now.toISOString(), verdict: result.verdict, signature: result.signature, driver: result.driver, bytes, sha256: hasher.digest('hex'), file, ...meta, } const metaFile = join(dir, `${id}.json`) await Bun.write(metaFile, `${JSON.stringify(record, null, 2)}\n`) await chmod(metaFile, 0o600) return record } /** Every quarantined file, newest first. */ export async function listQuarantine(): Promise { const root = quarantineRoot() let days: string[] try { days = await readdir(root) } catch { return [] } const records: QuarantineRecord[] = [] for (const day of days.sort().reverse()) { let entries: string[] try { entries = await readdir(join(root, day)) } catch { continue } for (const entry of entries.filter(e => e.endsWith('.json')).sort().reverse()) { try { records.push(JSON.parse(await readFile(join(root, day, entry), 'utf8')) as QuarantineRecord) } catch {} } } return records } /** Delete a quarantined file and its metadata for good. */ export async function deleteQuarantined(id: string): Promise { if (!/^[\w-]+$/.test(id)) return false const record = (await listQuarantine()).find(r => r.id === id) if (!record) return false await rm(record.file, { force: true }) await rm(record.file.replace(/\.quarantined$/, '.json'), { force: true }) return true }