12 Commits

Author SHA1 Message Date
a810338cc4 1.3.1
Some checks failed
Default (tags) / security (push) Successful in 51s
Default (tags) / test (push) Failing after 2m9s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-02-07 20:47:31 +01:00
c5049d5155 fix(core): Updated descriptions and keywords in package.json and npmextra.json. Improved README content for usage clarity. 2025-02-07 20:47:30 +01:00
6ddcfc8d90 1.3.0
Some checks failed
Default (tags) / security (push) Successful in 39s
Default (tags) / test (push) Failing after 1m5s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-02-05 10:52:36 +01:00
a2d8d1cbfd feat(ClamAvService): Add support for enhanced streaming methods in ClamAvService 2025-02-05 10:52:35 +01:00
6adfcc2201 1.2.0
Some checks failed
Default (tags) / security (push) Successful in 1m2s
Default (tags) / test (push) Failing after 1m11s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-02-05 10:49:46 +01:00
6300843616 feat(ClamAvService): Add stream scanning methods to ClamAvService 2025-02-05 10:49:46 +01:00
8acfedd7f3 1.1.2
Some checks failed
Default (tags) / security (push) Successful in 38s
Default (tags) / test (push) Failing after 2m53s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-02-03 13:56:42 +01:00
3ef7d69380 fix(documentation): Update readme with additional legal and trademark information 2025-02-03 13:56:42 +01:00
4266d76319 1.1.1
Some checks failed
Default (tags) / security (push) Successful in 53s
Default (tags) / test (push) Failing after 2m55s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-02-03 13:55:16 +01:00
4446f265cb fix(clamav.manager): Improve log handling and add timeout for log reception in ClamAV manager tests 2025-02-03 13:55:15 +01:00
e31e7cca44 1.1.0
Some checks failed
Default (tags) / security (push) Successful in 55s
Default (tags) / test (push) Failing after 1m32s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-02-03 13:34:52 +01:00
a19638b476 feat(ClamAvService): Add ClamAV Manager with Docker container management capabilities. 2025-02-03 13:34:52 +01:00
14 changed files with 936 additions and 210 deletions

View File

@@ -1,5 +1,47 @@
# Changelog
## 2025-02-07 - 1.3.1 - fix(core)
Updated descriptions and keywords in package.json and npmextra.json. Improved README content for usage clarity.
- Revised package.json description and keywords to better represent the project's features.
- Enhanced npmextra.json with updated module attributes.
- Improved README with clearer instructions and examples for using ClamAVManager and ClamAvService.
- Fixed incorrect import path in test.clamav.manager.ts.
## 2025-02-05 - 1.3.0 - feat(ClamAvService)
Add support for enhanced streaming methods in ClamAvService
- Add methods to ClamAvService: scanStream for NodeJS streams, scanWebStream for Web API streams, and scanFileFromWebAsStream for fetching and scanning files from URLs.
- Update usage examples in readme for new streaming methods.
## 2025-02-05 - 1.2.0 - feat(ClamAvService)
Add stream scanning methods to ClamAvService
- Added scanStream method to support scanning NodeJS streams directly.
- Introduced scanWebStream method for scanning web resources as streams.
- Integrated stream scanning into existing ClamAvService class.
## 2025-02-03 - 1.1.2 - fix(documentation)
Update readme with additional legal and trademark information
- Added legal information related to licensing and trademarks
- Provided company details of Task Venture Capital GmbH
## 2025-02-03 - 1.1.1 - fix(clamav.manager)
Improve log handling and add timeout for log reception in ClamAV manager tests
- Refined the log receiving mechanism in ClamAV manager tests to use promises for better control over log receipt timing.
- Introduced a timeout mechanism in the log receiving test case to avoid indefinite waiting.
- Fixed the test case setup to accurately reflect log receipt and database information verification.
## 2025-02-03 - 1.1.0 - feat(ClamAvService)
Add ClamAV Manager with Docker container management capabilities.
- Introduced ClamAVManager class to manage ClamAV Docker containers.
- Implemented startContainer and stopContainer methods in ClamAVManager.
- Integrated ClamAVManager into ClamAvService for managing container lifecycle.
- Added ClamAVManager test setups and helpers in test suite.
## 2025-01-10 - 1.0.4 - fix(documentation)
Removed redundant conclusion section in readme.

View File

@@ -5,21 +5,23 @@
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartantivirus",
"description": "A Node.js package for integrating antivirus scanning capabilities using ClamAV, allowing in-memory file and data scanning.",
"description": "A Node.js package providing integration with ClamAV for anti-virus scanning, facilitating both Docker containerized management and direct connection to a ClamAV daemon.",
"npmPackagename": "@push.rocks/smartantivirus",
"license": "MIT",
"projectDomain": "push.rocks",
"keywords": [
"antivirus",
"ClamAV",
"Node.js",
"ClamAV",
"virus scanning",
"security",
"buffer scanning",
"Docker",
"in-memory scanning",
"file scanning",
"stream scanning",
"data protection",
"HTTP requests",
"file handling",
"network communication",
"network security",
"buffer scanning",
"software testing"
]
}

