npm package: @raj-dev/guardrail
Description: A lightweight, offline-first security scanner for npm projects.
Latest version: 1.0.0

# @raj-dev/guardrail

> A lightweight, **offline-first** security scanner for npm projects.  
> Run dependency checks, SAST, secrets detection, and SBOM generation from your terminal—no cloud, no telemetry.

[![npm version](https://img.shields.io/npm/v/@raj-dev/guardrail.svg)](https://www.npmjs.com/package/@raj-dev/guardrail)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE)
[![Node](https://img.shields.io/badge/node-%3E%3D14.0.0-brightgreen.svg)](https://nodejs.org)
[![Buy Me A Coffee](https://img.shields.io/badge/Buy%20Me%20A%20Coffee-support-yellow.svg)](https://buymeacoffee.com/rajappar412)
[![GitHub Sponsors](https://img.shields.io/badge/GitHub%20Sponsors-RajappaR-ea4aaa.svg)](https://github.com/sponsors/RajappaR)

---

## Table of contents

- [Why guardrail?](#why-guardrail)
- [What it does](#what-it-does)
- [What it does *not* do](#what-it-does-not-do)
- [Quick start](#quick-start)
- [Installation](#installation)
- [Usage](#usage)
- [CLI reference](#cli-reference)
- [Example output](#example-output)
- [HTML report](#html-report)
- [Features in detail](#features-in-detail)
- [Configuration](#configuration)
- [Exit codes](#exit-codes)
- [Security disclaimer](#security-disclaimer)
- [Roadmap](#roadmap)
- [Support](#support)
- [License](#license)

---

## Why guardrail?

- **Offline-first** — Everything runs on your machine. No uploads, no SaaS, no account.
- **Zero telemetry** — We don’t collect or send any data.
- **Single command** — One CLI to run npm audit, SAST, secrets checks, and optional SBOM.
- **CI-friendly** — JSON output and configurable fail level for pipelines.

---

## What it does

| Capability | Description |
|------------|-------------|
| **Dependency scan** | Runs `npm audit` and normalizes vulnerabilities into severity buckets (critical / high / medium / low). |
| **SAST (v1)** | String-based checks for dangerous patterns: `eval()`, `new Function()`, `child_process.exec` / `execSync`. |
| **SAST (v2)** | ESLint-driven AST rules for the same patterns—fewer false positives from comments or strings. |
| **Secrets detection** | Regex-based scan for AWS keys, `token=`, `secret=`, `apiKey=` and similar in your code. |
| **SBOM** | Generates a CycloneDX Software Bill of Materials (`sbom.json`) when you pass `--sbom`. Stays on disk; no upload. |

All scanning is **local only**. No frameworks required; just Node.js and your project.

---

## What it does *not* do

- **No network upload** of results or SBOM.
- **No CI/CD config generation** (you plug it into your own pipeline).
- **No guarantee** that every finding is a true positive—manual review is still required.
- **Not a full SAST suite** — it focuses on a small set of high-value checks, not exhaustive analysis.

---

## Quick start

From your project root (where `package.json` lives). Install globally once (`npm install -g @raj-dev/guardrail`), or use npx:

```bash
npx @raj-dev/guardrail scan
```

To also generate an SBOM and use pretty output:

```bash
npx @raj-dev/guardrail scan --level high --format pretty --sbom
```

---

## Installation

Because guardrail is a CLI, the usual way to install it is **globally** with `-g`. Then you can run `guardrail` from any project directory:

```bash
npm install -g @raj-dev/guardrail
```

Then from any project root:

```bash
guardrail scan
guardrail scan --sbom --format json
```

**Other options:**

**Run without installing** (uses latest from npm each time):

```bash
npx @raj-dev/guardrail scan
```

**As a dev dependency** (lock to a version; good for CI or team consistency):

```bash
npm install --save-dev @raj-dev/guardrail
```

Then in your scripts (in `package.json`):

```json
{
  "scripts": {
    "security": "guardrail scan --level high",
    "security:full": "guardrail scan --level high --sbom --format json"
  }
}
```

---

## Usage

The main command is **`scan`**. Run it from your project directory (the one with `package.json`).

```bash
guardrail scan [options]
```

### Common examples

| Goal | Command |
|------|--------|
| Quick local check | `guardrail scan` |
| Fail on high and above, pretty output | `guardrail scan --level high --format pretty` |
| Generate SBOM | `guardrail scan --sbom` |
| HTML report (browser) | `guardrail scan --format html` or `guardrail scan --report` |
| Machine-readable for CI | `guardrail scan --format json --level high` |
| Full run with SBOM and JSON | `guardrail scan --level high --sbom --format json` |
| Pretty output + HTML report | `guardrail scan --report` |

---

## CLI reference

| Option | Description | Default |
|--------|-------------|---------|
| `--level <level>` | Fail (exit 1) if any finding at this severity or above exists. One of: `low`, `medium`, `high`, `critical`. | `high` |
| `--format <format>` | Output format: `pretty` (human-readable), `json` (for scripts/CI), or `html` (browser report only). | `pretty` |
| `--sbom` | Generate a CycloneDX SBOM and write it to `sbom.json` in the project root. | not generated |
| `--report` | In addition to console output, generate an HTML report at `report.html` (open in browser). | off |

**Examples:**

```bash
# Strict: fail on any finding from low up
guardrail scan --level low

# Relaxed: only fail on critical
guardrail scan --level critical

# JSON for piping or CI
guardrail scan --format json > report.json
```

---

## Example output

With `--format pretty` (default), you’ll see progress and a summary like this:

```
🔍 Starting security scan...
━━━━━━━━━━━━━━━━━━━━━━━━━━

📦 Scanning npm dependencies
⏳ Running npm audit...
✅ Dependency scan completed

🧠 Running static code analysis
📁 Scanning JavaScript files...
⚠️  Found 3 potential issues

🔐 Checking for hardcoded secrets
🔎 Searching for API keys & tokens...
✅ No secrets found

📦 Generating SBOM (CycloneDX)
📄 sbom.json created

📊 Final Summary
━━━━━━━━━━━━━━━━━━━━━━━━━━
❌ Critical : 1
⚠️  High     : 2
🟡 Medium   : 3
🟢 Low      : 1
```

With `--format json`, the output is a single JSON object with `summary` and `issues`, suitable for CI or custom tooling.

### HTML report

Use `--format html` to only generate a report file, or `--report` to generate a report in addition to your usual output:

```bash
guardrail scan --format html
# Writes report.html; open in a browser.

guardrail scan --report
# Pretty output in terminal + report.html generated.
```

The report is written to **`report.html`** in your project root. Open it in any browser to view:

- **Summary cards** — Critical, High, Medium, Low counts at a glance
- **Issues by source** — Grouped by npm-audit, SAST, secrets, SBOM
- **Severity badges** — Color-coded for quick scanning
- **Print-friendly** — Works well when printed or saved as PDF

No server or network required; the report is a single self-contained HTML file.

---

## Features in detail

### Dependency scanning (npm audit)

Guardrail runs `npm audit --json` and parses the result. It maps npm’s severity levels to a normalized summary and issue list. If `npm audit` fails (e.g. no `package-lock.json`) or returns non-zero, that’s reported as a low-severity issue so the rest of the scan still runs.

### SAST v1 (string-based)

Scans `.js` files (excluding `node_modules`) for literal patterns:

- `eval(`
- `new Function(`
- `child_process.exec` / `child_process.execSync`

Useful for a fast first pass; can have false positives (e.g. in comments or strings).

### SAST v2 (ESLint-based)

Runs ESLint programmatically with custom rules—no project `.eslintrc` needed. The same risky constructs are flagged using the AST, which cuts down false positives. Rules included:

| Rule | What it flags |
|------|----------------|
| **no-eval** | `eval(...)` |
| **no-new-function** | `new Function(...)` |
| **no-child-process** | `child_process.exec` / `execSync` (suggests `execFile` with explicit args) |

### Secrets detection

Regex-based scan over `.js` files (again excluding `node_modules`) for:

- AWS-style access key patterns (e.g. `AKIA...`)
- `token=...`, `secret=...`, `apiKey=...`-style assignments

Designed to catch obvious leaks; not a replacement for a dedicated secrets manager or pre-commit hooks.

### SBOM (CycloneDX)

With `--sbom`, guardrail uses [@cyclonedx/cyclonedx-npm](https://www.npmjs.com/package/@cyclonedx/cyclonedx-npm) to generate a CycloneDX SBOM and writes it to `sbom.json` in the current working directory. Useful for supply-chain visibility and compliance. The file is created **only on your machine**; nothing is sent to any server.

---

## Configuration

You can set defaults in your project’s `package.json` under a `guardrail` key. CLI flags override these.

```json
{
  "guardrail": {
    "failLevel": "high",
    "exclude": ["dist", "coverage"],
    "includeGlob": ["**/*.js"]
  }
}
```

| Field | Description |
|-------|-------------|
| `failLevel` | Same as `--level`: `low`, `medium`, `high`, or `critical`. |
| `exclude` | Directories to exclude from scanning (in addition to `node_modules`). |
| `includeGlob` | Glob patterns for files to include in SAST/secrets (default includes `**/*.js`). |

---

## Exit codes

| Code | Meaning |
|------|--------|
| **0** | Scan completed; no findings at or above the configured fail level. |
| **1** | Scan completed but at least one finding at or above the fail level, or a fatal error (e.g. missing deps). |

Use `--level` and the exit code in CI to gate on security findings.

---

## Security disclaimer

Guardrail is intended to **help** you spot common issues. It is not a full security audit. Findings can be false positives or false negatives. Use it alongside code review, dependency review, and other tools—not as the only security gate.

---

## Roadmap

- More SAST rules (e.g. unsafe deserialization, dangerous redirects).
- Configurable secret patterns and exclude list.
- Optional SARIF output for CI integration.
- Support for lockfile-only SBOM when `node_modules` is not present.

---

## Support

If this tool is useful to you, consider supporting the author:

- [**Buy Me a Coffee**](https://buymeacoffee.com/rajappar412) — One-time or monthly support
- [**GitHub Sponsors**](https://github.com/sponsors/RajappaR) — Sponsor open source work

---

## Publishing

To publish this package to npm:

1. **Update `package.json`**  
   Set `repository`, `bugs`, and `homepage` URLs to your actual repo (e.g. `https://github.com/YourUser/guardrail`).

2. **Login to npm** (if needed):
   ```bash
   npm login
   ```

3. **Dry-run** (see what would be published):
   ```bash
   npm pack --dry-run
   ```

4. **Publish** (scoped packages are public when `publishConfig.access` is `"public"`):
   ```bash
   npm publish
   ```

Before publishing, `prepublishOnly` runs `node --check src/cli.js` to catch syntax errors. No scan is run.

---

## License

MIT. See [LICENSE](./LICENSE) for details.