Skip to content

A comprehensive Node.js middleware and API server for code linting and bug detection, built on ESLint with SonarJS integration

Notifications You must be signed in to change notification settings

NashTech-Labs/nodejs-linter-extention

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Node.js Code Linter and Bug Detection Middleware

A comprehensive Node.js middleware and API server for code linting and bug detection, built on top of ESLint with enhanced capabilities for identifying potential security vulnerabilities and code quality issues.

Features

  • ESLint Integration: Leverages the power and flexibility of ESLint for core linting functionality
  • SonarJS Plugin: Includes SonarJS rules for advanced bug detection and code smell identification
  • Custom Security Rules: Additional custom rules for detecting:
    • Hardcoded credentials and sensitive data
    • Potential SQL injection vulnerabilities
    • Console statements in production code
  • Express Middleware: Easy integration with Express.js applications
  • Standalone API Server: Ready-to-use REST API for code analysis
  • Batch Processing: Support for analyzing multiple files or code snippets
  • Configurable Rules: Flexible rule configuration for different environments
  • Comprehensive Testing: Full test suite with Jest

Installation

npm install

Quick Start

As a Standalone API Server

npm start

The server will start on http://localhost:3000 (or the port specified in the PORT environment variable).

As Express Middleware

const express = require('express');
const { createLinterMiddleware } = require('./middleware');

const app = express();

// Add the linter middleware
app.use(createLinterMiddleware({
  production: process.env.NODE_ENV === 'production',
  browser: false
}));

// Use the linter in your routes
app.post('/analyze', async (req, res) => {
  const { code } = req.body;
  const result = await req.lintCode(code);
  res.json(result);
});

API Endpoints

Health Check

GET /health

Returns the health status of the API.

Lint Code

POST /lint
Content-Type: application/json

{
  "code": "const message = 'Hello, World!'; console.log(message);",
  "filename": "example.js"
}

Lint with Custom Options

POST /lint/custom
Content-Type: application/json

{
  "code": "var x = 1;",
  "filename": "example.js",
  "options": {
    "rules": {
      "no-var": "error"
    },
    "env": {
      "browser": true
    }
  }
}

Batch Lint Multiple Snippets

POST /lint/batch
Content-Type: application/json

{
  "codeSnippets": [
    { "code": "const a = 1;", "filename": "file1.js" },
    { "code": "const b = 2;", "filename": "file2.js" }
  ]
}

Upload and Lint Files

POST /lint/files
Content-Type: multipart/form-data

files: [file1.js, file2.js, ...]

Get Available Rules

GET /rules

Returns a list of all available linting rules with their descriptions and categories.

Response Format

All linting endpoints return a standardized response format:

{
  "success": true,
  "summary": {
    "totalFiles": 1,
    "totalErrors": 2,
    "totalWarnings": 1,
    "totalIssues": 3
  },
  "results": [
    {
      "filePath": "example.js",
      "errorCount": 2,
      "warningCount": 1,
      "issues": [
        {
          "line": 1,
          "column": 7,
          "severity": "error",
          "message": "'undefinedVar' is not defined.",
          "ruleId": "no-undef",
          "category": "bug-detection"
        }
      ]
    }
  ]
}

Custom Rules

no-console-in-production

Detects console statements that might be left in production code.

Configuration:

{
  "custom/no-console-in-production": ["error", { "allow": ["warn", "error"] }]
}

no-hardcoded-credentials

Identifies potential hardcoded passwords, API keys, and other sensitive data.

Detects:

  • Variables with suspicious names (password, apiKey, secret, etc.)
  • Base64-encoded strings that might be credentials
  • Object properties containing sensitive data

no-sql-injection

Identifies potential SQL injection vulnerabilities in string concatenation and template literals.

Detects:

  • String concatenation with SQL keywords and variables
  • Template literals containing SQL queries with interpolated variables

Rule Categories

Rules are automatically categorized into:

  • bug-detection: Rules that identify potential bugs and runtime errors
  • code-smell: Rules that identify code quality issues and maintainability problems
  • style: Rules that enforce coding style and formatting
  • security: Custom rules that identify potential security vulnerabilities

Configuration Options

Middleware Options

const options = {
  production: false,        // Enable production-specific rules
  browser: false,          // Enable browser environment
  rules: {                 // Override or add custom rules
    "no-console": "warn",
    "custom/no-hardcoded-credentials": "error"
  }
};

Environment Variables

  • PORT: Server port (default: 3000)
  • HOST: Server host (default: 0.0.0.0)
  • NODE_ENV: Environment mode (affects rule strictness)

Testing

Run the test suite:

npm test

Run tests in watch mode:

npm run test:watch

Integration Examples

Express.js Application

const express = require('express');
const { createLinterRoute } = require('./middleware');

const app = express();
app.use(express.json());

// Add linting endpoint
app.post('/lint', createLinterRoute({
  production: true,
  rules: {
    'no-console': 'error'
  }
}));

app.listen(3000);

Custom Linter Instance

const CodeLinter = require('./linter');

const linter = new CodeLinter({
  baseConfig: {
    env: { node: true, browser: true },
    rules: {
      'no-var': 'error',
      'prefer-const': 'warn'
    }
  }
});

async function analyzeCode(code) {
  const result = await linter.lintCode(code);
  console.log(`Found ${result.summary.totalIssues} issues`);
  return result;
}

CI/CD Integration

const { CodeLinter } = require('./middleware');
const fs = require('fs').promises;

async function lintProject(directory) {
  const linter = new CodeLinter();
  const files = await fs.readdir(directory);
  const jsFiles = files.filter(file => file.endsWith('.js'));
  
  const result = await linter.lintFiles(jsFiles.map(file => `${directory}/${file}`));
  
  if (result.summary.totalErrors > 0) {
    console.error('Linting failed with errors');
    process.exit(1);
  }
  
  console.log('Linting passed');
}

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

License

ISC License

Support

For issues and questions, please create an issue in the repository or contact the development team.

About

A comprehensive Node.js middleware and API server for code linting and bug detection, built on ESLint with SonarJS integration

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published