vigilsutra 0.4.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,81 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0 - 2026-11-28
4
+
5
+ ### Read before upgrading
6
+
7
+ - `VS-CICD-005` and `VS-K8S-007` are low severity and common, so a `--fail-on low` gate is likely to fail.
8
+ - New language patterns can fail a higher gate that passed with 0.5.0.
9
+ - Recreate a baseline to let it follow moved files.
10
+
11
+ ### Fixes
12
+
13
+ - Waivers for Kubernetes rules (`VS-K8S-*`) stopped the scan with an error, and the published finding schema rejected those rule ids.
14
+
15
+ ### Rules (56 to 59, rules version `1.9.0`)
16
+
17
+ - `VS-CODE-013`: request data into a shell or SQL call (Go, Java, Kotlin, PHP, Ruby, C#).
18
+ - `VS-CICD-005`: workflow without `permissions`. `VS-K8S-007`: no resource limits.
19
+ - `VS-CODE-005`, `006` and `009` to `011` also read Go, Java, Kotlin, PHP, Ruby and C#. These language checks match one line.
20
+ - `VS-CICD-002` covers `workflow_run`. `VS-CICD-001` and `004` read composite actions.
21
+
22
+ ### Features
23
+
24
+ - Baselines follow a moved file; a copy is still reported.
25
+ - The SBOM carries package hashes and licences from npm lockfiles.
26
+ - A warning when the report folder is listed in `package.json` `files`.
27
+
28
+ ## 0.5.0 - 2026-11-28
29
+
30
+ ### Read before upgrading
31
+
32
+ - Scans report more than 0.4.2 did (14 new rules, wider secret coverage), so a `--fail-on` gate that passed can fail.
33
+ - With `--fail-on`, an incomplete scan (time or file limit, including Git history) exits 2 instead of passing.
34
+ - Unknown command-line options are now errors.
35
+ - The GitHub Action reads `.vigilsutra.yml` from the base commit on pull request and merge queue runs, and shows annotations.
36
+ - Some baseline fingerprints change for lines with repeated secrets; refresh a baseline if needed.
37
+
38
+ ### Security and fixes
39
+
40
+ - Every secret on a line is redacted, including a second value matched by the same rule and values in different windows of a long line.
41
+ - A placeholder earlier on a line no longer hides a later secret, and only values made entirely of filler words count as placeholders.
42
+ - `--report-dir` on a folder with other files, such as the project root, no longer overwrites its `.gitignore`.
43
+ - A mistyped `--fail-on` can no longer pass a CI gate; `--flag=value` works.
44
+ - A pull request can no longer ignore its own findings by editing the policy file.
45
+ - `--staged` applies policy ignore patterns and the file size limit.
46
+ - `fix --apply` no longer rewrites SHA-1, which protocols such as the WebSocket handshake require.
47
+ - UTF-16 files with a byte-order mark are scanned. A byte-order mark no longer breaks `.vigilsutra.yml`.
48
+ - Scoped npm packages get a valid purl in the SBOM.
49
+ - `VS-IAC-001` reports open ingress that follows an egress block and Azure `*`/`Internet` sources. `VS-IAC-003` reports `*` anywhere in an action list.
50
+
51
+ ### Rules (42 to 56, rules version `1.6.0`)
52
+
53
+ - Hidden Unicode: `VS-AGENT-004`.
54
+ - Web requests on the same line (JavaScript, TypeScript, Python): `VS-CODE-008` to `VS-CODE-012`.
55
+ - Kubernetes and Compose: `VS-K8S-004` to `VS-K8S-006`, `VS-COMPOSE-001`.
56
+ - Databases and cloud: `VS-DB-001`, `VS-DB-002`, `VS-IAC-004`, `VS-IAC-005`.
57
+ - Workflows: `VS-CICD-002` reports checkout of `refs/pull/.../merge`; `VS-CICD-004` also reads `actions/github-script`.
58
+
59
+ ### Coverage
60
+
61
+ - Secret rules read `dist/`, `build/`, `out/`, `vendor/` and `*.min.js`. Other rules skip them.
62
+ - `VS-SECRET-004` reads unquoted values in configuration files, real-looking values in `.env` example files, and the names `token` and `cryptoKey`.
63
+ - Lockfiles are read at any depth, including npm lockfile version 1 and Yarn Berry.
64
+ - The SBOM reads `Cargo.lock`, `poetry.lock`, `composer.lock` and `Gemfile.lock`. Advisory matching covers Poetry (PyPI), not the other three ecosystems.
65
+ - More generated cache folders are ignored.
66
+
67
+ ### Features
68
+
69
+ - Custom rules from a JSON file with `--rules`, and `vigilsutra rules test <file>`.
70
+ - `--annotate` prints GitHub Actions annotations. The Action also writes the report to the job summary.
71
+ - SARIF adds `security-severity`, `helpUri` and `automationDetails`.
72
+ - `SOURCE_DATE_EPOCH` gives byte-identical reports and SBOM.
73
+ - Waivers accept a wildcard path, an optional `:line` and an optional reason.
74
+ - Findings from Git history state the commit date and whether the file still exists in HEAD.
75
+ - Long-line evidence shows the match. The HTML report has readable badge colours and severity filters.
76
+ - Report files are owner-only on POSIX, with a warning for commonly published folders.
77
+ - Shell completion for bash, zsh and PowerShell, and suggestions for mistyped commands.
78
+
3
79
  ## 0.4.2 - 2026-11-24
4
80
 
5
81
  - New documentation site (`site/`): guided pages, diagrams, charts, six real-world scenarios, light theme by default with a dark option, phone and desktop layouts, search, and a fresh sample report generated from the real CLI. Built by a zero-dependency generator and deployed by the Pages workflow. No rule or CLI changes.
package/README.md CHANGED
@@ -124,7 +124,33 @@ Full sample reports (labelled as samples, generated from the demo project): [HTM
124
124
  | `vigilsutra init` | Create `.vigilsutra.yml` (never overwrites). `--hook` installs `templates/pre-commit` when that hook is absent. |
125
125
  | `vigilsutra adapters list / install <name> / uninstall <name>` | `claude`, `cursor`, `codex`, `gemini`, `copilot`. File copy is tested. In-IDE invocation is not. `--dry-run` previews. |
126
126
 
127
- Exit codes: `0` ok · `1` findings at or above `--fail-on` (or new findings in `verify`) · `2` usage or runtime error.
127
+ In the GitHub Action, pull request and merge queue runs read `.vigilsutra.yml` from the base commit, so a pull request cannot loosen its own gate. A policy change takes effect after it is merged. If the base commit or its policy file cannot be read, the built-in defaults apply. Protect the workflow file itself with branch rules or `CODEOWNERS`. In another CI system, pass the base branch copy with `--policy <file>`.
128
+
129
+ ## Custom rules
130
+
131
+ Keep project-specific patterns in a JSON file and name it with `--rules`. The file is never read from the scanned project on its own, because a slow regular expression can stall a scan. In CI, take it from a trusted branch.
132
+
133
+ ```json
134
+ {
135
+ "rules": [
136
+ {
137
+ "id": "VS-CUSTOM-001",
138
+ "title": "Internal service token",
139
+ "severity": "high",
140
+ "pattern": "\\b(itk_[a-z0-9]{20})\\b",
141
+ "secretGroup": 1,
142
+ "files": ["src/**"],
143
+ "tests": { "match": ["t = itk_aaaaaaaaaaaaaaaaaaaa"], "noMatch": ["t = itk_short"] }
144
+ }
145
+ ]
146
+ }
147
+ ```
148
+
149
+ Check the examples with `vigilsutra rules test rules.json`. Set `secretGroup` for secrets so the value is redacted. Custom findings appear in every report; the SARIF rule descriptions cover built-in rules only.
150
+
151
+ Set `SOURCE_DATE_EPOCH` (seconds) to get byte-identical reports and SBOM from the same input.
152
+
153
+ Exit codes: `0` ok · `1` findings at or above `--fail-on` (or new findings in `verify`) · `2` usage or runtime error, or an incomplete scan with `--fail-on`.
128
154
 
129
155
  ## What it checks (feature matrix)
130
156
 
@@ -132,7 +158,13 @@ Exit codes: `0` ok · `1` findings at or above `--fail-on` (or new findings in `
132
158
  |---|---|---|
133
159
  | Secrets: AWS key IDs, GitHub tokens, Slack tokens, private keys, hardcoded credentials, tracked `.env` files, JWT, npm tokens, Stripe secret keys, Google API keys, Azure storage keys, GitLab tokens | `VS-SECRET-001..012` | **Implemented** |
134
160
  | Git history of those secret rules, from git objects, SHA-1 or SHA-256, until the time limit. Blobs over 1 MiB are skipped | | **Implemented** (`--no-history` skips it) |
161
+ | Hidden Unicode in code and agent instruction files; SARIF severity scores and rule links; job summary in the Action | | **Implemented** |
135
162
  | GitHub Actions: unpinned actions, `pull_request_target` checkout, `write-all`, expression injection | `VS-CICD-001..004` | **Implemented** |
163
+ | Request data used on the same line as a query, file path, outbound URL or redirect; weak cookie flags (JavaScript, TypeScript, Python) | `VS-CODE-008..012` | **Implemented** (same line only) |
164
+ | Databases without a password or with security off; public databases and storage; access granted to everyone | `VS-DB-001..002`, `VS-IAC-004..005` | **Implemented** |
165
+ | Go, Java, Kotlin, PHP, Ruby, C#: request data into shell, SQL, file path, outbound URL or redirect on one line; disabled TLS checks; MD5 and SHA-1 | `VS-CODE-005`, `006`, `009..011`, `013` | **Implemented** (line patterns only) |
166
+ | Workflows without a `permissions` block; Kubernetes manifests without resource limits | `VS-CICD-005`, `VS-K8S-007` | **Implemented** |
167
+ | Host paths, dangerous capabilities, RBAC wildcards, host-level Docker Compose settings | `VS-K8S-004..006`, `VS-COMPOSE-001` | **Implemented** |
136
168
  | Docker: root user, `:latest`, `curl \| sh` | `VS-DOCKER-001..003` | **Implemented** |
137
169
  | Kubernetes: privileged, host namespaces, root / privilege escalation | `VS-K8S-001..003` | **Implemented** |
138
170
  | Terraform / IaC: open CIDR, public ACL, wildcard IAM | `VS-IAC-001..003` | **Implemented** |
@@ -213,7 +245,7 @@ VigilSutra is a lightweight first pass, not a replacement for mature scanners. U
213
245
 
214
246
  **Is it a penetration-testing tool?** No. It reads files only. It does not probe live systems, exploit anything or test credentials.
215
247
 
216
- **Does a clean report mean my project is secure?** No. It means the 42 implemented rules found nothing inside this scan. Auth design, mobile apps, and runtime state are not assessed. The advisory snapshot can be older than a vulnerability published after 2026-11-07. Name tracking stops at object fields, dynamic imports, and function returns.
248
+ **Does a clean report mean my project is secure?** No. It means the 59 implemented rules found nothing inside this scan. Auth design, mobile apps, and runtime state are not assessed. The advisory snapshot can be older than a vulnerability published after 2026-11-07. Name tracking stops at object fields, dynamic imports, and function returns.
217
249
 
218
250
  **Will it find secrets in git history?** It reads commits reachable from HEAD, SHA-1 or SHA-256, without running `git`, until the time limit. A blob over 1 MiB is skipped. A secret of a type with no rule can still be missed. If a secret was ever committed, rotate it regardless of what the scan says.
219
251
 
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
3
- import { dirname, join, resolve } from "node:path";
4
- import { audit, exceeds, VERSION } from "./engine.js";
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, relative, resolve } from "node:path";
4
+ import { audit, contentKey, exceeds, VERSION } from "./engine.js";
5
5
  import { loadPolicy } from "./policy.js";
6
6
  import { render, FORMATS } from "./reporters/index.js";
7
7
  import { ALL_RULES, findRule, RULES_VERSION } from "./rules/index.js";
@@ -9,6 +9,9 @@ import { ADAPTERS, PACKAGE_ROOT, installAdapter, planAdapter, uninstallAdapter }
9
9
  import { locateGit } from "./git-objects.js";
10
10
  import { cycloneDx, readComponents } from "./components.js";
11
11
  import { applyFixes, planFixes } from "./fix.js";
12
+ import { closest } from "./suggest.js";
13
+ import { loadCustomRules, testCustomRules } from "./custom-rules.js";
14
+ import { annotations } from "./reporters/annotations.js";
12
15
  import { SEVERITY_ORDER } from "./types.js";
13
16
  const HELP = `VigilSutra AI ${VERSION} - offline, read-only security & privacy auditor. Created by Vatsal Shah (https://shahvatsal.com).
14
17
 
@@ -31,6 +34,8 @@ Commands:
31
34
  --no-advisories Do not match the shipped advisory snapshot
32
35
  --advisories <file> Match this advisory snapshot instead of the shipped one
33
36
  --no-color Plain output (also honours NO_COLOR)
37
+ --rules <file> Also apply custom rules from this JSON file (never read from the project on its own)
38
+ --annotate Also print GitHub Actions annotations; use with --out
34
39
  report [path] Same scan as audit. Always writes report.md and report.html (plus JSON and SARIF)
35
40
  sbom [path] Write a CycloneDX 1.6 JSON SBOM of pinned npm, PyPI and Go components
36
41
  --out <file> Write the SBOM to a file instead of stdout
@@ -39,8 +44,10 @@ Commands:
39
44
  baseline [path] --out <file> Record current findings as an accepted baseline
40
45
  verify [path] --previous <results.json> Re-scan and compare with an earlier JSON result
41
46
  rules list List implemented rules
47
+ rules test <file> Run the examples in a custom rules file
42
48
  explain <RULE-ID> Show rule details, fix and false-positive notes
43
49
  doctor Environment and offline-readiness check
50
+ completion <shell> Print a completion script for bash, zsh or powershell
44
51
  init [path] Create .vigilsutra.yml if absent (never overwrites)
45
52
  --hook Also install templates/pre-commit as .git/hooks/pre-commit if that hook is absent
46
53
  adapters list Show adapter status
@@ -48,30 +55,53 @@ Commands:
48
55
  adapters uninstall <claude|cursor|codex|gemini|copilot> [--project <dir>]
49
56
  --help, --version
50
57
 
51
- Exit codes: 0 ok | 1 findings at/above --fail-on | 2 usage or runtime error
58
+ Exit codes: 0 ok | 1 findings at/above --fail-on | 2 usage or runtime error, or an incomplete scan with --fail-on
52
59
  `;
53
- const VALUE_FLAGS = new Set(["format", "out", "fail-on", "baseline", "previous", "project", "policy", "report-dir", "since", "advisories"]);
60
+ const COMMANDS = ["audit", "report", "sbom", "fix", "baseline", "verify", "rules", "explain", "doctor", "init", "adapters", "completion"];
61
+ const VALUE_FLAGS = new Set(["format", "out", "fail-on", "baseline", "previous", "project", "policy", "report-dir", "since", "advisories", "rules"]);
62
+ const BOOL_FLAGS = new Set(["help", "report", "no-report", "no-policy", "no-history", "staged", "no-advisories", "no-color", "apply", "hook", "force", "dry-run", "annotate"]);
54
63
  function parse(argv) {
55
64
  const pos = [];
56
65
  const flags = new Map();
57
66
  for (let i = 0; i < argv.length; i++) {
58
67
  const a = argv[i];
59
- if (a.startsWith("--")) {
60
- const k = a.slice(2);
68
+ if (a.startsWith("-") && a.length > 1) {
69
+ const eq = a.indexOf("=");
70
+ const name = eq < 0 ? a : a.slice(0, eq);
71
+ const k = name === "-h" ? "help" : name.slice(2);
72
+ // A mistyped flag must stop the run: ignoring it could silently disable a CI gate.
73
+ if (name !== "-h" && (!name.startsWith("--") || !(VALUE_FLAGS.has(k) || BOOL_FLAGS.has(k)))) {
74
+ const near = closest(k, [...VALUE_FLAGS, ...BOOL_FLAGS]);
75
+ throw new Error(`unknown option "${name}".${near ? ` Did you mean --${near}?` : ""} Run: vigilsutra --help`);
76
+ }
61
77
  if (VALUE_FLAGS.has(k)) {
62
- const v = argv[++i];
63
- if (v === undefined)
78
+ const v = eq < 0 ? argv[++i] : a.slice(eq + 1);
79
+ if (!v || (eq < 0 && v.startsWith("--")))
64
80
  throw new Error(`--${k} needs a value`);
65
81
  flags.set(k, v);
66
82
  }
67
- else
83
+ else {
84
+ if (eq >= 0)
85
+ throw new Error(`${name} does not take a value`);
68
86
  flags.set(k, true);
87
+ }
69
88
  }
70
89
  else
71
90
  pos.push(a);
72
91
  }
73
92
  return { pos, flags };
74
93
  }
94
+ /** A completion script for the given shell, built from the command and option lists. */
95
+ function completion(shell) {
96
+ const words = [...COMMANDS, ...[...VALUE_FLAGS, ...BOOL_FLAGS].map((f) => `--${f}`)].join(" ");
97
+ if (shell === "bash")
98
+ return `complete -o default -W "${words}" vigilsutra\n`;
99
+ if (shell === "zsh")
100
+ return `autoload -U +X bashcompinit && bashcompinit\ncomplete -o default -W "${words}" vigilsutra\n`;
101
+ if (shell === "powershell")
102
+ return `Register-ArgumentCompleter -Native -CommandName vigilsutra -ScriptBlock {\n param($word)\n '${words}'.Split(' ') | Where-Object { $_ -like "$word*" }\n}\n`;
103
+ return null;
104
+ }
75
105
  function policyOpts(flags) {
76
106
  const p = flags.get("policy");
77
107
  return { policyFile: typeof p === "string" ? resolve(p) : undefined, ignoreProjectPolicy: flags.has("no-policy") };
@@ -79,7 +109,9 @@ function policyOpts(flags) {
79
109
  function auditOpts(root, flags) {
80
110
  const since = flags.get("since");
81
111
  const advisories = flags.get("advisories");
112
+ const rules = flags.get("rules");
82
113
  return {
114
+ extraRules: typeof rules === "string" ? loadCustomRules(resolve(rules)).map((c) => c.rule) : undefined,
83
115
  root,
84
116
  history: !flags.has("no-history"),
85
117
  since: typeof since === "string" ? since : undefined,
@@ -99,14 +131,39 @@ function checkRoot(p) {
99
131
  fail(`not a directory: ${p}`);
100
132
  return realpathSync(abs);
101
133
  }
102
- /** Writes report.md, report.html, results.json and results.sarif. The folder gets a .gitignore so reports are not committed by accident. */
103
- function writeReportFolder(dir, result) {
104
- mkdirSync(dir, { recursive: true });
105
- writeFileSync(join(dir, "report.md"), render(result, "markdown"));
106
- writeFileSync(join(dir, "report.html"), render(result, "html"));
107
- writeFileSync(join(dir, "results.json"), render(result, "json"));
108
- writeFileSync(join(dir, "results.sarif"), render(result, "sarif"));
109
- writeFileSync(join(dir, ".gitignore"), "# Reports contain file paths and redacted excerpts; do not commit them.\n*\n");
134
+ const REPORT_FILES = [["report.md", "markdown"], ["report.html", "html"], ["results.json", "json"], ["results.sarif", "sarif"]];
135
+ /** Folders that are commonly deployed or published. */
136
+ const PUBLISHED = new Set(["docs", "public", "static", "site", "www", "dist", "build", "out"]);
137
+ /** The `files` entries of the project's package.json, without leading `./`. */
138
+ function packageFiles(root) {
139
+ try {
140
+ const { files } = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
141
+ return Array.isArray(files) ? files.filter((x) => typeof x === "string").map((x) => x.replace(/^\.?\//, "")) : [];
142
+ }
143
+ catch {
144
+ return [];
145
+ }
146
+ }
147
+ /**
148
+ * Writes report.md, report.html, results.json and results.sarif, readable by the owner only.
149
+ * A folder that holds nothing else also gets a .gitignore so reports are not committed by accident.
150
+ */
151
+ function writeReportFolder(dir, result, root) {
152
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
153
+ const ours = new Set([".gitignore", ...REPORT_FILES.map(([name]) => name)]);
154
+ const shared = readdirSync(dir).some((name) => !ours.has(name));
155
+ for (const [name, format] of REPORT_FILES)
156
+ writeFileSync(join(dir, name), render(result, format), { mode: 0o600 });
157
+ // Never replace or add an ignore-everything file in a folder with other content, such as the project root.
158
+ if (shared)
159
+ process.stderr.write(`Warning: ${dir} holds other files, so no .gitignore was written. Do not commit or publish the reports.\n`);
160
+ else
161
+ writeFileSync(join(dir, ".gitignore"), "# Reports contain file paths and redacted excerpts; do not commit them.\n*\n");
162
+ const top = relative(root, realpathSync(dir)).split(/[\\/]/)[0];
163
+ if (top && packageFiles(root).some((entry) => entry === top || entry.startsWith(`${top}/`)))
164
+ process.stderr.write(`Warning: package.json "files" includes "${top}/", so the reports would be published with the package.\n`);
165
+ if (PUBLISHED.has(top))
166
+ process.stderr.write(`Warning: reports are inside "${top}/", which is often published. Choose another --report-dir.\n`);
110
167
  }
111
168
  function writeOut(file, data) {
112
169
  const abs = resolve(file);
@@ -132,6 +189,10 @@ function main() {
132
189
  }
133
190
  const cmd = argv[0];
134
191
  const { pos, flags } = parse(argv.slice(1));
192
+ if (flags.has("help")) {
193
+ process.stdout.write(HELP);
194
+ return;
195
+ }
135
196
  const color = !flags.has("no-color") && !process.env.NO_COLOR && !!process.stdout.isTTY;
136
197
  switch (cmd) {
137
198
  case "audit":
@@ -154,15 +215,20 @@ function main() {
154
215
  }
155
216
  else
156
217
  process.stdout.write(render(result, format, color));
218
+ if (flags.has("annotate"))
219
+ process.stdout.write(annotations(result));
157
220
  // Readable reports are files, not only a terminal scrollback. Stdout stays the chosen format.
158
221
  const dirFlag = flags.get("report-dir");
159
222
  if (!flags.has("no-report")) {
160
223
  const dir = resolve(typeof dirFlag === "string" ? dirFlag : "vigilsutra-report");
161
- writeReportFolder(dir, result);
224
+ writeReportFolder(dir, result, root);
162
225
  process.stderr.write(`Reports written to ${dir}\n report.html open this in a browser\n report.md Markdown version\n results.json, results.sarif for tools and CI\n`);
163
226
  }
164
227
  if (failOn && exceeds(result, failOn))
165
228
  process.exit(1);
229
+ // A gate cannot pass on a scan that did not finish.
230
+ if (failOn && result.scope.truncated)
231
+ fail(`scan incomplete (${result.scope.truncatedReason}); --fail-on cannot pass. Raise timeLimitMs or maxFiles, or narrow the path.`);
166
232
  return;
167
233
  }
168
234
  case "baseline": {
@@ -171,7 +237,7 @@ function main() {
171
237
  if (typeof out !== "string")
172
238
  fail("baseline needs --out <file>");
173
239
  const result = audit(auditOpts(root, flags));
174
- writeOut(out, JSON.stringify({ tool: "vigilsutra", version: VERSION, createdAt: result.generatedAt, fingerprints: result.findings.map((f) => f.fingerprint).sort() }, null, 2) + "\n");
240
+ writeOut(out, JSON.stringify({ tool: "vigilsutra", version: VERSION, createdAt: result.generatedAt, fingerprints: result.findings.map((f) => f.fingerprint).sort(), entries: result.findings.filter((f) => f.path !== "." && !f.path.startsWith("git-history/")).map((f) => ({ path: f.path, key: contentKey(f) })) }, null, 2) + "\n");
175
241
  process.stdout.write(`Baseline of ${result.findings.length} finding(s) written to ${out}\n`);
176
242
  return;
177
243
  }
@@ -238,8 +304,19 @@ function main() {
238
304
  return;
239
305
  }
240
306
  case "rules": {
307
+ if (pos[0] === "test" && pos[1]) {
308
+ const custom = loadCustomRules(resolve(pos[1]));
309
+ const failures = testCustomRules(custom);
310
+ for (const f of failures)
311
+ process.stdout.write(`FAIL ${f}\n`);
312
+ const examples = custom.reduce((n, c) => n + c.match.length + c.noMatch.length, 0);
313
+ process.stdout.write(`${custom.length} rule(s), ${examples} example(s), ${failures.length} failure(s)\n`);
314
+ if (failures.length)
315
+ process.exit(1);
316
+ return;
317
+ }
241
318
  if (pos[0] !== "list")
242
- fail("usage: vigilsutra rules list");
319
+ fail("usage: vigilsutra rules list | rules test <file>");
243
320
  process.stdout.write(`Rules version ${RULES_VERSION}: ${ALL_RULES.length} rules\n`);
244
321
  for (const r of ALL_RULES)
245
322
  process.stdout.write(`${r.id.padEnd(15)} ${r.severity.padEnd(8)} ${r.status.padEnd(13)} ${r.agent.padEnd(13)} ${r.title}\n`);
@@ -264,6 +341,13 @@ function main() {
264
341
  .join("\n") + "\n");
265
342
  return;
266
343
  }
344
+ case "completion": {
345
+ const script = completion(pos[0] ?? "");
346
+ if (!script)
347
+ fail("usage: vigilsutra completion <bash|zsh|powershell>");
348
+ process.stdout.write(script);
349
+ return;
350
+ }
267
351
  case "doctor": {
268
352
  const lines = [
269
353
  `VigilSutra AI ${VERSION}`,
@@ -347,7 +431,10 @@ function main() {
347
431
  fail("usage: vigilsutra adapters list | install <claude|cursor|codex|gemini|copilot> | uninstall <claude|cursor|codex|gemini|copilot>");
348
432
  }
349
433
  default:
350
- fail(`unknown command "${cmd}". Run: vigilsutra --help`);
434
+ {
435
+ const near = closest(cmd, COMMANDS);
436
+ fail(`unknown command "${cmd}".${near ? ` Did you mean "${near}"?` : ""} Run: vigilsutra --help`);
437
+ }
351
438
  }
352
439
  }
353
440
  try {
package/dist/clock.js ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Time written into reports. SOURCE_DATE_EPOCH (seconds, reproducible-builds.org) pins it so equal input
3
+ * gives equal bytes. Waiver expiry never uses this: it must follow the real date.
4
+ */
5
+ export function stamp() {
6
+ const epoch = process.env.SOURCE_DATE_EPOCH;
7
+ return (epoch && /^\d{1,11}$/.test(epoch) ? new Date(Number(epoch) * 1000) : new Date()).toISOString();
8
+ }
@@ -1,6 +1,7 @@
1
- import { randomUUID } from "node:crypto";
2
- import { existsSync, readFileSync } from "node:fs";
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
+ import { stamp } from "./clock.js";
4
5
  const MAX = 20 * 1024 * 1024;
5
6
  function readText(root, rel) {
6
7
  const abs = join(root, rel);
@@ -16,8 +17,30 @@ function readText(root, rel) {
16
17
  return null;
17
18
  }
18
19
  }
20
+ const MANIFESTS = new Set(["package-lock.json", "npm-shrinkwrap.json", "requirements.txt", "yarn.lock", "pnpm-lock.yaml", "go.mod", "Cargo.lock", "poetry.lock", "composer.lock", "Gemfile.lock"]);
21
+ const SKIP_DIRS = new Set([".git", "node_modules", "dist", "build", "out", "vendor", ".venv", "venv", "__pycache__", "coverage", ".next", "target", "vigilsutra-report"]);
22
+ /** Relative paths of manifests at any depth. Symlinks are not followed. */
23
+ function findManifests(root, skip, dir = "", depth = 0) {
24
+ let entries;
25
+ try {
26
+ entries = readdirSync(join(root, dir), { withFileTypes: true });
27
+ }
28
+ catch {
29
+ return [];
30
+ }
31
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
32
+ const out = [];
33
+ for (const e of entries) {
34
+ const rel = dir ? `${dir}/${e.name}` : e.name;
35
+ if (e.isFile() && MANIFESTS.has(e.name) && !skip(rel))
36
+ out.push(rel);
37
+ if (e.isDirectory() && depth < 8 && !SKIP_DIRS.has(e.name) && !skip(rel + "/placeholder"))
38
+ out.push(...findManifests(root, skip, rel, depth + 1));
39
+ }
40
+ return out;
41
+ }
19
42
  /** Resolved components from lockfiles and pinned manifests. Ranges are skipped. Lockfiles are read even when the scan ignores them. */
20
- export function readComponents(root) {
43
+ export function readComponents(root, skip = () => false) {
21
44
  const out = [];
22
45
  const seen = new Set();
23
46
  const add = (c) => {
@@ -29,71 +52,125 @@ export function readComponents(root) {
29
52
  seen.add(key);
30
53
  out.push(c);
31
54
  };
32
- const lock = readText(root, "package-lock.json");
33
- if (lock) {
34
- try {
35
- const json = JSON.parse(lock);
36
- for (const [path, meta] of Object.entries(json.packages ?? {})) {
37
- if (!path || !meta.version)
38
- continue;
39
- const name = meta.name ?? path.split("node_modules/").pop();
40
- if (!name || name === path)
41
- continue;
42
- add({ ecosystem: "npm", name, version: meta.version, path: "package-lock.json" });
55
+ for (const path of findManifests(root, skip)) {
56
+ const text = readText(root, path);
57
+ if (!text)
58
+ continue;
59
+ const file = path.split("/").pop();
60
+ const lines = text.split(/\r?\n/);
61
+ if (file === "package-lock.json" || file === "npm-shrinkwrap.json") {
62
+ try {
63
+ const json = JSON.parse(text);
64
+ for (const [at, meta] of Object.entries(json.packages ?? {})) {
65
+ if (!at || !meta.version)
66
+ continue;
67
+ const name = meta.name ?? at.split("node_modules/").pop();
68
+ if (!name || name === at)
69
+ continue;
70
+ add({ ecosystem: "npm", name, version: meta.version, path, integrity: meta.integrity, license: typeof meta.license === "string" ? meta.license : undefined });
71
+ }
72
+ // Lockfile version 1 has only a nested dependency tree.
73
+ const walk = (deps) => {
74
+ for (const [name, meta] of Object.entries(deps)) {
75
+ add({ ecosystem: "npm", name, version: meta.version ?? "", path });
76
+ if (meta.dependencies)
77
+ walk(meta.dependencies);
78
+ }
79
+ };
80
+ if (!json.packages)
81
+ walk(json.dependencies ?? {});
82
+ }
83
+ catch {
84
+ /* not a lockfile */
43
85
  }
44
86
  }
45
- catch {
46
- /* not a lockfile */
87
+ else if (file === "requirements.txt") {
88
+ for (const line of lines) {
89
+ const m = /^\s*([A-Za-z0-9_.-]+)\s*==\s*([0-9][^\\\s]*)/.exec(line);
90
+ if (m)
91
+ add({ ecosystem: "pypi", name: m[1], version: m[2], path });
92
+ }
47
93
  }
48
- }
49
- const req = readText(root, "requirements.txt");
50
- if (req) {
51
- for (const line of req.split(/\n/)) {
52
- const m = /^\s*([A-Za-z0-9_.-]+)\s*==\s*([0-9][^\\\s]*)/.exec(line);
53
- if (m)
54
- add({ ecosystem: "pypi", name: m[1], version: m[2], path: "requirements.txt" });
94
+ else if (file === "yarn.lock") {
95
+ let name = "";
96
+ for (const line of lines) {
97
+ if (line && !line.startsWith(" ") && !line.startsWith("\t"))
98
+ name = line.includes("@workspace:") ? "" : (/^"?(@?[^@"\s]+)@/.exec(line)?.[1] ?? "");
99
+ // Classic writes `version "1.0.0"`, Berry writes `version: 1.0.0`.
100
+ const ver = /^ {2}version:? "?(\d[^"\s]*)/.exec(line);
101
+ if (ver && name)
102
+ add({ ecosystem: "npm", name, version: ver[1], path });
103
+ }
55
104
  }
56
- }
57
- const yarn = readText(root, "yarn.lock");
58
- if (yarn) {
59
- let name = "";
60
- for (const line of yarn.split(/\n/)) {
61
- if (!line.startsWith(" ") && !line.startsWith("\t")) {
62
- const head = /^"?(@?[^@"\s]+)@/.exec(line);
63
- if (head)
64
- name = head[1];
105
+ else if (file === "pnpm-lock.yaml") {
106
+ for (const line of lines) {
107
+ const m = /^\s{2}['"]?\/?(@?[^@\s'"]+)@(\d[^:(/'"]*)/.exec(line);
108
+ if (m)
109
+ add({ ecosystem: "npm", name: m[1], version: m[2], path });
65
110
  }
66
- const ver = /^ {2}version "(\d[^"]*)"/.exec(line);
67
- if (ver && name)
68
- add({ ecosystem: "npm", name, version: ver[1], path: "yarn.lock" });
69
111
  }
70
- }
71
- const pnpm = readText(root, "pnpm-lock.yaml");
72
- if (pnpm) {
73
- for (const line of pnpm.split(/\n/)) {
74
- const m = /^\s{2}\/?(@?[^@\s'"]+)@(\d[^:(/'"]*)/.exec(line);
75
- if (m)
76
- add({ ecosystem: "npm", name: m[1], version: m[2], path: "pnpm-lock.yaml" });
112
+ else if (file === "Cargo.lock" || file === "poetry.lock") {
113
+ const ecosystem = file === "Cargo.lock" ? "cargo" : "pypi";
114
+ let name = "";
115
+ for (const line of lines) {
116
+ if (line.startsWith("["))
117
+ name = "";
118
+ name = /^name = "([^"]+)"/.exec(line)?.[1] ?? name;
119
+ const version = /^version = "([^"]+)"/.exec(line)?.[1];
120
+ if (version && name)
121
+ add({ ecosystem, name, version, path });
122
+ }
77
123
  }
78
- }
79
- const gomod = readText(root, "go.mod");
80
- if (gomod) {
81
- for (const line of gomod.split(/\n/)) {
82
- const m = /(?:^|\s)([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)\s+v([0-9][^\s]*)/.exec(line);
83
- if (m)
84
- add({ ecosystem: "golang", name: m[1], version: m[2], path: "go.mod" });
124
+ else if (file === "composer.lock") {
125
+ try {
126
+ const json = JSON.parse(text);
127
+ for (const p of [...(json.packages ?? []), ...(json["packages-dev"] ?? [])]) {
128
+ if (p.name)
129
+ add({ ecosystem: "composer", name: p.name, version: (p.version ?? "").replace(/^v/, ""), path });
130
+ }
131
+ }
132
+ catch {
133
+ /* not a lockfile */
134
+ }
135
+ }
136
+ else if (file === "Gemfile.lock") {
137
+ // Resolved gems are indented four spaces; their dependency ranges are indented six.
138
+ for (const line of lines) {
139
+ const m = /^ {4}([A-Za-z0-9_.-]+) \((\d[^)\s]*)\)$/.exec(line);
140
+ if (m)
141
+ add({ ecosystem: "gem", name: m[1], version: m[2], path });
142
+ }
143
+ }
144
+ else {
145
+ for (const line of lines) {
146
+ const m = /(?:^|\s)([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)\s+v([0-9][^\s]*)/.exec(line);
147
+ if (m)
148
+ add({ ecosystem: "golang", name: m[1], version: m[2], path });
149
+ }
85
150
  }
86
151
  }
87
152
  return out;
88
153
  }
154
+ /** Random by default; derived from the content when SOURCE_DATE_EPOCH asks for reproducible output. */
155
+ function serial(components, version) {
156
+ if (!process.env.SOURCE_DATE_EPOCH)
157
+ return randomUUID();
158
+ const h = createHash("sha256").update(JSON.stringify([version, components])).digest("hex");
159
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-8${h.slice(17, 20)}-${h.slice(20, 32)}`;
160
+ }
161
+ /** CycloneDX wants hexadecimal digests. Strings that are not a SHA integrity value are left out. */
162
+ function hashes(integrity) {
163
+ const m = /^sha(1|256|384|512)-([A-Za-z0-9+/]+={0,2})(?:\s|$)/.exec(typeof integrity === "string" ? integrity : "");
164
+ return m ? { hashes: [{ alg: `SHA-${m[1]}`, content: Buffer.from(m[2], "base64").toString("hex") }] } : {};
165
+ }
89
166
  export function cycloneDx(components, version) {
90
167
  const bom = {
91
168
  bomFormat: "CycloneDX",
92
169
  specVersion: "1.6",
93
- serialNumber: `urn:uuid:${randomUUID()}`,
170
+ serialNumber: `urn:uuid:${serial(components, version)}`,
94
171
  version: 1,
95
172
  metadata: {
96
- timestamp: new Date().toISOString(),
173
+ timestamp: stamp(),
97
174
  tools: { components: [{ type: "application", name: "vigilsutra", version }] },
98
175
  component: { type: "application", name: "scanned-project" }
99
176
  },
@@ -102,6 +179,8 @@ export function cycloneDx(components, version) {
102
179
  name: c.name,
103
180
  version: c.version,
104
181
  purl: purl(c),
182
+ ...hashes(c.integrity),
183
+ ...(c.license ? { licenses: [{ license: { name: c.license } }] } : {}),
105
184
  properties: [{ name: "vigilsutra:manifest", value: c.path }]
106
185
  }))
107
186
  };
@@ -109,8 +188,10 @@ export function cycloneDx(components, version) {
109
188
  }
110
189
  function purl(c) {
111
190
  if (c.ecosystem === "npm")
112
- return `pkg:npm/${c.name.replace("/", "%2F")}@${c.version}`;
191
+ return `pkg:npm/${c.name.replace(/^@/, "%40")}@${c.version}`;
113
192
  if (c.ecosystem === "pypi")
114
193
  return `pkg:pypi/${c.name.toLowerCase()}@${c.version}`;
115
- return `pkg:golang/${c.name}@v${c.version}`;
194
+ if (c.ecosystem === "golang")
195
+ return `pkg:golang/${c.name}@v${c.version}`;
196
+ return `pkg:${c.ecosystem}/${c.name}@${c.version}`;
116
197
  }