A Node.js package providing integration with ClamAV for anti-virus scanning, facilitating both Docker containerized management and direct connection to a ClamAV daemon.
Enterprise-grade antivirus scanning for Node.js applications - Seamlessly integrate ClamAV's powerful virus detection into your TypeScript/JavaScript projects with zero hassle.
In today's digital landscape, security is paramount. Whether you're building a file-sharing platform, processing user uploads, or handling sensitive data streams, you need reliable virus protection that just works. SmartAntivirus gives you:
- ๐ณ Docker-based or Direct Connection - Choose your deployment style
- โก In-memory Scanning - Lightning-fast scanning without disk I/O
- ๐ Stream Processing - Scan data on-the-fly as it flows through your app
- ๐ฏ TypeScript First - Full type safety and IntelliSense support
- ๐ฆ Zero Config - Works out of the box with sensible defaults
- ๐ Auto-updating - Virus definitions stay current automatically
``bash`
npm install @push.rocks/smartantivirus
Or if you're using pnpm (recommended):
`bash`
pnpm add @push.rocks/smartantivirus
`typescript
import { ClamAvService } from '@push.rocks/smartantivirus';
// That's it! The service automatically manages a Docker container
const scanner = new ClamAvService();
// Scan a suspicious string
const result = await scanner.scanString('Is this text safe?');
console.log(result.isInfected ? 'โ ๏ธ Threat detected!' : 'โ
All clear!');
// Scan a buffer
const fileBuffer = await fs.readFile('./upload.pdf');
const scanResult = await scanner.scanBuffer(fileBuffer);
`
SmartAntivirus provides two main classes:
`typescript
import { ClamAvService } from '@push.rocks/smartantivirus';
import express from 'express';
import multer from 'multer';
const app = express();
const scanner = new ClamAvService();
const upload = multer({ storage: multer.memoryStorage() });
app.post('/upload', upload.single('file'), async (req, res) => {
try {
// Scan the uploaded file buffer
const result = await scanner.scanBuffer(req.file.buffer);
if (result.isInfected) {
return res.status(400).json({
error: 'File rejected',
threat: result.reason
});
}
// File is safe, proceed with storage
await saveFile(req.file);
res.json({ message: 'File uploaded successfully' });
} catch (error) {
res.status(500).json({ error: 'Scan failed' });
}
});
`
Never load huge files into memory! Stream them instead:
`typescript
import { ClamAvService } from '@push.rocks/smartantivirus';
import { createReadStream } from 'fs';
const scanner = new ClamAvService();
async function scanLargeFile(filePath: string) {
const stream = createReadStream(filePath);
const result = await scanner.scanStream(stream);
if (result.isInfected) {
console.log(๐จ Threat found: ${result.reason});`
// Quarantine or delete the file
} else {
console.log('โ
File is clean');
}
}
Perfect for proxies, CDNs, or content moderation:
`typescript
const scanner = new ClamAvService();
// Scan a file from a URL
const result = await scanner.scanFileFromWebAsStream('https://example.com/document.pdf');
// For browser environments using Web Streams API
async function scanInBrowser(url: string) {
const response = await fetch(url);
const webStream = response.body as ReadableStream
if (webStream) {
const result = await scanner.scanWebStream(webStream);
return result;
}
}
`
For production environments requiring fine-grained control:
`typescript
import { ClamAVManager } from '@push.rocks/smartantivirus';
class AntivirusService {
private manager: ClamAVManager;
async initialize() {
this.manager = new ClamAVManager();
// Start the container
await this.manager.startContainer();
// Set up log monitoring
this.manager.on('log', (event) => {
if (event.type === 'error') {
console.error(ClamAV Error: ${event.message});Virus DB Version: ${dbInfo}
// Send to your logging service
}
});
// Update virus definitions
await this.manager.updateDatabase();
// Get database info
const dbInfo = await this.manager.getDatabaseInfo();
console.log();`
}
async shutdown() {
await this.manager.stopContainer();
}
}
We use the industry-standard EICAR test string for verification:
`typescript
import { ClamAvService } from '@push.rocks/smartantivirus';
const scanner = new ClamAvService();
// This is the EICAR test string - it's harmless but triggers antivirus
const EICAR = 'X5O!P%@AP4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*';
const result = await scanner.scanString(EICAR);
console.log(result.isInfected); // true
console.log(result.reason); // 'Eicar-Test-Signature'
`
Run the test suite:
`bash`
npm test
#### Constructor
`typescript`
new ClamAvService(host?: string, port?: number)host
- - ClamAV daemon host (default: '127.0.0.1')port
- - ClamAV daemon port (default: 3310)
#### Methods
##### scanString(text: string): Promise
Scan a text string for threats.
##### scanBuffer(buffer: Buffer): Promise
Scan binary data in a Buffer.
##### scanStream(stream: NodeJS.ReadableStream): Promise
Scan a Node.js readable stream.
##### scanWebStream(stream: ReadableStream
Scan a Web Streams API stream (browser-compatible).
##### scanFileFromWebAsStream(url: string): Promise
Download and scan a file from a URL.
##### verifyConnection(): Promise
Test the connection to ClamAV daemon.
#### ScanResult Type
`typescript`
interface ScanResult {
isInfected: boolean;
reason?: string; // Threat name if infected
}
Advanced container management for production deployments:
- startContainer() - Launch ClamAV in DockerstopContainer()
- - Gracefully shutdownupdateDatabase()
- - Update virus definitionsgetDatabaseInfo()
- - Get current DB versiongetLogs()
- - Retrieve container logs'log'
- Event: - Real-time log streaming
1. Reuse connections - Create one ClamAvService instance and reuse it
2. Stream large files - Don't load them into memory
3. Implement timeouts - Protect against hanging scans
4. Monitor logs - Watch for database update failures
- Run ClamAV container with limited resources
- Implement rate limiting on scan endpoints
- Log all detected threats for audit trails
- Regularly update virus definitions
- Use separate containers for different environments
#### Docker Compose
`yaml``
services:
clamav:
image: clamav/clamav:latest
ports:
- "3310:3310"
volumes:
- clamav-db:/var/lib/clamav
#### Kubernetes
The service automatically manages containers, but you can also deploy ClamAV separately and connect directly to the daemon.
Container won't start
- Ensure Docker is running
- Check port 3310 isn't already in use
- Verify sufficient disk space for virus definitions
Scans timing out
- Large files may take time - implement appropriate timeouts
- Check container resources (CPU/Memory)
- Ensure virus database is not updating
False positives
- Some packers/obfuscators trigger detection
- Whitelist known-safe patterns if needed
- Keep virus definitions updated
- ๐ [Report Issues
- ๐ Documentation
- ๐ฌ Discussions
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the license file within this repository.
Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.