@yagyeshvyas/vibeguard 1.3.0 → 1.11.1

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.
Files changed (167) hide show
  1. package/.vibeguard-mcp.example.json +51 -0
  2. package/CHANGELOG.md +604 -216
  3. package/MCP-FIREWALL.md +296 -0
  4. package/README.md +355 -31
  5. package/bin/cli.js +355 -27
  6. package/bin/cmd-agent-monitor.js +45 -0
  7. package/bin/cmd-agent-risk.js +64 -0
  8. package/bin/cmd-gif.js +62 -0
  9. package/bin/cmd-git-scan.js +74 -0
  10. package/bin/cmd-llm-proxy.js +164 -0
  11. package/bin/cmd-mcp-firewall.js +191 -0
  12. package/bin/cmd-pentest.js +103 -0
  13. package/bin/cmd-platform.js +137 -0
  14. package/bin/cmd-pr-scan.js +135 -0
  15. package/bin/cmd-sbom-diff.js +38 -0
  16. package/bin/cmd-skill-scan.js +35 -0
  17. package/docs/AISVS.md +25 -0
  18. package/docs/ARCHITECTURE.md +81 -0
  19. package/docs/INSTALLATION.md +139 -0
  20. package/docs/WINDOWS.md +74 -0
  21. package/docs/security-policy.strict.example.json +134 -0
  22. package/docs/security-policy.strict.example.pub.pem +3 -0
  23. package/package.json +45 -7
  24. package/src/.vibeguard/cache/file-hashes.json +60 -0
  25. package/src/.vibeguard/latest-snapshot.json +36 -0
  26. package/src/.vibeguard/mcp-pins.json +1 -0
  27. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/auto.js +428 -0
  28. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/daemon.js +344 -0
  29. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/dashboard.js +279 -0
  30. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/engine.js +297 -0
  31. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/hook.js +151 -0
  32. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/install.js +299 -0
  33. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/manifest.json +65 -0
  34. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/mcp-server.js +2051 -0
  35. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/plugin.js +168 -0
  36. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/pre-deploy.js +362 -0
  37. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/repl.js +150 -0
  38. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/rules.js +1611 -0
  39. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/sbom.js +164 -0
  40. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/shell-guard.js +292 -0
  41. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/slopsquat.js +144 -0
  42. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/trace.js +220 -0
  43. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/auto.js +428 -0
  44. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/daemon.js +344 -0
  45. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/engine.js +297 -0
  46. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/install.js +299 -0
  47. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/manifest.json +37 -0
  48. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/mcp-server.js +2055 -0
  49. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/plugin.js +168 -0
  50. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/pre-deploy.js +362 -0
  51. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/trace.js +220 -0
  52. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/auto.js +428 -0
  53. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/daemon.js +344 -0
  54. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/dashboard.js +279 -0
  55. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/engine.js +297 -0
  56. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/hook.js +151 -0
  57. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/install.js +299 -0
  58. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/manifest.json +65 -0
  59. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/mcp-server.js +2055 -0
  60. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/plugin.js +168 -0
  61. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/pre-deploy.js +362 -0
  62. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/repl.js +150 -0
  63. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/rules.js +1611 -0
  64. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/sbom.js +164 -0
  65. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/shell-guard.js +292 -0
  66. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/slopsquat.js +144 -0
  67. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/trace.js +220 -0
  68. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/auto.js +428 -0
  69. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/daemon.js +344 -0
  70. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/dashboard.js +279 -0
  71. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/engine.js +297 -0
  72. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/hook.js +151 -0
  73. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/install.js +299 -0
  74. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/manifest.json +65 -0
  75. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/mcp-server.js +2054 -0
  76. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/plugin.js +168 -0
  77. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/pre-deploy.js +362 -0
  78. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/repl.js +150 -0
  79. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/rules.js +1611 -0
  80. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/sbom.js +164 -0
  81. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/shell-guard.js +292 -0
  82. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/slopsquat.js +144 -0
  83. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/trace.js +220 -0
  84. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/auto.js +428 -0
  85. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/daemon.js +344 -0
  86. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/engine.js +297 -0
  87. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/install.js +299 -0
  88. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/manifest.json +37 -0
  89. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/mcp-server.js +2055 -0
  90. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/plugin.js +168 -0
  91. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/pre-deploy.js +362 -0
  92. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/trace.js +220 -0
  93. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/auto.js +428 -0
  94. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/daemon.js +344 -0
  95. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/engine.js +297 -0
  96. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/manifest.json +33 -0
  97. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/mcp-server.js +2055 -0
  98. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/rules.js +1611 -0
  99. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/shell-guard.js +292 -0
  100. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/trace.js +220 -0
  101. package/src/.vibeguard-baseline.json +5226 -0
  102. package/src/action-guard.js +84 -6
  103. package/src/agent-monitor.js +262 -0
  104. package/src/agent-policy.js +642 -0
  105. package/src/agent-risk.js +271 -0
  106. package/src/agentic.js +1513 -0
  107. package/src/ast.js +165 -7
  108. package/src/audit-trail.js +212 -67
  109. package/src/auto.js +427 -427
  110. package/src/autofix.js +11 -4
  111. package/src/bundles.js +198 -0
  112. package/src/daemon.js +343 -343
  113. package/src/dashboard.js +278 -278
  114. package/src/engine.js +3 -0
  115. package/src/entropy.js +187 -0
  116. package/src/firewall.js +19 -3
  117. package/src/gif.js +134 -0
  118. package/src/gitscan.js +282 -0
  119. package/src/hook.js +151 -151
  120. package/src/injection-decode.js +136 -0
  121. package/src/install.js +298 -280
  122. package/src/integrity.js +16 -1
  123. package/src/integrity.json +43 -13
  124. package/src/interceptor.js +12 -9
  125. package/src/llm-proxy.js +986 -0
  126. package/src/mcp-audit.js +61 -5
  127. package/src/mcp-firewall.js +971 -0
  128. package/src/mcp-server.js +2500 -2047
  129. package/src/obfuscation.js +315 -0
  130. package/src/owasp-agentic.js +314 -0
  131. package/src/pentest.js +589 -0
  132. package/src/pii.js +4 -0
  133. package/src/platform/aisvs.js +38 -0
  134. package/src/platform/approval.js +187 -0
  135. package/src/platform/canonical.js +73 -0
  136. package/src/platform/contracts.js +158 -0
  137. package/src/platform/delegation.js +73 -0
  138. package/src/platform/http-gateway.js +177 -0
  139. package/src/platform/identity.js +253 -0
  140. package/src/platform/jwt.js +86 -0
  141. package/src/platform/mcp-http-bridge.js +199 -0
  142. package/src/platform/memory-guard.js +64 -0
  143. package/src/platform/os-sandbox.js +144 -0
  144. package/src/platform/policy.js +332 -0
  145. package/src/platform/sandbox-manager.js +92 -0
  146. package/src/platform/signed-audit.js +357 -0
  147. package/src/platform/ssrf.js +129 -0
  148. package/src/plugin.js +182 -168
  149. package/src/pre-deploy.js +170 -55
  150. package/src/privacy-audit.js +272 -272
  151. package/src/repl.js +150 -150
  152. package/src/report.js +7 -1
  153. package/src/routes.js +1210 -0
  154. package/src/rules-2026.js +1407 -0
  155. package/src/rules-pack.js +3068 -3019
  156. package/src/rules.js +376 -60
  157. package/src/sandbox.js +200 -10
  158. package/src/sbom.js +193 -164
  159. package/src/scanner.js +189 -33
  160. package/src/shell-guard.js +11 -0
  161. package/src/skill-scan.js +477 -0
  162. package/src/slopsquat.js +144 -144
  163. package/src/surface.js +408 -0
  164. package/src/taint-ast.js +204 -37
  165. package/src/taint.js +15 -3
  166. package/src/tokenlean.js +579 -0
  167. package/src/trace.js +220 -220
