Skip to content

Commit

Permalink
Some code cleanup/linting
Browse files Browse the repository at this point in the history
  • Loading branch information
kylefarris committed Oct 21, 2024
1 parent 82984ef commit a3191db
Show file tree
Hide file tree
Showing 13 changed files with 1,143 additions and 922 deletions.
62 changes: 39 additions & 23 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,50 +1,63 @@
{
"parser": "babel-eslint",
"env": {
"browser": false,
"node": true,
"es6": true
"es6": true,
"mocha": true
},
"extends": ["airbnb-base", "plugin:prettier/recommended", "plugin:chai-friendly/recommended"],
"extends": [
"airbnb-base",
"plugin:prettier/recommended",
"plugin:chai-friendly/recommended",
"plugin:jsdoc/recommended"
],
"plugins": ["prettier", "chai-friendly", "jsdoc"],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parserOptions": {
"ecmaVersion": 2018,
"ecmaVersion": 2022,
"sourceType": "module"
},
"rules": {
"no-console": "off",
"no-param-reassign": "off",
"prettier/prettier": "error",
"no-underscore-dangle": "off",
"class-methods-use-this": "off",
"require-jsdoc": "error",
"valid-jsdoc": "off",
"global-require": "warn",
"lines-between-class-members": "off",
"no-underscore-dangle": "off",
"no-promise-executor-return": "off",
"jsdoc/check-alignment": 1, // Recommended
"jsdoc/check-indentation": 1,
"jsdoc/check-param-names": 1, // Recommended
"jsdoc/check-syntax": 1,
"jsdoc/check-tag-names": [
"warn",
{
"definedTags": ["typicalname", "route", "authentication", "bodyparam", "routeparam"]
"definedTags": [
"typicalname",
"route",
"authentication",
"bodyparam",
"routeparam",
"queryparam"
]
}
],
"jsdoc/check-types": 1, // Recommended
"jsdoc/implements-on-classes": 1, // Recommended
"jsdoc/match-description": 1,
"jsdoc/newline-after-description": 1, // Recommended
"jsdoc/no-undefined-types": [
"warn",
"jsdoc/tag-lines": [
"error",
"never",
{
"definedTypes": ["DELETE", "POST", "PATCH", "PUT", "GET"]
"startLines": 1
}
], // Recommended
],
"jsdoc/require-description": 1,
"jsdoc/require-hyphen-before-param-description": 1,
"jsdoc/require-jsdoc": 1, // Recommended
Expand All @@ -56,16 +69,19 @@
"jsdoc/require-returns-check": 1, // Recommended
"jsdoc/require-returns-description": 1, // Recommended
"jsdoc/require-returns-type": 1, // Recommended
"jsdoc/valid-types": 1 // Recommended
},
"settings": {
"jsdoc": {
"plugins": ["jsdoc-route-plugin"],
"structuredTags": {
"route": {
"type": ["DELETE", "POST", "PATCH", "PUT", "GET"]
}
}
}
"jsdoc/valid-types": 1, // Recommended
"jsdoc/no-defaults": 0, // Recommended
"jsdoc/check-access": 1, // Recommended
"jsdoc/check-property-names": 1, // Recommended
"jsdoc/check-values": 1, // Recommended
"jsdoc/empty-tags": 1, // Recommended
"jsdoc/multiline-blocks": 1, // Recommended
"jsdoc/no-multi-asterisks": 1, // Recommended
"jsdoc/require-property": 1, // Recommended
"jsdoc/require-property-description": 1, // Recommended
"jsdoc/require-property-name": 1, // Recommended
"jsdoc/require-property-type": 1, // Recommended
"jsdoc/require-yields": 1, // Recommended
"jsdoc/require-yields-check": 1 // Recommended
}
}
}
2 changes: 1 addition & 1 deletion examples/basic_async_await.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const config = {
};

// Initialize the clamscan module
const NodeClam = require('../index.js'); // Offically: require('clamscan');
const NodeClam = require('../index'); // Offically: require('clamscan');

