/** * Keep refused files for review instead of losing them. * * Each quarantined file is written under its SHA-256 digest with no original * extension (`-.quarantined`, no execute bit, mode 0600) next * to `-.json` with what was found and where it came from, * under `quarantine.path//`, and mirrored into the * `quarantined_files` table when the database is configured. * See Guardian P8.08 (stacksjs/stacks#3330). */ import type { MalwareScanResult, MalwareSurface } from '@stacksjs/types' import type { ScanInput } from './input' import { chmod, mkdir, readdir, readFile, rename, rm } from 'node:fs/promises' import { isAbsolute, join, resolve } from 'node:path' import process from 'node:process' import { malwareConfig } from './config' import { MalwareDetectedError, MalwareScanError } from './errors' 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 /** Who uploaded the file (user id, email, or actor label). */ uploader?: 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 /** Private quarantine disk name (default `quarantine`). */ quarantineDisk?: string /** Relative key on the quarantine disk (`/-.quarantined`). */ storageKey?: string /** Parsed original disk name from `intendedPath`, when known. */ originalDisk?: string /** Parsed original path from `intendedPath`, when known. */ originalPath?: string /** Absolute path of the stored bytes. */ file: string } export interface RestoreQuarantinedOptions { /** Admin override: allow restoring even when the re-scan is not clean. */ force?: boolean /** Override destination disk (defaults to `record.originalDisk ?? 'local'`). */ disk?: string /** Override destination path (defaults to `record.originalPath ?? record.originalName ?? record.sha256`). */ path?: string /** Custom writer for restoring bytes (defaults to `@stacksjs/storage`'s `Storage.disk(disk).write`). */ writeRestored?: (disk: string, path: string, bytes: Uint8Array) => Promise } export interface RestoreQuarantinedResult { id: string restored: true forced: boolean disk: string path: string verdict: MalwareScanResult record: QuarantineRecord } export interface PruneQuarantineResult { pruned: number retentionDays: number } export function quarantineRoot(): string { const path = malwareConfig().quarantine.path return isAbsolute(path) ? path : resolve(process.cwd(), path) } function parseIntendedPath(intendedPath?: string): { disk?: string, path?: string } { if (!intendedPath) return {} const colon = intendedPath.indexOf(':') if (colon > 0 && !intendedPath.slice(0, colon).includes('/')) { return { disk: intendedPath.slice(0, colon), path: intendedPath.slice(colon + 1), } } return { disk: 'local', path: intendedPath } } function extractUploader(meta: QuarantineMeta): string | undefined { if (meta.uploader) return meta.uploader const candidate = meta.context?.uploader ?? meta.context?.userEmail ?? meta.context?.userId ?? meta.context?.actor return candidate != null ? String(candidate) : undefined } async function persistQuarantinedRow(record: QuarantineRecord): Promise { try { const { db } = await import('@stacksjs/database/runtime') await db .insertInto('quarantined_files') .values({ uuid: crypto.randomUUID(), quarantine_id: record.id, original_disk: record.originalDisk ?? null, original_path: record.originalPath ?? null, original_name: record.originalName ?? null, quarantine_disk: record.quarantineDisk ?? 'quarantine', storage_key: record.storageKey ?? record.file, size: record.bytes, sha256: record.sha256, signature: record.signature ?? null, verdict: record.verdict, driver: record.driver, surface: record.surface ?? null, uploader: record.uploader ?? null, status: 'quarantined', quarantined_at: record.quarantinedAt, }) .executeTakeFirst() } catch { // Database or `quarantined_files` table may not be initialized in standalone/unit runs. } } async function markQuarantinedRowRestored(id: string, restoredAt: string): Promise { try { const { db } = await import('@stacksjs/database/runtime') await db .updateTable('quarantined_files') .set({ status: 'restored', restored_at: restoredAt }) .where('quarantine_id', '=', id) .execute() } catch { // Best-effort DB sync. } } async function deleteQuarantinedRow(id: string): Promise { try { const { db } = await import('@stacksjs/database/runtime') await db .deleteFrom('quarantined_files') .where('quarantine_id', '=', id) .execute() } catch { // Best-effort DB sync. } } /** * 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 shortId = crypto.randomUUID().slice(0, 8) const id = `${now.toISOString().replace(/[-:.TZ]/g, '').slice(0, 14)}-${shortId}` const day = now.toISOString().slice(0, 10) const dir = join(quarantineRoot(), day) await mkdir(dir, { recursive: true, mode: 0o700 }) const tempFile = join(dir, `.tmp-${shortId}`) const hasher = new Bun.CryptoHasher('sha256') const sink = Bun.file(tempFile).writer() let bytes = 0 try { for await (const chunk of toChunks(input)) { hasher.update(chunk) bytes += chunk.byteLength sink.write(chunk) await sink.flush() } } catch (error) { await Promise.resolve(sink.end()).catch(() => {}) await rm(tempFile, { force: true }).catch(() => {}) throw error } await sink.end() // Store quarantined bytes under their SHA-256 digest with no original extension // so nothing can ever serve them as active content. const sha256 = hasher.digest('hex') const objectName = `${sha256}-${shortId}.quarantined` const file = join(dir, objectName) await rename(tempFile, file) await chmod(file, 0o600) const parsedTarget = parseIntendedPath(meta.intendedPath) const uploader = extractUploader(meta) const record: QuarantineRecord = { id, quarantinedAt: now.toISOString(), verdict: result.verdict, signature: result.signature, driver: result.driver, bytes, sha256, quarantineDisk: config.quarantine.disk, storageKey: `${day}/${objectName}`, originalDisk: parsedTarget.disk, originalPath: parsedTarget.path, uploader, file, ...meta, } const metaFile = join(dir, `${sha256}-${shortId}.json`) await Bun.write(metaFile, `${JSON.stringify(record, null, 2)}\n`) await chmod(metaFile, 0o600) await persistQuarantinedRow(record) 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.sort((a, b) => b.quarantinedAt.localeCompare(a.quarantinedAt)) } /** * Re-scan a quarantined file and restore it to its original disk and path. * * Refuses restoration when the file is still infected, suspicious, or fails to * scan, unless an administrator explicitly passes `{ force: true }`. */ export async function restoreQuarantined( id: string, options: RestoreQuarantinedOptions = {}, ): Promise { if (!/^[\w-]+$/.test(id)) return null const record = (await listQuarantine()).find(r => r.id === id) if (!record) return null const bytes = new Uint8Array(await Bun.file(record.file).arrayBuffer()) const { scan } = await import('./scan') const verdict = await scan(bytes) if (verdict.verdict !== 'clean' && !options.force) { if (verdict.verdict === 'infected' || verdict.verdict === 'suspicious') throw new MalwareDetectedError(verdict, { quarantineId: record.id }) throw new MalwareScanError(verdict) } const disk = options.disk ?? record.originalDisk ?? 'local' const path = options.path ?? record.originalPath ?? record.originalName ?? record.sha256 if (options.writeRestored) { await options.writeRestored(disk, path, bytes) } else { const { Storage } = await import('@stacksjs/storage') await Storage.disk(disk).write(path, bytes) } await rm(record.file, { force: true }) await rm(record.file.replace(/\.quarantined$/, '.json'), { force: true }) await markQuarantinedRowRestored(record.id, new Date().toISOString()) return { id: record.id, restored: true, forced: Boolean(options.force && verdict.verdict !== 'clean'), disk, path, verdict, record, } } /** 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 }) await deleteQuarantinedRow(record.id) return true } /** * Remove quarantined files older than the configured retention window. */ export async function pruneQuarantine( options: { retentionDays?: number, now?: Date } = {}, ): Promise { const retentionDays = options.retentionDays ?? malwareConfig().quarantine.retentionDays const cutoffMs = (options.now ?? new Date()).getTime() - retentionDays * 86_400_000 const cutoffIso = new Date(cutoffMs).toISOString() const records = await listQuarantine() let pruned = 0 for (const record of records) { const ts = Date.parse(record.quarantinedAt) if (Number.isFinite(ts) && ts < cutoffMs) { if (await deleteQuarantined(record.id)) pruned++ } } try { const { db } = await import('@stacksjs/database/runtime') await db .deleteFrom('quarantined_files') .where('quarantined_at', '<', cutoffIso) .execute() } catch { // Best-effort DB cleanup. } return { pruned, retentionDays } }