@yagyeshvyas/vibeguard 0.1.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/README.md +600 -0
- package/bin/cli.js +1640 -0
- package/ci/vibeguard.yml +41 -0
- package/ci-templates/Jenkinsfile +26 -0
- package/ci-templates/azure-pipelines.yml +29 -0
- package/ci-templates/circleci.yml +24 -0
- package/ci-templates/gitlab.yml +19 -0
- package/hooks/pre-commit +31 -0
- package/package.json +94 -0
- package/src/ai-guard.js +205 -0
- package/src/ast.js +319 -0
- package/src/audit-trail.js +154 -0
- package/src/autofix.js +524 -0
- package/src/badge.js +42 -0
- package/src/behavior.js +205 -0
- package/src/compliance.js +151 -0
- package/src/crosstaint.js +324 -0
- package/src/cve-intel.js +136 -0
- package/src/dashboard.js +279 -0
- package/src/deps.js +159 -0
- package/src/doctor.js +111 -0
- package/src/engine.js +234 -0
- package/src/external.js +160 -0
- package/src/firewall.js +517 -0
- package/src/history.js +87 -0
- package/src/hook.js +151 -0
- package/src/install.js +248 -0
- package/src/interceptor.js +476 -0
- package/src/mcp-server.js +1804 -0
- package/src/net-audit.js +208 -0
- package/src/pii.js +212 -0
- package/src/plugin.js +80 -0
- package/src/policy-gen.js +288 -0
- package/src/pre-deploy.js +282 -0
- package/src/presets.js +113 -0
- package/src/privacy-audit.js +273 -0
- package/src/repl.js +150 -0
- package/src/report.js +312 -0
- package/src/rules-pack.js +2753 -0
- package/src/rules.js +1446 -0
- package/src/sandbox.js +139 -0
- package/src/scanner.js +651 -0
- package/src/secure-prompt.js +140 -0
- package/src/slopsquat.js +144 -0
- package/src/supply-firewall.js +243 -0
- package/src/suppress.js +89 -0
- package/src/taint.js +168 -0
- package/src/trace.js +220 -0
- package/src/urlscan.js +142 -0
- package/src/vault.js +145 -0
- package/src/verify.js +98 -0
- package/src/verifykeys.js +87 -0
package/src/rules.js
ADDED
|
@@ -0,0 +1,1446 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* Detection rules for VibeGuard.
|
|
5
|
+
*
|
|
6
|
+
* Design goals (in order): low false positives, well-defined matches, clear fixes.
|
|
7
|
+
* Every rule is deliberately narrow. We would rather MISS a fuzzy case than cry
|
|
8
|
+
* wolf on a safe one — noise is what makes people uninstall a scanner.
|
|
9
|
+
*
|
|
10
|
+
* Two kinds of rules:
|
|
11
|
+
* - lineRules: run per line of every scanned file. Return matches with a column.
|
|
12
|
+
* - projectRules: run once over the whole project (see scanner.js for wiring).
|
|
13
|
+
*
|
|
14
|
+
* Severity: 'critical' | 'high' | 'medium' | 'low'
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
|
|
18
|
+
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
// Helpers
|
|
21
|
+
// ---------------------------------------------------------------------------
|
|
22
|
+
|
|
23
|
+
// A line that is purely a comment (used to skip code-pattern rules, NOT secrets —
|
|
24
|
+
// a leaked key inside a comment is still a leaked key).
|
|
25
|
+
function isCommentLine(line) {
|
|
26
|
+
const t = line.trim();
|
|
27
|
+
return (
|
|
28
|
+
t.startsWith('//') ||
|
|
29
|
+
t.startsWith('#') ||
|
|
30
|
+
t.startsWith('*') ||
|
|
31
|
+
t.startsWith('/*')
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Obvious placeholder / non-secret values. Keeps generic secret rule quiet on
|
|
36
|
+
// templates like `password = "your_password_here"` or env interpolation.
|
|
37
|
+
const PLACEHOLDER_RE =
|
|
38
|
+
/^(x{3,}|changeme|your[_-]?|example|placeholder|dummy|test|sample|\.\.\.|<|\{\{|\$\{|process\.env|import\.meta|os\.environ|todo|none|null|undefined|redacted|\*{3,})/i;
|
|
39
|
+
|
|
40
|
+
function looksLikePlaceholder(value) {
|
|
41
|
+
if (!value) return true;
|
|
42
|
+
const v = value.trim();
|
|
43
|
+
if (v.length < 6) return true;
|
|
44
|
+
if (PLACEHOLDER_RE.test(v)) return true;
|
|
45
|
+
// Contains an env-var reference anywhere.
|
|
46
|
+
if (/\$\{|process\.env|import\.meta\.env|os\.environ/.test(v)) return true;
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// BaaS keys that are DESIGNED to be public. Never flag these as secrets.
|
|
51
|
+
// Firebase web apiKey (AIza...) and Supabase / PostgREST anon keys.
|
|
52
|
+
function isPublicBaaSKey(fullLine, value) {
|
|
53
|
+
// Firebase browser API key.
|
|
54
|
+
if (/AIza[0-9A-Za-z\-_]{20,}/.test(value)) return true;
|
|
55
|
+
// Named as an anon / public / publishable key on the same line.
|
|
56
|
+
if (/\b(anon|public|publishable|NEXT_PUBLIC|VITE_|REACT_APP_)\w*\s*[:=]/i.test(fullLine)) {
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
// Supabase anon key naming.
|
|
60
|
+
if (/supabase\w*anon|anon\w*key/i.test(fullLine)) return true;
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Build a fix-prompt-friendly one-liner.
|
|
65
|
+
function makeFinding(rule, opts) {
|
|
66
|
+
return {
|
|
67
|
+
ruleId: opts.ruleId || rule.id,
|
|
68
|
+
severity: opts.severity || rule.severity,
|
|
69
|
+
// Confidence: 'high' = mechanical match, safe to act on.
|
|
70
|
+
// 'medium'= strong heuristic, glance before acting.
|
|
71
|
+
// 'low' = "review this" — a hint, not a verdict.
|
|
72
|
+
confidence: opts.confidence || rule.confidence || 'high',
|
|
73
|
+
title: opts.title || rule.title,
|
|
74
|
+
message: opts.message || rule.message,
|
|
75
|
+
fix: opts.fix || rule.fix,
|
|
76
|
+
file: opts.file,
|
|
77
|
+
line: opts.line,
|
|
78
|
+
column: opts.column,
|
|
79
|
+
snippet: opts.snippet,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Scan a single line with a global regex, yielding one match object per hit.
|
|
84
|
+
function* matchAll(re, line) {
|
|
85
|
+
const g = new RegExp(re.source, re.flags.includes('g') ? re.flags : re.flags + 'g');
|
|
86
|
+
let m;
|
|
87
|
+
while ((m = g.exec(line)) !== null) {
|
|
88
|
+
yield { index: m.index, match: m[0], groups: m };
|
|
89
|
+
if (m.index === g.lastIndex) g.lastIndex++; // avoid zero-width loop
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ---------------------------------------------------------------------------
|
|
94
|
+
// Secret rules (severity: critical)
|
|
95
|
+
// ---------------------------------------------------------------------------
|
|
96
|
+
|
|
97
|
+
const secretRules = [
|
|
98
|
+
{
|
|
99
|
+
id: 'secret.github-token',
|
|
100
|
+
severity: 'critical',
|
|
101
|
+
confidence: 'high',
|
|
102
|
+
title: 'GitHub token',
|
|
103
|
+
re: /\bgh[posur]_[A-Za-z0-9]{36,}\b/,
|
|
104
|
+
message: 'Hardcoded GitHub token (personal access / OAuth / app token).',
|
|
105
|
+
fix: 'Remove it, load from an environment variable, and revoke it in GitHub settings.',
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
id: 'secret.slack-token',
|
|
109
|
+
severity: 'critical',
|
|
110
|
+
confidence: 'high',
|
|
111
|
+
title: 'Slack token',
|
|
112
|
+
re: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/,
|
|
113
|
+
message: 'Hardcoded Slack token.',
|
|
114
|
+
fix: 'Remove it, load from an environment variable, and rotate it in the Slack app settings.',
|
|
115
|
+
},
|
|
116
|
+
{
|
|
117
|
+
id: 'secret.gitlab-token',
|
|
118
|
+
severity: 'critical',
|
|
119
|
+
confidence: 'high',
|
|
120
|
+
title: 'GitLab personal access token',
|
|
121
|
+
re: /\bglpat-[A-Za-z0-9_\-]{20,}\b/,
|
|
122
|
+
message: 'Hardcoded GitLab personal access token.',
|
|
123
|
+
fix: 'Remove it, load from an environment variable, and revoke it in GitLab.',
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
id: 'secret.twilio-key',
|
|
127
|
+
severity: 'critical',
|
|
128
|
+
confidence: 'high',
|
|
129
|
+
title: 'Twilio API key',
|
|
130
|
+
re: /\bSK[0-9a-f]{32}\b/,
|
|
131
|
+
message: 'Hardcoded Twilio API key.',
|
|
132
|
+
fix: 'Remove it, load from an environment variable, and rotate it in the Twilio console.',
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
id: 'secret.sendgrid-key',
|
|
136
|
+
severity: 'critical',
|
|
137
|
+
confidence: 'high',
|
|
138
|
+
title: 'SendGrid API key',
|
|
139
|
+
re: /\bSG\.[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{16,}\b/,
|
|
140
|
+
message: 'Hardcoded SendGrid API key.',
|
|
141
|
+
fix: 'Remove it, load from an environment variable, and rotate it in SendGrid.',
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
id: 'secret.mailgun-key',
|
|
145
|
+
severity: 'critical',
|
|
146
|
+
confidence: 'high',
|
|
147
|
+
title: 'Mailgun API key',
|
|
148
|
+
re: /\bkey-[0-9a-f]{32}\b/,
|
|
149
|
+
message: 'Hardcoded Mailgun API key.',
|
|
150
|
+
fix: 'Remove it, load from an environment variable, and rotate it in Mailgun.',
|
|
151
|
+
},
|
|
152
|
+
{
|
|
153
|
+
id: 'secret.telegram-bot-token',
|
|
154
|
+
severity: 'critical',
|
|
155
|
+
confidence: 'high',
|
|
156
|
+
title: 'Telegram bot token',
|
|
157
|
+
re: /\b\d{8,10}:[A-Za-z0-9_-]{35}\b/,
|
|
158
|
+
message: 'Hardcoded Telegram bot token.',
|
|
159
|
+
fix: 'Remove it, load from an environment variable, and revoke it via BotFather.',
|
|
160
|
+
},
|
|
161
|
+
{
|
|
162
|
+
id: 'secret.npm-token',
|
|
163
|
+
severity: 'critical',
|
|
164
|
+
confidence: 'high',
|
|
165
|
+
title: 'npm access token',
|
|
166
|
+
re: /\bnpm_[A-Za-z0-9]{36}\b/,
|
|
167
|
+
message: 'Hardcoded npm access token (also flagged in .npmrc).',
|
|
168
|
+
fix: 'Remove it, use an environment variable / CI secret, and revoke it on npmjs.com.',
|
|
169
|
+
},
|
|
170
|
+
{
|
|
171
|
+
id: 'secret.resend-key',
|
|
172
|
+
severity: 'critical',
|
|
173
|
+
confidence: 'high',
|
|
174
|
+
title: 'Resend API key',
|
|
175
|
+
re: /\bre_[A-Za-z0-9]{20,}\b/,
|
|
176
|
+
message: 'Hardcoded Resend API key.',
|
|
177
|
+
fix: 'Remove it, load from an environment variable, and rotate it in Resend.',
|
|
178
|
+
filter(line) {
|
|
179
|
+
// Avoid matching words like "re_export" / "re_run" — require it look like a token.
|
|
180
|
+
return !/\bre_(?:export|run|try|use|new|set|get|map|do)\b/i.test(line);
|
|
181
|
+
},
|
|
182
|
+
},
|
|
183
|
+
{
|
|
184
|
+
id: 'secret.connection-string',
|
|
185
|
+
severity: 'critical',
|
|
186
|
+
confidence: 'high',
|
|
187
|
+
title: 'Connection string with embedded credentials',
|
|
188
|
+
re: /\b(?:mongodb(?:\+srv)?|postgres(?:ql)?|mysql|mariadb|redis|amqps?):\/\/[^\s:@/]+:[^\s:@/]+@/,
|
|
189
|
+
message: 'A database/broker connection string embeds a username and password.',
|
|
190
|
+
fix: 'Load the connection string from an environment variable; never commit credentials.',
|
|
191
|
+
filter(line, m) {
|
|
192
|
+
// Ignore obvious placeholders like user:pass@ / user:password@host.
|
|
193
|
+
return !/:\/\/(?:user|username|root|admin):(?:pass|password|changeme|xxx+|\.\.\.)@/i.test(m.match);
|
|
194
|
+
},
|
|
195
|
+
},
|
|
196
|
+
{
|
|
197
|
+
id: 'secret.public-llm-key',
|
|
198
|
+
severity: 'critical',
|
|
199
|
+
confidence: 'high',
|
|
200
|
+
title: 'AI/secret key exposed to the browser via a public env prefix',
|
|
201
|
+
// NEXT_PUBLIC_/VITE_/EXPO_PUBLIC_ on an LLM provider key or anything named *SECRET*.
|
|
202
|
+
re: /\b(?:NEXT_PUBLIC_|VITE_|EXPO_PUBLIC_|REACT_APP_|PUBLIC_)[A-Z0-9_]*(?:OPENAI|ANTHROPIC|GROQ|MISTRAL|COHERE|GEMINI|HUGGINGFACE|REPLICATE|TOGETHER|OPENROUTER|PERPLEXITY|DEEPSEEK)[A-Z0-9_]*|\b(?:NEXT_PUBLIC_|VITE_|EXPO_PUBLIC_)[A-Z0-9_]*SECRET[A-Z0-9_]*/i,
|
|
203
|
+
message: 'A public env prefix exposes an AI provider key or a secret to the browser bundle — anyone can read it.',
|
|
204
|
+
fix: 'Move this to a server-only env var (no NEXT_PUBLIC_/VITE_/EXPO_PUBLIC_ prefix) and rotate the key.',
|
|
205
|
+
},
|
|
206
|
+
{
|
|
207
|
+
id: 'secret.anthropic-key',
|
|
208
|
+
severity: 'critical',
|
|
209
|
+
title: 'Anthropic API key',
|
|
210
|
+
// Must be checked before the OpenAI rule (sk- prefix overlap).
|
|
211
|
+
re: /\bsk-ant-[A-Za-z0-9_\-]{20,}\b/,
|
|
212
|
+
message: 'Hardcoded Anthropic API key.',
|
|
213
|
+
fix: 'Move the key to an environment variable (e.g. process.env.ANTHROPIC_API_KEY) and rotate the exposed key immediately.',
|
|
214
|
+
},
|
|
215
|
+
{
|
|
216
|
+
id: 'secret.openai-key',
|
|
217
|
+
severity: 'critical',
|
|
218
|
+
title: 'OpenAI API key',
|
|
219
|
+
// sk- or sk-proj-, but NOT sk-ant- (Anthropic) and NOT sk_live_ (Stripe uses _).
|
|
220
|
+
re: /\bsk-(?!ant-)(?:proj-)?[A-Za-z0-9_\-]{20,}\b/,
|
|
221
|
+
message: 'Hardcoded OpenAI API key.',
|
|
222
|
+
fix: 'Move the key to an environment variable (e.g. process.env.OPENAI_API_KEY) and rotate the exposed key immediately.',
|
|
223
|
+
},
|
|
224
|
+
{
|
|
225
|
+
id: 'secret.stripe-live-key',
|
|
226
|
+
severity: 'critical',
|
|
227
|
+
title: 'Stripe live secret key',
|
|
228
|
+
re: /\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/,
|
|
229
|
+
message: 'Hardcoded Stripe LIVE secret key. This can move real money.',
|
|
230
|
+
fix: 'Remove the key, load it from process.env.STRIPE_SECRET_KEY, and roll it in the Stripe dashboard now.',
|
|
231
|
+
},
|
|
232
|
+
{
|
|
233
|
+
id: 'secret.aws-access-key',
|
|
234
|
+
severity: 'critical',
|
|
235
|
+
title: 'AWS access key id',
|
|
236
|
+
re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/,
|
|
237
|
+
message: 'Hardcoded AWS access key id.',
|
|
238
|
+
fix: 'Remove it, use an IAM role or environment variables, and deactivate/rotate the key in AWS IAM.',
|
|
239
|
+
},
|
|
240
|
+
{
|
|
241
|
+
id: 'secret.private-key',
|
|
242
|
+
severity: 'critical',
|
|
243
|
+
title: 'Private key block',
|
|
244
|
+
re: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-----/,
|
|
245
|
+
message: 'Private key material committed in source.',
|
|
246
|
+
fix: 'Delete the key from the repo, store it in a secrets manager, and treat it as compromised (rotate it).',
|
|
247
|
+
},
|
|
248
|
+
{
|
|
249
|
+
id: 'secret.generic-credential',
|
|
250
|
+
severity: 'critical',
|
|
251
|
+
title: 'Hardcoded credential',
|
|
252
|
+
// key = "value" style. We post-filter for placeholders and public BaaS keys.
|
|
253
|
+
re: /\b(password|passwd|secret|api[_-]?key|apikey|access[_-]?token|auth[_-]?token|client[_-]?secret)\b\s*[:=]\s*['"]([^'"]{6,})['"]/i,
|
|
254
|
+
message: 'Looks like a hardcoded credential.',
|
|
255
|
+
fix: 'Load this from an environment variable instead of embedding it in code, and rotate it if it was ever real.',
|
|
256
|
+
filter(line, m) {
|
|
257
|
+
const value = m.groups[2];
|
|
258
|
+
if (looksLikePlaceholder(value)) return false;
|
|
259
|
+
if (isPublicBaaSKey(line, value)) return false;
|
|
260
|
+
return true;
|
|
261
|
+
},
|
|
262
|
+
},
|
|
263
|
+
];
|
|
264
|
+
|
|
265
|
+
// ---------------------------------------------------------------------------
|
|
266
|
+
// Code rules
|
|
267
|
+
// ---------------------------------------------------------------------------
|
|
268
|
+
|
|
269
|
+
const codeRules = [
|
|
270
|
+
{
|
|
271
|
+
id: 'code.eval',
|
|
272
|
+
severity: 'high',
|
|
273
|
+
title: 'eval() usage',
|
|
274
|
+
re: /\beval\s*\(/,
|
|
275
|
+
skipComments: true,
|
|
276
|
+
skipInString: true, // an eval() inside a quoted string is text, not a call
|
|
277
|
+
message: 'eval() executes arbitrary code and is a common injection vector.',
|
|
278
|
+
fix: 'Remove eval(). Use JSON.parse for data, a lookup object for dynamic dispatch, or a real parser.',
|
|
279
|
+
},
|
|
280
|
+
{
|
|
281
|
+
id: 'code.command-injection',
|
|
282
|
+
severity: 'high',
|
|
283
|
+
title: 'Shell command built from variables',
|
|
284
|
+
// exec/execSync/spawn(...) whose argument uses a template with ${...} or string + concat.
|
|
285
|
+
re: /\b(?:exec|execSync|spawn|spawnSync|execFile)\s*\(\s*(?:`[^`]*\$\{|['"][^'"]*['"]\s*\+|[A-Za-z_$][\w$]*\s*\+)/,
|
|
286
|
+
skipComments: true,
|
|
287
|
+
message: 'Shell command is assembled from variables — command injection risk.',
|
|
288
|
+
fix: 'Pass arguments as an array (execFile("cmd", [arg1, arg2])) instead of interpolating into a shell string. Validate/allowlist inputs.',
|
|
289
|
+
},
|
|
290
|
+
{
|
|
291
|
+
id: 'code.sql-injection',
|
|
292
|
+
severity: 'high',
|
|
293
|
+
title: 'SQL built by string concatenation',
|
|
294
|
+
// Candidate detection: a SQL verb followed later on the line by either a
|
|
295
|
+
// template interpolation (${) or a string+concat. The filter below then
|
|
296
|
+
// confirms the string is REAL SQL (verb+clause), not English prose like
|
|
297
|
+
// "FROM: " + email or "Delete from list: " + item.
|
|
298
|
+
re: /\b(?:SELECT|INSERT\s+INTO|UPDATE|DELETE\s+FROM)\b[\s\S]*?(?:`[^`]*\$\{|['"]\s*\+|\+\s*['"])/i,
|
|
299
|
+
skipComments: true,
|
|
300
|
+
message: 'SQL query is built by string concatenation/interpolation — SQL injection risk.',
|
|
301
|
+
fix: 'Use parameterized queries / prepared statements (e.g. db.query("... WHERE id = $1", [id])) instead of building the string.',
|
|
302
|
+
filter(line) {
|
|
303
|
+
// Require a genuine SQL statement shape. Each verb must pair with the
|
|
304
|
+
// clause it always has in real queries, which prose almost never does.
|
|
305
|
+
const isSql =
|
|
306
|
+
/\bSELECT\b[\s\S]*\bFROM\b/i.test(line) ||
|
|
307
|
+
/\bINSERT\s+INTO\b[\s\S]*(?:\bVALUES\b|\()/i.test(line) ||
|
|
308
|
+
/\bUPDATE\b[\s\S]*\bSET\b/i.test(line) ||
|
|
309
|
+
/\bDELETE\s+FROM\b[\s\S]*\bWHERE\b/i.test(line);
|
|
310
|
+
if (!isSql) return false;
|
|
311
|
+
// And the interpolation must land in a value position (after WHERE/SET/
|
|
312
|
+
// VALUES/LIKE/IN/an operator), which is where injection actually happens.
|
|
313
|
+
const injects =
|
|
314
|
+
/(?:WHERE|SET|VALUES|LIKE|IN|=|<|>)[^;]*?(?:`[^`]*\$\{|['"]\s*\+|\+\s*['"])/i.test(
|
|
315
|
+
line
|
|
316
|
+
);
|
|
317
|
+
return injects;
|
|
318
|
+
},
|
|
319
|
+
},
|
|
320
|
+
{
|
|
321
|
+
id: 'code.cors-wildcard',
|
|
322
|
+
severity: 'medium',
|
|
323
|
+
title: 'CORS allows any origin',
|
|
324
|
+
re: /(?:origin\s*:\s*['"]\*['"]|Access-Control-Allow-Origin['"]?\s*[:,]\s*['"]\*['"])/i,
|
|
325
|
+
skipComments: true,
|
|
326
|
+
message: 'CORS is set to "*", allowing any website to call this API.',
|
|
327
|
+
fix: 'Restrict origin to an explicit allowlist of your own domains instead of "*".',
|
|
328
|
+
},
|
|
329
|
+
{
|
|
330
|
+
id: 'code.insecure-http',
|
|
331
|
+
severity: 'low',
|
|
332
|
+
title: 'Plain http:// URL',
|
|
333
|
+
// External http URLs only — localhost / loopback are fine for dev.
|
|
334
|
+
re: /http:\/\/(?!localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])[A-Za-z0-9.-]+/,
|
|
335
|
+
skipComments: false,
|
|
336
|
+
message: 'Plain http:// URL — traffic is unencrypted and can be intercepted.',
|
|
337
|
+
fix: 'Use https:// for external URLs.',
|
|
338
|
+
filter(line) {
|
|
339
|
+
// Skip XML namespaces / schema URLs which are identifiers, not requests.
|
|
340
|
+
return !/xmlns|w3\.org|schemas?\.|\.dtd|\.xsd/i.test(line);
|
|
341
|
+
},
|
|
342
|
+
},
|
|
343
|
+
];
|
|
344
|
+
|
|
345
|
+
// ---------------------------------------------------------------------------
|
|
346
|
+
// Auth / access-control rules (Phase 2)
|
|
347
|
+
// ---------------------------------------------------------------------------
|
|
348
|
+
|
|
349
|
+
const WEAK_SECRET_RE = /^(?:secret|secretkey|keyboard cat|changeme|change[_-]?me|password|passwd|123456|test|dev|mysecret|supersecret|topsecret|shhh+|admin|token|jwt|s3cr3t)$/i;
|
|
350
|
+
|
|
351
|
+
const authRules = [
|
|
352
|
+
{
|
|
353
|
+
id: 'auth.weak-session-secret',
|
|
354
|
+
severity: 'high',
|
|
355
|
+
confidence: 'high',
|
|
356
|
+
title: 'Hardcoded / weak session secret',
|
|
357
|
+
// session({ secret: '...' }) or cookieSession({ secret: '...' }) with a string literal.
|
|
358
|
+
re: /(?:session|cookieSession|cookie-session)\s*\(\s*\{[\s\S]{0,200}?secret\s*:\s*['"]([^'"]+)['"]/i,
|
|
359
|
+
skipComments: true,
|
|
360
|
+
message: 'Session secret is a hardcoded string literal — sessions can be forged.',
|
|
361
|
+
fix: 'Load the session secret from an environment variable and use a long random value (openssl rand -hex 32).',
|
|
362
|
+
filter(line, m) {
|
|
363
|
+
const v = m.groups[1];
|
|
364
|
+
// A hardcoded literal here is always wrong (should be env). We still show
|
|
365
|
+
// the weak-value note when it is also short/obvious.
|
|
366
|
+
return !looksLikePlaceholder(v) || WEAK_SECRET_RE.test(v.trim()) || v.length < 16;
|
|
367
|
+
},
|
|
368
|
+
},
|
|
369
|
+
{
|
|
370
|
+
id: 'auth.hardcoded-jwt-secret',
|
|
371
|
+
severity: 'high',
|
|
372
|
+
confidence: 'high',
|
|
373
|
+
title: 'Hardcoded JWT secret',
|
|
374
|
+
// jwt.sign(payload, 'literal-secret', ...) / jwt.verify(token, 'literal')
|
|
375
|
+
re: /\bjwt\.(?:sign|verify)\s*\([^,)]+,\s*['"]([^'"]{3,})['"]/i,
|
|
376
|
+
skipComments: true,
|
|
377
|
+
message: 'JWT secret is hardcoded in source — anyone with the code can mint valid tokens.',
|
|
378
|
+
fix: 'Move the JWT secret to an environment variable (process.env.JWT_SECRET) and rotate it.',
|
|
379
|
+
filter(line, m) {
|
|
380
|
+
return !looksLikePlaceholder(m.groups[1]);
|
|
381
|
+
},
|
|
382
|
+
},
|
|
383
|
+
{
|
|
384
|
+
id: 'auth.idor-direct-object-ref',
|
|
385
|
+
severity: 'high',
|
|
386
|
+
confidence: 'low', // heuristic — presented as "review", not a verdict
|
|
387
|
+
title: 'Possible IDOR — request id used in query without an ownership check',
|
|
388
|
+
// A lookup/mutation call that passes req.params/query/body.<id> straight in.
|
|
389
|
+
re: /\b(?:findById|findByPk|findOne|findUnique|deleteOne|updateOne|update|delete|get|query)\s*\([^)]*\breq\.(?:params|query|body)\.([A-Za-z_$][\w$]*)/,
|
|
390
|
+
skipComments: true,
|
|
391
|
+
message:
|
|
392
|
+
'A record id from the request is used directly in a data lookup. Confirm the record belongs to the current user (an IDOR lets users read/modify others’ data).',
|
|
393
|
+
fix: 'Scope the query to the authenticated user, e.g. Model.findOne({ id, ownerId: req.user.id }), or verify ownership after loading.',
|
|
394
|
+
filter(line, m) {
|
|
395
|
+
// Skip if an ownership/tenant signal is already on the line.
|
|
396
|
+
if (/req\.user|userId|owner|tenant|req\.session\.user|accountId/i.test(line)) return false;
|
|
397
|
+
// Only flag when the field looks like an identifier.
|
|
398
|
+
const field = m.groups[1];
|
|
399
|
+
return /(^id$|Id$|uuid|_id|pk$|slug$|key$)/.test(field) || /findById|findByPk/.test(line);
|
|
400
|
+
},
|
|
401
|
+
},
|
|
402
|
+
{
|
|
403
|
+
id: 'auth.missing-route-auth',
|
|
404
|
+
severity: 'medium',
|
|
405
|
+
confidence: 'low',
|
|
406
|
+
title: 'Mutating route with an inline handler and no visible auth middleware',
|
|
407
|
+
// app.post('/x', (req,res)=>...) — handler directly after the path, no middleware arg.
|
|
408
|
+
re: /\bapp\.(?:post|put|delete|patch)\s*\(\s*['"]([^'"]+)['"]\s*,\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)/i,
|
|
409
|
+
skipComments: true,
|
|
410
|
+
message:
|
|
411
|
+
'This route mutates data but has no middleware between the path and the handler. Confirm authentication/authorization is enforced (inside the handler or via a global guard).',
|
|
412
|
+
fix: 'Add an auth middleware (e.g. app.post("/x", requireAuth, handler)) or verify req.user inside the handler before mutating.',
|
|
413
|
+
filter(line, m) {
|
|
414
|
+
const routePath = (m.groups[1] || '').toLowerCase();
|
|
415
|
+
// Public endpoints legitimately have no auth.
|
|
416
|
+
if (/login|signin|sign-in|signup|sign-up|register|logout|webhook|health|healthz|ping|public|oauth|callback|csp-report/.test(routePath)) {
|
|
417
|
+
return false;
|
|
418
|
+
}
|
|
419
|
+
return true;
|
|
420
|
+
},
|
|
421
|
+
},
|
|
422
|
+
{
|
|
423
|
+
id: 'supabase.service-role-public',
|
|
424
|
+
severity: 'critical',
|
|
425
|
+
confidence: 'high',
|
|
426
|
+
title: 'Supabase service_role key exposed to the browser',
|
|
427
|
+
// NEXT_PUBLIC_/VITE_/REACT_APP_ prefix on a service-role key ships it to the
|
|
428
|
+
// client, where it BYPASSES row-level security entirely.
|
|
429
|
+
re: /\b(?:NEXT_PUBLIC_|VITE_|REACT_APP_|PUBLIC_)[A-Z0-9_]*SERVICE_ROLE[A-Z0-9_]*/i,
|
|
430
|
+
skipComments: false,
|
|
431
|
+
message:
|
|
432
|
+
'A Supabase service_role key is exposed to the browser via a public env prefix. The service role bypasses row-level security — anyone can read/write all data.',
|
|
433
|
+
fix: 'Never expose the service_role key client-side. Use the anon key in the browser (with RLS), and keep service_role server-only (no NEXT_PUBLIC_/VITE_ prefix).',
|
|
434
|
+
},
|
|
435
|
+
{
|
|
436
|
+
id: 'upload.path-traversal',
|
|
437
|
+
severity: 'high',
|
|
438
|
+
confidence: 'medium',
|
|
439
|
+
title: 'User-controlled value used in a filesystem path',
|
|
440
|
+
// path.join/resolve or fs.* with req.body/params/query inside.
|
|
441
|
+
re: /(?:path\.(?:join|resolve)|fs\.(?:readFile|readFileSync|writeFile|writeFileSync|createReadStream|createWriteStream|unlink|unlinkSync|sendFile))\s*\([^)]*\breq\.(?:body|params|query)\.[A-Za-z_$][\w$]*/,
|
|
442
|
+
skipComments: true,
|
|
443
|
+
message:
|
|
444
|
+
'A request value is used to build a filesystem path — path traversal (../../) can read or overwrite arbitrary files.',
|
|
445
|
+
fix: 'Sanitize with path.basename(), resolve against a fixed base dir, and reject any resolved path that escapes it.',
|
|
446
|
+
},
|
|
447
|
+
];
|
|
448
|
+
|
|
449
|
+
// ---------------------------------------------------------------------------
|
|
450
|
+
// Web / crypto / backdoor rules (breadth pack)
|
|
451
|
+
// ---------------------------------------------------------------------------
|
|
452
|
+
|
|
453
|
+
const webRules = [
|
|
454
|
+
{
|
|
455
|
+
id: 'web.open-redirect',
|
|
456
|
+
severity: 'medium',
|
|
457
|
+
confidence: 'high',
|
|
458
|
+
title: 'Open redirect from user input',
|
|
459
|
+
re: /\bres\.(?:redirect|location)\s*\(\s*(?:[^)]*,\s*)?[^)]*\breq\.(?:query|params|body|headers)\.[A-Za-z_$][\w$]*/,
|
|
460
|
+
skipComments: true,
|
|
461
|
+
message: 'A redirect target comes straight from the request — open redirect (used for phishing).',
|
|
462
|
+
fix: 'Redirect only to an allowlist of internal paths; reject absolute/off-site URLs from user input.',
|
|
463
|
+
},
|
|
464
|
+
{
|
|
465
|
+
id: 'web.ssrf',
|
|
466
|
+
severity: 'high',
|
|
467
|
+
confidence: 'medium',
|
|
468
|
+
title: 'Possible SSRF — outbound request to a user-supplied URL',
|
|
469
|
+
re: /\b(?:fetch|got|superagent)\s*\(\s*[^)]*\breq\.(?:query|params|body|headers)\.|axios(?:\.(?:get|post|put|delete))?\s*\(\s*[^)]*\breq\.(?:query|params|body|headers)\.|https?\.get\s*\(\s*[^)]*\breq\.(?:query|params|body|headers)\./,
|
|
470
|
+
skipComments: true,
|
|
471
|
+
message: 'An outbound request targets a URL built from user input — server-side request forgery (SSRF).',
|
|
472
|
+
fix: 'Allowlist permitted hosts/schemes; block internal/metadata IPs (169.254.169.254, localhost, private ranges).',
|
|
473
|
+
},
|
|
474
|
+
{
|
|
475
|
+
id: 'auth.jwt-alg-none',
|
|
476
|
+
severity: 'critical',
|
|
477
|
+
confidence: 'high',
|
|
478
|
+
title: 'JWT verification accepts the "none" algorithm',
|
|
479
|
+
re: /algorithms?\s*:\s*\[[^\]]*['"]none['"]|['"]alg['"]\s*:\s*['"]none['"]|\.verify\([^)]*none/i,
|
|
480
|
+
skipComments: true,
|
|
481
|
+
message: 'JWT config allows the "none" algorithm — tokens can be forged with no signature.',
|
|
482
|
+
fix: 'Pin an explicit algorithm allowlist (e.g. algorithms: ["HS256"]) and never accept "none".',
|
|
483
|
+
},
|
|
484
|
+
{
|
|
485
|
+
id: 'crypto.weak-hash',
|
|
486
|
+
severity: 'medium',
|
|
487
|
+
confidence: 'medium',
|
|
488
|
+
title: 'Weak hash for credentials',
|
|
489
|
+
// md5/sha1 are unsuitable for passwords/tokens.
|
|
490
|
+
re: /createHash\s*\(\s*['"](?:md5|sha1)['"]\s*\)|\b(?:md5|sha1)\s*\(/i,
|
|
491
|
+
skipComments: true,
|
|
492
|
+
message: 'MD5/SHA-1 is used — unsafe for passwords or security tokens (fast to brute-force / broken).',
|
|
493
|
+
fix: 'For passwords use bcrypt/scrypt/argon2. For integrity use SHA-256+. (Ignore if this hash is non-security, e.g. a cache key.)',
|
|
494
|
+
},
|
|
495
|
+
{
|
|
496
|
+
id: 'crypto.insecure-random',
|
|
497
|
+
severity: 'medium',
|
|
498
|
+
confidence: 'low',
|
|
499
|
+
title: 'Insecure randomness for a secret/token',
|
|
500
|
+
// Math.random() used to build something security-sensitive on the same line.
|
|
501
|
+
re: /\b(?:token|secret|otp|nonce|salt|session|password|apikey|api_key|reset|verify)\w*\s*[:=][^;\n]*Math\.random\s*\(|Math\.random\s*\([^;\n]*(?:token|secret|otp|nonce|salt|session|password)/i,
|
|
502
|
+
skipComments: true,
|
|
503
|
+
message: 'Math.random() is not cryptographically secure — predictable tokens/secrets can be guessed.',
|
|
504
|
+
fix: 'Use crypto.randomBytes()/crypto.randomUUID() (Node) or crypto.getRandomValues() (browser) for anything secret.',
|
|
505
|
+
},
|
|
506
|
+
{
|
|
507
|
+
id: 'backdoor.hardcoded-comparison',
|
|
508
|
+
severity: 'high',
|
|
509
|
+
confidence: 'low',
|
|
510
|
+
title: 'Credential compared to a hardcoded literal (possible backdoor / weak check)',
|
|
511
|
+
// e.g. if (password === 'letmein') / token == "backdoor"
|
|
512
|
+
re: /\b(?:password|passwd|pass|token|apikey|api_key|secret|auth|role|isAdmin|admin)\b\s*===?\s*['"][^'"]{2,}['"]/i,
|
|
513
|
+
skipComments: true,
|
|
514
|
+
message:
|
|
515
|
+
'A credential/role is compared against a hardcoded string. This is a common backdoor or a check that should hit a real store — verify it is intentional.',
|
|
516
|
+
fix: 'Compare against hashed values in your data store (constant-time compare for secrets). Remove any hardcoded bypass.',
|
|
517
|
+
filter(line) {
|
|
518
|
+
// Skip obvious test/enum comparisons and env-driven values.
|
|
519
|
+
if (/process\.env|test|expect\(|assert|describe\(|it\(/i.test(line)) return false;
|
|
520
|
+
// role/isAdmin compared to 'admin'/'user' is often legit RBAC — require a
|
|
521
|
+
// secret-ish left side OR a suspicious literal for those.
|
|
522
|
+
if (/\b(?:role|isAdmin|admin)\b/i.test(line) && !/(letmein|backdoor|god|secret|bypass|master|root)/i.test(line)) {
|
|
523
|
+
return false;
|
|
524
|
+
}
|
|
525
|
+
return true;
|
|
526
|
+
},
|
|
527
|
+
},
|
|
528
|
+
];
|
|
529
|
+
|
|
530
|
+
// ---------------------------------------------------------------------------
|
|
531
|
+
// PII / sensitive-data leak rules
|
|
532
|
+
// ---------------------------------------------------------------------------
|
|
533
|
+
// These are the "data leak" checks vibe coders expect: secrets/PII written to
|
|
534
|
+
// logs, or personal data returned to the client. Heuristic and property-access
|
|
535
|
+
// oriented to keep false positives down; most are "review" confidence.
|
|
536
|
+
|
|
537
|
+
// Fields that are secrets/credentials — high value if they leak.
|
|
538
|
+
const SECRET_FIELD = 'password|passwd|pwd|passwordhash|password_hash|secret|token|apikey|api_key|access_token|refresh_token|private_key|session_secret';
|
|
539
|
+
// Personal data — sensitive but noisier, so lower confidence.
|
|
540
|
+
const PII_FIELD = 'ssn|social_security|creditcard|credit_card|card_number|cardnumber|cvv|cvc|passport|dob|date_of_birth|bank_account|routing_number';
|
|
541
|
+
|
|
542
|
+
// Functions that deliberately shape/redact data. If a value passes through one,
|
|
543
|
+
// the leak warning is suppressed. Teams can extend this list via a config file
|
|
544
|
+
// (.vibeguardrc.json { "shapingFunctions": ["toDTO", ...] }) — see configure().
|
|
545
|
+
const BASE_SHAPING = [
|
|
546
|
+
'redact', 'omit', 'pick', 'sanitize', 'scrub', 'mask', 'obfuscate',
|
|
547
|
+
'toSafe\\w*', 'toPublic\\w*', 'serialize\\w*', 'toJSON', 'select', 'only', 'except',
|
|
548
|
+
];
|
|
549
|
+
let extraShaping = [];
|
|
550
|
+
|
|
551
|
+
function buildRedactRe() {
|
|
552
|
+
return new RegExp('\\b(?:' + [...BASE_SHAPING, ...extraShaping].join('|') + ')\\s*\\(', 'i');
|
|
553
|
+
}
|
|
554
|
+
// Reassigned by configure(); closures below read the current value.
|
|
555
|
+
let REDACT_RE = buildRedactRe();
|
|
556
|
+
|
|
557
|
+
// Called by the scanner with the project's config (or resets to defaults).
|
|
558
|
+
function configure(cfg) {
|
|
559
|
+
const fns = (cfg && Array.isArray(cfg.shapingFunctions) ? cfg.shapingFunctions : [])
|
|
560
|
+
.filter((s) => typeof s === 'string' && /^[\w\\*]+$/.test(s));
|
|
561
|
+
extraShaping = fns;
|
|
562
|
+
REDACT_RE = buildRedactRe();
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function isRedacted(line) {
|
|
566
|
+
return REDACT_RE.test(line);
|
|
567
|
+
}
|
|
568
|
+
function notRedacted(line) {
|
|
569
|
+
return !REDACT_RE.test(line);
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// Extract the balanced argument string of a call whose opening '(' is at
|
|
573
|
+
// openIdx. Skips parens inside string literals. Returns null if the call spans
|
|
574
|
+
// multiple lines (unbalanced on this line) — we don't try to analyze those.
|
|
575
|
+
function balancedArgs(line, openIdx) {
|
|
576
|
+
let depth = 0;
|
|
577
|
+
let quote = null;
|
|
578
|
+
for (let i = openIdx; i < line.length; i++) {
|
|
579
|
+
const c = line[i];
|
|
580
|
+
if (quote) {
|
|
581
|
+
if (c === '\\') i++;
|
|
582
|
+
else if (c === quote) quote = null;
|
|
583
|
+
continue;
|
|
584
|
+
}
|
|
585
|
+
if (c === '"' || c === "'" || c === '`') quote = c;
|
|
586
|
+
else if (c === '(') depth++;
|
|
587
|
+
else if (c === ')') {
|
|
588
|
+
depth--;
|
|
589
|
+
if (depth === 0) return line.slice(openIdx + 1, i);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
return null;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// Filter factory: from the sink opener match, pull the FULL balanced argument
|
|
596
|
+
// expression (handles nested calls like console.log(fn(x).password)), then keep
|
|
597
|
+
// the finding only if a sensitive field appears AND the args aren't redacted.
|
|
598
|
+
function leakFilter(fieldRe) {
|
|
599
|
+
return (line, hit) => {
|
|
600
|
+
const open = hit.index + hit.match.length - 1; // index of '(' in the opener
|
|
601
|
+
const args = balancedArgs(line, open);
|
|
602
|
+
if (args == null) return false; // multi-line call — skip
|
|
603
|
+
if (!fieldRe.test(args)) return false;
|
|
604
|
+
if (isRedacted(args)) return false;
|
|
605
|
+
return true;
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
const LOG_SINK = /\b(?:console\.(?:log|info|debug|warn|error)|logger\.\w+|log\.\w+|print|println|fmt\.Print\w*|System\.out\.print\w*)\s*\(/i;
|
|
610
|
+
const RES_SINK = /\bres\.(?:json|send|write|end)\s*\(/i;
|
|
611
|
+
|
|
612
|
+
const piiRules = [
|
|
613
|
+
{
|
|
614
|
+
id: 'pii.secret-in-log',
|
|
615
|
+
severity: 'high',
|
|
616
|
+
confidence: 'medium',
|
|
617
|
+
title: 'Secret written to logs',
|
|
618
|
+
re: LOG_SINK,
|
|
619
|
+
skipComments: true,
|
|
620
|
+
message: 'A secret/credential is written to logs. Logs get shipped to files, consoles, and log aggregators — this leaks it.',
|
|
621
|
+
fix: 'Never log secrets. Redact the field or log only a non-sensitive identifier.',
|
|
622
|
+
filter: leakFilter(new RegExp(`\\.(?:${SECRET_FIELD})\\b`, 'i')),
|
|
623
|
+
},
|
|
624
|
+
{
|
|
625
|
+
id: 'pii.personal-data-in-log',
|
|
626
|
+
severity: 'medium',
|
|
627
|
+
confidence: 'low',
|
|
628
|
+
title: 'Personal data written to logs',
|
|
629
|
+
re: LOG_SINK,
|
|
630
|
+
skipComments: true,
|
|
631
|
+
message: 'Personal data (PII) is written to logs. Confirm this is intended and compliant — logs are often less protected than your DB.',
|
|
632
|
+
fix: 'Avoid logging PII, or redact/hash it. Log a user id instead of the raw personal field.',
|
|
633
|
+
filter: leakFilter(new RegExp(`\\.(?:email|phone|${PII_FIELD})\\b`, 'i')),
|
|
634
|
+
},
|
|
635
|
+
{
|
|
636
|
+
id: 'pii.secret-in-response',
|
|
637
|
+
severity: 'high',
|
|
638
|
+
confidence: 'medium',
|
|
639
|
+
title: 'Secret/credential sent in an HTTP response',
|
|
640
|
+
re: RES_SINK,
|
|
641
|
+
skipComments: true,
|
|
642
|
+
message: 'A secret/credential field is included in an HTTP response body — it will be sent to the client.',
|
|
643
|
+
fix: 'Strip secret fields before responding (select only safe fields, or delete password/token from the object).',
|
|
644
|
+
filter: leakFilter(new RegExp(`\\b(?:${SECRET_FIELD})\\b`, 'i')),
|
|
645
|
+
},
|
|
646
|
+
{
|
|
647
|
+
id: 'pii.request-body-echoed',
|
|
648
|
+
severity: 'medium',
|
|
649
|
+
confidence: 'low',
|
|
650
|
+
title: 'Raw request body returned to the client',
|
|
651
|
+
re: /\bres\.(?:json|send)\s*\(\s*req\.body\s*\)/i,
|
|
652
|
+
skipComments: true,
|
|
653
|
+
message: 'The raw request body is echoed back in the response. Combined with mass-assignment this can reflect or expose unintended fields.',
|
|
654
|
+
fix: 'Return an explicit, allowlisted object rather than echoing req.body.',
|
|
655
|
+
},
|
|
656
|
+
];
|
|
657
|
+
|
|
658
|
+
// ---------------------------------------------------------------------------
|
|
659
|
+
// Robustness pack: input validation, injection, error handling, transport
|
|
660
|
+
// ---------------------------------------------------------------------------
|
|
661
|
+
|
|
662
|
+
const robustnessRules = [
|
|
663
|
+
{
|
|
664
|
+
id: 'validation.mass-assignment',
|
|
665
|
+
severity: 'high',
|
|
666
|
+
confidence: 'medium',
|
|
667
|
+
title: 'Mass assignment from the request body',
|
|
668
|
+
// new Model(req.body) / Model.create(req.body) / Object.assign(x, req.body)
|
|
669
|
+
re: /\b(?:new\s+[A-Z]\w*|(?:\w+\.)?(?:create|insertOne|insert|save|build|update|updateOne|findOneAndUpdate))\s*\(\s*req\.body\s*[),]|Object\.assign\s*\([^,]+,\s*req\.body\s*\)/,
|
|
670
|
+
skipComments: true,
|
|
671
|
+
message: 'The whole request body is written to a model/record. An attacker can set fields you did not intend (role, isAdmin, balance) — mass assignment.',
|
|
672
|
+
fix: 'Pick an explicit allowlist of fields from req.body instead of passing it whole.',
|
|
673
|
+
},
|
|
674
|
+
{
|
|
675
|
+
id: 'injection.nosql',
|
|
676
|
+
severity: 'high',
|
|
677
|
+
confidence: 'medium',
|
|
678
|
+
title: 'NoSQL query built from the request',
|
|
679
|
+
// Model.find(req.body) / passing req.* straight as a query, or $where operator.
|
|
680
|
+
re: /\.(?:find|findOne|findOneAndUpdate|findOneAndDelete|updateOne|updateMany|deleteOne|deleteMany|count|countDocuments)\s*\(\s*req\.(?:body|query|params)\s*[),]|\$where\s*:/,
|
|
681
|
+
skipComments: true,
|
|
682
|
+
message: 'A database query object comes directly from the request — NoSQL/operator injection (e.g. { "$gt": "" } bypasses checks).',
|
|
683
|
+
fix: 'Build the query explicitly from validated scalar fields; never pass req.body/query straight into find().',
|
|
684
|
+
},
|
|
685
|
+
{
|
|
686
|
+
id: 'error.detail-to-client',
|
|
687
|
+
severity: 'medium',
|
|
688
|
+
confidence: 'medium',
|
|
689
|
+
title: 'Error detail / stack trace sent to the client',
|
|
690
|
+
re: /\bres\.(?:json|send|write|end|status\s*\(\s*\d+\s*\)\s*\.(?:json|send))\s*\([^)]*\b(?:err|error|e|ex)\.(?:stack|message|sqlMessage|detail)\b|\bres\.(?:json|send)\s*\(\s*(?:err|error|ex)\s*\)/,
|
|
691
|
+
skipComments: true,
|
|
692
|
+
message: 'An error object/stack is returned in the response. Stack traces leak file paths, library versions, and query internals to attackers.',
|
|
693
|
+
fix: 'Return a generic error message + status code to the client; log the full error server-side only.',
|
|
694
|
+
},
|
|
695
|
+
{
|
|
696
|
+
id: 'error.empty-catch',
|
|
697
|
+
severity: 'low',
|
|
698
|
+
confidence: 'low',
|
|
699
|
+
title: 'Empty catch block swallows errors',
|
|
700
|
+
re: /catch\s*(?:\([^)]*\))?\s*\{\s*\}/,
|
|
701
|
+
skipComments: true,
|
|
702
|
+
message: 'An error is caught and silently ignored. Failures (including security failures) become invisible.',
|
|
703
|
+
fix: 'At minimum log the error; handle it explicitly or rethrow.',
|
|
704
|
+
},
|
|
705
|
+
{
|
|
706
|
+
id: 'net.tls-verification-disabled',
|
|
707
|
+
severity: 'high',
|
|
708
|
+
confidence: 'high',
|
|
709
|
+
title: 'TLS certificate verification disabled',
|
|
710
|
+
re: /rejectUnauthorized\s*:\s*false|NODE_TLS_REJECT_UNAUTHORIZED\s*[:=]\s*['"]?0|strictSSL\s*:\s*false|verify\s*=\s*False/,
|
|
711
|
+
skipComments: true,
|
|
712
|
+
message: 'TLS certificate validation is turned off. Traffic can be silently intercepted (man-in-the-middle).',
|
|
713
|
+
fix: 'Remove rejectUnauthorized:false / NODE_TLS_REJECT_UNAUTHORIZED=0. Trust a proper CA instead.',
|
|
714
|
+
},
|
|
715
|
+
{
|
|
716
|
+
id: 'cookie.insecure-flags',
|
|
717
|
+
severity: 'medium',
|
|
718
|
+
confidence: 'low',
|
|
719
|
+
title: 'Cookie set without HttpOnly/Secure',
|
|
720
|
+
re: /\bres\.cookie\s*\(/,
|
|
721
|
+
skipComments: true,
|
|
722
|
+
message: 'A cookie is set without HttpOnly and/or Secure — exposed to theft via XSS or over plain HTTP.',
|
|
723
|
+
fix: 'Set { httpOnly: true, secure: true, sameSite: "lax" } on cookies (unless JS must read it).',
|
|
724
|
+
filter(line, hit) {
|
|
725
|
+
const open = hit.index + hit.match.length - 1;
|
|
726
|
+
const args = balancedArgs(line, open);
|
|
727
|
+
if (args == null) return false;
|
|
728
|
+
// Flag if HttpOnly is not present in the options.
|
|
729
|
+
return !/httponly/i.test(args);
|
|
730
|
+
},
|
|
731
|
+
},
|
|
732
|
+
{
|
|
733
|
+
id: 'upload.filename-path-traversal',
|
|
734
|
+
severity: 'high',
|
|
735
|
+
confidence: 'medium',
|
|
736
|
+
title: 'Upload filename used to build a path',
|
|
737
|
+
re: /(?:path\.(?:join|resolve)|fs\.\w+|createWriteStream)\s*\([^)]*\.(?:originalname|originalName|filename|name)\b/,
|
|
738
|
+
skipComments: true,
|
|
739
|
+
message: 'An uploaded file name is used to build a filesystem path. A crafted name (../../) overwrites arbitrary files.',
|
|
740
|
+
fix: 'Generate a random server-side filename (e.g. crypto.randomUUID()); never trust the client filename.',
|
|
741
|
+
filter(line) {
|
|
742
|
+
// Require an upload/file context on the line to avoid generic .name FPs.
|
|
743
|
+
return /file|upload|multer|req\.file|\.originalname/i.test(line);
|
|
744
|
+
},
|
|
745
|
+
},
|
|
746
|
+
];
|
|
747
|
+
|
|
748
|
+
// ---------------------------------------------------------------------------
|
|
749
|
+
// Framework-aware pack (Prisma / React / Express reflected XSS)
|
|
750
|
+
// ---------------------------------------------------------------------------
|
|
751
|
+
|
|
752
|
+
const frameworkRules = [
|
|
753
|
+
{
|
|
754
|
+
id: 'prisma.raw-unsafe',
|
|
755
|
+
severity: 'high',
|
|
756
|
+
confidence: 'high',
|
|
757
|
+
title: 'Prisma raw query built dynamically',
|
|
758
|
+
// $queryRawUnsafe / $executeRawUnsafe with a template ${} or string concat.
|
|
759
|
+
re: /\$(?:queryRawUnsafe|executeRawUnsafe)\s*\(\s*(?:`[^`]*\$\{|['"][^'"]*['"]\s*\+|[A-Za-z_$][\w$]*\s*\+|[^)]*\+\s*[A-Za-z_$])/,
|
|
760
|
+
skipComments: true,
|
|
761
|
+
message: 'Prisma $queryRawUnsafe/$executeRawUnsafe is built from a dynamic string — SQL injection (the "Unsafe" variants do not parameterize).',
|
|
762
|
+
fix: 'Use $queryRaw`...${x}...` (tagged template, parameterized) or Prisma.sql with placeholders — not the Unsafe variants with concatenation.',
|
|
763
|
+
},
|
|
764
|
+
{
|
|
765
|
+
id: 'react.dangerous-html',
|
|
766
|
+
severity: 'medium',
|
|
767
|
+
confidence: 'medium',
|
|
768
|
+
title: 'dangerouslySetInnerHTML with dynamic content',
|
|
769
|
+
// __html set to something other than a string literal.
|
|
770
|
+
re: /dangerouslySetInnerHTML\s*=\s*\{\{\s*__html\s*:\s*(?!['"`])/,
|
|
771
|
+
skipComments: true,
|
|
772
|
+
message: 'dangerouslySetInnerHTML renders raw HTML from a dynamic value — stored/reflected XSS if any part is user-controlled.',
|
|
773
|
+
fix: 'Render text as children (React escapes it) or sanitize with DOMPurify before setting __html.',
|
|
774
|
+
},
|
|
775
|
+
{
|
|
776
|
+
id: 'xss.reflected-response',
|
|
777
|
+
severity: 'medium',
|
|
778
|
+
confidence: 'low',
|
|
779
|
+
title: 'User input reflected in an HTML response',
|
|
780
|
+
// res.send/write/end that interpolates req.* (res.json is safe — escaped/typed).
|
|
781
|
+
re: /\bres\.(?:send|write|end)\s*\(\s*(?:`[^`]*\$\{[^}]*\breq\.(?:query|params|body)|['"][^'"]*['"]\s*\+[^)]*\breq\.(?:query|params|body)|[^)]*\breq\.(?:query|params|body)\.[A-Za-z_$][\w$]*\s*\+)/,
|
|
782
|
+
skipComments: true,
|
|
783
|
+
message: 'User input is concatenated into an HTML/text response — reflected XSS. res.send renders HTML; the browser will execute injected <script>.',
|
|
784
|
+
fix: 'Escape/encode the value for HTML context, or return JSON (res.json) and render safely on the client.',
|
|
785
|
+
},
|
|
786
|
+
];
|
|
787
|
+
|
|
788
|
+
// ---------------------------------------------------------------------------
|
|
789
|
+
// AI / LLM / MCP security pack
|
|
790
|
+
// ---------------------------------------------------------------------------
|
|
791
|
+
|
|
792
|
+
const aiRules = [
|
|
793
|
+
{
|
|
794
|
+
id: 'ai.browser-api-key',
|
|
795
|
+
severity: 'critical',
|
|
796
|
+
confidence: 'high',
|
|
797
|
+
title: 'AI SDK configured to run in the browser',
|
|
798
|
+
re: /dangerouslyAllowBrowser\s*:\s*true/,
|
|
799
|
+
skipComments: true,
|
|
800
|
+
message: 'dangerouslyAllowBrowser: true ships your AI provider API key to the browser, where anyone can steal it.',
|
|
801
|
+
fix: 'Call the AI provider from a server route/edge function; never expose the API key client-side.',
|
|
802
|
+
},
|
|
803
|
+
{
|
|
804
|
+
id: 'ai.disabled-sandbox',
|
|
805
|
+
severity: 'high',
|
|
806
|
+
confidence: 'high',
|
|
807
|
+
title: 'AI agent sandbox / permission check disabled',
|
|
808
|
+
re: /dangerouslyDisableSandbox\s*:\s*true|dangerouslySkipPermissions|--dangerously-skip-permissions|bypassPermissions\s*:\s*true/,
|
|
809
|
+
skipComments: true,
|
|
810
|
+
message: 'A sandbox or permission gate for an AI agent/tool is disabled — the model can run unrestricted actions.',
|
|
811
|
+
fix: 'Keep the sandbox/permission checks on; allowlist only the specific tools/paths the agent needs.',
|
|
812
|
+
},
|
|
813
|
+
{
|
|
814
|
+
id: 'ai.eval-llm-output',
|
|
815
|
+
severity: 'high',
|
|
816
|
+
confidence: 'medium',
|
|
817
|
+
title: 'Executing LLM output as code',
|
|
818
|
+
re: /\b(?:eval|Function)\s*\(\s*[^)]*(?:completion|response|llmOutput|aiResponse|message\.content|choices\[0\]|\.text\b|generatedCode)/i,
|
|
819
|
+
skipComments: true,
|
|
820
|
+
message: 'Model output is executed as code (eval/Function). A prompt-injected response becomes remote code execution.',
|
|
821
|
+
fix: 'Never execute model output. Parse structured data, or run it in a strict sandbox with no host access.',
|
|
822
|
+
},
|
|
823
|
+
{
|
|
824
|
+
id: 'ai.prompt-injection-marker',
|
|
825
|
+
severity: 'medium',
|
|
826
|
+
confidence: 'low',
|
|
827
|
+
title: 'Prompt-injection phrase in code / tool description',
|
|
828
|
+
re: /ignore\s+(?:all\s+)?(?:previous|prior|above)\s+instructions|disregard\s+(?:the\s+)?(?:above|previous)|jailbreak\s+mode|\bDAN\s+mode\b|you\s+are\s+now\s+(?:in\s+)?developer\s+mode/i,
|
|
829
|
+
skipComments: false,
|
|
830
|
+
message: 'A classic prompt-injection phrase appears here (e.g. in an MCP tool description or system prompt). If this text can reach an LLM, it can hijack it.',
|
|
831
|
+
fix: 'Remove untrusted instruction text; treat tool descriptions and external content as data, not instructions.',
|
|
832
|
+
},
|
|
833
|
+
];
|
|
834
|
+
|
|
835
|
+
// ---------------------------------------------------------------------------
|
|
836
|
+
// Advanced injection pack (prototype pollution, ReDoS, XXE, CRLF)
|
|
837
|
+
// ---------------------------------------------------------------------------
|
|
838
|
+
|
|
839
|
+
const injectionRules = [
|
|
840
|
+
{
|
|
841
|
+
id: 'injection.prototype-pollution',
|
|
842
|
+
severity: 'high',
|
|
843
|
+
confidence: 'medium',
|
|
844
|
+
title: 'Prototype pollution via deep merge of request data',
|
|
845
|
+
re: /\b(?:_\.)?(?:merge|mergeWith|defaultsDeep|extend|set|setWith)\s*\([^)]*\breq\.(?:body|query|params)\b|deepmerge\s*\([^)]*\breq\.(?:body|query|params)\b/i,
|
|
846
|
+
skipComments: true,
|
|
847
|
+
message: 'A deep-merge/set of request data can set __proto__/constructor keys — prototype pollution.',
|
|
848
|
+
fix: 'Validate keys, freeze prototypes, or use a merge that ignores __proto__/prototype/constructor.',
|
|
849
|
+
},
|
|
850
|
+
{
|
|
851
|
+
id: 'injection.redos-user-regex',
|
|
852
|
+
severity: 'high',
|
|
853
|
+
confidence: 'high',
|
|
854
|
+
title: 'RegExp built from user input (ReDoS)',
|
|
855
|
+
re: /new\s+RegExp\s*\(\s*[^)]*\breq\.(?:body|query|params)\b/,
|
|
856
|
+
skipComments: true,
|
|
857
|
+
message: 'A RegExp is constructed from user input — a crafted pattern causes catastrophic backtracking (ReDoS) and can DoS the process.',
|
|
858
|
+
fix: 'Do not build regexes from user input; use a fixed pattern or escape and length-limit the input.',
|
|
859
|
+
},
|
|
860
|
+
{
|
|
861
|
+
id: 'injection.xxe',
|
|
862
|
+
severity: 'high',
|
|
863
|
+
confidence: 'medium',
|
|
864
|
+
title: 'XML parser with external entities enabled',
|
|
865
|
+
re: /noent\s*:\s*true|resolveExternalEntities\s*:\s*true|expandEntities\s*:\s*true|XMLParser\([^)]*processEntities\s*:\s*true/i,
|
|
866
|
+
skipComments: true,
|
|
867
|
+
message: 'XML external entity expansion is enabled — XXE lets attackers read files and reach internal services.',
|
|
868
|
+
fix: 'Disable external entity resolution (noent/resolveExternalEntities/expandEntities = false).',
|
|
869
|
+
},
|
|
870
|
+
{
|
|
871
|
+
id: 'injection.crlf',
|
|
872
|
+
severity: 'medium',
|
|
873
|
+
confidence: 'low',
|
|
874
|
+
title: 'User input written to a response header',
|
|
875
|
+
re: /\bres\.(?:setHeader|writeHead|header)\s*\([^)]*\breq\.(?:body|query|params|headers)\b/,
|
|
876
|
+
skipComments: true,
|
|
877
|
+
message: 'User input is used in a response header — CRLF injection can split headers or set arbitrary cookies.',
|
|
878
|
+
fix: 'Validate/strip \\r and \\n from any user value used in a header.',
|
|
879
|
+
},
|
|
880
|
+
];
|
|
881
|
+
|
|
882
|
+
// Import extended rule packs
|
|
883
|
+
const pack = require('./rules-pack');
|
|
884
|
+
const cveVersionRules = pack.allCveVersionRules || pack.cveVersionRules;
|
|
885
|
+
const COMPLIANCE_MAP = pack.COMPLIANCE_MAP;
|
|
886
|
+
|
|
887
|
+
const lineRules = [
|
|
888
|
+
...secretRules, ...codeRules, ...authRules, ...webRules, ...piiRules,
|
|
889
|
+
...robustnessRules, ...frameworkRules, ...aiRules, ...injectionRules,
|
|
890
|
+
...pack.allLineRules,
|
|
891
|
+
];
|
|
892
|
+
|
|
893
|
+
// ---------------------------------------------------------------------------
|
|
894
|
+
// File-level rules (need whole-file context, run once per file)
|
|
895
|
+
// ---------------------------------------------------------------------------
|
|
896
|
+
|
|
897
|
+
// Shannon entropy in bits/char — high for random secrets, low for words.
|
|
898
|
+
function shannonEntropy(s) {
|
|
899
|
+
const freq = Object.create(null);
|
|
900
|
+
for (const c of s) freq[c] = (freq[c] || 0) + 1;
|
|
901
|
+
let e = 0;
|
|
902
|
+
const n = s.length;
|
|
903
|
+
for (const k in freq) {
|
|
904
|
+
const p = freq[k] / n;
|
|
905
|
+
e -= p * Math.log2(p);
|
|
906
|
+
}
|
|
907
|
+
return e;
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
// Files that are full of high-entropy strings that are NOT secrets.
|
|
911
|
+
const ENTROPY_SKIP_FILE = /(?:package-lock\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|poetry\.lock|composer\.lock|\.min\.js|\.map|\.lock)$/i;
|
|
912
|
+
// Prefixes already covered by specific secret rules (avoid double-reporting) or
|
|
913
|
+
// known-public tokens.
|
|
914
|
+
const ENTROPY_SKIP_PREFIX = /^(?:sk-|sk_live_|sk_test_|rk_live_|pk_live_|pk_test_|AKIA|ASIA|AIza|eyJ|ghp_|gho_|xox[baprs]-)/;
|
|
915
|
+
|
|
916
|
+
const fileRules = [
|
|
917
|
+
{
|
|
918
|
+
id: 'secret.high-entropy',
|
|
919
|
+
severity: 'high',
|
|
920
|
+
confidence: 'medium',
|
|
921
|
+
title: 'High-entropy string (possible hardcoded secret)',
|
|
922
|
+
run(content, lines, relPath) {
|
|
923
|
+
if (ENTROPY_SKIP_FILE.test(relPath || '')) return [];
|
|
924
|
+
const out = [];
|
|
925
|
+
const strRe = /['"`]([A-Za-z0-9+/=_\-]{24,120})['"`]/g;
|
|
926
|
+
for (let i = 0; i < lines.length; i++) {
|
|
927
|
+
const line = lines[i];
|
|
928
|
+
if (line.length > 2000) continue;
|
|
929
|
+
let m;
|
|
930
|
+
strRe.lastIndex = 0;
|
|
931
|
+
while ((m = strRe.exec(line)) !== null) {
|
|
932
|
+
const val = m[1];
|
|
933
|
+
if (ENTROPY_SKIP_PREFIX.test(val)) continue;
|
|
934
|
+
if (looksLikePlaceholder(val)) continue;
|
|
935
|
+
if (isPublicBaaSKey(line, val)) continue;
|
|
936
|
+
// UUID — structured, not a secret.
|
|
937
|
+
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(val)) continue;
|
|
938
|
+
// Pure-hex of checksum lengths (md5/sha1/sha256) — usually a hash, not a secret.
|
|
939
|
+
if (/^[0-9a-f]+$/i.test(val) && [32, 40, 64].includes(val.length)) continue;
|
|
940
|
+
// Must have digit+letter mix (avoids long English identifiers / base64 words).
|
|
941
|
+
if (!/[0-9]/.test(val) || !/[A-Za-z]/.test(val)) continue;
|
|
942
|
+
if (shannonEntropy(val) < 4.0) continue;
|
|
943
|
+
out.push({
|
|
944
|
+
line: i + 1,
|
|
945
|
+
column: (m.index || 0) + 1,
|
|
946
|
+
snippet: (val.slice(0, 4) + '****' + val.slice(-2)),
|
|
947
|
+
message:
|
|
948
|
+
'A long, high-entropy string is hardcoded here — it looks like a secret/token/key. If it is one, move it to an environment variable and rotate it.',
|
|
949
|
+
fix: 'If this is a credential, load it from process.env and rotate it. If it is not (e.g. a public id), you can ignore this finding.',
|
|
950
|
+
});
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
return out;
|
|
954
|
+
},
|
|
955
|
+
},
|
|
956
|
+
{
|
|
957
|
+
id: 'pii.full-record-response',
|
|
958
|
+
severity: 'medium',
|
|
959
|
+
confidence: 'low',
|
|
960
|
+
title: 'Full database record may be returned to the client',
|
|
961
|
+
run(content, lines, relPath) {
|
|
962
|
+
const ext = (relPath || '').toLowerCase();
|
|
963
|
+
if (!/\.(?:js|jsx|ts|tsx|mjs|cjs)$/.test(ext)) return [];
|
|
964
|
+
const out = [];
|
|
965
|
+
const findRe = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:await\s+)?[\w.$]*\.(?:find|findAll|findMany|findById|findOne|findByPk|findUnique|findFirst)\s*\(/;
|
|
966
|
+
const selectRe = /\.select\s*\(|attributes\s*:|\bselect\s*:/i;
|
|
967
|
+
|
|
968
|
+
// A .map()/serializer callback that picks explicit fields (object literal,
|
|
969
|
+
// no spread of the record) is treated as SAFE shaping. A spread `...` or a
|
|
970
|
+
// raw passthrough (u => u) keeps the whole record -> still unsafe.
|
|
971
|
+
const selectsFields = (cb) => {
|
|
972
|
+
if (/\.\.\./.test(cb)) return false; // spread copies everything
|
|
973
|
+
if (/\{[^}]*:[^}]*\}/.test(cb)) return true; // explicit { field: ... }
|
|
974
|
+
if (REDACT_RE.test(cb)) return true; // redact/omit/pick/serialize inside
|
|
975
|
+
return false; // e.g. u => u, u => u.toJSON()
|
|
976
|
+
};
|
|
977
|
+
|
|
978
|
+
// Pass 1: seed unsafe vars from unfiltered finds.
|
|
979
|
+
const unsafe = new Set();
|
|
980
|
+
// Sanitized vars: once a value passes through a shaping fn (redact/omit/…),
|
|
981
|
+
// it is trusted forever after — even if it was unsafe before. Sanitized
|
|
982
|
+
// always wins over unsafe.
|
|
983
|
+
const sanitized = new Set();
|
|
984
|
+
for (const line of lines) {
|
|
985
|
+
const m = findRe.exec(line);
|
|
986
|
+
if (m && !selectRe.test(line)) unsafe.add(m[1]);
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
// Assignment shape helpers.
|
|
990
|
+
const mapRe = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*([A-Za-z_$][\w$]*)\.(?:map|reduce)\s*\((.*)$/;
|
|
991
|
+
const filterRe = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*([A-Za-z_$][\w$]*)\.(?:filter|slice|concat|sort)\s*\(/; // shape-preserving
|
|
992
|
+
const aliasRe = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*([A-Za-z_$][\w$]*)\s*;?\s*$/;
|
|
993
|
+
// Y = { ...X, ... } -> Y carries all of X's fields.
|
|
994
|
+
const spreadRe = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*\{[^}]*\.\.\.([A-Za-z_$][\w$]*)/;
|
|
995
|
+
// Y = redact(X) / omit(X, ...) / toDTO(X) -> Y is sanitized.
|
|
996
|
+
const shapeAssignRe = new RegExp(
|
|
997
|
+
'(?:const|let|var)\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*(?:await\\s+)?(?:' +
|
|
998
|
+
[...BASE_SHAPING, ...extraShaping].join('|') +
|
|
999
|
+
')\\s*\\(',
|
|
1000
|
+
'i'
|
|
1001
|
+
);
|
|
1002
|
+
|
|
1003
|
+
for (let pass = 0; pass < 4; pass++) {
|
|
1004
|
+
for (const line of lines) {
|
|
1005
|
+
// Sanitizing assignment wins.
|
|
1006
|
+
let m = shapeAssignRe.exec(line);
|
|
1007
|
+
if (m) {
|
|
1008
|
+
sanitized.add(m[1]);
|
|
1009
|
+
unsafe.delete(m[1]);
|
|
1010
|
+
continue;
|
|
1011
|
+
}
|
|
1012
|
+
// map/reduce: safe only if the callback selects fields.
|
|
1013
|
+
m = mapRe.exec(line);
|
|
1014
|
+
if (m && unsafe.has(m[2]) && !selectsFields(m[3]) && !sanitized.has(m[1])) {
|
|
1015
|
+
unsafe.add(m[1]);
|
|
1016
|
+
continue;
|
|
1017
|
+
}
|
|
1018
|
+
// filter/slice/concat/sort: shape-preserving -> stays unsafe.
|
|
1019
|
+
m = filterRe.exec(line);
|
|
1020
|
+
if (m && unsafe.has(m[2]) && !sanitized.has(m[1])) {
|
|
1021
|
+
unsafe.add(m[1]);
|
|
1022
|
+
continue;
|
|
1023
|
+
}
|
|
1024
|
+
// object spread of an unsafe var -> unsafe (unless line also shapes it).
|
|
1025
|
+
m = spreadRe.exec(line);
|
|
1026
|
+
if (m && unsafe.has(m[2]) && !isRedacted(line) && !sanitized.has(m[1])) {
|
|
1027
|
+
unsafe.add(m[1]);
|
|
1028
|
+
continue;
|
|
1029
|
+
}
|
|
1030
|
+
// plain alias.
|
|
1031
|
+
m = aliasRe.exec(line);
|
|
1032
|
+
if (m && unsafe.has(m[2]) && !sanitized.has(m[1])) unsafe.add(m[1]);
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
// Sanitized always wins.
|
|
1036
|
+
for (const s of sanitized) unsafe.delete(s);
|
|
1037
|
+
|
|
1038
|
+
const flag = (i, name, why) =>
|
|
1039
|
+
out.push({
|
|
1040
|
+
line: i + 1,
|
|
1041
|
+
column: 1,
|
|
1042
|
+
snippet: lines[i].trim().slice(0, 120),
|
|
1043
|
+
message: `${why} — this can leak fields like password hashes, tokens, or other users' data.`,
|
|
1044
|
+
fix: 'Select only the fields the client needs (or delete sensitive fields / use a serializer) before responding.',
|
|
1045
|
+
});
|
|
1046
|
+
|
|
1047
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1048
|
+
const line = lines[i];
|
|
1049
|
+
if (isRedacted(line)) continue; // line shapes the data -> trust it
|
|
1050
|
+
// res.json(varFromUnfilteredRecord)
|
|
1051
|
+
let rm = /\bres\.(?:json|send)\s*\(\s*([A-Za-z_$][\w$]*)\s*\)/.exec(line);
|
|
1052
|
+
if (rm && unsafe.has(rm[1]) && !sanitized.has(rm[1])) {
|
|
1053
|
+
flag(i, rm[1], `"${rm[1]}" comes from an unfiltered DB lookup and is sent straight to the client`);
|
|
1054
|
+
continue;
|
|
1055
|
+
}
|
|
1056
|
+
// res.json(await Model.find...()) inline, no field selection
|
|
1057
|
+
if (/\bres\.(?:json|send)\s*\(\s*(?:await\s+)?[\w.$]*\.(?:find|findAll|findMany|findById|findOne|findByPk|findUnique|findFirst)\s*\(/i.test(line) && !selectRe.test(line)) {
|
|
1058
|
+
flag(i, 'record', 'An unfiltered DB record is returned inline in the response');
|
|
1059
|
+
continue;
|
|
1060
|
+
}
|
|
1061
|
+
// res.json({ ...unsafeVar }) inline spread of a full record
|
|
1062
|
+
rm = /\bres\.(?:json|send)\s*\(\s*\{[^}]*\.\.\.([A-Za-z_$][\w$]*)/.exec(line);
|
|
1063
|
+
if (rm && unsafe.has(rm[1])) {
|
|
1064
|
+
flag(i, rm[1], `"${rm[1]}" is spread into the response object, carrying all of its fields to the client`);
|
|
1065
|
+
continue;
|
|
1066
|
+
}
|
|
1067
|
+
// res.json(unsafeVar.map(cb)) where the map does not select fields
|
|
1068
|
+
rm = /\bres\.(?:json|send)\s*\(\s*([A-Za-z_$][\w$]*)\.map\s*\((.*)$/.exec(line);
|
|
1069
|
+
if (rm && unsafe.has(rm[1]) && !selectsFields(rm[2])) {
|
|
1070
|
+
flag(i, rm[1], `"${rm[1]}" records are mapped without selecting fields and returned to the client`);
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
return out;
|
|
1074
|
+
},
|
|
1075
|
+
},
|
|
1076
|
+
{
|
|
1077
|
+
id: 'package.hygiene',
|
|
1078
|
+
severity: 'medium',
|
|
1079
|
+
confidence: 'high',
|
|
1080
|
+
title: 'package.json supply-chain hygiene',
|
|
1081
|
+
run(content, lines, relPath) {
|
|
1082
|
+
if ((relPath || '') !== 'package.json') return [];
|
|
1083
|
+
let pkg;
|
|
1084
|
+
try {
|
|
1085
|
+
pkg = JSON.parse(content);
|
|
1086
|
+
} catch {
|
|
1087
|
+
return [];
|
|
1088
|
+
}
|
|
1089
|
+
const out = [];
|
|
1090
|
+
const findLoc = (needle) => {
|
|
1091
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1092
|
+
const c = lines[i].indexOf(needle);
|
|
1093
|
+
if (c !== -1) return { line: i + 1, column: c + 1 };
|
|
1094
|
+
}
|
|
1095
|
+
return { line: 1, column: 1 };
|
|
1096
|
+
};
|
|
1097
|
+
const deps = Object.assign({}, pkg.dependencies, pkg.devDependencies, pkg.optionalDependencies);
|
|
1098
|
+
for (const [name, ver] of Object.entries(deps)) {
|
|
1099
|
+
if (typeof ver !== 'string') continue;
|
|
1100
|
+
if (ver === '*' || ver === 'latest' || ver === '' || /^[x*]/.test(ver)) {
|
|
1101
|
+
const loc = findLoc(`"${name}"`);
|
|
1102
|
+
out.push({
|
|
1103
|
+
line: loc.line,
|
|
1104
|
+
column: loc.column,
|
|
1105
|
+
confidence: 'high',
|
|
1106
|
+
snippet: `"${name}": "${ver}"`,
|
|
1107
|
+
message: `Dependency "${name}" is unpinned ("${ver}"). Any future (possibly malicious) version can be installed — supply-chain risk.`,
|
|
1108
|
+
fix: `Pin "${name}" to a specific version range (e.g. ^1.2.3) and commit a lockfile.`,
|
|
1109
|
+
});
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
// Dangerous install scripts.
|
|
1113
|
+
const scripts = pkg.scripts || {};
|
|
1114
|
+
for (const hook of ['preinstall', 'postinstall', 'install', 'prepare']) {
|
|
1115
|
+
const s = scripts[hook];
|
|
1116
|
+
if (s && /curl|wget|\|\s*(?:sh|bash)|sudo|npx\s+\S+@|eval\s/i.test(s)) {
|
|
1117
|
+
const loc = findLoc(`"${hook}"`);
|
|
1118
|
+
out.push({
|
|
1119
|
+
line: loc.line,
|
|
1120
|
+
column: loc.column,
|
|
1121
|
+
severity: 'high',
|
|
1122
|
+
confidence: 'medium',
|
|
1123
|
+
snippet: `"${hook}": ${JSON.stringify(s).slice(0, 80)}`,
|
|
1124
|
+
message: `The "${hook}" script runs a network/shell command on install — a common malware and supply-chain vector.`,
|
|
1125
|
+
fix: `Review the "${hook}" script; avoid piping remote scripts to a shell during install.`,
|
|
1126
|
+
});
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
return out;
|
|
1130
|
+
},
|
|
1131
|
+
},
|
|
1132
|
+
{
|
|
1133
|
+
id: 'ratelimit.missing-on-auth',
|
|
1134
|
+
severity: 'medium',
|
|
1135
|
+
confidence: 'low',
|
|
1136
|
+
title: 'Auth endpoint without visible rate limiting',
|
|
1137
|
+
run(content, lines) {
|
|
1138
|
+
const authRouteRe = /\bapp\.(?:post|put)\s*\(\s*['"]([^'"]*(?:login|signin|sign-in|auth|register|signup|sign-up|password|reset|token|otp)[^'"]*)['"]/i;
|
|
1139
|
+
const hasRateLimit = /rate[-\s]?limit|ratelimit|express-rate-limit|slow[-\s]?down|slowDown|\blimiter\b|throttle|express-brute|bruteforce/i.test(content);
|
|
1140
|
+
if (hasRateLimit) return [];
|
|
1141
|
+
const out = [];
|
|
1142
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1143
|
+
const m = authRouteRe.exec(lines[i]);
|
|
1144
|
+
if (m) {
|
|
1145
|
+
out.push({
|
|
1146
|
+
line: i + 1,
|
|
1147
|
+
column: 1,
|
|
1148
|
+
snippet: lines[i].trim().slice(0, 120),
|
|
1149
|
+
message:
|
|
1150
|
+
'This authentication endpoint has no rate limiting in this file — it is exposed to brute-force / credential-stuffing.',
|
|
1151
|
+
fix: 'Add a rate limiter (e.g. express-rate-limit) to login/auth routes, e.g. app.post("/login", loginLimiter, handler).',
|
|
1152
|
+
});
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
return out;
|
|
1156
|
+
},
|
|
1157
|
+
},
|
|
1158
|
+
{
|
|
1159
|
+
id: 'upload.unrestricted-multer',
|
|
1160
|
+
severity: 'medium',
|
|
1161
|
+
confidence: 'low',
|
|
1162
|
+
title: 'File upload without type/size restrictions',
|
|
1163
|
+
run(content, lines) {
|
|
1164
|
+
if (!/\bmulter\s*\(/.test(content) && !/require\(['"]multer['"]\)/.test(content)) {
|
|
1165
|
+
return [];
|
|
1166
|
+
}
|
|
1167
|
+
// If limits or a fileFilter are configured anywhere in the file, assume guarded.
|
|
1168
|
+
if (/fileFilter|limits\s*:/.test(content)) return [];
|
|
1169
|
+
const out = [];
|
|
1170
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1171
|
+
if (/\bmulter\s*\(/.test(lines[i])) {
|
|
1172
|
+
out.push({
|
|
1173
|
+
line: i + 1,
|
|
1174
|
+
column: 1,
|
|
1175
|
+
snippet: lines[i].trim().slice(0, 120),
|
|
1176
|
+
message:
|
|
1177
|
+
'multer is configured without fileFilter or size limits — accepts any file type and size (upload abuse, storage exhaustion).',
|
|
1178
|
+
fix: 'Add limits (e.g. { limits: { fileSize: 5*1024*1024 } }) and a fileFilter that allowlists expected MIME types.',
|
|
1179
|
+
});
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
return out;
|
|
1183
|
+
},
|
|
1184
|
+
},
|
|
1185
|
+
{
|
|
1186
|
+
id: 'iac.dockerfile',
|
|
1187
|
+
severity: 'medium',
|
|
1188
|
+
confidence: 'high',
|
|
1189
|
+
title: 'Dockerfile hardening',
|
|
1190
|
+
run(content, lines, relPath) {
|
|
1191
|
+
const base = (relPath || '').split('/').pop() || '';
|
|
1192
|
+
if (!/^dockerfile$/i.test(base) && !/\.dockerfile$/i.test(base)) return [];
|
|
1193
|
+
const out = [];
|
|
1194
|
+
let hasUser = false;
|
|
1195
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1196
|
+
const l = lines[i];
|
|
1197
|
+
if (/^\s*USER\s+\S+/i.test(l) && !/^\s*USER\s+root\b/i.test(l)) hasUser = true;
|
|
1198
|
+
if (/^\s*(?:ENV|ARG)\s+\w*(?:PASSWORD|SECRET|TOKEN|API_?KEY|PRIVATE_KEY|CREDENTIAL)\w*\s*[=\s]/i.test(l)) {
|
|
1199
|
+
out.push({ line: i + 1, column: 1, severity: 'high', snippet: l.trim().slice(0, 100), message: 'A secret is baked into the image via ENV/ARG — it is readable in every image layer.', fix: 'Pass secrets at runtime (docker secrets / --env-file / mounted files), never via ENV/ARG in the Dockerfile.' });
|
|
1200
|
+
}
|
|
1201
|
+
if (/^\s*ADD\s+https?:\/\//i.test(l)) {
|
|
1202
|
+
out.push({ line: i + 1, column: 1, severity: 'medium', snippet: l.trim().slice(0, 100), message: 'ADD fetches a remote URL — no checksum verification, and it auto-extracts archives.', fix: 'Use curl/wget with a pinned checksum, or COPY a vendored file.' });
|
|
1203
|
+
}
|
|
1204
|
+
const from = /^\s*FROM\s+([^\s]+)/i.exec(l);
|
|
1205
|
+
if (from && (/:latest$/i.test(from[1]) || !/[:@]/.test(from[1]))) {
|
|
1206
|
+
out.push({ line: i + 1, column: 1, severity: 'low', snippet: l.trim().slice(0, 100), message: 'Base image is untagged or :latest — builds are not reproducible and can pull a changed/compromised image.', fix: 'Pin the base image to a specific version and ideally a digest (image@sha256:...).' });
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
if (!hasUser) out.push({ line: 1, column: 1, severity: 'medium', snippet: base, message: 'No non-root USER directive — the container runs as root, widening the blast radius of any compromise.', fix: 'Add a non-root user (RUN adduser ... && USER appuser).' });
|
|
1210
|
+
return out;
|
|
1211
|
+
},
|
|
1212
|
+
},
|
|
1213
|
+
{
|
|
1214
|
+
id: 'iac.github-actions',
|
|
1215
|
+
severity: 'medium',
|
|
1216
|
+
confidence: 'medium',
|
|
1217
|
+
title: 'GitHub Actions workflow hardening',
|
|
1218
|
+
run(content, lines, relPath) {
|
|
1219
|
+
if (!/\.github\/workflows\/.+\.(?:yml|yaml)$/.test(relPath || '')) return [];
|
|
1220
|
+
const out = [];
|
|
1221
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1222
|
+
const l = lines[i];
|
|
1223
|
+
if (/\$\{\{\s*github\.(?:event|head_ref|pull_request)[^}]*\}\}/.test(l) && !/\benv\s*:/.test(l)) {
|
|
1224
|
+
out.push({ line: i + 1, column: 1, severity: 'high', confidence: 'medium', snippet: l.trim().slice(0, 100), message: 'Untrusted github.event/head_ref data is interpolated directly — script injection into the runner.', fix: 'Pass it through an env: var and reference "$VAR" in the script instead of inlining ${{ }}.' });
|
|
1225
|
+
}
|
|
1226
|
+
if (/permissions:\s*write-all/i.test(l)) {
|
|
1227
|
+
out.push({ line: i + 1, column: 1, severity: 'medium', snippet: l.trim().slice(0, 100), message: 'permissions: write-all grants the token full write access to the repo.', fix: 'Set least-privilege permissions per job (e.g. contents: read).' });
|
|
1228
|
+
}
|
|
1229
|
+
const uses = /^\s*-?\s*uses:\s*([\w.\-]+\/[\w.\-]+)@([\w.\-]+)\s*$/.exec(l);
|
|
1230
|
+
if (uses && !/^[0-9a-f]{40}$/.test(uses[2])) {
|
|
1231
|
+
out.push({ line: i + 1, column: 1, severity: 'low', snippet: l.trim().slice(0, 100), message: `Action ${uses[1]} is pinned to a tag/branch (@${uses[2]}), not a commit SHA — a moved tag can inject malicious code.`, fix: 'Pin third-party actions to a full commit SHA.' });
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
return out;
|
|
1235
|
+
},
|
|
1236
|
+
},
|
|
1237
|
+
{
|
|
1238
|
+
id: 'iac.terraform',
|
|
1239
|
+
severity: 'high',
|
|
1240
|
+
confidence: 'high',
|
|
1241
|
+
title: 'Terraform misconfiguration',
|
|
1242
|
+
run(content, lines, relPath) {
|
|
1243
|
+
if (!/\.(?:tf|hcl)$/.test(relPath || '')) return [];
|
|
1244
|
+
const out = [];
|
|
1245
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1246
|
+
const l = lines[i];
|
|
1247
|
+
if (/cidr_blocks?\s*=\s*\[?\s*"0\.0\.0\.0\/0"/.test(l)) {
|
|
1248
|
+
out.push({ line: i + 1, column: 1, severity: 'high', snippet: l.trim().slice(0, 100), message: 'Security group / firewall allows 0.0.0.0/0 — open to the entire internet.', fix: 'Restrict ingress to specific IP ranges; never expose admin ports (22/3389/db) to 0.0.0.0/0.' });
|
|
1249
|
+
}
|
|
1250
|
+
if (/acl\s*=\s*"public-read(?:-write)?"/.test(l)) {
|
|
1251
|
+
out.push({ line: i + 1, column: 1, severity: 'high', snippet: l.trim().slice(0, 100), message: 'A storage bucket ACL is public — objects are world-readable/writable.', fix: 'Use private ACLs and grant access via IAM policies / signed URLs.' });
|
|
1252
|
+
}
|
|
1253
|
+
if (/"(?:Action|Resource)"\s*:\s*"\*"|actions?\s*=\s*\[\s*"\*"\s*\]/.test(l)) {
|
|
1254
|
+
out.push({ line: i + 1, column: 1, severity: 'medium', confidence: 'medium', snippet: l.trim().slice(0, 100), message: 'IAM policy uses a wildcard "*" for Action/Resource — over-broad privileges.', fix: 'Scope IAM policies to the specific actions and resources needed.' });
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
return out;
|
|
1258
|
+
},
|
|
1259
|
+
},
|
|
1260
|
+
{
|
|
1261
|
+
id: 'nextjs.missing-security-headers',
|
|
1262
|
+
severity: 'low',
|
|
1263
|
+
confidence: 'low',
|
|
1264
|
+
title: 'Next.js config without security headers',
|
|
1265
|
+
run(content, lines, relPath) {
|
|
1266
|
+
if (!/^next\.config\.(?:js|mjs|ts|cjs)$/.test(relPath || '')) return [];
|
|
1267
|
+
const hasHeadersFn = /headers\s*\(/.test(content) || /async\s+headers/.test(content);
|
|
1268
|
+
const hasSecHeader =
|
|
1269
|
+
/Strict-Transport-Security|Content-Security-Policy|X-Frame-Options|X-Content-Type-Options|Referrer-Policy|Permissions-Policy/i.test(
|
|
1270
|
+
content
|
|
1271
|
+
);
|
|
1272
|
+
if (hasHeadersFn && hasSecHeader) return [];
|
|
1273
|
+
return [
|
|
1274
|
+
{
|
|
1275
|
+
line: 1,
|
|
1276
|
+
column: 1,
|
|
1277
|
+
snippet: relPath,
|
|
1278
|
+
message:
|
|
1279
|
+
'No security response headers configured in next.config. Deployed pages ship without CSP / HSTS / X-Frame-Options / X-Content-Type-Options.',
|
|
1280
|
+
fix: 'Add an async headers() returning Content-Security-Policy, Strict-Transport-Security, X-Frame-Options=DENY, X-Content-Type-Options=nosniff, and Referrer-Policy.',
|
|
1281
|
+
},
|
|
1282
|
+
];
|
|
1283
|
+
},
|
|
1284
|
+
},
|
|
1285
|
+
{
|
|
1286
|
+
id: 'cve.known-vulnerable-version',
|
|
1287
|
+
severity: 'high',
|
|
1288
|
+
confidence: 'high',
|
|
1289
|
+
title: 'Known vulnerable dependency version',
|
|
1290
|
+
run(content, lines, relPath) {
|
|
1291
|
+
if ((relPath || '') !== 'package.json') return [];
|
|
1292
|
+
let pkg;
|
|
1293
|
+
try { pkg = JSON.parse(content); } catch { return []; }
|
|
1294
|
+
const deps = Object.assign({}, pkg.dependencies, pkg.devDependencies, pkg.optionalDependencies);
|
|
1295
|
+
const out = [];
|
|
1296
|
+
for (const cveRule of cveVersionRules) {
|
|
1297
|
+
const ver = deps[cveRule.pkg];
|
|
1298
|
+
if (!ver || typeof ver !== 'string') continue;
|
|
1299
|
+
const cleanVer = ver.replace(/^[^0-9]*/, '');
|
|
1300
|
+
const parts = cleanVer.split('.').map(Number);
|
|
1301
|
+
const major = parts[0] || 0;
|
|
1302
|
+
const minor = parts[1] || 0;
|
|
1303
|
+
const patch = parts[2] || 0;
|
|
1304
|
+
let isVulnerable = false;
|
|
1305
|
+
for (const vuln of cveRule.vuln) {
|
|
1306
|
+
if (vuln === '*') { isVulnerable = true; break; }
|
|
1307
|
+
const m = /^<(\d+)\.(\d+)(?:\.(\d+))?$/.exec(vuln);
|
|
1308
|
+
if (m) {
|
|
1309
|
+
const vMaj = parseInt(m[1], 10);
|
|
1310
|
+
const vMin = parseInt(m[2], 10);
|
|
1311
|
+
const vPat = parseInt(m[3] || '0', 10);
|
|
1312
|
+
if (major < vMaj || (major === vMaj && minor < vMin) || (major === vMaj && minor === vMin && patch < vPat)) {
|
|
1313
|
+
isVulnerable = true; break;
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
if (isVulnerable) {
|
|
1318
|
+
const loc = { line: 1, column: 1 };
|
|
1319
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1320
|
+
const idx = lines[i].indexOf(`"${cveRule.pkg}"`);
|
|
1321
|
+
if (idx !== -1) { loc.line = i + 1; loc.column = idx + 1; break; }
|
|
1322
|
+
}
|
|
1323
|
+
out.push({
|
|
1324
|
+
line: loc.line,
|
|
1325
|
+
column: loc.column,
|
|
1326
|
+
severity: cveRule.severity,
|
|
1327
|
+
snippet: `"${cveRule.pkg}": "${ver}"`,
|
|
1328
|
+
message: `${cveRule.title}. Installed: ${ver}. ${cveRule.cve}.`,
|
|
1329
|
+
fix: cveRule.fix,
|
|
1330
|
+
title: cveRule.title,
|
|
1331
|
+
});
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
return out;
|
|
1335
|
+
},
|
|
1336
|
+
},
|
|
1337
|
+
];
|
|
1338
|
+
|
|
1339
|
+
// ---------------------------------------------------------------------------
|
|
1340
|
+
// Cross-file rules (need ALL file contents at once — see scanner.js)
|
|
1341
|
+
// ---------------------------------------------------------------------------
|
|
1342
|
+
|
|
1343
|
+
// Escape a string for use inside a RegExp.
|
|
1344
|
+
function reEscape(s) {
|
|
1345
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
const crossFileRules = [
|
|
1349
|
+
{
|
|
1350
|
+
id: 'supabase.rls-missing',
|
|
1351
|
+
severity: 'high',
|
|
1352
|
+
confidence: 'low',
|
|
1353
|
+
title: 'SQL table created without row-level security enabled',
|
|
1354
|
+
// Aggregates across EVERY .sql file: a table may be created in schema.sql and
|
|
1355
|
+
// have RLS enabled in a separate migration. Only flag tables that are never
|
|
1356
|
+
// RLS-enabled anywhere in the project.
|
|
1357
|
+
run(files) {
|
|
1358
|
+
const sql = files.filter((f) => /\.sql$/i.test(f.rel));
|
|
1359
|
+
if (sql.length === 0) return [];
|
|
1360
|
+
|
|
1361
|
+
const rlsTables = new Set();
|
|
1362
|
+
const creates = [];
|
|
1363
|
+
const createRe = /create\s+table\s+(?:if\s+not\s+exists\s+)?["'`]?([A-Za-z0-9_.]+)["'`]?/gi;
|
|
1364
|
+
const rlsRe = /alter\s+table\s+(?:public\.)?["'`]?([A-Za-z0-9_.]+)["'`]?\s+enable\s+row\s+level\s+security/gi;
|
|
1365
|
+
|
|
1366
|
+
for (const f of sql) {
|
|
1367
|
+
let m;
|
|
1368
|
+
rlsRe.lastIndex = 0;
|
|
1369
|
+
while ((m = rlsRe.exec(f.content)) !== null) {
|
|
1370
|
+
rlsTables.add(m[1].replace(/^public\./i, '').toLowerCase());
|
|
1371
|
+
}
|
|
1372
|
+
for (let i = 0; i < f.lines.length; i++) {
|
|
1373
|
+
createRe.lastIndex = 0;
|
|
1374
|
+
const cm = createRe.exec(f.lines[i]);
|
|
1375
|
+
if (cm) creates.push({ table: cm[1].replace(/^public\./i, ''), file: f.rel, line: i + 1 });
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
const out = [];
|
|
1380
|
+
for (const c of creates) {
|
|
1381
|
+
if (rlsTables.has(c.table.toLowerCase())) continue;
|
|
1382
|
+
out.push({
|
|
1383
|
+
file: c.file,
|
|
1384
|
+
line: c.line,
|
|
1385
|
+
column: 1,
|
|
1386
|
+
snippet: `create table ${c.table}`,
|
|
1387
|
+
message: `Table "${c.table}" is created but row-level security is never enabled for it anywhere in the project. Without RLS, Supabase exposes the whole table to any anon-key client.`,
|
|
1388
|
+
fix: `Add: ALTER TABLE ${c.table} ENABLE ROW LEVEL SECURITY; and define policies scoped to auth.uid().`,
|
|
1389
|
+
});
|
|
1390
|
+
}
|
|
1391
|
+
return out;
|
|
1392
|
+
},
|
|
1393
|
+
},
|
|
1394
|
+
];
|
|
1395
|
+
|
|
1396
|
+
// Flat registry of every rule (for `vibeguard rules` / `explain`). File/cross
|
|
1397
|
+
// rules carry dynamic messages, so message/fix may be empty there — title covers it.
|
|
1398
|
+
function allRules() {
|
|
1399
|
+
const out = [];
|
|
1400
|
+
const add = (r) => out.push({
|
|
1401
|
+
id: r.id,
|
|
1402
|
+
category: (r.id || '').split('.')[0],
|
|
1403
|
+
severity: r.severity,
|
|
1404
|
+
confidence: r.confidence || 'high',
|
|
1405
|
+
title: r.title || r.id,
|
|
1406
|
+
message: r.message || '',
|
|
1407
|
+
fix: r.fix || '',
|
|
1408
|
+
});
|
|
1409
|
+
for (const r of lineRules) add(r);
|
|
1410
|
+
for (const r of fileRules) add(r);
|
|
1411
|
+
for (const r of crossFileRules) add(r);
|
|
1412
|
+
// Rules that live in other modules (not line/file/cross) — list by id for docs.
|
|
1413
|
+
for (const id of [
|
|
1414
|
+
'ast.eval-dynamic', 'ast.command-injection', 'ast.function-constructor',
|
|
1415
|
+
'ast.mass-assignment', 'ast.nosql-injection', 'ast.path-traversal', 'ast.ssrf',
|
|
1416
|
+
'taint.command-injection', 'taint.sql-injection', 'taint.code-injection',
|
|
1417
|
+
'taint.path-traversal', 'taint.ssrf', 'taint.open-redirect',
|
|
1418
|
+
'taint.interprocedural', 'taint.cross-file',
|
|
1419
|
+
'dep.npm-vulnerability', 'dep.pip-vulnerability',
|
|
1420
|
+
'package.no-lockfile', 'project.env-not-ignored', 'project.env-exposed',
|
|
1421
|
+
'url.no-https', 'url.missing-content-security-policy', 'url.insecure-cookie', 'url.version-leak',
|
|
1422
|
+
'history.secret', 'doctor.hook-injection', 'doctor.base-url-hijack', 'doctor.mcp-suspicious',
|
|
1423
|
+
]) out.push({ id, category: id.split('.')[0], severity: '-', confidence: '-', title: id, message: '', fix: '' });
|
|
1424
|
+
return out;
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
module.exports = {
|
|
1428
|
+
SEVERITY_ORDER,
|
|
1429
|
+
allRules,
|
|
1430
|
+
lineRules,
|
|
1431
|
+
fileRules,
|
|
1432
|
+
crossFileRules,
|
|
1433
|
+
secretRules,
|
|
1434
|
+
codeRules,
|
|
1435
|
+
authRules,
|
|
1436
|
+
webRules,
|
|
1437
|
+
piiRules,
|
|
1438
|
+
makeFinding,
|
|
1439
|
+
matchAll,
|
|
1440
|
+
isCommentLine,
|
|
1441
|
+
looksLikePlaceholder,
|
|
1442
|
+
isPublicBaaSKey,
|
|
1443
|
+
configure,
|
|
1444
|
+
isRedacted,
|
|
1445
|
+
COMPLIANCE_MAP,
|
|
1446
|
+
};
|