@cachly-dev/audit-rules 0.0.0-stage → 0.2.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/LICENSE +202 -0
- package/README.md +184 -2
- package/action.yml +59 -0
- package/bin/audit-rules.mjs +185 -0
- package/examples/vulnerable-demo/.cursorrules +12 -0
- package/examples/vulnerable-demo/CLAUDE.md +18 -0
- package/package.json +49 -4
- package/src/formatters.mjs +183 -0
- package/src/rules.mjs +639 -0
- package/src/scanner.mjs +209 -0
package/src/rules.mjs
ADDED
|
@@ -0,0 +1,639 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical rule catalog and deterministic line/document checks for
|
|
3
|
+
* @cachly-dev/audit-rules.
|
|
4
|
+
*
|
|
5
|
+
* Design principles:
|
|
6
|
+
* - Zero network calls, zero external dependencies, 100% local & auditable.
|
|
7
|
+
* - Every detected secret is ALWAYS redacted before returning findings so
|
|
8
|
+
* plaintext credentials never leak into CI logs, JSON, or SARIF output.
|
|
9
|
+
* - Low false-positive discipline: benign security guidance ("guard against
|
|
10
|
+
* prompt injection", "use API_KEY=your-api-key") must not trigger alerts.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export const RULE_CATALOG = {
|
|
14
|
+
// ── Secrets (always severity: error, always redacted) ──────────────────────
|
|
15
|
+
"SEC-001": {
|
|
16
|
+
id: "SEC-001",
|
|
17
|
+
category: "secret",
|
|
18
|
+
severity: "error",
|
|
19
|
+
name: "AWS Access Key ID",
|
|
20
|
+
cwe: "CWE-798",
|
|
21
|
+
description: "AWS access key identifier detected inside an AI rule file.",
|
|
22
|
+
help: "Remove the key from the rule file, rotate it immediately in IAM, and reference an environment variable name instead.",
|
|
23
|
+
},
|
|
24
|
+
"SEC-002": {
|
|
25
|
+
id: "SEC-002",
|
|
26
|
+
category: "secret",
|
|
27
|
+
severity: "error",
|
|
28
|
+
name: "GitHub Personal or Fine-Grained Token",
|
|
29
|
+
cwe: "CWE-798",
|
|
30
|
+
description: "GitHub access token detected inside an AI rule file.",
|
|
31
|
+
help: "Revoke the token in GitHub Settings and never commit credentials in rule or prompt files.",
|
|
32
|
+
},
|
|
33
|
+
"SEC-003": {
|
|
34
|
+
id: "SEC-003",
|
|
35
|
+
category: "secret",
|
|
36
|
+
severity: "error",
|
|
37
|
+
name: "LLM or Payment Provider API Key",
|
|
38
|
+
cwe: "CWE-798",
|
|
39
|
+
description: "Anthropic, OpenAI, or Stripe secret key pattern detected.",
|
|
40
|
+
help: "Rotate the key at the provider dashboard and reference it via an environment variable only.",
|
|
41
|
+
},
|
|
42
|
+
"SEC-004": {
|
|
43
|
+
id: "SEC-004",
|
|
44
|
+
category: "secret",
|
|
45
|
+
severity: "error",
|
|
46
|
+
name: "SaaS / Package Registry Token",
|
|
47
|
+
cwe: "CWE-798",
|
|
48
|
+
description: "Slack, Google API, npm, or PyPI token pattern detected.",
|
|
49
|
+
help: "Revoke the token and replace it with an obvious placeholder such as <YOUR_TOKEN>.",
|
|
50
|
+
},
|
|
51
|
+
"SEC-005": {
|
|
52
|
+
id: "SEC-005",
|
|
53
|
+
category: "secret",
|
|
54
|
+
severity: "error",
|
|
55
|
+
name: "Private Key Block",
|
|
56
|
+
cwe: "CWE-321",
|
|
57
|
+
description: "PEM private key header detected in an AI rule file.",
|
|
58
|
+
help: "Remove the private key material immediately and rotate the affected keypair.",
|
|
59
|
+
},
|
|
60
|
+
"SEC-006": {
|
|
61
|
+
id: "SEC-006",
|
|
62
|
+
category: "secret",
|
|
63
|
+
severity: "error",
|
|
64
|
+
name: "Embedded Credentials in URL",
|
|
65
|
+
cwe: "CWE-798",
|
|
66
|
+
description: "URL with embedded username and password detected.",
|
|
67
|
+
help: "Strip credentials from URLs in rule files and use environment variables instead.",
|
|
68
|
+
},
|
|
69
|
+
"SEC-007": {
|
|
70
|
+
id: "SEC-007",
|
|
71
|
+
category: "secret",
|
|
72
|
+
severity: "error",
|
|
73
|
+
name: "Hardcoded Secret Assignment",
|
|
74
|
+
cwe: "CWE-798",
|
|
75
|
+
description: "Hardcoded API key, secret, token, or password assignment detected.",
|
|
76
|
+
help: "Replace hardcoded values with environment variable references (e.g. $API_KEY) or explicit placeholders.",
|
|
77
|
+
},
|
|
78
|
+
"SEC-008": {
|
|
79
|
+
id: "SEC-008",
|
|
80
|
+
category: "secret",
|
|
81
|
+
severity: "error",
|
|
82
|
+
name: "cachly API Key",
|
|
83
|
+
cwe: "CWE-798",
|
|
84
|
+
description: "cachly API key (cky_live_ or cky_trial_) detected inside an AI rule file.",
|
|
85
|
+
help: "Revoke the key in the cachly dashboard and reference an environment variable such as CACHLY_API_KEY instead.",
|
|
86
|
+
},
|
|
87
|
+
|
|
88
|
+
// ── Prompt Injection & Supply-Chain Backdoors (severity: error) ────────────
|
|
89
|
+
"INJ-001": {
|
|
90
|
+
id: "INJ-001",
|
|
91
|
+
category: "injection",
|
|
92
|
+
severity: "error",
|
|
93
|
+
name: "Instruction Override Attempt",
|
|
94
|
+
cwe: "CWE-74",
|
|
95
|
+
description: "Imperative trying to override prior system, developer, or user safety instructions.",
|
|
96
|
+
help: "Inspect whether this rule file was tampered with. Legitimate repo rules should state project conventions directly without telling the model to ignore prior instructions.",
|
|
97
|
+
},
|
|
98
|
+
"INJ-002": {
|
|
99
|
+
id: "INJ-002",
|
|
100
|
+
category: "injection",
|
|
101
|
+
severity: "error",
|
|
102
|
+
name: "Suspected Secret Exfiltration Command",
|
|
103
|
+
cwe: "CWE-200",
|
|
104
|
+
description: "Network command combined with sensitive local paths or environment secrets.",
|
|
105
|
+
help: "AI rule files must never instruct coding agents to transmit .env files, SSH keys, or credentials to external endpoints.",
|
|
106
|
+
},
|
|
107
|
+
"INJ-003": {
|
|
108
|
+
id: "INJ-003",
|
|
109
|
+
category: "injection",
|
|
110
|
+
severity: "error",
|
|
111
|
+
name: "Hidden Directive Inside HTML Comment",
|
|
112
|
+
cwe: "CWE-94",
|
|
113
|
+
description: "HTML comment containing hidden agent instructions, tool commands, or external URLs.",
|
|
114
|
+
help: "HTML comments are invisible in rendered Markdown diffs and GitHub previews, making them a common hiding spot for prompt injections. Move legitimate notes into visible Markdown.",
|
|
115
|
+
},
|
|
116
|
+
"INJ-004": {
|
|
117
|
+
id: "INJ-004",
|
|
118
|
+
category: "injection",
|
|
119
|
+
severity: "error",
|
|
120
|
+
name: "Invisible Unicode Backdoor / Trojan Source",
|
|
121
|
+
cwe: "CWE-116",
|
|
122
|
+
description: "Hidden Unicode Tag characters (U+E0000-U+E007F), BiDi override controls, or suspicious zero-width clusters detected.",
|
|
123
|
+
help: "Invisible Unicode characters can smuggle hidden prompts past human code review. Strip all non-printing control characters and verify the commit author.",
|
|
124
|
+
},
|
|
125
|
+
"INJ-005": {
|
|
126
|
+
id: "INJ-005",
|
|
127
|
+
category: "injection",
|
|
128
|
+
severity: "error",
|
|
129
|
+
name: "Stealth Behavior or Security Bypass Directive",
|
|
130
|
+
cwe: "CWE-693",
|
|
131
|
+
description: "Instruction telling the agent to hide actions from the user or silently bypass git/security hooks.",
|
|
132
|
+
help: "Rule files must never instruct an AI to conceal actions from the developer or bypass verification hooks (--no-verify, HUSKY=0).",
|
|
133
|
+
},
|
|
134
|
+
"INJ-006": {
|
|
135
|
+
id: "INJ-006",
|
|
136
|
+
category: "injection",
|
|
137
|
+
severity: "error",
|
|
138
|
+
name: "Unverified Pipe-to-Shell Execution",
|
|
139
|
+
cwe: "CWE-829",
|
|
140
|
+
description: "Instruction telling the agent to pipe remote scripts directly into a shell (curl|sh, irm|iex).",
|
|
141
|
+
help: "Pin verified package versions or local scripts instead of instructing coding agents to execute arbitrary remote shell streams.",
|
|
142
|
+
},
|
|
143
|
+
|
|
144
|
+
// ── Hygiene & Context Drift (severity: warn) ───────────────────────────────
|
|
145
|
+
"HYG-001": {
|
|
146
|
+
id: "HYG-001",
|
|
147
|
+
category: "hygiene",
|
|
148
|
+
severity: "warn",
|
|
149
|
+
name: "Oversized CLAUDE.md (>200 lines)",
|
|
150
|
+
cwe: "CWE-1059",
|
|
151
|
+
description: "CLAUDE.md exceeds 200 lines. Rule of thumb: shorter rule files are easier to review and to keep consistent.",
|
|
152
|
+
help: "Keep root rule files short (rule of thumb: <=200 lines) and move task-specific knowledge into scoped rules or a shared team memory layer.",
|
|
153
|
+
},
|
|
154
|
+
"HYG-002": {
|
|
155
|
+
id: "HYG-002",
|
|
156
|
+
category: "hygiene",
|
|
157
|
+
severity: "warn",
|
|
158
|
+
name: "Fragmented Multi-Tool Rule Files",
|
|
159
|
+
cwe: "CWE-1059",
|
|
160
|
+
description: "Multiple tool-specific AI rule files exist in the same repository and can drift out of sync.",
|
|
161
|
+
help: "Consolidate shared rules into a single source of truth so Claude Code, Cursor, Copilot, and JetBrains receive the same team decisions.",
|
|
162
|
+
},
|
|
163
|
+
"HYG-003": {
|
|
164
|
+
id: "HYG-003",
|
|
165
|
+
category: "hygiene",
|
|
166
|
+
severity: "warn",
|
|
167
|
+
name: "Heavy Rule File (>16 KB)",
|
|
168
|
+
cwe: "CWE-400",
|
|
169
|
+
description: "Rule file exceeds 16 KB and consumes substantial context budget on every prompt.",
|
|
170
|
+
help: "Trim verbose logs or historical examples from always-loaded rule files.",
|
|
171
|
+
},
|
|
172
|
+
|
|
173
|
+
// ── Dead References (severity: warn) ───────────────────────────────────────
|
|
174
|
+
"REF-001": {
|
|
175
|
+
id: "REF-001",
|
|
176
|
+
category: "reference",
|
|
177
|
+
severity: "warn",
|
|
178
|
+
name: "Dead Local File Reference",
|
|
179
|
+
cwe: "CWE-1059",
|
|
180
|
+
description: "Rule file references a local source path that does not exist in the repository.",
|
|
181
|
+
help: "Update or remove stale file paths so coding agents do not waste turns searching for deleted files.",
|
|
182
|
+
},
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Redacts a detected secret so plaintext NEVER appears in any output channel.
|
|
187
|
+
*/
|
|
188
|
+
export function redactSecret(raw) {
|
|
189
|
+
const s = String(raw || "");
|
|
190
|
+
if (s.length <= 8) return `*** (len ${s.length})`;
|
|
191
|
+
const head = s.slice(0, Math.min(4, Math.floor(s.length / 4)));
|
|
192
|
+
const tail = s.slice(-2);
|
|
193
|
+
return `${head}***...***${tail} (len ${s.length})`;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const PLACEHOLDER_TOKENS = [
|
|
197
|
+
"your-api-key",
|
|
198
|
+
"your_api_key",
|
|
199
|
+
"your-token",
|
|
200
|
+
"your_token",
|
|
201
|
+
"your-secret",
|
|
202
|
+
"your_secret",
|
|
203
|
+
"your-password",
|
|
204
|
+
"your_password",
|
|
205
|
+
"example",
|
|
206
|
+
"placeholder",
|
|
207
|
+
"changeme",
|
|
208
|
+
"replace-me",
|
|
209
|
+
"replace_me",
|
|
210
|
+
"insert-here",
|
|
211
|
+
"insert_here",
|
|
212
|
+
"xxxxxx",
|
|
213
|
+
"redacted",
|
|
214
|
+
"<",
|
|
215
|
+
">",
|
|
216
|
+
"${",
|
|
217
|
+
"process.env",
|
|
218
|
+
"os.environ",
|
|
219
|
+
"env.",
|
|
220
|
+
];
|
|
221
|
+
|
|
222
|
+
function looksLikePlaceholder(value) {
|
|
223
|
+
const lower = value.toLowerCase().trim();
|
|
224
|
+
if (lower.length < 12) return true;
|
|
225
|
+
if (/^([a-z0-9])\1{7,}$/i.test(lower)) return true;
|
|
226
|
+
if (lower.startsWith("$") || lower.startsWith("%")) return true;
|
|
227
|
+
for (const marker of PLACEHOLDER_TOKENS) {
|
|
228
|
+
if (lower.includes(marker)) return true;
|
|
229
|
+
}
|
|
230
|
+
return false;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function shannonEntropy(str) {
|
|
234
|
+
if (!str) return 0;
|
|
235
|
+
const freq = new Map();
|
|
236
|
+
for (const ch of str) {
|
|
237
|
+
freq.set(ch, (freq.get(ch) || 0) + 1);
|
|
238
|
+
}
|
|
239
|
+
let h = 0;
|
|
240
|
+
for (const count of freq.values()) {
|
|
241
|
+
const p = count / str.length;
|
|
242
|
+
h -= p * Math.log2(p);
|
|
243
|
+
}
|
|
244
|
+
return h;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const SECRET_PATTERNS = [
|
|
248
|
+
{
|
|
249
|
+
ruleId: "SEC-001",
|
|
250
|
+
label: "AWS Access Key ID",
|
|
251
|
+
regex: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
|
|
252
|
+
},
|
|
253
|
+
{
|
|
254
|
+
ruleId: "SEC-002",
|
|
255
|
+
label: "GitHub Token",
|
|
256
|
+
regex: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b|\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,
|
|
257
|
+
},
|
|
258
|
+
{
|
|
259
|
+
ruleId: "SEC-003",
|
|
260
|
+
label: "Anthropic / OpenAI / Stripe API Key",
|
|
261
|
+
regex:
|
|
262
|
+
/\bsk-ant-[A-Za-z0-9_-]{16,}\b|\bsk-proj-[A-Za-z0-9_-]{16,}\b|\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b|\bsk-[A-Za-z0-9]{24,}\b/g,
|
|
263
|
+
},
|
|
264
|
+
{
|
|
265
|
+
ruleId: "SEC-004",
|
|
266
|
+
label: "Slack / Google / npm / PyPI Token",
|
|
267
|
+
regex:
|
|
268
|
+
/\bxox[baprs]-[0-9A-Za-z-]{16,}\b|\bAIza[0-9A-Za-z_-]{35}\b|\bnpm_[A-Za-z0-9]{20,}\b|\bpypi-[A-Za-z0-9_-]{24,}\b/g,
|
|
269
|
+
},
|
|
270
|
+
{
|
|
271
|
+
ruleId: "SEC-005",
|
|
272
|
+
label: "PEM Private Key",
|
|
273
|
+
regex: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-----/g,
|
|
274
|
+
},
|
|
275
|
+
{
|
|
276
|
+
ruleId: "SEC-006",
|
|
277
|
+
label: "URL with Embedded Credentials",
|
|
278
|
+
regex: /\b(?:https?|postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp):\/\/[^\s/:@"'`]+:[^\s/@"'`]{4,}@[^\s/"'`]+/gi,
|
|
279
|
+
filter: (match) => {
|
|
280
|
+
// Allow obvious placeholder credentials like user:pass@localhost or <user>:<pass>@host
|
|
281
|
+
const credsPart = match.split("://")[1]?.split("@")[0] || "";
|
|
282
|
+
const lower = credsPart.toLowerCase();
|
|
283
|
+
if (
|
|
284
|
+
lower.includes("user:pass") ||
|
|
285
|
+
lower.includes("username:password") ||
|
|
286
|
+
lower.includes("<") ||
|
|
287
|
+
lower.includes("${") ||
|
|
288
|
+
lower.includes("example")
|
|
289
|
+
) {
|
|
290
|
+
return false;
|
|
291
|
+
}
|
|
292
|
+
return true;
|
|
293
|
+
},
|
|
294
|
+
},
|
|
295
|
+
{
|
|
296
|
+
ruleId: "SEC-008",
|
|
297
|
+
label: "cachly API Key",
|
|
298
|
+
// Real keys: "cky_live_" or "cky_trial_" plus 32 hex chars (16 random bytes).
|
|
299
|
+
regex: /\bcky_(?:live|trial)_[A-Za-z0-9]{16,}\b/g,
|
|
300
|
+
// Skip documentation placeholders such as cky_live_xxxxxxxxxxxxxxxx.
|
|
301
|
+
filter: (match) => !looksLikePlaceholder(match.replace(/^cky_(?:live|trial)_/, "")),
|
|
302
|
+
},
|
|
303
|
+
];
|
|
304
|
+
|
|
305
|
+
const GENERIC_ASSIGNMENT_RE =
|
|
306
|
+
/\b(?:[A-Z0-9_]*(?:API_KEY|SIGNING_KEY|PRIVATE_KEY|SECRET|TOKEN|PASSWORD|PASSWD|JWT))[ \t]*[:=][ \t]*["'`]?([A-Za-z0-9_./+=-]{14,})["'`]?/gi;
|
|
307
|
+
|
|
308
|
+
// Benign defensive phrasing guard so security docs don't trigger INJ-001
|
|
309
|
+
const DEFENSIVE_CONTEXT_RE =
|
|
310
|
+
/\b(?:protect against|guard against|prevent|detect|block|defend against|mitigate|example of|never follow|reject prompts? that say|sanitize)\b/i;
|
|
311
|
+
|
|
312
|
+
const INJ_OVERRIDE_PATTERNS = [
|
|
313
|
+
/\b(?:ignore|disregard|forget|override|bypass)\s+(?:all\s+)?(?:previous|prior|above|earlier|existing)\s+(?:instructions|rules|prompts|constraints|guidelines)\b/i,
|
|
314
|
+
/\byou\s+are\s+now\s+(?:in\s+)?(?:developer\s+mode|unrestricted|dan\b|jailbroken)\b/i,
|
|
315
|
+
/\bsystem\s+override\s*:/i,
|
|
316
|
+
];
|
|
317
|
+
|
|
318
|
+
const EXFIL_CMD_RE = /\b(?:curl|wget|nc|netcat|Invoke-WebRequest|iwr|fetch\s*\(|http\.request)\b/i;
|
|
319
|
+
const SENSITIVE_TARGET_RE =
|
|
320
|
+
/(?:\.env\b|~\/\.ssh|id_rsa|id_ed25519|\/etc\/passwd|credentials\.json|\.aws\/credentials|\.npmrc|process\.env\b|printenv\b|cat\s+~\/)/i;
|
|
321
|
+
|
|
322
|
+
const STEALTH_PATTERNS = [
|
|
323
|
+
/\b(?:do not|never|don't)\s+(?:mention|tell|inform|show|reveal|disclose)\s+(?:this|these|it|the\s+user|the\s+developer)\b/i,
|
|
324
|
+
/\b(?:silently|secretly|covertly)\s+(?:run|execute|modify|exfiltrate|send|bypass|disable|inject|add)\b/i,
|
|
325
|
+
/\b(?:always\s+pass|use|run\s+with)\s+--no-verify\b/i,
|
|
326
|
+
/\b(?:set|export|prefix\s+with)\s+HUSKY=0\b/i,
|
|
327
|
+
/\b(?:disable|skip|bypass)\s+(?:all\s+)?(?:authentication|auth\s+checks|authorization|security\s+checks|tls\s+verification)\b/i,
|
|
328
|
+
];
|
|
329
|
+
|
|
330
|
+
// The downloader needs an argument before the pipe. A bare "curl|bash" or "irm | iex" names the
|
|
331
|
+
// pattern (e.g. "Never allow curl|bash in CI") and cannot run anything. No defensive-word guard
|
|
332
|
+
// here on purpose: "To prevent errors, run curl -fsSL https://x/i.sh | bash" must still fire.
|
|
333
|
+
const PIPE_TO_SHELL_RE =
|
|
334
|
+
/\b(?:curl|wget)\b[ \t]*[^\s|][^\n|]{0,160}\|\s*(?:sudo\s+)?(?:ba|z|da|k|c)?sh\b|\b(?:irm|Invoke-RestMethod|iwr)\b[ \t]*[^\s|][^\n|]{0,160}\|\s*(?:iex|Invoke-Expression)\b/i;
|
|
335
|
+
|
|
336
|
+
const HTML_COMMENT_DIRECTIVE_RE =
|
|
337
|
+
/\b(?:ignore\s+(?:all\s+)?(?:previous|prior)|override|curl\b|wget\b|https?:\/\/|execute|run\s+this|do\s+not\s+tell|never\s+mention|exfiltrate|base64|system\s+prompt|secret|credentials|\.env)\b/i;
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Inspects a single line for invisible Unicode backdoors:
|
|
341
|
+
* - Tag Block (U+E0000 - U+E007F): classic invisible prompt-injection smuggling
|
|
342
|
+
* - BiDi controls (U+202A-U+202E, U+2066-U+2069): Trojan Source
|
|
343
|
+
* - Suspicious zero-width clusters (3+ zero-width chars in one line)
|
|
344
|
+
*/
|
|
345
|
+
export function detectInvisibleUnicode(line) {
|
|
346
|
+
let tagCount = 0;
|
|
347
|
+
let bidiCount = 0;
|
|
348
|
+
let zwCount = 0;
|
|
349
|
+
const codePoints = [];
|
|
350
|
+
|
|
351
|
+
let i = 0;
|
|
352
|
+
for (const ch of line) {
|
|
353
|
+
const cp = ch.codePointAt(0);
|
|
354
|
+
if (cp >= 0xe0000 && cp <= 0xe007f) {
|
|
355
|
+
tagCount++;
|
|
356
|
+
if (codePoints.length < 4) codePoints.push(`U+${cp.toString(16).toUpperCase()}`);
|
|
357
|
+
} else if (
|
|
358
|
+
(cp >= 0x202a && cp <= 0x202e) ||
|
|
359
|
+
(cp >= 0x2066 && cp <= 0x2069)
|
|
360
|
+
) {
|
|
361
|
+
bidiCount++;
|
|
362
|
+
if (codePoints.length < 4) codePoints.push(`U+${cp.toString(16).toUpperCase()}`);
|
|
363
|
+
} else if (
|
|
364
|
+
cp === 0x200b ||
|
|
365
|
+
cp === 0x200c ||
|
|
366
|
+
cp === 0x200d ||
|
|
367
|
+
cp === 0x2060 ||
|
|
368
|
+
(cp === 0xfeff && i > 0)
|
|
369
|
+
) {
|
|
370
|
+
zwCount++;
|
|
371
|
+
if (codePoints.length < 4) codePoints.push(`U+${cp.toString(16).toUpperCase()}`);
|
|
372
|
+
}
|
|
373
|
+
i++;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
if (tagCount > 0) {
|
|
377
|
+
return {
|
|
378
|
+
kind: "Unicode Tag Block (invisible prompt smuggling)",
|
|
379
|
+
count: tagCount,
|
|
380
|
+
sample: codePoints.join(", "),
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
if (bidiCount > 0) {
|
|
384
|
+
return {
|
|
385
|
+
kind: "BiDi override / isolate control (Trojan Source)",
|
|
386
|
+
count: bidiCount,
|
|
387
|
+
sample: codePoints.join(", "),
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
if (zwCount >= 3) {
|
|
391
|
+
return {
|
|
392
|
+
kind: "Zero-width character cluster",
|
|
393
|
+
count: zwCount,
|
|
394
|
+
sample: codePoints.join(", "),
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
return null;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Parses an inline suppression directive like:
|
|
402
|
+
* <!-- audit-rules-ignore: INJ-001, HYG-001 -->
|
|
403
|
+
* # audit-rules-ignore: INJ-001
|
|
404
|
+
*
|
|
405
|
+
* Returns a Set of rule IDs suppressed for the immediately following line.
|
|
406
|
+
*/
|
|
407
|
+
export function parseInlineIgnore(line) {
|
|
408
|
+
const match = line.match(/audit-rules-ignore\s*:\s*([A-Z]{3}-\d{3}(?:\s*,\s*[A-Z]{3}-\d{3})*)/i);
|
|
409
|
+
if (!match) return null;
|
|
410
|
+
const ids = match[1]
|
|
411
|
+
.split(",")
|
|
412
|
+
.map((s) => s.trim().toUpperCase())
|
|
413
|
+
.filter(Boolean);
|
|
414
|
+
return new Set(ids);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Checks a single rule file's text and returns raw findings (with secrets redacted).
|
|
419
|
+
*/
|
|
420
|
+
export function checkFileContent({ relativePath, content, existingPathCheck }) {
|
|
421
|
+
const findings = [];
|
|
422
|
+
const lines = content.split(/\r?\n/);
|
|
423
|
+
|
|
424
|
+
// Track fenced code blocks for dead-ref heuristic (still scan secrets & injections inside code blocks!)
|
|
425
|
+
let inCodeFence = false;
|
|
426
|
+
let nextLineIgnore = null;
|
|
427
|
+
|
|
428
|
+
// ── 1. Multi-line HTML comment inspection (INJ-003) ────────────────────────
|
|
429
|
+
const htmlCommentRe = /<!--([\s\S]*?)-->/g;
|
|
430
|
+
let commentMatch;
|
|
431
|
+
while ((commentMatch = htmlCommentRe.exec(content)) !== null) {
|
|
432
|
+
const body = commentMatch[1];
|
|
433
|
+
// Ignore our own inline suppression comments
|
|
434
|
+
if (/^\s*audit-rules-ignore\s*:/i.test(body)) continue;
|
|
435
|
+
|
|
436
|
+
if (HTML_COMMENT_DIRECTIVE_RE.test(body)) {
|
|
437
|
+
const prefix = content.slice(0, commentMatch.index);
|
|
438
|
+
const lineNum = prefix.split(/\r?\n/).length;
|
|
439
|
+
const prevLine = lineNum > 1 ? lines[lineNum - 2] : "";
|
|
440
|
+
const prevIgnore = parseInlineIgnore(prevLine);
|
|
441
|
+
if (prevIgnore && prevIgnore.has("INJ-003")) continue;
|
|
442
|
+
|
|
443
|
+
findings.push({
|
|
444
|
+
ruleId: "INJ-003",
|
|
445
|
+
severity: RULE_CATALOG["INJ-003"].severity,
|
|
446
|
+
file: relativePath,
|
|
447
|
+
line: lineNum,
|
|
448
|
+
message: "Hidden HTML comment contains imperative/command or URL directive invisible in Markdown previews.",
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// ── 2. Line-by-line checks ─────────────────────────────────────────────────
|
|
454
|
+
for (let idx = 0; idx < lines.length; idx++) {
|
|
455
|
+
const lineNum = idx + 1;
|
|
456
|
+
const line = lines[idx];
|
|
457
|
+
const suppressed = nextLineIgnore;
|
|
458
|
+
nextLineIgnore = null;
|
|
459
|
+
|
|
460
|
+
const ignoreDirective = parseInlineIgnore(line);
|
|
461
|
+
if (ignoreDirective) {
|
|
462
|
+
nextLineIgnore = ignoreDirective;
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
if (/^\s*```/.test(line)) {
|
|
467
|
+
inCodeFence = !inCodeFence;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const isSuppressed = (id) => Boolean(suppressed && suppressed.has(id));
|
|
471
|
+
|
|
472
|
+
// 2a. Invisible Unicode (INJ-004)
|
|
473
|
+
if (!isSuppressed("INJ-004")) {
|
|
474
|
+
const uni = detectInvisibleUnicode(line);
|
|
475
|
+
if (uni) {
|
|
476
|
+
findings.push({
|
|
477
|
+
ruleId: "INJ-004",
|
|
478
|
+
severity: RULE_CATALOG["INJ-004"].severity,
|
|
479
|
+
file: relativePath,
|
|
480
|
+
line: lineNum,
|
|
481
|
+
message: `${uni.kind} detected (${uni.count} chars: ${uni.sample}).`,
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// 2b. Specific Secret Patterns (SEC-001 .. SEC-006, SEC-008)
|
|
487
|
+
let matchedSpecificSecret = false;
|
|
488
|
+
for (const pat of SECRET_PATTERNS) {
|
|
489
|
+
if (isSuppressed(pat.ruleId)) continue;
|
|
490
|
+
pat.regex.lastIndex = 0;
|
|
491
|
+
let m;
|
|
492
|
+
while ((m = pat.regex.exec(line)) !== null) {
|
|
493
|
+
const raw = m[0];
|
|
494
|
+
if (pat.filter && !pat.filter(raw)) continue;
|
|
495
|
+
matchedSpecificSecret = true;
|
|
496
|
+
findings.push({
|
|
497
|
+
ruleId: pat.ruleId,
|
|
498
|
+
severity: RULE_CATALOG[pat.ruleId].severity,
|
|
499
|
+
file: relativePath,
|
|
500
|
+
line: lineNum,
|
|
501
|
+
message: `Possible ${pat.label} detected (redacted: ${redactSecret(raw)}).`,
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// 2c. Generic Secret Assignments (SEC-007) — only if not already caught above
|
|
507
|
+
if (!matchedSpecificSecret && !isSuppressed("SEC-007")) {
|
|
508
|
+
GENERIC_ASSIGNMENT_RE.lastIndex = 0;
|
|
509
|
+
let gm;
|
|
510
|
+
while ((gm = GENERIC_ASSIGNMENT_RE.exec(line)) !== null) {
|
|
511
|
+
const val = gm[1];
|
|
512
|
+
if (looksLikePlaceholder(val)) continue;
|
|
513
|
+
// Value must be >=14 chars (regex), not a placeholder, and contain letters AND digits, or else have Shannon entropy >= 3.4 bits/char
|
|
514
|
+
const hasDigit = /\d/.test(val);
|
|
515
|
+
const hasAlpha = /[A-Za-z]/.test(val);
|
|
516
|
+
if (!(hasDigit && hasAlpha) && shannonEntropy(val) < 3.4) continue;
|
|
517
|
+
|
|
518
|
+
findings.push({
|
|
519
|
+
ruleId: "SEC-007",
|
|
520
|
+
severity: RULE_CATALOG["SEC-007"].severity,
|
|
521
|
+
file: relativePath,
|
|
522
|
+
line: lineNum,
|
|
523
|
+
message: `Possible hardcoded secret assignment detected (redacted: ${redactSecret(val)}).`,
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// 2d. Prompt Injection Override (INJ-001)
|
|
529
|
+
if (!isSuppressed("INJ-001") && !DEFENSIVE_CONTEXT_RE.test(line)) {
|
|
530
|
+
for (const re of INJ_OVERRIDE_PATTERNS) {
|
|
531
|
+
if (re.test(line)) {
|
|
532
|
+
findings.push({
|
|
533
|
+
ruleId: "INJ-001",
|
|
534
|
+
severity: RULE_CATALOG["INJ-001"].severity,
|
|
535
|
+
file: relativePath,
|
|
536
|
+
line: lineNum,
|
|
537
|
+
message: "Instruction override phrase detected — verify this line is not a prompt injection.",
|
|
538
|
+
});
|
|
539
|
+
break;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// 2e. Secret Exfiltration Command (INJ-002)
|
|
545
|
+
if (!isSuppressed("INJ-002") && EXFIL_CMD_RE.test(line) && SENSITIVE_TARGET_RE.test(line)) {
|
|
546
|
+
findings.push({
|
|
547
|
+
ruleId: "INJ-002",
|
|
548
|
+
severity: RULE_CATALOG["INJ-002"].severity,
|
|
549
|
+
file: relativePath,
|
|
550
|
+
line: lineNum,
|
|
551
|
+
message: "Network command combined with sensitive local file or environment secret detected.",
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
// 2f. Stealth / Hook Bypass Directive (INJ-005)
|
|
556
|
+
if (!isSuppressed("INJ-005") && !DEFENSIVE_CONTEXT_RE.test(line)) {
|
|
557
|
+
for (const re of STEALTH_PATTERNS) {
|
|
558
|
+
if (re.test(line)) {
|
|
559
|
+
findings.push({
|
|
560
|
+
ruleId: "INJ-005",
|
|
561
|
+
severity: RULE_CATALOG["INJ-005"].severity,
|
|
562
|
+
file: relativePath,
|
|
563
|
+
line: lineNum,
|
|
564
|
+
message: "Directive instructing agent to hide actions or bypass security/git verification hooks.",
|
|
565
|
+
});
|
|
566
|
+
break;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
// 2g. Pipe-to-Shell Execution (INJ-006)
|
|
572
|
+
if (!isSuppressed("INJ-006") && PIPE_TO_SHELL_RE.test(line)) {
|
|
573
|
+
findings.push({
|
|
574
|
+
ruleId: "INJ-006",
|
|
575
|
+
severity: RULE_CATALOG["INJ-006"].severity,
|
|
576
|
+
file: relativePath,
|
|
577
|
+
line: lineNum,
|
|
578
|
+
message: "Unverified remote script piped directly to a shell (curl|sh / irm|iex).",
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// 2h. Dead Local File References (REF-001) — outside fenced code blocks
|
|
583
|
+
if (!inCodeFence && existingPathCheck && !isSuppressed("REF-001")) {
|
|
584
|
+
const refRe = /`((?:\.\/)?(?:[A-Za-z0-9_.-]+\/)+[A-Za-z0-9_.-]+\.(?:ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|rb|php|cs|cpp|c|h|json|yaml|yml|toml|sql|sh|md))`/g;
|
|
585
|
+
let rm;
|
|
586
|
+
while ((rm = refRe.exec(line)) !== null) {
|
|
587
|
+
const candidate = rm[1].replace(/^\.\//, "");
|
|
588
|
+
// Skip obvious example/template/system paths
|
|
589
|
+
if (
|
|
590
|
+
candidate.includes("*") ||
|
|
591
|
+
candidate.includes("<") ||
|
|
592
|
+
candidate.includes("{") ||
|
|
593
|
+
candidate.startsWith("path/to/") ||
|
|
594
|
+
candidate.startsWith("foo/") ||
|
|
595
|
+
candidate.startsWith("example/") ||
|
|
596
|
+
candidate.startsWith("examples/") ||
|
|
597
|
+
candidate.startsWith("http") ||
|
|
598
|
+
candidate.startsWith("node_modules/")
|
|
599
|
+
) {
|
|
600
|
+
continue;
|
|
601
|
+
}
|
|
602
|
+
if (!existingPathCheck(candidate)) {
|
|
603
|
+
findings.push({
|
|
604
|
+
ruleId: "REF-001",
|
|
605
|
+
severity: RULE_CATALOG["REF-001"].severity,
|
|
606
|
+
file: relativePath,
|
|
607
|
+
line: lineNum,
|
|
608
|
+
message: `Referenced local file \`${candidate}\` does not exist in this repository.`,
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// ── 3. File-level Hygiene Checks (HYG-001, HYG-003) ────────────────────────
|
|
616
|
+
const baseName = relativePath.split("/").pop() || relativePath;
|
|
617
|
+
if (/^CLAUDE(?:\.local)?\.md$/i.test(baseName) && lines.length > 200) {
|
|
618
|
+
findings.push({
|
|
619
|
+
ruleId: "HYG-001",
|
|
620
|
+
severity: RULE_CATALOG["HYG-001"].severity,
|
|
621
|
+
file: relativePath,
|
|
622
|
+
line: 1,
|
|
623
|
+
message: `${baseName} has ${lines.length} lines (exceeds the 200-line rule of thumb).`,
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
const byteLen = Buffer.byteLength(content, "utf8");
|
|
628
|
+
if (byteLen > 16 * 1024) {
|
|
629
|
+
findings.push({
|
|
630
|
+
ruleId: "HYG-003",
|
|
631
|
+
severity: RULE_CATALOG["HYG-003"].severity,
|
|
632
|
+
file: relativePath,
|
|
633
|
+
line: 1,
|
|
634
|
+
message: `Rule file is ${(byteLen / 1024).toFixed(1)} KB (>16 KB); consumes context window on every prompt.`,
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
return findings;
|
|
639
|
+
}
|