vigilsutra 0.4.2 → 0.5.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.
@@ -0,0 +1,86 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { globToRegExp } from "./policy.js";
3
+ import { lineRule } from "./rules/util.js";
4
+ import { SEVERITY_ORDER } from "./types.js";
5
+ const KEYS = new Set(["id", "title", "severity", "pattern", "flags", "files", "remediation", "secretGroup", "tests"]);
6
+ const strings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
7
+ /**
8
+ * Rules from a JSON file named with --rules. They are never read from the scanned project on their own:
9
+ * a pattern is code that runs against every line, and a slow one can stall the scan.
10
+ */
11
+ export function loadCustomRules(file) {
12
+ const data = JSON.parse(readFileSync(file, "utf8").replace(/^\uFEFF/, ""));
13
+ if (!Array.isArray(data.rules) || !data.rules.length)
14
+ throw new Error(`${file}: expected {"rules": [ ... ]}`);
15
+ const seen = new Set();
16
+ return data.rules.map((raw, i) => {
17
+ const bad = (why) => {
18
+ throw new Error(`${file}: rule ${i + 1}: ${why}`);
19
+ };
20
+ for (const key of Object.keys(raw))
21
+ if (!KEYS.has(key))
22
+ bad(`unknown key "${key}"`);
23
+ const { id, title, severity, pattern, flags = "", files, remediation, secretGroup, tests = {} } = raw;
24
+ if (typeof id !== "string" || !/^VS-CUSTOM-\d{3}$/.test(id) || seen.has(id))
25
+ bad("id must be a unique VS-CUSTOM-000 style id");
26
+ seen.add(id);
27
+ if (typeof title !== "string" || !title)
28
+ bad("title is required");
29
+ if (!SEVERITY_ORDER.includes(severity))
30
+ bad("severity must be critical|high|medium|low|info");
31
+ if (typeof pattern !== "string" || !pattern)
32
+ bad("pattern is required");
33
+ if (typeof flags !== "string" || !/^[ius]*$/.test(flags))
34
+ bad("flags may contain only i, u and s");
35
+ if (files !== undefined && !strings(files))
36
+ bad("files must be a list of globs");
37
+ if (secretGroup !== undefined && !(Number.isInteger(secretGroup) && secretGroup >= 0))
38
+ bad("secretGroup must be a group number");
39
+ const { match = [], noMatch = [] } = tests;
40
+ if (!strings(match) || !strings(noMatch))
41
+ bad("tests.match and tests.noMatch must be lists of strings");
42
+ let re;
43
+ try {
44
+ re = new RegExp(pattern, flags);
45
+ }
46
+ catch (e) {
47
+ return bad(e.message);
48
+ }
49
+ const globs = (files ?? []).map(globToRegExp);
50
+ const rule = {
51
+ id: id,
52
+ version: "1.0.0",
53
+ title: title,
54
+ category: secretGroup === undefined ? "custom" : "secrets",
55
+ agent: "Custom",
56
+ severity: severity,
57
+ confidence: "medium",
58
+ status: "potential",
59
+ description: `Custom rule from a rules file: ${title}`,
60
+ remediation: typeof remediation === "string" ? remediation : "Follow the guidance of whoever maintains the rules file.",
61
+ falsePositives: "Depends on the custom pattern.",
62
+ verification: "Re-run the audit with the same --rules file.",
63
+ applies: (f) => !globs.length || globs.some((g) => g.test(f.path)),
64
+ check: (f) => {
65
+ const group = secretGroup;
66
+ // A match without the secret group would leave the value unredacted, so the whole match is used.
67
+ return lineRule(f, re, group === undefined ? {} : { secretGroup: group });
68
+ }
69
+ };
70
+ return { rule, match: match, noMatch: noMatch };
71
+ });
72
+ }
73
+ /** Failed examples, as readable messages. */
74
+ export function testCustomRules(rules) {
75
+ const failures = [];
76
+ for (const { rule, match, noMatch } of rules) {
77
+ const hits = (line) => rule.check({ path: "example", name: "example", ext: "", text: line, lines: [line] }).length > 0;
78
+ for (const line of match)
79
+ if (!hits(line))
80
+ failures.push(`${rule.id}: should match: ${line}`);
81
+ for (const line of noMatch)
82
+ if (hits(line))
83
+ failures.push(`${rule.id}: should not match: ${line}`);
84
+ }
85
+ return failures;
86
+ }
package/dist/decode.js ADDED
@@ -0,0 +1,9 @@
1
+ /** Bytes of a text file as a string, or null for binary data. UTF-16 is recognised by its byte-order mark. */
2
+ export function decodeText(buf) {
3
+ const le = buf[0] === 0xff && buf[1] === 0xfe;
4
+ if (le || (buf[0] === 0xfe && buf[1] === 0xff)) {
5
+ const body = Buffer.from(buf.subarray(2, buf.length - (buf.length % 2)));
6
+ return (le ? body : body.swap16()).toString("utf16le");
7
+ }
8
+ return buf.subarray(0, 8192).includes(0) ? null : buf.toString("utf8");
9
+ }
package/dist/engine.js CHANGED
@@ -8,10 +8,11 @@ import { blobHash, revisionTree, scanHistory, stagedBlobs } from "./git-objects.
8
8
  import { readComponents } from "./components.js";