@@ -0,0 +1,1407 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * VibeGuard 2026 detection pack — the classes AI code generators get wrong.
5
+ *
6
+ * Separate from rules.js/rules-pack.js because this file targets the *evidence*
7
+ * from 2025-2026 research on AI-written applications:
8
+ * - Veracode GenAI report: 45% of generated samples shipped an OWASP Top-10
9
+ * flaw; crypto (CWE-327) and log injection (CWE-117) were the worst classes.
10
+ * - CSA / CodeRabbit: 1.91x IDOR, 1.82x insecure deserialization, 2.74x more
11
+ * security issues in AI-co-authored PRs; 15/15 vibe-coded apps lacked CSRF.
12
+ * - GitGuardian 2026: Claude-assisted commits leak secrets at 3.2% vs 1.5%.
13
+ * - USENIX'25: 19.7% of LLM-recommended packages do not exist (slopsquatting).
14
+ *
15
+ * Precision contract: every rule either requires two independent signals or
16
+ * matches a construct that is unambiguously wrong in production code. Rules that
17
+ * would page on framework boilerplate are left out rather than shipped noisy.
18
+ */
19
+
20
+ // --- small helpers ---------------------------------------------------------
21
+
22
+ const REQ = /\b(?:req|request|ctx|c|event|input|params|searchParams|query|body)\b/;
23
+
24
+ // A value derived from the request, in the forms generators actually emit.
25
+ const REQ_DERIVED =
26
+ '(?:req\\.(?:body|query|params|headers|cookies)|request\\.(?:body|query|params|form|args|json|GET|POST|data)|' +
27
+ 'ctx\\.(?:body|query|params)|c\\.req\\.(?:query|param|json|body)|event\\.(?:body|queryStringParameters|pathParameters)|' +
28
+ 'searchParams\\.get\\(|params\\.(?:id|slug|uuid|key|token)|formData\\.get\\()';
29
+
30
+ const isComment = (l) => /^\s*(?:\/\/|#|\*|\/\*)/.test(l);
31
+ const has = (s, re) => re.test(s);
32
+
33
+ function idxOf(lines, line) {
34
+ return lines ? lines.indexOf(line) : -1;
35
+ }
36
+
37
+ function makeLineRule(o) {
38
+ return o;
39
+ }
40
+
41
+ // ---------------------------------------------------------------------------
42
+ // 1. Authorization: IDOR, missing authz, privilege from client
43
+ // ---------------------------------------------------------------------------
44
+
45
+ const authz2026 = [
46
+ makeLineRule({
47
+ id: 'authz2026.orm-fetch-by-param-id-no-owner',
48
+ severity: 'high',
49
+ confidence: 'medium',
50
+ title: 'Object fetched by request id with no ownership filter (IDOR)',
51
+ re: new RegExp(
52
+ `(?:findUnique|findFirst|findOne|findById|findByIdAndUpdate|findByIdAndDelete|findOneAndUpdate|findOneAndDelete|` +
53
+ `first|single|maybeSingle)\\s*\\(\\s*\\{[^}]{0,160}?${REQ_DERIVED}`,
54
+ 'i'
55
+ ),
56
+ filter(line) {
57
+ // The query must select by id AND not constrain by an owner/tenant column.
58
+ const selectsById = /\b(?:id|uuid|slug|key|token)\b\s*:?\s*(?:params|req\.|searchParams|\(\s*\))/i.test(line) ||
59
+ /\.eq\(\s*['"](id|uuid)['"]/i.test(line);
60
+ if (!selectsById) return false;
61
+ const ownerScoped = /(?:userId|user_id|ownerId|owner_id|tenantId|tenant_id|orgId|org_id|accountId|account_id|authorId|author_id|workspaceId|teamId|customerId|auth\.uid\(\))/i.test(line);
62
+ return !ownerScoped;
63
+ },
64
+ skipComments: true,
65
+ message:
66
+ 'A record is fetched by an id that came straight from the request, with no owner/tenant predicate on the same query. Any authenticated user can read any row by changing the id (IDOR / BOLA).',
67
+ fix: 'Add an ownership constraint to the same query — e.g. where: { id: params.id, userId: session.user.id } — or enforce it in a policy (RLS, Prisma extension, scoped repository).',
68
+ cwe: 'CWE-639', owasp: 'A01:2025 Broken Access Control',
69
+ }),
70
+
71
+ makeLineRule({
72
+ id: 'authz2026.orm-mutation-by-param-id-no-owner',
73
+ severity: 'high',
74
+ confidence: 'medium',
75
+ title: 'Object updated/deleted by request id with no ownership filter',
76
+ re: new RegExp(
77
+ `\\.(?:update|updateMany|delete|deleteMany|upsert)\\s*\\(\\s*\\{[^}]{0,200}?where\\s*:\\s*\\{[^}]{0,120}?${REQ_DERIVED}`,
78
+ 'i'
79
+ ),
80
+ filter(line) {
81
+ if (!/\bwhere\b/.test(line)) return false;
82
+ return !/(?:userId|user_id|ownerId|owner_id|tenantId|tenant_id|orgId|org_id|authorId|accountId|workspaceId|teamId)/i.test(line);
83
+ },
84
+ skipComments: true,
85
+ message:
86
+ 'A write is scoped only by a request-supplied id. Without an owner/tenant predicate the caller can update or delete another user\'s record (IDOR → privilege abuse / data loss).',
87
+ fix: 'Constrain the write with the caller identity too: where: { id, userId: session.user.id }. Prefer a repository that cannot issue an unscoped write.',
88
+ cwe: 'CWE-639', owasp: 'A01:2025 Broken Access Control',
89
+ }),
90
+
91
+ makeLineRule({
92
+ id: 'authz2026.supabase-eq-id-no-user-filter',
93
+ severity: 'high',
94
+ confidence: 'medium',
95
+ title: 'Supabase query filtered only by request id (RLS must cover it)',
96
+ re: /\.eq\(\s*['"](?:id|uuid)['"]\s*,\s*[^)]*(?:params|req\.|searchParams|\bid\b)[^)]*\)/i,
97
+ filter(line) {
98
+ return !/(?:user_id|userId|owner_id|ownerId|tenant_id|tenantId|org_id|auth\.uid)/i.test(line);
99
+ },
100
+ skipComments: true,
101
+ message:
102
+ 'Supabase row fetch/delete is filtered only by the id from the request. If the table\'s RLS policy is permissive or missing, any anon-key client can read/modify every row. RLS presence is not RLS correctness.',
103
+ fix: 'Filter by the member column too (.eq("user_id", user.id)) and make sure the policy itself says auth.uid() = user_id for SELECT/UPDATE/DELETE.',
104
+ cwe: 'CWE-639', owasp: 'A01:2025 Broken Access Control',
105
+ }),
106
+
107
+ makeLineRule({
108
+ id: 'authz2026.mass-assignment-privileged-field',
109
+ severity: 'high',
110
+ confidence: 'medium',
111
+ title: 'Request body spread into a write — privilege fields reachable',
112
+ re: new RegExp(`(?:data|values|setRepr|document)\\s*:\\s*(?:\\.\\.\\.)?\\s*${REQ_DERIVED}`, 'i'),
113
+ filter(line, hit, lines) { const idx = idxOf(lines, line);
114
+ // Only when a privileged field exists nearby (the model or payload).
115
+ const ctx = lines.slice(Math.max(0, idx - 4), idx + 6).join('\n') + line;
116
+ return /(?:role|isAdmin|is_admin|admin|plan|credits|balance|verified|isVerified|tier|permissions|ownerId|price)\b/.test(ctx);
117
+ },
118
+ skipComments: true,
119
+ message:
120
+ 'The whole request body is written to a record. Generators do this as `prisma.user.update({ data: req.body })`; a caller can then set role/isAdmin/credits/plan fields the UI never exposes (mass assignment).',
121
+ fix: 'Destructure an explicit allowlist: const { name, bio } = body; then write only those. Never spread req.body into create/update.',
122
+ cwe: 'CWE-915', owasp: 'A01:2025 Broken Access Control',
123
+ }),
124
+
125
+ makeLineRule({
126
+ id: 'authz2026.admin-flag-from-request',
127
+ severity: 'critical',
128
+ confidence: 'high',
129
+ title: 'Privilege flag taken from the request',
130
+ re: new RegExp(`\\b(?:isAdmin|is_admin|role|permissions|isSuperuser|isStaff)\\b\\s*[:=]\\s*${REQ_DERIVED}`, 'i'),
131
+ skipComments: true,
132
+ message:
133
+ 'A privileged field is assigned straight from the request. A caller sets role/isAdmin themselves — vertical privilege escalation, regardless of auth.',
134
+ fix: 'Never accept role/permission fields from clients. Resolve them server-side from the session or an allowlist.',
135
+ cwe: 'CWE-269', owasp: 'A01:2025 Broken Access Control',
136
+ }),
137
+
138
+ makeLineRule({
139
+ id: 'authz2026.authorization-header-trusted',
140
+ severity: 'high',
141
+ confidence: 'medium',
142
+ title: 'Identity taken from a client-controlled header',
143
+ re: /(?:headers?\.(?:get\()?\s*['"]?x-(?:user|userid|user-id|role|admin|tenant|account))|(?:req\.headers\[['"]x-user)/i,
144
+ skipComments: true,
145
+ message:
146
+ 'The request\'s own `x-user-id` / `x-role` header is trusted for identity. Headers are client-controlled unless a trusted proxy strips and rewrites them — impersonation.',
147
+ fix: 'Derive identity from the verified session/JWT. If a gateway sets the header, strip inbound copies and verify the signature.',
148
+ cwe: 'CWE-290', owasp: 'A07:2025 Authentication Failures',
149
+ }),
150
+
151
+ makeLineRule({
152
+ id: 'authz2026.check-then-act-role',
153
+ severity: 'medium',
154
+ confidence: 'medium',
155
+ title: 'Role check via assignment instead of comparison',
156
+ re: /if\s*\(\s*[\w.]+\s*===\s*['"]admin['"]\s*\)\s*\{?|\brole\s*=\s*['"]admin['"]\s*(?:\)|;)/,
157
+ filter(line) {
158
+ return /\bif\s*\(|\brole\s*=/.test(line);
159
+ },
160
+ skipComments: true,
161
+ message:
162
+ 'A role check looks like an assignment or has no trusted source. `if (user.role = "admin")` is always truthy in JS and grants admin to everyone.',
163
+ fix: 'Compare, never assign: if (user?.role === "admin"). Put the check in one middleware and test it.',
164
+ cwe: 'CWE-697', owasp: 'A01:2025 Broken Access Control',
165
+ }),
166
+ ];
167
+
168
+ // Next.js-specific: middleware-only auth, matchers, server actions.
169
+ const nextjs2026 = [
170
+ {
171
+ id: 'nextjs2026.middleware-matcher-excludes-api',
172
+ severity: 'high',
173
+ confidence: 'medium',
174
+ title: 'Next.js middleware matcher excludes /api — those routes are unguarded',
175
+ match(content) {
176
+ const m = /matcher\s*:\s*\[([\s\S]{0,500}?)\]/.exec(content);
177
+ if (!m) return [];
178
+ const patterns = [...m[1].matchAll(/['"]([^'"]+)['"]/g)].map((x) => x[1]);
179
+ const index = m.index + m[1].indexOf(patterns[0] || '');
180
+ // `/((?!api|_next).*)` style negative lookaheads deliberately skip /api.
181
+ const skipsApi = patterns.some((p) => /\(\?!.*\bapi\b/.test(p));
182
+ if (!skipsApi) return [];
183
+ return [{ index: Math.max(0, index), match: patterns.join(' ') }];
184
+ },
185
+ message:
186
+ 'The middleware matcher excludes /api. If auth lives only in middleware.ts, every app/api/*/route.ts is public — and middleware auth can be bypassed via x-middleware-subrequest (CVE-2025-29927) on unpatched Next versions.',
187
+ fix: 'Guard each route handler/Server Action with the session check itself, and add an explicit per-route or per-middleware API guard. Upgrade next past the CVE-2025-29927 fix.',
188
+ cwe: 'CWE-288', owasp: 'A01:2025 Broken Access Control',
189
+ },
190
+ {
191
+ id: 'nextjs2026.server-action-no-auth',
192
+ severity: 'high',
193
+ confidence: 'medium',
194
+ title: 'Server Action exported without an auth check',
195
+ run(content, lines, relPath) {
196
+ if (!/['"]use server['"]/.test(content)) return [];
197
+ const re = /export\s+(?:async\s+)?function\s+(\w+)\s*\(/g;
198
+ const out = [];
199
+ let m;
200
+ while ((m = re.exec(content)) !== null) {
201
+ const lineIdx = content.slice(0, m.index).split('\n').length - 1;
202
+ // Window: the function body, approximated to the next export or 60 lines.
203
+ const window = lines.slice(lineIdx, Math.min(lines.length, lineIdx + 60)).join('\n');
204
+ if (/\bauth\s*\(|\bgetServerSession\b|\bgetSession\b|\bcurrentUser\b|\brequire(?:User|Auth|Session)\b|\bverifySession\b|\bassertAuth\b/.test(window)) continue;
205
+ // Only flag when the action does something privileged.
206
+ if (!/(?:prisma|db|supabase|firebase|knex|drizzle|\.(?:create|update|delete|insert|save)\b|fetch\s*\(|fs\.)/.test(window)) continue;
207
+ out.push({
208
+ line: lineIdx + 1,
209
+ column: 1,
210
+ snippet: m[0].slice(0, 120),
211
+ message: `Server Action ${m[1]}() is callable from any page by any visitor and performs a privileged operation with no session check. A Server Action is a public RPC endpoint, not a form handler.`,
212
+ fix: `Start ${m[1]}() with the session check (e.g. const session = await auth(); if (!session) throw new Error("UNAUTHORIZED")), and authorize the specific object it mutates.`,
213
+ });
214
+ if (out.length >= 8) break;
215
+ }
216
+ return out;
217
+ },
218
+ severity: 'high',
219
+ confidence: 'medium',
220
+ titleCheck: true,
221
+ },
222
+ makeLineRule({
223
+ id: 'nextjs2026.public-env-secret',
224
+ severity: 'critical',
225
+ confidence: 'high',
226
+ title: 'Secret-looking value under a public env prefix — shipped to the browser',
227
+ re: /\b(?:NEXT_PUBLIC|VITE|REACT_APP|EXPO_PUBLIC|PUBLIC|NUXT_PUBLIC)_[A-Z0-9_]*(?:SECRET|SERVICE_ROLE|PRIVATE|PASSWORD|CREDENTIAL|DB_|DATABASE|OPENAI|ANTHROPIC|STRIPE_SECRET|AWS_SECRET|JWT_SECRET|API_KEY|TOKEN)[A-Z0-9_]*\b/i,
228
+ filter(line) {
229
+ // NEXT_PUBLIC_SITE_URL, VITE_ANON_KEY etc. are meant to be public.
230
+ if (/(?:SITE_URL|PUBLIC_KEY|ANON_KEY|POSTHOG|GOOGLE_ANALYTICS|GA_ID|SENTRY_DSN|STRIPE_PUBLISHABLE|PUBLISHABLE)/i.test(line)) return false;
231
+ return true;
232
+ },
233
+ skipComments: true,
234
+ message:
235
+ 'A name under a public/browser env prefix holds a private credential. Next/Vite/Expo inline these into the client bundle — the value is readable by every visitor (and by any AI agent that later scrapes the bundle).',
236
+ fix: 'Drop the public prefix for server-only secrets, keep them only in server components/route handlers, and rotate the exposed value.',
237
+ cwe: 'CWE-200', owasp: 'A02:2025 Security Misconfiguration',
238
+ }),
239
+ makeLineRule({
240
+ id: 'nextjs2026.server-only-missing-service-role',
241
+ severity: 'high',
242
+ confidence: 'medium',
243
+ title: 'Service-role/admin client created outside a server-only module',
244
+ re: /(?:createClient|initializeApp|admin\.initializeApp)\s*\([^)]*(?:SERVICE_ROLE|service_role|ADMIN_KEY|SERVICE_KEY)/i,
245
+ filter(line) {
246
+ return !/['"]use server['"]|server-only|process\.env\.SUPABASE_SERVICE_ROLE/i.test(line);
247
+ },
248
+ skipComments: true,
249
+ message:
250
+ 'A service-role/admin Supabase or Firebase client is created here. If this module can be imported by a client component, the key ships to the browser and RLS no longer protects anything.',
251
+ fix: 'Move this into a server-only module (import "server-only") or a route handler, use the anon key on the client, and keep RLS enabled.',
252
+ cwe: 'CWE-798', owasp: 'A02:2025 Security Misconfiguration',
253
+ }),
254
+ makeLineRule({
255
+ id: 'nextjs2026.redirect-user-input',
256
+ severity: 'medium',
257
+ confidence: 'medium',
258
+ title: 'Redirect target from request input (open redirect)',
259
+ re: /\bredirect\s*\(\s*(?:searchParams\.get|params\.|req\.|request\.|ctx\.|c\.req\.|next\b|returnTo\b|callbackUrl\b)/i,
260
+ skipComments: true,
261
+ message:
262
+ 'The redirect target comes from the request (?next=, callbackUrl). Attackers use the trusted domain for phishing and token leakage.',
263
+ fix: 'Allowlist internal paths: only accept a leading "/" and no "//"/scheme, or map an enum of known destinations.',
264
+ cwe: 'CWE-601', owasp: 'A01:2025 Broken Access Control',
265
+ }),
266
+ {
267
+ id: 'nextjs2026.config-no-security-headers',
268
+ severity: 'medium',
269
+ confidence: 'medium',
270
+ title: 'next.config has no headers() block (CSP/HSTS/frame protection)',
271
+ match(content, ctx) {
272
+ const rel = ((ctx && ctx.relPath) || '').replace(/\\/g, '/');
273
+ if (!/(?:^|\/)next\.config\.(?:js|mjs|ts)$/.test(rel)) return [];
274
+ if (!/module\.exports|export\s+default/.test(content)) return [];
275
+ if (/\bheaders\s*(?:\(\s*\)|:)\s*(?:async\s*)?\(?\s*\)?\s*(?:=>|\{)/.test(content)) return [];
276
+ const idx = content.indexOf('module.exports');
277
+ return [{ index: Math.max(0, idx), match: 'next.config' }];
278
+ },
279
+ message:
280
+ 'next.config defines no headers(), so the app ships without a Content-Security-Policy, HSTS, X-Frame-Options or Referrer-Policy by default — the exact gap found in AI-built apps.',
281
+ fix: 'Add headers() returning Content-Security-Policy, Strict-Transport-Security, X-Frame-Options: DENY, Referrer-Policy: strict-origin-when-cross-origin.',
282
+ cwe: 'CWE-693', owasp: 'A02:2025 Security Misconfiguration',
283
+ },
284
+ ];
285
+
286
+ // ---------------------------------------------------------------------------
287
+ // 2. Supabase / Firebase — correctness, not presence
288
+ // ---------------------------------------------------------------------------
289
+
290
+ const supabase2026 = [
291
+ makeLineRule({
292
+ id: 'supabase2026.rls-policy-using-true',
293
+ severity: 'critical',
294
+ confidence: 'high',
295
+ title: 'RLS policy allows every row (USING (true))',
296
+ re: /using\s*\(\s*true\s*\)/i,
297
+ fileFilter: /\.(sql|ts|js)$/i,
298
+ skipComments: true,
299
+ message:
300
+ 'A row-level security policy allows all rows. RLS is enabled, so the Supabase dashboard shows "protected" — but any client with the anon key reads and writes everything.',
301
+ fix: 'Scope the policy to the owner: using (auth.uid() = user_id) with check (auth.uid() = user_id). Run the Supabase security advisor after the change.',
302
+ cwe: 'CWE-284', owasp: 'A01:2025 Broken Access Control',
303
+ }),
304
+ makeLineRule({
305
+ id: 'supabase2026.security-definer-no-search-path',
306
+ severity: 'medium',
307
+ confidence: 'medium',
308
+ title: 'SECURITY DEFINER function without a pinned search_path',
309
+ re: /security\s+definer/i,
310
+ filter(line, hit, lines) { const idx = idxOf(lines, line);
311
+ if (!lines) return true;
312
+ // The function's own body only: stop at the next CREATE FUNCTION, so a
313
+ // later safe function cannot mask this one.
314
+ const window = [];
315
+ for (let i = Math.max(0, idx); i < Math.min(lines.length, idx + 20); i++) {
316
+ if (i > idx && /create\s+(?:or\s+replace\s+)?function/i.test(lines[i])) break;
317
+ window.push(lines[i]);
318
+ }
319
+ return !/set\s+search_path/i.test(window.join('\n'));
320
+ },
321
+ fileFilter: /\.sql$/i,
322
+ skipComments: true,
323
+ message:
324
+ 'A SECURITY DEFINER function runs with its owner\'s privileges. Without `set search_path = \'\'` an attacker who can create objects in an earlier schema shadows tables/functions it calls (CVE-2018-1058 class).',
325
+ fix: 'Add `set search_path = \'\'` (or a fixed schema) to the function body and fully qualify every referenced object.',
326
+ cwe: 'CWE-269', owasp: 'A01:2025 Broken Access Control',
327
+ }),
328
+ makeLineRule({
329
+ id: 'supabase2026.grant-all-to-anon',
330
+ severity: 'critical',
331
+ confidence: 'high',
332
+ title: 'GRANT ALL to anon/authenticated',
333
+ re: /grant\s+all\s+(?:privileges\s+)?on\s+[a-z_."]+?\s+to\s+(?:anon|authenticated)\b/i,
334
+ fileFilter: /\.sql$/i,
335
+ skipComments: true,
336
+ message:
337
+ 'ALL privileges are granted to anon/authenticated. Even with RLS enabled, this hands DDL/DML power and defeats least privilege; anonymous callers can often truncate or drop.',
338
+ fix: 'Grant the minimum verbs per table (select/insert/update/delete) only to authenticated, and scope RLS policies per row.',
339
+ cwe: 'CWE-269', owasp: 'A01:2025 Broken Access Control',
340
+ }),
341
+ makeLineRule({
342
+ id: 'supabase2026.select-star-exposed',
343
+ severity: 'medium',
344
+ confidence: 'medium',
345
+ title: 'select("*") from a table plus a response — column leak',
346
+ re: /\.from\(\s*['"][\w]+['"]\s*\)\s*\.select\(\s*['"]\*['"]\s*\)/i,
347
+ filter(line, hit, lines) { const idx = idxOf(lines, line);
348
+ const ctx = lines ? lines.slice(Math.max(0, (idx) - 2), (idx) + 6).join('\n') : line;
349
+ // Only when the rows then go back to the caller / client.
350
+ return /res\.(?:json|send)|Response\.json|return\s+data|NextResponse\.json|\.map\(|serialize/i.test(ctx);
351
+ },
352
+ skipComments: true,
353
+ message:
354
+ 'select("*") returns every column and the rows are sent to the caller — password_hash, api_key, reset_token and internal notes included. AI-generated schemas usually carry those columns.',
355
+ fix: 'Select the fields the UI needs explicitly: .select("id, title, created_at"). Never return auth/secret columns to the client.',
356
+ cwe: 'CWE-200', owasp: 'A01:2025 Broken Access Control',
357
+ }),
358
+ {
359
+ id: 'supabase2026.service-role-in-client',
360
+ severity: 'critical',
361
+ confidence: 'high',
362
+ title: 'service_role key referenced from client-side code',
363
+ match(content, ctx) {
364
+ const relPath = (ctx && ctx.relPath) || '';
365
+ if (!/\.(?:tsx|jsx|ts|js)$/.test(relPath)) return [];
366
+ const client = /['"]use client['"]/.test(content) || /(?:^|\/)components?\//.test(relPath) || /\.(?:tsx|jsx)$/.test(relPath);
367
+ if (!client) return [];
368
+ const idx = content.search(/(?:SUPABASE_SERVICE_ROLE|service_role|SERVICE_ROLE_KEY)/);
369
+ if (idx < 0) return [];
370
+ // Server-only marker in the same file makes it safe.
371
+ if (/server-only|['"]use server['"]/.test(content)) return [];
372
+ return [{ index: idx, match: 'service_role' }];
373
+ },
374
+ message:
375
+ 'A service_role key is used in a file that can be (or is) part of the client bundle. service_role bypasses RLS entirely — shipping it means the whole database is public.',
376
+ fix: 'Never reference service_role outside server-only modules/route handlers. Use the anon key on the client and enforce RLS policies.',
377
+ cwe: 'CWE-798', owasp: 'A02:2025 Security Misconfiguration',
378
+ },
379
+ ];
380
+
381
+ const firebase2026 = [
382
+ makeLineRule({
383
+ id: 'firebase2026.rules-allow-true',
384
+ severity: 'critical',
385
+ confidence: 'high',
386
+ title: 'Firestore/Storage rules allow everyone',
387
+ re: /allow\s+(?:read|write|read\s*,\s*write|write\s*,\s*read)\s*:\s*if\s*(?:true|\btrue\b)/i,
388
+ fileFilter: /(?:firestore\.rules|storage\.rules|database\.rules)$/i,
389
+ skipComments: true,
390
+ message:
391
+ 'A Firebase rules file allows unauthenticated read/write. Anyone with the public config (which is in every client) can read, write and delete the collection.',
392
+ fix: 'Scope rules to the owner: allow read, write: if request.auth != null && request.auth.uid == resource.data.userId.',
393
+ cwe: 'CWE-284', owasp: 'A01:2025 Broken Access Control',
394
+ }),
395
+ makeLineRule({
396
+ id: 'firebase2026.rules-auth-only-write',
397
+ severity: 'medium',
398
+ confidence: 'medium',
399
+ title: 'Firebase write allowed for any authenticated user',
400
+ re: /allow\s+write\s*:\s*if\s*request\.auth\s*!=\s*null\s*;/i,
401
+ fileFilter: /(?:firestore|storage|database)\.rules$/i,
402
+ skipComments: true,
403
+ message:
404
+ 'Any signed-in user can write any document. "Logged in" is not "owns this row" — a second account can overwrite the first user\'s data.',
405
+ fix: 'Compare identity to the record: request.auth.uid == resource.data.userId (and a separate create rule checking request.resource.data.userId).',
406
+ cwe: 'CWE-284', owasp: 'A01:2025 Broken Access Control',
407
+ }),
408
+ ];
409
+
410
+ // ---------------------------------------------------------------------------
411
+ // 3. Auth: JWT, cookies, sessions, CSRF
412
+ // ---------------------------------------------------------------------------
413
+
414
+ const jwt2026 = [
415
+ makeLineRule({
416
+ id: 'jwt2026.decode-used-for-identity',
417
+ severity: 'high',
418
+ confidence: 'high',
419
+ title: 'JWT decoded (not verified) and used as identity',
420
+ re: /\bjwt(?:Decode|_decode|\s*)\.decode\s*\(|\bjwtDecode\s*\(|\batob\s*\(\s*\w+\.split\(['"]\.['"]\)\s*\[\s*1\s*\]/i,
421
+ filter(line, hit, lines) { const idx = idxOf(lines, line);
422
+ const ctx = lines ? lines.slice(idx, (idx) + 8).join('\n') : line;
423
+ return /\b(?:userId|user_id|sub|role|email|admin|uid|identity|owner)\b/i.test(ctx);
424
+ },
425
+ skipComments: true,
426
+ message:
427
+ 'A JWT is decoded without verifying its signature, then its claims are trusted. Anyone can forge `{"sub":"1","role":"admin"}` in base64 — full account takeover.',
428
+ fix: 'Use jwt.verify(token, secret, { algorithms: ["HS256"] }) (or the framework session helper) and only trust verified claims.',
429
+ cwe: 'CWE-347', owasp: 'A07:2025 Authentication Failures',
430
+ }),
431
+ makeLineRule({
432
+ id: 'jwt2026.alg-none',
433
+ severity: 'critical',
434
+ confidence: 'high',
435
+ title: 'JWT accepts the "none" algorithm',
436
+ re: /algorithms?\s*:\s*\[?\s*['"]none['"]/i,
437
+ skipComments: true,
438
+ message:
439
+ 'The verifier accepts `alg: none`. An attacker strips the signature and the token is accepted as valid.',
440
+ fix: 'Pin the expected algorithm (e.g. ["RS256"]) and reject everything else.',
441
+ cwe: 'CWE-347', owasp: 'A07:2025 Authentication Failures',
442
+ }),
443
+ makeLineRule({
444
+ id: 'jwt2026.weak-fallback-secret',
445
+ severity: 'high',
446
+ confidence: 'high',
447
+ title: 'Session/JWT secret falls back to a literal',
448
+ re: /(?:JWT_SECRET|NEXTAUTH_SECRET|SESSION_SECRET|AUTH_SECRET)\b[^;\n]{0,40}?\|\|\s*['"][^'"]{3,}['"]/i,
449
+ skipComments: true,
450
+ message:
451
+ 'The signing secret falls back to a hardcoded string. If the env var is missing in production (it usually is on first deploy), every token is forgeable with a value that is in the repo.',
452
+ fix: 'Fail closed: if (!process.env.JWT_SECRET) throw new Error("JWT_SECRET missing"). Generate 32+ random bytes.',
453
+ cwe: 'CWE-798', owasp: 'A07:2025 Authentication Failures',
454
+ }),
455
+ makeLineRule({
456
+ id: 'jwt2026.no-expiry',
457
+ severity: 'medium',
458
+ confidence: 'medium',
459
+ title: 'JWT signed without an expiry',
460
+ re: /\bjwt\.sign\s*\(\s*[^;]{0,200}\)\s*;/,
461
+ filter(line) {
462
+ return !/(?:expiresIn|exp\s*:)/.test(line);
463
+ },
464
+ skipComments: true,
465
+ message:
466
+ 'A token is signed with no expiry. A leaked token stays valid forever; "logout" cannot revoke it.',
467
+ fix: 'Add { expiresIn: "15m" } and a refresh flow, or use the framework session (which rotates).',
468
+ cwe: 'CWE-613', owasp: 'A07:2025 Authentication Failures',
469
+ }),
470
+ makeLineRule({
471
+ id: 'jwt2026.token-in-localstorage',
472
+ severity: 'medium',
473
+ confidence: 'medium',
474
+ title: 'Session token stored in localStorage',
475
+ re: /localStorage\.(?:setItem|getItem)\s*\(\s*['"](?:token|access_token|jwt|auth|session)['"]/i,
476
+ skipComments: true,
477
+ message:
478
+ 'An auth token is kept in localStorage, readable by any XSS. httpOnly cookies are not readable by script and are the right default.',
479
+ fix: 'Set the session in an httpOnly, Secure, SameSite=Lax cookie server-side; keep localStorage for non-sensitive UI state only.',
480
+ cwe: 'CWE-1004', owasp: 'A07:2025 Authentication Failures',
481
+ }),
482
+ makeLineRule({
483
+ id: 'jwt2026.cookie-insecure',
484
+ severity: 'medium',
485
+ confidence: 'high',
486
+ title: 'Session cookie without httpOnly/secure/sameSite',
487
+ re: /cookie\s*:\s*\{|setCookie\s*\(|res\.cookie\s*\(/,
488
+ filter(line) {
489
+ // Must look like session/auth cookie context.
490
+ if (!/(?:session|token|auth|jwt|sid)/i.test(line)) return false;
491
+ return !/httpOnly\s*:\s*true/i.test(line) || !/secure\s*:\s*true/i.test(line);
492
+ },
493
+ skipComments: true,
494
+ message:
495
+ 'A session-shaped cookie is set without the full httpOnly + secure + sameSite flags. Script-readable session cookies turn any XSS into account takeover; missing Secure leaks them over HTTP.',
496
+ fix: 'cookies().set("session", v, { httpOnly: true, secure: true, sameSite: "lax", path: "/" }) — or the equivalent in your framework.',
497
+ cwe: 'CWE-1004', owasp: 'A07:2025 Authentication Failures',
498
+ }),
499
+ makeLineRule({
500
+ id: 'jwt2026.csrf-missing-state-route',
501
+ severity: 'medium',
502
+ confidence: 'low',
503
+ title: 'Cookie-authenticated write route with no CSRF/origin check',
504
+ re: /\b(?:app|router|server)\.(?:post|put|patch|delete)\s*\(/i,
505
+ filter(line, hit, lines) { const idx = idxOf(lines, line);
506
+ if (!lines) return false;
507
+
508
+ const ctx = lines.slice(idx, Math.min(lines.length, idx + 25)).join('\n');
509
+ const cookieAuth = /(?:req\.cookies|getSession|auth\(\)|session|cookie)/i.test(ctx);
510
+ const writes = /(?:\.(?:create|update|delete|insert|save)|writeFile|sendMail|transfer)/i.test(ctx);
511
+ const csrf = /(?:csrf|origin\s*!==|origin\s*===|x-csrf|sameSite\s*:\s*['"]strict|verifyOrigin)/i.test(ctx);
512
+ return cookieAuth && writes && !csrf;
513
+ },
514
+ skipComments: true,
515
+ message:
516
+ 'A cookie-authenticated state-changing route has no CSRF token and no Origin/Referer check. Another site can submit the request with the victim\'s cookies (CWE-352); 15/15 vibe-coded apps tested in the 2026 CSA note shipped without CSRF protection.',
517
+ fix: 'Use SameSite=Lax/Strict cookies plus a double-submit CSRF token, or verify Origin on every unsafe method; use the framework\'s built-in CSRF helper.',
518
+ cwe: 'CWE-352', owasp: 'A01:2025 Broken Access Control',
519
+ }),
520
+ ];
521
+
522
+ // ---------------------------------------------------------------------------
523
+ // 4. LLM output handling / agent safety / cost
524
+ // ---------------------------------------------------------------------------
525
+
526
+ const llm2026 = [
527
+ makeLineRule({
528
+ id: 'llm2026.output-to-exec',
529
+ severity: 'critical',
530
+ confidence: 'high',
531
+ title: 'Model output reaches eval/exec (improper output handling)',
532
+ re: /(?:eval|new\s+Function|exec|execSync|vm\.runIn\w+)\s*\(\s*(?:await\s+)?[\w.]*(?:completion|response|output|content|message|choices|answer|result|llm|ai)[\w.['"]{0,60}/i,
533
+ skipComments: true,
534
+ message:
535
+ 'Text returned by an LLM is executed as code. Prompt injection becomes RCE — the model (or a web page it read) controls the command (OWASP LLM05).',
536
+ fix: 'Never execute model output. Map output to a fixed enum of actions, validate with a JSON schema, and parameterize any downstream call.',
537
+ cwe: 'CWE-95', owasp: 'LLM05 Improper Output Handling',
538
+ }),
539
+ makeLineRule({
540
+ id: 'llm2026.output-to-sql',
541
+ severity: 'critical',
542
+ confidence: 'medium',
543
+ title: 'Model output interpolated into SQL',
544
+ re: /(?:query|raw|execute|executeRawUnsafe|queryRawUnsafe)\s*\(\s*`[^`]*\$\{[^}]*(?:completion|response|answer|output|llm|choices|message)/i,
545
+ skipComments: true,
546
+ message:
547
+ 'SQL is built from model output. A prompt-injected response (or bad hallucination) runs arbitrary SQL (OWASP LLM05).',
548
+ fix: 'Model output must never become SQL text. Map it to parameters or a fixed query chosen by a validated enum.',
549
+ cwe: 'CWE-89', owasp: 'LLM05 Improper Output Handling',
550
+ }),
551
+ makeLineRule({
552
+ id: 'llm2026.system-prompt-from-request',
553
+ severity: 'high',
554
+ confidence: 'high',
555
+ title: 'System prompt built from request/user data',
556
+ re: /role\s*:\s*['"]system['"]\s*,\s*content\s*:\s*(?:`[^`]*\$\{|[^,\n]*\+|[^,\n]*\breq\.)/i,
557
+ skipComments: true,
558
+ message:
559
+ 'A system message includes request data. The system slot is the trust boundary; injecting untrusted text there lets user content rewrite the instructions (OWASP LLM01).',
560
+ fix: 'Keep the system prompt static; pass user content in the user/assistant role inside explicit delimiters, and never concatenate tool output into system.',
561
+ cwe: 'CWE-1427', owasp: 'LLM01 Prompt Injection',
562
+ }),
563
+ makeLineRule({
564
+ id: 'llm2026.tool-result-into-system',
565
+ severity: 'high',
566
+ confidence: 'medium',
567
+ title: 'Tool/function result fed back into a system message',
568
+ re: /(?:role\s*:\s*['"]system['"]|systemPrompt\s*[:=]|system_prompt\s*=)[^;\n]{0,120}(?:toolResult|tool_result|functionResult|toolOutput|result\.content|output\.content)/i,
569
+ skipComments: true,
570
+ message:
571
+ 'Tool output is inserted into the system prompt. Tool results are attacker-influenced (a web page, an email, a file) — this is the indirect prompt-injection path that turns a read-only tool into an instruction channel.',
572
+ fix: 'Keep tool results in the tool role, label them as untrusted data, and require an explicit policy check before the model can act on them.',
573
+ cwe: 'CWE-1427', owasp: 'LLM01 Prompt Injection',
574
+ }),
575
+ makeLineRule({
576
+ id: 'llm2026.llm-call-no-max-tokens',
577
+ severity: 'medium',
578
+ confidence: 'medium',
579
+ title: 'LLM call with no max_tokens / budget (cost blowup)',
580
+ re: /(?:messages\.create|chat\.completions\.create|generateText|generateContent|completions\.create|responses\.create)\s*\(/,
581
+ filter(line, hit, lines) { const idx = idxOf(lines, line);
582
+ if (!lines) return false;
583
+
584
+ const ctx = lines.slice(idx, Math.min(lines.length, idx + 15)).join('\n');
585
+ if (/(?:max_tokens|maxTokens|maxOutputTokens|max_completion_tokens|max_output_tokens|budget)/.test(ctx)) return false;
586
+ // Streaming calls need the cap too; a call with no cap is the signal.
587
+ return true;
588
+ },
589
+ skipComments: true,
590
+ message:
591
+ 'A paid model call has no output cap and no timeout. One user prompt (or an injected loop) can run up an unbounded bill (OWASP LLM10).',
592
+ fix: 'Always pass max_tokens/maxOutputTokens, a timeout/AbortController, and a per-user rate limit on the route.',
593
+ cwe: 'CWE-770', owasp: 'LLM10 Unbounded Consumption',
594
+ }),
595
+ makeLineRule({
596
+ id: 'llm2026.agent-loop-no-cap',
597
+ severity: 'medium',
598
+ confidence: 'medium',
599
+ title: 'Agent loop with no iteration/cost cap',
600
+ re: /while\s*\(\s*(?:true|1|!?\s*(?:done|finished|complete))\s*\)|for\s*\(\s*;\s*;\s*\)/,
601
+ filter(line, hit, lines) { const idx = idxOf(lines, line);
602
+ if (!lines) return false;
603
+
604
+ const ctx = lines.slice(idx, Math.min(lines.length, idx + 40)).join('\n');
605
+ const agent = /(?:tool_calls|toolCalls|tools\s*:|generateText|chat\.completions|messages\.create|agent\.run|callModel|llm\()/i.test(ctx);
606
+ const capped = /(?:maxIterations|max_steps|maxSteps|maxTurns|step\s*<\s*\d|COST_LIMIT|tokenBudget|break\b)/i.test(ctx);
607
+ return agent && !capped;
608
+ },
609
+ skipComments: true,
610
+ message:
611
+ 'An agent loop calls a model/tool until `done`, with no step, token or cost ceiling. A tool that returns a "not finished" response spins forever — unbounded spend and a stuck worker (OWASP LLM06/LLM10).',
612
+ fix: 'Add maxIterations (e.g. 8), a token budget, a wall-clock timeout, and a hard stop that surfaces to the user.',
613
+ cwe: 'CWE-834', owasp: 'LLM06 Excessive Agency',
614
+ }),
615
+ makeLineRule({
616
+ id: 'llm2026.tool-schema-raw-command',
617
+ severity: 'high',
618
+ confidence: 'medium',
619
+ title: 'Tool schema accepts a raw command/shell string',
620
+ re: /(?:command|shell|cmd|script|exec)\s*:\s*\{\s*type\s*:\s*['"]string['"]/i,
621
+ filter(line, hit, lines) { const idx = idxOf(lines, line);
622
+ if (!lines) return false;
623
+
624
+ const ctx = lines.slice(Math.max(0, idx - 8), Math.min(lines.length, idx + 20)).join('\n');
625
+ return /(?:description|name)\s*:/.test(ctx); // it is a tool schema, not a config
626
+ },
627
+ skipComments: true,
628
+ message:
629
+ 'A tool exposes a free-form command/shell string to the model. The model is a confused deputy: injected text (a file, a web page) can dictate that command (OWASP Agentic ASI02/ASI05).',
630
+ fix: 'Expose typed, enumerated actions (e.g. { op: "list" | "read", path }) instead of a shell string; sandbox the executor and require confirmation for destructive ops.',
631
+ cwe: 'CWE-78', owasp: 'LLM06 Excessive Agency',
632
+ }),
633
+ makeLineRule({
634
+ id: 'llm2026.memory-write-from-untrusted',
635
+ severity: 'medium',
636
+ confidence: 'medium',
637
+ title: 'Unscreened tool/web output written to agent memory',
638
+ re: /(?:memory|memories|vectorstore|vectorStore|index)\.(?:save|addDocuments|upsert|insert|add)\s*\(/i,
639
+ filter(line) {
640
+ return /(?:toolResult|tool_result|webpage|scrape|html|response\.text|content|toolOutput)/i.test(line);
641
+ },
642
+ skipComments: true,
643
+ message:
644
+ 'Raw tool/web content is persisted to long-term memory. Poisoned content survives the session and steers every later answer (memory poisoning, OWASP Agentic ASI06).',
645
+ fix: 'Sanitize and label provenance before persisting; keep agent-written memory out of the trusted instruction channel; expire it.',
646
+ cwe: 'CWE-349', owasp: 'LLM04 Data and Model Poisoning',
647
+ }),
648
+ makeLineRule({
649
+ id: 'llm2026.permission-bypass',
650
+ severity: 'high',
651
+ confidence: 'high',
652
+ title: 'Agent permission/sandbox bypass enabled',
653
+ re: /(?:dangerously[-_ ]?skip[-_ ]?permissions|--dangerously-skip-permissions|bypassPermissions|autoApproveAll|allowAllTools|dangerouslyAllowAll|skipPermissions\s*:\s*true)/i,
654
+ skipComments: false,
655
+ message:
656
+ 'An agent is configured to skip human approval or sandbox controls. Every prompt injection now executes without a human gate (OWASP Agentic ASI10).',
657
+ fix: 'Remove the bypass in shared code/config; scope tools and require confirmation for write/deploy/delete actions.',
658
+ cwe: 'CWE-250', owasp: 'LLM06 Excessive Agency',
659
+ }),
660
+ makeLineRule({
661
+ id: 'llm2026.rag-no-tenant-filter',
662
+ severity: 'medium',
663
+ confidence: 'medium',
664
+ title: 'Vector search without a tenant/user filter',
665
+ re: /(?:similaritySearch|similarity_search|asRetriever|vectorSearch|retrieve)\s*\(/i,
666
+ filter(line) {
667
+ return !/(?:filter|where|namespace|userId|user_id|tenant|orgId|metadata)/i.test(line);
668
+ },
669
+ skipComments: true,
670
+ message:
671
+ 'Retrieval runs against the whole index with no tenant predicate. One customer\'s documents (and system prompt fragments) surface in another customer\'s answer (OWASP LLM08).',
672
+ fix: 'Pass a metadata filter with the caller\'s tenant id and use per-tenant namespaces where the vector store supports them.',
673
+ cwe: 'CWE-284', owasp: 'LLM08 Vector and Embedding Weaknesses',
674
+ }),
675
+ ];
676
+
677
+ // ---------------------------------------------------------------------------
678
+ // 5. Crypto (CWE-327 — AI code's worst class after log injection)
679
+ // ---------------------------------------------------------------------------
680
+
681
+ const crypto2026 = [
682
+ makeLineRule({
683
+ id: 'crypto2026.weak-hash-for-password',
684
+ severity: 'high',
685
+ confidence: 'high',
686
+ title: 'MD5/SHA-1 used for passwords',
687
+ re: /createHash\s*\(\s*['"](?:md5|sha1)['"]|hashlib\.(?:md5|sha1)\s*\(|MessageDigest\.getInstance\(\s*['"](?:MD5|SHA-?1)['"]/i,
688
+ filter(line) {
689
+ return /(?:password|passwd|pwd|secret|token)/i.test(line);
690
+ },
691
+ skipComments: true,
692
+ message:
693
+ 'A fast, broken hash is used for password material. GPU cracking recovers passwords at billions/sec; nobody should ship md5/sha1 for credentials.',
694
+ fix: 'Use bcrypt/argon2/scrypt (cost 10-12 for bcrypt) or the framework auth provider — never createHash for passwords.',
695
+ cwe: 'CWE-327', owasp: 'A02:2025 Cryptographic Failures',
696
+ }),
697
+ makeLineRule({
698
+ id: 'crypto2026.math-random-token',
699
+ severity: 'high',
700
+ confidence: 'high',
701
+ title: 'Math.random()/random.random() for a token or OTP',
702
+ re: /(?:Math\.random\(\)|random\.random\(\)|new\s+Random\(\))/i,
703
+ filter(line) {
704
+ // Security-relevant name either side of the PRNG call: `otp = Math.random…`
705
+ // or `Math.random(…).toString(36)` assigned to `token`. Requiring both the
706
+ // PRNG and a security word on the same line keeps paint jitter out.
707
+ const securityWord = /\b(?:token|otp|one[- ]?time|code|password|secret|nonce|session|reset|api[_-]?key|salt|csrf|verification)\b/i;
708
+ if (!securityWord.test(line)) return false;
709
+ if (/(?:uuid|test|mock|seed|jitter|retry|delay|animation|styling|color|theme)/i.test(line)) return false;
710
+ return true;
711
+ },
712
+ skipComments: true,
713
+ message:
714
+ 'A predictor is used to generate a security token/OTP. Math.random() is seedable and observed output predicts the next value.',
715
+ fix: 'Use crypto.randomBytes(32) / crypto.randomUUID() (or secrets.token_urlsafe in Python) for anything security-relevant.',
716
+ cwe: 'CWE-338', owasp: 'A02:2025 Cryptographic Failures',
717
+ }),
718
+ makeLineRule({
719
+ id: 'crypto2026.ecb-mode',
720
+ severity: 'high',
721
+ confidence: 'high',
722
+ title: 'AES-ECB mode',
723
+ re: /aes-\d+-ecb|createCipheriv\s*\(\s*['"]aes-[^'"]*-ecb/i,
724
+ skipComments: true,
725
+ message:
726
+ 'ECB encrypts identical plaintext blocks identically — patterns survive encryption (and it is unauthenticated).',
727
+ fix: 'Use aes-256-gcm (or chacha20-poly1305) with a random 12-byte IV and authenticate the tag.',
728
+ cwe: 'CWE-327', owasp: 'A02:2025 Cryptographic Failures',
729
+ }),
730
+ makeLineRule({
731
+ id: 'crypto2026.static-iv',
732
+ severity: 'high',
733
+ confidence: 'medium',
734
+ title: 'Static IV/nonce in encryption',
735
+ re: /createCipheriv\s*\([^;]{0,200}(?:iv|nonce)\s*[:=]\s*(?:Buffer\.from\(\s*['"][^'"]+['"]|['"][A-Za-z0-9+/=]{8,}['"]|Buffer\.alloc\s*\(\s*\d+\s*\))/i,
736
+ skipComments: true,
737
+ message:
738
+ 'A hardcoded/zero IV is reused for every message. Reuse breaks confidentiality (identifiable ciphertexts, keystream reuse) even with a strong cipher.',
739
+ fix: 'Generate a fresh random IV per encryption (crypto.randomBytes(12) for GCM) and store it next to the ciphertext.',
740
+ cwe: 'CWE-329', owasp: 'A02:2025 Cryptographic Failures',
741
+ }),
742
+ makeLineRule({
743
+ id: 'crypto2026.timing-unsafe-compare',
744
+ severity: 'medium',
745
+ confidence: 'medium',
746
+ title: 'Secret compared with === / == (timing leak)',
747
+ re: /(?:password|api[_-]?key|token|secret|signature|hmac)\w*\s*(?:===?|!==?)\s*(?:req\.|request\.|body\.|query\.|headers|params\.|['"])/i,
748
+ skipComments: true,
749
+ message:
750
+ 'A secret is compared with a normal equality operator, which short-circuits on the first differing byte — a timing oracle for tokens/API keys.',
751
+ fix: 'Use crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b)) with equal lengths (or hmac.compare_digest in Python).',
752
+ cwe: 'CWE-208', owasp: 'A02:2025 Cryptographic Failures',
753
+ }),
754
+ makeLineRule({
755
+ id: 'crypto2026.jwt-alg-verify-disabled',
756
+ severity: 'high',
757
+ confidence: 'high',
758
+ title: 'Signature verification disabled',
759
+ re: /verify\s*:\s*false|verify_signature\s*:\s*false|jwt\.verify\([^)]*\{\s*algorithms\s*:\s*\[\s*\]/i,
760
+ skipComments: true,
761
+ message:
762
+ 'Signature/verification is explicitly disabled. The token or webhook is accepted from anyone.',
763
+ fix: 'Enable verification with a pinned algorithm and key, and verify webhook signatures with the provider\'s SDK.',
764
+ cwe: 'CWE-347', owasp: 'A07:2025 Authentication Failures',
765
+ }),
766
+ ];
767
+
768
+ // ---------------------------------------------------------------------------
769
+ // 6. Log injection / PII in logs (CWE-117 — 88% failure in Veracode)
770
+ // ---------------------------------------------------------------------------
771
+
772
+ const leak2026 = [
773
+ makeLineRule({
774
+ id: 'leak2026.log-injection-request-interpolation',
775
+ severity: 'medium',
776
+ confidence: 'medium',
777
+ title: 'Request data interpolated into a log line (log injection)',
778
+ re: /\b(?:console\.(?:log|info|warn|error|debug)|logger\.(?:info|warn|error|debug)|log\.(?:info|warn|error)|print\s*\(|logging\.(?:info|warning|error|debug)\s*\()/i,
779
+ filter(line) {
780
+ // Two signals: a log/print call and a request-derived value on the line.
781
+ const requestData = /\b(?:req\.(?:body|query|params|headers|cookies)|request\.(?:body|query|params|form|json|headers)|ctx\.(?:body|query|params)|searchParams\.get\(|params\.|\bbody\.)/i;
782
+ if (!requestData.test(line)) return false;
783
+ if (/(?:sanitize|escape|redact|\[REDACTED\]|JSON\.stringify\([^)]*req)/i.test(line)) return false;
784
+ return true;
785
+ },
786
+ skipComments: true,
787
+ message:
788
+ 'Raw request data is interpolated into a log message. Newlines let an attacker forge log entries, and the value usually carries secrets/PII (CWE-117, the most-failed class in the 2025 Veracode GenAI report).',
789
+ fix: 'Log structured fields (logger.info({ userId, route }, "msg")) with an encoder, or JSON.stringify the values; never concatenate raw input.',
790
+ cwe: 'CWE-117', owasp: 'A09:2025 Security Logging and Alerting Failures',
791
+ }),
792
+ makeLineRule({
793
+ id: 'leak2026.logs-auth-header',
794
+ severity: 'high',
795
+ confidence: 'high',
796
+ title: 'Authorization header / token logged',
797
+ re: /(?:console\.(?:log|info|warn|error)|logger\.\w+|log\.\w+|print\s*\(|logging\.\w+\s*\()\s*\([^;\n]{0,120}(?:authorization|bearer|api[_-]?key|access[_-]?token|refresh[_-]?token|req\.headers|request\.headers)/i,
798
+ skipComments: true,
799
+ message:
800
+ 'A credential is written to logs. Logs are copied to observability vendors, bug reports and AI agents — one line can leak a live token (GitGuardian 2026: AI-assisted commits leak at 3.2% vs 1.5%).',
801
+ fix: 'Never log headers/tokens. Log an identifier (userId, requestId) and redact the rest; add a log scrubber at the transport.',
802
+ cwe: 'CWE-532', owasp: 'A09:2025 Security Logging and Alerting Failures',
803
+ }),
804
+ makeLineRule({
805
+ id: 'leak2026.error-stack-to-client',
806
+ severity: 'high',
807
+ confidence: 'high',
808
+ title: 'Stack trace / error internals returned to the client',
809
+ re: /(?:res|response|reply)\.(?:json|send|status\([^)]*\)\.json)\s*\(\s*\{[^}]{0,200}(?:e\.stack|err\.stack|error\.stack|\.stack\b|e\.message\s*,\s*e\.stack)/i,
810
+ skipComments: true,
811
+ message:
812
+ 'A raw error with stack/message goes to the client. It exposes file paths, SQL and internal library versions — the reconnaissance step of most exploits.',
813
+ fix: 'Return a generic message plus an error id; log the detail server-side.',
814
+ cwe: 'CWE-209', owasp: 'A02:2025 Security Misconfiguration',
815
+ }),
816
+ makeLineRule({
817
+ id: 'leak2026.debug-endpoint',
818
+ severity: 'high',
819
+ confidence: 'high',
820
+ title: 'Debug/admin endpoint exposed in app code',
821
+ re: /(?:app|router|server)\.(?:get|post|all)\s*\(\s*['"]\/(?:debug|__debug|dev|__dev|admin\/debug|_test)[^'"]*['"]/i,
822
+ skipComments: true,
823
+ message:
824
+ 'A debug/dev endpoint is registered unconditionally. These return env, DB state or arbitrary query results in production.',
825
+ fix: 'Register it only under a NODE_ENV check and an admin guard, or move it out of the deployed app.',
826
+ cwe: 'CWE-489', owasp: 'A05:2025 Security Misconfiguration',
827
+ }),
828
+ ];
829
+
830
+ // ---------------------------------------------------------------------------
831
+ // 7. Secrets: formats generators leak that regex packs miss
832
+ // ---------------------------------------------------------------------------
833
+
834
+ // Narrow, well-prefixed, high-entropy providers. Kept here (not in rules-pack)
835
+ // because they postdate most rule sets: DeepSeek/OpenRouter/Groq/HF/pscale etc.
836
+ const secretRe = (prefix, minLen, label, fix) => ({
837
+ id: `secret2026.${label}`,
838
+ severity: 'critical',
839
+ confidence: 'high',
840
+ title: `${label.replace(/-/g, ' ')} leaked`,
841
+ re: new RegExp(`['"\`](${prefix}[A-Za-z0-9_-]{${minLen},})['"\`]`),
842
+ skipComments: false,
843
+ message: `A ${label.replace(/-/g, ' ')} is hardcoded in tracked code. Secret scanning in CI cannot stop the push that already happened — rotate and move it to an env var.`,
844
+ fix: `${fix || 'Rotate the key now, remove it from the file, move it to .env (gitignored) and use the AI tool credentials store for local runs.'}`,
845
+ cwe: 'CWE-798', owasp: 'A02:2025 Security Misconfiguration',
846
+ });
847
+
848
+ const secret2026 = [
849
+ secretRe('sk-or-v1-', 32, 'openrouter-key'),
850
+ secretRe('gsk_', 32, 'groq-key'),
851
+ secretRe('hf_', 24, 'huggingface-token'),
852
+ secretRe('nvapi-', 20, 'nvidia-api-key'),
853
+ secretRe('r8_', 20, 'replicate-token'),
854
+ secretRe('pscale_tkn_', 16, 'planetscale-token'),
855
+ secretRe('vercel_', 20, 'vercel-token'),
856
+ secretRe('shpat_', 24, 'shopify-admin-token'),
857
+ secretRe('sbp_', 20, 'supabase-access-token'),
858
+ secretRe('github_pat_', 20, 'github-fine-grained-pat'),
859
+ secretRe('rzp_live_', 12, 'razorpay-live-key'),
860
+ secretRe('dop_v1_', 24, 'digitalocean-token'),
861
+ {
862
+ id: 'secret2026.supabase-service-role-jwt',
863
+ severity: 'critical',
864
+ confidence: 'high',
865
+ title: 'Supabase service_role JWT',
866
+ re: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/,
867
+ filter(line, hit) {
868
+ const tok = (hit && hit.match) || '';
869
+ const parts = tok.split('.');
870
+ if (parts.length !== 3) return false;
871
+ try {
872
+ const payload = Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');
873
+ return /"role"\s*:\s*"service_role"/.test(payload);
874
+ } catch {
875
+ return false;
876
+ }
877
+ },
878
+ skipComments: false,
879
+ message:
880
+ 'A Supabase JWT with role=service_role is in the source. It bypasses every RLS policy — the anon key is public by design, this key is not.',
881
+ fix: 'Rotate the JWT secret (this invalidates the key), keep service_role only in server env vars, and access it through a server-only client.',
882
+ cwe: 'CWE-798', owasp: 'A02:2025 Security Misconfiguration',
883
+ },
884
+ {
885
+ id: 'secret2026.private-key-block',
886
+ severity: 'critical',
887
+ confidence: 'high',
888
+ title: 'Private key committed',
889
+ re: /-----BEGIN (?:RSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/,
890
+ filter(line, hit, lines) { const idx = idxOf(lines, line);
891
+ // Fixtures/tests are common; keep them but at lower noise if obviously fake.
892
+ const ctx = lines ? lines.slice(idx, (idx) + 4).join('\n') : line;
893
+ return !/(?:BEGIN PRIVATE KEY-----\\n'|test|fixture|dummy|example|placeholder)/i.test(ctx);
894
+ },
895
+ skipComments: false,
896
+ message:
897
+ 'A private key is committed. Anything signed or encrypted with it is compromised until rotated — historical copies survive in forks and caches.',
898
+ fix: 'Revoke/rotate the key pair, remove it from the working tree and git history (git filter-repo), and load keys from a secret manager.',
899
+ cwe: 'CWE-798', owasp: 'A02:2025 Security Misconfiguration',
900
+ },
901
+ ];
902
+
903
+ // ---------------------------------------------------------------------------
904
+ // 8. Supply chain / CI / containers / IaC
905
+ // ---------------------------------------------------------------------------
906
+
907
+ const supply2026 = [
908
+ {
909
+ id: 'supply2026.postinstall-network-shell',
910
+ severity: 'critical',
911
+ confidence: 'high',
912
+ title: 'Install script downloads and executes code',
913
+ run(content, lines, relPath) {
914
+ if (!/package\.json$/.test(relPath || '')) return [];
915
+ let pkg;
916
+ try { pkg = JSON.parse(content); } catch { return []; }
917
+ const scripts = pkg.scripts || {};
918
+ const risky = ['preinstall', 'install', 'postinstall', 'prepare', 'prepublish'];
919
+ const out = [];
920
+ const re = /(?:curl|wget|Invoke-WebRequest|iwr|iex|powershell|bash\s+-c|sh\s+-c|node\s+-e|base64\s+(?:-d|--decode)|eval\b|child_process|process\.env)/i;
921
+ for (const name of risky) {
922
+ const cmd = scripts[name];
923
+ if (typeof cmd !== 'string' || !re.test(cmd)) continue;
924
+ const idx = content.indexOf(cmd);
925
+ out.push({
926
+ line: idx >= 0 ? content.slice(0, idx).split('\n').length : 1,
927
+ column: 1,
928
+ snippet: `${name}: ${cmd.slice(0, 100)}`,
929
+ message: `The "${name}" script downloads/executes code or touches the environment at install time. This is how npm supply-chain malware (postinstall RCE) runs on every deploy, and it is invisible to a code review of dependencies.`,
930
+ fix: 'Remove network/shell work from install scripts. If a build step is required, make it explicit (npm run build) and pin it in CI after review.',
931
+ });
932
+ }
933
+ return out;
934
+ },
935
+ },
936
+ makeLineRule({
937
+ id: 'supply2026.unpinned-npx-install',
938
+ severity: 'medium',
939
+ confidence: 'medium',
940
+ title: 'Unpinned npx/uvx auto-install (MCP/server bootstrap)',
941
+ re: /\b(?:npx|uvx|bunx)\s+(?:-y|--yes)\s+(?:@?[\w./-]+)(?:\s|['"`]|$)/,
942
+ filter(line) {
943
+ // A pinned version (pkg@1.2.3) is the safe form.
944
+ const m = /(?:npx|uvx|bunx)\s+(?:-y|--yes)\s+([@\w./-]+)/.exec(line);
945
+ if (!m) return false;
946
+ const spec = m[1];
947
+ if (/vibeguard/i.test(spec)) return false; // documented self-invocation
948
+ return !/@\d+\.\d+/.test(spec);
949
+ },
950
+ skipComments: true,
951
+ message:
952
+ 'An unpinned package is fetched and run at startup. The registry version can change (or be hijacked) after review — a rug pull, not a reproducible bootstrap.',
953
+ fix: 'Pin the exact version (npx -y package@1.4.2) and record it in the config; update deliberately.',
954
+ cwe: 'CWE-829', owasp: 'A06:2025 Vulnerable and Outdated Components',
955
+ }),
956
+ {
957
+ id: 'supply2026.dependency-confusion-scoped-private',
958
+ severity: 'medium',
959
+ confidence: 'low',
960
+ title: 'Scoped dependency could be claimed on public npm',
961
+ run(content, lines, relPath) {
962
+ if (!/package\.json$/.test(relPath || '')) return [];
963
+ let pkg;
964
+ try { pkg = JSON.parse(content); } catch { return []; }
965
+ const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
966
+ const names = Object.keys(deps);
967
+ // Only scopes that no registry config pins to a private feed.
968
+ const npmrc = (() => {
969
+ // A sibling .npmrc is not visible here; treat as unknown.
970
+ return '';
971
+ })();
972
+ const out = [];
973
+ for (const name of names) {
974
+ const m = /^@([\w.-]+)\/([\w.-]+)$/.exec(name);
975
+ if (!m) continue;
976
+ const scope = m[1];
977
+ // The project's own package name scope is internal by definition (it is
978
+ // published); everything else scoped is a private-name candidate.
979
+ const own = pkg.name && pkg.name.startsWith(`@${scope}/`);
980
+ if (own) continue;
981
+ const idx = content.indexOf(`"${name}"`);
982
+ out.push({
983
+ line: idx >= 0 ? content.slice(0, idx).split('\n').length : 1,
984
+ column: 1,
985
+ snippet: name,
986
+ message: `Dependency ${name} is a scoped private name with no registry pin visible here. If the scope is unclaimed on public npm, an attacker can publish it and npm may prefer the public version (dependency confusion).`,
987
+ fix: `Pin scopes to the private registry in .npmrc (@${scope}:registry=https://your-registry/) and use --ignore-scripts in CI installs.`,
988
+ });
989
+ }
990
+ return out.slice(0, 20);
991
+ },
992
+ },
993
+ {
994
+ id: 'supply2026.lockfile-no-integrity',
995
+ severity: 'medium',
996
+ confidence: 'medium',
997
+ title: 'Lockfile has no integrity hashes',
998
+ run(content, lines, relPath) {
999
+ if (!/(?:package-lock\.json|npm-shrinkwrap\.json)$/.test(relPath || '')) return [];
1000
+ // v1 lockfiles can legitimately lack integrity in old projects; a v2/v3
1001
+ // lockfile without any integrity means tampering/proxy stripping.
1002
+ const version = (/"lockfileVersion"\s*:\s*(\d)/.exec(content) || [])[1];
1003
+ if (!version || Number(version) < 2) return [];
1004
+ const hasIntegrity = /"integrity"\s*:/.test(content);
1005
+ if (hasIntegrity) return [];
1006
+ return [{ line: 1, column: 1, snippet: `lockfileVersion ${version}, 0 integrity fields` }];
1007
+ },
1008
+ message:
1009
+ 'A modern npm lockfile has zero `integrity` fields. Installs cannot verify tarball contents, so a registry/proxy compromise or a mutated package goes unnoticed.',
1010
+ fix: 'Regenerate the lockfile with npm install (it writes integrity normally), commit it, and pin the registry over HTTPS.',
1011
+ cwe: 'CWE-829',
1012
+ },
1013
+ makeLineRule({
1014
+ id: 'supply2026.npmrc-http-registry',
1015
+ severity: 'high',
1016
+ confidence: 'high',
1017
+ title: '.npmrc uses an insecure/overridden registry',
1018
+ re: /^\s*(?:registry|@[\w-]+:registry)\s*=\s*http:/i,
1019
+ fileFilter: /(?:\.npmrc|\.yarnrc(?:\.yml)?)$/i,
1020
+ message:
1021
+ 'Packages are fetched over plain HTTP. A network attacker can replace any tarball with malware (install scripts run on deploy).',
1022
+ fix: 'Use https:// (or a pinned internal registry over TLS); set strict-ssl=true and never commit auth tokens.',
1023
+ cwe: 'CWE-319', owasp: 'A06:2025 Vulnerable and Outdated Components',
1024
+ }),
1025
+ makeLineRule({
1026
+ id: 'supply2026.npmrc-auth-token-committed',
1027
+ severity: 'critical',
1028
+ confidence: 'high',
1029
+ title: 'npm auth token committed in .npmrc',
1030
+ re: /(?:_authToken|_auth|_password)\s*=\s*[A-Za-z0-9+/=_-]{8,}/i,
1031
+ fileFilter: /(?:\.npmrc|\.yarnrc(?:\.yml)?)$/i,
1032
+ message:
1033
+ 'A registry auth token is committed. Anyone with the repo (including every AI agent that reads it) can publish/read under your account.',
1034
+ fix: 'Remove it, rotate the token, and use ${NPM_TOKEN} expansion in .npmrc with the token only in CI secrets.',
1035
+ cwe: 'CWE-798', owasp: 'A06:2025 Vulnerable and Outdated Components',
1036
+ }),
1037
+ makeLineRule({
1038
+ id: 'supply2026.ci-unpinned-action',
1039
+ severity: 'medium',
1040
+ confidence: 'medium',
1041
+ title: 'Third-party GitHub Action pinned to a branch/tag',
1042
+ re: /uses\s*:\s*([\w.-]+\/[\w.-]+)@(?:main|master|latest|HEAD)\b/i,
1043
+ fileFilter: /\.github\/workflows\/.*\.ya?ml$/i,
1044
+ message:
1045
+ 'An action is pinned to a mutable ref. If the action repo is compromised or its maintainer retags, the next workflow run executes attacker code with your repository secrets.',
1046
+ fix: 'Pin third-party actions to a full commit SHA (with the version in a comment) and enable Dependabot for actions.',
1047
+ cwe: 'CWE-829', owasp: 'A06:2025 Vulnerable and Outdated Components',
1048
+ }),
1049
+ makeLineRule({
1050
+ id: 'supply2026.ci-user-input-in-run',
1051
+ severity: 'critical',
1052
+ confidence: 'high',
1053
+ title: 'Pull request text interpolated into a shell step (script injection)',
1054
+ re: /\$\{\{\s*github\.event\.(?:pull_request|issue|discussion)\.(?:title|body|head\.ref|head\.label|message|comment\.body)/i,
1055
+ fileFilter: /\.github\/workflows\/.*\.ya?ml$/i,
1056
+ skipComments: false,
1057
+ message:
1058
+ 'A PR title/body/branch name is interpolated into a workflow `run:` step. The shell executes the attacker\'s text with your token — arbitrary code in CI (script injection).',
1059
+ fix: 'Pass untrusted values through env: and reference "$GITHUB_EVENT_PATH" / "${{ env.TITLE }}"; never inline them into the script.',
1060
+ cwe: 'CWE-78', owasp: 'A03:2025 Injection',
1061
+ }),
1062
+ ];
1063
+
1064
+ const container2026 = [
1065
+ makeLineRule({
1066
+ id: 'container2026.docker-secret-in-env-or-arg',
1067
+ severity: 'high',
1068
+ confidence: 'medium',
1069
+ title: 'Secret baked into image via ENV/ARG',
1070
+ re: /^\s*(?:ENV|ARG)\s+[A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|PRIVATE_KEY|API_KEY|CREDENTIAL)[A-Z0-9_]*\s*[=\s]+\S+/i,
1071
+ fileFilter: /(?:Dockerfile|\.dockerfile)$/i,
1072
+ filter(line) {
1073
+ return !/\$\{/ .test(line); // ARG with a runtime-provided value is not baked
1074
+ },
1075
+ message:
1076
+ 'A secret is written into an image layer. Anyone who pulls the image (or the registry cache) reads it, and `docker history` shows it.',
1077
+ fix: 'Use build secrets (BuildKit --mount=type=secret) or runtime env injection; never ENV/ARG a credential.',
1078
+ cwe: 'CWE-798', owasp: 'A02:2025 Security Misconfiguration',
1079
+ }),
1080
+ makeLineRule({
1081
+ id: 'container2026.docker-published-db-port',
1082
+ severity: 'medium',
1083
+ confidence: 'high',
1084
+ title: 'Database port published to the host',
1085
+ re: /^\s*-\s*["']?(?:5432|3306|6379|27017|5433|1433|9200):/m,
1086
+ fileFilter: /(?:docker-compose|compose)\.ya?ml$/i,
1087
+ skipComments: true,
1088
+ message:
1089
+ 'A database port is mapped to the host without a bind address. Any process (or network, on a cloud VM without a firewall) reaches the DB; the generated password is often "postgres".',
1090
+ fix: 'Remove the ports mapping (services talk over the compose network) or bind to 127.0.0.1: "127.0.0.1:5432:5432".',
1091
+ cwe: 'CWE-284', owasp: 'A05:2025 Security Misconfiguration',
1092
+ }),
1093
+ makeLineRule({
1094
+ id: 'container2026.container-runs-as-root',
1095
+ severity: 'medium',
1096
+ confidence: 'low',
1097
+ title: 'Container has no non-root USER',
1098
+ re: /^\s*FROM\s+\S+/i,
1099
+ fileFilter: /(?:Dockerfile|\.dockerfile)$/i,
1100
+ filter(line, hit, lines) {
1101
+ if (!lines) return false;
1102
+ return !lines.some((l) => /^\s*USER\s+(?!root\b)\S+/i.test(l));
1103
+ },
1104
+ message:
1105
+ 'The image never switches to a non-root user. A container escape or app RCE starts with root inside the container and escalates host mounts.',
1106
+ fix: 'Create a non-root user in the Dockerfile (RUN adduser --system app) and add USER app before the entrypoint.',
1107
+ cwe: 'CWE-250',
1108
+ }),
1109
+ makeLineRule({
1110
+ id: 'container2026.compose-privileged',
1111
+ severity: 'high',
1112
+ confidence: 'high',
1113
+ title: 'Compose service runs privileged / mounts docker.sock',
1114
+ re: /privileged\s*:\s*true|\/var\/run\/docker\.sock/i,
1115
+ fileFilter: /(?:docker-compose|compose)\.ya?ml$/i,
1116
+ skipComments: true,
1117
+ message:
1118
+ 'A service is privileged or holds the Docker socket. That is root on the host — any RCE in the app owns the machine.',
1119
+ fix: 'Drop privileged; replace docker.sock access with a scoped API proxy; mount only the directories needed.',
1120
+ cwe: 'CWE-250', owasp: 'A05:2025 Security Misconfiguration',
1121
+ }),
1122
+ ];
1123
+
1124
+ // Terraform: the open-cidr rule needs a few lines of context (port + cidr blocks).
1125
+ const cloud2026 = [
1126
+ {
1127
+ id: 'cloud2026.terraform-open-admin-ports',
1128
+ severity: 'high',
1129
+ confidence: 'medium',
1130
+ title: 'Terraform security group open to the world on an admin port',
1131
+ run(content, lines, relPath) {
1132
+ if (!/\.(tf|hcl)$/.test(relPath || '')) return [];
1133
+ const out = [];
1134
+ const cidrRe = /0\.0\.0\.0\/0/g;
1135
+ let m;
1136
+ while ((m = cidrRe.exec(content)) !== null) {
1137
+ const idx = content.slice(0, m.index).split('\n').length - 1;
1138
+ const ctx = lines.slice(Math.max(0, idx - 6), idx + 4).join('\n');
1139
+ const adminPort = /\b(?:22|3389|5432|3306|6379|27017|9200|2375|2376)\b/.test(ctx);
1140
+ const httpPort = /\b(?:80|443)\b/.test(ctx);
1141
+ if (!adminPort || httpPort) continue;
1142
+ out.push({
1143
+ line: idx + 1,
1144
+ column: 1,
1145
+ snippet: '0.0.0.0/0 on an administrative port',
1146
+ message:
1147
+ 'A security group admits 0.0.0.0/0 on an administrative port (SSH/DB/Redis/K8s API). AI-generated Terraform copies the quickstart allow-all and ships a database to the internet.',
1148
+ fix: 'Restrict to a bastion/VPN CIDR (var.admin_cidr), or remove the public ingress and use SSM/session-manager.',
1149
+ });
1150
+ if (out.length >= 5) break;
1151
+ }
1152
+ return out;
1153
+ },
1154
+ },
1155
+ makeLineRule({
1156
+ id: 'cloud2026.terraform-public-bucket',
1157
+ severity: 'high',
1158
+ confidence: 'medium',
1159
+ title: 'Terraform S3 bucket publicly readable',
1160
+ re: /acl\s*=\s*["']public-read(?:-write)?["']|block_public_acls\s*=\s*false/i,
1161
+ fileFilter: /\.tf$/i,
1162
+ skipComments: true,
1163
+ message:
1164
+ 'The bucket is public. Every object (uploads, backups, user files) is world-readable, and public-write buckets are used to host malware.',
1165
+ fix: 'Keep ACLs private (block_public_acls = true, ignore_public_acls = false) and serve files through signed URLs or CloudFront.',
1166
+ cwe: 'CWE-284', owasp: 'A05:2025 Security Misconfiguration',
1167
+ }),
1168
+ makeLineRule({
1169
+ id: 'cloud2026.aws-wildcard-iam',
1170
+ severity: 'high',
1171
+ confidence: 'medium',
1172
+ title: 'IAM policy with wildcard Action and Resource',
1173
+ re: /Action\s*[:=]\s*["']\*["'][\s\S]{0,120}?Resource\s*[:=]\s*["']\*["']|Resource\s*[:=]\s*["']\*["'][\s\S]{0,120}?Action\s*[:=]\s*["']\*["']/,
1174
+ fileFilter: /\.(tf|json|ya?ml)$/i,
1175
+ skipComments: true,
1176
+ message:
1177
+ 'An IAM policy grants * on *. Any RCE or leaked credential with this role owns the whole account (delete backups, exfiltrate everything).',
1178
+ fix: 'Scope actions and resources to what the service uses; add a condition (aws:SourceAccount / SourceArn) for cross-service access.',
1179
+ cwe: 'CWE-269', owasp: 'A01:2025 Broken Access Control',
1180
+ }),
1181
+ ];
1182
+
1183
+ // ---------------------------------------------------------------------------
1184
+ // 9. Web-app basics generators still miss
1185
+ // ---------------------------------------------------------------------------
1186
+
1187
+ const api2026 = [
1188
+ makeLineRule({
1189
+ id: 'api2026.cors-wildcard-credentials',
1190
+ severity: 'high',
1191
+ confidence: 'high',
1192
+ title: 'CORS allows every origin with credentials',
1193
+ re: /origin\s*:\s*(?:true|['"]\*['"]|\([^)]*\)\s*=>\s*[^,\n]*)\s*,\s*credentials\s*:\s*true|Access-Control-Allow-Origin['"]?\s*[,:]\s*['"]\*['"][\s\S]{0,80}Allow-Credentials['"]?\s*[,:]\s*['"]true/i,
1194
+ skipComments: true,
1195
+ message:
1196
+ 'Any website can send credentialed requests to this API and read the response. With session cookies, that is a full cross-site account takeover.',
1197
+ fix: 'Allowlist origins from config and never combine "*" (or reflected Origin) with credentials:true.',
1198
+ cwe: 'CWE-942', owasp: 'A05:2025 Security Misconfiguration',
1199
+ }),
1200
+ makeLineRule({
1201
+ id: 'api2026.graphql-introspection-prod',
1202
+ severity: 'low',
1203
+ confidence: 'medium',
1204
+ title: 'GraphQL introspection/playground enabled unconditionally',
1205
+ re: /introspection\s*:\s*true|playground\s*:\s*true/i,
1206
+ skipComments: true,
1207
+ message:
1208
+ 'Introspection/playground is enabled without an environment check, exposing the whole schema and mutation surface in production.',
1209
+ fix: 'Enable only when NODE_ENV !== "production", or gate behind admin auth.',
1210
+ cwe: 'CWE-200', owasp: 'A05:2025 Security Misconfiguration',
1211
+ }),
1212
+ makeLineRule({
1213
+ id: 'api2026.postmessage-no-origin',
1214
+ severity: 'medium',
1215
+ confidence: 'medium',
1216
+ title: 'message listener without origin check',
1217
+ re: /addEventListener\s*\(\s*['"]message['"]\s*,\s*(?:async\s*)?(?:\(|function)/,
1218
+ filter(line, hit, lines) { const idx = idxOf(lines, line);
1219
+ if (!lines) return false;
1220
+
1221
+ const ctx = lines.slice(idx, Math.min(lines.length, idx + 12)).join('\n');
1222
+ return !/(?:event|e|evt)\.origin|origin\s*!==|origin\s*===|allowedOrigin/i.test(ctx);
1223
+ },
1224
+ skipComments: true,
1225
+ message:
1226
+ 'A postMessage handler does not verify event.origin. Any embedded/open page can send it messages and drive privileged actions.',
1227
+ fix: 'Check e.origin against an allowlist at the top of the handler (and validate the payload shape).',
1228
+ cwe: 'CWE-346', owasp: 'A01:2025 Broken Access Control',
1229
+ }),
1230
+ makeLineRule({
1231
+ id: 'api2026.upload-unrestricted',
1232
+ severity: 'medium',
1233
+ confidence: 'medium',
1234
+ title: 'File upload without size/type limits',
1235
+ re: /multer\s*\(\s*\{|busboy\s*\(|formidable\s*\(|formData\s*\(\s*\)/,
1236
+ filter(line, hit, lines) { const idx = idxOf(lines, line);
1237
+ const ctx = lines ? lines.slice(idx, (idx) + 12).join('\n') : line;
1238
+ return !/(?:limits|fileSize|maxFileSize|mimetype|mimeType|allowedTypes|accept)/i.test(ctx);
1239
+ },
1240
+ skipComments: true,
1241
+ message:
1242
+ 'An upload handler has no size or MIME allowlist. Attackers upload multi-GB files (disk/cost DoS), .html/.svg (stored XSS) or polyglots.',
1243
+ fix: 'Set limits.fileSize, allowlist MIME + extension, store outside the web root with a random name, and serve with Content-Disposition/Content-Type set.',
1244
+ cwe: 'CWE-434', owasp: 'A04:2025 Insecure Design',
1245
+ }),
1246
+ makeLineRule({
1247
+ id: 'api2026.ssrf-metadata-url',
1248
+ severity: 'critical',
1249
+ confidence: 'high',
1250
+ title: 'Outbound fetch to a user-controllable URL (SSRF)',
1251
+ re: /(?:fetch|axios(?:\.get|\.post)?|got|requests\.(?:get|post)|http\.get)\s*\(\s*(?:req\.|request\.|ctx\.|body\.|params\.|searchParams|query\.)/i,
1252
+ skipComments: true,
1253
+ message:
1254
+ 'A URL taken from the request is fetched directly. The server\'s network position lets the caller hit 169.254.169.254 (cloud credentials), localhost admin ports and internal services.',
1255
+ fix: 'Parse with new URL(), allowlist schemes/hosts, block private/link-local ranges after DNS resolution, and disable redirects.',
1256
+ cwe: 'CWE-918', owasp: 'A01:2025 Broken Access Control',
1257
+ }),
1258
+ makeLineRule({
1259
+ id: 'api2026.raw-sql-unsafe',
1260
+ severity: 'critical',
1261
+ confidence: 'high',
1262
+ title: 'Unsafe raw SQL API (queryRawUnsafe / executeRawUnsafe / sql.raw)',
1263
+ re: /\$(?:query|execute)RawUnsafe\s*\(|\bsql\.raw\s*\(|\bknex\.raw\s*\(\s*[`'"].*\$\{/i,
1264
+ skipComments: true,
1265
+ message:
1266
+ 'An explicitly-unsafe raw API is used. These bypass parameterization by design — any interpolated value is SQL injection.',
1267
+ fix: 'Use the tagged-template form ($queryRaw`...${value}`) or parameterized calls; never build the string yourself.',
1268
+ cwe: 'CWE-89', owasp: 'A03:2025 Injection',
1269
+ }),
1270
+ makeLineRule({
1271
+ id: 'api2026.header-injection',
1272
+ severity: 'high',
1273
+ confidence: 'medium',
1274
+ title: 'Request data written into a response header',
1275
+ re: /(?:res|response|reply)\.(?:setHeader|header|set)\s*\(\s*[^,)]+,\s*[^)]*(?:req\.|request\.|ctx\.|searchParams|params\.)/i,
1276
+ skipComments: true,
1277
+ message:
1278
+ 'Request data is used as a response header value. CR/LF in the value splits the response and can set arbitrary headers/cookies (CWE-113).',
1279
+ fix: 'Validate/strip \\r and \\n, or map the value to an enum before setting the header.',
1280
+ cwe: 'CWE-113', owasp: 'A03:2025 Injection',
1281
+ }),
1282
+ makeLineRule({
1283
+ id: 'api2026.dangerously-set-innerhtml-llm',
1284
+ severity: 'high',
1285
+ confidence: 'high',
1286
+ title: 'LLM output rendered as raw HTML',
1287
+ re: /dangerouslySetInnerHTML\s*=\s*\{\{\s*__html\s*:\s*[^}]{0,80}(?:completion|response\.|message\.content|output|answer|llm)/i,
1288
+ skipComments: true,
1289
+ message:
1290
+ 'Model output is injected as HTML. Prompt injection becomes stored XSS in the user\'s session (OWASP LLM05).',
1291
+ fix: 'Render as text ({content}) or sanitize with DOMPurify before dangerous HTML; prefer markdown with a sanitizer.',
1292
+ cwe: 'CWE-79', owasp: 'LLM05 Improper Output Handling',
1293
+ }),
1294
+ makeLineRule({
1295
+ id: 'api2026.react-markdown-rehype-raw',
1296
+ severity: 'medium',
1297
+ confidence: 'medium',
1298
+ title: 'ReactMarkdown with rehype-raw and no sanitizer',
1299
+ re: /rehypePlugins\s*=\s*\{\s*\[[^\]]*rehypeRaw/i,
1300
+ filter(line) {
1301
+ return !/rehypeSanitize|rehype-sanitize|DOMPurify|sanitize-html/i.test(line);
1302
+ },
1303
+ skipComments: true,
1304
+ message:
1305
+ 'Markdown is rendered with raw HTML enabled and no sanitizer — any markdown source (user comment, model output, scraped page) can inject script.',
1306
+ fix: 'Add rehype-sanitize AFTER rehype-raw (sanitize the result) or drop rehype-raw entirely.',
1307
+ cwe: 'CWE-79', owasp: 'A03:2025 Injection',
1308
+ }),
1309
+ ];
1310
+
1311
+ // ---------------------------------------------------------------------------
1312
+ // 10. Deserialization / prototype pollution / template injection
1313
+ // ---------------------------------------------------------------------------
1314
+
1315
+ const deser2026 = [
1316
+ makeLineRule({
1317
+ id: 'deser2026.pickle-loads-user',
1318
+ severity: 'critical',
1319
+ confidence: 'high',
1320
+ title: 'pickle.loads on request data',
1321
+ re: /pickle\.loads?\s*\(\s*(?:request\.|req\.|body|data|payload|base64)/i,
1322
+ filter(line) {
1323
+ return !/(?:test|fixture|trusted)/i.test(line);
1324
+ },
1325
+ skipComments: true,
1326
+ message:
1327
+ 'pickle deserializes arbitrary Python objects — request data executes code on load (RCE).',
1328
+ fix: 'Use JSON (or a signed, versioned format). If pickle is unavoidable, verify an HMAC over the payload with a server-side key first.',
1329
+ cwe: 'CWE-502', owasp: 'A08:2025 Software and Data Integrity Failures',
1330
+ }),
1331
+ makeLineRule({
1332
+ id: 'deser2026.unsafe-yaml-load',
1333
+ severity: 'high',
1334
+ confidence: 'medium',
1335
+ title: 'yaml.load without SafeLoader',
1336
+ re: /yaml\.load\s*\(\s*(?!.*Loader\s*=\s*(?:yaml\.)?SafeLoader)/,
1337
+ skipComments: true,
1338
+ message:
1339
+ 'yaml.load with the default loader can construct arbitrary Python objects (RCE) from untrusted YAML.',
1340
+ fix: 'Use yaml.safe_load() / Loader=yaml.SafeLoader.',
1341
+ cwe: 'CWE-502', owasp: 'A08:2025 Software and Data Integrity Failures',
1342
+ }),
1343
+ makeLineRule({
1344
+ id: 'deser2026.node-serialize',
1345
+ severity: 'critical',
1346
+ confidence: 'high',
1347
+ title: 'node-serialize / unserialize on input',
1348
+ re: /(?:node-serialize|unserialize)\s*\(/i,
1349
+ filter(line) {
1350
+ return /serialize\.unserialize|node-serialize|require\(\s*['"]node-serialize/.test(line) || !/^\s*\/\//.test(line);
1351
+ },
1352
+ skipComments: true,
1353
+ message:
1354
+ 'The node-serialize package evaluates serialized functions — a well-known RCE. Untrusted input there is instant code execution.',
1355
+ fix: 'Remove node-serialize; use JSON plus a schema validator (zod) and explicit class hydration.',
1356
+ cwe: 'CWE-502', owasp: 'A08:2025 Software and Data Integrity Failures',
1357
+ }),
1358
+ makeLineRule({
1359
+ id: 'deser2026.proto-pollution-merge',
1360
+ severity: 'high',
1361
+ confidence: 'medium',
1362
+ title: 'Deep merge of request body (prototype pollution)',
1363
+ re: /(?:lodash\.)?_\.merge\s*\(|(?:Object\.assign|merge|defaultsDeep|set|unflatten)\s*\([^)]*(?:req\.body|request\.json|body\b)/i,
1364
+ filter(line) {
1365
+ return !/(?:Object\.freeze|Object\.create\(null\))/.test(line);
1366
+ },
1367
+ skipComments: true,
1368
+ message:
1369
+ 'Request data is deep-merged into an object. `{"__proto__":{"isAdmin":true}}` pollutes Object.prototype for the whole process (CWE-1321).',
1370
+ fix: 'Merge only schema-validated keys, reject __proto__/constructor/prototype, and use Object.create(null) for maps.',
1371
+ cwe: 'CWE-1321', owasp: 'A03:2025 Injection',
1372
+ }),
1373
+ makeLineRule({
1374
+ id: 'deser2026.template-injection',
1375
+ severity: 'high',
1376
+ confidence: 'medium',
1377
+ title: 'Template engine compiled from request data (SSTI)',
1378
+ re: /\.(?:render|compile)\s*\([^;]*(?:req\.|request\.|body\.|query\.|params\.|searchParams)/i,
1379
+ fileFilter: /\.(?:js|ts|mjs|cjs|py)$/i,
1380
+ filter(line, hit, lines) {
1381
+ // Only when a template engine is actually in play (imported in this file).
1382
+ const ctx = (lines || []).join('\n');
1383
+ return /\b(?:ejs|pug|handlebars|nunjucks|liquid|twig|jinja2?|mustache)\b/i.test(ctx);
1384
+ },
1385
+ skipComments: true,
1386
+ message:
1387
+ 'A template string built from request data is compiled server-side. Template engines can read the filesystem / execute helpers (SSTI → RCE).',
1388
+ fix: 'Keep templates static; pass user data only as context values, never as the template source.',
1389
+ cwe: 'CWE-1336', owasp: 'A03:2025 Injection',
1390
+ }),
1391
+ ];
1392
+
1393
+ module.exports = {
1394
+ lineRules: [
1395
+ ...authz2026, ...nextjs2026.filter((r) => r.re), ...supabase2026.filter((r) => r.re),
1396
+ ...firebase2026, ...jwt2026, ...llm2026, ...crypto2026, ...leak2026,
1397
+ ...secret2026, ...supply2026.filter((r) => r.re), ...container2026,
1398
+ ...cloud2026.filter((r) => r.re), ...api2026, ...deser2026,
1399
+ ],
1400
+ fileRules: [
1401
+ ...nextjs2026.filter((r) => !r.re),
1402
+ ...supabase2026.filter((r) => !r.re),
1403
+ ...supply2026.filter((r) => !r.re),
1404
+ ...cloud2026.filter((r) => !r.re),
1405
+ ],
1406
+ crossFileRules: [],
1407
+ };