### Install njsscan Source: https://context7.com/ajinabraham/njsscan/llms.txt Install njsscan using pip for Python 3.7+ environments. ```bash pip install njsscan ``` -------------------------------- ### GitLab CI/CD Integration for njsscan Source: https://github.com/ajinabraham/njsscan/blob/master/README.md Set up njsscan in your GitLab CI/CD pipeline. This configuration uses a Python image, installs njsscan, and runs a scan on the current directory. ```yaml stages: - test njsscan: image: python before_script: - pip3 install --upgrade njsscan script: - njsscan . ``` -------------------------------- ### Travis CI Integration for njsscan Source: https://github.com/ajinabraham/njsscan/blob/master/README.md Configure njsscan to run in a Travis CI environment. It installs the njsscan package and executes a scan. ```yaml language: python install: - pip3 install --upgrade njsscan script: - njsscan . ``` -------------------------------- ### Circle CI Integration for njsscan Source: https://github.com/ajinabraham/njsscan/blob/master/README.md Integrate njsscan into Circle CI by defining a job that uses a Python Docker image, installs njsscan, and runs the scan. ```yaml version: 2.1 jobs: njsscan: docker: - image: cimg/python:3.9.6 steps: - checkout - run: name: Install njsscan command: pip install --upgrade njsscan - run: name: njsscan check command: njsscan . ``` -------------------------------- ### Run njsscan with Docker (Prebuilt Image) Source: https://github.com/ajinabraham/njsscan/blob/master/README.md Use the prebuilt njsscan Docker image from DockerHub. Mount your source code directory to `/src` within the container and run the scan. ```bash docker pull opensecurity/njsscan docker run -v /path-to-source-dir:/src opensecurity/njsscan /src ``` -------------------------------- ### Build and Run njsscan Locally with Docker Source: https://github.com/ajinabraham/njsscan/blob/master/README.md Build the njsscan Docker image locally from the source and then run it. Mount your source code directory to `/src` within the container. ```bash docker build -t njsscan . docker run -v /path-to-source-dir:/src njsscan /src ``` -------------------------------- ### Docker Usage for njsscan Source: https://context7.com/ajinabraham/njsscan/llms.txt Demonstrates how to run njsscan using Docker, including pulling the image, scanning local directories, and building the image locally. ```bash # Pull prebuilt image from DockerHub docker pull opensecurity/njsscan # Scan a local directory docker run -v /path/to/source:/src opensecurity/njsscan /src # Scan with JSON output docker run -v /path/to/source:/src opensecurity/njsscan --json /src # Build locally docker build -t njsscan . docker run -v /path/to/source:/src njsscan /src ``` -------------------------------- ### HTML Output Format Source: https://context7.com/ajinabraham/njsscan/llms.txt Generate HTML formatted reports for human-readable vulnerability documentation. Use the --html flag and specify an output file with -o. ```bash # Save HTML report njsscan --html -o report.html ./src ``` -------------------------------- ### SonarQube Output Format Source: https://context7.com/ajinabraham/njsscan/llms.txt Generate SonarQube-compatible JSON for integration with SonarQube quality gates. Use the --sonarqube flag. ```bash # Output SonarQube format to stdout njsscan --sonarqube ./src ``` ```bash # Save for SonarQube import njsscan --sonarqube -o sonarqube-report.json ./src ``` ```json { "issues": [{ "engineId": "njsscan", "ruleId": "express_xss", "type": "VULNERABILITY", "severity": "CRITICAL", "primaryLocation": { "message": "Untrusted User Input in Response will result in Reflected XSS.", "filePath": "routes/user.js", "textRange": {"startLine": 15, "endLine": 16, "startColumn": 5, "endColumn": 45} } }] } ``` -------------------------------- ### Configuration File (.njsscan) Source: https://context7.com/ajinabraham/njsscan/llms.txt Configure scan behavior through a YAML configuration file placed in the project root. This file allows customization of file extensions, ignored paths, disabled rules, and severity filtering. ```APIDOC ## Configuration File (.njsscan) ### Description Configure scan behavior through a YAML configuration file placed in the project root. The `.njsscan` file allows customization of file extensions to scan, paths to ignore, rules to disable, and severity filtering. ### File Structure ```yaml --- nodjs-extensions: - .js - .mjs - .cjs template-extensions: - .html - .hbs - .ejs - .pug - .vue ignore-filenames: - jquery.js - bootstrap.js - vendor.js ignore-paths: - __MACOSX - node_modules - bower_components - dist - build - test - spec ignore-extensions: - .min.js - .bundle.js ignore-rules: - regex_injection_dos - pug_jade_template severity-filter: - WARNING - ERROR ``` ``` -------------------------------- ### CLI Basic Scan Source: https://context7.com/ajinabraham/njsscan/llms.txt Run a security scan on Node.js files or directories from the command line. Outputs findings in a formatted table. ```bash # Scan a single file njsscan app.js ``` ```bash # Scan entire directory njsscan ./src ``` ```bash # Scan multiple paths njsscan ./routes ./controllers ./models ``` -------------------------------- ### Configure Scan Behavior with YAML Source: https://context7.com/ajinabraham/njsscan/llms.txt Define file extensions, ignore paths, and severity filters in a .njsscan configuration file. ```yaml --- - nodejs-extensions: - .js - .mjs - .cjs template-extensions: - .html - .hbs - .ejs - .pug - .vue ignore-filenames: - jquery.js - bootstrap.js - vendor.js ignore-paths: - __MACOSX - node_modules - bower_components - dist - build - test - spec ignore-extensions: - .min.js - .bundle.js ignore-rules: - regex_injection_dos - pug_jade_template severity-filter: - WARNING - ERROR ``` -------------------------------- ### Configure njsscan with YAML Source: https://github.com/ajinabraham/njsscan/blob/master/README.md Define scan parameters such as file extensions, ignored paths, and severity filters in a .njsscan configuration file. ```yaml --- - nodejs-extensions: - .js template-extensions: - .new - .hbs - '' ignore-filenames: - skip.js ignore-paths: - __MACOSX - skip_dir - node_modules ignore-extensions: - .jsx ignore-rules: - regex_injection_dos - pug_jade_template severity-filter: - WARNING - ERROR ``` -------------------------------- ### Check for Missing Security Controls Source: https://context7.com/ajinabraham/njsscan/llms.txt Enable detection of missing security best practices like CSRF protection and helmet headers via CLI or Python. ```bash # Enable missing controls check via CLI njsscan --missing-controls ./src ``` ```python # Via Python API from njsscan.njsscan import NJSScan scanner = NJSScan(['/path/to/project'], json=True, check_controls=True) results = scanner.scan() ``` -------------------------------- ### Use njsscan Python API Source: https://github.com/ajinabraham/njsscan/blob/master/README.md Programmatically scan source files by importing the NJSScan class. The scan results are returned as a dictionary. ```python >>> from njsscan.njsscan import NJSScan >>> node_source = '/node_source/true_positives/sqli_node.js' >>> scanner = NJSScan([node_source], json=True, check_controls=False) >>> scanner.scan() { 'templates': {}, 'nodejs': { 'node_sqli_injection': { 'files': [{ 'file_path': '/node_source/true_positives/sqli_node.js', 'match_position': (1, 24), 'match_lines': (4, 11), 'match_string': 'var employeeId = req.foo;\n\nvar sql = "SELECT * FROM trn_employee WHERE employee_id = " + employeeId;\n\n\n\nconnection.query(sql, function (error, results, fields) {\n\n if (error) {\n\n throw error;\n\n }\n\n console.log(results);' }], 'metadata': { 'owasp': 'A1: Injection', 'cwe': "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", 'description': 'Untrusted input concatinated with raw SQL query can result in SQL Injection.', 'severity': 'ERROR' } } }, 'errors': [] } ``` -------------------------------- ### SARIF Output Format Source: https://context7.com/ajinabraham/njsscan/llms.txt Generate SARIF 2.1.0 formatted output for GitHub Code Scanning and other SARIF-compatible tools. Use the --sarif flag. ```bash # Output SARIF to stdout njsscan --sarif ./src ``` ```bash # Save SARIF for GitHub Code Scanning njsscan --sarif -o results.sarif ./src ``` -------------------------------- ### JavaScript Data and Underscore.js Rendering Source: https://github.com/ajinabraham/njsscan/blob/master/tests/assets/templates/true_negatives/underscore_template.html Prepares an array of data objects and uses Underscore.js's template function to render an HTML template. The rendered HTML is then injected into a DOM element with the ID 'target'. Make sure the template ID '#usageList' exists in your HTML. ```javascript var items = [ {name:"Alexander"}, {name:"Barklay"}, {name:"Chester"}, {name:"Domingo"}, {name:"Edward"}, {name:"..."}, {name:"Yolando"}, {name:"Zachary"} ]; var template = $("#usageList").html(); $("#target").html(_.template(template,{items:items})); ``` -------------------------------- ### Run njsscan via CLI Source: https://github.com/ajinabraham/njsscan/blob/master/README.md Execute a scan on a specific JavaScript file using the command line interface. ```bash $ njsscan test.js ``` -------------------------------- ### JSON Output Format Source: https://context7.com/ajinabraham/njsscan/llms.txt Export scan results as JSON for programmatic processing. Use the --json flag and optionally specify an output file with -o. ```bash # Output JSON to stdout njsscan --json ./src ``` ```bash # Save JSON to file njsscan --json -o results.json ./src ``` ```json { "nodejs": { "node_sqli_injection": { "files": [{ "file_path": "/src/db.js", "match_position": [1, 24], "match_lines": [4, 11], "match_string": "var sql = \"SELECT * FROM users WHERE id = \" + userId;" }], "metadata": { "owasp": "A1: Injection", "cwe": "CWE-89: SQL Injection", "description": "Untrusted input concatenated with raw SQL query can result in SQL Injection.", "severity": "ERROR" } } }, "templates": {}, "errors": [], "njsscan_version": "0.4.3" } ``` -------------------------------- ### GitLab CI/CD Integration for njsscan Source: https://context7.com/ajinabraham/njsscan/llms.txt Adds njsscan to a GitLab CI/CD pipeline using a Python Docker image for security testing. ```yaml # .gitlab-ci.yml stages: - test njsscan: image: python before_script: - pip3 install --upgrade njsscan script: - njsscan . ``` -------------------------------- ### GitHub Actions Workflow for SARIF Output Source: https://context7.com/ajinabraham/njsscan/llms.txt Configures a GitHub Actions workflow to generate SARIF output from njsscan and upload it to GitHub Security for integrated vulnerability tracking. ```yaml # .github/workflows/njsscan_sarif.yml name: njsscan sarif on: push: branches: [master, main] pull_request: branches: [master, main] jobs: njsscan: runs-on: ubuntu-latest name: njsscan code scanning steps: - name: Checkout the code uses: actions/checkout@v4.2.2 - uses: actions/setup-python@v5.3.0 with: python-version: '3.12' - name: nodejsscan scan id: njsscan uses: ajinabraham/njsscan-action@master with: args: '. --sarif --output results.sarif || true' - name: Upload njsscan report uses: github/codeql-action/upload-sarif@v3 with: sarif_file: results.sarif ``` -------------------------------- ### GitHub Actions Workflow for njsscan Source: https://context7.com/ajinabraham/njsscan/llms.txt Integrates njsscan into a GitHub Actions workflow for automated security scanning on push and pull requests. ```yaml name: njsscan on: push: branches: [master, main] pull_request: branches: [master, main] jobs: njsscan: runs-on: ubuntu-latest name: njsscan check steps: - name: Checkout the code uses: actions/checkout@v4.2.2 - uses: actions/setup-python@v5.3.0 with: python-version: '3.12' - name: nodejsscan scan id: njsscan uses: ajinabraham/njsscan-action@master with: args: '.' ``` -------------------------------- ### GitHub Action for njsscan Source: https://github.com/ajinabraham/njsscan/blob/master/README.md Integrate njsscan into your GitHub Actions workflow by adding this YAML configuration. Ensure Python 3.12 is set up and the njsscan-action is used. ```yaml name: njsscan on: push: branches: [ master, main ] pull_request: branches: [ master, main ] jobs: njsscan: runs-on: ubuntu-latest name: njsscan check steps: - name: Checkout the code uses: actions/checkout@v4.2.2 - uses: actions/setup-python@v5.3.0 with: python-version: '3.12' - name: nodejsscan scan id: njsscan uses: ajinabraham/njsscan-action@master with: args: '.' ``` -------------------------------- ### GitHub Code Scanning Integration with SARIF Source: https://github.com/ajinabraham/njsscan/blob/master/README.md Configure GitHub Actions to generate and upload SARIF reports for code scanning. The `|| true` ensures the workflow continues even if njsscan finds issues. ```yaml name: njsscan sarif on: push: branches: [ master, main ] pull_request: branches: [ master, main ] jobs: njsscan: runs-on: ubuntu-latest name: njsscan code scanning steps: - name: Checkout the code uses: actions/checkout@v4.2.2 - uses: actions/setup-python@v5.3.0 with: python-version: '3.12' - name: nodejsscan scan id: njsscan uses: ajinabraham/njsscan-action@master with: args: '. --sarif --output results.sarif || true' - name: Upload njsscan report uses: github/codeql-action/upload-sarif@v3 with: sarif_file: results.sarif ``` -------------------------------- ### Perform Programmatic Scans with Python API Source: https://context7.com/ajinabraham/njsscan/llms.txt Use the NJSScan class to execute scans and process results. The scan method returns a dictionary containing findings for Node.js and templates. ```python from njsscan.njsscan import NJSScan # Basic scan with default settings paths = ['/path/to/node/project'] scanner = NJSScan(paths, json=True, check_controls=False) results = scanner.scan() # Access scan results for rule_id, findings in results['nodejs'].items(): print(f"Rule: {rule_id}") print(f"Severity: {findings['metadata']['severity']}") print(f"CWE: {findings['metadata']['cwe']}") print(f"Description: {findings['metadata']['description']}") for file_match in findings['files']: print(f" File: {file_match['file_path']}") print(f" Lines: {file_match['match_lines']}") print(f" Code: {file_match['match_string']}") # Scan with custom config file scanner = NJSScan( ['/path/to/project'], json=True, check_controls=True, # Enable missing security controls check config='/path/to/.njsscan' ) results = scanner.scan() ``` -------------------------------- ### Manage CI/CD Exit Codes Source: https://context7.com/ajinabraham/njsscan/llms.txt Control pipeline failure behavior based on finding severity using exit codes. ```bash # Exit 1 on ERROR findings only (default) njsscan ./src echo $? # 0 if no errors, 1 if errors found # Exit 1 on WARNING or ERROR findings njsscan --exit-warning ./src echo $? # 0 if clean, 1 if warnings or errors found # Use in CI/CD pipeline njsscan --json -o results.json ./src || exit 1 ``` -------------------------------- ### Python API - NJSScan Class Source: https://context7.com/ajinabraham/njsscan/llms.txt Use the NJSScan class for programmatic scanning within Python applications. It accepts paths, JSON output flag, missing controls check flag, and an optional config file path. The scan() method returns a dictionary with 'nodejs', 'templates', and 'errors' keys. ```APIDOC ## Python API - NJSScan Class ### Description Use the NJSScan class for programmatic scanning within Python applications. ### Method `NJSScan(paths, json=False, check_controls=False, config=None)` ### Parameters #### Path Parameters - **paths** (list[str]) - Required - A list of paths to scan. - **json** (bool) - Optional - If True, output results in JSON format. - **check_controls** (bool) - Optional - If True, enable missing security controls check. - **config** (str) - Optional - Path to a custom configuration file. ### Method `scan()` ### Description Executes the scan and returns the results. ### Response #### Success Response (dict) - **nodejs** (dict) - Findings related to Node.js code. - **templates** (dict) - Findings related to template files. - **errors** (list) - A list of errors encountered during the scan. ### Request Example ```python from njsscan.njsscan import NJSScan paths = ['/path/to/node/project'] scanner = NJSScan(paths, json=True, check_controls=False) results = scanner.scan() ``` ### Response Example ```json { "templates": {}, "nodejs": { "node_sqli_injection": { "files": [{ "file_path": "/src/sqli_node.js", "match_position": [1, 24], "match_lines": [4, 11], "match_string": "var sql = \"SELECT * FROM users...\"" }], "metadata": { "owasp": "A1: Injection", "cwe": "CWE-89: SQL Injection", "description": "Untrusted input concatenated with raw SQL query.", "severity": "ERROR" } } }, "errors": [] } ``` ``` -------------------------------- ### njsscan Security Rule Categories Source: https://context7.com/ajinabraham/njsscan/llms.txt Lists common security rule categories detected by njsscan, covering OWASP Top 10 vulnerabilities and specific Node.js security concerns. ```bash # Rule categories detected: # - SQL Injection (MySQL, PostgreSQL, MSSQL, Oracle, Knex, Sequelize) # - NoSQL Injection (MongoDB) # - XSS (Express responses, template engines) # - Command Injection (exec, spawn, shelljs) # - Path Traversal (file operations, archive extraction) # - SSRF (HTTP clients, Puppeteer, Playwright, wkhtmltopdf) # - XXE (XML parsers, expat, sax) # - Insecure Cryptography (weak algorithms, timing attacks, TLS config) # - JWT Vulnerabilities (hardcoded secrets, none algorithm) # - Open Redirect # - Electron.js Security (nodeIntegration, webSecurity) # - Template Injection (Handlebars, Mustache, Pug, EJS, Vue) # - Missing Security Headers (helmet.js checks) # - Insecure Cookie Configuration # - ReDoS (regex denial of service) ``` -------------------------------- ### Unescape HTML entities using underscore Source: https://github.com/ajinabraham/njsscan/blob/master/tests/assets/templates/true_positives/underscore.html Converts HTML entities like < and > back into their literal characters. Requires the underscore library to be available in the environment. ```javascript var escapedStr = "<html>topjavatutorial.com</html>"; var unescapedStr = _.unescape(escapedStr); console.log(unescapedStr); ``` -------------------------------- ### Missing Security Controls Check Source: https://context7.com/ajinabraham/njsscan/llms.txt Enable detection of missing security controls like CSRF protection, rate limiting, and helmet headers using the `--missing-controls` flag or the `check_controls=True` parameter in the Python API. ```APIDOC ## Missing Security Controls Check ### Description Enable detection of missing security controls like CSRF protection, rate limiting, and helmet headers. The `--missing-controls` flag checks for the absence of security best practices including anti-CSRF tokens, rate limiting middleware, and all helmet.js security headers. ### CLI Usage ```bash # Enable missing controls check via CLI njsscan --missing-controls ./src ``` ### Python API Usage ```python from njsscan.njsscan import NJSScan scanner = NJSScan(['/path/to/project'], json=True, check_controls=True) results = scanner.scan() ``` ### Detected Controls - **anti_csrf_control**: CSRF protection not found - **rate_limit_control**: Rate limiting not implemented - **helmet_header_csp**: Content-Security-Policy not set - **helmet_header_hsts**: Strict-Transport-Security not set - **helmet_header_nosniff**: X-Content-Type-Options not set - **helmet_header_xss_filter**: X-XSS-Protection not set - **helmet_header_frame_guard**: X-Frame-Options not set ``` -------------------------------- ### Underscore.js Template for HTML List Source: https://github.com/ajinabraham/njsscan/blob/master/tests/assets/templates/true_negatives/underscore_template.html This is an Underscore.js template designed to iterate over a collection of items and render them into an HTML table row. It uses Underscore's syntax for loops and variable interpolation. Ensure the data passed to the template has an 'name' property. ```html <% _.each(items,function(item,key,list){ var f = item.name; %> <% }); %>
Id Name
<%= key %> <%= item.name %>
``` -------------------------------- ### Exit Codes Source: https://context7.com/ajinabraham/njsscan/llms.txt Control CI/CD pipeline behavior with exit codes based on finding severity. By default, njsscan exits with code 1 only for ERROR severity findings. Use `--exit-warning` to also fail on WARNING severity. ```APIDOC ## Exit Codes ### Description Control CI/CD pipeline behavior with exit codes based on finding severity. By default, njsscan exits with code 1 only for ERROR severity findings. Use `--exit-warning` to also fail on WARNING severity. ### Usage ```bash # Exit 1 on ERROR findings only (default) njsscan ./src echo $? # 0 if no errors, 1 if errors found # Exit 1 on WARNING or ERROR findings njsscan --exit-warning ./src echo $? # 0 if clean, 1 if warnings or errors found # Use in CI/CD pipeline njsscan --json -o results.json ./src || exit 1 ``` ``` -------------------------------- ### Suppressing Findings with Inline Comments Source: https://context7.com/ajinabraham/njsscan/llms.txt Suppress specific findings directly in source code using inline comments. Add `// njsscan-ignore: rule_id` to the line containing the finding. ```APIDOC ## Suppressing Findings with Inline Comments ### Description Suppress specific findings directly in source code using inline comments. Add `// njsscan-ignore: rule_id` to the line containing the finding to suppress that specific rule. Multiple rule IDs can be comma-separated. ### Example ```javascript const express = require('express'); const app = express(); // This finding will be suppressed app.get('/redirect', function(req, res) { var target = req.param("target"); res.redirect(target); // njsscan-ignore: express_open_redirect }); // Suppress multiple rules on same line app.get('/api', function(req, res) { var query = req.query.search; res.send(query); // njsscan-ignore: express_xss, header_injection }); ``` ``` -------------------------------- ### Suppress njsscan Findings Source: https://github.com/ajinabraham/njsscan/blob/master/README.md Add `// njsscan-ignore: rule_id` to a line to suppress specific findings from that line. ```javascript app.get('/some/redirect', function (req, res) { var target = req.param("target"); res.redirect(target); // njsscan-ignore: express_open_redirect }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.