Files
smartantivirus/readme.md

233 lines
7.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# @push.rocks/smartantivirus
A Node.js package for integrating antivirus scanning capabilities using ClamAV, allowing in-memory file and data scanning.
## Install
To install `@push.rocks/smartantivirus`, ensure that you have Node.js and npm installed on your system. You will also need Docker if you intend to use the containerized version of ClamAV. Once the prerequisites are sorted, you can install the package using the following command:
```bash
npm install @push.rocks/smartantivirus
```
### Prerequisites
- Node.js and npm
- Docker (for container-based usage)
- ClamAV daemon (for direct daemon usage)
## Usage
The `@push.rocks/smartantivirus` package provides intuitive tools for integrating ClamAV's virus scanning capabilities into your Node.js applications. It supports both Docker-based container management and direct communication with a running ClamAV daemon. Lets dive into how you can effectively use this package.
### Docker-based Usage with ClamAVManager
The `ClamAVManager` class simplifies the process of managing a ClamAV service running inside a Docker container. It ensures that the container is started, the virus database is updated, and logs are captured for monitoring.
#### Basic Setup
Below demonstrates starting a ClamAV container, updating virus definitions, and reading logs:
```typescript
import { ClamAVManager } from '@push.rocks/smartantivirus';
async function main() {
// Instantiate a ClamAVManager
const clamAvManager = new ClamAVManager();
// Start ClamAV Docker container
await clamAvManager.startContainer();
// Listen for log events
clamAvManager.on('log', event => {
console.log(`ClamAV log (${event.type}): ${event.message}`);
});
// Fetch and display database information
const dbInfo = await clamAvManager.getDatabaseInfo();
console.log('Database Information:', dbInfo);
// Update the virus database
await clamAvManager.updateDatabase();
// Stop the container when done
await clamAvManager.stopContainer();
}
main().catch(console.error);
```
### Direct Daemon Usage with ClamAvService
If you prefer direct communication with an existing ClamAV daemon, use the `ClamAvService` class. This allows you to scan strings and streams directly in memory.
#### Connection Verification and String Scanning
Below is an example of verifying connection to the ClamAV daemon and scanning a given string for virus signatures, using the EICAR test string:
```typescript
import { ClamAvService } from '@push.rocks/smartantivirus';
async function main() {
const clamService = new ClamAvService('127.0.0.1', 3310);
// Verify connection to ClamAV
const isConnected = await clamService.verifyConnection();
console.log(`Connection to ClamAV: ${isConnected ? 'successful' : 'failed'}`);
// Scan a test string
const eicarTest = 'X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*';
const scanResult = await clamService.scanString(eicarTest);
console.log('EICAR Test Result:', scanResult);
}
main().catch(console.error);
```
### Streaming Scanning
`ClamAvService` provides methods to scan NodeJS and Web API streams. This is particularly useful for processing large files or data transferred over the network.
#### Example: NodeJS Streaming
```typescript
import { ClamAvService } from '@push.rocks/smartantivirus';
import { createReadStream } from 'fs';
async function main() {
const clamService = new ClamAvService();
// Scan a local file stream
const fileStream = createReadStream('path/to/suspicious/file');
const fileScanResult = await clamService.scanStream(fileStream);
console.log('File Stream Scan Result:', fileScanResult);
// Scan a remote file by stream
const remoteFileScan = await clamService.scanFileFromWebAsStream('http://example.com/file');
console.log('Remote File Scan Result:', remoteFileScan);
}
main().catch(console.error);
```
#### Example: Web Stream (in Browser)
```typescript
import { ClamAvService } from '@push.rocks/smartantivirus';
async function scanWebStream(url: string) {
const response = await fetch(url);
const webStream = response.body as ReadableStream<Uint8Array>;
const clamService = new ClamAvService();
if (webStream) {
const scanResult = await clamService.scanWebStream(webStream);
console.log('Web Stream Scan Result:', scanResult);
}
}
scanWebStream('http://example.com/streamed-file').catch(console.error);
```
### Handling Buffers
Scan binary data directly using a buffer:
```typescript
import { ClamAvService } from '@push.rocks/smartantivirus';
async function main() {
const clamService = new ClamAvService();
const buffer = Buffer.from('Potentially harmful binary data', 'utf8');
try {
const bufferScanResult = await clamService.scanBuffer(buffer);
console.log('Buffer Scan Result:', bufferScanResult);
} catch (err) {
console.error('Error scanning buffer:', err);
}
}
main().catch(console.error);
```
### Error Handling and Event Monitoring
Both `ClamAVManager` and `ClamAvService` are designed with error handling features for robustness.
```typescript
import { ClamAVManager } from '@push.rocks/smartantivirus';
async function errorHandlingExample() {
const clamAvManager = new ClamAVManager();
try {
await clamAvManager.startContainer();
// Listen for errors in logs
clamAvManager.on('log', event => {
if (event.type === 'error') {
console.error(`ClamAV Error: ${event.message}`);
}
});
console.log('ClamAV container started successfully.');
} catch (err) {
console.error('Error starting ClamAV container:', err);
}
}
errorHandlingExample().catch(console.error);
```
### Advanced Usage and Configuration
#### Customize Container Settings
Customizing the Docker container setup is possible through class methods and properties:
```typescript
const manager = new ClamAVManager();
console.log(`Container Name: ${manager.containerName}`); // Access default name
console.log(`Listening Port: ${manager.port}`); // Access default port
```
#### Managing Logs
Capture and filter ClamAV logs for insights:
```typescript
const manager = new ClamAVManager();
await manager.startContainer();
const logs = manager.getLogs();
const errorLogs = logs.filter(log => log.type === 'error');
console.log('Error Logs:', errorLogs);
```
#### Health Checks
Monitor and ensure ClamAV service readiness:
```typescript
const manager = new ClamAVManager();
await manager.startContainer(); // Includes readiness checks
const dbInfo = await manager.getDatabaseInfo();
console.log('Database Version:', dbInfo);
```
### Testing your setup
Utilize provided test scripts to validate your ClamAV setup:
```bash
npm run test
```
These tests use the `@push.rocks/tapbundle` framework to verify functionality, ensuring a reliable setup.
### Conclusion
The `@push.rocks/smartantivirus` package offers a powerful suite of tools for incorporating ClamAV's scanning capabilities into Node.js applications. With Docker integration and direct daemon access, it covers a wide range of use-cases, from file scanning to real-time stream analysis. Designed with a focus on flexibility and ease of use, it allows developers to build secure, antivirus-enabled applications efficiently.
undefined