games_app/backend/src/services/virusScanService.ts
2026-07-07 15:03:17 +02:00

96 lines
2.5 KiB
TypeScript

/**
* Optional ClamAV (clamd) virus scanning for uploaded files.
*/
import fs from 'fs';
import net from 'net';
import { config } from '../config';
export class VirusScanError extends Error {
constructor(message: string) {
super(message);
this.name = 'VirusScanError';
}
}
export function isVirusScanEnabled(): boolean {
return config.clamav.enabled;
}
/** Scans a file on disk; no-op when ClamAV is disabled. */
export async function scanUploadedFile(filePath: string): Promise<void> {
if (!config.clamav.enabled) return;
await scanWithClamd(filePath, config.clamav.host, config.clamav.port);
}
function scanWithClamd(filePath: string, host: string, port: number): Promise<void> {
return new Promise((resolve, reject) => {
const socket = net.createConnection({ host, port });
let response = '';
let streamEnded = false;
let socketEnded = false;
const finish = (err?: Error) => {
if (err) reject(err);
else resolve();
};
const tryFinish = () => {
if (!streamEnded || !socketEnded) return;
if (/\bFOUND\b/i.test(response)) {
finish(new VirusScanError('File failed virus scan'));
return;
}
if (/\bOK\b/i.test(response)) {
finish();
return;
}
finish(new VirusScanError('Virus scan returned an unexpected result'));
};
socket.setTimeout(config.clamav.timeoutMs, () => {
socket.destroy();
finish(new VirusScanError('Virus scan timed out'));
});
socket.on('error', (err) => {
finish(new VirusScanError(`Virus scan unavailable: ${err.message}`));
});
socket.on('data', (chunk) => {
response += chunk.toString('utf8');
});
socket.on('end', () => {
socketEnded = true;
tryFinish();
});
socket.on('connect', () => {
socket.write(Buffer.from('zINSTREAM\0'));
const stream = fs.createReadStream(filePath, { highWaterMark: 64 * 1024 });
stream.on('data', (chunk) => {
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
const len = Buffer.alloc(4);
len.writeUInt32BE(buf.length, 0);
if (!socket.write(len) || !socket.write(buf)) {
stream.pause();
socket.once('drain', () => stream.resume());
}
});
stream.on('end', () => {
socket.write(Buffer.alloc(4));
streamEnded = true;
tryFinish();
});
stream.on('error', (err) => {
socket.destroy();
finish(new VirusScanError(`Virus scan failed: ${err.message}`));
});
});
});
}