burnoff 1.3.0 → 1.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.
@@ -1,1676 +1,1705 @@
1
- /**
2
- * @file src/guards/shell-guard.mjs
3
- * Deterministic Shell & Git Safety, Secret Boundary, and Protected File Ask-Gate (`DET-01`..`DET-03`).
4
- * Zero external dependencies.
5
- */
6
-
7
- export const SHELL_TOOL_REGEX = /^(Bash|PowerShell|pwsh|cmd|sh|run_command|execute_bash)$/i;
8
- export const EDIT_WRITE_TOOL_REGEX = /^(Edit|Write|MultiEdit|NotebookEdit)$/i;
9
- export const SEARCH_READ_TOOL_REGEX = /^(Read|Grep|Glob|read_file|grep_search)$/i;
10
-
11
- const GIT_GLOBAL_OPTS_WITH_ARG = new Set([
12
- '-c',
13
- '-C',
14
- '--git-dir',
15
- '--work-tree',
16
- '--namespace',
17
- '--super-prefix',
18
- '--config-env'
19
- ]);
20
-
21
- const GIT_COMMIT_OPTS_WITH_ARG = new Set([
22
- '-m',
23
- '--message',
24
- '-F',
25
- '--file',
26
- '-c',
27
- '--reedit-message',
28
- '-C',
29
- '--reuse-message',
30
- '--author',
31
- '--date',
32
- '--cleanup',
33
- '-t',
34
- '--template'
35
- ]);
36
-
37
- const GIT_CONFIG_OPTS_WITH_ARG = new Set([
38
- '-f',
39
- '--file',
40
- '--blob',
41
- '--type',
42
- '-t',
43
- '--default',
44
- '--comment',
45
- '--fixed-value'
46
- ]);
47
-
48
- const VALID_GIT_COMMIT_UNTRACKED_MODES = new Set(['', 'no', 'normal', 'all']);
49
- const SHORT_COMMIT_ARG_CHARS = new Set(['m', 'F', 'c', 'C', 't']);
50
-
51
- const SAFE_ENV_ALLOWLIST_REGEX =
52
- /(?:^|[\\/])\.env\.(?:example|sample|template|defaults|schema)$/i;
53
-
54
- const SECRET_FILE_PATTERNS = [
55
- /(?:^|[\\/])\.env(?:\.[a-zA-Z0-9._-]+)?$/i,
56
- /\.(?:pem|key|p12|pfx|crt)$/i,
57
- /(?:^|[\\/])id_(?:rsa|ed25519|ecdsa|dsa)(?:\.pub)?$/i,
58
- /(?:^|[\\/])\.(?:ssh|aws)[\\/]/i,
59
- /(?:^|[\\/])\.(?:npmrc|netrc|pypirc)$/i
60
- ];
61
-
62
- const SECRET_READ_EXFIL_BINS = new Set([
63
- 'cat',
64
- 'head',
65
- 'tail',
66
- 'less',
67
- 'more',
68
- 'bat',
69
- 'nl',
70
- 'tac',
71
- 'od',
72
- 'xxd',
73
- 'hexdump',
74
- 'strings',
75
- 'base64',
76
- 'grep',
77
- 'egrep',
78
- 'fgrep',
79
- 'rg',
80
- 'ag',
81
- 'awk',
82
- 'sed',
83
- 'cut',
84
- 'sort',
85
- 'uniq',
86
- 'wc',
87
- 'diff',
88
- 'tr',
89
- 'tee',
90
- 'get-content',
91
- 'gc',
92
- 'type',
93
- 'select-string',
94
- 'curl',
95
- 'wget',
96
- 'scp',
97
- 'rsync',
98
- 'sftp',
99
- 'ftp',
100
- 'nc',
101
- 'ncat',
102
- 'socat',
103
- 'source',
104
- '.',
105
- 'node',
106
- 'python',
107
- 'python3',
108
- 'perl',
109
- 'ruby',
110
- 'bash',
111
- 'sh',
112
- 'zsh',
113
- 'pwsh',
114
- 'powershell'
115
- ]);
116
-
117
- const COPY_MOVE_BINS = new Set([
118
- 'cp',
119
- 'mv',
120
- 'install',
121
- 'copy-item',
122
- 'move-item',
123
- 'cpi',
124
- 'mi'
125
- ]);
126
-
127
- const BENIGN_GIT_SUBCOMMANDS = new Set(['status', 'diff', 'log', 'branch']);
128
-
129
- const PROTECTED_EDIT_PATTERNS = [
130
- /(?:^|[\\/])migrations[\\/]/i,
131
- /(?:^|[\\/])prisma[\\/]migrations[\\/]/i,
132
- /(?:^|[\\/])(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|poetry\.lock|go\.sum)$/i,
133
- /(?:^|[\\/])\.github[\\/]workflows[\\/]/i
134
- ];
135
-
136
- function detectPowerShellSyntax(toolName = 'Bash', command = '') {
137
- if (/^(?:PowerShell|pwsh)$/i.test(String(toolName || ''))) {
138
- return true;
139
- }
140
- const str = String(command || '');
141
- return /(?:^|[;|&\r\n]\s*)&\s*['"A-Za-z0-9_.\\/]|(?:\$env:[A-Za-z_])|(?:`--|`-[A-Za-z])/i.test(
142
- str
143
- );
144
- }
145
-
146
- /**
147
- * Tokenizes a shell command line into tokens while preserving quoted strings as single tokens.
148
- * Supports both POSIX backslash escapes and PowerShell backtick escapes / `&` call operator.
149
- */
150
- export function tokenizeShellSegment(commandSegment = '', options = {}) {
151
- const tokens = [];
152
- const str = String(commandSegment || '').trim();
153
- const isPowerShell = Boolean(options?.isPowerShell);
154
- let current = '';
155
- let quoteChar = null;
156
-
157
- for (let i = 0; i < str.length; i++) {
158
- const ch = str[i];
159
- if (quoteChar === "'") {
160
- if (ch === "'") {
161
- if (isPowerShell && str[i + 1] === "'") {
162
- current += "'";
163
- i += 1;
164
- } else {
165
- quoteChar = null;
166
- }
167
- } else {
168
- current += ch;
169
- }
170
- } else if (quoteChar === '"') {
171
- if (isPowerShell && ch === '`' && i + 1 < str.length) {
172
- const next = str[i + 1];
173
- current += next === 'n' ? '\n' : next === 'r' ? '\r' : next === 't' ? '\t' : next;
174
- i += 1;
175
- } else if (!isPowerShell && ch === '\\' && i + 1 < str.length && ['"', '\\', '$', '`'].includes(str[i + 1])) {
176
- current += str[i + 1];
177
- i += 1;
178
- } else if (isPowerShell && ch === '\\' && str[i + 1] === '"') {
179
- current += '"';
180
- i += 1;
181
- } else if (ch === '"') {
182
- quoteChar = null;
183
- } else {
184
- current += ch;
185
- }
186
- } else if (ch === '"' || ch === "'") {
187
- quoteChar = ch;
188
- } else if (isPowerShell && ch === '`' && i + 1 < str.length) {
189
- const next = str[i + 1];
190
- current += next === 'n' ? '\n' : next === 'r' ? '\r' : next === 't' ? '\t' : next;
191
- i += 1;
192
- } else if (!isPowerShell && ch === '\\' && i + 1 < str.length) {
193
- current += str[i + 1];
194
- i += 1;
195
- } else if (current.length === 0 && ch === '&' && str[i + 1] !== '&' && str[i + 1] !== '>') {
196
- tokens.push('&');
197
- } else if (/\s/.test(ch)) {
198
- if (current.length > 0) {
199
- tokens.push(current);
200
- current = '';
201
- }
202
- } else {
203
- current += ch;
204
- }
205
- }
206
- if (current.length > 0) {
207
- tokens.push(current);
208
- }
209
- return tokens;
210
- }
211
-
212
- function scanBalancedParens(str = '', openParenIdx = 0) {
213
- let depth = 1;
214
- let j = openParenIdx + 1;
215
- let innerQuote = null;
216
- while (j < str.length && depth > 0) {
217
- const c = str[j];
218
- if (innerQuote === "'") {
219
- if (c === "'") innerQuote = null;
220
- } else if (innerQuote === '"') {
221
- if (c === '\\' && j + 1 < str.length) {
222
- j += 1;
223
- } else if (c === '"') {
224
- innerQuote = null;
225
- }
226
- } else if (c === "'" || c === '"') {
227
- innerQuote = c;
228
- } else if (c === '(') {
229
- depth += 1;
230
- } else if (c === ')') {
231
- depth -= 1;
232
- if (depth === 0) break;
233
- }
234
- j += 1;
235
- }
236
- if (depth !== 0) return null;
237
- return { inner: str.slice(openParenIdx + 1, j).trim(), closeIdx: j };
238
- }
239
-
240
- function extractCommandSubstitutions(commandLine = '', options = {}) {
241
- const extracted = [];
242
- const str = String(commandLine || '');
243
- const isPowerShell = Boolean(options?.isPowerShell);
244
- let quoteChar = null;
245
-
246
- for (let i = 0; i < str.length; i++) {
247
- const ch = str[i];
248
- if (quoteChar === "'") {
249
- if (ch === "'") quoteChar = null;
250
- continue;
251
- }
252
- if (quoteChar === '"') {
253
- if ((ch === '\\' || (isPowerShell && ch === '`')) && i + 1 < str.length) {
254
- i += 1;
255
- continue;
256
- }
257
- if (ch === '"') {
258
- quoteChar = null;
259
- continue;
260
- }
261
- } else if (ch === "'" || ch === '"') {
262
- quoteChar = ch;
263
- continue;
264
- } else if ((ch === '\\' || (isPowerShell && ch === '`')) && i + 1 < str.length) {
265
- i += 1;
266
- continue;
267
- }
268
-
269
- if (ch === '$' && str[i + 1] === '(') {
270
- const paren = scanBalancedParens(str, i + 1);
271
- if (paren) {
272
- if (paren.inner) extracted.push(paren.inner);
273
- i = paren.closeIdx;
274
- }
275
- continue;
276
- }
277
-
278
- if (!quoteChar && !isPowerShell && (ch === '<' || ch === '>') && str[i + 1] === '(') {
279
- const paren = scanBalancedParens(str, i + 1);
280
- if (paren) {
281
- if (paren.inner) extracted.push(paren.inner);
282
- i = paren.closeIdx;
283
- }
284
- continue;
285
- }
286
-
287
- if (!isPowerShell && ch === '`') {
288
- let j = i + 1;
289
- while (j < str.length) {
290
- if (str[j] === '\\' && j + 1 < str.length) {
291
- j += 2;
292
- continue;
293
- }
294
- if (str[j] === '`') break;
295
- j += 1;
296
- }
297
- if (j < str.length && str[j] === '`') {
298
- const inner = str.slice(i + 1, j).trim();
299
- if (inner && !inner.startsWith('-')) {
300
- extracted.push(inner);
301
- }
302
- i = j;
303
- }
304
- }
305
- }
306
-
307
- return extracted;
308
- }
309
-
310
- function splitCommandSegments(commandLine = '', options = {}) {
311
- const segments = [];
312
- const str = String(commandLine || '');
313
- const isPowerShell = Boolean(options?.isPowerShell);
314
- let current = '';
315
- let quoteChar = null;
316
- let subshellDepth = 0;
317
-
318
- for (let i = 0; i < str.length; i++) {
319
- const ch = str[i];
320
- if (quoteChar === "'") {
321
- current += ch;
322
- if (ch === "'") {
323
- if (isPowerShell && str[i + 1] === "'") {
324
- current += "'";
325
- i += 1;
326
- } else {
327
- quoteChar = null;
328
- }
329
- }
330
- continue;
331
- }
332
- if (quoteChar === '"') {
333
- current += ch;
334
- if ((ch === '\\' || (isPowerShell && ch === '`')) && i + 1 < str.length) {
335
- current += str[i + 1];
336
- i += 1;
337
- } else if (ch === '"') {
338
- quoteChar = null;
339
- }
340
- continue;
341
- }
342
-
343
- if (ch === '"' || ch === "'") {
344
- quoteChar = ch;
345
- current += ch;
346
- continue;
347
- }
348
-
349
- if ((ch === '\\' || (isPowerShell && ch === '`')) && i + 1 < str.length) {
350
- current += ch + str[i + 1];
351
- i += 1;
352
- continue;
353
- }
354
-
355
- if (ch === '$' && str[i + 1] === '(') {
356
- subshellDepth += 1;
357
- current += '$(';
358
- i += 1;
359
- continue;
360
- }
361
- if (subshellDepth > 0) {
362
- if (ch === '(') subshellDepth += 1;
363
- else if (ch === ')') subshellDepth -= 1;
364
- current += ch;
365
- continue;
366
- }
367
-
368
- if (ch === ';' || ch === '\n' || ch === '\r') {
369
- if (current.trim()) segments.push(current.trim());
370
- current = '';
371
- continue;
372
- }
373
-
374
- if ((ch === '&' && str[i + 1] === '&') || (ch === '|' && str[i + 1] === '|')) {
375
- if (current.trim()) segments.push(current.trim());
376
- current = '';
377
- i += 1;
378
- continue;
379
- }
380
-
381
- if (ch === '|') {
382
- if (current.trim()) segments.push(current.trim());
383
- current = '';
384
- if (str[i + 1] === '&') i += 1;
385
- continue;
386
- }
387
-
388
- const prevChar = i > 0 ? str[i - 1] : '';
389
- const nextChar = i + 1 < str.length ? str[i + 1] : '';
390
- if (
391
- ch === '&' &&
392
- current.trim().length > 0 &&
393
- prevChar !== '>' &&
394
- prevChar !== '<' &&
395
- nextChar !== '>' &&
396
- nextChar !== '&'
397
- ) {
398
- segments.push(current.trim());
399
- current = '';
400
- continue;
401
- }
402
-
403
- current += ch;
404
- }
405
-
406
- if (current.trim()) {
407
- segments.push(current.trim());
408
- }
409
- return segments;
410
- }
411
-
412
- function checkForbiddenGitEnvAssignment(rawKey, rawVal) {
413
- const key = String(rawKey || '').trim().toUpperCase();
414
- const val = String(rawVal ?? '')
415
- .trim()
416
- .replace(/^['"]|['"]$/g, '');
417
-
418
- if (
419
- (key === 'HUSKY' && val === '0') ||
420
- (key === 'HUSKY_SKIP_HOOKS' && (val === '1' || val.toLowerCase() === 'true')) ||
421
- (key === 'SKIP_GIT_HOOKS' && (val === '1' || val.toLowerCase() === 'true'))
422
- ) {
423
- return {
424
- subType: 'GIT_HOOK_ENV_BYPASS',
425
- reason: `[Burnoff DET-01 Git Hook Bypass Blocked] Disabling git hooks via ${key}=${val} is forbidden.`
426
- };
427
- }
428
-
429
- if (
430
- (key === 'GIT_CONFIG_COUNT' && /^[1-9]\d*$/.test(val)) ||
431
- (/^GIT_CONFIG_KEY_\d+$/.test(key) && /^core\.hooksPath$/i.test(val)) ||
432
- (key === 'GIT_CONFIG_PARAMETERS' && /core\.hooksPath/i.test(val))
433
- ) {
434
- return {
435
- subType: 'GIT_HOOKS_PATH_OVERRIDE',
436
- reason: `[Burnoff DET-01 Git Hook Bypass Blocked] Overriding git config via environment variable ${key}=${val} is forbidden.`
437
- };
438
- }
439
-
440
- return null;
441
- }
442
-
443
- function splitEnvKeyValToken(token = '') {
444
- const m = String(token || '').match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s);
445
- if (!m) return null;
446
- return { key: m[1], value: m[2] };
447
- }
448
-
449
- /**
450
- * Checks whether the user's prompt explicitly requested modifying, deleting, or skipping tests.
451
- */
452
- export function hasExplicitTestModifyIntent(promptText = '') {
453
- const s = String(promptText || '');
454
- if (!s) return false;
455
- return (
456
- /\b(?:edit|update|modify|delete|remove|drop|skip|disable|rewrite|adjust|refactor)\s+(?:(?:the|all|any|some|these|those|existing|failing|obsolete|legacy|old|broken|flaky|unit|integration|e2e)\s+)*(?:tests?|specs?|assertions?)\b/i.test(
457
- s
458
- ) ||
459
- (/\.(?:test|spec)\.[a-z0-9]+\b/i.test(s) &&
460
- /\b(?:delete|remove|drop|skip|disable|update|rewrite)\b/i.test(s))
461
- );
462
- }
463
-
464
- function isProtectedTestFileToken(token = '') {
465
- const norm = String(token || '').trim().replace(/^['"]|['"]$/g, '').replace(/\\/g, '/');
466
- if (!norm) return false;
467
- if (
468
- /^(?:\/tmp\/|\/var\/folders\/)/i.test(norm) ||
469
- /(?:^|\/)(?:tmp|temp|\.claude\/cache|\.burnoff\/tmp)\//i.test(norm) ||
470
- /appdata\/local\/temp\//i.test(norm)
471
- ) {
472
- return false;
473
- }
474
- return (
475
- /\.(?:test|spec)\.(?:[cm]?[jt]sx?|py|go|rs)$/i.test(norm) ||
476
- /(?:^|\/)(?:test|tests|__tests__)\/.*\.(?:[cm]?[jt]sx?|py|go|rs)$/i.test(norm) ||
477
- /_test\.(?:py|go)$/i.test(norm)
478
- );
479
- }
480
-
481
- /**
482
- * DET-01: Destructive Shell & Git Hook-Bypass Blocker (`Bash|PowerShell`).
483
- * Skips option arguments (such as `git commit -m "-next"`), allows `-n` dry-runs on `git log`/`clean`,
484
- * downgrades un-stashed `git checkout --` / `git restore` to `ask` in default `guard`/`COACH` mode,
485
- * and allows them within 120s of a recorded `git stash`.
486
- */
487
- export function evaluateDet01GitAndShellSafety(params = {}, _depth = 0) {
488
- if (_depth > 4) {
489
- return { detectorId: 'DET-01', triggered: false, decision: 'allow', reason: null };
490
- }
491
-
492
- const toolName = String(params.toolName || 'Bash');
493
- if (!SHELL_TOOL_REGEX.test(toolName)) {
494
- return { detectorId: 'DET-01', triggered: false, decision: 'allow', reason: null };
495
- }
496
-
497
- const command = String(params.command || params.cmd || '').trim();
498
- if (!command) {
499
- return { detectorId: 'DET-01', triggered: false, decision: 'allow', reason: null };
500
- }
501
-
502
- const isPowerShell = detectPowerShellSyntax(toolName, command);
503
- const nowMs = Number(params.nowMs ?? Date.now());
504
- const recentStashActive =
505
- /\bgit\s+stash\b[\s\S]*?(?:&&|;)\s*git\s+(?:checkout|restore)\b/i.test(command) ||
506
- (Number.isFinite(Number(params.recentGitStashAtMs)) &&
507
- Number(params.recentGitStashAtMs) > 0 &&
508
- nowMs - Number(params.recentGitStashAtMs) <= 120_000);
509
- const rawMode = String(params.mode ?? params.flightMode ?? 'guard').trim().toUpperCase();
510
- const isStrictAutoMode = rawMode === 'STRICT' || rawMode === 'AUTO' || rawMode === 'AUTO_PILOT';
511
- const strictTestIntegrity = Boolean(params.strictTestIntegrity);
512
-
513
- // 1. Recursively inspect $(...) and POSIX backtick command substitutions
514
- const substitutions = extractCommandSubstitutions(command, { isPowerShell });
515
- for (const subCmd of substitutions) {
516
- const subVerdict = evaluateDet01GitAndShellSafety(
517
- {
518
- toolName: isPowerShell ? 'PowerShell' : toolName,
519
- command: subCmd,
520
- mode: params.mode,
521
- flightMode: params.flightMode,
522
- recentGitStashAtMs: params.recentGitStashAtMs,
523
- strictTestIntegrity: params.strictTestIntegrity,
524
- nowMs
525
- },
526
- _depth + 1
527
- );
528
- if (subVerdict.triggered) return subVerdict;
529
- }
530
-
531
- // 2. Inspect individual segments after splitting on ;, &&, ||, |, newlines, &
532
- let sawGitStashInCommand = false;
533
- const segments = splitCommandSegments(command, { isPowerShell });
534
- for (const segment of segments) {
535
- const rawTokens = tokenizeShellSegment(segment, { isPowerShell });
536
- if (rawTokens.length === 0) continue;
537
-
538
- let idx = 0;
539
- while (idx < rawTokens.length && rawTokens[idx] === '&') {
540
- idx += 1;
541
- }
542
- if (idx >= rawTokens.length) continue;
543
-
544
- const psEnvMatch = rawTokens[idx].match(/^\$env:([A-Za-z_][A-Za-z0-9_]*)(?:=(.*))?$/is);
545
- if (psEnvMatch) {
546
- const envKey = psEnvMatch[1];
547
- let envVal = psEnvMatch[2];
548
- if (envVal === undefined) {
549
- if (rawTokens[idx + 1] === '=') {
550
- envVal = rawTokens[idx + 2] ?? '';
551
- } else if (rawTokens[idx + 1]?.startsWith('=')) {
552
- envVal = rawTokens[idx + 1].slice(1) || (rawTokens[idx + 2] ?? '');
553
- }
554
- }
555
- if (envVal !== undefined) {
556
- const envHit = checkForbiddenGitEnvAssignment(envKey, envVal);
557
- if (envHit) {
558
- return {
559
- detectorId: 'DET-01',
560
- triggered: true,
561
- decision: 'deny',
562
- subType: envHit.subType,
563
- reason: envHit.reason
564
- };
565
- }
566
- }
567
- continue;
568
- }
569
-
570
- if (/^(?:Set-Item|si)$/i.test(rawTokens[idx]) && rawTokens[idx + 1]) {
571
- const envPathMatch = rawTokens[idx + 1].match(/^env:[\\/]?([A-Za-z_][A-Za-z0-9_]*)$/i);
572
- if (envPathMatch) {
573
- const envHit = checkForbiddenGitEnvAssignment(envPathMatch[1], rawTokens[idx + 2] ?? '');
574
- if (envHit) {
575
- return {
576
- detectorId: 'DET-01',
577
- triggered: true,
578
- decision: 'deny',
579
- subType: envHit.subType,
580
- reason: envHit.reason
581
- };
582
- }
583
- }
584
- }
585
-
586
- const firstWordLower = rawTokens[idx].toLowerCase();
587
- if (firstWordLower === 'export' || firstWordLower === 'set') {
588
- for (let eIdx = idx + 1; eIdx < rawTokens.length; eIdx++) {
589
- const kv = splitEnvKeyValToken(rawTokens[eIdx]);
590
- if (kv) {
591
- const envHit = checkForbiddenGitEnvAssignment(kv.key, kv.value);
592
- if (envHit) {
593
- return {
594
- detectorId: 'DET-01',
595
- triggered: true,
596
- decision: 'deny',
597
- subType: envHit.subType,
598
- reason: envHit.reason
599
- };
600
- }
601
- }
602
- }
603
- continue;
604
- }
605
-
606
- while (idx < rawTokens.length) {
607
- const kv = splitEnvKeyValToken(rawTokens[idx]);
608
- if (!kv) break;
609
- const envHit = checkForbiddenGitEnvAssignment(kv.key, kv.value);
610
- if (envHit) {
611
- return {
612
- detectorId: 'DET-01',
613
- triggered: true,
614
- decision: 'deny',
615
- subType: envHit.subType,
616
- reason: envHit.reason
617
- };
618
- }
619
- idx += 1;
620
- }
621
- while (idx < rawTokens.length && rawTokens[idx] === '&') {
622
- idx += 1;
623
- }
624
- if (idx >= rawTokens.length) continue;
625
-
626
- let bin = rawTokens[idx].replace(/^.*[\\/]/, '').toLowerCase();
627
- if (bin === 'env' || bin === 'env.exe') {
628
- idx += 1;
629
- while (idx < rawTokens.length) {
630
- const t = rawTokens[idx];
631
- if (t === '-u' || t === '--unset' || t === '-C' || t === '--chdir' || t === '-S') {
632
- idx += 2;
633
- continue;
634
- }
635
- if (t.startsWith('-')) {
636
- idx += 1;
637
- continue;
638
- }
639
- const kv = splitEnvKeyValToken(t);
640
- if (kv) {
641
- const envHit = checkForbiddenGitEnvAssignment(kv.key, kv.value);
642
- if (envHit) {
643
- return {
644
- detectorId: 'DET-01',
645
- triggered: true,
646
- decision: 'deny',
647
- subType: envHit.subType,
648
- reason: envHit.reason
649
- };
650
- }
651
- idx += 1;
652
- continue;
653
- }
654
- break;
655
- }
656
- if (idx >= rawTokens.length) continue;
657
- bin = rawTokens[idx].replace(/^.*[\\/]/, '').toLowerCase();
658
- }
659
-
660
- const userExplicitTestIntent =
661
- Boolean(params.userExplicitTestIntent) ||
662
- hasExplicitTestModifyIntent(params.lastUserInput || params.prompt || '');
663
- if (['bash', 'bash.exe', 'sh', 'sh.exe', 'zsh', 'dash'].includes(bin)) {
664
- const cPos = rawTokens.findIndex((t, ti) => ti > idx && (t === '-c' || /^-[a-zA-Z]*c$/.test(t)));
665
- if (cPos !== -1 && rawTokens[cPos + 1]) {
666
- const nested = evaluateDet01GitAndShellSafety(
667
- {
668
- toolName: 'Bash',
669
- command: rawTokens[cPos + 1],
670
- userExplicitTestIntent,
671
- lastUserInput: params.lastUserInput || params.prompt || '',
672
- mode: params.mode,
673
- flightMode: params.flightMode,
674
- recentGitStashAtMs: params.recentGitStashAtMs,
675
- strictTestIntegrity: params.strictTestIntegrity,
676
- nowMs
677
- },
678
- _depth + 1
679
- );
680
- if (nested.triggered) return nested;
681
- }
682
- continue;
683
- }
684
- if (bin === 'cmd' || bin === 'cmd.exe') {
685
- const cPos = rawTokens.findIndex((t, ti) => ti > idx && /^\/[ck]$/i.test(t));
686
- if (cPos !== -1 && cPos + 1 < rawTokens.length) {
687
- const nestedCmd = rawTokens.slice(cPos + 1).join(' ');
688
- const nested = evaluateDet01GitAndShellSafety(
689
- {
690
- toolName: 'cmd',
691
- command: nestedCmd,
692
- userExplicitTestIntent,
693
- lastUserInput: params.lastUserInput || params.prompt || '',
694
- mode: params.mode,
695
- flightMode: params.flightMode,
696
- recentGitStashAtMs: params.recentGitStashAtMs,
697
- strictTestIntegrity: params.strictTestIntegrity,
698
- nowMs
699
- },
700
- _depth + 1
701
- );
702
- if (nested.triggered) return nested;
703
- }
704
- continue;
705
- }
706
- if (['powershell', 'powershell.exe', 'pwsh', 'pwsh.exe'].includes(bin)) {
707
- const cPos = rawTokens.findIndex((t, ti) => ti > idx && /^-(?:c|command)$/i.test(t));
708
- if (cPos !== -1 && cPos + 1 < rawTokens.length) {
709
- const nestedCmd = rawTokens.slice(cPos + 1).join(' ');
710
- const nested = evaluateDet01GitAndShellSafety(
711
- {
712
- toolName: 'PowerShell',
713
- command: nestedCmd,
714
- userExplicitTestIntent,
715
- lastUserInput: params.lastUserInput || params.prompt || '',
716
- mode: params.mode,
717
- flightMode: params.flightMode,
718
- recentGitStashAtMs: params.recentGitStashAtMs,
719
- strictTestIntegrity: params.strictTestIntegrity,
720
- nowMs
721
- },
722
- _depth + 1
723
- );
724
- if (nested.triggered) return nested;
725
- }
726
- continue;
727
- }
728
-
729
- function isExplicitTempTarget(normArg = '') {
730
- return /^(?:\/tmp(?:\/|$)|\/var\/folders(?:\/|$)|\$tmpdir(?:\/|$)|\$\{tmpdir\}(?:\/|$)|\$\{?env:(?:temp|tmp)\}?[\\/]|(?:[a-z]:)?[\\/]?(?:temp|tmp)(?:\/|$))/i.test(
731
- String(normArg || '').replace(/\\/g, '/')
732
- );
733
- }
734
-
735
- function isProtectedRecursiveDeleteTarget(rawArg = '') {
736
- const norm = String(rawArg || '').trim().replace(/^["']|["']$/g, '').replace(/\\/g, '/');
737
- if (!norm || norm.startsWith('-')) return false;
738
- if (isExplicitTempTarget(norm)) return false;
739
- if (/^(?:\/+|\/\*|\~|\$HOME|\$\{HOME\}|\$env:USERPROFILE|[A-Za-z]:\/?)$/i.test(norm)) {
740
- return true;
741
- }
742
- const stripped = norm.replace(/\/+$/, '').replace(/^\.\//, '');
743
- if (norm === '.' || norm === './' || stripped === '' || stripped === '*') {
744
- return true;
745
- }
746
- return /^(?:src|test|tests|__tests__)(?:\/\*|\/)?$/i.test(stripped);
747
- }
748
-
749
- if (bin === 'rm' || bin === 'rm.exe' || bin === 'unlink' || bin === 'unlink.exe') {
750
- const rmArgs = rawTokens.slice(idx + 1);
751
- const hasRecursive = rmArgs.some(
752
- (a) => a === '--recursive' || (/^-[a-zA-Z]+$/.test(a) && /[rR]/.test(a))
753
- );
754
- const hasForce = rmArgs.some(
755
- (a) => a === '--force' || (/^-[a-zA-Z]+$/.test(a) && /f/.test(a))
756
- );
757
- const targetsRootOrHome = rmArgs.some((a) => isProtectedRecursiveDeleteTarget(a));
758
- if (hasRecursive && hasForce && targetsRootOrHome) {
759
- return {
760
- detectorId: 'DET-01',
761
- triggered: true,
762
- decision: 'deny',
763
- subType: 'DESTRUCTIVE_FS_WIPE',
764
- reason: '[Burnoff DET-01 Destructive Shell Blocked] Recursive root/home/repo/src/test deletion is forbidden.'
765
- };
766
- }
767
- if (!userExplicitTestIntent) {
768
- const deletedTestTarget = rmArgs.find(
769
- (a) => !a.startsWith('-') && isProtectedTestFileToken(a)
770
- );
771
- if (deletedTestTarget) {
772
- return {
773
- detectorId: 'DET-01',
774
- triggered: true,
775
- decision: isStrictAutoMode ? 'deny' : 'ask',
776
- subType: 'TEST_FILE_DELETION',
777
- reason: `[Burnoff DET-01 Test Integrity Lock] Deleting test file "${deletedTestTarget}" via shell without explicit user instruction requires confirmation.`
778
- };
779
- }
780
- }
781
- continue;
782
- }
783
-
784
- if (/^(?:remove-item|ri|del|erase|rmdir)$/i.test(bin)) {
785
- const psArgs = rawTokens.slice(idx + 1);
786
- const hasRecurse = psArgs.some((a) => /^-r(?:ecurse)?$/i.test(a));
787
- const hasForce = psArgs.some((a) => /^-f(?:orce)?$/i.test(a));
788
- const targetsRootOrHome = psArgs.some((a) => isProtectedRecursiveDeleteTarget(a));
789
- if (hasRecurse && hasForce && targetsRootOrHome) {
790
- return {
791
- detectorId: 'DET-01',
792
- triggered: true,
793
- decision: 'deny',
794
- subType: 'DESTRUCTIVE_FS_WIPE',
795
- reason: '[Burnoff DET-01 Destructive Shell Blocked] Recursive root/home/repo/src/test deletion is forbidden.'
796
- };
797
- }
798
- if (!userExplicitTestIntent) {
799
- const deletedTestTarget = psArgs.find(
800
- (a) => !a.startsWith('-') && !a.startsWith('/') && isProtectedTestFileToken(a)
801
- );
802
- if (deletedTestTarget) {
803
- return {
804
- detectorId: 'DET-01',
805
- triggered: true,
806
- decision: isStrictAutoMode ? 'deny' : 'ask',
807
- subType: 'TEST_FILE_DELETION',
808
- reason: `[Burnoff DET-01 Test Integrity Lock] Deleting test file "${deletedTestTarget}" via shell without explicit user instruction requires confirmation.`
809
- };
810
- }
811
- }
812
- continue;
813
- }
814
-
815
- if (bin !== 'git' && bin !== 'git.exe') continue;
816
- idx += 1;
817
-
818
- let subcommand = null;
819
- while (idx < rawTokens.length) {
820
- const tok = rawTokens[idx];
821
- if (!tok.startsWith('-')) {
822
- subcommand = tok.toLowerCase();
823
- idx += 1;
824
- break;
825
- }
826
- if (tok === '-c' && idx + 1 < rawTokens.length) {
827
- const cfg = rawTokens[idx + 1];
828
- if (/^core\.hooksPath(?:\s*=|$)/i.test(cfg)) {
829
- return {
830
- detectorId: 'DET-01',
831
- triggered: true,
832
- decision: 'deny',
833
- subType: 'GIT_HOOKS_PATH_OVERRIDE',
834
- reason: `[Burnoff DET-01 Git Hook Bypass Blocked] Overriding core.hooksPath via "git -c ${cfg}" is forbidden.`
835
- };
836
- }
837
- idx += 2;
838
- continue;
839
- }
840
- if (
841
- /^-c\s*core\.hooksPath(?:\s*=|$)/i.test(tok) ||
842
- /^--config-env=core\.hooksPath(?:=|$)/i.test(tok)
843
- ) {
844
- return {
845
- detectorId: 'DET-01',
846
- triggered: true,
847
- decision: 'deny',
848
- subType: 'GIT_HOOKS_PATH_OVERRIDE',
849
- reason: '[Burnoff DET-01 Git Hook Bypass Blocked] Overriding core.hooksPath is forbidden.'
850
- };
851
- }
852
- if (tok === '--config-env' && idx + 1 < rawTokens.length) {
853
- if (/^core\.hooksPath(?:=|$)/i.test(rawTokens[idx + 1])) {
854
- return {
855
- detectorId: 'DET-01',
856
- triggered: true,
857
- decision: 'deny',
858
- subType: 'GIT_HOOKS_PATH_OVERRIDE',
859
- reason: '[Burnoff DET-01 Git Hook Bypass Blocked] Overriding core.hooksPath via --config-env is forbidden.'
860
- };
861
- }
862
- idx += 2;
863
- continue;
864
- }
865
- if (GIT_GLOBAL_OPTS_WITH_ARG.has(tok)) {
866
- idx += 2;
867
- } else {
868
- idx += 1;
869
- }
870
- }
871
-
872
- if (!subcommand) continue;
873
-
874
- const subArgs = rawTokens.slice(idx);
875
-
876
- if (subcommand === 'rm' && !userExplicitTestIntent) {
877
- const deletedTestTarget = subArgs.find(
878
- (a) => !a.startsWith('-') && isProtectedTestFileToken(a)
879
- );
880
- if (deletedTestTarget) {
881
- return {
882
- detectorId: 'DET-01',
883
- triggered: true,
884
- decision: isStrictAutoMode ? 'deny' : 'ask',
885
- subType: 'TEST_FILE_DELETION',
886
- reason: `[Burnoff DET-01 Test Integrity Lock] Deleting test file "${deletedTestTarget}" via "git rm" without explicit user instruction requires confirmation.`
887
- };
888
- }
889
- }
890
-
891
- if (subcommand === 'config') {
892
- let isReadOnlyQuery = false;
893
- const positional = [];
894
- for (let i = 0; i < subArgs.length; i++) {
895
- const arg = subArgs[i];
896
- if (arg === '--') {
897
- positional.push(...subArgs.slice(i + 1));
898
- break;
899
- }
900
- if (
901
- arg === '--get' ||
902
- arg === '--get-all' ||
903
- arg === '--get-regexp' ||
904
- arg === '--get-urlmatch' ||
905
- arg === '--list' ||
906
- arg === '-l'
907
- ) {
908
- isReadOnlyQuery = true;
909
- break;
910
- }
911
- if (GIT_CONFIG_OPTS_WITH_ARG.has(arg)) {
912
- i += 1;
913
- continue;
914
- }
915
- if (arg.startsWith('-')) {
916
- continue;
917
- }
918
- positional.push(arg);
919
- }
920
-
921
- if (!isReadOnlyQuery && positional.length >= 2) {
922
- const firstPosLower = positional[0].toLowerCase();
923
- if (firstPosLower !== 'get' && firstPosLower !== 'list') {
924
- const cfgKey = firstPosLower === 'set' ? positional[1] || '' : positional[0];
925
- const hasCfgVal = firstPosLower === 'set' ? positional.length >= 3 : positional.length >= 2;
926
- if (hasCfgVal && /^core\.hooksPath$/i.test(cfgKey)) {
927
- return {
928
- detectorId: 'DET-01',
929
- triggered: true,
930
- decision: 'deny',
931
- subType: 'GIT_HOOKS_PATH_OVERRIDE',
932
- reason: '[Burnoff DET-01 Git Hook Bypass Blocked] Mutating "git config core.hooksPath" is forbidden.'
933
- };
934
- }
935
- }
936
- }
937
- continue;
938
- }
939
-
940
- if (subcommand === 'reset' && subArgs.includes('--hard')) {
941
- return {
942
- detectorId: 'DET-01',
943
- triggered: true,
944
- decision: 'deny',
945
- subType: 'GIT_RESET_HARD',
946
- reason: '[Burnoff DET-01 Destructive Git Blocked] "git reset --hard" destroys uncommitted work.'
947
- };
948
- }
949
-
950
- if (subcommand === 'clean') {
951
- let hasDryRun = false;
952
- let hasForce = false;
953
- let hasExplicitLongForce = false;
954
- for (let i = 0; i < subArgs.length; i++) {
955
- const arg = subArgs[i];
956
- if (arg === '--') break;
957
- if (arg === '-e' || arg === '--exclude') {
958
- i += 1;
959
- continue;
960
- }
961
- if (arg === '-n' || arg === '--dry-run' || (/^-[a-zA-Z]+$/.test(arg) && arg.includes('n'))) {
962
- hasDryRun = true;
963
- }
964
- if (arg === '--force') {
965
- hasForce = true;
966
- hasExplicitLongForce = true;
967
- } else if (/^-[a-zA-Z]*f[a-zA-Z]*$/.test(arg)) {
968
- hasForce = true;
969
- }
970
- }
971
- if (hasForce && (!hasDryRun || hasExplicitLongForce)) {
972
- return {
973
- detectorId: 'DET-01',
974
- triggered: true,
975
- decision: 'deny',
976
- subType: 'GIT_CLEAN_FORCE',
977
- reason: '[Burnoff DET-01 Destructive Git Blocked] "git clean -f" permanently deletes untracked files (use "git clean -n" for dry-run).'
978
- };
979
- }
980
- }
981
-
982
- if (subcommand === 'commit') {
983
- for (let i = 0; i < subArgs.length; i++) {
984
- const arg = subArgs[i];
985
- if (arg === '--') break;
986
-
987
- if (arg === '--no-verify') {
988
- return {
989
- detectorId: 'DET-01',
990
- triggered: true,
991
- decision: 'deny',
992
- subType: 'GIT_COMMIT_NO_VERIFY',
993
- reason: '[Burnoff DET-01 Git Hook Bypass Blocked] "git commit --no-verify" is forbidden.'
994
- };
995
- }
996
-
997
- if (GIT_COMMIT_OPTS_WITH_ARG.has(arg)) {
998
- i += 1;
999
- continue;
1000
- }
1001
-
1002
- if (arg.startsWith('--')) {
1003
- continue;
1004
- }
1005
-
1006
- if (arg.startsWith('-') && arg.length > 1) {
1007
- const cluster = arg.slice(1);
1008
- if (
1009
- !SHORT_COMMIT_ARG_CHARS.has(cluster[0]) &&
1010
- cluster[0] !== 'u' &&
1011
- /^[amnvqseS]+$/.test(cluster)
1012
- ) {
1013
- if (cluster.includes('n')) {
1014
- return {
1015
- detectorId: 'DET-01',
1016
- triggered: true,
1017
- decision: 'deny',
1018
- subType: 'GIT_COMMIT_SHORT_NO_VERIFY',
1019
- reason: `[Burnoff DET-01 Git Hook Bypass Blocked] Short flag "-n" (--no-verify) in "git commit ${arg}" is forbidden.`
1020
- };
1021
- }
1022
- if (cluster.includes('m')) {
1023
- i += 1;
1024
- }
1025
- continue;
1026
- }
1027
-
1028
- let consumedRestOfToken = false;
1029
- for (let cIdx = 0; cIdx < cluster.length; cIdx++) {
1030
- const ch = cluster[cIdx];
1031
- if (ch === 'n') {
1032
- return {
1033
- detectorId: 'DET-01',
1034
- triggered: true,
1035
- decision: 'deny',
1036
- subType: 'GIT_COMMIT_SHORT_NO_VERIFY',
1037
- reason: `[Burnoff DET-01 Git Hook Bypass Blocked] Short flag "-n" (--no-verify) in "git commit ${arg}" is forbidden.`
1038
- };
1039
- }
1040
- if (ch === 'u') {
1041
- const restMode = cluster.slice(cIdx + 1);
1042
- if (VALID_GIT_COMMIT_UNTRACKED_MODES.has(restMode)) {
1043
- consumedRestOfToken = true;
1044
- break;
1045
- }
1046
- continue;
1047
- }
1048
- if (SHORT_COMMIT_ARG_CHARS.has(ch)) {
1049
- if (cIdx === cluster.length - 1) {
1050
- i += 1;
1051
- }
1052
- consumedRestOfToken = true;
1053
- break;
1054
- }
1055
- }
1056
- if (consumedRestOfToken) continue;
1057
- }
1058
- }
1059
- }
1060
-
1061
- if (['push', 'merge', 'rebase', 'cherry-pick'].includes(subcommand)) {
1062
- for (let i = 0; i < subArgs.length; i++) {
1063
- const arg = subArgs[i];
1064
- if (arg === '--') break;
1065
- if (arg === '--no-verify') {
1066
- return {
1067
- detectorId: 'DET-01',
1068
- triggered: true,
1069
- decision: 'deny',
1070
- subType: 'GIT_NO_VERIFY',
1071
- reason: `[Burnoff DET-01 Git Hook Bypass Blocked] "git ${subcommand} --no-verify" is forbidden.`
1072
- };
1073
- }
1074
- if (
1075
- subcommand === 'push' &&
1076
- (arg === '--force' || arg === '-f') &&
1077
- !subArgs.some((a) => a.startsWith('--force-with-lease'))
1078
- ) {
1079
- return {
1080
- detectorId: 'DET-01',
1081
- triggered: true,
1082
- decision: 'deny',
1083
- subType: 'GIT_PUSH_FORCE',
1084
- reason: '[Burnoff DET-01 Destructive Git Blocked] Unconditional "git push --force" is forbidden (use --force-with-lease if required).'
1085
- };
1086
- }
1087
- }
1088
- }
1089
-
1090
- if (subcommand === 'stash') {
1091
- sawGitStashInCommand = true;
1092
- }
1093
-
1094
- const discardDecision = isStrictAutoMode ? 'deny' : 'ask';
1095
- if (!recentStashActive && !sawGitStashInCommand) {
1096
- if (subcommand === 'checkout') {
1097
- const isBranchCreation = subArgs.some((a) => a === '-b' || a === '-B' || a === '--orphan');
1098
- if (!isBranchCreation) {
1099
- const hasForceCheckout = subArgs.some((a) => a === '-f' || a === '--force');
1100
- const hasDoubleDashDiscard = subArgs.includes('--');
1101
- const hasDotDiscard = subArgs.includes('.');
1102
- if (hasForceCheckout || hasDoubleDashDiscard || hasDotDiscard) {
1103
- return {
1104
- detectorId: 'DET-01',
1105
- triggered: true,
1106
- decision: discardDecision,
1107
- subType: 'GIT_UNSTASHED_DISCARD',
1108
- reason: '[Burnoff DET-01 Worktree Destructive Guard] Un-stashed working-tree discard ("git checkout") destroys uncommitted edits. Run "git stash push -u" first.'
1109
- };
1110
- }
1111
- }
1112
- }
1113
-
1114
- if (subcommand === 'restore') {
1115
- const hasStagedOnly =
1116
- subArgs.some((a) => a === '--staged' || a === '-S') &&
1117
- !subArgs.some((a) => a === '--worktree' || a === '-W');
1118
- if (!hasStagedOnly && subArgs.some((a) => a !== '--help' && a !== '-h')) {
1119
- return {
1120
- detectorId: 'DET-01',
1121
- triggered: true,
1122
- decision: discardDecision,
1123
- subType: 'GIT_UNSTASHED_DISCARD',
1124
- reason: '[Burnoff DET-01 Worktree Destructive Guard] Un-stashed "git restore" overwrites working-tree edits. Run "git stash push -u" first (or pass --staged to unstage).'
1125
- };
1126
- }
1127
- }
1128
- }
1129
-
1130
- const promptForGit = String(params.lastUserInput || params.prompt || '');
1131
- const userRequestedGitForensics = /\b(?:reflog|fsck|cat-file|recover\s+lost|dangling)\b/i.test(
1132
- promptForGit
1133
- );
1134
- if (strictTestIntegrity && !userRequestedGitForensics) {
1135
- const miningDecision = isStrictAutoMode ? 'deny' : 'ask';
1136
- if (subcommand === 'fsck' || subcommand === 'cat-file' || subcommand === 'reflog') {
1137
- return {
1138
- detectorId: 'DET-01',
1139
- triggered: true,
1140
- decision: miningDecision,
1141
- subType: 'GIT_HISTORY_MINING',
1142
- reason: `[Burnoff DET-01 Test Integrity Lock] Raw git object/reflog inspection ("git ${subcommand}") is gated in strict test-integrity mode.`
1143
- };
1144
- }
1145
- if (
1146
- subcommand === 'log' &&
1147
- subArgs.includes('--all') &&
1148
- subArgs.some((a) => a === '-p' || a === '--patch')
1149
- ) {
1150
- return {
1151
- detectorId: 'DET-01',
1152
- triggered: true,
1153
- decision: miningDecision,
1154
- subType: 'GIT_HISTORY_MINING',
1155
- reason: '[Burnoff DET-01 Test Integrity Lock] Full-history patch mining ("git log --all -p") is gated in strict test-integrity mode.'
1156
- };
1157
- }
1158
- }
1159
- }
1160
-
1161
- return { detectorId: 'DET-01', triggered: false, decision: 'allow', reason: null };
1162
- }
1163
-
1164
- function normalizeSecretCandidate(rawPath = '') {
1165
- return String(rawPath || '').trim().replace(/^['"]|['"]$/g, '').replace(/\\/g, '/').replace(/^\.\//, '');
1166
- }
1167
-
1168
- function secretGlobToRegExp(pattern = '') {
1169
- let out = '^';
1170
- for (let i = 0; i < pattern.length; i += 1) {
1171
- const ch = pattern[i];
1172
- if (ch === '*') {
1173
- if (pattern[i + 1] === '*') {
1174
- out += '.*';
1175
- i += 1;
1176
- if (pattern[i + 1] === '/') i += 1;
1177
- } else {
1178
- out += '[^/]*';
1179
- }
1180
- } else if (ch === '?') {
1181
- out += '[^/]';
1182
- } else if ('.+^${}()|[]\\'.includes(ch)) {
1183
- out += `\\${ch}`;
1184
- } else {
1185
- out += ch;
1186
- }
1187
- }
1188
- out += '$';
1189
- return new RegExp(out, 'i');
1190
- }
1191
-
1192
- function matchesSecretAllowList(rawTarget = '', secretAllow = []) {
1193
- if (!Array.isArray(secretAllow) || secretAllow.length === 0) return false;
1194
- const norm = normalizeSecretCandidate(rawTarget);
1195
- if (!norm) return false;
1196
- const baseName = norm.split('/').pop() || norm;
1197
-
1198
- for (const rawPat of secretAllow) {
1199
- const pat = normalizeSecretCandidate(rawPat);
1200
- if (!pat) continue;
1201
- const normLower = norm.toLowerCase();
1202
- const patLower = pat.toLowerCase();
1203
- if (normLower === patLower) return true;
1204
- if (normLower.endsWith(`/${patLower}`)) return true;
1205
- if (!pat.includes('/') && baseName.toLowerCase() === patLower) return true;
1206
- const re = secretGlobToRegExp(pat);
1207
- if (re.test(norm) || (!pat.includes('/') && re.test(baseName))) {
1208
- return true;
1209
- }
1210
- }
1211
- return false;
1212
- }
1213
-
1214
- const GLOB_META_REGEX = /[*?[]/;
1215
- const CANONICAL_SECRET_GLOB_SAMPLES = [
1216
- '.env',
1217
- '.env.local',
1218
- '.env.production',
1219
- 'server.key',
1220
- 'private.pem',
1221
- 'cert.p12',
1222
- 'cert.pfx',
1223
- 'id_rsa',
1224
- 'id_ed25519',
1225
- 'id_ecdsa',
1226
- 'id_dsa',
1227
- '.npmrc',
1228
- '.netrc',
1229
- '.pypirc',
1230
- '.ssh/id_rsa',
1231
- '.ssh/config',
1232
- '.aws/credentials'
1233
- ];
1234
- const BENIGN_GLOB_SAMPLES = [
1235
- 'index.js',
1236
- 'app.ts',
1237
- 'README.md',
1238
- 'package.json',
1239
- 'notes.txt',
1240
- '.gitignore',
1241
- '.eslintrc',
1242
- '.editorconfig'
1243
- ];
1244
-
1245
- function shellGlobToRegExp(pattern = '') {
1246
- let out = '^';
1247
- for (let i = 0; i < pattern.length; i += 1) {
1248
- const ch = pattern[i];
1249
- if (ch === '*') {
1250
- if (pattern[i + 1] === '*') {
1251
- out += '.*';
1252
- i += 1;
1253
- if (pattern[i + 1] === '/') i += 1;
1254
- } else {
1255
- out += '[^/]*';
1256
- }
1257
- } else if (ch === '?') {
1258
- out += '[^/]';
1259
- } else if (ch === '[') {
1260
- const closeIdx = pattern.indexOf(']', i + 1);
1261
- if (closeIdx !== -1) {
1262
- const body = pattern.slice(i + 1, closeIdx);
1263
- const negated = body.startsWith('!') ? `^${body.slice(1)}` : body;
1264
- out += `[${negated}]`;
1265
- i = closeIdx;
1266
- } else {
1267
- out += '\\[';
1268
- }
1269
- } else if ('.+^${}()|\\'.includes(ch)) {
1270
- out += `\\${ch}`;
1271
- } else {
1272
- out += ch;
1273
- }
1274
- }
1275
- out += '$';
1276
- return new RegExp(out, 'i');
1277
- }
1278
-
1279
- function isSecretGlobPattern(normTarget = '', secretAllow = []) {
1280
- const norm = normalizeSecretCandidate(normTarget);
1281
- if (!norm || !GLOB_META_REGEX.test(norm)) return false;
1282
- if (/^(?:\*+|\*\.\*|\.\*|\.\/\*|\*\*\/\*|\?+)$/.test(norm)) return false;
1283
- if (SAFE_ENV_ALLOWLIST_REGEX.test(norm)) return false;
1284
- if (matchesSecretAllowList(norm, secretAllow)) return false;
1285
-
1286
- const hasSlash = norm.includes('/');
1287
- const basePat = hasSlash ? norm.split('/').pop() : norm;
1288
- let re;
1289
- try {
1290
- re = shellGlobToRegExp(hasSlash ? norm : basePat);
1291
- } catch (err) {
1292
- void err; // ignore: malformed bracket glob does not crash guard
1293
- return false;
1294
- }
1295
-
1296
- for (const benign of BENIGN_GLOB_SAMPLES) {
1297
- if (re.test(benign)) return false;
1298
- }
1299
-
1300
- for (const sample of CANONICAL_SECRET_GLOB_SAMPLES) {
1301
- if (matchesSecretAllowList(sample, secretAllow)) continue;
1302
- const targetSample = hasSlash ? sample : sample.split('/').pop();
1303
- if (re.test(targetSample)) return true;
1304
- }
1305
- return false;
1306
- }
1307
-
1308
- function isConfidentalSecretPath(normTarget = '', secretAllow = []) {
1309
- const norm = String(normTarget || '').trim().replace(/\\/g, '/');
1310
- if (!norm) return false;
1311
- if (SAFE_ENV_ALLOWLIST_REGEX.test(norm)) return false;
1312
- if (matchesSecretAllowList(norm, secretAllow)) return false;
1313
- if (SECRET_FILE_PATTERNS.some((pattern) => pattern.test(norm))) return true;
1314
- return isSecretGlobPattern(norm, secretAllow);
1315
- }
1316
-
1317
- function isNonPrivateCertPath(normTarget = '') {
1318
- const norm = String(normTarget || '').trim().replace(/\\/g, '/');
1319
- if (GLOB_META_REGEX.test(norm)) return false;
1320
- if (!/\.(?:pem|crt)$/i.test(norm)) return false;
1321
- if (/(?:^|[\\/])\.(?:ssh|aws)[\\/]/i.test(norm)) return false;
1322
- return !/(?:key|private)/i.test(norm);
1323
- }
1324
-
1325
- function pickStricterVerdict(best, candidate) {
1326
- if (!candidate || !candidate.triggered) return best;
1327
- if (!best || !best.triggered) return candidate;
1328
- if (best.decision === 'deny') return best;
1329
- if (candidate.decision === 'deny') return candidate;
1330
- return best;
1331
- }
1332
-
1333
- const INLINE_EVAL_BIN_FLAGS = new Map([
1334
- ['node', new Set(['-e', '--eval', '-p', '--print'])],
1335
- ['deno', new Set(['-e', '--eval', '-p', '--print'])],
1336
- ['bun', new Set(['-e', '--eval', '-p', '--print'])],
1337
- ['python', new Set(['-c'])],
1338
- ['python3', new Set(['-c'])],
1339
- ['py', new Set(['-c'])],
1340
- ['perl', new Set(['-e', '-E'])],
1341
- ['ruby', new Set(['-e'])],
1342
- ['php', new Set(['-r'])]
1343
- ]);
1344
-
1345
- function extractInlineScriptPayloads(bin, rawTokens = [], binIdx = 0) {
1346
- const flags = INLINE_EVAL_BIN_FLAGS.get(bin);
1347
- if (!flags) return [];
1348
- const payloads = [];
1349
- for (let i = binIdx + 1; i < rawTokens.length; i += 1) {
1350
- const tok = String(rawTokens[i] || '');
1351
- if (flags.has(tok) && i + 1 < rawTokens.length) {
1352
- payloads.push(String(rawTokens[i + 1] || ''));
1353
- i += 1;
1354
- continue;
1355
- }
1356
- const eqIdx = tok.indexOf('=');
1357
- if (eqIdx > 0 && flags.has(tok.slice(0, eqIdx))) {
1358
- payloads.push(tok.slice(eqIdx + 1));
1359
- }
1360
- }
1361
- return payloads;
1362
- }
1363
-
1364
- function extractInlineScriptCandidates(scriptText = '') {
1365
- let normalized = String(scriptText || '');
1366
- for (let pass = 0; pass < 4; pass += 1) {
1367
- const next = normalized.replace(
1368
- /(['"`])((?:\\.|(?!\1)[^\\])*)\1\s*\+\s*(['"`])((?:\\.|(?!\3)[^\\])*)\3/g,
1369
- (_, _q1, left, _q2, right) => JSON.stringify(`${left}${right}`)
1370
- );
1371
- if (next === normalized) break;
1372
- normalized = next;
1373
- }
1374
-
1375
- const out = [];
1376
- const litRe = /'((?:\\.|[^'\\])*)'|"((?:\\.|[^"\\])*)"|`((?:\\.|[^`\\])*)`/g;
1377
- let m;
1378
- while ((m = litRe.exec(normalized)) !== null) {
1379
- const val = (m[1] ?? m[2] ?? m[3] ?? '').trim();
1380
- if (!val) continue;
1381
- out.push(val);
1382
- for (const part of val.split(/\s+/)) {
1383
- const trimmed = part.replace(/^[,;()<>]+|[,;()<>]+$/g, '').trim();
1384
- if (trimmed && trimmed !== val) out.push(trimmed);
1385
- }
1386
- }
1387
- return out;
1388
- }
1389
-
1390
- function extractRedirectTokenTarget(rawTok = '') {
1391
- const s = String(rawTok || '').trim();
1392
- if (!s) return null;
1393
- if (/^(?:&>>?|(?:\d*)>>?|\d*>\|)$/.test(s)) {
1394
- return { kind: 'output_op' };
1395
- }
1396
- const outMatch = s.match(/^(?:&>>?|(?:\d*)>>?|\d*>\|)(.+)$/);
1397
- if (outMatch && !outMatch[1].startsWith('&')) {
1398
- return { kind: 'output_inline', target: outMatch[1].trim() };
1399
- }
1400
- if (/^<<<?$/.test(s)) {
1401
- return { kind: 'heredoc_op' };
1402
- }
1403
- if (s === '<' || /^0<$/.test(s)) {
1404
- return { kind: 'stdin_op' };
1405
- }
1406
- if (/^<<[^<]/.test(s)) {
1407
- return { kind: 'heredoc_inline' };
1408
- }
1409
- const inMatch = s.match(/^(?:0?<)(.+)$/);
1410
- if (inMatch && !inMatch[1].startsWith('<') && !inMatch[1].startsWith('&')) {
1411
- return { kind: 'stdin_inline', target: inMatch[1].trim() };
1412
- }
1413
- return null;
1414
- }
1415
-
1416
- /**
1417
- * DET-02: Secret & Credential Boundary.
1418
- * Distinguishes direct credential reads/exfiltration (`deny`) from write/creation/argument usage
1419
- * (`ask` in default `guard` mode, `deny` in `strict`/`auto`), treats non-private `.pem`/`.crt`
1420
- * files as `ask`, and honors `guards.secretAllow` while allowlisting `.env.example` / `.env.sample`.
1421
- */
1422
- export function evaluateDet02SecretBoundary(params = {}, _depth = 0) {
1423
- if (_depth > 4) {
1424
- return { detectorId: 'DET-02', triggered: false, decision: 'allow', reason: null };
1425
- }
1426
-
1427
- const toolName = String(params.toolName || 'Bash');
1428
- const rawMode = String(params.mode ?? params.flightMode ?? 'guard').trim().toUpperCase();
1429
- const isStrictAutoMode = rawMode === 'STRICT' || rawMode === 'AUTO' || rawMode === 'AUTO_PILOT';
1430
- const gatedAskDecision = isStrictAutoMode ? 'deny' : 'ask';
1431
- const secretAllow = Array.isArray(params.secretAllow) ? params.secretAllow : [];
1432
-
1433
- let best = { detectorId: 'DET-02', triggered: false, decision: 'allow', reason: null };
1434
-
1435
- const makeVerdict = (decision, normPath, modeHint = '') => ({
1436
- detectorId: 'DET-02',
1437
- triggered: true,
1438
- decision,
1439
- targetPath: normPath,
1440
- reason:
1441
- decision === 'ask'
1442
- ? `[Burnoff DET-02 Secret & Credential Boundary] ${modeHint || 'Operation involving'} "${normPath}" requires confirmation.`
1443
- : `[Burnoff DET-02 Secret & Credential Boundary] Access to sensitive credential path "${normPath}" is blocked. (.env.example / .env.sample are permitted.)`
1444
- });
1445
-
1446
- // 1. Direct file tool target (`Read`, `Grep`, `Glob`, `Edit`, `Write`, etc.)
1447
- for (const rawField of [params.filePath, params.path]) {
1448
- const norm = String(rawField || '').trim().replace(/\\/g, '/');
1449
- if (!norm || !isConfidentalSecretPath(norm, secretAllow)) continue;
1450
- if (EDIT_WRITE_TOOL_REGEX.test(toolName) || isNonPrivateCertPath(norm)) {
1451
- best = pickStricterVerdict(best, makeVerdict(gatedAskDecision, norm, `${toolName} targeting`));
1452
- } else {
1453
- best = pickStricterVerdict(best, makeVerdict('deny', norm));
1454
- }
1455
- }
1456
-
1457
- // 2. Shell command evaluation
1458
- if (params.command && SHELL_TOOL_REGEX.test(toolName)) {
1459
- const command = String(params.command);
1460
- const isPowerShell = detectPowerShellSyntax(toolName, command);
1461
-
1462
- for (const subCmd of extractCommandSubstitutions(command, { isPowerShell })) {
1463
- const subVerdict = evaluateDet02SecretBoundary(
1464
- {
1465
- toolName: isPowerShell ? 'PowerShell' : toolName,
1466
- command: subCmd,
1467
- mode: params.mode,
1468
- flightMode: params.flightMode,
1469
- secretAllow
1470
- },
1471
- _depth + 1
1472
- );
1473
- best = pickStricterVerdict(best, subVerdict);
1474
- }
1475
-
1476
- const segments = splitCommandSegments(command, { isPowerShell });
1477
- for (const seg of segments) {
1478
- const rawTokens = tokenizeShellSegment(seg, { isPowerShell });
1479
- if (rawTokens.length === 0) continue;
1480
-
1481
- let binIdx = 0;
1482
- while (binIdx < rawTokens.length && (rawTokens[binIdx] === '&' || splitEnvKeyValToken(rawTokens[binIdx]))) {
1483
- binIdx += 1;
1484
- }
1485
- if (binIdx >= rawTokens.length) continue;
1486
-
1487
- let bin = String(rawTokens[binIdx] || '').split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/i, '');
1488
- if (bin === 'env' || bin === 'sudo' || bin === 'command') {
1489
- let k = binIdx + 1;
1490
- while (k < rawTokens.length && (rawTokens[k].startsWith('-') || splitEnvKeyValToken(rawTokens[k]))) {
1491
- k += 1;
1492
- }
1493
- if (k < rawTokens.length) {
1494
- binIdx = k;
1495
- bin = String(rawTokens[binIdx] || '').split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/i, '');
1496
- }
1497
- }
1498
-
1499
- if (['bash', 'sh', 'zsh', 'dash'].includes(bin)) {
1500
- const cPos = rawTokens.findIndex((t, ti) => ti > binIdx && (t === '-c' || /^-[a-zA-Z]*c$/.test(t)));
1501
- if (cPos !== -1 && rawTokens[cPos + 1]) {
1502
- best = pickStricterVerdict(
1503
- best,
1504
- evaluateDet02SecretBoundary(
1505
- {
1506
- toolName: 'Bash',
1507
- command: rawTokens[cPos + 1],
1508
- mode: params.mode,
1509
- flightMode: params.flightMode,
1510
- secretAllow
1511
- },
1512
- _depth + 1
1513
- )
1514
- );
1515
- }
1516
- } else if (bin === 'powershell' || bin === 'pwsh') {
1517
- const cPos = rawTokens.findIndex(
1518
- (t, ti) => ti > binIdx && /^(?:-c|-command)$/i.test(String(t || ''))
1519
- );
1520
- if (cPos !== -1 && rawTokens[cPos + 1]) {
1521
- best = pickStricterVerdict(
1522
- best,
1523
- evaluateDet02SecretBoundary(
1524
- {
1525
- toolName: 'PowerShell',
1526
- command: rawTokens[cPos + 1],
1527
- mode: params.mode,
1528
- flightMode: params.flightMode,
1529
- secretAllow
1530
- },
1531
- _depth + 1
1532
- )
1533
- );
1534
- }
1535
- }
1536
-
1537
- for (const scriptBody of extractInlineScriptPayloads(bin, rawTokens, binIdx)) {
1538
- for (const cand of extractInlineScriptCandidates(scriptBody)) {
1539
- const norm = cand.replace(/\\/g, '/');
1540
- if (!norm || !isConfidentalSecretPath(norm, secretAllow)) continue;
1541
- const decision = isNonPrivateCertPath(norm) ? gatedAskDecision : 'deny';
1542
- best = pickStricterVerdict(best, makeVerdict(decision, norm, `Inline ${bin} script referencing`));
1543
- }
1544
- }
1545
-
1546
- const isOutputBinOnly = bin === 'echo' || bin === 'printf' || bin === 'write-output' || bin === 'write-host';
1547
- const isBenignGit = bin === 'git' && BENIGN_GIT_SUBCOMMANDS.has(String(rawTokens[binIdx + 1] || '').toLowerCase());
1548
- const isReadExfilBin = SECRET_READ_EXFIL_BINS.has(bin);
1549
- const isCopyMoveBin = COPY_MOVE_BINS.has(bin);
1550
-
1551
- const candidates = [];
1552
- const positionalArgs = [];
1553
- let pendingRedirect = null;
1554
-
1555
- for (let tIdx = binIdx + 1; tIdx < rawTokens.length; tIdx += 1) {
1556
- const tok = String(rawTokens[tIdx] || '').trim();
1557
- if (!tok) continue;
1558
-
1559
- if (pendingRedirect === 'output') {
1560
- pendingRedirect = null;
1561
- candidates.push({ raw: tok.replace(/^[<>&]+/, ''), role: 'output_redirect' });
1562
- continue;
1563
- }
1564
- if (pendingRedirect === 'stdin') {
1565
- pendingRedirect = null;
1566
- candidates.push({ raw: tok.replace(/^[<>&]+/, ''), role: 'stdin_redirect' });
1567
- continue;
1568
- }
1569
- if (pendingRedirect === 'heredoc') {
1570
- pendingRedirect = null;
1571
- continue;
1572
- }
1573
-
1574
- const redir = extractRedirectTokenTarget(tok);
1575
- if (redir) {
1576
- if (redir.kind === 'output_op') pendingRedirect = 'output';
1577
- else if (redir.kind === 'output_inline') candidates.push({ raw: redir.target, role: 'output_redirect' });
1578
- else if (redir.kind === 'stdin_op') pendingRedirect = 'stdin';
1579
- else if (redir.kind === 'stdin_inline') candidates.push({ raw: redir.target, role: 'stdin_redirect' });
1580
- else if (redir.kind === 'heredoc_op') pendingRedirect = 'heredoc';
1581
- continue;
1582
- }
1583
-
1584
- if (isOutputBinOnly || isBenignGit) {
1585
- continue;
1586
- }
1587
-
1588
- const isOption = tok.startsWith('-');
1589
- if (isOption && tok.includes('=')) {
1590
- const val = tok.slice(tok.indexOf('=') + 1).trim();
1591
- if (val) candidates.push({ raw: val, role: 'flag_val' });
1592
- } else if (!isOption) {
1593
- const posIdx = positionalArgs.length;
1594
- positionalArgs.push(tok);
1595
- candidates.push({ raw: tok, role: 'arg', posIdx });
1596
- }
1597
- }
1598
-
1599
- for (const item of candidates) {
1600
- const norm = String(item.raw || '').trim().replace(/\\/g, '/');
1601
- if (!norm || !isConfidentalSecretPath(norm, secretAllow)) continue;
1602
-
1603
- if (item.role === 'output_redirect') {
1604
- best = pickStricterVerdict(best, makeVerdict(gatedAskDecision, norm, 'Output redirection to'));
1605
- continue;
1606
- }
1607
- if (isNonPrivateCertPath(norm)) {
1608
- best = pickStricterVerdict(best, makeVerdict(gatedAskDecision, norm, 'Certificate operation referencing'));
1609
- continue;
1610
- }
1611
- if (item.role === 'stdin_redirect') {
1612
- best = pickStricterVerdict(best, makeVerdict('deny', norm));
1613
- continue;
1614
- }
1615
- if (isCopyMoveBin && item.role === 'arg') {
1616
- const isFinalDestArg = positionalArgs.length >= 2 && item.posIdx === positionalArgs.length - 1;
1617
- best = pickStricterVerdict(
1618
- best,
1619
- isFinalDestArg
1620
- ? makeVerdict(gatedAskDecision, norm, `${bin} destination targeting`)
1621
- : makeVerdict('deny', norm)
1622
- );
1623
- continue;
1624
- }
1625
- if (isReadExfilBin) {
1626
- best = pickStricterVerdict(best, makeVerdict('deny', norm));
1627
- } else {
1628
- best = pickStricterVerdict(best, makeVerdict(gatedAskDecision, norm, `${bin || 'Command'} argument referencing`));
1629
- }
1630
- }
1631
- }
1632
- }
1633
-
1634
- return best;
1635
- }
1636
-
1637
- /**
1638
- * DET-03: Protected Migration, Lockfile & Workflow Ask Gate.
1639
- * Triggers `"ask"` on manual `Edit`/`Write` to `migrations/*`, lockfiles, and `.github/workflows/*`.
1640
- */
1641
- export function evaluateDet03ProtectedFilesAskGate(params = {}) {
1642
- const toolName = String(params.toolName || '');
1643
- if (!EDIT_WRITE_TOOL_REGEX.test(toolName)) {
1644
- return { detectorId: 'DET-03', triggered: false, decision: 'allow', reason: null };
1645
- }
1646
-
1647
- const filePath = String(params.filePath || params.path || '').trim().replace(/\\/g, '/');
1648
- if (!filePath) {
1649
- return { detectorId: 'DET-03', triggered: false, decision: 'allow', reason: null };
1650
- }
1651
-
1652
- for (const pattern of PROTECTED_EDIT_PATTERNS) {
1653
- if (pattern.test(filePath)) {
1654
- return {
1655
- detectorId: 'DET-03',
1656
- triggered: true,
1657
- decision: 'ask',
1658
- targetPath: filePath,
1659
- reason: `[Burnoff DET-03 Protected File Ask Gate] Direct manual ${toolName} to "${filePath}" requires confirmation (use package manager CLI for lockfiles).`
1660
- };
1661
- }
1662
- }
1663
-
1664
- return { detectorId: 'DET-03', triggered: false, decision: 'allow', reason: null };
1665
- }
1666
-
1667
- export default {
1668
- SHELL_TOOL_REGEX,
1669
- EDIT_WRITE_TOOL_REGEX,
1670
- SEARCH_READ_TOOL_REGEX,
1671
- tokenizeShellSegment,
1672
- hasExplicitTestModifyIntent,
1673
- evaluateDet01GitAndShellSafety,
1674
- evaluateDet02SecretBoundary,
1675
- evaluateDet03ProtectedFilesAskGate
1676
- };
1
+ /**
2
+ * @file src/guards/shell-guard.mjs
3
+ * Deterministic Shell & Git Safety, Secret Boundary, and Protected File Ask-Gate (`DET-01`..`DET-03`).
4
+ * Zero external dependencies.
5
+ */
6
+
7
+ export const SHELL_TOOL_REGEX = /^(Bash|PowerShell|pwsh|cmd|sh|run_command|execute_bash)$/i;
8
+ export const EDIT_WRITE_TOOL_REGEX = /^(Edit|Write|MultiEdit|NotebookEdit)$/i;
9
+ export const SEARCH_READ_TOOL_REGEX = /^(Read|Grep|Glob|read_file|grep_search)$/i;
10
+
11
+ const GIT_GLOBAL_OPTS_WITH_ARG = new Set([
12
+ '-c',
13
+ '-C',
14
+ '--git-dir',
15
+ '--work-tree',
16
+ '--namespace',
17
+ '--super-prefix',
18
+ '--config-env'
19
+ ]);
20
+
21
+ const GIT_COMMIT_OPTS_WITH_ARG = new Set([
22
+ '-m',
23
+ '--message',
24
+ '-F',
25
+ '--file',
26
+ '-c',
27
+ '--reedit-message',
28
+ '-C',
29
+ '--reuse-message',
30
+ '--author',
31
+ '--date',
32
+ '--cleanup',
33
+ '-t',
34
+ '--template'
35
+ ]);
36
+
37
+ const GIT_CONFIG_OPTS_WITH_ARG = new Set([
38
+ '-f',
39
+ '--file',
40
+ '--blob',
41
+ '--type',
42
+ '-t',
43
+ '--default',
44
+ '--comment',
45
+ '--fixed-value'
46
+ ]);
47
+
48
+ const VALID_GIT_COMMIT_UNTRACKED_MODES = new Set(['', 'no', 'normal', 'all']);
49
+ const SHORT_COMMIT_ARG_CHARS = new Set(['m', 'F', 'c', 'C', 't']);
50
+
51
+ const SAFE_ENV_ALLOWLIST_REGEX =
52
+ /(?:^|[\\/])\.env\.(?:example|sample|template|defaults|schema)$/i;
53
+
54
+ const SECRET_FILE_PATTERNS = [
55
+ /(?:^|[\\/])\.env(?:\.[a-zA-Z0-9._-]+)?$/i,
56
+ /\.(?:pem|key|p12|pfx|crt)$/i,
57
+ /(?:^|[\\/])id_(?:rsa|ed25519|ecdsa|dsa)(?:\.pub)?$/i,
58
+ /(?:^|[\\/])\.(?:ssh|aws)[\\/]/i,
59
+ /(?:^|[\\/])\.(?:npmrc|netrc|pypirc)$/i
60
+ ];
61
+
62
+ const SECRET_READ_EXFIL_BINS = new Set([
63
+ 'cat',
64
+ 'head',
65
+ 'tail',
66
+ 'less',
67
+ 'more',
68
+ 'bat',
69
+ 'nl',
70
+ 'tac',
71
+ 'od',
72
+ 'xxd',
73
+ 'hexdump',
74
+ 'strings',
75
+ 'base64',
76
+ 'grep',
77
+ 'egrep',
78
+ 'fgrep',
79
+ 'rg',
80
+ 'ag',
81
+ 'awk',
82
+ 'sed',
83
+ 'cut',
84
+ 'sort',
85
+ 'uniq',
86
+ 'wc',
87
+ 'diff',
88
+ 'tr',
89
+ 'tee',
90
+ 'get-content',
91
+ 'gc',
92
+ 'type',
93
+ 'select-string',
94
+ 'curl',
95
+ 'wget',
96
+ 'scp',
97
+ 'rsync',
98
+ 'sftp',
99
+ 'ftp',
100
+ 'nc',
101
+ 'ncat',
102
+ 'socat',
103
+ 'source',
104
+ '.',
105
+ 'node',
106
+ 'python',
107
+ 'python3',
108
+ 'perl',
109
+ 'ruby',
110
+ 'bash',
111
+ 'sh',
112
+ 'zsh',
113
+ 'pwsh',
114
+ 'powershell'
115
+ ]);
116
+
117
+ const COPY_MOVE_BINS = new Set([
118
+ 'cp',
119
+ 'mv',
120
+ 'install',
121
+ 'copy-item',
122
+ 'move-item',
123
+ 'cpi',
124
+ 'mi'
125
+ ]);
126
+
127
+ const BENIGN_GIT_SUBCOMMANDS = new Set(['status', 'diff', 'log', 'branch']);
128
+
129
+ const PROTECTED_EDIT_PATTERNS = [
130
+ /(?:^|[\\/])migrations[\\/]/i,
131
+ /(?:^|[\\/])prisma[\\/]migrations[\\/]/i,
132
+ /(?:^|[\\/])(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|poetry\.lock|go\.sum)$/i,
133
+ /(?:^|[\\/])\.github[\\/]workflows[\\/]/i
134
+ ];
135
+
136
+ function detectPowerShellSyntax(toolName = 'Bash', command = '') {
137
+ if (/^(?:PowerShell|pwsh)$/i.test(String(toolName || ''))) {
138
+ return true;
139
+ }
140
+ const str = String(command || '');
141
+ return /(?:^|[;|&\r\n]\s*)&\s*['"A-Za-z0-9_.\\/]|(?:\$env:[A-Za-z_])|(?:`--|`-[A-Za-z])/i.test(
142
+ str
143
+ );
144
+ }
145
+
146
+ /**
147
+ * Tokenizes a shell command line into tokens while preserving quoted strings as single tokens.
148
+ * Supports both POSIX backslash escapes and PowerShell backtick escapes / `&` call operator.
149
+ */
150
+ export function tokenizeShellSegment(commandSegment = '', options = {}) {
151
+ const tokens = [];
152
+ const str = String(commandSegment || '').trim();
153
+ const isPowerShell = Boolean(options?.isPowerShell);
154
+ let current = '';
155
+ let quoteChar = null;
156
+
157
+ for (let i = 0; i < str.length; i++) {
158
+ const ch = str[i];
159
+ if (quoteChar === "'") {
160
+ if (ch === "'") {
161
+ if (isPowerShell && str[i + 1] === "'") {
162
+ current += "'";
163
+ i += 1;
164
+ } else {
165
+ quoteChar = null;
166
+ }
167
+ } else {
168
+ current += ch;
169
+ }
170
+ } else if (quoteChar === '"') {
171
+ if (isPowerShell && ch === '`' && i + 1 < str.length) {
172
+ const next = str[i + 1];
173
+ current += next === 'n' ? '\n' : next === 'r' ? '\r' : next === 't' ? '\t' : next;
174
+ i += 1;
175
+ } else if (!isPowerShell && ch === '\\' && i + 1 < str.length && ['"', '\\', '$', '`'].includes(str[i + 1])) {
176
+ current += str[i + 1];
177
+ i += 1;
178
+ } else if (isPowerShell && ch === '\\' && str[i + 1] === '"') {
179
+ current += '"';
180
+ i += 1;
181
+ } else if (ch === '"') {
182
+ quoteChar = null;
183
+ } else {
184
+ current += ch;
185
+ }
186
+ } else if (ch === '"' || ch === "'") {
187
+ quoteChar = ch;
188
+ } else if (isPowerShell && ch === '`' && i + 1 < str.length) {
189
+ const next = str[i + 1];
190
+ current += next === 'n' ? '\n' : next === 'r' ? '\r' : next === 't' ? '\t' : next;
191
+ i += 1;
192
+ } else if (!isPowerShell && ch === '\\' && i + 1 < str.length) {
193
+ current += str[i + 1];
194
+ i += 1;
195
+ } else if (current.length === 0 && ch === '&' && str[i + 1] !== '&' && str[i + 1] !== '>') {
196
+ tokens.push('&');
197
+ } else if (/\s/.test(ch)) {
198
+ if (current.length > 0) {
199
+ tokens.push(current);
200
+ current = '';
201
+ }
202
+ } else {
203
+ current += ch;
204
+ }
205
+ }
206
+ if (current.length > 0) {
207
+ tokens.push(current);
208
+ }
209
+ return tokens;
210
+ }
211
+
212
+ function scanBalancedParens(str = '', openParenIdx = 0) {
213
+ let depth = 1;
214
+ let j = openParenIdx + 1;
215
+ let innerQuote = null;
216
+ while (j < str.length && depth > 0) {
217
+ const c = str[j];
218
+ if (innerQuote === "'") {
219
+ if (c === "'") innerQuote = null;
220
+ } else if (innerQuote === '"') {
221
+ if (c === '\\' && j + 1 < str.length) {
222
+ j += 1;
223
+ } else if (c === '"') {
224
+ innerQuote = null;
225
+ }
226
+ } else if (c === "'" || c === '"') {
227
+ innerQuote = c;
228
+ } else if (c === '(') {
229
+ depth += 1;
230
+ } else if (c === ')') {
231
+ depth -= 1;
232
+ if (depth === 0) break;
233
+ }
234
+ j += 1;
235
+ }
236
+ if (depth !== 0) return null;
237
+ return { inner: str.slice(openParenIdx + 1, j).trim(), closeIdx: j };
238
+ }
239
+
240
+ function extractCommandSubstitutions(commandLine = '', options = {}) {
241
+ const extracted = [];
242
+ const str = String(commandLine || '');
243
+ const isPowerShell = Boolean(options?.isPowerShell);
244
+ let quoteChar = null;
245
+
246
+ for (let i = 0; i < str.length; i++) {
247
+ const ch = str[i];
248
+ if (quoteChar === "'") {
249
+ if (ch === "'") quoteChar = null;
250
+ continue;
251
+ }
252
+ if (quoteChar === '"') {
253
+ if ((ch === '\\' || (isPowerShell && ch === '`')) && i + 1 < str.length) {
254
+ i += 1;
255
+ continue;
256
+ }
257
+ if (ch === '"') {
258
+ quoteChar = null;
259
+ continue;
260
+ }
261
+ } else if (ch === "'" || ch === '"') {
262
+ quoteChar = ch;
263
+ continue;
264
+ } else if ((ch === '\\' || (isPowerShell && ch === '`')) && i + 1 < str.length) {
265
+ i += 1;
266
+ continue;
267
+ }
268
+
269
+ if (ch === '$' && str[i + 1] === '(') {
270
+ const paren = scanBalancedParens(str, i + 1);
271
+ if (paren) {
272
+ if (paren.inner) extracted.push(paren.inner);
273
+ i = paren.closeIdx;
274
+ }
275
+ continue;
276
+ }
277
+
278
+ if (!quoteChar && !isPowerShell && (ch === '<' || ch === '>') && str[i + 1] === '(') {
279
+ const paren = scanBalancedParens(str, i + 1);
280
+ if (paren) {
281
+ if (paren.inner) extracted.push(paren.inner);
282
+ i = paren.closeIdx;
283
+ }
284
+ continue;
285
+ }
286
+
287
+ if (!isPowerShell && ch === '`') {
288
+ let j = i + 1;
289
+ while (j < str.length) {
290
+ if (str[j] === '\\' && j + 1 < str.length) {
291
+ j += 2;
292
+ continue;
293
+ }
294
+ if (str[j] === '`') break;
295
+ j += 1;
296
+ }
297
+ if (j < str.length && str[j] === '`') {
298
+ const inner = str.slice(i + 1, j).trim();
299
+ if (inner && !inner.startsWith('-')) {
300
+ extracted.push(inner);
301
+ }
302
+ i = j;
303
+ }
304
+ }
305
+ }
306
+
307
+ return extracted;
308
+ }
309
+
310
+ function splitCommandSegments(commandLine = '', options = {}) {
311
+ const segments = [];
312
+ const str = String(commandLine || '');
313
+ const isPowerShell = Boolean(options?.isPowerShell);
314
+ let current = '';
315
+ let quoteChar = null;
316
+ let subshellDepth = 0;
317
+
318
+ for (let i = 0; i < str.length; i++) {
319
+ const ch = str[i];
320
+ if (quoteChar === "'") {
321
+ current += ch;
322
+ if (ch === "'") {
323
+ if (isPowerShell && str[i + 1] === "'") {
324
+ current += "'";
325
+ i += 1;
326
+ } else {
327
+ quoteChar = null;
328
+ }
329
+ }
330
+ continue;
331
+ }
332
+ if (quoteChar === '"') {
333
+ current += ch;
334
+ if ((ch === '\\' || (isPowerShell && ch === '`')) && i + 1 < str.length) {
335
+ current += str[i + 1];
336
+ i += 1;
337
+ } else if (ch === '"') {
338
+ quoteChar = null;
339
+ }
340
+ continue;
341
+ }
342
+
343
+ if (ch === '"' || ch === "'") {
344
+ quoteChar = ch;
345
+ current += ch;
346
+ continue;
347
+ }
348
+
349
+ if ((ch === '\\' || (isPowerShell && ch === '`')) && i + 1 < str.length) {
350
+ current += ch + str[i + 1];
351
+ i += 1;
352
+ continue;
353
+ }
354
+
355
+ if (ch === '$' && str[i + 1] === '(') {
356
+ subshellDepth += 1;
357
+ current += '$(';
358
+ i += 1;
359
+ continue;
360
+ }
361
+ if (subshellDepth > 0) {
362
+ if (ch === '(') subshellDepth += 1;
363
+ else if (ch === ')') subshellDepth -= 1;
364
+ current += ch;
365
+ continue;
366
+ }
367
+
368
+ if (ch === ';' || ch === '\n' || ch === '\r') {
369
+ if (current.trim()) segments.push(current.trim());
370
+ current = '';
371
+ continue;
372
+ }
373
+
374
+ if ((ch === '&' && str[i + 1] === '&') || (ch === '|' && str[i + 1] === '|')) {
375
+ if (current.trim()) segments.push(current.trim());
376
+ current = '';
377
+ i += 1;
378
+ continue;
379
+ }
380
+
381
+ if (ch === '|') {
382
+ if (current.trim()) segments.push(current.trim());
383
+ current = '';
384
+ if (str[i + 1] === '&') i += 1;
385
+ continue;
386
+ }
387
+
388
+ const prevChar = i > 0 ? str[i - 1] : '';
389
+ const nextChar = i + 1 < str.length ? str[i + 1] : '';
390
+ if (
391
+ ch === '&' &&
392
+ current.trim().length > 0 &&
393
+ prevChar !== '>' &&
394
+ prevChar !== '<' &&
395
+ nextChar !== '>' &&
396
+ nextChar !== '&'
397
+ ) {
398
+ segments.push(current.trim());
399
+ current = '';
400
+ continue;
401
+ }
402
+
403
+ current += ch;
404
+ }
405
+
406
+ if (current.trim()) {
407
+ segments.push(current.trim());
408
+ }
409
+ return segments;
410
+ }
411
+
412
+ function checkForbiddenGitEnvAssignment(rawKey, rawVal) {
413
+ const key = String(rawKey || '').trim().toUpperCase();
414
+ const val = String(rawVal ?? '')
415
+ .trim()
416
+ .replace(/^['"]|['"]$/g, '');
417
+
418
+ if (
419
+ (key === 'HUSKY' && val === '0') ||
420
+ (key === 'HUSKY_SKIP_HOOKS' && (val === '1' || val.toLowerCase() === 'true')) ||
421
+ (key === 'SKIP_GIT_HOOKS' && (val === '1' || val.toLowerCase() === 'true'))
422
+ ) {
423
+ return {
424
+ subType: 'GIT_HOOK_ENV_BYPASS',
425
+ reason: `[Burnoff DET-01 Git Hook Bypass Blocked] Disabling git hooks via ${key}=${val} is forbidden.`
426
+ };
427
+ }
428
+
429
+ if (
430
+ (key === 'GIT_CONFIG_COUNT' && /^[1-9]\d*$/.test(val)) ||
431
+ (/^GIT_CONFIG_KEY_\d+$/.test(key) && /^core\.hooksPath$/i.test(val)) ||
432
+ (key === 'GIT_CONFIG_PARAMETERS' && /core\.hooksPath/i.test(val))
433
+ ) {
434
+ return {
435
+ subType: 'GIT_HOOKS_PATH_OVERRIDE',
436
+ reason: `[Burnoff DET-01 Git Hook Bypass Blocked] Overriding git config via environment variable ${key}=${val} is forbidden.`
437
+ };
438
+ }
439
+
440
+ return null;
441
+ }
442
+
443
+ function splitEnvKeyValToken(token = '') {
444
+ const m = String(token || '').match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s);
445
+ if (!m) return null;
446
+ return { key: m[1], value: m[2] };
447
+ }
448
+
449
+ /**
450
+ * Checks whether the user's prompt explicitly requested modifying, deleting, or skipping tests.
451
+ */
452
+ export function hasExplicitTestModifyIntent(promptText = '') {
453
+ const s = String(promptText || '');
454
+ if (!s) return false;
455
+ return (
456
+ /\b(?:edit|update|modify|delete|remove|drop|skip|disable|rewrite|adjust|refactor)\s+(?:(?:the|all|any|some|these|those|existing|failing|obsolete|legacy|old|broken|flaky|unit|integration|e2e)\s+)*(?:tests?|specs?|assertions?)\b/i.test(
457
+ s
458
+ ) ||
459
+ (/\.(?:test|spec)\.[a-z0-9]+\b/i.test(s) &&
460
+ /\b(?:delete|remove|drop|skip|disable|update|rewrite)\b/i.test(s))
461
+ );
462
+ }
463
+
464
+ function isProtectedTestFileToken(token = '') {
465
+ const norm = String(token || '').trim().replace(/^['"]|['"]$/g, '').replace(/\\/g, '/');
466
+ if (!norm) return false;
467
+ if (
468
+ /^(?:\/tmp\/|\/var\/folders\/)/i.test(norm) ||
469
+ /(?:^|\/)(?:tmp|temp|\.claude\/cache|\.burnoff\/tmp)\//i.test(norm) ||
470
+ /appdata\/local\/temp\//i.test(norm)
471
+ ) {
472
+ return false;
473
+ }
474
+ return (
475
+ /\.(?:test|spec)\.(?:[cm]?[jt]sx?|py|go|rs)$/i.test(norm) ||
476
+ /(?:^|\/)(?:test|tests|__tests__)\/.*\.(?:[cm]?[jt]sx?|py|go|rs)$/i.test(norm) ||
477
+ /_test\.(?:py|go)$/i.test(norm)
478
+ );
479
+ }
480
+
481
+ /**
482
+ * DET-01: Destructive Shell & Git Hook-Bypass Blocker (`Bash|PowerShell`).
483
+ * Skips option arguments (such as `git commit -m "-next"`), allows `-n` dry-runs on `git log`/`clean`,
484
+ * downgrades un-stashed `git checkout --` / `git restore` to `ask` in default `guard`/`COACH` mode,
485
+ * and allows them within 120s of a recorded `git stash`.
486
+ */
487
+ export function evaluateDet01GitAndShellSafety(params = {}, _depth = 0) {
488
+ if (_depth > 4) {
489
+ return { detectorId: 'DET-01', triggered: false, decision: 'allow', reason: null };
490
+ }
491
+
492
+ const toolName = String(params.toolName || 'Bash');
493
+ if (!SHELL_TOOL_REGEX.test(toolName)) {
494
+ return { detectorId: 'DET-01', triggered: false, decision: 'allow', reason: null };
495
+ }
496
+
497
+ const command = String(params.command || params.cmd || '').trim();
498
+ if (!command) {
499
+ return { detectorId: 'DET-01', triggered: false, decision: 'allow', reason: null };
500
+ }
501
+
502
+ const isPowerShell = detectPowerShellSyntax(toolName, command);
503
+ const nowMs = Number(params.nowMs ?? Date.now());
504
+ const recentStashActive =
505
+ /\bgit\s+stash\b[\s\S]*?(?:&&|;)\s*git\s+(?:checkout|restore)\b/i.test(command) ||
506
+ (Number.isFinite(Number(params.recentGitStashAtMs)) &&
507
+ Number(params.recentGitStashAtMs) > 0 &&
508
+ nowMs - Number(params.recentGitStashAtMs) <= 120_000);
509
+ const rawMode = String(params.mode ?? params.flightMode ?? 'guard').trim().toUpperCase();
510
+ const isStrictAutoMode = rawMode === 'STRICT' || rawMode === 'AUTO' || rawMode === 'AUTO_PILOT';
511
+ const strictTestIntegrity = Boolean(params.strictTestIntegrity);
512
+
513
+ // 1. Recursively inspect $(...) and POSIX backtick command substitutions
514
+ const substitutions = extractCommandSubstitutions(command, { isPowerShell });
515
+ for (const subCmd of substitutions) {
516
+ const subVerdict = evaluateDet01GitAndShellSafety(
517
+ {
518
+ toolName: isPowerShell ? 'PowerShell' : toolName,
519
+ command: subCmd,
520
+ mode: params.mode,
521
+ flightMode: params.flightMode,
522
+ recentGitStashAtMs: params.recentGitStashAtMs,
523
+ strictTestIntegrity: params.strictTestIntegrity,
524
+ nowMs
525
+ },
526
+ _depth + 1
527
+ );
528
+ if (subVerdict.triggered) return subVerdict;
529
+ }
530
+
531
+ // 2. Inspect individual segments after splitting on ;, &&, ||, |, newlines, &
532
+ let sawGitStashInCommand = false;
533
+ const segments = splitCommandSegments(command, { isPowerShell });
534
+ for (const segment of segments) {
535
+ const rawTokens = tokenizeShellSegment(segment, { isPowerShell });
536
+ if (rawTokens.length === 0) continue;
537
+
538
+ let idx = 0;
539
+ while (idx < rawTokens.length && rawTokens[idx] === '&') {
540
+ idx += 1;
541
+ }
542
+ if (idx >= rawTokens.length) continue;
543
+
544
+ const psEnvMatch = rawTokens[idx].match(/^\$env:([A-Za-z_][A-Za-z0-9_]*)(?:=(.*))?$/is);
545
+ if (psEnvMatch) {
546
+ const envKey = psEnvMatch[1];
547
+ let envVal = psEnvMatch[2];
548
+ if (envVal === undefined) {
549
+ if (rawTokens[idx + 1] === '=') {
550
+ envVal = rawTokens[idx + 2] ?? '';
551
+ } else if (rawTokens[idx + 1]?.startsWith('=')) {
552
+ envVal = rawTokens[idx + 1].slice(1) || (rawTokens[idx + 2] ?? '');
553
+ }
554
+ }
555
+ if (envVal !== undefined) {
556
+ const envHit = checkForbiddenGitEnvAssignment(envKey, envVal);
557
+ if (envHit) {
558
+ return {
559
+ detectorId: 'DET-01',
560
+ triggered: true,
561
+ decision: 'deny',
562
+ subType: envHit.subType,
563
+ reason: envHit.reason
564
+ };
565
+ }
566
+ }
567
+ continue;
568
+ }
569
+
570
+ if (/^(?:Set-Item|si)$/i.test(rawTokens[idx]) && rawTokens[idx + 1]) {
571
+ const envPathMatch = rawTokens[idx + 1].match(/^env:[\\/]?([A-Za-z_][A-Za-z0-9_]*)$/i);
572
+ if (envPathMatch) {
573
+ const envHit = checkForbiddenGitEnvAssignment(envPathMatch[1], rawTokens[idx + 2] ?? '');
574
+ if (envHit) {
575
+ return {
576
+ detectorId: 'DET-01',
577
+ triggered: true,
578
+ decision: 'deny',
579
+ subType: envHit.subType,
580
+ reason: envHit.reason
581
+ };
582
+ }
583
+ }
584
+ }
585
+
586
+ const firstWordLower = rawTokens[idx].toLowerCase();
587
+ if (firstWordLower === 'export' || firstWordLower === 'set') {
588
+ for (let eIdx = idx + 1; eIdx < rawTokens.length; eIdx++) {
589
+ const kv = splitEnvKeyValToken(rawTokens[eIdx]);
590
+ if (kv) {
591
+ const envHit = checkForbiddenGitEnvAssignment(kv.key, kv.value);
592
+ if (envHit) {
593
+ return {
594
+ detectorId: 'DET-01',
595
+ triggered: true,
596
+ decision: 'deny',
597
+ subType: envHit.subType,
598
+ reason: envHit.reason
599
+ };
600
+ }
601
+ }
602
+ }
603
+ continue;
604
+ }
605
+
606
+ while (idx < rawTokens.length) {
607
+ const kv = splitEnvKeyValToken(rawTokens[idx]);
608
+ if (!kv) break;
609
+ const envHit = checkForbiddenGitEnvAssignment(kv.key, kv.value);
610
+ if (envHit) {
611
+ return {
612
+ detectorId: 'DET-01',
613
+ triggered: true,
614
+ decision: 'deny',
615
+ subType: envHit.subType,
616
+ reason: envHit.reason
617
+ };
618
+ }
619
+ idx += 1;
620
+ }
621
+ while (idx < rawTokens.length && rawTokens[idx] === '&') {
622
+ idx += 1;
623
+ }
624
+ if (idx >= rawTokens.length) continue;
625
+
626
+ let bin = rawTokens[idx].replace(/^.*[\\/]/, '').toLowerCase();
627
+ if (bin === 'env' || bin === 'env.exe') {
628
+ idx += 1;
629
+ while (idx < rawTokens.length) {
630
+ const t = rawTokens[idx];
631
+ if (t === '-u' || t === '--unset' || t === '-C' || t === '--chdir' || t === '-S') {
632
+ idx += 2;
633
+ continue;
634
+ }
635
+ if (t.startsWith('-')) {
636
+ idx += 1;
637
+ continue;
638
+ }
639
+ const kv = splitEnvKeyValToken(t);
640
+ if (kv) {
641
+ const envHit = checkForbiddenGitEnvAssignment(kv.key, kv.value);
642
+ if (envHit) {
643
+ return {
644
+ detectorId: 'DET-01',
645
+ triggered: true,
646
+ decision: 'deny',
647
+ subType: envHit.subType,
648
+ reason: envHit.reason
649
+ };
650
+ }
651
+ idx += 1;
652
+ continue;
653
+ }
654
+ break;
655
+ }
656
+ if (idx >= rawTokens.length) continue;
657
+ bin = rawTokens[idx].replace(/^.*[\\/]/, '').toLowerCase();
658
+ }
659
+
660
+ const userExplicitTestIntent =
661
+ Boolean(params.userExplicitTestIntent) ||
662
+ hasExplicitTestModifyIntent(params.lastUserInput || params.prompt || '');
663
+ if (['bash', 'bash.exe', 'sh', 'sh.exe', 'zsh', 'dash'].includes(bin)) {
664
+ const cPos = rawTokens.findIndex((t, ti) => ti > idx && (t === '-c' || /^-[a-zA-Z]*c$/.test(t)));
665
+ if (cPos !== -1 && rawTokens[cPos + 1]) {
666
+ const nested = evaluateDet01GitAndShellSafety(
667
+ {
668
+ toolName: 'Bash',
669
+ command: rawTokens[cPos + 1],
670
+ userExplicitTestIntent,
671
+ lastUserInput: params.lastUserInput || params.prompt || '',
672
+ mode: params.mode,
673
+ flightMode: params.flightMode,
674
+ recentGitStashAtMs: params.recentGitStashAtMs,
675
+ strictTestIntegrity: params.strictTestIntegrity,
676
+ nowMs
677
+ },
678
+ _depth + 1
679
+ );
680
+ if (nested.triggered) return nested;
681
+ }
682
+ continue;
683
+ }
684
+ if (bin === 'cmd' || bin === 'cmd.exe') {
685
+ const cPos = rawTokens.findIndex((t, ti) => ti > idx && /^\/[ck]$/i.test(t));
686
+ if (cPos !== -1 && cPos + 1 < rawTokens.length) {
687
+ const nestedCmd = rawTokens.slice(cPos + 1).join(' ');
688
+ const nested = evaluateDet01GitAndShellSafety(
689
+ {
690
+ toolName: 'cmd',
691
+ command: nestedCmd,
692
+ userExplicitTestIntent,
693
+ lastUserInput: params.lastUserInput || params.prompt || '',
694
+ mode: params.mode,
695
+ flightMode: params.flightMode,
696
+ recentGitStashAtMs: params.recentGitStashAtMs,
697
+ strictTestIntegrity: params.strictTestIntegrity,
698
+ nowMs
699
+ },
700
+ _depth + 1
701
+ );
702
+ if (nested.triggered) return nested;
703
+ }
704
+ continue;
705
+ }
706
+ if (['powershell', 'powershell.exe', 'pwsh', 'pwsh.exe'].includes(bin)) {
707
+ const cPos = rawTokens.findIndex((t, ti) => ti > idx && /^-(?:c|command)$/i.test(t));
708
+ if (cPos !== -1 && cPos + 1 < rawTokens.length) {
709
+ const nestedCmd = rawTokens.slice(cPos + 1).join(' ');
710
+ const nested = evaluateDet01GitAndShellSafety(
711
+ {
712
+ toolName: 'PowerShell',
713
+ command: nestedCmd,
714
+ userExplicitTestIntent,
715
+ lastUserInput: params.lastUserInput || params.prompt || '',
716
+ mode: params.mode,
717
+ flightMode: params.flightMode,
718
+ recentGitStashAtMs: params.recentGitStashAtMs,
719
+ strictTestIntegrity: params.strictTestIntegrity,
720
+ nowMs
721
+ },
722
+ _depth + 1
723
+ );
724
+ if (nested.triggered) return nested;
725
+ }
726
+ continue;
727
+ }
728
+
729
+ function isExplicitTempTarget(normArg = '') {
730
+ return /^(?:\/tmp(?:\/|$)|\/var\/folders(?:\/|$)|\$tmpdir(?:\/|$)|\$\{tmpdir\}(?:\/|$)|\$\{?env:(?:temp|tmp)\}?[\\/]|(?:[a-z]:)?[\\/]?(?:temp|tmp)(?:\/|$))/i.test(
731
+ String(normArg || '').replace(/\\/g, '/')
732
+ );
733
+ }
734
+
735
+ function isProtectedRecursiveDeleteTarget(rawArg = '') {
736
+ const norm = String(rawArg || '').trim().replace(/^["']|["']$/g, '').replace(/\\/g, '/');
737
+ if (!norm || norm.startsWith('-')) return false;
738
+ if (isExplicitTempTarget(norm)) return false;
739
+ if (/^(?:\/+|\/\*|\~|\$HOME|\$\{HOME\}|\$env:USERPROFILE|[A-Za-z]:\/?)$/i.test(norm)) {
740
+ return true;
741
+ }
742
+ const stripped = norm.replace(/\/+$/, '').replace(/^\.\//, '');
743
+ if (norm === '.' || norm === './' || stripped === '' || stripped === '*') {
744
+ return true;
745
+ }
746
+ return /^(?:src|test|tests|__tests__)(?:\/\*|\/)?$/i.test(stripped);
747
+ }
748
+
749
+ if (bin === 'rm' || bin === 'rm.exe' || bin === 'unlink' || bin === 'unlink.exe') {
750
+ const rmArgs = rawTokens.slice(idx + 1);
751
+ const hasRecursive = rmArgs.some(
752
+ (a) => a === '--recursive' || (/^-[a-zA-Z]+$/.test(a) && /[rR]/.test(a))
753
+ );
754
+ const hasForce = rmArgs.some(
755
+ (a) => a === '--force' || (/^-[a-zA-Z]+$/.test(a) && /f/.test(a))
756
+ );
757
+ const targetsRootOrHome = rmArgs.some((a) => isProtectedRecursiveDeleteTarget(a));
758
+ if (hasRecursive && hasForce && targetsRootOrHome) {
759
+ return {
760
+ detectorId: 'DET-01',
761
+ triggered: true,
762
+ decision: 'deny',
763
+ subType: 'DESTRUCTIVE_FS_WIPE',
764
+ reason: '[Burnoff DET-01 Destructive Shell Blocked] Recursive root/home/repo/src/test deletion is forbidden.'
765
+ };
766
+ }
767
+ if (!userExplicitTestIntent) {
768
+ const deletedTestTarget = rmArgs.find(
769
+ (a) => !a.startsWith('-') && isProtectedTestFileToken(a)
770
+ );
771
+ if (deletedTestTarget) {
772
+ return {
773
+ detectorId: 'DET-01',
774
+ triggered: true,
775
+ decision: isStrictAutoMode ? 'deny' : 'ask',
776
+ subType: 'TEST_FILE_DELETION',
777
+ reason: `[Burnoff DET-01 Test Integrity Lock] Deleting test file "${deletedTestTarget}" via shell without explicit user instruction requires confirmation.`
778
+ };
779
+ }
780
+ }
781
+ continue;
782
+ }
783
+
784
+ if (/^(?:remove-item|ri|del|erase|rmdir)$/i.test(bin)) {
785
+ const psArgs = rawTokens.slice(idx + 1);
786
+ const hasRecurse = psArgs.some((a) => /^-r(?:ecurse)?$/i.test(a));
787
+ const hasForce = psArgs.some((a) => /^-f(?:orce)?$/i.test(a));
788
+ const targetsRootOrHome = psArgs.some((a) => isProtectedRecursiveDeleteTarget(a));
789
+ if (hasRecurse && hasForce && targetsRootOrHome) {
790
+ return {
791
+ detectorId: 'DET-01',
792
+ triggered: true,
793
+ decision: 'deny',
794
+ subType: 'DESTRUCTIVE_FS_WIPE',
795
+ reason: '[Burnoff DET-01 Destructive Shell Blocked] Recursive root/home/repo/src/test deletion is forbidden.'
796
+ };
797
+ }
798
+ if (!userExplicitTestIntent) {
799
+ const deletedTestTarget = psArgs.find(
800
+ (a) => !a.startsWith('-') && !a.startsWith('/') && isProtectedTestFileToken(a)
801
+ );
802
+ if (deletedTestTarget) {
803
+ return {
804
+ detectorId: 'DET-01',
805
+ triggered: true,
806
+ decision: isStrictAutoMode ? 'deny' : 'ask',
807
+ subType: 'TEST_FILE_DELETION',
808
+ reason: `[Burnoff DET-01 Test Integrity Lock] Deleting test file "${deletedTestTarget}" via shell without explicit user instruction requires confirmation.`
809
+ };
810
+ }
811
+ }
812
+ continue;
813
+ }
814
+
815
+ if (bin !== 'git' && bin !== 'git.exe') continue;
816
+ idx += 1;
817
+
818
+ let subcommand = null;
819
+ while (idx < rawTokens.length) {
820
+ const tok = rawTokens[idx];
821
+ if (!tok.startsWith('-')) {
822
+ subcommand = tok.toLowerCase();
823
+ idx += 1;
824
+ break;
825
+ }
826
+ if (tok === '-c' && idx + 1 < rawTokens.length) {
827
+ const cfg = rawTokens[idx + 1];
828
+ if (/^core\.hooksPath(?:\s*=|$)/i.test(cfg)) {
829
+ return {
830
+ detectorId: 'DET-01',
831
+ triggered: true,
832
+ decision: 'deny',
833
+ subType: 'GIT_HOOKS_PATH_OVERRIDE',
834
+ reason: `[Burnoff DET-01 Git Hook Bypass Blocked] Overriding core.hooksPath via "git -c ${cfg}" is forbidden.`
835
+ };
836
+ }
837
+ idx += 2;
838
+ continue;
839
+ }
840
+ if (
841
+ /^-c\s*core\.hooksPath(?:\s*=|$)/i.test(tok) ||
842
+ /^--config-env=core\.hooksPath(?:=|$)/i.test(tok)
843
+ ) {
844
+ return {
845
+ detectorId: 'DET-01',
846
+ triggered: true,
847
+ decision: 'deny',
848
+ subType: 'GIT_HOOKS_PATH_OVERRIDE',
849
+ reason: '[Burnoff DET-01 Git Hook Bypass Blocked] Overriding core.hooksPath is forbidden.'
850
+ };
851
+ }
852
+ if (tok === '--config-env' && idx + 1 < rawTokens.length) {
853
+ if (/^core\.hooksPath(?:=|$)/i.test(rawTokens[idx + 1])) {
854
+ return {
855
+ detectorId: 'DET-01',
856
+ triggered: true,
857
+ decision: 'deny',
858
+ subType: 'GIT_HOOKS_PATH_OVERRIDE',
859
+ reason: '[Burnoff DET-01 Git Hook Bypass Blocked] Overriding core.hooksPath via --config-env is forbidden.'
860
+ };
861
+ }
862
+ idx += 2;
863
+ continue;
864
+ }
865
+ if (GIT_GLOBAL_OPTS_WITH_ARG.has(tok)) {
866
+ idx += 2;
867
+ } else {
868
+ idx += 1;
869
+ }
870
+ }
871
+
872
+ if (!subcommand) continue;
873
+
874
+ const subArgs = rawTokens.slice(idx);
875
+
876
+ if (subcommand === 'rm' && !userExplicitTestIntent) {
877
+ const deletedTestTarget = subArgs.find(
878
+ (a) => !a.startsWith('-') && isProtectedTestFileToken(a)
879
+ );
880
+ if (deletedTestTarget) {
881
+ return {
882
+ detectorId: 'DET-01',
883
+ triggered: true,
884
+ decision: isStrictAutoMode ? 'deny' : 'ask',
885
+ subType: 'TEST_FILE_DELETION',
886
+ reason: `[Burnoff DET-01 Test Integrity Lock] Deleting test file "${deletedTestTarget}" via "git rm" without explicit user instruction requires confirmation.`
887
+ };
888
+ }
889
+ }
890
+
891
+ if (subcommand === 'config') {
892
+ let isReadOnlyQuery = false;
893
+ const positional = [];
894
+ for (let i = 0; i < subArgs.length; i++) {
895
+ const arg = subArgs[i];
896
+ if (arg === '--') {
897
+ positional.push(...subArgs.slice(i + 1));
898
+ break;
899
+ }
900
+ if (
901
+ arg === '--get' ||
902
+ arg === '--get-all' ||
903
+ arg === '--get-regexp' ||
904
+ arg === '--get-urlmatch' ||
905
+ arg === '--list' ||
906
+ arg === '-l'
907
+ ) {
908
+ isReadOnlyQuery = true;
909
+ break;
910
+ }
911
+ if (GIT_CONFIG_OPTS_WITH_ARG.has(arg)) {
912
+ i += 1;
913
+ continue;
914
+ }
915
+ if (arg.startsWith('-')) {
916
+ continue;
917
+ }
918
+ positional.push(arg);
919
+ }
920
+
921
+ if (!isReadOnlyQuery && positional.length >= 2) {
922
+ const firstPosLower = positional[0].toLowerCase();
923
+ if (firstPosLower !== 'get' && firstPosLower !== 'list') {
924
+ const cfgKey = firstPosLower === 'set' ? positional[1] || '' : positional[0];
925
+ const hasCfgVal = firstPosLower === 'set' ? positional.length >= 3 : positional.length >= 2;
926
+ if (hasCfgVal && /^core\.hooksPath$/i.test(cfgKey)) {
927
+ return {
928
+ detectorId: 'DET-01',
929
+ triggered: true,
930
+ decision: 'deny',
931
+ subType: 'GIT_HOOKS_PATH_OVERRIDE',
932
+ reason: '[Burnoff DET-01 Git Hook Bypass Blocked] Mutating "git config core.hooksPath" is forbidden.'
933
+ };
934
+ }
935
+ }
936
+ }
937
+ continue;
938
+ }
939
+
940
+ if (subcommand === 'reset' && subArgs.includes('--hard')) {
941
+ return {
942
+ detectorId: 'DET-01',
943
+ triggered: true,
944
+ decision: 'deny',
945
+ subType: 'GIT_RESET_HARD',
946
+ reason: '[Burnoff DET-01 Destructive Git Blocked] "git reset --hard" destroys uncommitted work.'
947
+ };
948
+ }
949
+
950
+ if (subcommand === 'clean') {
951
+ let hasDryRun = false;
952
+ let hasForce = false;
953
+ let hasExplicitLongForce = false;
954
+ for (let i = 0; i < subArgs.length; i++) {
955
+ const arg = subArgs[i];
956
+ if (arg === '--') break;
957
+ if (arg === '-e' || arg === '--exclude') {
958
+ i += 1;
959
+ continue;
960
+ }
961
+ if (arg === '-n' || arg === '--dry-run' || (/^-[a-zA-Z]+$/.test(arg) && arg.includes('n'))) {
962
+ hasDryRun = true;
963
+ }
964
+ if (arg === '--force') {
965
+ hasForce = true;
966
+ hasExplicitLongForce = true;
967
+ } else if (/^-[a-zA-Z]*f[a-zA-Z]*$/.test(arg)) {
968
+ hasForce = true;
969
+ }
970
+ }
971
+ if (hasForce && (!hasDryRun || hasExplicitLongForce)) {
972
+ return {
973
+ detectorId: 'DET-01',
974
+ triggered: true,
975
+ decision: 'deny',
976
+ subType: 'GIT_CLEAN_FORCE',
977
+ reason: '[Burnoff DET-01 Destructive Git Blocked] "git clean -f" permanently deletes untracked files (use "git clean -n" for dry-run).'
978
+ };
979
+ }
980
+ }
981
+
982
+ if (subcommand === 'commit') {
983
+ for (let i = 0; i < subArgs.length; i++) {
984
+ const arg = subArgs[i];
985
+ if (arg === '--') break;
986
+
987
+ if (arg === '--no-verify') {
988
+ return {
989
+ detectorId: 'DET-01',
990
+ triggered: true,
991
+ decision: 'deny',
992
+ subType: 'GIT_COMMIT_NO_VERIFY',
993
+ reason: '[Burnoff DET-01 Git Hook Bypass Blocked] "git commit --no-verify" is forbidden.'
994
+ };
995
+ }
996
+
997
+ if (GIT_COMMIT_OPTS_WITH_ARG.has(arg)) {
998
+ i += 1;
999
+ continue;
1000
+ }
1001
+
1002
+ if (arg.startsWith('--')) {
1003
+ continue;
1004
+ }
1005
+
1006
+ if (arg.startsWith('-') && arg.length > 1) {
1007
+ const cluster = arg.slice(1);
1008
+ if (
1009
+ !SHORT_COMMIT_ARG_CHARS.has(cluster[0]) &&
1010
+ cluster[0] !== 'u' &&
1011
+ /^[amnvqseS]+$/.test(cluster)
1012
+ ) {
1013
+ if (cluster.includes('n')) {
1014
+ return {
1015
+ detectorId: 'DET-01',
1016
+ triggered: true,
1017
+ decision: 'deny',
1018
+ subType: 'GIT_COMMIT_SHORT_NO_VERIFY',
1019
+ reason: `[Burnoff DET-01 Git Hook Bypass Blocked] Short flag "-n" (--no-verify) in "git commit ${arg}" is forbidden.`
1020
+ };
1021
+ }
1022
+ if (cluster.includes('m')) {
1023
+ i += 1;
1024
+ }
1025
+ continue;
1026
+ }
1027
+
1028
+ let consumedRestOfToken = false;
1029
+ for (let cIdx = 0; cIdx < cluster.length; cIdx++) {
1030
+ const ch = cluster[cIdx];
1031
+ if (ch === 'n') {
1032
+ return {
1033
+ detectorId: 'DET-01',
1034
+ triggered: true,
1035
+ decision: 'deny',
1036
+ subType: 'GIT_COMMIT_SHORT_NO_VERIFY',
1037
+ reason: `[Burnoff DET-01 Git Hook Bypass Blocked] Short flag "-n" (--no-verify) in "git commit ${arg}" is forbidden.`
1038
+ };
1039
+ }
1040
+ if (ch === 'u') {
1041
+ const restMode = cluster.slice(cIdx + 1);
1042
+ if (VALID_GIT_COMMIT_UNTRACKED_MODES.has(restMode)) {
1043
+ consumedRestOfToken = true;
1044
+ break;
1045
+ }
1046
+ continue;
1047
+ }
1048
+ if (SHORT_COMMIT_ARG_CHARS.has(ch)) {
1049
+ if (cIdx === cluster.length - 1) {
1050
+ i += 1;
1051
+ }
1052
+ consumedRestOfToken = true;
1053
+ break;
1054
+ }
1055
+ }
1056
+ if (consumedRestOfToken) continue;
1057
+ }
1058
+ }
1059
+ }
1060
+
1061
+ if (['push', 'merge', 'rebase', 'cherry-pick'].includes(subcommand)) {
1062
+ for (let i = 0; i < subArgs.length; i++) {
1063
+ const arg = subArgs[i];
1064
+ if (arg === '--') break;
1065
+ if (arg === '--no-verify') {
1066
+ return {
1067
+ detectorId: 'DET-01',
1068
+ triggered: true,
1069
+ decision: 'deny',
1070
+ subType: 'GIT_NO_VERIFY',
1071
+ reason: `[Burnoff DET-01 Git Hook Bypass Blocked] "git ${subcommand} --no-verify" is forbidden.`
1072
+ };
1073
+ }
1074
+ if (
1075
+ subcommand === 'push' &&
1076
+ (arg === '--force' || arg === '-f') &&
1077
+ !subArgs.some((a) => a.startsWith('--force-with-lease'))
1078
+ ) {
1079
+ return {
1080
+ detectorId: 'DET-01',
1081
+ triggered: true,
1082
+ decision: 'deny',
1083
+ subType: 'GIT_PUSH_FORCE',
1084
+ reason: '[Burnoff DET-01 Destructive Git Blocked] Unconditional "git push --force" is forbidden (use --force-with-lease if required).'
1085
+ };
1086
+ }
1087
+ }
1088
+ }
1089
+
1090
+ if (subcommand === 'stash') {
1091
+ sawGitStashInCommand = true;
1092
+ }
1093
+
1094
+ const discardDecision = isStrictAutoMode ? 'deny' : 'ask';
1095
+ if (!recentStashActive && !sawGitStashInCommand) {
1096
+ if (subcommand === 'checkout') {
1097
+ const isBranchCreation = subArgs.some((a) => a === '-b' || a === '-B' || a === '--orphan');
1098
+ if (!isBranchCreation) {
1099
+ const hasForceCheckout = subArgs.some((a) => a === '-f' || a === '--force');
1100
+ const hasDoubleDashDiscard = subArgs.includes('--');
1101
+ const hasDotDiscard = subArgs.includes('.');
1102
+ if (hasForceCheckout || hasDoubleDashDiscard || hasDotDiscard) {
1103
+ return {
1104
+ detectorId: 'DET-01',
1105
+ triggered: true,
1106
+ decision: discardDecision,
1107
+ subType: 'GIT_UNSTASHED_DISCARD',
1108
+ reason: '[Burnoff DET-01 Worktree Destructive Guard] Un-stashed working-tree discard ("git checkout") destroys uncommitted edits. Run "git stash push -u" first.'
1109
+ };
1110
+ }
1111
+ }
1112
+ }
1113
+
1114
+ if (subcommand === 'restore') {
1115
+ const hasStagedOnly =
1116
+ subArgs.some((a) => a === '--staged' || a === '-S') &&
1117
+ !subArgs.some((a) => a === '--worktree' || a === '-W');
1118
+ if (!hasStagedOnly && subArgs.some((a) => a !== '--help' && a !== '-h')) {
1119
+ return {
1120
+ detectorId: 'DET-01',
1121
+ triggered: true,
1122
+ decision: discardDecision,
1123
+ subType: 'GIT_UNSTASHED_DISCARD',
1124
+ reason: '[Burnoff DET-01 Worktree Destructive Guard] Un-stashed "git restore" overwrites working-tree edits. Run "git stash push -u" first (or pass --staged to unstage).'
1125
+ };
1126
+ }
1127
+ }
1128
+ }
1129
+
1130
+ const promptForGit = String(params.lastUserInput || params.prompt || '');
1131
+ const userRequestedGitForensics = /\b(?:reflog|fsck|cat-file|recover\s+lost|dangling)\b/i.test(
1132
+ promptForGit
1133
+ );
1134
+ if (strictTestIntegrity && !userRequestedGitForensics) {
1135
+ const miningDecision = isStrictAutoMode ? 'deny' : 'ask';
1136
+ if (subcommand === 'fsck' || subcommand === 'cat-file' || subcommand === 'reflog') {
1137
+ return {
1138
+ detectorId: 'DET-01',
1139
+ triggered: true,
1140
+ decision: miningDecision,
1141
+ subType: 'GIT_HISTORY_MINING',
1142
+ reason: `[Burnoff DET-01 Test Integrity Lock] Raw git object/reflog inspection ("git ${subcommand}") is gated in strict test-integrity mode.`
1143
+ };
1144
+ }
1145
+ if (
1146
+ subcommand === 'log' &&
1147
+ subArgs.includes('--all') &&
1148
+ subArgs.some((a) => a === '-p' || a === '--patch')
1149
+ ) {
1150
+ return {
1151
+ detectorId: 'DET-01',
1152
+ triggered: true,
1153
+ decision: miningDecision,
1154
+ subType: 'GIT_HISTORY_MINING',
1155
+ reason: '[Burnoff DET-01 Test Integrity Lock] Full-history patch mining ("git log --all -p") is gated in strict test-integrity mode.'
1156
+ };
1157
+ }
1158
+ }
1159
+ }
1160
+
1161
+ return { detectorId: 'DET-01', triggered: false, decision: 'allow', reason: null };
1162
+ }
1163
+
1164
+ function normalizeSecretCandidate(rawPath = '') {
1165
+ return String(rawPath || '').trim().replace(/^['"]|['"]$/g, '').replace(/\\/g, '/').replace(/^\.\//, '');
1166
+ }
1167
+
1168
+ function secretGlobToRegExp(pattern = '') {
1169
+ let out = '^';
1170
+ for (let i = 0; i < pattern.length; i += 1) {
1171
+ const ch = pattern[i];
1172
+ if (ch === '*') {
1173
+ if (pattern[i + 1] === '*') {
1174
+ out += '.*';
1175
+ i += 1;
1176
+ if (pattern[i + 1] === '/') i += 1;
1177
+ } else {
1178
+ out += '[^/]*';
1179
+ }
1180
+ } else if (ch === '?') {
1181
+ out += '[^/]';
1182
+ } else if ('.+^${}()|[]\\'.includes(ch)) {
1183
+ out += `\\${ch}`;
1184
+ } else {
1185
+ out += ch;
1186
+ }
1187
+ }
1188
+ out += '$';
1189
+ return new RegExp(out, 'i');
1190
+ }
1191
+
1192
+ function matchesSecretAllowList(rawTarget = '', secretAllow = []) {
1193
+ if (!Array.isArray(secretAllow) || secretAllow.length === 0) return false;
1194
+ const norm = normalizeSecretCandidate(rawTarget);
1195
+ if (!norm) return false;
1196
+ const baseName = norm.split('/').pop() || norm;
1197
+
1198
+ for (const rawPat of secretAllow) {
1199
+ const pat = normalizeSecretCandidate(rawPat);
1200
+ if (!pat) continue;
1201
+ const normLower = norm.toLowerCase();
1202
+ const patLower = pat.toLowerCase();
1203
+ if (normLower === patLower) return true;
1204
+ if (normLower.endsWith(`/${patLower}`)) return true;
1205
+ if (!pat.includes('/') && baseName.toLowerCase() === patLower) return true;
1206
+ const re = secretGlobToRegExp(pat);
1207
+ if (re.test(norm) || (!pat.includes('/') && re.test(baseName))) {
1208
+ return true;
1209
+ }
1210
+ }
1211
+ return false;
1212
+ }
1213
+
1214
+ const GLOB_META_REGEX = /[*?[]/;
1215
+ const CANONICAL_SECRET_GLOB_SAMPLES = [
1216
+ '.env',
1217
+ '.env.local',
1218
+ '.env.production',
1219
+ 'server.key',
1220
+ 'private.pem',
1221
+ 'cert.p12',
1222
+ 'cert.pfx',
1223
+ 'id_rsa',
1224
+ 'id_ed25519',
1225
+ 'id_ecdsa',
1226
+ 'id_dsa',
1227
+ '.npmrc',
1228
+ '.netrc',
1229
+ '.pypirc',
1230
+ '.ssh/id_rsa',
1231
+ '.ssh/config',
1232
+ '.aws/credentials'
1233
+ ];
1234
+ const BENIGN_GLOB_SAMPLES = [
1235
+ 'index.js',
1236
+ 'app.ts',
1237
+ 'README.md',
1238
+ 'package.json',
1239
+ 'notes.txt',
1240
+ '.gitignore',
1241
+ '.eslintrc',
1242
+ '.editorconfig'
1243
+ ];
1244
+
1245
+ function shellGlobToRegExp(pattern = '') {
1246
+ let out = '^';
1247
+ for (let i = 0; i < pattern.length; i += 1) {
1248
+ const ch = pattern[i];
1249
+ if (ch === '*') {
1250
+ if (pattern[i + 1] === '*') {
1251
+ out += '.*';
1252
+ i += 1;
1253
+ if (pattern[i + 1] === '/') i += 1;
1254
+ } else {
1255
+ out += '[^/]*';
1256
+ }
1257
+ } else if (ch === '?') {
1258
+ out += '[^/]';
1259
+ } else if (ch === '[') {
1260
+ const closeIdx = pattern.indexOf(']', i + 1);
1261
+ if (closeIdx !== -1) {
1262
+ const body = pattern.slice(i + 1, closeIdx);
1263
+ const negated = body.startsWith('!') ? `^${body.slice(1)}` : body;
1264
+ out += `[${negated}]`;
1265
+ i = closeIdx;
1266
+ } else {
1267
+ out += '\\[';
1268
+ }
1269
+ } else if ('.+^${}()|\\'.includes(ch)) {
1270
+ out += `\\${ch}`;
1271
+ } else {
1272
+ out += ch;
1273
+ }
1274
+ }
1275
+ out += '$';
1276
+ return new RegExp(out, 'i');
1277
+ }
1278
+
1279
+ function isSecretGlobPattern(normTarget = '', secretAllow = []) {
1280
+ const norm = normalizeSecretCandidate(normTarget);
1281
+ if (!norm || !GLOB_META_REGEX.test(norm)) return false;
1282
+ if (/^(?:\*+|\*\.\*|\.\*|\.\/\*|\*\*\/\*|\?+)$/.test(norm)) return false;
1283
+ if (SAFE_ENV_ALLOWLIST_REGEX.test(norm)) return false;
1284
+ if (matchesSecretAllowList(norm, secretAllow)) return false;
1285
+
1286
+ const hasSlash = norm.includes('/');
1287
+ const basePat = hasSlash ? norm.split('/').pop() : norm;
1288
+ let re;
1289
+ try {
1290
+ re = shellGlobToRegExp(hasSlash ? norm : basePat);
1291
+ } catch (err) {
1292
+ void err; // ignore: malformed bracket glob does not crash guard
1293
+ return false;
1294
+ }
1295
+
1296
+ for (const benign of BENIGN_GLOB_SAMPLES) {
1297
+ if (re.test(benign)) return false;
1298
+ }
1299
+
1300
+ for (const sample of CANONICAL_SECRET_GLOB_SAMPLES) {
1301
+ if (matchesSecretAllowList(sample, secretAllow)) continue;
1302
+ const targetSample = hasSlash ? sample : sample.split('/').pop();
1303
+ if (re.test(targetSample)) return true;
1304
+ }
1305
+ return false;
1306
+ }
1307
+
1308
+ function isConfidentalSecretPath(normTarget = '', secretAllow = []) {
1309
+ const norm = String(normTarget || '').trim().replace(/\\/g, '/');
1310
+ if (!norm) return false;
1311
+ if (SAFE_ENV_ALLOWLIST_REGEX.test(norm)) return false;
1312
+ if (matchesSecretAllowList(norm, secretAllow)) return false;
1313
+ if (SECRET_FILE_PATTERNS.some((pattern) => pattern.test(norm))) return true;
1314
+ return isSecretGlobPattern(norm, secretAllow);
1315
+ }
1316
+
1317
+ function isNonPrivateCertPath(normTarget = '') {
1318
+ const norm = String(normTarget || '').trim().replace(/\\/g, '/');
1319
+ if (GLOB_META_REGEX.test(norm)) return false;
1320
+ if (!/\.(?:pem|crt)$/i.test(norm)) return false;
1321
+ if (/(?:^|[\\/])\.(?:ssh|aws)[\\/]/i.test(norm)) return false;
1322
+ return !/(?:key|private)/i.test(norm);
1323
+ }
1324
+
1325
+ function isPrivateCertPath(normTarget = '') {
1326
+ const norm = String(normTarget || '').trim().replace(/\\/g, '/');
1327
+ if (GLOB_META_REGEX.test(norm)) return false;
1328
+ if (!/\.(?:pem|crt)$/i.test(norm)) return false;
1329
+ return /(?:key|private)/i.test(norm);
1330
+ }
1331
+
1332
+ function pickStricterVerdict(best, candidate) {
1333
+ if (!candidate || !candidate.triggered) return best;
1334
+ if (!best || !best.triggered) return candidate;
1335
+ if (best.decision === 'deny') return best;
1336
+ if (candidate.decision === 'deny') return candidate;
1337
+ return best;
1338
+ }
1339
+
1340
+ const INLINE_EVAL_BIN_FLAGS = new Map([
1341
+ ['node', new Set(['-e', '--eval', '-p', '--print'])],
1342
+ ['deno', new Set(['-e', '--eval', '-p', '--print'])],
1343
+ ['bun', new Set(['-e', '--eval', '-p', '--print'])],
1344
+ ['python', new Set(['-c'])],
1345
+ ['python3', new Set(['-c'])],
1346
+ ['py', new Set(['-c'])],
1347
+ ['perl', new Set(['-e', '-E'])],
1348
+ ['ruby', new Set(['-e'])],
1349
+ ['php', new Set(['-r'])]
1350
+ ]);
1351
+
1352
+ function extractInlineScriptPayloads(bin, rawTokens = [], binIdx = 0) {
1353
+ const flags = INLINE_EVAL_BIN_FLAGS.get(bin);
1354
+ if (!flags) return [];
1355
+ const payloads = [];
1356
+ for (let i = binIdx + 1; i < rawTokens.length; i += 1) {
1357
+ const tok = String(rawTokens[i] || '');
1358
+ if (flags.has(tok) && i + 1 < rawTokens.length) {
1359
+ payloads.push(String(rawTokens[i + 1] || ''));
1360
+ i += 1;
1361
+ continue;
1362
+ }
1363
+ const eqIdx = tok.indexOf('=');
1364
+ if (eqIdx > 0 && flags.has(tok.slice(0, eqIdx))) {
1365
+ payloads.push(tok.slice(eqIdx + 1));
1366
+ }
1367
+ }
1368
+ return payloads;
1369
+ }
1370
+
1371
+ function extractInlineScriptCandidates(scriptText = '') {
1372
+ let normalized = String(scriptText || '');
1373
+ for (let pass = 0; pass < 4; pass += 1) {
1374
+ const next = normalized.replace(
1375
+ /(['"`])((?:\\.|(?!\1)[^\\])*)\1\s*\+\s*(['"`])((?:\\.|(?!\3)[^\\])*)\3/g,
1376
+ (_, _q1, left, _q2, right) => JSON.stringify(`${left}${right}`)
1377
+ );
1378
+ if (next === normalized) break;
1379
+ normalized = next;
1380
+ }
1381
+
1382
+ const out = [];
1383
+ const litRe = /'((?:\\.|[^'\\])*)'|"((?:\\.|[^"\\])*)"|`((?:\\.|[^`\\])*)`/g;
1384
+ let m;
1385
+ while ((m = litRe.exec(normalized)) !== null) {
1386
+ const val = (m[1] ?? m[2] ?? m[3] ?? '').trim();
1387
+ if (!val) continue;
1388
+ out.push(val);
1389
+ for (const part of val.split(/\s+/)) {
1390
+ const trimmed = part.replace(/^[,;()<>]+|[,;()<>]+$/g, '').trim();
1391
+ if (trimmed && trimmed !== val) out.push(trimmed);
1392
+ }
1393
+ }
1394
+ return out;
1395
+ }
1396
+
1397
+ function extractRedirectTokenTarget(rawTok = '') {
1398
+ const s = String(rawTok || '').trim();
1399
+ if (!s) return null;
1400
+ if (/^(?:&>>?|(?:\d*)>>?|\d*>\|)$/.test(s)) {
1401
+ return { kind: 'output_op' };
1402
+ }
1403
+ const outMatch = s.match(/^(?:&>>?|(?:\d*)>>?|\d*>\|)(.+)$/);
1404
+ if (outMatch && !outMatch[1].startsWith('&')) {
1405
+ return { kind: 'output_inline', target: outMatch[1].trim() };
1406
+ }
1407
+ if (/^<<<?$/.test(s)) {
1408
+ return { kind: 'heredoc_op' };
1409
+ }
1410
+ if (s === '<' || /^0<$/.test(s)) {
1411
+ return { kind: 'stdin_op' };
1412
+ }
1413
+ if (/^<<[^<]/.test(s)) {
1414
+ return { kind: 'heredoc_inline' };
1415
+ }
1416
+ const inMatch = s.match(/^(?:0?<)(.+)$/);
1417
+ if (inMatch && !inMatch[1].startsWith('<') && !inMatch[1].startsWith('&')) {
1418
+ return { kind: 'stdin_inline', target: inMatch[1].trim() };
1419
+ }
1420
+ return null;
1421
+ }
1422
+
1423
+ /**
1424
+ * DET-02: Secret & Credential Boundary.
1425
+ * Distinguishes direct credential reads/exfiltration (`deny`) from write/creation/argument usage
1426
+ * (`ask` in default `guard` mode, `deny` in `strict`/`auto`), treats non-private `.pem`/`.crt`
1427
+ * files as `ask`, and honors `guards.secretAllow` while allowlisting `.env.example` / `.env.sample`.
1428
+ */
1429
+ export function evaluateDet02SecretBoundary(params = {}, _depth = 0) {
1430
+ if (_depth > 4) {
1431
+ return { detectorId: 'DET-02', triggered: false, decision: 'allow', reason: null };
1432
+ }
1433
+
1434
+ const toolName = String(params.toolName || 'Bash');
1435
+ const rawMode = String(params.mode ?? params.flightMode ?? 'guard').trim().toUpperCase();
1436
+ const isStrictAutoMode = rawMode === 'STRICT' || rawMode === 'AUTO' || rawMode === 'AUTO_PILOT';
1437
+ const gatedAskDecision = isStrictAutoMode ? 'deny' : 'ask';
1438
+ const secretAllow = Array.isArray(params.secretAllow) ? params.secretAllow : [];
1439
+
1440
+ let best = { detectorId: 'DET-02', triggered: false, decision: 'allow', reason: null };
1441
+
1442
+ const makeVerdict = (decision, normPath, modeHint = '') => ({
1443
+ detectorId: 'DET-02',
1444
+ triggered: true,
1445
+ decision,
1446
+ targetPath: normPath,
1447
+ reason:
1448
+ decision === 'ask'
1449
+ ? `[Burnoff DET-02 Secret & Credential Boundary] ${modeHint || 'Operation involving'} "${normPath}" requires confirmation.`
1450
+ : `[Burnoff DET-02 Secret & Credential Boundary] Access to sensitive credential path "${normPath}" is blocked. (.env.example / .env.sample are permitted.)`
1451
+ });
1452
+
1453
+ // 1. Direct file tool target (`Read`, `Grep`, `Glob`, `Edit`, `Write`, etc.)
1454
+ for (const rawField of [params.filePath, params.path]) {
1455
+ const norm = String(rawField || '').trim().replace(/\\/g, '/');
1456
+ if (!norm || !isConfidentalSecretPath(norm, secretAllow)) continue;
1457
+ if (EDIT_WRITE_TOOL_REGEX.test(toolName) || isNonPrivateCertPath(norm)) {
1458
+ best = pickStricterVerdict(best, makeVerdict(gatedAskDecision, norm, `${toolName} targeting`));
1459
+ } else {
1460
+ best = pickStricterVerdict(best, makeVerdict('deny', norm));
1461
+ }
1462
+ }
1463
+
1464
+ // 2. Shell command evaluation
1465
+ if (params.command && SHELL_TOOL_REGEX.test(toolName)) {
1466
+ const command = String(params.command);
1467
+ const isPowerShell = detectPowerShellSyntax(toolName, command);
1468
+
1469
+ for (const subCmd of extractCommandSubstitutions(command, { isPowerShell })) {
1470
+ const subVerdict = evaluateDet02SecretBoundary(
1471
+ {
1472
+ toolName: isPowerShell ? 'PowerShell' : toolName,
1473
+ command: subCmd,
1474
+ mode: params.mode,
1475
+ flightMode: params.flightMode,
1476
+ secretAllow
1477
+ },
1478
+ _depth + 1
1479
+ );
1480
+ best = pickStricterVerdict(best, subVerdict);
1481
+ }
1482
+
1483
+ const segments = splitCommandSegments(command, { isPowerShell });
1484
+ for (const seg of segments) {
1485
+ const rawTokens = tokenizeShellSegment(seg, { isPowerShell });
1486
+ if (rawTokens.length === 0) continue;
1487
+
1488
+ let binIdx = 0;
1489
+ while (binIdx < rawTokens.length && (rawTokens[binIdx] === '&' || splitEnvKeyValToken(rawTokens[binIdx]))) {
1490
+ binIdx += 1;
1491
+ }
1492
+ if (binIdx >= rawTokens.length) continue;
1493
+
1494
+ let bin = String(rawTokens[binIdx] || '').split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/i, '');
1495
+ if (bin === 'env' || bin === 'sudo' || bin === 'command') {
1496
+ let k = binIdx + 1;
1497
+ while (k < rawTokens.length && (rawTokens[k].startsWith('-') || splitEnvKeyValToken(rawTokens[k]))) {
1498
+ k += 1;
1499
+ }
1500
+ if (k < rawTokens.length) {
1501
+ binIdx = k;
1502
+ bin = String(rawTokens[binIdx] || '').split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/i, '');
1503
+ }
1504
+ }
1505
+
1506
+ if (['bash', 'sh', 'zsh', 'dash'].includes(bin)) {
1507
+ const cPos = rawTokens.findIndex((t, ti) => ti > binIdx && (t === '-c' || /^-[a-zA-Z]*c$/.test(t)));
1508
+ if (cPos !== -1 && rawTokens[cPos + 1]) {
1509
+ best = pickStricterVerdict(
1510
+ best,
1511
+ evaluateDet02SecretBoundary(
1512
+ {
1513
+ toolName: 'Bash',
1514
+ command: rawTokens[cPos + 1],
1515
+ mode: params.mode,
1516
+ flightMode: params.flightMode,
1517
+ secretAllow
1518
+ },
1519
+ _depth + 1
1520
+ )
1521
+ );
1522
+ }
1523
+ } else if (bin === 'powershell' || bin === 'pwsh') {
1524
+ const cPos = rawTokens.findIndex(
1525
+ (t, ti) => ti > binIdx && /^(?:-c|-command)$/i.test(String(t || ''))
1526
+ );
1527
+ if (cPos !== -1 && rawTokens[cPos + 1]) {
1528
+ best = pickStricterVerdict(
1529
+ best,
1530
+ evaluateDet02SecretBoundary(
1531
+ {
1532
+ toolName: 'PowerShell',
1533
+ command: rawTokens[cPos + 1],
1534
+ mode: params.mode,
1535
+ flightMode: params.flightMode,
1536
+ secretAllow
1537
+ },
1538
+ _depth + 1
1539
+ )
1540
+ );
1541
+ }
1542
+ }
1543
+
1544
+ for (const scriptBody of extractInlineScriptPayloads(bin, rawTokens, binIdx)) {
1545
+ for (const cand of extractInlineScriptCandidates(scriptBody)) {
1546
+ const norm = cand.replace(/\\/g, '/');
1547
+ if (!norm || !isConfidentalSecretPath(norm, secretAllow)) continue;
1548
+ const decision = isNonPrivateCertPath(norm) ? gatedAskDecision : 'deny';
1549
+ best = pickStricterVerdict(best, makeVerdict(decision, norm, `Inline ${bin} script referencing`));
1550
+ }
1551
+ }
1552
+
1553
+ const isOutputBinOnly = bin === 'echo' || bin === 'printf' || bin === 'write-output' || bin === 'write-host';
1554
+ const isBenignGit = bin === 'git' && BENIGN_GIT_SUBCOMMANDS.has(String(rawTokens[binIdx + 1] || '').toLowerCase());
1555
+ const isReadExfilBin = SECRET_READ_EXFIL_BINS.has(bin);
1556
+ const isCopyMoveBin = COPY_MOVE_BINS.has(bin);
1557
+
1558
+ const candidates = [];
1559
+ const positionalArgs = [];
1560
+ let pendingRedirect = null;
1561
+ let pendingPatternFlag = false;
1562
+ const patternFilterFlagRe = /^(?:--grep|--test-name-pattern|--filter|--match|-k)$/i;
1563
+ const patternFilterEqRe = /^(?:--grep|--test-name-pattern|--filter|--match)=/i;
1564
+
1565
+ for (let tIdx = binIdx + 1; tIdx < rawTokens.length; tIdx += 1) {
1566
+ const tok = String(rawTokens[tIdx] || '').trim();
1567
+ if (!tok) continue;
1568
+
1569
+ if (pendingRedirect === 'output') {
1570
+ pendingRedirect = null;
1571
+ candidates.push({ raw: tok.replace(/^[<>&]+/, ''), role: 'output_redirect' });
1572
+ continue;
1573
+ }
1574
+ if (pendingRedirect === 'stdin') {
1575
+ pendingRedirect = null;
1576
+ candidates.push({ raw: tok.replace(/^[<>&]+/, ''), role: 'stdin_redirect' });
1577
+ continue;
1578
+ }
1579
+ if (pendingRedirect === 'heredoc') {
1580
+ pendingRedirect = null;
1581
+ continue;
1582
+ }
1583
+
1584
+ const redir = extractRedirectTokenTarget(tok);
1585
+ if (redir) {
1586
+ pendingPatternFlag = false;
1587
+ if (redir.kind === 'output_op') pendingRedirect = 'output';
1588
+ else if (redir.kind === 'output_inline') candidates.push({ raw: redir.target, role: 'output_redirect' });
1589
+ else if (redir.kind === 'stdin_op') pendingRedirect = 'stdin';
1590
+ else if (redir.kind === 'stdin_inline') candidates.push({ raw: redir.target, role: 'stdin_redirect' });
1591
+ else if (redir.kind === 'heredoc_op') pendingRedirect = 'heredoc';
1592
+ continue;
1593
+ }
1594
+
1595
+ if (isOutputBinOnly || isBenignGit) {
1596
+ continue;
1597
+ }
1598
+
1599
+ if (!isReadExfilBin && pendingPatternFlag) {
1600
+ pendingPatternFlag = false;
1601
+ continue;
1602
+ }
1603
+
1604
+ if (!isReadExfilBin && patternFilterFlagRe.test(tok)) {
1605
+ pendingPatternFlag = true;
1606
+ continue;
1607
+ }
1608
+
1609
+ if (!isReadExfilBin && patternFilterEqRe.test(tok)) {
1610
+ continue;
1611
+ }
1612
+
1613
+ const isOption = tok.startsWith('-');
1614
+ if (isOption && tok.includes('=')) {
1615
+ const val = tok.slice(tok.indexOf('=') + 1).trim();
1616
+ if (val) candidates.push({ raw: val, role: 'flag_val' });
1617
+ } else if (!isOption) {
1618
+ const posIdx = positionalArgs.length;
1619
+ positionalArgs.push(tok);
1620
+ candidates.push({ raw: tok, role: 'arg', posIdx });
1621
+ }
1622
+ }
1623
+
1624
+ for (const item of candidates) {
1625
+ const norm = String(item.raw || '').trim().replace(/\\/g, '/');
1626
+ if (!norm || !isConfidentalSecretPath(norm, secretAllow)) continue;
1627
+
1628
+ if (item.role === 'output_redirect') {
1629
+ best = pickStricterVerdict(best, makeVerdict(gatedAskDecision, norm, 'Output redirection to'));
1630
+ continue;
1631
+ }
1632
+ if (isNonPrivateCertPath(norm)) {
1633
+ best = pickStricterVerdict(best, makeVerdict(gatedAskDecision, norm, 'Certificate operation referencing'));
1634
+ continue;
1635
+ }
1636
+ if (isPrivateCertPath(norm) && !(isCopyMoveBin && item.role === 'arg' && positionalArgs.length >= 2 && item.posIdx === positionalArgs.length - 1)) {
1637
+ best = pickStricterVerdict(best, makeVerdict('deny', norm));
1638
+ continue;
1639
+ }
1640
+ if (item.role === 'stdin_redirect') {
1641
+ best = pickStricterVerdict(best, makeVerdict('deny', norm));
1642
+ continue;
1643
+ }
1644
+ if (isCopyMoveBin && item.role === 'arg') {
1645
+ const isFinalDestArg = positionalArgs.length >= 2 && item.posIdx === positionalArgs.length - 1;
1646
+ best = pickStricterVerdict(
1647
+ best,
1648
+ isFinalDestArg
1649
+ ? makeVerdict(gatedAskDecision, norm, `${bin} destination targeting`)
1650
+ : makeVerdict('deny', norm)
1651
+ );
1652
+ continue;
1653
+ }
1654
+ if (isReadExfilBin) {
1655
+ best = pickStricterVerdict(best, makeVerdict('deny', norm));
1656
+ } else {
1657
+ best = pickStricterVerdict(best, makeVerdict(gatedAskDecision, norm, `${bin || 'Command'} argument referencing`));
1658
+ }
1659
+ }
1660
+ }
1661
+ }
1662
+
1663
+ return best;
1664
+ }
1665
+
1666
+ /**
1667
+ * DET-03: Protected Migration, Lockfile & Workflow Ask Gate.
1668
+ * Triggers `"ask"` on manual `Edit`/`Write` to `migrations/*`, lockfiles, and `.github/workflows/*`.
1669
+ */
1670
+ export function evaluateDet03ProtectedFilesAskGate(params = {}) {
1671
+ const toolName = String(params.toolName || '');
1672
+ if (!EDIT_WRITE_TOOL_REGEX.test(toolName)) {
1673
+ return { detectorId: 'DET-03', triggered: false, decision: 'allow', reason: null };
1674
+ }
1675
+
1676
+ const filePath = String(params.filePath || params.path || '').trim().replace(/\\/g, '/');
1677
+ if (!filePath) {
1678
+ return { detectorId: 'DET-03', triggered: false, decision: 'allow', reason: null };
1679
+ }
1680
+
1681
+ for (const pattern of PROTECTED_EDIT_PATTERNS) {
1682
+ if (pattern.test(filePath)) {
1683
+ return {
1684
+ detectorId: 'DET-03',
1685
+ triggered: true,
1686
+ decision: 'ask',
1687
+ targetPath: filePath,
1688
+ reason: `[Burnoff DET-03 Protected File Ask Gate] Direct manual ${toolName} to "${filePath}" requires confirmation (use package manager CLI for lockfiles).`
1689
+ };
1690
+ }
1691
+ }
1692
+
1693
+ return { detectorId: 'DET-03', triggered: false, decision: 'allow', reason: null };
1694
+ }
1695
+
1696
+ export default {
1697
+ SHELL_TOOL_REGEX,
1698
+ EDIT_WRITE_TOOL_REGEX,
1699
+ SEARCH_READ_TOOL_REGEX,
1700
+ tokenizeShellSegment,
1701
+ hasExplicitTestModifyIntent,
1702
+ evaluateDet01GitAndShellSafety,
1703
+ evaluateDet02SecretBoundary,
1704
+ evaluateDet03ProtectedFilesAskGate
1705
+ };