fix(core): Updated descriptions and keywords in package.json and npmextra.json. Improved README content for usage clarity.

This commit is contained in:
2025-02-07 20:47:30 +01:00
parent 6ddcfc8d90
commit c5049d5155
6 changed files with 161 additions and 195 deletions

View File

@@ -1,5 +1,13 @@
# Changelog # 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) ## 2025-02-05 - 1.3.0 - feat(ClamAvService)
Add support for enhanced streaming methods in ClamAvService Add support for enhanced streaming methods in ClamAvService

View File

@@ -5,21 +5,23 @@
"githost": "code.foss.global", "githost": "code.foss.global",
"gitscope": "push.rocks", "gitscope": "push.rocks",
"gitrepo": "smartantivirus", "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", "npmPackagename": "@push.rocks/smartantivirus",
"license": "MIT", "license": "MIT",
"projectDomain": "push.rocks", "projectDomain": "push.rocks",
"keywords": [ "keywords": [
"antivirus", "antivirus",
"ClamAV",
"Node.js", "Node.js",
"ClamAV",
"virus scanning", "virus scanning",
"security", "security",
"buffer scanning", "Docker",
"in-memory scanning",
"file scanning",
"stream scanning",
"data protection", "data protection",
"HTTP requests", "network security",
"file handling", "buffer scanning",
"network communication",
"software testing" "software testing"
] ]
} }

View File

@@ -2,7 +2,7 @@
"name": "@push.rocks/smartantivirus", "name": "@push.rocks/smartantivirus",
"version": "1.3.0", "version": "1.3.0",
"private": false, "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", "main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts", "typings": "dist_ts/index.d.ts",
"type": "module", "type": "module",
@@ -51,15 +51,17 @@
], ],
"keywords": [ "keywords": [
"antivirus", "antivirus",
"ClamAV",
"Node.js", "Node.js",
"ClamAV",
"virus scanning", "virus scanning",
"security", "security",
"buffer scanning", "Docker",
"in-memory scanning",
"file scanning",
"stream scanning",
"data protection", "data protection",
"HTTP requests", "network security",
"file handling", "buffer scanning",
"network communication",
"software testing" "software testing"
] ]
} }

310
readme.md
View File

