devanvil 0.0.0-stage → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.ar.md +113 -0
  3. package/README.md +272 -2
  4. package/SECURITY.md +49 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +659 -0
  7. package/dist/core/contract-drift.d.ts +49 -0
  8. package/dist/core/contract-drift.js +302 -0
  9. package/dist/core/converters.d.ts +18 -0
  10. package/dist/core/converters.js +981 -0
  11. package/dist/core/cron.d.ts +33 -0
  12. package/dist/core/cron.js +306 -0
  13. package/dist/core/crypto.d.ts +59 -0
  14. package/dist/core/crypto.js +250 -0
  15. package/dist/core/curl.d.ts +17 -0
  16. package/dist/core/curl.js +170 -0
  17. package/dist/core/diff.d.ts +36 -0
  18. package/dist/core/diff.js +148 -0
  19. package/dist/core/encoding.d.ts +3 -0
  20. package/dist/core/encoding.js +143 -0
  21. package/dist/core/importers.d.ts +65 -0
  22. package/dist/core/importers.js +361 -0
  23. package/dist/core/jwt.d.ts +39 -0
  24. package/dist/core/jwt.js +256 -0
  25. package/dist/core/llm-tokens.d.ts +38 -0
  26. package/dist/core/llm-tokens.js +125 -0
  27. package/dist/core/log-analyzer.d.ts +30 -0
  28. package/dist/core/log-analyzer.js +155 -0
  29. package/dist/core/network.d.ts +72 -0
  30. package/dist/core/network.js +185 -0
  31. package/dist/core/oauth-protobuf.d.ts +74 -0
  32. package/dist/core/oauth-protobuf.js +390 -0
  33. package/dist/core/openapi.d.ts +27 -0
  34. package/dist/core/openapi.js +257 -0
  35. package/dist/core/pipeline.d.ts +28 -0
  36. package/dist/core/pipeline.js +154 -0
  37. package/dist/core/regex.d.ts +50 -0
  38. package/dist/core/regex.js +351 -0
  39. package/dist/core/runner.d.ts +53 -0
  40. package/dist/core/runner.js +250 -0
  41. package/dist/core/secrets.d.ts +87 -0
  42. package/dist/core/secrets.js +599 -0
  43. package/dist/core/security.d.ts +34 -0
  44. package/dist/core/security.js +284 -0
  45. package/dist/core/sql-explain.d.ts +50 -0
  46. package/dist/core/sql-explain.js +259 -0
  47. package/dist/core/tls.d.ts +44 -0
  48. package/dist/core/tls.js +166 -0
  49. package/dist/index.d.ts +31 -0
  50. package/dist/index.js +31 -0
  51. package/dist/server/app.d.ts +31 -0
  52. package/dist/server/app.js +348 -0
  53. package/dist/server/http-proxy.d.ts +55 -0
  54. package/dist/server/http-proxy.js +364 -0
  55. package/dist/server/http-utils.d.ts +28 -0
  56. package/dist/server/http-utils.js +106 -0
  57. package/dist/server/load-tester.d.ts +53 -0
  58. package/dist/server/load-tester.js +134 -0
  59. package/dist/server/mcp.d.ts +35 -0
  60. package/dist/server/mcp.js +466 -0
  61. package/dist/server/mock-store.d.ts +38 -0
  62. package/dist/server/mock-store.js +197 -0
  63. package/dist/server/plugin-loader.d.ts +60 -0
  64. package/dist/server/plugin-loader.js +285 -0
  65. package/dist/server/recorder-store.d.ts +35 -0
  66. package/dist/server/recorder-store.js +146 -0
  67. package/dist/server/routes/network-routes.d.ts +3 -0
  68. package/dist/server/routes/network-routes.js +391 -0
  69. package/dist/server/routes/tools-routes.d.ts +3 -0
  70. package/dist/server/routes/tools-routes.js +292 -0
  71. package/dist/server/routes/workspace-routes.d.ts +3 -0
  72. package/dist/server/routes/workspace-routes.js +240 -0
  73. package/dist/server/webhook-store.d.ts +29 -0
  74. package/dist/server/webhook-store.js +90 -0
  75. package/dist/server/workspace-store.d.ts +91 -0
  76. package/dist/server/workspace-store.js +447 -0
  77. package/dist/server/ws-probe.d.ts +34 -0
  78. package/dist/server/ws-probe.js +283 -0
  79. package/dist/ui/app.js +274 -0
  80. package/dist/ui/favicon.svg +14 -0
  81. package/dist/ui/index.html +83 -0
  82. package/dist/ui/logo.png +0 -0
  83. package/dist/ui/styles.css +694 -0
  84. package/dist/ui/tools-data.js +704 -0
  85. package/dist/ui/tools-network.js +727 -0
  86. package/dist/ui/tools-ops.js +295 -0
  87. package/dist/ui/tools-pro.js +500 -0
  88. package/dist/ui/tools-security.js +389 -0
  89. package/dist/ui/tools-v12.js +745 -0
  90. package/dist/ui/tools-v13.js +321 -0
  91. package/dist/ui/tools-v20.js +563 -0
  92. package/dist/ui/tools-v21.js +395 -0
  93. package/package.json +75 -4
