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 +76 -0
- package/README.md +34 -2
- package/dist/cli.js +109 -22
- package/dist/clock.js +8 -0
- package/dist/components.js +134 -53
- package/dist/custom-rules.js +86 -0
- package/dist/decode.js +9 -0
- package/dist/engine.js +73 -19
- package/dist/fix.js +2 -3
- package/dist/git-objects.js +17 -7
- package/dist/policy.js +24 -11
- package/dist/redact.js +1 -1
- package/dist/reporters/annotations.js +13 -0
- package/dist/reporters/index.js +9 -2
- package/dist/reporters/rich.js +10 -7
- package/dist/rules/agents-privacy.js +28 -0
- package/dist/rules/code.js +146 -9
- package/dist/rules/index.js +1 -1
- package/dist/rules/infra.js +230 -20
- package/dist/rules/secrets.js +17 -7
- package/dist/rules/util.js +56 -14
- package/dist/scope.js +2 -5
- package/dist/suggest.js +18 -0
- package/docs/rules.md +162 -9
- package/llms.txt +2 -2
- package/package.json +1 -2
- package/policies/safe-default.yaml +3 -2
- package/schemas/finding.schema.json +1 -1
|
@@ -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.
|
|
15
|
+
export const VERSION = "0.6.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,17 +38,40 @@ 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
|
+
}
|
|
50
|
+
/** Identity of a finding without its path, so a baseline can follow a moved file. */
|
|
51
|
+
const contentKeys = new WeakMap();
|
|
52
|
+
export const contentKey = (f) => contentKeys.get(f);
|
|
40
53
|
function fingerprint(rule, path, hit, occurrence, spans) {
|
|
41
54
|
const basis = redactAll(hit.excerpt ?? "", spans).replace(/\s+/g, " ").trim();
|
|
42
55
|
return sha(`${rule.id}|${rule.version}|${path}|${basis}|${occurrence}`).slice(0, 32);
|
|
43
56
|
}
|
|
44
|
-
function
|
|
57
|
+
function pathless(rule, hit, occurrence, spans) {
|
|
58
|
+
return fingerprint(rule, "", hit, occurrence, spans);
|
|
59
|
+
}
|
|
60
|
+
function toFinding(rule, file, hit, occurrence, secrets = hit.secrets ?? []) {
|
|
61
|
+
const spans = spansOf(hit.excerpt ?? "", secrets);
|
|
45
62
|
const redacted = spans.length > 0 || rule.category === "secrets";
|
|
46
|
-
|
|
47
|
-
|
|
63
|
+
const clean = (text, ranges) => scrubTokens(redactAll(text, ranges));
|
|
64
|
+
let shown = clean(hit.excerpt ?? "", spans);
|
|
65
|
+
// Long lines: start the excerpt shortly before the match. Redaction happens first, so a cut cannot expose part of a secret.
|
|
66
|
+
if ((hit.at ?? 0) > 120) {
|
|
67
|
+
const before = clean(hit.excerpt.slice(0, hit.at), spans.filter((s) => s[1] <= hit.at)).length;
|
|
68
|
+
if (before > 60)
|
|
69
|
+
shown = "…" + shown.slice(before - 60);
|
|
70
|
+
}
|
|
71
|
+
const excerpt = tidy(shown);
|
|
48
72
|
const fp = fingerprint(rule, file.path, hit, occurrence, spans);
|
|
49
73
|
const testCtx = file.path !== "." && isTestPath(file.path) && rule.category !== "process";
|
|
50
|
-
|
|
74
|
+
const finding = {
|
|
51
75
|
id: `${rule.id}-${fp.slice(0, 8)}`,
|
|
52
76
|
fingerprint: fp,
|
|
53
77
|
ruleId: rule.id,
|
|
@@ -74,6 +98,8 @@ function toFinding(rule, file, hit, occurrence, spans = hit.secretSpan ? [hit.se
|
|
|
74
98
|
note: testCtx ? [hit.note, "Located in a test, example, archived or vendored path; confidence lowered."].filter(Boolean).join(" ") : hit.note,
|
|
75
99
|
...(testCtx ? { pathContext: "test-or-example" } : {})
|
|
76
100
|
};
|
|
101
|
+
contentKeys.set(finding, pathless(rule, hit, occurrence, spans));
|
|
102
|
+
return finding;
|
|
77
103
|
}
|
|
78
104
|
export function detectProject(files) {
|
|
79
105
|
const has = (re) => files.some((f) => re.test(f.path));
|
|
@@ -100,7 +126,11 @@ export function loadBaseline(file) {
|
|
|
100
126
|
const data = JSON.parse(readFileSync(file, "utf8"));
|
|
101
127
|
if (!Array.isArray(data.fingerprints))
|
|
102
128
|
throw new Error("baseline file has no fingerprints array");
|
|
103
|
-
|
|
129
|
+
const entries = Array.isArray(data.entries) ? data.entries : [];
|
|
130
|
+
return {
|
|
131
|
+
fingerprints: new Set(data.fingerprints.filter((x) => typeof x === "string")),
|
|
132
|
+
entries: entries.filter((e) => typeof e?.path === "string" && typeof e.key === "string")
|
|
133
|
+
};
|
|
104
134
|
}
|
|
105
135
|
export function audit(opts) {
|
|
106
136
|
const root = realpathSync(opts.root);
|
|
@@ -116,7 +146,13 @@ export function audit(opts) {
|
|
|
116
146
|
const staged = stagedBlobs(root);
|
|
117
147
|
if (!staged)
|
|
118
148
|
throw new Error("--staged needs a readable git index in this project");
|
|
119
|
-
|
|
149
|
+
// The index gets the same ignore patterns and size limit as the worktree.
|
|
150
|
+
const ignored = makeIgnoreMatcher(policy.ignore);
|
|
151
|
+
files = staged
|
|
152
|
+
.filter((s) => !ignored(s.path) && Buffer.byteLength(s.text) <= policy.maxFileSize)
|
|
153
|
+
.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/) }));
|
|
154
|
+
if (files.length < staged.length)
|
|
155
|
+
extraNotes.push(`${staged.length - files.length} staged file(s) were skipped by ignore patterns or the file size limit.`);
|
|
120
156
|
extraNotes.push("Staged scan reads blobs in the git index. The worktree and older history were not scanned.");
|
|
121
157
|
}
|
|
122
158
|
else if (opts.since) {
|
|
@@ -131,6 +167,10 @@ export function audit(opts) {
|
|
|
131
167
|
const hist = scanHistory(root, policy.ignore, current, deadline);
|
|
132
168
|
files = files.concat(hist.files);
|
|
133
169
|
extraNotes.push(...hist.notes);
|
|
170
|
+
if (hist.capped) {
|
|
171
|
+
inv.stats.truncated = true;
|
|
172
|
+
inv.stats.truncatedReason = inv.stats.truncatedReason ?? "git history stopped at the time limit";
|
|
173
|
+
}
|
|
134
174
|
historyRan = hist.commitsSeen > 0 || hist.notes.some((n) => n.startsWith("Git history read"));
|
|
135
175
|
}
|
|
136
176
|
else {
|
|
@@ -143,8 +183,11 @@ export function audit(opts) {
|
|
|
143
183
|
extraNotes.push(opened.note);
|
|
144
184
|
let capped = 0;
|
|
145
185
|
const disabled = new Set(policy.disableRules.map((r) => r.toUpperCase()));
|
|
146
|
-
const rules = ALL_RULES.filter((r) => !disabled.has(r.id));
|
|
147
|
-
|
|
186
|
+
const rules = ALL_RULES.concat(opts.extraRules ?? []).filter((r) => !disabled.has(r.id));
|
|
187
|
+
if (opts.extraRules?.length)
|
|
188
|
+
extraNotes.push(`${opts.extraRules.length} custom rule(s) from --rules were applied.`);
|
|
189
|
+
const generated = makeIgnoreMatcher(SECRETS_ONLY);
|
|
190
|
+
const baseline = opts.baselineFile ? loadBaseline(opts.baselineFile) : { fingerprints: new Set(), entries: [] };
|
|
148
191
|
let findings = [];
|
|
149
192
|
for (const file of files) {
|
|
150
193
|
if (Date.now() > deadline) {
|
|
@@ -155,8 +198,11 @@ export function audit(opts) {
|
|
|
155
198
|
}
|
|
156
199
|
const raw = [];
|
|
157
200
|
// Every secret span found on a line is redacted from every finding that quotes that line.
|
|
158
|
-
const
|
|
201
|
+
const lineSecrets = new Map();
|
|
202
|
+
const secretsOnly = generated(file.path);
|
|
159
203
|
for (const rule of rules) {
|
|
204
|
+
if (secretsOnly && rule.category !== "secrets")
|
|
205
|
+
continue;
|
|
160
206
|
let applies = false;
|
|
161
207
|
try {
|
|
162
208
|
applies = rule.applies(file);
|
|
@@ -176,8 +222,8 @@ export function audit(opts) {
|
|
|
176
222
|
}
|
|
177
223
|
raw.push({ rule, hits });
|
|
178
224
|
for (const h of hits) {
|
|
179
|
-
if (h.
|
|
180
|
-
|
|
225
|
+
if (h.secrets)
|
|
226
|
+
lineSecrets.set(h.line, [...(lineSecrets.get(h.line) ?? []), ...h.secrets]);
|
|
181
227
|
}
|
|
182
228
|
}
|
|
183
229
|
for (const { rule, hits } of raw) {
|
|
@@ -191,13 +237,14 @@ export function audit(opts) {
|
|
|
191
237
|
const key = `${hit.excerpt ?? ""}`;
|
|
192
238
|
const n = seen.get(key) ?? 0;
|
|
193
239
|
seen.set(key, n + 1);
|
|
194
|
-
|
|
240
|
+
const noted = file.note ? { ...hit, note: [hit.note, file.note].filter(Boolean).join(" ") } : hit;
|
|
241
|
+
findings.push(toFinding(rule, file, noted, n, lineSecrets.get(hit.line) ?? []));
|
|
195
242
|
}
|
|
196
243
|
}
|
|
197
244
|
}
|
|
198
245
|
const advRule = findRule("VS-SUPPLY-004");
|
|
199
246
|
if (advRule && opened.db && !disabled.has(advRule.id)) {
|
|
200
|
-
const matches = matchAdvisories(readComponents(root), opened.db);
|
|
247
|
+
const matches = matchAdvisories(readComponents(root, makeIgnoreMatcher(policy.ignore.slice(DEFAULT_POLICY.ignore.length))), opened.db);
|
|
201
248
|
const shown = matches.slice(0, 500);
|
|
202
249
|
if (matches.length > shown.length)
|
|
203
250
|
extraNotes.push(`${matches.length - shown.length} advisory match(es) were not listed (cap 500).`);
|
|
@@ -225,11 +272,18 @@ export function audit(opts) {
|
|
|
225
272
|
let waiversExpired = 0;
|
|
226
273
|
const today = new Date().toISOString().slice(0, 10);
|
|
227
274
|
findings = findings.filter((f) => {
|
|
228
|
-
|
|
275
|
+
// A moved file: same content, and the accepted path no longer exists. Each entry covers one finding, so a copy is still reported.
|
|
276
|
+
const moved = baseline.entries.findIndex((e) => e.key === contentKeys.get(f) && f.path !== "." && !f.path.startsWith("git-history/") && !existsSync(join(root, e.path)));
|
|
277
|
+
const exact = baseline.fingerprints.has(f.fingerprint);
|
|
278
|
+
if (!exact && moved >= 0)
|
|
279
|
+
baseline.entries.splice(moved, 1);
|
|
280
|
+
if (exact || moved >= 0) {
|
|
229
281
|
suppressed++;
|
|
230
282
|
return false;
|
|
231
283
|
}
|
|
232
|
-
const waiver = policy.waivers.
|
|
284
|
+
const waiver = policy.waivers.filter((w) => waiverCovers(w, f.ruleId, f.path, f.startLine))
|
|
285
|
+
// An expired waiver must not shadow a current one for the same finding.
|
|
286
|
+
.sort((a, b) => (a.until < b.until ? 1 : -1))[0];
|
|
233
287
|
if (!waiver)
|
|
234
288
|
return true;
|
|
235
289
|
if (waiver.until < today) {
|
|
@@ -262,7 +316,7 @@ export function audit(opts) {
|
|
|
262
316
|
opened.db
|
|
263
317
|
? "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
318
|
: "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
|
|
319
|
+
"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
320
|
"Lines longer than 2,000 characters are scanned in overlapping windows. The excerpt is the window that matched.",
|
|
267
321
|
"When a filesystem reports inode 0, a swapped file is refused only when size or mtime also changes.",
|
|
268
322
|
"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 +340,7 @@ export function audit(opts) {
|
|
|
286
340
|
return {
|
|
287
341
|
schemaVersion: "1.0",
|
|
288
342
|
tool: { name: "vigilsutra", version: VERSION, rulesVersion: RULES_VERSION },
|
|
289
|
-
generatedAt:
|
|
343
|
+
generatedAt: stamp(),
|
|
290
344
|
mode: "local",
|
|
291
345
|
project: { name: basename(root), detected: detectProject(inv.files) },
|
|
292
346
|
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: /
|
|
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) {
|
package/dist/git-objects.js
CHANGED
|
@@ -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
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
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
|
-
|
|
543
|
-
|
|
544
|
-
|
|
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,10 +90,12 @@ 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
|
|
89
|
-
throw new Error(`.vigilsutra.yml: waiver must be ruleId|path|owner|YYYY-MM-DD`);
|
|
90
|
-
const [ruleId,
|
|
91
|
-
|
|
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;
|
|
98
|
+
if (!/^VS-[A-Z0-9]+-\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(".."))
|
|
94
101
|
throw new Error(`.vigilsutra.yml: waiver path must stay inside the project`);
|
|
@@ -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
|
|
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
|
+
}
|
package/dist/reporters/index.js
CHANGED
|
@@ -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
|
|
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),
|
package/dist/reporters/rich.js
CHANGED
|
@@ -8,7 +8,7 @@ export const htmlEsc = (s) => s.replace(/&/g, "&").replace(/</g, "<").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
|
|
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:#
|
|
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
|
|
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",
|