wide-cli 0.0.0-stage → 0.3.101126

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 (172) hide show
  1. package/.github/workflows/ci.yml +29 -0
  2. package/LICENSE +674 -0
  3. package/README.md +80 -2
  4. package/assets/logo.png +0 -0
  5. package/assets/wide-logo.png +0 -0
  6. package/bin/wide.js +17 -0
  7. package/dist/agent/context.d.ts +7 -0
  8. package/dist/agent/context.d.ts.map +1 -0
  9. package/dist/agent/context.js +38 -0
  10. package/dist/agent/context.js.map +1 -0
  11. package/dist/agent/index.d.ts +16 -0
  12. package/dist/agent/index.d.ts.map +1 -0
  13. package/dist/agent/index.js +138 -0
  14. package/dist/agent/index.js.map +1 -0
  15. package/dist/config/index.d.ts +29 -0
  16. package/dist/config/index.d.ts.map +1 -0
  17. package/dist/config/index.js +66 -0
  18. package/dist/config/index.js.map +1 -0
  19. package/dist/config/workspace.d.ts +7 -0
  20. package/dist/config/workspace.d.ts.map +1 -0
  21. package/dist/config/workspace.js +31 -0
  22. package/dist/config/workspace.js.map +1 -0
  23. package/dist/decision/index.d.ts +113 -0
  24. package/dist/decision/index.d.ts.map +1 -0
  25. package/dist/decision/index.js +485 -0
  26. package/dist/decision/index.js.map +1 -0
  27. package/dist/index.d.ts +2 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +167 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/providers/claude.d.ts +10 -0
  32. package/dist/providers/claude.d.ts.map +1 -0
  33. package/dist/providers/claude.js +147 -0
  34. package/dist/providers/claude.js.map +1 -0
  35. package/dist/providers/gemini.d.ts +10 -0
  36. package/dist/providers/gemini.d.ts.map +1 -0
  37. package/dist/providers/gemini.js +129 -0
  38. package/dist/providers/gemini.js.map +1 -0
  39. package/dist/providers/index.d.ts +4 -0
  40. package/dist/providers/index.d.ts.map +1 -0
  41. package/dist/providers/index.js +44 -0
  42. package/dist/providers/index.js.map +1 -0
  43. package/dist/providers/ollama.d.ts +10 -0
  44. package/dist/providers/ollama.d.ts.map +1 -0
  45. package/dist/providers/ollama.js +94 -0
  46. package/dist/providers/ollama.js.map +1 -0
  47. package/dist/providers/openai.d.ts +11 -0
  48. package/dist/providers/openai.d.ts.map +1 -0
  49. package/dist/providers/openai.js +142 -0
  50. package/dist/providers/openai.js.map +1 -0
  51. package/dist/providers/types.d.ts +22 -0
  52. package/dist/providers/types.d.ts.map +1 -0
  53. package/dist/providers/types.js +2 -0
  54. package/dist/providers/types.js.map +1 -0
  55. package/dist/repl/index.d.ts +2 -0
  56. package/dist/repl/index.d.ts.map +1 -0
  57. package/dist/repl/index.js +94 -0
  58. package/dist/repl/index.js.map +1 -0
  59. package/dist/security/fuzzer.d.ts +20 -0
  60. package/dist/security/fuzzer.d.ts.map +1 -0
  61. package/dist/security/fuzzer.js +109 -0
  62. package/dist/security/fuzzer.js.map +1 -0
  63. package/dist/security/loader.d.ts +17 -0
  64. package/dist/security/loader.d.ts.map +1 -0
  65. package/dist/security/loader.js +126 -0
  66. package/dist/security/loader.js.map +1 -0
  67. package/dist/security/payloads.d.ts +9 -0
  68. package/dist/security/payloads.d.ts.map +1 -0
  69. package/dist/security/payloads.js +88 -0
  70. package/dist/security/payloads.js.map +1 -0
  71. package/dist/security/rules.d.ts +14 -0
  72. package/dist/security/rules.d.ts.map +1 -0
  73. package/dist/security/rules.js +288 -0
  74. package/dist/security/rules.js.map +1 -0
  75. package/dist/security/scanner.d.ts +29 -0
  76. package/dist/security/scanner.d.ts.map +1 -0
  77. package/dist/security/scanner.js +136 -0
  78. package/dist/security/scanner.js.map +1 -0
  79. package/dist/tools/browser.d.ts +47 -0
  80. package/dist/tools/browser.d.ts.map +1 -0
  81. package/dist/tools/browser.js +441 -0
  82. package/dist/tools/browser.js.map +1 -0
  83. package/dist/tools/fs.d.ts +5 -0
  84. package/dist/tools/fs.d.ts.map +1 -0
  85. package/dist/tools/fs.js +131 -0
  86. package/dist/tools/fs.js.map +1 -0
  87. package/dist/tools/git.d.ts +3 -0
  88. package/dist/tools/git.d.ts.map +1 -0
  89. package/dist/tools/git.js +50 -0
  90. package/dist/tools/git.js.map +1 -0
  91. package/dist/tools/http.d.ts +3 -0
  92. package/dist/tools/http.d.ts.map +1 -0
  93. package/dist/tools/http.js +69 -0
  94. package/dist/tools/http.js.map +1 -0
  95. package/dist/tools/index.d.ts +5 -0
  96. package/dist/tools/index.d.ts.map +1 -0
  97. package/dist/tools/index.js +50 -0
  98. package/dist/tools/index.js.map +1 -0
  99. package/dist/tools/search.d.ts +4 -0
  100. package/dist/tools/search.d.ts.map +1 -0
  101. package/dist/tools/search.js +109 -0
  102. package/dist/tools/search.js.map +1 -0
  103. package/dist/tools/security.d.ts +5 -0
  104. package/dist/tools/security.d.ts.map +1 -0
  105. package/dist/tools/security.js +129 -0
  106. package/dist/tools/security.js.map +1 -0
  107. package/dist/tools/shell.d.ts +3 -0
  108. package/dist/tools/shell.d.ts.map +1 -0
  109. package/dist/tools/shell.js +50 -0
  110. package/dist/tools/shell.js.map +1 -0
  111. package/dist/tools/types.d.ts +33 -0
  112. package/dist/tools/types.d.ts.map +1 -0
  113. package/dist/tools/types.js +2 -0
  114. package/dist/tools/types.js.map +1 -0
  115. package/dist/ui/banner.d.ts +2 -0
  116. package/dist/ui/banner.d.ts.map +1 -0
  117. package/dist/ui/banner.js +14 -0
  118. package/dist/ui/banner.js.map +1 -0
  119. package/dist/ui/colors.d.ts +18 -0
  120. package/dist/ui/colors.d.ts.map +1 -0
  121. package/dist/ui/colors.js +19 -0
  122. package/dist/ui/colors.js.map +1 -0
  123. package/dist/ui/diff.d.ts +2 -0
  124. package/dist/ui/diff.d.ts.map +1 -0
  125. package/dist/ui/diff.js +26 -0
  126. package/dist/ui/diff.js.map +1 -0
  127. package/dist/ui/markdown.d.ts +2 -0
  128. package/dist/ui/markdown.d.ts.map +1 -0
  129. package/dist/ui/markdown.js +32 -0
  130. package/dist/ui/markdown.js.map +1 -0
  131. package/dist/ui/spinner.d.ts +12 -0
  132. package/dist/ui/spinner.d.ts.map +1 -0
  133. package/dist/ui/spinner.js +46 -0
  134. package/dist/ui/spinner.js.map +1 -0
  135. package/package.json +50 -4
  136. package/src/agent/context.ts +44 -0
  137. package/src/agent/index.ts +166 -0
  138. package/src/config/index.ts +88 -0
  139. package/src/config/workspace.ts +39 -0
  140. package/src/decision/index.ts +528 -0
  141. package/src/index.ts +180 -0
  142. package/src/providers/claude.ts +163 -0
  143. package/src/providers/gemini.ts +147 -0
  144. package/src/providers/index.ts +52 -0
  145. package/src/providers/ollama.ts +108 -0
  146. package/src/providers/openai.ts +159 -0
  147. package/src/providers/types.ts +29 -0
  148. package/src/repl/index.ts +100 -0
  149. package/src/security/fuzzer.ts +140 -0
  150. package/src/security/loader.ts +129 -0
  151. package/src/security/payloads.ts +95 -0
  152. package/src/security/rules.ts +300 -0
  153. package/src/security/scanner.ts +180 -0
  154. package/src/tools/browser.ts +528 -0
  155. package/src/tools/fs.ts +143 -0
  156. package/src/tools/git.ts +51 -0
  157. package/src/tools/http.ts +77 -0
  158. package/src/tools/index.ts +64 -0
  159. package/src/tools/search.ts +109 -0
  160. package/src/tools/security.ts +140 -0
  161. package/src/tools/shell.ts +56 -0
  162. package/src/tools/types.ts +33 -0
  163. package/src/ui/banner.ts +17 -0
  164. package/src/ui/colors.ts +19 -0
  165. package/src/ui/diff.ts +24 -0
  166. package/src/ui/markdown.ts +34 -0
  167. package/src/ui/spinner.ts +53 -0
  168. package/tests/browser.test.mjs +71 -0
  169. package/tests/decision.test.mjs +68 -0
  170. package/tests/loader.test.mjs +24 -0
  171. package/tests/suite.test.mjs +61 -0
  172. package/tsconfig.json +20 -0
