tribunal-kit 4.4.0 → 4.4.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 (85) hide show
  1. package/.agent/agents/api-architect.md +66 -66
  2. package/.agent/agents/db-latency-auditor.md +216 -216
  3. package/.agent/agents/precedence-reviewer.md +250 -250
  4. package/.agent/agents/resilience-reviewer.md +88 -88
  5. package/.agent/agents/schema-reviewer.md +67 -67
  6. package/.agent/agents/throughput-optimizer.md +299 -299
  7. package/.agent/agents/ui-ux-auditor.md +292 -292
  8. package/.agent/agents/vitals-reviewer.md +223 -223
  9. package/.agent/scripts/_colors.js +18 -18
  10. package/.agent/scripts/_utils.js +42 -42
  11. package/.agent/scripts/append_flow.js +72 -72
  12. package/.agent/scripts/auto_preview.js +197 -197
  13. package/.agent/scripts/bundle_analyzer.js +290 -290
  14. package/.agent/scripts/case_law_manager.js +17 -6
  15. package/.agent/scripts/checklist.js +266 -266
  16. package/.agent/scripts/colors.js +17 -17
  17. package/.agent/scripts/compress_skills.js +141 -141
  18. package/.agent/scripts/consolidate_skills.js +149 -149
  19. package/.agent/scripts/context_broker.js +611 -609
  20. package/.agent/scripts/deep_compress.js +150 -150
  21. package/.agent/scripts/dependency_analyzer.js +272 -272
  22. package/.agent/scripts/graph_builder.js +313 -311
  23. package/.agent/scripts/graph_visualizer.js +384 -384
  24. package/.agent/scripts/inner_loop_validator.js +451 -465
  25. package/.agent/scripts/lint_runner.js +187 -187
  26. package/.agent/scripts/minify_context.js +100 -100
  27. package/.agent/scripts/mutation_runner.js +280 -280
  28. package/.agent/scripts/patch_skills_meta.js +156 -156
  29. package/.agent/scripts/patch_skills_output.js +244 -244
  30. package/.agent/scripts/schema_validator.js +297 -297
  31. package/.agent/scripts/security_scan.js +303 -303
  32. package/.agent/scripts/session_manager.js +276 -276
  33. package/.agent/scripts/skill_evolution.js +644 -644
  34. package/.agent/scripts/skill_integrator.js +313 -313
  35. package/.agent/scripts/strengthen_skills.js +193 -193
  36. package/.agent/scripts/strip_tribunal.js +47 -47
  37. package/.agent/scripts/swarm_dispatcher.js +360 -360
  38. package/.agent/scripts/test_runner.js +193 -193
  39. package/.agent/scripts/utils.js +32 -32
  40. package/.agent/scripts/verify_all.js +257 -256
  41. package/.agent/skills/app-builder/templates/astro-static/TEMPLATE.md +1 -1
  42. package/.agent/skills/app-builder/templates/chrome-extension/TEMPLATE.md +1 -1
  43. package/.agent/skills/app-builder/templates/cli-tool/TEMPLATE.md +1 -1
  44. package/.agent/skills/app-builder/templates/electron-desktop/TEMPLATE.md +1 -1
  45. package/.agent/skills/app-builder/templates/express-api/TEMPLATE.md +1 -1
  46. package/.agent/skills/app-builder/templates/flutter-app/TEMPLATE.md +1 -1
  47. package/.agent/skills/app-builder/templates/monorepo-turborepo/TEMPLATE.md +1 -1
  48. package/.agent/skills/app-builder/templates/nextjs-fullstack/TEMPLATE.md +1 -1
  49. package/.agent/skills/app-builder/templates/nextjs-saas/TEMPLATE.md +1 -1
  50. package/.agent/skills/app-builder/templates/nextjs-static/TEMPLATE.md +1 -1
  51. package/.agent/skills/app-builder/templates/nuxt-app/TEMPLATE.md +1 -1
  52. package/.agent/skills/app-builder/templates/python-fastapi/TEMPLATE.md +1 -1
  53. package/.agent/skills/app-builder/templates/react-native-app/TEMPLATE.md +1 -1
  54. package/.agent/skills/doc.md +1 -1
  55. package/.agent/skills/knowledge-graph/SKILL.md +52 -52
  56. package/.agent/skills/ui-ux-pro-max/SKILL.md +562 -562
  57. package/.agent/workflows/generate.md +183 -183
  58. package/.agent/workflows/tribunal-speed.md +183 -183
  59. package/README.md +1 -1
  60. package/bin/tribunal-kit.js +76 -87
  61. package/package.json +6 -3
  62. package/scripts/changelog.js +167 -167
  63. package/scripts/sync-version.js +81 -81
  64. package/.agent/history/architecture-explorer.html +0 -352
  65. package/.agent/history/architecture-graph.yaml +0 -109
  66. package/.agent/history/graph-cache.json +0 -215
  67. package/.agent/history/snapshots/migrate_refs.js.json +0 -11
  68. package/.agent/history/snapshots/scripts__changelog.js.json +0 -12
  69. package/.agent/history/snapshots/scripts__sync-version.js.json +0 -11
  70. package/.agent/history/snapshots/scripts__validate-payload.js.json +0 -11
  71. package/.agent/history/snapshots/test__integration__bridges.test.js.json +0 -13
  72. package/.agent/history/snapshots/test__integration__init.test.js.json +0 -13
  73. package/.agent/history/snapshots/test__integration__routing.test.js.json +0 -11
  74. package/.agent/history/snapshots/test__integration__swarm_dispatcher.test.js.json +0 -13
  75. package/.agent/history/snapshots/test__integration__wave2.test.js.json +0 -13
  76. package/.agent/history/snapshots/test__unit__args.test.js.json +0 -10
  77. package/.agent/history/snapshots/test__unit__case_law_manager.test.js.json +0 -10
  78. package/.agent/history/snapshots/test__unit__copyDir.test.js.json +0 -13
  79. package/.agent/history/snapshots/test__unit__graph_tools.test.js.json +0 -11
  80. package/.agent/history/snapshots/test__unit__selfInstall.test.js.json +0 -13
  81. package/.agent/history/snapshots/test__unit__semver.test.js.json +0 -10
  82. package/.agent/history/snapshots/test__unit__swarm_dispatcher.test.js.json +0 -11
  83. package/.agent/scripts/__pycache__/_colors.cpython-311.pyc +0 -0
  84. package/.agent/scripts/__pycache__/_utils.cpython-311.pyc +0 -0
  85. package/.agent/scripts/__pycache__/case_law_manager.cpython-311.pyc +0 -0