View File

@@ -1,8 +1,8 @@
{
"name": "@push.rocks/smartantivirus",
"version": "1.0.4",
"version": "1.3.1",
"private": false,
"description": "A Node.js package for integrating antivirus scanning capabilities using ClamAV, allowing in-memory file and data scanning.",
"description": "A Node.js package providing integration with ClamAV for anti-virus scanning, facilitating both Docker containerized management and direct connection to a ClamAV daemon.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"type": "module",
@@ -19,11 +19,13 @@
"@git.zone/tsrun": "^1.2.46",
"@git.zone/tstest": "^1.0.44",
"@push.rocks/tapbundle": "^5.0.15",
"@types/node": "^20.8.7"
"@types/node": "^20.8.7",
"typescript": "^5.7.3"
},
"dependencies": {
"@push.rocks/smartfile": "^11.1.5",
"@push.rocks/smartpath": "^5.0.18",
"@push.rocks/smartstream": "^3.2.5",
"axios": "^1.7.9",
"tar": "^7.4.3"
},
@@ -49,15 +51,17 @@
],
"keywords": [
"antivirus",
"ClamAV",
"Node.js",
"ClamAV",
"virus scanning",
"security",
"buffer scanning",
"Docker",
"in-memory scanning",
"file scanning",
"stream scanning",
"data protection",
"HTTP requests",
"file handling",
"network communication",
"network security",
"buffer scanning",
"software testing"
]
}

13
pnpm-lock.yaml generated
View File

@@ -14,6 +14,9 @@ importers:
'@push.rocks/smartpath':
specifier: ^5.0.18
version: 5.0.18
'@push.rocks/smartstream':
specifier: ^3.2.5
version: 3.2.5
axios:
specifier: ^1.7.9
version: 1.7.9
@@ -39,6 +42,9 @@ importers:
'@types/node':
specifier: ^20.8.7
version: 20.17.12
typescript:
specifier: ^5.7.3
version: 5.7.3
packages:
@@ -3935,6 +3941,11 @@ packages:
engines: {node: '>=14.17'}
hasBin: true
typescript@5.7.3:
resolution: {integrity: sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==}
engines: {node: '>=14.17'}
hasBin: true
uglify-js@3.19.3:
resolution: {integrity: sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==}
engines: {node: '>=0.8.0'}
@@ -9602,6 +9613,8 @@ snapshots:
typescript@5.6.3: {}
typescript@5.7.3: {}
uglify-js@3.19.3: {}
uint8array-extras@1.4.0: {}

237
readme.md
View File