@@ -0,0 +1,599 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { isDangerousKey } from './security.js';
5
+ // All rules are strictly linear-time (zero nested quantifiers / ReDoS-safe)
6
+ export const SECRET_RULES = [
7
+ { id: 'GITHUB_PAT', name: 'GitHub Personal Access Token', severity: 'critical', pattern: '\\bghp_[A-Za-z0-9]{30,64}\\b' },
8
+ { id: 'GITHUB_FINE_GRAINED', name: 'GitHub Fine-Grained PAT', severity: 'critical', pattern: '\\bgithub_pat_[A-Za-z0-9_]{30,120}\\b' },
9
+ { id: 'GITHUB_OAUTH', name: 'GitHub OAuth / App Token', severity: 'critical', pattern: '\\bgh[ousr]_[A-Za-z0-9]{30,64}\\b' },
10
+ { id: 'AWS_ACCESS_KEY', name: 'AWS Access Key ID', severity: 'critical', pattern: '\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b' },
11
+ { id: 'OPENAI_KEY', name: 'OpenAI API Key', severity: 'critical', pattern: '\\bsk-(?:proj-|live-|svcacct-)?[A-Za-z0-9_-]{24,120}\\b' },
12
+ { id: 'ANTHROPIC_KEY', name: 'Anthropic API Key', severity: 'critical', pattern: '\\bsk-ant-[A-Za-z0-9_-]{24,140}\\b' },
13
+ { id: 'GOOGLE_API_KEY', name: 'Google Cloud / Gemini API Key', severity: 'high', pattern: '\\bAIza[0-9A-Za-z_-]{35}\\b' },
14
+ { id: 'STRIPE_SECRET', name: 'Stripe Secret / Restricted Key', severity: 'critical', pattern: '\\b[sr]k_(?:live|test)_[0-9A-Za-z]{20,99}\\b' },
15
+ { id: 'SLACK_TOKEN', name: 'Slack API Token', severity: 'critical', pattern: '\\bxox[baprs]-[0-9A-Za-z-]{16,80}\\b' },
16
+ { id: 'SLACK_WEBHOOK', name: 'Slack Incoming Webhook URL', severity: 'high', pattern: 'https://hooks\\.slack\\.com/services/T[A-Z0-9]{6,}/B[A-Z0-9]{6,}/[A-Za-z0-9]{16,}' },
17
+ { id: 'DISCORD_WEBHOOK', name: 'Discord Webhook URL', severity: 'high', pattern: 'https://(?:ptb\\.|canary\\.)?discord(?:app)?\\.com/api/webhooks/\\d{15,22}/[A-Za-z0-9_-]{30,90}' },
18
+ { id: 'SENDGRID_KEY', name: 'SendGrid API Key', severity: 'critical', pattern: '\\bSG\\.[A-Za-z0-9_-]{16,32}\\.[A-Za-z0-9_-]{32,64}\\b' },
19
+ { id: 'NPM_TOKEN', name: 'npm Access Token', severity: 'critical', pattern: '\\bnpm_[A-Za-z0-9]{30,64}\\b' },
20
+ { id: 'PYPI_TOKEN', name: 'PyPI API Token', severity: 'critical', pattern: '\\bpypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{30,180}\\b' },
21
+ { id: 'PRIVATE_KEY_PEM', name: 'Private Cryptographic Key (PEM)', severity: 'critical', pattern: '-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-----' },
22
+ { id: 'DB_URI_CREDS', name: 'Database Connection String with Password', severity: 'critical', pattern: '\\b(?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\\+srv)?|rediss?)://[^\\s:/@]{1,64}:[^\\s/@]{4,128}@[^\\s/]+' },
23
+ { id: 'JWT_TOKEN', name: 'JSON Web Token (JWT)', severity: 'medium', pattern: '\\beyJ[A-Za-z0-9_-]{8,}\\.eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{10,}\\b' },
24
+ { id: 'GENERIC_SECRET_ASSIGN', name: 'Hardcoded Secret / Password Assignment', severity: 'high', pattern: '\\b(?:api[_-]?key|secret[_-]?key|access[_-]?token|auth[_-]?token|private[_-]?key|client[_-]?secret|db[_-]?password|password)\\s*[:=]\\s*["\']?([A-Za-z0-9_/+=-]{14,128})["\']?', flags: 'gi' },
25
+ ];
26
+ export function calculateShannonEntropy(value) {
27
+ if (!value.length)
28
+ return 0;
29
+ const counts = new Map();
30
+ for (const ch of value) {
31
+ counts.set(ch, (counts.get(ch) ?? 0) + 1);
32
+ }
33
+ let entropy = 0;
34
+ const len = value.length;
35
+ for (const c of counts.values()) {
36
+ const p = c / len;
37
+ entropy -= p * Math.log2(p);
38
+ }
39
+ return Math.round(entropy * 100) / 100;
40
+ }
41
+ function maskSecret(raw) {
42
+ if (raw.length <= 8)
43
+ return '****';
44
+ return `${raw.slice(0, 4)}…${raw.slice(-4)}`;
45
+ }
46
+ function buildLineOffsets(text) {
47
+ const offsets = [0];
48
+ for (let i = 0; i < text.length; i++) {
49
+ if (text[i] === '\n')
50
+ offsets.push(i + 1);
51
+ }
52
+ return offsets;
53
+ }
54
+ function indexToLineCol(offsets, index) {
55
+ let lo = 0;
56
+ let hi = offsets.length - 1;
57
+ while (lo <= hi) {
58
+ const mid = (lo + hi) >>> 1;
59
+ if (offsets[mid] <= index)
60
+ lo = mid + 1;
61
+ else
62
+ hi = mid - 1;
63
+ }
64
+ const lineIdx = Math.max(0, hi);
65
+ return { line: lineIdx + 1, column: index - offsets[lineIdx] + 1 };
66
+ }
67
+ export function scanSecrets(input, options = {}) {
68
+ if (input.length > 500_000) {
69
+ throw new Error('Secret scanner input exceeds 500,000 character safety limit');
70
+ }
71
+ const checkEntropy = options.checkHighEntropy !== false;
72
+ const entropyThreshold = options.entropyThreshold ?? 4.3;
73
+ const lineOffsets = buildLineOffsets(input);
74
+ const suppressedLines = new Set();
75
+ const splitLines = input.split('\n');
76
+ for (let i = 0; i < splitLines.length; i++) {
77
+ const ln = splitLines[i];
78
+ if (/devanvil[-:]ignore-next-line/i.test(ln)) {
79
+ suppressedLines.add(i + 2); // 1-based next line
80
+ }
81
+ else if (/devanvil[-:]ignore\b/i.test(ln)) {
82
+ suppressedLines.add(i + 1); // 1-based current line
83
+ }
84
+ }
85
+ const rawFindings = [];
86
+ for (const rule of SECRET_RULES) {
87
+ const flags = rule.flags ?? 'g';
88
+ const re = new RegExp(rule.pattern, flags.includes('g') ? flags : `${flags}g`);
89
+ let m;
90
+ while ((m = re.exec(input)) !== null) {
91
+ const matched = m[1] ?? m[0];
92
+ const matchStart = m[1] ? m.index + m[0].indexOf(m[1]) : m.index;
93
+ const matchEnd = matchStart + matched.length;
94
+ // Skip obvious placeholders in generic rule
95
+ if (rule.id === 'GENERIC_SECRET_ASSIGN' &&
96
+ /^(?:your[_-]|changeme|example|placeholder|redacted|xxxxxxxx|00000000|\$\{|process\.env)/i.test(matched)) {
97
+ if (m[0].length === 0)
98
+ re.lastIndex++;
99
+ continue;
100
+ }
101
+ const loc = indexToLineCol(lineOffsets, matchStart);
102
+ if (suppressedLines.has(loc.line)) {
103
+ if (m[0].length === 0)
104
+ re.lastIndex++;
105
+ continue;
106
+ }
107
+ rawFindings.push({
108
+ ruleId: rule.id,
109
+ name: rule.name,
110
+ severity: rule.severity,
111
+ line: loc.line,
112
+ column: loc.column,
113
+ start: matchStart,
114
+ end: matchEnd,
115
+ masked: maskSecret(matched),
116
+ entropy: calculateShannonEntropy(matched),
117
+ });
118
+ if (m[0].length === 0)
119
+ re.lastIndex++;
120
+ }
121
+ }
122
+ function isLikelySequentialAlphabet(s) {
123
+ if (s.includes('0123456789') || s.includes('ABCDEFGH') || s.includes('abcdefgh') || s.includes('QWERTYUI')) {
124
+ return true;
125
+ }
126
+ // Check long ascending ASCII runs (e.g. Base32/Base64/NanoID charset tables)
127
+ let run = 1;
128
+ let maxRun = 1;
129
+ for (let i = 1; i < s.length; i++) {
130
+ if (s.charCodeAt(i) === s.charCodeAt(i - 1) + 1) {
131
+ run++;
132
+ if (run > maxRun)
133
+ maxRun = run;
134
+ }
135
+ else {
136
+ run = 1;
137
+ }
138
+ }
139
+ return maxRun >= 7;
140
+ }
141
+ // Optional high-entropy quoted/assigned token scan
142
+ if (checkEntropy) {
143
+ const entropyRe = /["'=\s]([A-Za-z0-9_/+=-]{24,96})["'\s,;]?/g;
144
+ let m;
145
+ while ((m = entropyRe.exec(input)) !== null) {
146
+ const candidate = m[1];
147
+ const start = m.index + m[0].indexOf(candidate);
148
+ const end = start + candidate.length;
149
+ // Ignore file paths, pure hex hashes, URLs, charset alphabets, or already-covered spans
150
+ if (candidate.includes('/') && candidate.split('/').length > 3)
151
+ continue;
152
+ if (/^[0-9a-f]{32,64}$/i.test(candidate))
153
+ continue;
154
+ if (isLikelySequentialAlphabet(candidate))
155
+ continue;
156
+ if (rawFindings.some((f) => start < f.end && end > f.start))
157
+ continue;
158
+ const hasMixedClasses = /[a-z]/.test(candidate) && /[A-Z]/.test(candidate) && /\d/.test(candidate);
159
+ const ent = calculateShannonEntropy(candidate);
160
+ if (hasMixedClasses && ent >= entropyThreshold) {
161
+ const loc = indexToLineCol(lineOffsets, start);
162
+ if (suppressedLines.has(loc.line))
163
+ continue;
164
+ rawFindings.push({
165
+ ruleId: 'HIGH_ENTROPY_TOKEN',
166
+ name: 'High-Entropy Secret Candidate',
167
+ severity: 'medium',
168
+ line: loc.line,
169
+ column: loc.column,
170
+ start,
171
+ end,
172
+ masked: maskSecret(candidate),
173
+ entropy: ent,
174
+ });
175
+ }
176
+ }
177
+ }
178
+ // Sort by position and remove overlapping lower-priority duplicates
179
+ const sevRank = { critical: 3, high: 2, medium: 1 };
180
+ rawFindings.sort((a, b) => a.start - b.start || sevRank[b.severity] - sevRank[a.severity]);
181
+ const findings = [];
182
+ for (const f of rawFindings) {
183
+ const prev = findings[findings.length - 1];
184
+ if (prev && f.start < prev.end) {
185
+ if (sevRank[f.severity] > sevRank[prev.severity]) {
186
+ findings[findings.length - 1] = f;
187
+ }
188
+ continue;
189
+ }
190
+ findings.push(f);
191
+ }
192
+ // Build redacted output cleanly from right to left
193
+ let redacted = input;
194
+ for (let i = findings.length - 1; i >= 0; i--) {
195
+ const f = findings[i];
196
+ redacted = `${redacted.slice(0, f.start)}[REDACTED:${f.ruleId}]${redacted.slice(f.end)}`;
197
+ }
198
+ const summary = {
199
+ critical: findings.filter((f) => f.severity === 'critical').length,
200
+ high: findings.filter((f) => f.severity === 'high').length,
201
+ medium: findings.filter((f) => f.severity === 'medium').length,
202
+ };
203
+ return {
204
+ clean: findings.length === 0,
205
+ totalFindings: findings.length,
206
+ summary,
207
+ findings,
208
+ redactedText: redacted,
209
+ };
210
+ }
211
+ function parseEnvEntries(content) {
212
+ const map = new Map();
213
+ const issues = [];
214
+ const lines = content.replace(/\r\n/g, '\n').split('\n');
215
+ lines.forEach((rawLine, i) => {
216
+ const lineNum = i + 1;
217
+ const trimmed = rawLine.trim();
218
+ if (!trimmed || trimmed.startsWith('#'))
219
+ return;
220
+ const cleanLine = trimmed.startsWith('export ') ? trimmed.slice(7).trim() : trimmed;
221
+ const eq = cleanLine.indexOf('=');
222
+ if (eq <= 0) {
223
+ issues.push({ line: lineNum, severity: 'error', message: `Malformed .env line (missing "="): "${trimmed.slice(0, 40)}"` });
224
+ return;
225
+ }
226
+ const key = cleanLine.slice(0, eq).trim();
227
+ const rawVal = cleanLine.slice(eq + 1).trim();
228
+ if (isDangerousKey(key)) {
229
+ issues.push({ line: lineNum, key, severity: 'error', message: `Forbidden prototype key "${key}"` });
230
+ return;
231
+ }
232
+ if (!/^[A-Z_][A-Z0-9_]*$/i.test(key)) {
233
+ issues.push({ line: lineNum, key, severity: 'warning', message: `Non-standard env key name "${key}"` });
234
+ }
235
+ if (map.has(key)) {
236
+ issues.push({ line: lineNum, key, severity: 'warning', message: `Duplicate key "${key}" (overrides line ${map.get(key).line})` });
237
+ }
238
+ if (rawVal === '') {
239
+ issues.push({ line: lineNum, key, severity: 'info', message: `Empty value for "${key}"` });
240
+ }
241
+ else if (!rawVal.startsWith('"') && !rawVal.startsWith("'") && /\s/.test(rawVal) && !rawVal.includes('#')) {
242
+ issues.push({ line: lineNum, key, severity: 'warning', message: `Unquoted whitespace in value for "${key}" — wrap in quotes` });
243
+ }
244
+ map.set(key, { value: rawVal, line: lineNum });
245
+ });
246
+ return { map, issues };
247
+ }
248
+ export function analyzeEnvFile(envContent, exampleContent) {
249
+ const target = parseEnvEntries(envContent);
250
+ const issues = [...target.issues];
251
+ const missingFromTarget = [];
252
+ const extraInTarget = [];
253
+ if (exampleContent && exampleContent.trim().length > 0) {
254
+ const example = parseEnvEntries(exampleContent);
255
+ for (const k of example.map.keys()) {
256
+ if (!target.map.has(k))
257
+ missingFromTarget.push(k);
258
+ }
259
+ for (const k of target.map.keys()) {
260
+ if (!example.map.has(k))
261
+ extraInTarget.push(k);
262
+ }
263
+ if (missingFromTarget.length > 0) {
264
+ issues.push({
265
+ line: 0,
266
+ severity: 'error',
267
+ message: `Missing ${missingFromTarget.length} key(s) defined in .env.example: ${missingFromTarget.join(', ')}`,
268
+ });
269
+ }
270
+ }
271
+ const secretScan = scanSecrets(envContent, { checkHighEntropy: false });
272
+ return {
273
+ keys: Array.from(target.map.keys()),
274
+ valuesCount: target.map.size,
275
+ issues,
276
+ missingFromTarget,
277
+ extraInTarget,
278
+ secretFindingsCount: secretScan.totalFindings,
279
+ };
280
+ }
281
+ const DEFAULT_SKIP_DIRS = new Set([
282
+ '.git',
283
+ 'node_modules',
284
+ 'dist',
285
+ 'dist-test',
286
+ 'build',
287
+ 'coverage',
288
+ '.next',
289
+ '.nuxt',
290
+ '.venv',
291
+ '__pycache__',
292
+ 'target',
293
+ 'vendor',
294
+ '.cache',
295
+ ]);
296
+ const BINARY_EXTS = new Set([
297
+ '.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico', '.pdf', '.zip', '.gz', '.tar', '.tgz',
298
+ '.woff', '.woff2', '.ttf', '.otf', '.eot', '.mp3', '.mp4', '.mov', '.wasm', '.exe', '.dll', '.so', '.dylib',
299
+ ]);
300
+ function parseIgnoreFile(ignorePath) {
301
+ if (!fs.existsSync(ignorePath))
302
+ return [];
303
+ try {
304
+ const raw = fs.readFileSync(ignorePath, 'utf8');
305
+ const regexes = [];
306
+ for (const line of raw.split(/\r?\n/)) {
307
+ const trimmed = line.trim();
308
+ if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('!'))
309
+ continue;
310
+ const clean = trimmed.replace(/^\/+/, '').replace(/\/+$/, '');
311
+ if (!clean)
312
+ continue;
313
+ const escaped = clean
314
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
315
+ .replace(/\*\*/g, '.*')
316
+ .replace(/\*/g, '[^/]*');
317
+ regexes.push(new RegExp(`(^|/)${escaped}($|/)`));
318
+ }
319
+ return regexes;
320
+ }
321
+ catch {
322
+ return [];
323
+ }
324
+ }
325
+ function loadIgnoreMatchers(rootDir, respectGitignore) {
326
+ const out = [];
327
+ if (respectGitignore) {
328
+ out.push(...parseIgnoreFile(path.join(rootDir, '.gitignore')));
329
+ }
330
+ // Always honor .devanvilignore if present
331
+ out.push(...parseIgnoreFile(path.join(rootDir, '.devanvilignore')));
332
+ return out;
333
+ }
334
+ export function scanDirectory(targetDir, options) {
335
+ const rootDir = path.resolve(targetDir);
336
+ if (!fs.existsSync(rootDir)) {
337
+ throw new Error(`Directory not found: ${targetDir}`);
338
+ }
339
+ const stat = fs.statSync(rootDir);
340
+ const maxFiles = Math.min(Math.max(options?.maxFiles ?? 2000, 1), 10_000);
341
+ const maxFileBytes = Math.min(Math.max(options?.maxFileBytes ?? 512 * 1024, 1024), 4 * 1024 * 1024);
342
+ const respectGitignore = options?.respectGitignore !== false;
343
+ const findings = [];
344
+ let scannedFiles = 0;
345
+ let skippedFiles = 0;
346
+ if (stat.isFile()) {
347
+ const content = fs.readFileSync(rootDir, 'utf8');
348
+ const res = scanSecrets(content, { checkHighEntropy: options?.checkHighEntropy !== false });
349
+ scannedFiles = 1;
350
+ for (const f of res.findings) {
351
+ findings.push({ ...f, file: path.basename(rootDir) });
352
+ }
353
+ return {
354
+ rootDir: path.dirname(rootDir),
355
+ scannedFiles,
356
+ skippedFiles,
357
+ clean: findings.length === 0,
358
+ totalFindings: findings.length,
359
+ summary: res.summary,
360
+ findings,
361
+ };
362
+ }
363
+ const ignorePatterns = loadIgnoreMatchers(rootDir, respectGitignore);
364
+ function walk(currentDir, depth) {
365
+ if (depth > 20 || scannedFiles >= maxFiles)
366
+ return;
367
+ let entries;
368
+ try {
369
+ entries = fs.readdirSync(currentDir, { withFileTypes: true });
370
+ }
371
+ catch {
372
+ return;
373
+ }
374
+ for (const entry of entries) {
375
+ if (scannedFiles >= maxFiles)
376
+ break;
377
+ const fullPath = path.join(currentDir, entry.name);
378
+ const relPosix = path.relative(rootDir, fullPath).split(path.sep).join('/');
379
+ if (entry.isSymbolicLink()) {
380
+ skippedFiles++;
381
+ continue;
382
+ }
383
+ if (entry.isDirectory()) {
384
+ if (DEFAULT_SKIP_DIRS.has(entry.name)) {
385
+ skippedFiles++;
386
+ continue;
387
+ }
388
+ if (ignorePatterns.some((re) => re.test(relPosix))) {
389
+ skippedFiles++;
390
+ continue;
391
+ }
392
+ walk(fullPath, depth + 1);
393
+ continue;
394
+ }
395
+ if (!entry.isFile())
396
+ continue;
397
+ const ext = path.extname(entry.name).toLowerCase();
398
+ if (BINARY_EXTS.has(ext) || entry.name === 'package-lock.json') {
399
+ skippedFiles++;
400
+ continue;
401
+ }
402
+ if (ignorePatterns.some((re) => re.test(relPosix))) {
403
+ skippedFiles++;
404
+ continue;
405
+ }
406
+ let fileStat;
407
+ try {
408
+ fileStat = fs.statSync(fullPath);
409
+ }
410
+ catch {
411
+ skippedFiles++;
412
+ continue;
413
+ }
414
+ if (fileStat.size === 0 || fileStat.size > maxFileBytes) {
415
+ skippedFiles++;
416
+ continue;
417
+ }
418
+ let buf;
419
+ try {
420
+ buf = fs.readFileSync(fullPath);
421
+ }
422
+ catch {
423
+ skippedFiles++;
424
+ continue;
425
+ }
426
+ // Binary sniff (check first 4KB for NUL bytes)
427
+ const sniffLen = Math.min(buf.length, 4096);
428
+ let isBinary = false;
429
+ for (let i = 0; i < sniffLen; i++) {
430
+ if (buf[i] === 0) {
431
+ isBinary = true;
432
+ break;
433
+ }
434
+ }
435
+ if (isBinary) {
436
+ skippedFiles++;
437
+ continue;
438
+ }
439
+ scannedFiles++;
440
+ const text = buf.toString('utf8');
441
+ const res = scanSecrets(text, { checkHighEntropy: options?.checkHighEntropy !== false });
442
+ for (const f of res.findings) {
443
+ findings.push({ ...f, file: relPosix });
444
+ }
445
+ }
446
+ }
447
+ walk(rootDir, 0);
448
+ return {
449
+ rootDir,
450
+ scannedFiles,
451
+ skippedFiles,
452
+ clean: findings.length === 0,
453
+ totalFindings: findings.length,
454
+ summary: {
455
+ critical: findings.filter((f) => f.severity === 'critical').length,
456
+ high: findings.filter((f) => f.severity === 'high').length,
457
+ medium: findings.filter((f) => f.severity === 'medium').length,
458
+ },
459
+ findings,
460
+ };
461
+ }
462
+ /**
463
+ * Scans ONLY files currently staged in the Git index (`git diff --cached`),
464
+ * reading each staged blob directly via `git show :<file>` so unstaged working-tree edits
465
+ * never cause false alarms in pre-commit hooks. Honors `.devanvilignore` and inline `devanvil-ignore`.
466
+ */
467
+ export function scanGitStaged(targetDir = '.', options) {
468
+ const rootDir = path.resolve(targetDir);
469
+ const maxFileBytes = Math.min(Math.max(options?.maxFileBytes ?? 512 * 1024, 1024), 4 * 1024 * 1024);
470
+ const ignorePatterns = parseIgnoreFile(path.join(rootDir, '.devanvilignore'));
471
+ let rawList;
472
+ try {
473
+ rawList = execFileSync('git', ['diff', '--cached', '--name-only', '--diff-filter=ACMR', '-z'], {
474
+ cwd: rootDir,
475
+ encoding: 'utf8',
476
+ maxBuffer: 8 * 1024 * 1024,
477
+ });
478
+ }
479
+ catch (err) {
480
+ throw new Error(`Failed to list Git staged files in ${rootDir}: ${err instanceof Error ? err.message : String(err)}`);
481
+ }
482
+ const stagedFiles = rawList.split('\0').filter(Boolean);
483
+ const findings = [];
484
+ let scannedFiles = 0;
485
+ let skippedFiles = 0;
486
+ for (const relPosix of stagedFiles) {
487
+ const ext = path.extname(relPosix).toLowerCase();
488
+ if (BINARY_EXTS.has(ext) || path.basename(relPosix) === 'package-lock.json') {
489
+ skippedFiles++;
490
+ continue;
491
+ }
492
+ if (ignorePatterns.some((re) => re.test(relPosix))) {
493
+ skippedFiles++;
494
+ continue;
495
+ }
496
+ let buf;
497
+ try {
498
+ buf = execFileSync('git', ['show', `:${relPosix}`], {
499
+ cwd: rootDir,
500
+ maxBuffer: maxFileBytes + 64 * 1024,
501
+ });
502
+ }
503
+ catch {
504
+ skippedFiles++;
505
+ continue;
506
+ }
507
+ if (buf.length === 0 || buf.length > maxFileBytes) {
508
+ skippedFiles++;
509
+ continue;
510
+ }
511
+ const sniffLen = Math.min(buf.length, 4096);
512
+ let isBinary = false;
513
+ for (let i = 0; i < sniffLen; i++) {
514
+ if (buf[i] === 0) {
515
+ isBinary = true;
516
+ break;
517
+ }
518
+ }
519
+ if (isBinary) {
520
+ skippedFiles++;
521
+ continue;
522
+ }
523
+ scannedFiles++;
524
+ const res = scanSecrets(buf.toString('utf8'), { checkHighEntropy: options?.checkHighEntropy !== false });
525
+ for (const f of res.findings) {
526
+ findings.push({ ...f, file: relPosix });
527
+ }
528
+ }
529
+ return {
530
+ rootDir,
531
+ scannedFiles,
532
+ skippedFiles,
533
+ clean: findings.length === 0,
534
+ totalFindings: findings.length,
535
+ summary: {
536
+ critical: findings.filter((f) => f.severity === 'critical').length,
537
+ high: findings.filter((f) => f.severity === 'high').length,
538
+ medium: findings.filter((f) => f.severity === 'medium').length,
539
+ },
540
+ findings,
541
+ };
542
+ }
543
+ /**
544
+ * Formats directory or single-file secret scan findings into valid SARIF 2.1.0 JSON
545
+ * for direct upload to GitHub Code Scanning (`github/codeql-action/upload-sarif`).
546
+ * Raw secrets are NEVER written into SARIF — only masked fingerprints.
547
+ */
548
+ export function formatSecretsAsSarif(findings, toolVersion = '1.2.0') {
549
+ const rulesMap = new Map();
550
+ for (const r of SECRET_RULES) {
551
+ rulesMap.set(r.id, { id: r.id, name: r.name, severity: r.severity });
552
+ }
553
+ rulesMap.set('HIGH_ENTROPY_SECRET', {
554
+ id: 'HIGH_ENTROPY_SECRET',
555
+ name: 'High-Entropy Secret Assignment',
556
+ severity: 'high',
557
+ });
558
+ const levelFor = (sev) => sev === 'critical' ? 'error' : sev === 'high' ? 'warning' : 'note';
559
+ return {
560
+ $schema: 'https://json.schemastore.org/sarif-2.1.0.json',
561
+ version: '2.1.0',
562
+ runs: [
563
+ {
564
+ tool: {
565
+ driver: {
566
+ name: 'DevAnvil Secret Guard',
567
+ version: toolVersion,
568
+ informationUri: 'https://github.com/abd77o/devanvil',
569
+ rules: Array.from(rulesMap.values()).map((r) => ({
570
+ id: r.id,
571
+ name: r.id,
572
+ shortDescription: { text: r.name },
573
+ defaultConfiguration: { level: levelFor(r.severity) },
574
+ properties: { tags: ['security', 'secrets'] },
575
+ })),
576
+ },
577
+ },
578
+ results: findings.map((f) => ({
579
+ ruleId: f.ruleId,
580
+ level: levelFor(f.severity),
581
+ message: {
582
+ text: `Potential leaked secret (${f.name}): masked fingerprint "${f.masked}" (Shannon entropy ${f.entropy})`,
583
+ },
584
+ locations: [
585
+ {
586
+ physicalLocation: {
587
+ artifactLocation: { uri: f.file || 'stdin' },
588
+ region: {
589
+ startLine: Math.max(1, f.line),
590
+ startColumn: Math.max(1, f.column),
591
+ },
592
+ },
593
+ },
594
+ ],
595
+ })),
596
+ },
597
+ ],
598
+ };
599
+ }
@@ -0,0 +1,34 @@
1
+ export declare function isDangerousKey(key: string): boolean;
2
+ export declare const DEFAULT_MAX_BODY_BYTES: number;
3
+ export declare const DEFAULT_MAX_DECOMPRESS_BYTES: number;
4
+ /**
5
+ * Recursively clones plain data structures while stripping prototype-pollution keys.
6
+ */
7
+ export declare function sanitizeObject<T>(value: T, maxDepth?: number, depth?: number): T;
8
+ export declare function safeJsonParse<T = unknown>(input: string, maxBytes?: number): T;
9
+ /**
10
+ * Constant-time string comparison that hides both content and length differences.
11
+ */
12
+ export declare function timingSafeEqualStr(a: string, b: string): boolean;
13
+ export declare function escapeHtml(input: string): string;
14
+ export declare function assertSafeChannelName(channel: string): string;
15
+ /**
16
+ * Checks whether an IPv4 or IPv6 address belongs to a private, loopback,
17
+ * link-local, metadata, multicast, or reserved network range.
18
+ */
19
+ export declare function isPrivateIp(rawIp: string): boolean;
20
+ export interface ValidatedProxyTarget {
21
+ url: URL;
22
+ resolvedAddress: string;
23
+ family: 4 | 6;
24
+ }
25
+ /**
26
+ * Validates an outbound proxy URL against SSRF, protocol smuggling, and DNS rebinding.
27
+ */
28
+ export declare function validateProxyTargetUrl(rawUrl: string, options?: {
29
+ allowPrivate?: boolean;
30
+ }): Promise<ValidatedProxyTarget>;
31
+ /**
32
+ * Same-origin guard for mutating API endpoints when browsers include an Origin header.
33
+ */
34
+ export declare function isOriginAllowed(origin: string | undefined, hostHeader: string | undefined): boolean;