import type { MalwareConfig, MalwareSurface } from '@stacksjs/types' import { config } from '@stacksjs/config' export interface ResolvedMalwareConfig extends MalwareConfig { failClosed: boolean maxScanBytes: number timeoutMs: number quarantine: { enabled: boolean, path: string } staging: { prefix: string } surfaces: Partial> } const DEFAULTS: ResolvedMalwareConfig = { driver: 'auto', failClosed: true, maxScanBytes: 512 * 1024 * 1024, timeoutMs: 30_000, quarantine: { enabled: true, path: 'storage/quarantine' }, staging: { prefix: 'incoming/' }, surfaces: {}, } let overrides: Partial | null = null let listeners: Array<() => void> = [] function appConfig(): Partial { try { return (config as { malware?: Partial }).malware ?? {} } catch { return {} } } /** * The effective malware config: framework defaults, then `config/malware.ts`, * then anything set with {@link configureMalware}. Nested objects merge; they * are never replaced whole. */ export function malwareConfig(): ResolvedMalwareConfig { const app = appConfig() const runtime = overrides ?? {} return { ...DEFAULTS, ...app, ...runtime, clamd: { ...app.clamd, ...runtime.clamd }, guardian: { ...app.guardian, ...runtime.guardian }, quarantine: { ...DEFAULTS.quarantine, ...app.quarantine, ...runtime.quarantine } as ResolvedMalwareConfig['quarantine'], staging: { ...DEFAULTS.staging, ...app.staging, ...runtime.staging } as ResolvedMalwareConfig['staging'], surfaces: { ...app.surfaces, ...runtime.surfaces }, driver: runtime.driver ?? app.driver ?? DEFAULTS.driver, failClosed: runtime.failClosed ?? app.failClosed ?? DEFAULTS.failClosed, maxScanBytes: runtime.maxScanBytes ?? app.maxScanBytes ?? DEFAULTS.maxScanBytes, timeoutMs: runtime.timeoutMs ?? app.timeoutMs ?? DEFAULTS.timeoutMs, } } /** * Override the malware config at runtime, merged over `config/malware.ts`. * Mostly for tests: `configureMalware({ driver: 'eicar' })`. */ export function configureMalware(options: Partial): void { overrides = { ...overrides, ...options } for (const listener of listeners) listener() } /** Drop every runtime override and cached driver. */ export function resetMalwareConfig(): void { overrides = null for (const listener of listeners) listener() } /** @internal Called when the config changes, so cached drivers are rebuilt. */ export function onMalwareConfigChange(listener: () => void): void { listeners = [...listeners, listener] } /** Whether a surface scans. A surface left out of `surfaces` scans. */ export function scanEnabled(surface: MalwareSurface): boolean { return malwareConfig().surfaces[surface] !== false }