@@ -1,120 +1,233 @@
# @push.rocks/smartantivirus
A package for performing antivirus testing, especially suitable for use with ClamAV.
A Node.js package for integrating antivirus scanning capabilities using ClamAV, allowing in-memory file and data scanning.
## Install
Installing `@push.rocks/smartantivirus` is straightforward. You'll need Node.js and npm installed on your machine to get started. Once they are ready, you can add the `@push.rocks/smartantivirus` package to your project by running the following command:
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
```
This will add the package to your project's dependencies and allow you to integrate antivirus scanning capabilities directly into your application.
### Prerequisites
- Node.js and npm
- Docker (for container-based usage)
- ClamAV daemon (for direct daemon usage)
## Usage
The `@push.rocks/smartantivirus` package provides tools to easily integrate antivirus scanning capabilities into your Node.js application by interfacing with the ClamAV daemon. Below is a comprehensive guide on how to use the features of this library.
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.
### Setting Up the ClamAV Daemon
### Docker-based Usage with ClamAVManager
Before using this package, make sure you have ClamAV installed and running on your system. You can find installation instructions for various operating systems on the [ClamAV official website](https://www.clamav.net/documents/installing-clamav).
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.
After installing ClamAV, start the ClamAV daemon (`clamd`). Make sure it is configured to listen on a port accessible to your Node.js application. You can configure this in the `clamd.conf` file, typically located in `/etc/clamav/clamd.conf`.
#### Basic Setup
### Basic Usage
The primary interface provided by the package is the `ClamAvService` class. It allows you to scan data in memory or verify the connection to the ClamAV daemon.
Below demonstrates starting a ClamAV container, updating virus definitions, and reading logs:
```typescript
import { ClamAvService } from '@push.rocks/smartantivirus';
import { ClamAVManager } from '@push.rocks/smartantivirus';
async function main() {
const clamService = new ClamAvService('127.0.0.1', 3310); // Replace with your ClamAV host and port
// Instantiate a ClamAVManager
const clamAvManager = new ClamAVManager();
// Verify connection to ClamAV
const isConnected = await clamService.verifyConnection();
console.log(`Connection to ClamAV: ${isConnected ? 'successful' : 'failed'}`);
// Start ClamAV Docker container
await clamAvManager.startContainer();
if (!isConnected) {
console.error('Could not connect to ClamAV daemon. Please check your configuration.');
return;
}
// Listen for log events
clamAvManager.on('log', event => {
console.log(`ClamAV log (${event.type}): ${event.message}`);
});
// Scan a text string
const testString = 'X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*';
const scanResult = await clamService.scanString(testString);
console.log('Scan Result:', scanResult);
// 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);
```
**Breaking Down the Example:**
### Direct Daemon Usage with ClamAvService
1. **Initialization**: We start by creating an instance of the `ClamAvService` class. It takes two optional parameters: the host and port where your ClamAV daemon is running. By default, it assumes `127.0.0.1` and `3310`.
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.
2. **Verify Connection**: The `verifyConnection` method is called to ensure that our application can communicate with the ClamAV daemon. It returns a promise that resolves to `true` if the connection is successful, and `false` otherwise.
#### Connection Verification and String Scanning
3. **Scan Strings**: We utilize the `scanString` method to scan a text string (in this example, the EICAR test virus string is used). This method converts the string to a buffer and sends it to the ClamAV daemon for scanning.
### Handling Buffers
Below is an example demonstrating scanning raw binary data in the form of buffers:
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 scanBufferExample() {
const clamService = new ClamAvService();
async function main() {
const clamService = new ClamAvService('127.0.0.1', 3310);
// This buffer should represent the binary data you want to scan.
const buffer = Buffer.from('Sample buffer contents', 'utf8');
// Verify connection to ClamAV
const isConnected = await clamService.verifyConnection();
console.log(`Connection to ClamAV: ${isConnected ? 'successful' : 'failed'}`);
try {
const scanResult = await clamService.scanBuffer(buffer);
console.log('Buffer Scan Result:', scanResult);
} catch (error) {
console.error('Error scanning buffer:', error);
}
// 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);
}
scanBufferExample();
main().catch(console.error);
```
**Explanation:**
### Streaming Scanning
- We create an instance of `ClamAvService`.
- A buffer is created and passed to the `scanBuffer` method, which scans the in-memory data for potential viruses.
`ClamAvService` provides methods to scan NodeJS and Web API streams. This is particularly useful for processing large files or data transferred over the network.
### Error Handling and Debugging
The methods of `ClamAvService` throw errors if there are issues with communication or processing data. Wrap your code in try-catch blocks and use appropriate logging to handle errors gracefully.
#### Example: NodeJS Streaming
```typescript
try {
const scanResult = await clamService.scanString('Some suspicious string...');
console.log(`Infection Status: ${scanResult.isInfected ? 'Infected' : 'Clean'}`);
if (scanResult.isInfected) {
console.log(`Reason: ${scanResult.reason}`);
}
} catch (error) {
console.error('An error occurred during the scanning process:', error);
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
A preconfigured test script is provided, which demonstrates how to use the package with the Tap bundle testing framework. You can find the test script in `test/test.ts`. This is configured to run with the default `@push.rocks/tapbundle` setup:
Utilize provided test scripts to validate your ClamAV setup:
```bash
npm run test
```
The tests include creating and utilizing a `ClamAvService` instance and attempts to scan the well-known EICAR test string. They ensure that the basic functionality of the package is working as intended.
These tests use the `@push.rocks/tapbundle` framework to verify functionality, ensuring a reliable setup.
### Advanced Usage and Integration
### Conclusion
Beyond scanning strings and buffers, you can implement additional advanced use cases based on your specific application needs, such as integrating into web services or automating file scans in cloud environments. Consider building upon provided functionalities and adapting them to meet the requirements of your application architecture.
With the help of Node.js worker threads or external task queues like RabbitMQ, you can distribute scanning tasks efficiently within high-traffic environments.
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

View File

@@ -0,0 +1,90 @@
import { ClamAVManager } from '../../ts/classes.clamav.manager.js';
import { execAsync } from '../../ts/plugins.js';
let clamManager: ClamAVManager | null = null;
let isCleaningUp = false;
export async function getManager(): Promise<ClamAVManager> {
if (!clamManager) {
throw new Error('ClamAV manager not initialized');
}
return clamManager;
}
export async function setupClamAV(): Promise<ClamAVManager> {
console.log('[Helper] Setting up ClamAV...');
// First cleanup any existing containers
await forceCleanupContainer();
if (!clamManager) {
console.log('[Helper] Creating new ClamAV manager instance');
clamManager = new ClamAVManager();
await clamManager.startContainer();
console.log('[Helper] ClamAV manager initialized');
} else {
console.log('[Helper] Using existing ClamAV manager instance');
}
return clamManager;
}
export async function cleanupClamAV(): Promise<void> {
if (isCleaningUp) {
console.log('[Helper] Cleanup already in progress, skipping');
return;
}
isCleaningUp = true;
console.log('[Helper] Cleaning up ClamAV...');
try {
if (clamManager) {
await clamManager.stopContainer();
console.log('[Helper] ClamAV container stopped');
}
await forceCleanupContainer();
} catch (error) {
console.error('[Helper] Error during cleanup:', error);
throw error;
} finally {
clamManager = null;
isCleaningUp = false;
}
}
async function forceCleanupContainer(): Promise<void> {
try {
// Stop any existing container
await execAsync('docker stop clamav-daemon').catch(() => {});
// Remove any existing container
await execAsync('docker rm -f clamav-daemon').catch(() => {});
console.log('[Helper] Forced cleanup of existing containers complete');
} catch (error) {
// Ignore errors as the container might not exist
}
}
// Handle interrupts
process.on('SIGINT', async () => {
console.log('\n[Helper] Received SIGINT. Cleaning up...');
try {
await cleanupClamAV();
process.exit(0);
} catch (err) {
console.error('[Helper] Error during cleanup:', err);
process.exit(1);
}
});
// Ensure cleanup on process exit
process.on('exit', () => {
if (clamManager && !isCleaningUp) {
console.log('[Helper] Process exit detected, attempting cleanup');
// We can't use async functions in exit handler, so we do our best
try {
execAsync('docker stop clamav-daemon').catch(() => {});
execAsync('docker rm -f clamav-daemon').catch(() => {});
} catch {}
}
});

View File

@@ -0,0 +1,73 @@
import { expect, tap } from '@push.rocks/tapbundle';
import type { ClamAVLogEvent } from '../ts/classes.clamav.manager.js';
import { setupClamAV, cleanupClamAV, getManager } from './helpers/clamav.helper.js';
type ClamAVManager = Awaited<ReturnType<typeof setupClamAV>>;
let manager: ClamAVManager;
tap.test('setup', async () => {
manager = await setupClamAV();
expect(manager).toBeTruthy();
});
tap.test('should have initialized container and receive logs', async () => {
// Create a promise that resolves when we receive a log
const logPromise = new Promise<void>((resolve) => {
// First check if we already have logs
const existingLogs = manager.getLogs();
if (existingLogs.length > 0) {
console.log('[Test] Found existing logs:', existingLogs.map(log => `${log.type}: ${log.message}`).join('\n'));
resolve();
return;
}
// If no existing logs, wait for new ones
const handler = (event: ClamAVLogEvent) => {
console.log(`[Test] Received log event: ${event.type} - ${event.message}`);
manager.removeListener('log', handler);
resolve();
};
manager.on('log', handler);
});
// Wait for logs with timeout
const timeoutPromise = new Promise<void>((_, reject) => {
setTimeout(() => reject(new Error('Timeout waiting for logs')), 30000);
});
try {
await Promise.race([logPromise, timeoutPromise]);
} catch (error) {
console.error('Error waiting for logs:', error);
throw error;
}
console.log('Log received check passed');
// Verify container is running by checking if we can get database info
try {
const dbInfo = await manager.getDatabaseInfo();
expect(dbInfo).toBeTruthy();
console.log('Database info check passed');
} catch (error) {
console.error('Error getting database info:', error);
throw new Error('Failed to get database info - container may not be fully initialized');
}
});
tap.test('should get database info', async () => {
const dbInfo = await manager.getDatabaseInfo();
console.log('Database Info:', dbInfo);
expect(dbInfo).toBeTruthy();
});
tap.test('should update database', async () => {
await manager.updateDatabase();
});
tap.test('cleanup', async () => {
await cleanupClamAV();
});
tap.start();

View File

@@ -1,35 +1,40 @@
import { expect, expectAsync, tap } from '@push.rocks/tapbundle';
import { tap, expect } from '@push.rocks/tapbundle';
import * as smartantivirus from '../ts/index.js';
import { setupClamAV, cleanupClamAV } from './helpers/clamav.helper.js';
const EICAR_TEST_STRING = 'X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*';
let clamService: smartantivirus.ClamAvService;
tap.test('should create a ClamAvService instance', async () => {
clamService = new smartantivirus.ClamAvService();
expect(clamService).toBeDefined();
tap.test('setup', async () => {
await setupClamAV();
});
tap.test('should scan a string', async () => {
const scanResult = await clamService.scanString('X5O!P%@AP[4\PZX54(P^)7CC)7}' + '$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*');
tap.test('should create a ClamAvService instance and initialize ClamAV', async () => {
clamService = new smartantivirus.ClamAvService();
expect(clamService).toBeTruthy();
// The manager will start the container and wait for initialization
await clamService.verifyConnection();
});
tap.test('should detect EICAR test string', async () => {
const scanResult = await clamService.scanString(EICAR_TEST_STRING);
console.log('Scan Result:', scanResult);
// expect(scanResult).toEqual({ isInfected: true, reason: 'FOUND' });
expect(scanResult.isInfected).toEqual(true);
expect(scanResult.reason).toBeTruthy();
});
tap.test('should not detect clean string', async () => {
const scanResult = await clamService.scanString('This is a clean string with no virus signature');
console.log('Clean Scan Result:', scanResult);
expect(scanResult.isInfected).toEqual(false);
expect(scanResult.reason).toBeUndefined();
});
tap.test('cleanup', async () => {
await cleanupClamAV();
});
tap.start();
/* (async () => {
try {
await clamService.updateVirusDefinitions(); // Step 2: Update definitions
await clamService.startClamDaemon(); // Step 3: Start daemon
const scanResult = await clamService.scanString('EICAR test string...');
console.log('Scan Result:', scanResult);
} catch (error) {
console.error('Error:', error);
}
})(); */

View File

@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartantivirus',
version: '1.0.4',
description: 'A Node.js package for integrating antivirus scanning capabilities using ClamAV, allowing in-memory file and data scanning.'
version: '1.3.1',
description: 'A Node.js package providing integration with ClamAV for anti-virus scanning, facilitating both Docker containerized management and direct connection to a ClamAV daemon.'
}

View File

@@ -0,0 +1,281 @@
import { exec, spawn, net, promisify, EventEmitter, execAsync } from './plugins.js';
export interface ClamAVLogEvent {
timestamp: string;
message: string;
type: 'update' | 'scan' | 'system' | 'error';
}
export class ClamAVManager extends EventEmitter {
private containerId: string | null = null;
private containerName = 'clamav-daemon';
private imageTag = 'clamav/clamav:latest';
private port = 3310;
private logs: ClamAVLogEvent[] = [];
constructor() {
super();
}
public getLogs(): ClamAVLogEvent[] {
return this.logs;
}
/**
* Start the ClamAV container if it's not already running
*/
public async startContainer(): Promise<void> {
try {
console.log('[ClamAV] Starting container initialization...');
// Check if container is already running
const { stdout: psOutput } = await execAsync('docker ps --filter name=' + this.containerName);
if (psOutput.includes(this.containerName)) {
console.log('[ClamAV] Container is already running');
this.containerId = (await execAsync(`docker ps -q --filter name=${this.containerName}`)).stdout.trim();
console.log('[ClamAV] Container ID:', this.containerId);
this.attachLogWatcher();
await this.waitForInitialization();
return;
}
// Check if container exists but is stopped
const { stdout: psaOutput } = await execAsync('docker ps -a --filter name=' + this.containerName);
if (psaOutput.includes(this.containerName)) {
console.log('[ClamAV] Found stopped container, starting it...');
await execAsync(`docker start ${this.containerName}`);
this.containerId = (await execAsync(`docker ps -q --filter name=${this.containerName}`)).stdout.trim();
console.log('[ClamAV] Started existing container, ID:', this.containerId);
} else {
// Create and start new container
console.log('[ClamAV] Creating new container...');
const { stdout } = await execAsync(
`docker run -d --name ${this.containerName} -p ${this.port}:3310 ${this.imageTag}`
);
this.containerId = stdout.trim();
console.log('[ClamAV] Created new container, ID:', this.containerId);
}
this.attachLogWatcher();
console.log('[ClamAV] Waiting for initialization...');
await this.waitForInitialization();
console.log('[ClamAV] Container successfully initialized');
} catch (error) {
console.error('[ClamAV] Error starting container:', error);
throw error;
}
}
/**
* Stop the ClamAV container
*/
public async stopContainer(): Promise<void> {
if (!this.containerId) {
console.log('No ClamAV container is running');
return;
}
try {
await execAsync(`docker stop ${this.containerId}`);
console.log('Stopped ClamAV container');
} catch (error) {
console.error('Error stopping ClamAV container:', error);
throw error;
}
}
/**
* Manually trigger a database update
*/
public async updateDatabase(): Promise<void> {
if (!this.containerId) {
throw new Error('ClamAV container is not running');
}
try {
// First check if freshclam is already running
const { stdout: psOutput } = await execAsync(`docker exec ${this.containerId} ps aux | grep freshclam`);
if (psOutput.includes('/usr/local/sbin/freshclam -d')) {
console.log('Freshclam daemon is already running');
// Wait a bit to ensure database is updated
await new Promise(resolve => setTimeout(resolve, 2000));
return;
}
// If not running as daemon, try to update manually
const { stdout, stderr } = await execAsync(`docker exec ${this.containerId} freshclam --no-warnings`);
console.log('Database update output:', stdout);
if (stderr) {
console.error('Database update errors:', stderr);
}
} catch (error) {
// Check if the error is due to freshclam already running
if (error.stderr?.includes('ERROR: Problem with internal logger') ||
error.stdout?.includes('Resource temporarily unavailable')) {
console.log('Freshclam is already running, skipping manual update');
return;
}
console.error('Error updating ClamAV database:', error);
throw error;
}
}
/**
* Get the current database version information
*/
public async getDatabaseInfo(): Promise<string> {
if (!this.containerId) {
throw new Error('ClamAV container is not running');
}
try {
// Try both .cld and .cvd files since ClamAV can use either format
try {
const { stdout } = await execAsync(`docker exec ${this.containerId} sigtool --info /var/lib/clamav/daily.cld`);
return stdout;
} catch {
const { stdout } = await execAsync(`docker exec ${this.containerId} sigtool --info /var/lib/clamav/daily.cvd`);
return stdout;
}
} catch (error) {
console.error('Error getting database info:', error);
throw error;
}
}
/**
* Watch container logs and emit events for different types of log messages
*/
private attachLogWatcher(): void {
if (!this.containerId) return;
const logProcess = spawn('docker', ['logs', '-f', this.containerId]);
logProcess.stdout.on('data', (data) => {
const lines = data.toString().split('\n');
lines.forEach(line => {
if (!line.trim()) return;
const event: ClamAVLogEvent = {
timestamp: new Date().toISOString(),
message: line,
type: this.determineLogType(line)
};
this.logs.push(event);
this.emit('log', event);
console.log(`[ClamAV ${event.type}] ${event.message}`);
});
});
logProcess.stderr.on('data', (data) => {
const event: ClamAVLogEvent = {
timestamp: new Date().toISOString(),
message: data.toString(),
type: 'error'
};
this.logs.push(event);
this.emit('log', event);
console.error(`[ClamAV error] ${event.message}`);
});
logProcess.on('error', (error) => {
console.error('Error in log watcher:', error);
});
}
/**
* Determine the type of log message
*/
private determineLogType(logMessage: string): ClamAVLogEvent['type'] {
const lowerMessage = logMessage.toLowerCase();
if (lowerMessage.includes('update') || lowerMessage.includes('freshclam')) {
return 'update';
} else if (lowerMessage.includes('scan') || lowerMessage.includes('found')) {
return 'scan';
} else if (lowerMessage.includes('error') || lowerMessage.includes('warning')) {
return 'error';
}
return 'system';
}
/**
* Wait for ClamAV to initialize by checking both logs and service readiness
*/
private async waitForInitialization(): Promise<void> {
return new Promise((resolve, reject) => {
if (!this.containerId) {
reject(new Error('Container ID not set'));
return;
}
let timeout: NodeJS.Timeout;
let checkCount = 0;
const maxChecks = 60; // Check for 60 seconds
const startTime = Date.now();
// Check service readiness
const checkService = async () => {
try {
const elapsedTime = Math.round((Date.now() - startTime) / 1000);
console.log(`[ClamAV] Checking service readiness (attempt ${checkCount + 1}, ${elapsedTime}s elapsed)...`);
// First check if the service is accepting connections
const client = new net.Socket();
await new Promise<void>((resolveConn, rejectConn) => {
const connectTimeout = setTimeout(() => {
client.destroy();
rejectConn(new Error('Connection timeout'));
}, 1000);
client.connect(this.port, 'localhost', () => {
clearTimeout(connectTimeout);
client.end();
resolveConn();
});
client.on('error', (err) => {
clearTimeout(connectTimeout);
rejectConn(err);
});
});
// Verify the service is responding to commands
const { stdout } = await execAsync(`echo PING | nc localhost ${this.port}`);
if (!stdout.includes('PONG')) {
throw new Error('Service not responding to commands');
}
// If we can connect and get a PONG, the service is ready
console.log('[ClamAV] Service is accepting connections and responding to commands');
cleanup();
resolve();
} catch (error) {
// Service not ready yet, will retry
if (checkCount >= maxChecks) {
cleanup();
reject(new Error(`ClamAV initialization timed out after ${maxChecks} seconds. Last error: ${error.message}`));
return;
}
checkCount++;
}
};
const cleanup = () => {
clearTimeout(timeout);
clearInterval(serviceCheck);
};
const serviceCheck = setInterval(checkService, 1000);
timeout = setTimeout(() => {
cleanup();
reject(new Error('ClamAV initialization timed out after 60 seconds'));
}, 60000);
// Start initial service check
checkService();
});
}
}

187
ts/classes.clamavservice.ts Normal file
View File

@@ -0,0 +1,187 @@
import * as plugins from './plugins.js';
import * as paths from './paths.js';
import { net } from './plugins.js';
import { ClamAVManager } from './classes.clamav.manager.js';
export class ClamAvService {
private host: string;
private port: number;
private manager: ClamAVManager;
constructor(host: string = '127.0.0.1', port: number = 3310) {
this.host = host;
this.port = port;
this.manager = new ClamAVManager();
// Listen to ClamAV logs
this.manager.on('log', (event) => {
if (event.type === 'scan') {
console.log(`[ClamAV Scan] ${event.message}`);
}
});
}
private async ensureContainerStarted(): Promise<void> {
await this.manager.startContainer();
}
/**
* Scans an in-memory Buffer using ClamAV daemon's INSTREAM command.
*/
public async scanBuffer(buffer: Buffer): Promise<{ isInfected: boolean; reason?: string }> {
await this.ensureContainerStarted();
return new Promise((resolve, reject) => {
const client = new net.Socket();
client.connect(this.port, this.host, () => {
console.log('Connected to ClamAV daemon');
client.write('zINSTREAM\0'); // Start the INSTREAM command
const chunkSize = 1024;
let offset = 0;
// Send data in chunks
while (offset < buffer.length) {
const chunk = buffer.slice(offset, offset + chunkSize);
console.log('Sending chunk:', chunk.toString('utf8'));
const sizeBuf = Buffer.alloc(4);
sizeBuf.writeUInt32BE(chunk.length, 0);
client.write(sizeBuf);
client.write(chunk);
offset += chunkSize;
}
// Send end-of-stream signal
const endOfStream = Buffer.alloc(4);
endOfStream.writeUInt32BE(0, 0);
console.log('Sending end-of-stream signal');
client.write(endOfStream);
});
client.on('data', (data) => {
const response = data.toString();
console.log('Raw Response from ClamAV:', response);
const isInfected = response.includes('FOUND');
const reason = isInfected ? response.split('FOUND')[0].trim() : undefined;
resolve({ isInfected, reason });
client.end();
});
client.on('error', (err) => {
console.error('Error communicating with ClamAV:', err);
reject(err);
});
client.on('close', () => {
console.log('Connection to ClamAV daemon closed');
});
});
}
/**
* Scans a string by converting it to a Buffer and using scanBuffer.
*/
public async scanString(input: string): Promise<{ isInfected: boolean; reason?: string }> {
console.log('Scanning string:', input); // Debug the input string
const buffer = Buffer.from(input, 'utf8');
console.log('Converted buffer:', buffer.toString('utf8')); // Debug the converted buffer
return this.scanBuffer(buffer);
}
/**
* Verifies the ClamAV daemon is reachable.
*/
public async verifyConnection(): Promise<boolean> {
await this.ensureContainerStarted();
return new Promise((resolve, reject) => {
const client = new net.Socket();
client.connect(this.port, this.host, () => {
console.log('Successfully connected to ClamAV daemon');
client.end();
resolve(true);
});
client.on('error', (err) => {
console.error('Failed to connect to ClamAV daemon:', err);
reject(err);
});
});
}
/**
* Scans data from a NodeJS stream using ClamAV daemon's INSTREAM command.
*/
public async scanStream(stream: NodeJS.ReadableStream): Promise<{ isInfected: boolean; reason?: string }> {
await this.ensureContainerStarted();
return new Promise((resolve, reject) => {
const client = new net.Socket();
client.connect(this.port, this.host, () => {
console.log('Connected to ClamAV daemon for stream scanning');
client.write('zINSTREAM\0');
stream.on('data', (chunk: Buffer) => {
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
const sizeBuf = Buffer.alloc(4);
sizeBuf.writeUInt32BE(buf.length, 0);
client.write(sizeBuf);
client.write(buf);
});
stream.on('end', () => {
const endOfStream = Buffer.alloc(4);
endOfStream.writeUInt32BE(0, 0);
console.log('Stream ended, sending end-of-stream signal');
client.write(endOfStream);
});
stream.on('error', (err) => {
console.error('Error reading stream:', err);
reject(err);
});
});
client.on('data', (data) => {
const response = data.toString();
console.log('Raw Response from ClamAV (stream):', response);
const isInfected = response.includes('FOUND');
const reason = isInfected ? response.split('FOUND')[0].trim() : undefined;
resolve({ isInfected, reason });
client.end();
});
client.on('error', (err) => {
console.error('Error with ClamAV stream scanning:', err);
reject(err);
});
});
}
/**
* Scans a file from a web URL as a stream using ClamAV daemon's INSTREAM command.
*/
public async scanFileFromWebAsStream(url: string): Promise<{ isInfected: boolean; reason?: string }> {
return new Promise((resolve, reject) => {
const protocol = url.startsWith('https') ? plugins.https : plugins.http;
protocol.get(url, (response) => {
this.scanStream(response).then(resolve).catch(reject);
}).on('error', (err) => {
console.error('Error fetching URL:', err);
reject(err);
});
});
}
/**
* Scans a web resource by URL using ClamAV daemon's INSTREAM command.
*/
public async scanWebStream(webstreamArg: ReadableStream): Promise<{ isInfected: boolean; reason?: string }> {
// Convert the web ReadableStream to a NodeJS ReadableStream
const nodeStream = plugins.smartstream.nodewebhelpers.convertWebReadableToNodeReadable(webstreamArg);
return this.scanStream(nodeStream);
}
}

View File

@@ -1,103 +0,0 @@
import * as plugins from './plugins.js';
import * as paths from './paths.js';
import { exec } from 'child_process';
import net from 'net';
import { promisify } from 'util';
const execAsync = promisify(exec);
export class ClamAvService {
private host: string;
private port: number;
constructor(host: string = '127.0.0.1', port: number = 3310) {
this.host = host;
this.port = port;
}
/**
* Scans an in-memory Buffer using ClamAV daemon's INSTREAM command.
*/
public async scanBuffer(buffer: Buffer): Promise<{ isInfected: boolean; reason?: string }> {
return new Promise((resolve, reject) => {
const client = new net.Socket();
client.connect(this.port, this.host, () => {
console.log('Connected to ClamAV daemon');
client.write('zINSTREAM\0'); // Start the INSTREAM command
const chunkSize = 1024;
let offset = 0;
// Send data in chunks
while (offset < buffer.length) {
const chunk = buffer.slice(offset, offset + chunkSize);
console.log('Sending chunk:', chunk.toString('utf8'));
const sizeBuf = Buffer.alloc(4);
sizeBuf.writeUInt32BE(chunk.length, 0);
client.write(sizeBuf);
client.write(chunk);
offset += chunkSize;
}
// Send end-of-stream signal
const endOfStream = Buffer.alloc(4);
endOfStream.writeUInt32BE(0, 0);
console.log('Sending end-of-stream signal');
client.write(endOfStream);
});
client.on('data', (data) => {
const response = data.toString();
console.log('Raw Response from ClamAV:', response);
const isInfected = response.includes('FOUND');
const reason = isInfected ? response.split('FOUND')[0].trim() : undefined;
resolve({ isInfected, reason });
client.end();
});
client.on('error', (err) => {
console.error('Error communicating with ClamAV:', err);
reject(err);
});
client.on('close', () => {
console.log('Connection to ClamAV daemon closed');
});
});
}
/**
* Scans a string by converting it to a Buffer and using scanBuffer.
*/
public async scanString(input: string): Promise<{ isInfected: boolean; reason?: string }> {
console.log('Scanning string:', input); // Debug the input string
const buffer = Buffer.from(input, 'utf8');
console.log('Converted buffer:', buffer.toString('utf8')); // Debug the converted buffer
return this.scanBuffer(buffer);
}
/**
* Verifies the ClamAV daemon is reachable.
*/
public async verifyConnection(): Promise<boolean> {
return new Promise((resolve, reject) => {
const client = new net.Socket();
client.connect(this.port, this.host, () => {
console.log('Successfully connected to ClamAV daemon');
client.end();
resolve(true);
});
client.on('error', (err) => {
console.error('Failed to connect to ClamAV daemon:', err);
reject(err);
});
});
}
}

View File

@@ -1 +1,2 @@
export * from './classes.smartantivirus.js';
export * from './classes.clamavservice.js';
export * from './classes.clamav.manager.js';

View File

@@ -1,24 +1,42 @@
// node native scope
// Node.js built-in modules
import * as fs from 'fs';
import * as path from 'path';
import { exec, spawn } from 'child_process';
import { promisify } from 'util';
import { EventEmitter } from 'events';
import net from 'net';
import * as http from 'http';
import * as https from 'https';
export {
fs,
path,
}
exec,
spawn,
promisify,
EventEmitter,
net,
http,
https
};
// @push.rocks scope
import * as smartpath from '@push.rocks/smartpath';
import * as smartfile from '@push.rocks/smartfile';
import * as smartstream from '@push.rocks/smartstream';
export {
smartpath,
smartfile,
}
smartstream,
};
// third party scope
// Third party scope
import axios from 'axios';
export {
axios,
}
axios
};
// Common utilities
export const execAsync = promisify(exec);