@@ -1,18 +1,10 @@
# @push.rocks/smartantivirus # @push.rocks/smartantivirus
A package for performing antivirus testing with ClamAV, featuring both direct daemon communication and Docker container management. A Node.js package for integrating antivirus scanning capabilities using ClamAV, allowing in-memory file and data scanning.
## Features
- **Docker Integration**: Automatically manages ClamAV containers for easy setup and testing
- **Real-time Logging**: Captures and processes ClamAV logs with type-safe event handling
- **Database Management**: Supports automatic database updates and version tracking
- **Flexible Scanning**: Scan strings, buffers, and files for malware
- **Health Monitoring**: Built-in service readiness checks and connection verification
## Install ## Install
Installing `@push.rocks/smartantivirus` is straightforward. You'll need Node.js and npm installed on your machine: 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 ```bash
npm install @push.rocks/smartantivirus npm install @push.rocks/smartantivirus
@@ -26,41 +18,40 @@ npm install @push.rocks/smartantivirus
## Usage ## Usage
The package provides two main ways to use ClamAV: 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.
1. **Docker-based Usage** (Recommended): Uses `ClamAVManager` to automatically handle container lifecycle
2. **Direct Daemon Usage**: Uses `ClamAvService` to communicate with an existing ClamAV daemon
Below is a comprehensive guide on how to use both approaches.
### Docker-based Usage with ClamAVManager ### Docker-based Usage with ClamAVManager
The `ClamAVManager` class provides a high-level interface for managing ClamAV in Docker containers: 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 ```typescript
import { ClamAVManager } from '@push.rocks/smartantivirus'; import { ClamAVManager } from '@push.rocks/smartantivirus';
async function main() { async function main() {
// Create a new manager instance // Instantiate a ClamAVManager
const manager = new ClamAVManager(); const clamAvManager = new ClamAVManager();
// Start the ClamAV container // Start ClamAV Docker container
await manager.startContainer(); await clamAvManager.startContainer();
// Listen for log events // Listen for log events
manager.on('log', (event) => { clamAvManager.on('log', event => {
console.log(`[ClamAV ${event.type}] ${event.message}`); console.log(`ClamAV log (${event.type}): ${event.message}`);
}); });
// Get database information // Fetch and display database information
const dbInfo = await manager.getDatabaseInfo(); const dbInfo = await clamAvManager.getDatabaseInfo();
console.log('Database Info:', dbInfo); console.log('Database Information:', dbInfo);
// Update virus definitions // Update the virus database
await manager.updateDatabase(); await clamAvManager.updateDatabase();
// When done, stop the container // Stop the container when done
await manager.stopContainer(); await clamAvManager.stopContainer();
} }
main().catch(console.error); main().catch(console.error);
@@ -68,27 +59,26 @@ main().catch(console.error);
### Direct Daemon Usage with ClamAvService ### Direct Daemon Usage with ClamAvService
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. 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 ```typescript
import { ClamAvService } from '@push.rocks/smartantivirus'; import { ClamAvService } from '@push.rocks/smartantivirus';
async function main() { async function main() {
const clamService = new ClamAvService('127.0.0.1', 3310); // Replace with your ClamAV host and port const clamService = new ClamAvService('127.0.0.1', 3310);
// Verify connection to ClamAV // Verify connection to ClamAV
const isConnected = await clamService.verifyConnection(); const isConnected = await clamService.verifyConnection();
console.log(`Connection to ClamAV: ${isConnected ? 'successful' : 'failed'}`); console.log(`Connection to ClamAV: ${isConnected ? 'successful' : 'failed'}`);
if (!isConnected) { // Scan a test string
console.error('Could not connect to ClamAV daemon. Please check your configuration.'); const eicarTest = 'X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*';
return; const scanResult = await clamService.scanString(eicarTest);
} console.log('EICAR Test Result:', scanResult);
// 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);
} }
main().catch(console.error); main().catch(console.error);
@@ -96,184 +86,148 @@ main().catch(console.error);
### Streaming Scanning ### Streaming Scanning
The `ClamAvService` supports scanning both NodeJS streams and Web API streams using three specialized methods: `ClamAvService` provides methods to scan NodeJS and Web API streams. This is particularly useful for processing large files or data transferred over the network.
- `scanStream(stream: NodeJS.ReadableStream)`: Scans any NodeJS readable stream (files, network, etc.) #### Example: NodeJS Streaming
- `scanWebStream(webstream: ReadableStream)`: Scans a Web API ReadableStream
- `scanFileFromWebAsStream(url: string)`: Fetches and scans a file from a URL using NodeJS http/https
#### Example Usage
```typescript ```typescript
import { ClamAvService } from '@push.rocks/smartantivirus'; import { ClamAvService } from '@push.rocks/smartantivirus';
import { createReadStream } from 'fs'; import { createReadStream } from 'fs';
async function main() { async function main() {
const clamService = new ClamAvService('127.0.0.1', 3310); const clamService = new ClamAvService();
// Example 1: Scanning a local file stream (NodeJS) // Scan a local file stream
const fileStream = createReadStream('path/to/local/file'); const fileStream = createReadStream('path/to/suspicious/file');
const streamResult = await clamService.scanStream(fileStream); const fileScanResult = await clamService.scanStream(fileStream);
console.log('Stream Scan Result:', streamResult); console.log('File Stream Scan Result:', fileScanResult);
// Example 2: Scanning a web resource using NodeJS http/https // Scan a remote file by stream
const webResult = await clamService.scanFileFromWebAsStream('http://example.com/file'); const remoteFileScan = await clamService.scanFileFromWebAsStream('http://example.com/file');
console.log('Web Stream Scan Result:', webResult); console.log('Remote File Scan Result:', remoteFileScan);
}
// Example 3: Scanning a Web API ReadableStream main().catch(console.error);
const response = await fetch('http://example.com/file'); ```
if (response.body) {
const webStreamResult = await clamService.scanWebStream(response.body); #### Example: Web Stream (in Browser)
console.log('Web Stream API Scan Result:', webStreamResult);
```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); main().catch(console.error);
``` ```
**Breaking Down the Example:** ### Error Handling and Event Monitoring
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`. Both `ClamAVManager` and `ClamAvService` are designed with error handling features for robustness.
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.
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:
```typescript ```typescript
import { ClamAvService } from '@push.rocks/smartantivirus'; import { ClamAVManager } from '@push.rocks/smartantivirus';
async function scanBufferExample() { async function errorHandlingExample() {
const clamService = new ClamAvService(); const clamAvManager = new ClamAVManager();
// This buffer should represent the binary data you want to scan.
const buffer = Buffer.from('Sample buffer contents', 'utf8');
try { try {
const scanResult = await clamService.scanBuffer(buffer); await clamAvManager.startContainer();
console.log('Buffer Scan Result:', scanResult);
} catch (error) { // Listen for errors in logs
console.error('Error scanning buffer:', error); 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);
} }
} }
scanBufferExample(); errorHandlingExample().catch(console.error);
``` ```
**Explanation:** ### Advanced Usage and Configuration
- We create an instance of `ClamAvService`. #### Customize Container Settings
- A buffer is created and passed to the `scanBuffer` method, which scans the in-memory data for potential viruses.
### Error Handling and Debugging Customizing the Docker container setup is possible through class methods and properties:
Both `ClamAVManager` and `ClamAvService` provide comprehensive error handling:
```typescript ```typescript
try { const manager = new ClamAVManager();
// Using ClamAVManager console.log(`Container Name: ${manager.containerName}`); // Access default name
const manager = new ClamAVManager(); console.log(`Listening Port: ${manager.port}`); // Access default port
await manager.startContainer(); ```
// Listen for errors in logs #### Managing Logs
manager.on('log', (event) => {
if (event.type === 'error') {
console.error(`ClamAV Error: ${event.message}`);
}
});
// Using ClamAvService Capture and filter ClamAV logs for insights:
const service = new ClamAvService();
const scanResult = await service.scanString('Some suspicious string...'); ```typescript
console.log(`Infection Status: ${scanResult.isInfected ? 'Infected' : 'Clean'}`); const manager = new ClamAVManager();
if (scanResult.isInfected) { await manager.startContainer();
console.log(`Reason: ${scanResult.reason}`);
} const logs = manager.getLogs();
} catch (error) { const errorLogs = logs.filter(log => log.type === 'error');
console.error('An error occurred during the scanning process:', 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 ### 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 ```bash
npm run test 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
#### Container Configuration 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
The `ClamAVManager` supports customizing the Docker container:
```typescript
const manager = new ClamAVManager();
// Container properties are configurable
console.log(manager.containerName); // 'clamav-daemon'
console.log(manager.port); // 3310
```
#### Log Management
Access and process ClamAV logs:
```typescript
const manager = new ClamAVManager();
// Get all logs
const logs = manager.getLogs();
// Filter logs by type
const errorLogs = logs.filter(log => log.type === 'error');
const updateLogs = logs.filter(log => log.type === 'update');
```
#### Health Checks
Monitor ClamAV service health:
```typescript
const manager = new ClamAVManager();
// Service automatically checks readiness during initialization
await manager.startContainer(); // Includes readiness checks
// Get database status
const dbInfo = await manager.getDatabaseInfo();
console.log('Database Version:', dbInfo);
```
You can build upon these functionalities to implement advanced use cases such as:
- Automated virus scanning in CI/CD pipelines
- Real-time file monitoring in web applications
- Cloud-based malware detection services
- Integration with security information and event management (SIEM) systems
With the help of Node.js worker threads or external task queues like RabbitMQ, you can distribute scanning tasks efficiently within high-traffic environments.
## License and Legal Information
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](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.
### Trademarks
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.
### Company Information
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.

View File

@@ -1,4 +1,4 @@
import { expect, tap } from '../ts/plugins.js'; import { expect, tap } from '@push.rocks/tapbundle';
import type { ClamAVLogEvent } from '../ts/classes.clamav.manager.js'; import type { ClamAVLogEvent } from '../ts/classes.clamav.manager.js';
import { setupClamAV, cleanupClamAV, getManager } from './helpers/clamav.helper.js'; import { setupClamAV, cleanupClamAV, getManager } from './helpers/clamav.helper.js';

View File

@@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@push.rocks/smartantivirus', name: '@push.rocks/smartantivirus',
version: '1.3.0', version: '1.3.1',
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.'
} }