@@ -0,0 +1,300 @@
1
+ export interface SecurityRule {
2
+ id: string;
3
+ cwe: string;
4
+ category: string;
5
+ severity: "CRITICAL" | "HIGH" | "MEDIUM" | "LOW";
6
+ languages: string[];
7
+ pattern: RegExp;
8
+ sourcePattern?: RegExp;
9
+ message: string;
10
+ remediation: string;
11
+ }
12
+
13
+ export const SECURITY_RULES: SecurityRule[] = [
14
+ {
15
+ id: "WIDE-SEC-001",
16
+ cwe: "CWE-89",
17
+ category: "SQL Injection",
18
+ severity: "CRITICAL",
19
+ languages: ["js", "ts", "py", "php", "java", "cs", "go", "rb"],
20
+ pattern: /(?:SELECT|INSERT|UPDATE|DELETE|FROM|WHERE).*?(?:\+|%s|\$|\.format\(|f['"]).*?(?:req\.|params|body|query|input|\$_(?:GET|POST|REQUEST)|request\.)/i,
21
+ sourcePattern: /(?:req\.(?:query|params|body)|request\.(?:args|form|GET|POST)|\$_(?:GET|POST))/i,
22
+ message: "Dynamic SQL query constructed with unescaped user input.",
23
+ remediation: "Use parameterized queries or prepared statements (e.g. pool.query('SELECT * FROM users WHERE id = $1', [id]))."
24
+ },
25
+ {
26
+ id: "WIDE-SEC-002",
27
+ cwe: "CWE-78",
28
+ category: "Command Injection",
29
+ severity: "CRITICAL",
30
+ languages: ["js", "ts", "py", "php", "java", "cs", "go", "rb"],
31
+ pattern: /(?:child_process|exec|execSync|spawn|subprocess\.Popen|subprocess\.run|os\.system|shell_exec|system|passthru|Runtime\.getRuntime\(\)\.exec)\s*\(\s*(?:`[^`]*\$\{|['"].*?\+\s*|f['"][^'"]*\{)/i,
32
+ sourcePattern: /(?:req\.|request\.|input|param|\$_)/i,
33
+ message: "System command execution sink receives unescaped parameters.",
34
+ remediation: "Avoid passing user input to shell commands. Use execFile or spawn with argument arrays without invoking a subshell."
35
+ },
36
+ {
37
+ id: "WIDE-SEC-003",
38
+ cwe: "CWE-79",
39
+ category: "Cross-Site Scripting (XSS)",
40
+ severity: "HIGH",
41
+ languages: ["js", "ts", "php"],
42
+ pattern: /(?:innerHTML|outerHTML|document\.write|dangerouslySetInnerHTML|v-html|\becho\s+\$_(?:GET|POST)|print\s+\$_)\s*(?:=|\()\s*(?:.*?\b(?:query|param|body|req|location|search|URLSearchParams)\b)/i,
43
+ message: "Unsanitized user input rendered directly into the DOM or HTML output.",
44
+ remediation: "Use textContent, framework-native safe bindings, or sanitize HTML using DOMPurify before rendering."
45
+ },
46
+ {
47
+ id: "WIDE-SEC-004",
48
+ cwe: "CWE-918",
49
+ category: "Server-Side Request Forgery (SSRF)",
50
+ severity: "HIGH",
51
+ languages: ["js", "ts", "py", "php", "go", "java"],
52
+ pattern: /(?:fetch|axios\.(?:get|post|request)|http\.get|urllib\.request|requests\.(?:get|post)|curl_exec)\s*\(\s*(?:req\.|params|query|body|request\.)/i,
53
+ message: "Outbound HTTP request targeting a user-supplied URL without destination validation.",
54
+ remediation: "Validate destination URLs against an explicit domain allowlist and block private IP ranges (127.0.0.1, 10.0.0.0/8, 169.254.169.254)."
55
+ },
56
+ {
57
+ id: "WIDE-SEC-005",
58
+ cwe: "CWE-22",
59
+ category: "Path Traversal",
60
+ severity: "HIGH",
61
+ languages: ["js", "ts", "py", "php", "java", "go"],
62
+ pattern: /(?:readFile|readFileSync|createReadStream|open|file_get_contents|readfile|FileInputStream)\s*\(\s*(?:.*?path\.join.*?req\.|.*?\+\s*(?:req\.|params|query|\$_)|f['"].*?\{request)/i,
63
+ message: "File system access with untrusted path concatenation vulnerable to directory traversal.",
64
+ remediation: "Resolve the path with path.resolve() and verify that it starts with the intended base directory."
65
+ },
66
+ {
67
+ id: "WIDE-SEC-006",
68
+ cwe: "CWE-502",
69
+ category: "Insecure Deserialization",
70
+ severity: "CRITICAL",
71
+ languages: ["js", "ts", "py", "php", "java"],
72
+ pattern: /(?:pickle\.loads|yaml\.load\([^,)]+\)|unserialize\s*\(|node-serialize|serialize\.unserialize|XMLDecoder|ObjectInputStream)/i,
73
+ message: "Untrusted deserialization can lead to arbitrary code execution.",
74
+ remediation: "Never deserialize untrusted input with unsafe serializers. Use JSON.parse, safe_load in PyYAML, or HMAC verification."
75
+ },
76
+ {
77
+ id: "WIDE-SEC-007",
78
+ cwe: "CWE-611",
79
+ category: "XML External Entity (XXE)",
80
+ severity: "HIGH",
81
+ languages: ["js", "ts", "py", "php", "java"],
82
+ pattern: /(?:xml2js|DOMParser|SimpleXMLElement|libxml_disable_entity_loader\s*\(\s*false|DocumentBuilderFactory.*?setFeature.*?external-general-entities.*?true)/i,
83
+ message: "XML parser configured without disabling external entity resolution.",
84
+ remediation: "Disable external DTDs and external entity expansion (e.g. setFeature('http://apache.org/xml/features/disallow-doctype-decl', true))."
85
+ },
86
+ {
87
+ id: "WIDE-SEC-008",
88
+ cwe: "CWE-798",
89
+ category: "Hardcoded Secret",
90
+ severity: "HIGH",
91
+ languages: ["all"],
92
+ pattern: /(?:(?:api_?key|secret|password|access_?token|jwt_?secret|private_?key)\s*[:=]\s*['"][a-zA-Z0-9_\-\.]{16,}['"]|AKIA[0-9A-Z]{16}|ghp_[a-zA-Z0-9]{36}|AIza[0-9A-Za-z\-_]{35})/i,
93
+ message: "High-entropy API token, private key, or credential hardcoded in source.",
94
+ remediation: "Extract secrets to environment variables or an external secret manager (AWS Secrets Manager, Vault)."
95
+ },
96
+ {
97
+ id: "WIDE-SEC-009",
98
+ cwe: "CWE-327",
99
+ category: "Broken Cryptography",
100
+ severity: "MEDIUM",
101
+ languages: ["js", "ts", "py", "php", "java", "cs", "go"],
102
+ pattern: /(?:createHash\s*\(\s*['"](?:md5|sha1)['"]|hashlib\.(?:md5|sha1)|MD5\.Create|DES|RC4|crypto\.createCipheriv\s*\(\s*['"][^'"]*ecb)/i,
103
+ message: "Collision-prone or deprecated cryptographic algorithm (MD5/SHA1/DES/ECB mode).",
104
+ remediation: "Use SHA-256/SHA-512 for integrity, bcrypt/argon2 for passwords, and AES-256-GCM for symmetric encryption."
105
+ },
106
+ {
107
+ id: "WIDE-SEC-010",
108
+ cwe: "CWE-94",
109
+ category: "Code Injection (eval)",
110
+ severity: "CRITICAL",
111
+ languages: ["js", "ts", "py", "php"],
112
+ pattern: /(?:\beval\s*\(|new\s+Function\s*\(|setTimeout\s*\(\s*['"`]|setInterval\s*\(\s*['"`])/i,
113
+ sourcePattern: /(?:req\.|params|query|input|\$_)/i,
114
+ message: "Dynamic code evaluation sink called with user-influenced string.",
115
+ remediation: "Remove eval and dynamic Function calls. Refactor logic to use structured mappings or data structures."
116
+ },
117
+ {
118
+ id: "WIDE-SEC-011",
119
+ cwe: "CWE-1333",
120
+ category: "Regular Expression Denial of Service (ReDoS)",
121
+ severity: "MEDIUM",
122
+ languages: ["js", "ts", "py", "java"],
123
+ pattern: /\/(?:[a-zA-Z0-9_]*\+)+[a-zA-Z0-9_]*\+/i,
124
+ message: "Catastrophic backtracking vulnerability detected in nested regex quantifier.",
125
+ remediation: "Refactor regex to eliminate overlapping nested repetitions, or enforce string length limits before matching."
126
+ },
127
+ {
128
+ id: "WIDE-SEC-012",
129
+ cwe: "CWE-1321",
130
+ category: "Prototype Pollution",
131
+ severity: "HIGH",
132
+ languages: ["js", "ts"],
133
+ pattern: /(?:__proto__|constructor\s*\[\s*['"]prototype['"]\]|Object\.assign\s*\(\s*\{\}\s*,\s*(?:req\.|body|params)|merge\s*\([^,]+,\s*(?:req\.|body))/i,
134
+ message: "Potential prototype pollution via unsafe recursive object merging.",
135
+ remediation: "Validate keys against '__proto__' and 'constructor', or use Object.create(null) for unpolluted dictionaries."
136
+ },
137
+ {
138
+ id: "WIDE-SEC-013",
139
+ cwe: "CWE-943",
140
+ category: "NoSQL Injection",
141
+ severity: "CRITICAL",
142
+ languages: ["js", "ts", "py"],
143
+ pattern: /(?:\.find|\.findOne|\.deleteMany|\.updateMany)\s*\(\s*(?:req\.(?:body|query|params)|\{[^}]*\$(?:where|ne|gt|regex))/i,
144
+ message: "NoSQL query structure accepts raw user object without type coercion.",
145
+ remediation: "Enforce strict schema validation and sanitize inputs so operator objects ($gt, $where) cannot be injected."
146
+ },
147
+ {
148
+ id: "WIDE-SEC-014",
149
+ cwe: "CWE-601",
150
+ category: "Open Redirect",
151
+ severity: "MEDIUM",
152
+ languages: ["js", "ts", "py", "php"],
153
+ pattern: /(?:res\.redirect|redirect|header\s*\(\s*['"]Location:)\s*\(\s*(?:req\.|params|query|request\.)/i,
154
+ message: "HTTP redirection destination is controlled by untrusted request parameter.",
155
+ remediation: "Use relative redirect paths or validate destinations against a strict allowlist of authorized hostnames."
156
+ },
157
+ {
158
+ id: "WIDE-SEC-015",
159
+ cwe: "CWE-384",
160
+ category: "Session Fixation",
161
+ severity: "MEDIUM",
162
+ languages: ["js", "ts", "py", "php"],
163
+ pattern: /(?:session\.regenerate|session_regenerate_id)\s*===?\s*false|req\.session\.regenerate\s*\(\s*function\s*\(\)\s*\{\s*\}\s*\)/i,
164
+ message: "Session identifier not refreshed upon privilege escalation or authentication.",
165
+ remediation: "Always regenerate session identifiers upon login using req.session.regenerate() or session_regenerate_id(true)."
166
+ },
167
+ {
168
+ id: "WIDE-SEC-016",
169
+ cwe: "CWE-639",
170
+ category: "Insecure Direct Object Reference (IDOR)",
171
+ severity: "HIGH",
172
+ languages: ["js", "ts", "py", "php", "java"],
173
+ pattern: /(?:findById|findByPk|findOne|SELECT.*?WHERE id =)\s*\(\s*req\.params\.id\s*\)(?!.*?(?:userId|ownerId|user\._?id|req\.user))/i,
174
+ message: "Database record queried strictly by client-supplied ID without verifying ownership.",
175
+ remediation: "Always scope database queries to the authenticated user ID (e.g. { id: req.params.id, userId: req.user.id })."
176
+ },
177
+ {
178
+ id: "WIDE-SEC-017",
179
+ cwe: "CWE-942",
180
+ category: "CORS Misconfiguration",
181
+ severity: "MEDIUM",
182
+ languages: ["js", "ts", "py", "php"],
183
+ pattern: /(?:Access-Control-Allow-Origin.*?['"]\*['"].*?Access-Control-Allow-Credentials.*?['"]true['"]|cors\s*\(\s*\{\s*origin:\s*true\s*,\s*credentials:\s*true)/i,
184
+ message: "Wildcard CORS origin allowed in conjunction with credential sharing.",
185
+ remediation: "Never combine Access-Control-Allow-Credentials: true with a wildcard or dynamically reflected origin."
186
+ },
187
+ {
188
+ id: "WIDE-SEC-018",
189
+ cwe: "CWE-352",
190
+ category: "Cross-Site Request Forgery (CSRF)",
191
+ severity: "MEDIUM",
192
+ languages: ["js", "ts", "py", "php"],
193
+ pattern: /(?:app\.(?:post|put|delete|patch)\s*\([^,]+,\s*(?!.*?csrf).*?\bfunction\b|csrfProtection.*?enabled:\s*false)/i,
194
+ message: "State-changing HTTP route registered without apparent CSRF token protection.",
195
+ remediation: "Enable SameSite=Lax/Strict cookie attributes and use CSRF tokens (csurf or double-submit cookie pattern)."
196
+ },
197
+ {
198
+ id: "WIDE-SEC-019",
199
+ cwe: "CWE-330",
200
+ category: "Weak Randomness",
201
+ severity: "LOW",
202
+ languages: ["js", "ts", "py", "php", "java"],
203
+ pattern: /(?:Math\.random|random\.random|rand\(|mt_rand)\s*\(\s*\).*?(?:token|secret|session|key|nonce|auth|otp)/i,
204
+ message: "Pseudorandom number generator used for security-sensitive token generation.",
205
+ remediation: "Use cryptographically secure random number generators (crypto.randomBytes() or secrets.token_hex())."
206
+ },
207
+ {
208
+ id: "WIDE-SEC-020",
209
+ cwe: "CWE-209",
210
+ category: "Information Leakage",
211
+ severity: "LOW",
212
+ languages: ["js", "ts", "py", "php", "java"],
213
+ pattern: /(?:res\.(?:send|json)\s*\(\s*(?:err\.stack|err\.message|error\.stack)|printStackTrace\s*\(\)|ini_set\s*\(\s*['"]display_errors['"]\s*,\s*['"]1['"]\))/i,
214
+ message: "Detailed internal error stack trace or debug information exposed to client.",
215
+ remediation: "Log stack traces internally and return generic error responses with error correlation IDs to clients."
216
+ }
217
+ ];
218
+
219
+ export const DEFAULT_AGENT_RULES: SecurityRule[] = [
220
+ {
221
+ id: "wide/cwe078-ai-unsafe-tool-exec",
222
+ cwe: "CWE-78",
223
+ category: "AI_SECURITY",
224
+ severity: "CRITICAL",
225
+ languages: ["js", "jsx", "ts", "tsx", "py", "mjs", "cjs"],
226
+ pattern: /\b(?:exec|execSync|spawn|subprocess\.run|os\.system)\s*\(\s*(?:toolCall|tool_call|args|arguments|response\.command|patch\.command)/i,
227
+ message: "Executing raw system command directly from AI tool call response without argument validation.",
228
+ remediation: "Whitelist allowed commands and run them in an isolated sandbox with fixed arguments."
229
+ },
230
+ {
231
+ id: "wide/cwe079-ai-prompt-injection",
232
+ cwe: "CWE-79",
233
+ category: "AI_SECURITY",
234
+ severity: "HIGH",
235
+ languages: ["js", "jsx", "ts", "tsx", "py", "mjs", "cjs"],
236
+ pattern: /\b(?:prompt|instruction|query|input)\s*[:=]\s*(?:f?["'].*?\{|`.*?$\{).*(?:req\.|params\.|body\.|userInput|user_input|request\.)/i,
237
+ message: "Untrusted user input concatenated directly into LLM prompt template without sanitization.",
238
+ remediation: "Use structured multi-turn message roles or sanitize prompt inputs before sending to the model."
239
+ },
240
+ {
241
+ id: "wide/cwe095-ai-unconstrained-eval",
242
+ cwe: "CWE-95",
243
+ category: "AI_SECURITY",
244
+ severity: "CRITICAL",
245
+ languages: ["js", "jsx", "ts", "tsx", "py", "mjs", "cjs"],
246
+ pattern: /\b(?:eval|Function|vm\.runInContext|compile)\s*\(\s*(?:toolOutput|tool_output|response\.text|aiResult|ai_output|completion)/i,
247
+ message: "Evaluating raw executable code returned by LLM without sandboxing or static verification.",
248
+ remediation: "Parse responses into structured abstract syntax trees or validate against a strict AST schema before execution."
249
+ },
250
+ {
251
+ id: "wide/cwe306-ai-unauthenticated-mcp-registration",
252
+ cwe: "CWE-306",
253
+ category: "AI_SECURITY",
254
+ severity: "HIGH",
255
+ languages: ["js", "jsx", "ts", "tsx", "py", "mjs", "cjs"],
256
+ pattern: /\b(?:registerMcpServer|addMcpServer|mcpClient\.connect)\s*\(\s*(?:url|endpoint|serverConfig)\s*\)/i,
257
+ message: "Model Context Protocol server registered without identity verification or authorization signature.",
258
+ remediation: "Verify server host authorization and enforce cryptographic signature checks prior to registering external toolsets."
259
+ },
260
+ {
261
+ id: "wide/cwe400-ai-unbounded-agent-loop",
262
+ cwe: "CWE-400",
263
+ category: "AI_SECURITY",
264
+ severity: "MEDIUM",
265
+ languages: ["js", "jsx", "ts", "tsx", "py", "mjs", "cjs"],
266
+ pattern: /while\s*\(\s*(?:true|1|!done|!finished|!settled)\s*\)\s*\{(?![^}]*\b(?:maxRounds|maxSteps|maxIterations|round\s*>=|step\s*>=)\b)/i,
267
+ message: "Autonomous agent execution loop lacks explicit termination boundary or maximum step limit.",
268
+ remediation: "Enforce a strict step threshold or cancellation budget to prevent runaway agent execution loops."
269
+ },
270
+ {
271
+ id: "wide/cwe770-ai-unbounded-context-accumulation",
272
+ cwe: "CWE-770",
273
+ category: "AI_SECURITY",
274
+ severity: "MEDIUM",
275
+ languages: ["js", "jsx", "ts", "tsx", "py", "mjs", "cjs"],
276
+ pattern: /\b(?:history|messages|chatContext)\.push\s*\(.*?\)(?![^;]*(?:slice|shift|trim|truncate|maxTokens|maxHistory))/i,
277
+ message: "LLM conversation context accumulates without token limits or sliding window truncation.",
278
+ remediation: "Prune chat context using sliding window truncation or token counting before appending turns."
279
+ },
280
+ {
281
+ id: "wide/cwe798-ai-prompt-secret-leak",
282
+ cwe: "CWE-798",
283
+ category: "AI_SECURITY",
284
+ severity: "HIGH",
285
+ languages: ["js", "jsx", "ts", "tsx", "py", "mjs", "cjs"],
286
+ pattern: /\b(?:systemPrompt|systemMessage|system_prompt)\s*[:=].*?(?:process\.env\.(?:[A-Z_]*(?:KEY|SECRET|TOKEN|PASSWORD|PASS|AUTH))|apiKey|api_key|secret)/i,
287
+ message: "Sensitive secrets or private API credentials embedded in prompt context.",
288
+ remediation: "Strip private credentials from prompt text and provide secrets through isolated backend proxy channels."
289
+ },
290
+ {
291
+ id: "wide/cwe829-ai-unvalidated-patch-apply",
292
+ cwe: "CWE-829",
293
+ category: "AI_SECURITY",
294
+ severity: "HIGH",
295
+ languages: ["js", "jsx", "ts", "tsx", "py", "mjs", "cjs"],
296
+ pattern: /\b(?:applyPatch|gitApply|applyDiff|writePatch)\s*\(\s*(?:aiPatch|llmResponse|output\.patch|modelDiff)/i,
297
+ message: "Applying LLM-generated patch directly to codebase without path traversal or integrity checks.",
298
+ remediation: "Validate destination file paths are strictly within workspace bounds and run static scans before applying patches."
299
+ }
300
+ ];
@@ -0,0 +1,180 @@
1
+ import { readFileSync, existsSync } from "node:fs";
2
+ import { resolve, relative, extname } from "node:path";
3
+ import fg from "fast-glob";
4
+ import pc from "picocolors";
5
+ import { SECURITY_RULES, type SecurityRule } from "./rules.js";
6
+ import { RuleLoader } from "./loader.js";
7
+
8
+ export interface Finding {
9
+ id: string;
10
+ cwe: string;
11
+ category: string;
12
+ severity: "CRITICAL" | "HIGH" | "MEDIUM" | "LOW";
13
+ file: string;
14
+ line: number;
15
+ snippet: string;
16
+ message: string;
17
+ remediation: string;
18
+ }
19
+
20
+ export interface ScanResult {
21
+ totalFilesScanned: number;
22
+ findings: Finding[];
23
+ summary: {
24
+ critical: number;
25
+ high: number;
26
+ medium: number;
27
+ low: number;
28
+ };
29
+ }
30
+
31
+ const EXTENSION_MAP: Record<string, string> = {
32
+ ".js": "js",
33
+ ".jsx": "js",
34
+ ".mjs": "js",
35
+ ".cjs": "js",
36
+ ".ts": "ts",
37
+ ".tsx": "ts",
38
+ ".py": "py",
39
+ ".php": "php",
40
+ ".java": "java",
41
+ ".cs": "cs",
42
+ ".go": "go",
43
+ ".rb": "rb",
44
+ ".rs": "rs",
45
+ ".c": "c",
46
+ ".cpp": "c",
47
+ ".h": "c"
48
+ };
49
+
50
+ export class SecurityScanner {
51
+ private workspaceDir: string;
52
+ private rulesPath?: string;
53
+
54
+ constructor(workspaceDir = process.cwd(), rulesPath?: string) {
55
+ this.workspaceDir = workspaceDir;
56
+ this.rulesPath = rulesPath;
57
+ }
58
+
59
+ public async scanPath(targetPath = ".", minSeverity: Finding["severity"] | "ALL" = "ALL"): Promise<ScanResult> {
60
+ const fullTarget = resolve(this.workspaceDir, targetPath);
61
+ if (!existsSync(fullTarget)) {
62
+ throw new Error(`Target path does not exist: ${targetPath}`);
63
+ }
64
+
65
+ const activeRules = RuleLoader.loadRules(this.rulesPath, this.workspaceDir);
66
+
67
+ const files = await fg(["**/*.{js,jsx,mjs,cjs,ts,tsx,py,php,java,cs,go,rb,rs,c,cpp,h}"], {
68
+ cwd: fullTarget,
69
+ ignore: [
70
+ "**/node_modules/**",
71
+ "**/.git/**",
72
+ "**/dist/**",
73
+ "**/build/**",
74
+ "**/vendor/**",
75
+ "**/.next/**",
76
+ "**/target/**",
77
+ "**/coverage/**"
78
+ ],
79
+ onlyFiles: true
80
+ });
81
+
82
+ const findings: Finding[] = [];
83
+ const severityRanks: Record<Finding["severity"], number> = {
84
+ CRITICAL: 4,
85
+ HIGH: 3,
86
+ MEDIUM: 2,
87
+ LOW: 1
88
+ };
89
+
90
+ const minRank = minSeverity === "ALL" ? 1 : severityRanks[minSeverity] || 1;
91
+
92
+ for (const file of files) {
93
+ const fullFilePath = resolve(fullTarget, file);
94
+ const ext = extname(file).toLowerCase();
95
+ const lang = EXTENSION_MAP[ext] || "all";
96
+
97
+ let content = "";
98
+ try {
99
+ content = readFileSync(fullFilePath, "utf8");
100
+ } catch {
101
+ continue;
102
+ }
103
+
104
+ const lines = content.split("\n");
105
+ const applicableRules = activeRules.filter(r =>
106
+ r.languages.includes("all") || r.languages.includes(lang)
107
+ );
108
+
109
+ for (let i = 0; i < lines.length; i++) {
110
+ const lineText = lines[i];
111
+ if (lineText.length > 1000) continue;
112
+
113
+ for (const rule of applicableRules) {
114
+ if (severityRanks[rule.severity] < minRank) continue;
115
+
116
+ if (rule.pattern.test(lineText)) {
117
+ let confirmed = true;
118
+ if (rule.sourcePattern) {
119
+ const windowStart = Math.max(0, i - 15);
120
+ const windowText = lines.slice(windowStart, i + 1).join("\n");
121
+ confirmed = rule.sourcePattern.test(windowText);
122
+ }
123
+
124
+ if (confirmed) {
125
+ findings.push({
126
+ id: rule.id,
127
+ cwe: rule.cwe,
128
+ category: rule.category,
129
+ severity: rule.severity,
130
+ file: relative(this.workspaceDir, fullFilePath),
131
+ line: i + 1,
132
+ snippet: lineText.trim(),
133
+ message: rule.message,
134
+ remediation: rule.remediation
135
+ });
136
+ }
137
+ }
138
+ }
139
+ }
140
+ }
141
+
142
+ const summary = {
143
+ critical: findings.filter(f => f.severity === "CRITICAL").length,
144
+ high: findings.filter(f => f.severity === "HIGH").length,
145
+ medium: findings.filter(f => f.severity === "MEDIUM").length,
146
+ low: findings.filter(f => f.severity === "LOW").length
147
+ };
148
+
149
+ return {
150
+ totalFilesScanned: files.length,
151
+ findings,
152
+ summary
153
+ };
154
+ }
155
+
156
+ public formatCliReport(result: ScanResult): string {
157
+ if (result.findings.length === 0) {
158
+ return `Wide Security Scan complete: 0 vulnerabilities found in ${result.totalFilesScanned} files scanned.`;
159
+ }
160
+
161
+ const lines: string[] = [
162
+ `Wide Security Scan: Found ${result.findings.length} issue(s) across ${result.totalFilesScanned} scanned files.`,
163
+ `Summary: [CRITICAL: ${result.summary.critical}] [HIGH: ${result.summary.high}] [MEDIUM: ${result.summary.medium}] [LOW: ${result.summary.low}]\n`
164
+ ];
165
+
166
+ for (const f of result.findings) {
167
+ const sevColor = f.severity === "CRITICAL" ? pc.red(pc.bold(`[${f.severity}]`)) :
168
+ f.severity === "HIGH" ? pc.red(`[${f.severity}]`) :
169
+ f.severity === "MEDIUM" ? pc.yellow(`[${f.severity}]`) :
170
+ pc.gray(`[${f.severity}]`);
171
+
172
+ lines.push(`${sevColor} ${pc.bold(f.category)} (${f.cwe}) in ${pc.cyan(`${f.file}:${f.line}`)}`);
173
+ lines.push(` Message: ${f.message}`);
174
+ lines.push(` Code: ${pc.dim(f.snippet)}`);
175
+ lines.push(` Remediation: ${pc.green(f.remediation)}\n`);
176
+ }
177
+
178
+ return lines.join("\n");
179
+ }
180
+ }