(async () => {
const clamscan = await new NodeClam().init(config);
Expand Down
2 changes: 1 addition & 1 deletion examples/passthrough.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const testUrl = normalFileUrl;
// const testUrl = largeFileUrl;

// Initialize the clamscan module
const NodeClam = require('../index.js'); // Offically: require('clamscan');
const NodeClam = require('../index'); // Offically: require('clamscan');

/**
* Removes whatever file was passed-through during the scan.
Expand Down
2 changes: 1 addition & 1 deletion examples/pipe2s3.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ async function pipe2s3(req, res, opts = {}) {
}

// If the scan threw an error...
else if (scanResult instanceof Error) {
if (scanResult instanceof Error) {
if ('data' in scanResult && scanResult.data.is_infected) {
logError('Stream contained virus(es):', scanResult.data.viruses);
}
Expand Down
9 changes: 3 additions & 6 deletions examples/stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const fakeVirusUrl = 'https://www.eicar.org/download/eicar-com-2/?wpdmdl=8842&re
const testUrl = fakeVirusUrl;

// Initialize the clamscan module
const NodeClam = require('../index.js'); // Offically: require('clamscan');
const NodeClam = require('../index'); // Offically: require('clamscan');

/**
* Actually run the test.
Expand All @@ -19,19 +19,16 @@ async function test() {
bypassTest: true,
host: 'localhost',
port: 3310,
//socket: '/var/run/clamd.scan/clamd.sock',
// socket: '/var/run/clamd.scan/clamd.sock',
},
});

// Fetch fake Eicar virus file and pipe it through to our scan screeam
const passthrough = new PassThrough();
axios.get(
testUrl, { responseType: 'stream' }
).then((response) => {
axios.get(testUrl, { responseType: 'stream' }).then((response) => {
response.data.pipe(passthrough);
});


try {
const { isInfected, viruses } = await clamscan.scanStream(passthrough);

Expand Down
2 changes: 1 addition & 1 deletion examples/version.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Initialize the clamscan module
const NodeClam = require('../index.js'); // Offically: require('clamscan');
const NodeClam = require('../index'); // Offically: require('clamscan');

const ClamScan = new NodeClam().init({
debugMode: false,
Expand Down
75 changes: 43 additions & 32 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ const { promisify } = require('util');
const { execFile } = require('child_process');
const { PassThrough, Transform, Readable } = require('stream');
const { Socket } = require('dgram');
const fsPromises = require('fs').promises;
const NodeClamError = require('./lib/NodeClamError');
const NodeClamTransform = require('./lib/NodeClamTransform');
const getFiles = require('./lib/getFiles');

// Re-named `fs` promise methods to prevent conflicts while keeping short names
const fsPromises = require('fs').promises;
const fsAccess = fsPromises.access;
const fsReadfile = fsPromises.readFile;
const fsReaddir = fsPromises.readdir;
Expand All @@ -33,14 +33,14 @@ const cpExecFile = promisify(execFile);
/**
* NodeClam class definition.
*
* @class
* @public
* @typicalname NodeClam
*/
class NodeClam {
/**
* This sets up all the defaults of the instance but does not
* necessarily return an initialized instance. Use `.init` for that.
*
* @constructor
*/
constructor() {
this.initialized = false;
Expand Down Expand Up @@ -111,7 +111,7 @@ class NodeClam {
* @param {boolean} [options.clamdscan.bypassTest=false] - If true, check to see if socket is avaliable
* @param {boolean} [options.clamdscan.tls=false] - If true, connect to a TLS-Termination proxy in front of ClamAV
* @param {object} [options.preference='clamdscan'] - If preferred binary is found and active, it will be used by default
* @param {Function} [cb] - Callback method. Prototype: `(err, <instance of NodeClam>)`
* @param {Function} [cb = null] - Callback method. Prototype: `(err, <instance of NodeClam>)`
* @returns {Promise<object>} An initated instance of NodeClam
* @example
* const NodeClam = require('clamscan');
Expand Down Expand Up @@ -144,7 +144,7 @@ class NodeClam {
* preference: 'clamdscan'
});
*/
async init(options = {}, cb) {
async init(options = {}, cb = null) {
let hasCb = false;

// Verify second param, if supplied, is a function
Expand Down Expand Up @@ -357,11 +357,11 @@ class NodeClam {
* Allows one to create a new instances of clamscan with new options.
*
* @public
* @param {object} [options] - Same options as the `init` method
* @param {Function} [cb] - What to do after reset (repsponds with reset instance of NodeClam)
* @param {object} [options = {}] - Same options as the `init` method
* @param {Function} [cb = null] - What to do after reset (repsponds with reset instance of NodeClam)
* @returns {Promise<object>} A reset instance of NodeClam
*/
reset(options = {}, cb) {
reset(options = {}, cb = null) {
let hasCb = false;

// Verify second param, if supplied, is a function
Expand Down Expand Up @@ -686,11 +686,13 @@ class NodeClam {

/**
* Alias `ping()` for backwards-compatibility with older package versions.
*
*
* @private
* @alias ping
* @param {Function} [cb] - Callback function
* @returns {Promise<object>} A copy of the Socket/TCP client
*/
_ping(cb) {
_ping(cb = null) {
return this.ping(cb);
}

Expand Down Expand Up @@ -737,11 +739,15 @@ class NodeClam {
}

// Parse out the name of the virus(es) found...
const viruses = Array.from(new Set(result
// eslint-disable-next-line no-control-regex
.split(/(\u0000|[\r\n])/)
.map((v) => (/:\s+(.+)FOUND$/gm.test(v) ? v.replace(/(.+:\s+)(.+)FOUND/gm, '$2').trim() : null))
.filter((v) => !!v)));
const viruses = Array.from(
new Set(
result
// eslint-disable-next-line no-control-regex
.split(/(\u0000|[\r\n])/)
.map((v) => (/:\s+(.+)FOUND$/gm.test(v) ? v.replace(/(.+:\s+)(.+)FOUND/gm, '$2').trim() : null))
.filter((v) => !!v)
)
);

return { isInfected: true, viruses, file, resultString: result, timeout };
}
Expand Down Expand Up @@ -878,7 +884,7 @@ class NodeClam {
*
* @public
* @param {string} file - Path to the file to check
* @param {Function} [cb] - What to do after the scan
* @param {Function} [cb = null] - What to do after the scan
* @returns {Promise<object>} Object like: `{ file: String, isInfected: Boolean, viruses: Array }`
* @example
* // Callback Example
Expand All @@ -901,7 +907,7 @@ class NodeClam {
* // Async/Await Example
* const {file, isInfected, viruses} = await clamscan.isInfected('/a/picture/for_example.jpg');
*/
isInfected(file = '', cb) {
isInfected(file = '', cb = null) {
const self = this;
let hasCb = false;

Expand Down Expand Up @@ -1326,7 +1332,7 @@ class NodeClam {
else if (
typeof result === 'object' &&
'isInfected' in result &&
result.isInfected === true
result.isInfected === false
) {
this.emit('timeout');
handleError(null, false, result);
Expand Down Expand Up @@ -1402,7 +1408,7 @@ class NodeClam {
});
}

/**
/**
* Quick check to see if the remote/local socket is working. Callback/Resolve
* response is an instance to a ClamAV socket client.
*
Expand Down Expand Up @@ -1578,11 +1584,11 @@ class NodeClam {
.forEach((result) => {
if (/^[-]+$/.test(result)) return;

let path = result.match(/^(.*): /);
if (path && path.length > 0) {
path = path[1];
} else {
path = '<Unknown File Path!>';
let path = '<Unknown File Path!>';
const pathMatch = result.match(/^(.*): /);
if (pathMatch && pathMatch.length > 0) {
// eslint-disable-next-line prefer-destructuring
path = pathMatch[1];
}

// eslint-disable-next-line no-control-regex
Expand Down Expand Up @@ -2101,10 +2107,14 @@ class NodeClam {
// If the path is infected, build out list of infected files
let badFiles = [];
if (isInfected) {
badFiles = Array.from(new Set(result.resultString.split(os.EOL).map(v => {
const [file, virus] = v.replace(/ FOUND$/, '').split(': ');
return { file, virus };
})));
badFiles = Array.from(
new Set(
result.resultString.split(os.EOL).map((v) => {
const [file, virus] = v.replace(/ FOUND$/, '').split(': ');
return { file, virus };
})
)
);
}

// Having a list of good files could use up all available memory if a big enough
Expand All @@ -2115,7 +2125,8 @@ class NodeClam {
const numGoodFiles = (await getFiles(path)).length - badFiles.length;

if (this.settings.debugMode) console.log(`${this.debugLabel}: Bad Files: `, badFiles);
if (this.settings.debugMode) console.log(`${this.debugLabel}: # Good Files: `, numGoodFiles);
if (this.settings.debugMode)
console.log(`${this.debugLabel}: # Good Files: `, numGoodFiles);

return hasCb
? endCb(null, goodFiles, badFiles, viruses, numGoodFiles)
Expand Down Expand Up @@ -2265,14 +2276,14 @@ class NodeClam {
// stream.pipe(transform).pipe(socket);
transform
// Writing data into ClamAV socket
.on('data', data => {
.on('data', (data) => {
socket.write(data);
})
// The transform stream has dried up
.on('end', () => {
if (this.settings.debugMode) console.log(`${this.debugLabel}: The transform stream has ended.`);
})
.on('error', err => {
.on('error', (err) => {
console.error(`${this.debugLabel}: Error emitted from transform stream: `, err);
socket.end();
return hasCb ? cb(err, null) : reject(err);
Expand All @@ -2281,7 +2292,7 @@ class NodeClam {
// Setup the listeners for the stream
stream
// The stream is writting data into transform stream
.on('data', data => {
.on('data', (data) => {
transform.write(data);
})
// The stream has dried up
Expand Down
Loading

0 comments on commit a3191db

Please sign in to comment.