javascript
// Safe Upload Pipeline in Node.js (Express + Multer + ClamAV + file-type)
// This pipeline handles streaming uploads securely:
// - Streams to temp file (no memory bloat)
// - Validates MIME type via magic bytes (ignores extensions)
// - Scans with ClamAV (local or socket)
// - Manages lifecycle: temp storage with auto-cleanup on error/success
// Prerequisites:
// npm i express multer file-type clamscan tmp graceful-fs aws-sdk@2 (optional for S3)
// Install ClamAV: brew install clamav (macOS) or apt install clamav clamav-daemon (Linux)
// Start freshclam && clamav-daemon (for socket scanning)
const express = require('express');
const multer = require('multer');
const { fileTypeFromFile } = require('file-type');
const clamscan = require('clamscan');
const tmp = require('tmp');
const fs = require('graceful-fs');
const path = require('path');
const AWS = require('aws-sdk'); // Optional: for S3 permanent storage
const app = express();
const PORT = 3000;
// Config
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
const ALLOWED_MIMES = [
'image/jpeg',
'image/png',
'application/pdf',
'text/plain'
];
const TMP_DIR = '/tmp/uploads'; // Use OS tmp dir in prod
// Ensure tmp dir
const mkdirp = require('mkdirp');
mkdirp.sync(TMP_DIR);
// ClamAV Scanner (assumes clamav-daemon running on /var/run/clamav/clamd.ctl)
let scanner;
(async () => {
scanner = await new clamscan({
clamdscan: {
socket: '/var/run/clamav/clamd.ctl', // Or use binary: path: '/usr/bin/clamscan'
host: 'localhost',
port: 3310,
},
}).init();
})();
// Multer: Stream to disk (temp files only)
const storage = multer.diskStorage({
destination: (req, file, cb) => {
tmp.dir({ dir: TMP_DIR }, (err, tempDir, cleanup) => {
if (err) return cb(err);
req.uploadCleanup = cleanup; // Register cleanup for lifecycle
cb(null, tempDir);
});
},
filename: (req, file, cb) => {
const uniqueName = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}${path.extname(file.originalname)}`;
cb(null, uniqueName);
}
});
const upload = multer({
storage,
limits: { fileSize: MAX_FILE_SIZE },
fileFilter: (req, file, cb) => {
// Pre-filter on declared MIME (extra safety)
if (!file.mimetype || !ALLOWED_MIMES.includes(file.mimetype)) {
return cb(new Error('Invalid MIME type'));
}
cb(null, true);
}
});
// Upload endpoint
app.post('/upload', upload.single('file'), async (req, res) => {
try {
const { file } = req;
if (!file) return res.status(400).json({ error: 'No file uploaded' });
const tempPath = file.path;
// Step 1: MIME Validation (magic bytes, not extension)
const type = await fileTypeFromFile(tempPath);
const mimeType = type?.mime;
if (!mimeType || !ALLOWED_MIMES.includes(mimeType)) {
throw new Error(`Invalid file type: ${mimeType}`);
}
// Step 2: AV Scan
const { isInfected, viruses } = await scanner.scanFile(tempPath);
if (isInfected) {
throw new Error(`Virus detected: ${viruses.join(', ')}`);
}
// Step 3: All clear! Move to permanent storage (local or S3)
const permanentPath = await storePermanently(tempPath, mimeType);
// Step 4: Lifecycle - Cleanup temp
fs.unlinkSync(tempPath);
if (req.uploadCleanup) req.uploadCleanup();
res.json({
success: true,
fileId: path.basename(permanentPath),
mimeType,
size: file.size
});
} catch (error) {
// Error handling: Always cleanup temp files
if (req.file?.path) fs.unlinkSync(req.file.path);
if (req.uploadCleanup) req.uploadCleanup();
console.error('Upload failed:', error.message);
res.status(400).json({ error: error.message });
}
});
// Optional: Permanent storage to local dir or S3
async function storePermanently(tempPath, mimeType) {
const permanentDir = './uploads'; // Or S3 bucket
mkdirp.sync(permanentDir);
const permanentPath = path.join(permanentDir, path.basename(tempPath));
// Local copy
fs.copyFileSync(tempPath, permanentPath);
// S3 example (uncomment and configure)
/*
const s3 = new AWS.S3({ /* credentials */ });
const fileKey = `uploads/${path.basename(tempPath)}`;
await s3.upload({
Bucket: 'your-bucket',
Key: fileKey,
Body: fs.createReadStream(tempPath),
ContentType: mimeType,
}).promise();
return `s3://${fileKey}`;
*/
return permanentPath;
}
// Lifecycle Management: Cron job for old files (e.g., via node-cron)
// Expire files > 7 days in permanent storage
const cron = require('node-cron');
cron.schedule('0 2 * * *', () => { // Daily at 2AM
const now = Date.now();
const sevenDays = 7 * 24 * 60 * 60 * 1000;
fs.readdirSync('./uploads').forEach(file => {
const filePath = path.join('./uploads', file);
const stats = fs.statSync(filePath);
if (now - stats.mtime.getTime() > sevenDays) {
fs.unlinkSync(filePath);
console.log(`Expired: ${file}`);
}
});
});
// Health check
app.get('/health', async (req, res) => {
const scanTest = await scanner.scanString('safe test');
res.json({ status: 'OK', clamav: !scanTest.isInfected });
});
app.listen(PORT, () => {
console.log(`Safe upload pipeline running on http://localhost:${PORT}`);
});