games_app/backend/dist-test-faq/services/virusScanService.js

99 lines
3.5 KiB
JavaScript

"use strict";
/**
* Optional ClamAV (clamd) virus scanning for uploaded files.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.VirusScanError = void 0;
exports.isVirusScanEnabled = isVirusScanEnabled;
exports.scanUploadedFile = scanUploadedFile;
const fs_1 = __importDefault(require("fs"));
const net_1 = __importDefault(require("net"));
const config_1 = require("../config");
class VirusScanError extends Error {
constructor(message) {
super(message);
this.name = 'VirusScanError';
}
}
exports.VirusScanError = VirusScanError;
function isVirusScanEnabled() {
return config_1.config.clamav.enabled;
}
/** Scans a file on disk; no-op when ClamAV is disabled. */
async function scanUploadedFile(filePath) {
if (!config_1.config.clamav.enabled)
return;
await scanWithClamd(filePath, config_1.config.clamav.host, config_1.config.clamav.port);
}
function scanWithClamd(filePath, host, port) {
return new Promise((resolve, reject) => {
let settled = false;
const socket = net_1.default.createConnection({ host, port });
let response = '';
let streamEnded = false;
let socketEnded = false;
const finish = (err) => {
if (settled)
return;
settled = true;
socket.destroy();
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_1.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_1.default.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}`));
});
});
});
}
//# sourceMappingURL=virusScanService.js.map