9
9
  import { matchAdvisories, openAdvisoryDb } from "./advisories.js";
10
10
  import { propagateTaint } from "./taint.js";
11
- import { DEFAULT_POLICY, loadPolicy } from "./policy.js";
11
+ import { DEFAULT_POLICY, loadPolicy, makeIgnoreMatcher, SECRETS_ONLY, waiverCovers } from "./policy.js";
12
12
  import { redactSpan, scrubTokens, tidy } from "./redact.js";
13
+ import { stamp } from "./clock.js";
13
14
  import { SEVERITY_ORDER } from "./types.js";
14
- export const VERSION = "0.4.2";
15
+ export const VERSION = "0.5.0";
15
16
  /** Per rule, per file. Keeps one noisy file from producing an unbounded report. */
16
17
  export const MAX_PER_RULE_PER_FILE = 200;
17
18
  function sha(s) {
@@ -37,14 +38,31 @@ function redactAll(line, spans) {
37
38
  out = redactSpan(out, sp);
38
39
  return out;
39
40
  }
41
+ /** Ranges of every occurrence of each secret value in `text`. */
42
+ function spansOf(text, secrets) {
43
+ const spans = [];
44
+ for (const s of new Set(secrets)) {
45
+ for (let i = s ? text.indexOf(s) : -1; i >= 0; i = text.indexOf(s, i + s.length))
46
+ spans.push([i, i + s.length]);
47
+ }
48
+ return spans;
49
+ }
40
50
  function fingerprint(rule, path, hit, occurrence, spans) {
41
51
  const basis = redactAll(hit.excerpt ?? "", spans).replace(/\s+/g, " ").trim();
42
52
  return sha(`${rule.id}|${rule.version}|${path}|${basis}|${occurrence}`).slice(0, 32);
43
53
  }
44
- function toFinding(rule, file, hit, occurrence, spans = hit.secretSpan ? [hit.secretSpan] : []) {
54
+ function toFinding(rule, file, hit, occurrence, secrets = hit.secrets ?? []) {
55
+ const spans = spansOf(hit.excerpt ?? "", secrets);
45
56
  const redacted = spans.length > 0 || rule.category === "secrets";
46
- let excerpt = tidy(redactAll(hit.excerpt ?? "", spans));
47
- excerpt = scrubTokens(excerpt);
57
+ const clean = (text, ranges) => scrubTokens(redactAll(text, ranges));
58
+ let shown = clean(hit.excerpt ?? "", spans);
59
+ // Long lines: start the excerpt shortly before the match. Redaction happens first, so a cut cannot expose part of a secret.
60
+ if ((hit.at ?? 0) > 120) {
61
+ const before = clean(hit.excerpt.slice(0, hit.at), spans.filter((s) => s[1] <= hit.at)).length;
62
+ if (before > 60)
63
+ shown = "…" + shown.slice(before - 60);
64
+ }
65
+ const excerpt = tidy(shown);
48
66
  const fp = fingerprint(rule, file.path, hit, occurrence, spans);
49
67
  const testCtx = file.path !== "." && isTestPath(file.path) && rule.category !== "process";
50
68
  return {
@@ -116,7 +134,13 @@ export function audit(opts) {
116
134
  const staged = stagedBlobs(root);
117
135
  if (!staged)
118
136
  throw new Error("--staged needs a readable git index in this project");
119
- files = staged.map((s) => ({ path: s.path, name: basename(s.path).toLowerCase(), ext: extname(s.path).toLowerCase(), text: s.text, lines: s.text.split(/\r\n|\n|\r/) }));
137
+ // The index gets the same ignore patterns and size limit as the worktree.
138
+ const ignored = makeIgnoreMatcher(policy.ignore);
139
+ files = staged
140
+ .filter((s) => !ignored(s.path) && Buffer.byteLength(s.text) <= policy.maxFileSize)
141
+ .map((s) => ({ path: s.path, name: basename(s.path).toLowerCase(), ext: extname(s.path).toLowerCase(), text: s.text, lines: s.text.split(/\r\n|\n|\r/) }));
142
+ if (files.length < staged.length)
143
+ extraNotes.push(`${staged.length - files.length} staged file(s) were skipped by ignore patterns or the file size limit.`);
120
144
  extraNotes.push("Staged scan reads blobs in the git index. The worktree and older history were not scanned.");
121
145
  }
122
146
  else if (opts.since) {
@@ -131,6 +155,10 @@ export function audit(opts) {
131
155
  const hist = scanHistory(root, policy.ignore, current, deadline);
132
156
  files = files.concat(hist.files);
133
157
  extraNotes.push(...hist.notes);
158
+ if (hist.capped) {
159
+ inv.stats.truncated = true;
160
+ inv.stats.truncatedReason = inv.stats.truncatedReason ?? "git history stopped at the time limit";
161
+ }
134
162
  historyRan = hist.commitsSeen > 0 || hist.notes.some((n) => n.startsWith("Git history read"));
135
163
  }
136
164
  else {
@@ -143,7 +171,10 @@ export function audit(opts) {
143
171
  extraNotes.push(opened.note);
144
172
  let capped = 0;
145
173
  const disabled = new Set(policy.disableRules.map((r) => r.toUpperCase()));
146
- const rules = ALL_RULES.filter((r) => !disabled.has(r.id));
174
+ const rules = ALL_RULES.concat(opts.extraRules ?? []).filter((r) => !disabled.has(r.id));
175
+ if (opts.extraRules?.length)
176
+ extraNotes.push(`${opts.extraRules.length} custom rule(s) from --rules were applied.`);
177
+ const generated = makeIgnoreMatcher(SECRETS_ONLY);
147
178
  const baseline = opts.baselineFile ? loadBaseline(opts.baselineFile) : new Set();
148
179
  let findings = [];
149
180
  for (const file of files) {
@@ -155,8 +186,11 @@ export function audit(opts) {
155
186
  }
156
187
  const raw = [];
157
188
  // Every secret span found on a line is redacted from every finding that quotes that line.
158
- const lineSpans = new Map();
189
+ const lineSecrets = new Map();
190
+ const secretsOnly = generated(file.path);
159
191
  for (const rule of rules) {
192
+ if (secretsOnly && rule.category !== "secrets")
193
+ continue;
160
194
  let applies = false;
161
195
  try {
162
196
  applies = rule.applies(file);
@@ -176,8 +210,8 @@ export function audit(opts) {
176
210
  }
177
211
  raw.push({ rule, hits });
178
212
  for (const h of hits) {
179
- if (h.secretSpan)
180
- lineSpans.set(h.line, [...(lineSpans.get(h.line) ?? []), h.secretSpan]);
213
+ if (h.secrets)
214
+ lineSecrets.set(h.line, [...(lineSecrets.get(h.line) ?? []), ...h.secrets]);
181
215
  }
182
216
  }
183
217
  for (const { rule, hits } of raw) {
@@ -191,13 +225,14 @@ export function audit(opts) {
191
225
  const key = `${hit.excerpt ?? ""}`;
192
226
  const n = seen.get(key) ?? 0;
193
227
  seen.set(key, n + 1);
194
- findings.push(toFinding(rule, file, hit, n, lineSpans.get(hit.line) ?? []));
228
+ const noted = file.note ? { ...hit, note: [hit.note, file.note].filter(Boolean).join(" ") } : hit;
229
+ findings.push(toFinding(rule, file, noted, n, lineSecrets.get(hit.line) ?? []));
195
230
  }
196
231
  }
197
232
  }
198
233
  const advRule = findRule("VS-SUPPLY-004");
199
234
  if (advRule && opened.db && !disabled.has(advRule.id)) {
200
- const matches = matchAdvisories(readComponents(root), opened.db);
235
+ const matches = matchAdvisories(readComponents(root, makeIgnoreMatcher(policy.ignore.slice(DEFAULT_POLICY.ignore.length))), opened.db);
201
236
  const shown = matches.slice(0, 500);
202
237
  if (matches.length > shown.length)
203
238
  extraNotes.push(`${matches.length - shown.length} advisory match(es) were not listed (cap 500).`);
@@ -229,7 +264,9 @@ export function audit(opts) {
229
264
  suppressed++;
230
265
  return false;
231
266
  }
232
- const waiver = policy.waivers.find((w) => w.ruleId === f.ruleId && w.path === f.path);
267
+ const waiver = policy.waivers.filter((w) => waiverCovers(w, f.ruleId, f.path, f.startLine))
268
+ // An expired waiver must not shadow a current one for the same finding.
269
+ .sort((a, b) => (a.until < b.until ? 1 : -1))[0];
233
270
  if (!waiver)
234
271
  return true;
235
272
  if (waiver.until < today) {
@@ -262,7 +299,7 @@ export function audit(opts) {
262
299
  opened.db
263
300
  ? "Advisory matches use the database shipped with this version. It is a snapshot of recorded ranges, not a live feed, and it does not prove a vulnerable function is reachable."
264
301
  : "No advisory database was loaded, so known vulnerabilities were not matched.",
265
- "Untracked .env files are not read when a git index is present. .env.example, .env.sample and .env.template are never treated as secret files.",
302
+ "Untracked .env files are not read when a git index is present. In .env.example, .env.sample and .env.template only values that look real are reported.",
266
303
  "Lines longer than 2,000 characters are scanned in overlapping windows. The excerpt is the window that matched.",
267
304
  "When a filesystem reports inode 0, a swapped file is refused only when size or mtime also changes.",
268
305
  "Git history is read until the time limit. A blob larger than 1 MiB is skipped. SHA-1 and SHA-256 object ids are both read.",
@@ -286,7 +323,7 @@ export function audit(opts) {
286
323
  return {
287
324
  schemaVersion: "1.0",
288
325
  tool: { name: "vigilsutra", version: VERSION, rulesVersion: RULES_VERSION },
289
- generatedAt: new Date().toISOString(),
326
+ generatedAt: stamp(),
290
327
  mode: "local",
291
328
  project: { name: basename(root), detected: detectProject(inv.files) },
292
329
  scope: inv.stats,
package/dist/fix.js CHANGED
@@ -17,11 +17,10 @@ const REPLACEMENTS = {
17
17
  { from: /NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*["']?0["']?/, to: "NODE_TLS_REJECT_UNAUTHORIZED=1" },
18
18
  { from: /\bverify\s*=\s*False\b/, to: "verify=True" }
19
19
  ],
20
+ // SHA-1 is never rewritten: protocols such as the WebSocket handshake and git object ids require it.
20
21
  "VS-CODE-006": [
21
22
  { from: /createHash\(\s*["']md5["']\s*\)/i, to: 'createHash("sha256")' },
22
- { from: /createHash\(\s*["']sha1["']\s*\)/i, to: 'createHash("sha256")' },
23
- { from: /hashlib\.md5\s*\(/i, to: "hashlib.sha256(" },
24
- { from: /hashlib\.sha1\s*\(/i, to: "hashlib.sha256(" }
23
+ { from: /hashlib\.md5\s*\(/i, to: "hashlib.sha256(" }
25
24
  ]
26
25
  };
27
26
  export function planFixes(findings, root) {
@@ -1,4 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { decodeText } from "./decode.js";
2
3
  import { lstatSync, readdirSync, readFileSync } from "node:fs";
3
4
  import { join, relative, resolve, extname, basename, isAbsolute } from "node:path";
4
5
  import { inflateSync } from "node:zlib";
@@ -374,6 +375,11 @@ function commitTree(obj) {
374
375
  const m = /^tree ([0-9a-f]{64}|[0-9a-f]{40})/m.exec(obj.data.toString("utf8"));
375
376
  return m ? m[1] : null;
376
377
  }
378
+ /** Committer date as YYYY-MM-DD. Author names and addresses are not copied into reports. */
379
+ function commitDate(obj) {
380
+ const m = /^committer [^\n]*> (\d{1,11}) [+-]\d{4}$/m.exec(obj.data.toString("utf8"));
381
+ return m ? new Date(Number(m[1]) * 1000).toISOString().slice(0, 10) : null;
382
+ }
377
383
  function commitParents(obj) {
378
384
  const out = [];
379
385
  for (const line of obj.data.toString("utf8").split("\n")) {
@@ -422,6 +428,7 @@ export function scanHistory(scanRoot, ignore, current, deadline) {
422
428
  const seenCommits = new Set();
423
429
  const seenBlobs = new Set();
424
430
  const queue = [head];
431
+ let inHead;
425
432
  const files = [];
426
433
  let capped = false;
427
434
  while (queue.length) {
@@ -443,6 +450,7 @@ export function scanHistory(scanRoot, ignore, current, deadline) {
443
450
  if (!tree)
444
451
  continue;
445
452
  const blobs = flatten(store, tree, "");
453
+ inHead ??= blobs; // the first commit read is HEAD
446
454
  for (const [path, blobSha] of blobs) {
447
455
  if (prefix && !path.startsWith(prefix))
448
456
  continue;
@@ -458,10 +466,12 @@ export function scanHistory(scanRoot, ignore, current, deadline) {
458
466
  const obj = store.get(blobSha);
459
467
  if (!obj || obj.type !== "blob" || obj.data.length > HISTORY_MAX_BLOB_BYTES)
460
468
  continue;
461
- if (obj.data.subarray(0, 8192).includes(0))
462
- continue;
463
- const text = obj.data.toString("utf8");
464
- files.push(virtualFile(`git-history/${sha.slice(0, 12)}/${rel}`, text));
469
+ const text = decodeText(obj.data);
470
+ if (text === null || text === current.get(rel))
471
+ continue; // UTF-16 files do not match by blob hash
472
+ const date = commitDate(commit);
473
+ const note = `Newest commit holding this version: ${sha.slice(0, 12)}${date ? `, ${date}` : ""}. The file ${inHead.has(path) ? "still exists" : "no longer exists"} in HEAD. Deleting does not remove history: rotate any secret at the provider.`;
474
+ files.push({ ...virtualFile(`git-history/${sha.slice(0, 12)}/${rel}`, text), note });
465
475
  }
466
476
  }
467
477
  const notes = [...store.notes];
@@ -539,9 +549,9 @@ export function stagedBlobs(scanRoot) {
539
549
  const obj = store.get(e.sha);
540
550
  if (!obj || obj.type !== "blob" || obj.data.length > HISTORY_MAX_BLOB_BYTES)
541
551
  continue;
542
- if (obj.data.subarray(0, 8192).includes(0))
543
- continue;
544
- out.push({ path: e.path, text: obj.data.toString("utf8") });
552
+ const text = decodeText(obj.data);
553
+ if (text !== null)
554
+ out.push({ path: e.path, text });
545
555
  }
546
556
  return out;
547
557
  }
package/dist/policy.js CHANGED
@@ -3,22 +3,27 @@ import { join } from "node:path";
3
3
  export const DEFAULT_IGNORE = [
4
4
  "**/.git/**",
5
5
  "**/node_modules/**",
6
- "**/dist/**",
7
- "**/build/**",
8
- "**/out/**",
9
- "**/vendor/**",
10
6
  "**/.venv/**",
11
7
  "**/venv/**",
12
8
  "**/__pycache__/**",
13
9
  "**/coverage/**",
14
10
  "**/.next/**",
15
11
  "**/target/**",
12
+ "**/.cache/**",
13
+ "**/.turbo/**",
14
+ "**/.nuxt/**",
15
+ "**/.svelte-kit/**",
16
+ "**/.mypy_cache/**",
17
+ "**/.pytest_cache/**",
18
+ "**/.ruff_cache/**",
19
+ "**/.tox/**",
16
20
  "**/vigilsutra-report/**",
17
- "*.min.js",
18
21
  "package-lock.json",
19
22
  "yarn.lock",
20
23
  "pnpm-lock.yaml"
21
24
  ];
25
+ /** Generated and vendored files ship to users, so secret rules read them. Every other rule skips them. */
26
+ export const SECRETS_ONLY = ["**/dist/**", "**/build/**", "**/out/**", "**/vendor/**", "*.min.js"];
22
27
  export const DEFAULT_POLICY = {
23
28
  ignore: DEFAULT_IGNORE,
24
29
  maxFileSize: 1024 * 1024,
@@ -35,7 +40,7 @@ export const DEFAULT_POLICY = {
35
40
  export function parsePolicy(text) {
36
41
  const out = {};
37
42
  let listKey = null;
38
- const lines = text.split(/\r?\n/);
43
+ const lines = text.replace(/^\uFEFF/, "").split(/\r?\n/); // Windows editors add a byte-order mark
39
44
  for (let i = 0; i < lines.length; i++) {
40
45
  const raw = lines[i].replace(/\s+#.*$/, "").replace(/^#.*$/, "");
41
46
  if (!raw.trim())
@@ -85,9 +90,11 @@ export function parsePolicy(text) {
85
90
  }
86
91
  function parseWaiver(item) {
87
92
  const parts = item.split("|").map((s) => s.trim());
88
- if (parts.length !== 4)
89
- throw new Error(`.vigilsutra.yml: waiver must be ruleId|path|owner|YYYY-MM-DD`);
90
- const [ruleId, path, owner, until] = parts;
93
+ if (parts.length < 4 || parts.length > 5)
94
+ throw new Error(`.vigilsutra.yml: waiver must be ruleId|path[:line]|owner|YYYY-MM-DD[|reason]`);
95
+ const [ruleId, target, owner, until, reason] = parts;
96
+ const at = /^(.*):([1-9]\d*)$/.exec(target);
97
+ const path = at ? at[1] : target;
91
98
  if (!/^VS-[A-Z]+-\d{3}$/.test(ruleId))
92
99
  throw new Error(`.vigilsutra.yml: waiver rule id "${ruleId}" is not a rule id`);
93
100
  if (!path || path.startsWith("/") || path.split("/").includes(".."))
@@ -96,7 +103,7 @@ function parseWaiver(item) {
96
103
  throw new Error(`.vigilsutra.yml: waiver needs an owner`);
97
104
  if (!/^\d{4}-\d{2}-\d{2}$/.test(until) || Number.isNaN(Date.parse(until + "T00:00:00Z")))
98
105
  throw new Error(`.vigilsutra.yml: waiver until must be YYYY-MM-DD`);
99
- return { ruleId, path, owner, until };
106
+ return { ruleId, path, owner, until, ...(at ? { line: Number(at[2]) } : {}), ...(reason ? { reason } : {}) };
100
107
  }
101
108
  function stripQuotes(s) {
102
109
  return /^(['"]).*\1$/.test(s) ? s.slice(1, -1) : s;
@@ -148,6 +155,12 @@ export function globToRegExp(glob) {
148
155
  // A pattern without a slash matches the base name at any depth.
149
156
  return glob.includes("/") ? new RegExp(`^${re}$`) : new RegExp(`(^|/)${re}$`);
150
157
  }
158
+ /** Exact path, or a glob only when the waiver path contains a wildcard, so a plain name never widens. */
159
+ export function waiverCovers(w, ruleId, path, line) {
160
+ if (w.ruleId !== ruleId || (w.line !== undefined && w.line !== line))
161
+ return false;
162
+ return /[*?]/.test(w.path) ? globToRegExp(w.path).test(path) : w.path === path;
163
+ }
151
164
  export function makeIgnoreMatcher(patterns) {
152
165
  const res = patterns.map(globToRegExp);
153
166
  return (p) => res.some((r) => r.test(p));
package/dist/redact.js CHANGED
@@ -7,7 +7,7 @@ export function redactSpan(text, span) {
7
7
  /** Collapse whitespace and cap length so excerpts stay small and diff-stable. */
8
8
  export function tidy(excerpt, max = 200) {
9
9
  // Control characters (for example ANSI escapes) in scanned files must never reach a terminal or report.
10
- const t = excerpt.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f‪-‮⁦-⁩]/g, "?").replace(/\s+/g, " ").trim();
10
+ const t = excerpt.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, "?").replace(/\s+/g, " ").trim();
11
11
  return t.length > max ? t.slice(0, max) + "…" : t;
12
12
  }
13
13
  /** Defence in depth: scrub well-known token shapes that survive in any excerpt. */
@@ -0,0 +1,13 @@
1
+ /** GitHub workflow command escaping; properties also escape the separators. */
2
+ const data = (s) => s.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
3
+ const prop = (s) => data(s).replace(/:/g, "%3A").replace(/,/g, "%2C");
4
+ /** One annotation per finding that points at a file in the checkout, most severe first. */
5
+ export function annotations(r) {
6
+ return r.findings
7
+ .filter((f) => f.path !== "." && !f.path.startsWith("git-history/"))
8
+ .map((f) => {
9
+ const level = f.severity === "critical" || f.severity === "high" ? "error" : f.severity === "medium" ? "warning" : "notice";
10
+ return `::${level} file=${prop(f.path)},line=${f.startLine},title=${prop(f.ruleId)}::${data(f.title)}\n`;
11
+ })
12
+ .join("");
13
+ }
@@ -9,7 +9,7 @@ export function toJson(r) {
9
9
  export function toText(r, color = false) {
10
10
  const c = (code, s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
11
11
  // File names come from the scanned project and are untrusted: neutralize terminal control characters.
12
- const safe = (t) => t.replace(/[\u0000-\u001f\u007f-\u009f‪-‮⁦-⁩]/g, "?");
12
+ const safe = (t) => t.replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, "?");
13
13
  const paint = { critical: "1;31", high: "31", medium: "33", low: "36", info: "2" };
14
14
  const out = [];
15
15
  out.push(`VigilSutra AI ${r.tool.version} - local read-only audit of "${safe(r.project.name)}"`);
@@ -30,6 +30,11 @@ export function toText(r, color = false) {
30
30
  return out.join("\n") + "\n";
31
31
  }
32
32
  const level = (s) => (s === "critical" || s === "high" ? "error" : s === "medium" ? "warning" : "note");
33
+ /** GitHub code scanning ranks alerts by this score. */
34
+ const SCORE = { critical: "9.5", high: "8.0", medium: "5.5", low: "3.0", info: "0.0" };
35
+ const RULE_DOCS = "https://github.com/shahvatsalofficial/vigilsutra/blob/main/docs/rules.md#";
36
+ /** The anchor GitHub generates for a `### ID: title` heading. */
37
+ const anchor = (heading) => heading.toLowerCase().replace(/[^a-z0-9 _-]/g, "").replace(/ /g, "-");
33
38
  export function toSarif(r) {
34
39
  const used = new Set(r.findings.map((f) => f.ruleId));
35
40
  const rules = ALL_RULES.filter((x) => used.has(x.id)).map((x) => ({
@@ -38,8 +43,9 @@ export function toSarif(r) {
38
43
  shortDescription: { text: x.title },
39
44
  fullDescription: { text: x.description },
40
45
  help: { text: `${x.remediation}\nVerify: ${x.verification}` },
46
+ helpUri: RULE_DOCS + anchor(`${x.id}: ${x.title}`),
41
47
  defaultConfiguration: { level: level(x.severity) },
42
- properties: { tags: ["security", x.category, ...(x.cwe ?? [])], precision: x.confidence }
48
+ properties: { tags: ["security", x.category, ...(x.cwe ?? [])], precision: x.confidence, "security-severity": SCORE[x.severity] }
43
49
  }));
44
50
  const sarif = {
45
51
  $schema: "https://json.schemastore.org/sarif-2.1.0.json",
@@ -47,6 +53,7 @@ export function toSarif(r) {
47
53
  runs: [
48
54
  {
49
55
  tool: { driver: { name: "VigilSutra AI", version: r.tool.version, informationUri: "https://github.com/shahvatsalofficial/vigilsutra", rules } },
56
+ automationDetails: { id: "vigilsutra/" },
50
57
  results: r.findings.map((f) => ({
51
58
  ruleId: f.ruleId,
52
59
  level: level(f.severity),
@@ -8,7 +8,7 @@ export const htmlEsc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").rep
8
8
  export function plainSummary(r) {
9
9
  const b = r.summary.bySeverity;
10
10
  if (r.summary.total === 0)
11
- return "No problems were found by the 32 built-in checks. That is not proof the project is secure: some areas are not checked (see Scope and limits).";
11
+ return "No problems were found by the built-in checks. That is not proof the project is secure: some areas are not checked (see Scope and limits).";
12
12
  const urgent = b.critical + b.high;
13
13
  if (urgent > 0)
14
14
  return `Start with the ${urgent} critical and high item${urgent === 1 ? "" : "s"}. They are the most likely to cause real harm. The rest can be scheduled afterwards.`;
@@ -97,15 +97,17 @@ const md = (s) => htmlEsc(s)
97
97
  .replace(/\*([^*]+)\*/g, "<em>$1</em>")
98
98
  .replace(/`([^`]+)`/g, "<code>$1</code>");
99
99
  const CSS = `
100
- :root{--bg:#f6f7fb;--card:#fff;--text:#161a2b;--muted:#586079;--line:#dde1ee;--accent:#3b46d9;--crit:#7a0f1a;--high:#c0392b;--med:#b9770e;--low:#2563eb;--info:#6b7280;--ok:#0f7a4d}
101
- @media (prefers-color-scheme:dark){:root{--bg:#0d111c;--card:#151b2e;--text:#e8ebf7;--muted:#9aa4c2;--line:#27304f;--accent:#8c96ff;--crit:#ff6b7d;--high:#ff8a80;--med:#f2c35b;--low:#7aa7ff;--info:#9aa4c2;--ok:#52d6a0}}
100
+ :root{--bg:#f6f7fb;--card:#fff;--text:#161a2b;--muted:#586079;--line:#dde1ee;--accent:#3b46d9;--crit:#7a0f1a;--high:#b03024;--med:#8a5800;--low:#1d4fc4;--info:#4b5563;--ok:#0f7a4d;--on:#fff}
101
+ @media (prefers-color-scheme:dark){:root{--bg:#0d111c;--card:#151b2e;--text:#e8ebf7;--muted:#9aa4c2;--line:#27304f;--accent:#8c96ff;--crit:#ff6b7d;--high:#ff8a80;--med:#f2c35b;--low:#7aa7ff;--info:#9aa4c2;--ok:#52d6a0;--on:#0d111c}}
102
102
  *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:16px/1.65 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
103
103
  main{max-width:62rem;margin:0 auto;padding:1.5rem 1rem 4rem}h1{font-size:1.9rem;margin:.2rem 0}h2{margin:2.2rem 0 .7rem;font-size:1.35rem}
104
104
  .meta{color:var(--muted);font-size:.9rem}.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:1rem 1.2rem;margin:.8rem 0}
105
105
  .lead{font-size:1.15rem;font-weight:600}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(8.5rem,1fr));gap:.7rem}
106
106
  .stat{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:.7rem 1rem}.stat b{display:block;font-size:1.7rem;line-height:1.1}.stat span{color:var(--muted);font-size:.85rem}
107
107
  .bar{height:.5rem;border-radius:99px;background:var(--line);margin-top:.5rem;overflow:hidden}.bar i{display:block;height:100%}
108
- .sev{display:inline-block;padding:.05rem .55rem;border-radius:6px;font-size:.75rem;font-weight:700;text-transform:uppercase;color:#fff}
108
+ .sev{display:inline-block;padding:.05rem .55rem;border-radius:6px;font-size:.75rem;font-weight:700;text-transform:uppercase;color:var(--on)}
109
+ .filters{display:flex;flex-wrap:wrap;gap:.4rem 1.1rem;border:0;padding:0;margin:.6rem 0}.filters label{cursor:pointer;min-height:2rem;display:inline-flex;align-items:center;gap:.35rem}
110
+ ${SEV.map((s) => `body:has(#show-${s}:not(:checked)) .f-${s}{display:none}`).join("")}
109
111
  .critical{background:var(--crit)}.high{background:var(--high)}.medium{background:var(--med)}.low{background:var(--low)}.info{background:var(--info)}
110
112
  .chip{display:inline-block;padding:.05rem .55rem;border-radius:99px;border:1px solid var(--line);font-size:.78rem;color:var(--muted);margin-right:.3rem}
111
113
  details{background:var(--card);border:1px solid var(--line);border-radius:10px;margin:.5rem 0;padding:.1rem 1rem}summary{cursor:pointer;padding:.7rem 0;font-weight:600}
@@ -116,7 +118,7 @@ th,td{border-bottom:1px solid var(--line);padding:.45rem .5rem;text-align:left;v
116
118
  a{color:var(--accent)}dt{font-weight:700;margin-top:.5rem}dd{margin:0 0 .3rem 0;color:var(--muted)}footer{color:var(--muted);font-size:.85rem;margin-top:2.5rem}
117
119
  @media print{details{break-inside:avoid}details>*{display:block}}`;
118
120
  function findingHtml(f, i) {
119
- return `<details id="f-${htmlEsc(f.fingerprint.slice(0, 12))}"${f.severity === "critical" || f.severity === "high" ? " open" : ""}>
121
+ return `<details class="f-${f.severity}" id="f-${htmlEsc(f.fingerprint.slice(0, 12))}"${f.severity === "critical" || f.severity === "high" ? " open" : ""}>
120
122
  <summary><span class="sev ${f.severity}">${f.severity}</span> ${htmlEsc(f.ruleId)}: ${htmlEsc(f.title)}</summary>
121
123
  <p class="where">${htmlEsc(f.path)}:${f.startLine}</p>
122
124
  <p><span class="chip">${htmlEsc(f.status)}</span><span class="chip">confidence ${htmlEsc(f.confidence)}</span>${f.pathContext ? '<span class="chip">test, example or vendored path</span>' : ""}${f.cwe.map((c) => `<span class="chip">${htmlEsc(c)}</span>`).join("")}</p>
@@ -136,9 +138,9 @@ export function toHtml(r) {
136
138
  const g = r.findings.filter((f) => f.severity === s);
137
139
  if (!g.length)
138
140
  return "";
139
- return `<h3>${SEV_LABEL[s]} (${g.length})</h3>\n${g.map((f) => findingHtml(f, ++n)).join("\n")}`;
141
+ return `<h3 class="f-${s}">${SEV_LABEL[s]} (${g.length})</h3>\n${g.map((f) => findingHtml(f, ++n)).join("\n")}`;
140
142
  }).join("\n");
141
- const rows = r.findings.map((f, i) => `<tr><td>${i + 1}</td><td><span class="sev ${f.severity}">${f.severity}</span></td><td>${htmlEsc(f.ruleId)}</td><td>${htmlEsc(f.title)}</td><td class="where"><a href="#f-${htmlEsc(f.fingerprint.slice(0, 12))}">${htmlEsc(f.path)}:${f.startLine}</a></td><td>${htmlEsc(f.status)}</td></tr>`).join("");
143
+ const rows = r.findings.map((f, i) => `<tr class="f-${f.severity}"><td>${i + 1}</td><td><span class="sev ${f.severity}">${f.severity}</span></td><td>${htmlEsc(f.ruleId)}</td><td>${htmlEsc(f.title)}</td><td class="where"><a href="#f-${htmlEsc(f.fingerprint.slice(0, 12))}">${htmlEsc(f.path)}:${f.startLine}</a></td><td>${htmlEsc(f.status)}</td></tr>`).join("");
142
144
  return `<!doctype html>
143
145
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
144
146
  <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'">
@@ -155,6 +157,7 @@ ${top.length ? `<h2>Top priorities</h2><ol>${top.map((f) => `<li><a href="#f-${h
155
157
  <h2>How to read this report</h2>
156
158
  <dl>${READING_GUIDE.map(([k, v]) => `<dt>${htmlEsc(k)}</dt><dd>${md(v)}</dd>`).join("")}</dl>
157
159
  <h2>All findings</h2>
160
+ ${r.findings.length ? `<fieldset class="filters"><legend class="meta">Show severities</legend>${SEV.filter((s) => r.summary.bySeverity[s]).map((s) => `<label><input type="checkbox" id="show-${s}" checked> ${SEV_LABEL[s]} (${r.summary.bySeverity[s]})</label>`).join("")}</fieldset>` : ""}
158
161
  ${r.findings.length ? `<div class="tw card"><table><thead><tr><th>#</th><th>Severity</th><th>Rule</th><th>What</th><th>Where</th><th>Status</th></tr></thead><tbody>${rows}</tbody></table></div>` : "<p>No findings from the implemented rules. This is not proof of security.</p>"}
159
162
  <h2>Details</h2>
160
163
  ${groups || "<p>Nothing to show.</p>"}
@@ -5,7 +5,35 @@ const pr = { version: "1.0.0", category: "process", agent: "Prime" };
5
5
  const AGENT_FILE = (p) => /(^|\/)(agents\.md|claude\.md|gemini\.md|\.cursorrules|copilot-instructions\.md|skill\.md|\.windsurfrules)$/i.test(p) ||
6
6
  /(^|\/)\.cursor\/rules\//i.test(p) ||
7
7
  /(^|\/)\.claude\/(?:agents|commands)\//i.test(p);
8
+ // Direction controls and tag characters are never needed in source. Zero-width space and word joiner
9
+ // are also flagged in instruction files; the joiners used by emoji and Indic scripts are not.
10
+ const HIDDEN_IN_CODE = /[\u202a-\u202e\u2066-\u2069]|(?<!\u{1f3f4}[\u{e0020}-\u{e007f}]*)[\u{e0000}-\u{e007f}]/u;
11
+ const HIDDEN_IN_AGENT = new RegExp(`${HIDDEN_IN_CODE.source}|[\\u200b\\u2060]`, "u");
12
+ const SOURCE_EXT = /\.(?:[cm]?[jt]sx?|py|go|rs|java|kt|c|h|cc|cpp|hpp|cs|rb|php|swift|sh|ps1|tf|ya?ml)$/;
13
+ /** Makes each invisible character visible, so the report shows what a reviewer cannot see in an editor. */
14
+ const reveal = (s) => s.replace(/[\u200b\u2060\u202a-\u202e\u2066-\u2069\u{e0000}-\u{e007f}]/gu, (c) => `<U+${c.codePointAt(0).toString(16).toUpperCase().padStart(4, "0")}>`);
8
15
  export const agentPrivacyRules = [
16
+ {
17
+ ...ag,
18
+ id: "VS-AGENT-004",
19
+ title: "Hidden Unicode characters in code or agent instructions",
20
+ severity: "medium",
21
+ confidence: "high",
22
+ status: "potential",
23
+ cwe: ["CWE-1007"],
24
+ description: "Invisible or direction-changing characters make a file read differently to a person than to a compiler or AI assistant (Trojan Source, rules-file backdoor).",
25
+ remediation: "Delete the characters, then read the line again. Treat hidden text in an instruction file as hostile until its author explains it.",
26
+ falsePositives: "Right-to-left text that needs direction controls in a string, and test data about Unicode.",
27
+ verification: "Re-run `vigilsutra audit`; an editor that shows invisible characters displays none on the line.",
28
+ applies: (f) => AGENT_FILE(f.path) || SOURCE_EXT.test(f.name),
29
+ check: (f) => {
30
+ const agent = AGENT_FILE(f.path);
31
+ return lineRule(f, agent ? HIDDEN_IN_AGENT : HIDDEN_IN_CODE).map((h) => {
32
+ const excerpt = reveal(h.excerpt ?? "");
33
+ return { ...h, excerpt, at: excerpt.indexOf("<U+"), ...(agent ? { severity: "high" } : {}) };
34
+ });
35
+ }
36
+ },
9
37
  {
10
38
  ...ag,
11
39
  id: "VS-AGENT-001",