@@ -1,303 +1,303 @@
1
- #!/usr/bin/env node
2
- /**
3
- * security_scan.js — Deep security scanner for the Tribunal Agent Kit.
4
- *
5
- * Checks for OWASP Top 10 patterns in source code:
6
- * - Hardcoded secrets and credentials
7
- * - SQL injection patterns (string concatenation in queries)
8
- * - XSS-prone code (innerHTML, dangerouslySetInnerHTML)
9
- * - Insecure eval() usage
10
- * - Missing auth patterns
11
- * - Insecure crypto usage
12
- *
13
- * ⚠️ DISCLAIMER: This is a heuristic regex-based pattern scanner, NOT a
14
- * full static analysis tool. It may produce false positives (e.g., test
15
- * fixtures containing 'password') and cannot detect indirect vulnerabilities
16
- * (e.g., SQL injection via variable indirection). For production security
17
- * auditing, supplement with dedicated tools like Semgrep, CodeQL, or Snyk.
18
- *
19
- * Usage:
20
- * node .agent/scripts/security_scan.js .
21
- * node .agent/scripts/security_scan.js . --severity high
22
- * node .agent/scripts/security_scan.js . --files src/auth.ts src/db.ts
23
- */
24
-
25
- 'use strict';
26
-
27
- const fs = require('fs');
28
- const path = require('path');
29
-
30
- // ━━━ ANSI colors ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
31
- const RED = '\x1b[91m';
32
- const GREEN = '\x1b[92m';
33
- const YELLOW = '\x1b[93m';
34
- const BLUE = '\x1b[94m';
35
- const MAGENTA = '\x1b[95m';
36
- const BOLD = '\x1b[1m';
37
- const RESET = '\x1b[0m';
38
-
39
- const SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.py', '.go', '.java', '.rb']);
40
- const SKIP_DIRS = new Set([
41
- 'node_modules', '.git', 'dist', 'build', '__pycache__', '.agent',
42
- '.next', 'vendor', 'coverage', 'lcov-report', '.nyc_output',
43
- 'test-results', '.jest-cache',
44
- ]);
45
-
46
- const SEVERITY_COLORS = {
47
- critical: RED + BOLD,
48
- high: RED,
49
- medium: YELLOW,
50
- low: BLUE,
51
- };
52
-
53
- const SEVERITY_RANK = { critical: 0, high: 1, medium: 2, low: 3 };
54
-
55
- // Pattern definitions: [regex, severity, category, message]
56
- const PATTERNS = [
57
- // Secrets
58
- [/(?:password|passwd|pwd)\s*=\s*["'][^"']+["']/i, 'critical', 'Hardcoded Secret', 'Hardcoded password detected'],
59
- [/(?:api_key|apikey|api_secret)\s*=\s*["'][^"']+["']/i, 'critical', 'Hardcoded Secret', 'Hardcoded API key detected'],
60
- [/(?:secret|token|auth_token)\s*=\s*["'][A-Za-z0-9+/=]{16,}["']/i, 'critical', 'Hardcoded Secret', 'Hardcoded secret/token detected'],
61
- [/(?:PRIVATE_KEY|private_key)\s*=\s*["']/i, 'critical', 'Hardcoded Secret', 'Hardcoded private key detected'],
62
-
63
- // SQL Injection
64
- [/(?:query|execute|raw)\s*\(\s*[`"'].*\$\{/i, 'high', 'SQL Injection', 'String interpolation in SQL query — use parameterized queries'],
65
- [/(?:query|execute|raw)\s*\(\s*["'].*\+\s*(?:req|input|params|body)/i, 'high', 'SQL Injection', 'String concatenation with user input in SQL'],
66
- [/\.raw\s*\(\s*`/, 'medium', 'SQL Injection', 'Raw query with template literal — verify inputs are sanitized'],
67
-
68
- // XSS
69
- [/\.innerHTML\s*=/, 'high', 'XSS', 'Direct innerHTML assignment — use textContent or a sanitizer'],
70
- [/dangerouslySetInnerHTML/, 'medium', 'XSS', 'dangerouslySetInnerHTML used — ensure input is sanitized'],
71
- [/document\.write\s*\(/, 'high', 'XSS', 'document.write() is an XSS vector'],
72
-
73
- // Insecure Functions
74
- [/\beval\s*\(/, 'high', 'Code Injection', 'eval() is a code injection vector — avoid entirely'],
75
- [/new\s+Function\s*\(/, 'high', 'Code Injection', 'new Function() is equivalent to eval()'],
76
- [/child_process\.exec\s*\(/, 'medium', 'Command Injection', 'exec() with unsanitized input is a command injection vector'],
77
- [/subprocess\.call\s*\(\s*[^,\]]*\bshell\s*=\s*True/, 'high', 'Command Injection', 'subprocess with shell=True — use shell=False and pass args as list'],
78
-
79
- // Crypto
80
- [/createHash\s*\(\s*["']md5["']/, 'medium', 'Weak Crypto', 'MD5 is cryptographically broken — use SHA-256+'],
81
- [/createHash\s*\(\s*["']sha1["']/, 'medium', 'Weak Crypto', 'SHA-1 is deprecated — use SHA-256+'],
82
- [/Math\.random\s*\(/, 'low', 'Weak Randomness', 'Math.random() is not cryptographically secure — use crypto.randomBytes()'],
83
-
84
- // Auth Issues
85
- [/algorithms\s*:\s*\[\s*["']none["']/, 'critical', 'Auth Bypass', "JWT 'none' algorithm allows auth bypass"],
86
- [/verify\s*:\s*false/, 'high', 'Auth Bypass', 'SSL/TLS verification disabled'],
87
- [/rejectUnauthorized\s*:\s*false/, 'high', 'Auth Bypass', 'TLS certificate validation disabled'],
88
-
89
- // Information Disclosure
90
- [/console\.log\s*\(.*(?:password|secret|token|key)/i, 'medium', 'Info Disclosure', 'Sensitive data logged to console'],
91
- [/\.env(?:\.local|\.production)/, 'low', 'Info Disclosure', 'Env file reference — ensure not committed to git'],
92
- ];
93
-
94
-
95
- /**
96
- * Scan a single file for security patterns.
97
- * @param {string} filepath - Absolute path to the file.
98
- * @param {string} projectRoot - Project root for relative path computation.
99
- * @returns {Array<{severity:string, category:string, file:string, line:number, message:string, snippet:string}>}
100
- */
101
- function scanFile(filepath, projectRoot) {
102
- const findings = [];
103
- const relPath = path.relative(projectRoot, filepath);
104
-
105
- let content;
106
- try {
107
- content = fs.readFileSync(filepath, 'utf8');
108
- } catch {
109
- return findings;
110
- }
111
-
112
- const lines = content.split('\n');
113
- for (let i = 0; i < lines.length; i++) {
114
- const stripped = lines[i].trim();
115
- // Skip comments
116
- if (stripped.startsWith('//') || stripped.startsWith('#') || stripped.startsWith('*')) {
117
- continue;
118
- }
119
-
120
- for (const [pattern, severity, category, message] of PATTERNS) {
121
- if (pattern.test(stripped)) {
122
- findings.push({
123
- severity,
124
- category,
125
- file: relPath,
126
- line: i + 1,
127
- message,
128
- snippet: stripped.slice(0, 120),
129
- });
130
- }
131
- }
132
- }
133
-
134
- return findings;
135
- }
136
-
137
-
138
- /**
139
- * Recursively walk a directory yield file paths.
140
- * @param {string} dir - Directory to walk.
141
- * @param {Set<string>} skipDirs - Directory names to skip.
142
- * @returns {string[]} Array of file paths.
143
- */
144
- function walkDir(dir, skipDirs) {
145
- const results = [];
146
- let entries;
147
- try {
148
- entries = fs.readdirSync(dir, { withFileTypes: true });
149
- } catch {
150
- return results;
151
- }
152
-
153
- for (const entry of entries) {
154
- if (entry.isDirectory()) {
155
- if (!skipDirs.has(entry.name)) {
156
- results.push(...walkDir(path.join(dir, entry.name), skipDirs));
157
- }
158
- } else if (entry.isFile()) {
159
- results.push(path.join(dir, entry.name));
160
- }
161
- }
162
- return results;
163
- }
164
-
165
-
166
- /**
167
- * Scan all source files in a directory.
168
- * @param {string} projectRoot - Root directory to scan.
169
- * @param {string[]|null} targetFiles - Specific files to scan, or null for full scan.
170
- * @returns {Array} Array of finding objects.
171
- */
172
- function scanDirectory(projectRoot, targetFiles) {
173
- const allFindings = [];
174
-
175
- if (targetFiles && targetFiles.length > 0) {
176
- for (const fpath of targetFiles) {
177
- const absPath = path.isAbsolute(fpath) ? fpath : path.join(projectRoot, fpath);
178
- if (fs.existsSync(absPath) && fs.statSync(absPath).isFile()) {
179
- allFindings.push(...scanFile(absPath, projectRoot));
180
- }
181
- }
182
- return allFindings;
183
- }
184
-
185
- const files = walkDir(projectRoot, SKIP_DIRS);
186
- for (const filepath of files) {
187
- const ext = path.extname(filepath);
188
- if (!SOURCE_EXTENSIONS.has(ext)) continue;
189
- allFindings.push(...scanFile(filepath, projectRoot));
190
- }
191
-
192
- return allFindings;
193
- }
194
-
195
-
196
- /**
197
- * Print findings filtered by minimum severity. Returns count of displayed findings.
198
- */
199
- function printFindings(findings, minSeverity) {
200
- const minRank = SEVERITY_RANK[minSeverity] ?? 3;
201
- const filtered = findings
202
- .filter(f => (SEVERITY_RANK[f.severity] ?? 3) <= minRank)
203
- .sort((a, b) => (SEVERITY_RANK[a.severity] ?? 3) - (SEVERITY_RANK[b.severity] ?? 3));
204
-
205
- if (filtered.length === 0) {
206
- console.log(`\n ${GREEN}✅ No security issues found at severity '${minSeverity}' or above${RESET}`);
207
- return 0;
208
- }
209
-
210
- let currentCategory = '';
211
- for (const finding of filtered) {
212
- if (finding.category !== currentCategory) {
213
- currentCategory = finding.category;
214
- console.log(`\n ${BOLD}${currentCategory}${RESET}`);
215
- }
216
- const color = SEVERITY_COLORS[finding.severity] || '';
217
- console.log(` ${color}[${finding.severity.toUpperCase()}]${RESET} ${finding.file}:${finding.line}`);
218
- console.log(` ${finding.message}`);
219
- console.log(` ${MAGENTA}→ ${finding.snippet}${RESET}`);
220
- }
221
-
222
- return filtered.length;
223
- }
224
-
225
-
226
- /**
227
- * Parse CLI arguments manually (no external dependencies).
228
- */
229
- function parseArgs(argv) {
230
- const args = { path: null, severity: 'low', files: null };
231
- const raw = argv.slice(2);
232
-
233
- for (let i = 0; i < raw.length; i++) {
234
- if (raw[i] === '--severity' && raw[i + 1]) {
235
- args.severity = raw[++i];
236
- } else if (raw[i] === '--files') {
237
- args.files = [];
238
- while (i + 1 < raw.length && !raw[i + 1].startsWith('--')) {
239
- args.files.push(raw[++i]);
240
- }
241
- } else if (!raw[i].startsWith('--') && !args.path) {
242
- args.path = raw[i];
243
- }
244
- }
245
- return args;
246
- }
247
-
248
-
249
- function main() {
250
- const args = parseArgs(process.argv);
251
-
252
- if (!args.path) {
253
- console.error(`Usage: node security_scan.js <path> [--severity critical|high|medium|low] [--files ...]`);
254
- process.exit(1);
255
- }
256
-
257
- const projectRoot = path.resolve(args.path);
258
- if (!fs.existsSync(projectRoot) || !fs.statSync(projectRoot).isDirectory()) {
259
- console.error(` ${RED}❌ Directory not found: ${projectRoot}${RESET}`);
260
- process.exit(1);
261
- }
262
-
263
- console.log(`${BOLD}Tribunal — security_scan.js${RESET}`);
264
- console.log(`Project: ${projectRoot}`);
265
- console.log(`Severity filter: ${args.severity}+`);
266
-
267
- const findings = scanDirectory(projectRoot, args.files);
268
- const count = printFindings(findings, args.severity);
269
-
270
- // Summary
271
- console.log(`\n${BOLD}━━━ Security Scan Summary ━━━${RESET}`);
272
- const bySeverity = {};
273
- for (const f of findings) {
274
- bySeverity[f.severity] = (bySeverity[f.severity] || 0) + 1;
275
- }
276
-
277
- for (const sev of ['critical', 'high', 'medium', 'low']) {
278
- const c = bySeverity[sev] || 0;
279
- if (c > 0) {
280
- const color = SEVERITY_COLORS[sev] || '';
281
- console.log(` ${color}${sev.toUpperCase()}: ${c}${RESET}`);
282
- }
283
- }
284
-
285
- if (count === 0) {
286
- console.log(` ${GREEN}✅ No issues found — scan passed${RESET}`);
287
- } else {
288
- const criticalHigh = (bySeverity.critical || 0) + (bySeverity.high || 0);
289
- if (criticalHigh > 0) {
290
- console.log(`\n ${RED}${BOLD}⚠️ ${criticalHigh} critical/high issue(s) require immediate attention${RESET}`);
291
- }
292
- }
293
-
294
- process.exit((bySeverity.critical || 0) > 0 ? 1 : 0);
295
- }
296
-
297
-
298
- // ━━━ Exports for testing & programmatic use ━━━
299
- module.exports = { scanFile, scanDirectory, printFindings, PATTERNS, SEVERITY_RANK };
300
-
301
- if (require.main === module) {
302
- main();
303
- }
1
+ #!/usr/bin/env node
2
+ /**
3
+ * security_scan.js — Deep security scanner for the Tribunal Agent Kit.
4
+ *
5
+ * Checks for OWASP Top 10 patterns in source code:
6
+ * - Hardcoded secrets and credentials
7
+ * - SQL injection patterns (string concatenation in queries)
8
+ * - XSS-prone code (innerHTML, dangerouslySetInnerHTML)
9
+ * - Insecure eval() usage
10
+ * - Missing auth patterns
11
+ * - Insecure crypto usage
12
+ *
13
+ * ⚠️ DISCLAIMER: This is a heuristic regex-based pattern scanner, NOT a
14
+ * full static analysis tool. It may produce false positives (e.g., test
15
+ * fixtures containing 'password') and cannot detect indirect vulnerabilities
16
+ * (e.g., SQL injection via variable indirection). For production security
17
+ * auditing, supplement with dedicated tools like Semgrep, CodeQL, or Snyk.
18
+ *
19
+ * Usage:
20
+ * node .agent/scripts/security_scan.js .
21
+ * node .agent/scripts/security_scan.js . --severity high
22
+ * node .agent/scripts/security_scan.js . --files src/auth.ts src/db.ts
23
+ */
24
+
25
+ 'use strict';
26
+
27
+ const fs = require('fs');
28
+ const path = require('path');
29
+
30
+ // ━━━ ANSI colors ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
31
+ const RED = '\x1b[91m';
32
+ const GREEN = '\x1b[92m';
33
+ const YELLOW = '\x1b[93m';
34
+ const BLUE = '\x1b[94m';
35
+ const MAGENTA = '\x1b[95m';
36
+ const BOLD = '\x1b[1m';
37
+ const RESET = '\x1b[0m';
38
+
39
+ const SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.py', '.go', '.java', '.rb']);
40
+ const SKIP_DIRS = new Set([
41
+ 'node_modules', '.git', 'dist', 'build', '__pycache__', '.agent',
42
+ '.next', 'vendor', 'coverage', 'lcov-report', '.nyc_output',
43
+ 'test-results', '.jest-cache',
44
+ ]);
45
+
46
+ const SEVERITY_COLORS = {
47
+ critical: RED + BOLD,
48
+ high: RED,
49
+ medium: YELLOW,
50
+ low: BLUE,
51
+ };
52
+
53
+ const SEVERITY_RANK = { critical: 0, high: 1, medium: 2, low: 3 };
54
+
55
+ // Pattern definitions: [regex, severity, category, message]
56
+ const PATTERNS = [
57
+ // Secrets
58
+ [/(?:password|passwd|pwd)\s*=\s*["'][^"']+["']/i, 'critical', 'Hardcoded Secret', 'Hardcoded password detected'],
59
+ [/(?:api_key|apikey|api_secret)\s*=\s*["'][^"']+["']/i, 'critical', 'Hardcoded Secret', 'Hardcoded API key detected'],
60
+ [/(?:secret|token|auth_token)\s*=\s*["'][A-Za-z0-9+/=]{16,}["']/i, 'critical', 'Hardcoded Secret', 'Hardcoded secret/token detected'],
61
+ [/(?:PRIVATE_KEY|private_key)\s*=\s*["']/i, 'critical', 'Hardcoded Secret', 'Hardcoded private key detected'],
62
+
63
+ // SQL Injection
64
+ [/(?:query|execute|raw)\s*\(\s*[`"'].*\$\{/i, 'high', 'SQL Injection', 'String interpolation in SQL query — use parameterized queries'],
65
+ [/(?:query|execute|raw)\s*\(\s*["'].*\+\s*(?:req|input|params|body)/i, 'high', 'SQL Injection', 'String concatenation with user input in SQL'],
66
+ [/\.raw\s*\(\s*`/, 'medium', 'SQL Injection', 'Raw query with template literal — verify inputs are sanitized'],
67
+
68
+ // XSS
69
+ [/\.innerHTML\s*=/, 'high', 'XSS', 'Direct innerHTML assignment — use textContent or a sanitizer'],
70
+ [/dangerouslySetInnerHTML/, 'medium', 'XSS', 'dangerouslySetInnerHTML used — ensure input is sanitized'],
71
+ [/document\.write\s*\(/, 'high', 'XSS', 'document.write() is an XSS vector'],
72
+
73
+ // Insecure Functions
74
+ [/\beval\s*\(/, 'high', 'Code Injection', 'eval() is a code injection vector — avoid entirely'],
75
+ [/new\s+Function\s*\(/, 'high', 'Code Injection', 'new Function() is equivalent to eval()'],
76
+ [/child_process\.exec\s*\(/, 'medium', 'Command Injection', 'exec() with unsanitized input is a command injection vector'],
77
+ [/subprocess\.call\s*\(\s*[^,\]]*\bshell\s*=\s*True/, 'high', 'Command Injection', 'subprocess with shell=True — use shell=False and pass args as list'],
78
+
79
+ // Crypto
80
+ [/createHash\s*\(\s*["']md5["']/, 'medium', 'Weak Crypto', 'MD5 is cryptographically broken — use SHA-256+'],
81
+ [/createHash\s*\(\s*["']sha1["']/, 'medium', 'Weak Crypto', 'SHA-1 is deprecated — use SHA-256+'],
82
+ [/Math\.random\s*\(/, 'low', 'Weak Randomness', 'Math.random() is not cryptographically secure — use crypto.randomBytes()'],
83
+
84
+ // Auth Issues
85
+ [/algorithms\s*:\s*\[\s*["']none["']/, 'critical', 'Auth Bypass', "JWT 'none' algorithm allows auth bypass"],
86
+ [/verify\s*:\s*false/, 'high', 'Auth Bypass', 'SSL/TLS verification disabled'],
87
+ [/rejectUnauthorized\s*:\s*false/, 'high', 'Auth Bypass', 'TLS certificate validation disabled'],
88
+
89
+ // Information Disclosure
90
+ [/console\.log\s*\(.*(?:password|secret|token|key)/i, 'medium', 'Info Disclosure', 'Sensitive data logged to console'],
91
+ [/\.env(?:\.local|\.production)/, 'low', 'Info Disclosure', 'Env file reference — ensure not committed to git'],
92
+ ];
93
+
94
+
95
+ /**
96
+ * Scan a single file for security patterns.
97
+ * @param {string} filepath - Absolute path to the file.
98
+ * @param {string} projectRoot - Project root for relative path computation.
99
+ * @returns {Array<{severity:string, category:string, file:string, line:number, message:string, snippet:string}>}
100
+ */
101
+ function scanFile(filepath, projectRoot) {
102
+ const findings = [];
103
+ const relPath = path.relative(projectRoot, filepath);
104
+
105
+ let content;
106
+ try {
107
+ content = fs.readFileSync(filepath, 'utf8');
108
+ } catch {
109
+ return findings;
110
+ }
111
+
112
+ const lines = content.split('\n');
113
+ for (let i = 0; i < lines.length; i++) {
114
+ const stripped = lines[i].trim();
115
+ // Skip comments
116
+ if (stripped.startsWith('//') || stripped.startsWith('#') || stripped.startsWith('*')) {
117
+ continue;
118
+ }
119
+
120
+ for (const [pattern, severity, category, message] of PATTERNS) {
121
+ if (pattern.test(stripped)) {
122
+ findings.push({
123
+ severity,
124
+ category,
125
+ file: relPath,
126
+ line: i + 1,
127
+ message,
128
+ snippet: stripped.slice(0, 120),
129
+ });
130
+ }
131
+ }
132
+ }
133
+
134
+ return findings;
135
+ }
136
+
137
+
138
+ /**
139
+ * Recursively walk a directory yield file paths.
140
+ * @param {string} dir - Directory to walk.
141
+ * @param {Set<string>} skipDirs - Directory names to skip.
142
+ * @returns {string[]} Array of file paths.
143
+ */
144
+ function walkDir(dir, skipDirs) {
145
+ const results = [];
146
+ let entries;
147
+ try {
148
+ entries = fs.readdirSync(dir, { withFileTypes: true });
149
+ } catch {
150
+ return results;
151
+ }
152
+
153
+ for (const entry of entries) {
154
+ if (entry.isDirectory()) {
155
+ if (!skipDirs.has(entry.name)) {
156
+ results.push(...walkDir(path.join(dir, entry.name), skipDirs));
157
+ }
158
+ } else if (entry.isFile()) {
159
+ results.push(path.join(dir, entry.name));
160
+ }
161
+ }
162
+ return results;
163
+ }
164
+
165
+
166
+ /**
167
+ * Scan all source files in a directory.
168
+ * @param {string} projectRoot - Root directory to scan.
169
+ * @param {string[]|null} targetFiles - Specific files to scan, or null for full scan.
170
+ * @returns {Array} Array of finding objects.
171
+ */
172
+ function scanDirectory(projectRoot, targetFiles) {
173
+ const allFindings = [];
174
+
175
+ if (targetFiles && targetFiles.length > 0) {
176
+ for (const fpath of targetFiles) {
177
+ const absPath = path.isAbsolute(fpath) ? fpath : path.join(projectRoot, fpath);
178
+ if (fs.existsSync(absPath) && fs.statSync(absPath).isFile()) {
179
+ allFindings.push(...scanFile(absPath, projectRoot));
180
+ }
181
+ }
182
+ return allFindings;
183
+ }
184
+
185
+ const files = walkDir(projectRoot, SKIP_DIRS);
186
+ for (const filepath of files) {
187
+ const ext = path.extname(filepath);
188
+ if (!SOURCE_EXTENSIONS.has(ext)) continue;
189
+ allFindings.push(...scanFile(filepath, projectRoot));
190
+ }
191
+
192
+ return allFindings;
193
+ }
194
+
195
+
196
+ /**
197
+ * Print findings filtered by minimum severity. Returns count of displayed findings.
198
+ */
199
+ function printFindings(findings, minSeverity) {
200
+ const minRank = SEVERITY_RANK[minSeverity] ?? 3;
201
+ const filtered = findings
202
+ .filter(f => (SEVERITY_RANK[f.severity] ?? 3) <= minRank)
203
+ .sort((a, b) => (SEVERITY_RANK[a.severity] ?? 3) - (SEVERITY_RANK[b.severity] ?? 3));
204
+
205
+ if (filtered.length === 0) {
206
+ console.log(`\n ${GREEN}✅ No security issues found at severity '${minSeverity}' or above${RESET}`);
207
+ return 0;
208
+ }
209
+
210
+ let currentCategory = '';
211
+ for (const finding of filtered) {
212
+ if (finding.category !== currentCategory) {
213
+ currentCategory = finding.category;
214
+ console.log(`\n ${BOLD}${currentCategory}${RESET}`);
215
+ }
216
+ const color = SEVERITY_COLORS[finding.severity] || '';
217
+ console.log(` ${color}[${finding.severity.toUpperCase()}]${RESET} ${finding.file}:${finding.line}`);
218
+ console.log(` ${finding.message}`);
219
+ console.log(` ${MAGENTA}→ ${finding.snippet}${RESET}`);
220
+ }
221
+
222
+ return filtered.length;
223
+ }
224
+
225
+
226
+ /**
227
+ * Parse CLI arguments manually (no external dependencies).
228
+ */
229
+ function parseArgs(argv) {
230
+ const args = { path: null, severity: 'low', files: null };
231
+ const raw = argv.slice(2);
232
+
233
+ for (let i = 0; i < raw.length; i++) {
234
+ if (raw[i] === '--severity' && raw[i + 1]) {
235
+ args.severity = raw[++i];
236
+ } else if (raw[i] === '--files') {
237
+ args.files = [];
238
+ while (i + 1 < raw.length && !raw[i + 1].startsWith('--')) {
239
+ args.files.push(raw[++i]);
240
+ }
241
+ } else if (!raw[i].startsWith('--') && !args.path) {
242
+ args.path = raw[i];
243
+ }
244
+ }
245
+ return args;
246
+ }
247
+
248
+
249
+ function main() {
250
+ const args = parseArgs(process.argv);
251
+
252
+ if (!args.path) {
253
+ console.error(`Usage: node security_scan.js <path> [--severity critical|high|medium|low] [--files ...]`);
254
+ process.exit(1);
255
+ }
256
+
257
+ const projectRoot = path.resolve(args.path);
258
+ if (!fs.existsSync(projectRoot) || !fs.statSync(projectRoot).isDirectory()) {
259
+ console.error(` ${RED}❌ Directory not found: ${projectRoot}${RESET}`);
260
+ process.exit(1);
261
+ }
262
+
263
+ console.log(`${BOLD}Tribunal — security_scan.js${RESET}`);
264
+ console.log(`Project: ${projectRoot}`);
265
+ console.log(`Severity filter: ${args.severity}+`);
266
+
267
+ const findings = scanDirectory(projectRoot, args.files);
268
+ const count = printFindings(findings, args.severity);
269
+
270
+ // Summary
271
+ console.log(`\n${BOLD}━━━ Security Scan Summary ━━━${RESET}`);
272
+ const bySeverity = {};
273
+ for (const f of findings) {
274
+ bySeverity[f.severity] = (bySeverity[f.severity] || 0) + 1;
275
+ }
276
+
277
+ for (const sev of ['critical', 'high', 'medium', 'low']) {
278
+ const c = bySeverity[sev] || 0;
279
+ if (c > 0) {
280
+ const color = SEVERITY_COLORS[sev] || '';
281
+ console.log(` ${color}${sev.toUpperCase()}: ${c}${RESET}`);
282
+ }
283
+ }
284
+
285
+ if (count === 0) {
286
+ console.log(` ${GREEN}✅ No issues found — scan passed${RESET}`);
287
+ } else {
288
+ const criticalHigh = (bySeverity.critical || 0) + (bySeverity.high || 0);
289
+ if (criticalHigh > 0) {
290
+ console.log(`\n ${RED}${BOLD}⚠️ ${criticalHigh} critical/high issue(s) require immediate attention${RESET}`);
291
+ }
292
+ }
293
+
294
+ process.exit((bySeverity.critical || 0) > 0 ? 1 : 0);
295
+ }
296
+
297
+
298
+ // ━━━ Exports for testing & programmatic use ━━━
299
+ module.exports = { scanFile, scanDirectory, printFindings, PATTERNS, SEVERITY_RANK };
300
+
301
+ if (require.main === module) {
302
+ main();
303
+ }