dsh-chief 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/chief-executor.js CHANGED
@@ -283,18 +283,141 @@ export function isPathInsideWorkspace(workspaceRoot, targetPath) {
283
283
  return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
284
284
  }
285
285
 
286
+ const SENSITIVE_CREDENTIAL_BASENAMES = /^(?:\.+env(?:\.[a-z0-9_-]+)?|\.credentials(?:\.[a-z0-9_-]+)?|\.(?:git-credentials|npmrc|pypirc|netrc))$/i
287
+ const SENSITIVE_CREDENTIAL_FULLPATH = /(?:id_rsa|id_ed25519|id_ecdsa|id_dsa|\.pem$|\.p12$|\.pfx$|credentials\.json$|secrets?\.(?:json|ya?ml)$)/i
288
+
289
+ function isSensitiveNameOrStream(candidate) {
290
+ const s = String(candidate || '').trim()
291
+ if (!s || s === '$DATA') return false
292
+ const slashNorm = s.replace(/\\/g, '/').toLowerCase()
293
+ const base = path.basename(slashNorm)
294
+ if (SENSITIVE_CREDENTIAL_BASENAMES.test(base)) return true
295
+ if (SENSITIVE_CREDENTIAL_FULLPATH.test(slashNorm)) return true
296
+ return false
297
+ }
298
+
299
+ function resolveWithSymlinkTarget(filePath) {
300
+ const out = []
301
+ const raw = String(filePath || '').trim()
302
+ if (!raw) return out
303
+ out.push(raw)
304
+ try {
305
+ const abs = path.resolve(raw)
306
+ out.push(abs)
307
+ try {
308
+ const lst = fs.lstatSync(abs)
309
+ if (lst.isSymbolicLink()) {
310
+ const linkTarget = fs.readlinkSync(abs)
311
+ out.push(linkTarget)
312
+ out.push(path.resolve(path.dirname(abs), linkTarget))
313
+ }
314
+ } catch {}
315
+ out.push(safeRealpath(abs))
316
+ const parent = path.dirname(abs)
317
+ if (fs.existsSync(parent)) {
318
+ out.push(path.join(safeRealpath(parent), path.basename(abs)))
319
+ }
320
+ } catch {}
321
+ return out
322
+ }
323
+
286
324
  function isSensitiveCredentialPath(filePath) {
287
- const base = path.basename(String(filePath || '')).toLowerCase()
288
- const normalized = String(filePath || '').replace(/\\/g, '/').toLowerCase()
289
- if (base === '.env' || base.startsWith('.env.') || base === '.credentials.yaml' || base.startsWith('.credentials.')) {
290
- return true
291
- }
292
- if (/(?:id_rsa|id_ed25519|id_dsa|\.pem$|\.p12$|\.pfx$|credentials\.json$|secrets?\.(?:json|ya?ml)$)/.test(normalized)) {
293
- return true
325
+ const candidates = resolveWithSymlinkTarget(filePath)
326
+ for (const cand of candidates) {
327
+ if (isSensitiveNameOrStream(cand)) return true
328
+ // Strip Windows drive letter `C:` then inspect any NTFS Alternate Data Streams (`file.txt:.env:$DATA`)
329
+ const withoutDrive = String(cand || '').replace(/^[a-zA-Z]:(?=[\\/]|$)/, '')
330
+ if (withoutDrive.includes(':')) {
331
+ for (const streamPart of withoutDrive.split(':')) {
332
+ if (isSensitiveNameOrStream(streamPart)) return true
333
+ }
334
+ }
294
335
  }
295
336
  return false
296
337
  }
297
338
 
339
+ function decodeEncodedPowerShell(command) {
340
+ const decodedParts = []
341
+ const raw = String(command || '')
342
+ const re = /(?:^|\s)-(?:e|ec|en|enc|enco|encod|encode|encoded|encodedc|encodedco|encodedcom|encodedcomm|encodedcomma|encodedcomman|encodedcommand)\s+([A-Za-z0-9+/=]{8,})/gi
343
+ let m
344
+ while ((m = re.exec(raw)) !== null) {
345
+ try {
346
+ const buf = Buffer.from(m[1], 'base64')
347
+ for (const enc of ['utf16le', 'utf8']) {
348
+ const rawTxt = buf.toString(enc)
349
+ if (/[\x00-\x08\x0e-\x1f\ufffd]/.test(rawTxt)) continue
350
+ const txt = rawTxt.trim()
351
+ if (txt.length >= 3 && /^[ -~\t\r\n\u4e00-\u9fff]+$/.test(txt)) {
352
+ decodedParts.push(txt)
353
+ }
354
+ }
355
+ } catch {}
356
+ }
357
+ return decodedParts.join(' ')
358
+ }
359
+
360
+ function extractCanonicalToolSubcommands(text) {
361
+ const extras = []
362
+ const s = String(text || '')
363
+ const gitValFlags = new Set(['-c', '--git-dir', '--work-tree', '--namespace', '--config-env', '--exec-path', '-p', '--paginate'])
364
+ const gitRe = /\bgit(?:\.exe)?\s+([^\n;|&`]+)/gi
365
+ let gm
366
+ while ((gm = gitRe.exec(s)) !== null) {
367
+ const tokens = gm[1].trim().split(/\s+/).filter(Boolean)
368
+ let i = 0
369
+ while (i < tokens.length) {
370
+ const tok = tokens[i]
371
+ if (tok === '-C' || gitValFlags.has(tok)) {
372
+ i += 2
373
+ continue
374
+ }
375
+ if (tok.startsWith('-')) {
376
+ i += 1
377
+ continue
378
+ }
379
+ break
380
+ }
381
+ if (i < tokens.length) {
382
+ const rest = tokens.slice(i).join(' ')
383
+ extras.push(`git ${tokens[i]}`, `git ${rest}`)
384
+ }
385
+ }
386
+ const npmRe = /\bnpm(?:\.cmd|\.exe)?\s+([^\n;|&`]+)/gi
387
+ let nm
388
+ while ((nm = npmRe.exec(s)) !== null) {
389
+ const tokens = nm[1].trim().split(/\s+/).filter(Boolean)
390
+ let i = 0
391
+ while (i < tokens.length && tokens[i].startsWith('-')) {
392
+ i += (tokens[i] === '--registry' || tokens[i] === '--tag' || tokens[i] === '--prefix') ? 2 : 1
393
+ }
394
+ if (i < tokens.length) {
395
+ extras.push(`npm ${tokens.slice(i).join(' ')}`)
396
+ }
397
+ }
398
+ return extras.join(' ')
399
+ }
400
+
401
+ export function normalizeCommandForSecurity(command) {
402
+ const nfkc = String(command || '').normalize('NFKC')
403
+ if (!nfkc) return ''
404
+ const psDecoded = decodeEncodedPowerShell(nfkc)
405
+ const base = psDecoded ? `${nfkc} ${psDecoded}` : nfkc
406
+ const concatCollapsed = base.replace(/(['"`])\s*\+\s*\1/g, '')
407
+ const escapedQuotesUnwrapped = concatCollapsed.replace(/\\(["'`])/g, '$1').replace(/["'`]/g, '')
408
+ const caretCollapsed = escapedQuotesUnwrapped.replace(/\^([a-zA-Z0-9_.-])/g, '$1')
409
+ const quoteStripped = concatCollapsed.replace(/["'`]/g, '')
410
+ const shellUnescaped = caretCollapsed.replace(/\\([ \t!$&()*,.;<>?@[\]^`{|}~])/g, '$1')
411
+ const spaceCollapsed = shellUnescaped.replace(/\s+/g, ' ').trim()
412
+ const canonicalTools = [
413
+ extractCanonicalToolSubcommands(spaceCollapsed),
414
+ extractCanonicalToolSubcommands(caretCollapsed.replace(/\s+/g, ' ').trim()),
415
+ ].filter(Boolean).join(' ')
416
+ return [nfkc, psDecoded, concatCollapsed, quoteStripped, escapedQuotesUnwrapped, caretCollapsed, spaceCollapsed, canonicalTools]
417
+ .filter(Boolean)
418
+ .join(' \n ')
419
+ }
420
+
298
421
  const DESTRUCTIVE_COMMAND_PATTERNS = [
299
422
  /\brm\s+-[a-z]*(?:r[a-z]*f|f[a-z]*r)[a-z]*\s+(?:\/(?:etc|usr|bin|sbin|var|lib|boot|dev|proc|sys|root|home|\*)?(?=$|[\s/])|~|\*|\.\.)/i,
300
423
  /\bgit\s+(?:reset\s+--hard|clean\s+-[a-z]*f[a-z]*d|push\s+(?:--force|-f)\b)/i,
@@ -307,26 +430,45 @@ const DESTRUCTIVE_COMMAND_PATTERNS = [
307
430
  ]
308
431
 
309
432
  function isDestructiveShellCommand(command) {
310
- const cmd = String(command || '').trim()
311
- if (!cmd) return false
312
- return DESTRUCTIVE_COMMAND_PATTERNS.some(re => re.test(cmd))
433
+ const raw = String(command || '').trim()
434
+ if (!raw) return false
435
+ const norm = normalizeCommandForSecurity(raw)
436
+ return DESTRUCTIVE_COMMAND_PATTERNS.some(re => re.test(raw) || re.test(norm))
313
437
  }
314
438
 
315
439
  function commandTouchesSensitiveCredential(command) {
316
- const cmd = String(command || '')
317
- return /(?:^|[\s"'=/\\])(?:\.env(?:\.[a-z0-9_-]+)?|\.credentials\.(?:ya?ml|json)|id_rsa|id_ed25519|id_dsa|\.pem|\.p12|\.pfx)(?:$|[\s"';&|])/i.test(cmd)
440
+ const raw = String(command || '')
441
+ if (!raw.trim()) return false
442
+ const norm = normalizeCommandForSecurity(raw)
443
+ const varExpanded = norm
444
+ .replace(/%[A-Za-z0-9_]+%/g, '/')
445
+ .replace(/\$env:[A-Za-z0-9_]+/gi, '/')
446
+ .replace(/\$\{[A-Za-z0-9_]+\}/g, '/')
447
+ const re = /(?:^|[\s"'=/\\:;>|&])(?:\.+env(?:\.[a-z0-9_-]+)?|\.credentials(?:\.[a-z0-9_-]+)?|\.(?:git-credentials|npmrc|pypirc|netrc)|id_rsa|id_ed25519|id_ecdsa|id_dsa|[a-z0-9_.-]+\.(?:pem|p12|pfx))(?:$|[\s"';&|><)\r\n])/i
448
+ return re.test(raw) || re.test(norm) || re.test(varExpanded)
318
449
  }
319
450
 
320
451
  /**
321
452
  * 无论当前处于何种权限级别(包括 danger-full-access),都坚决守住用户在看板中设定的禁止红线。
322
453
  */
323
- export function checkForbiddenBounds(board, actionDesc = '', commandOrPath = '') {
454
+ export function checkForbiddenBounds(board, actionDesc = '', commandOrPath = '', extraContent = '') {
324
455
  const forbidden = [
325
456
  ...((board && board.bounds && Array.isArray(board.bounds.forbidden)) ? board.bounds.forbidden : []),
326
457
  ...((board && board.pinnedBounds && Array.isArray(board.pinnedBounds.forbidden)) ? board.pinnedBounds.forbidden : []),
327
458
  ]
328
459
  if (!forbidden.length) return { blocked: false }
329
- const haystack = `${actionDesc} ${commandOrPath}`.replace(/\\/g, '/').toLowerCase()
460
+ const primary = String(commandOrPath || '')
461
+ const normCmd = normalizeCommandForSecurity(primary)
462
+ const contentSample = String(extraContent || '').slice(0, 8192).normalize('NFKC')
463
+ const haystack = [
464
+ String(actionDesc || ''),
465
+ primary,
466
+ primary.replace(/\\/g, '/'),
467
+ normCmd,
468
+ normCmd.replace(/\\/g, '/'),
469
+ contentSample,
470
+ contentSample.replace(/\\/g, '/'),
471
+ ].join(' \n ').toLowerCase()
330
472
 
331
473
  for (const rule of forbidden) {
332
474
  const rText = String(rule || '').trim()
@@ -556,17 +698,32 @@ export function getToolOpClass(tool) {
556
698
  }
557
699
 
558
700
  /** 安全卫兵硬性规则:优先于四级权限判定,L3 与逐项放行均不可绕过。 */
559
- export function evaluateSafetyGuardHardRules({ tool = '', opClass = '', targetPath = '', command = '', board = null } = {}) {
560
- if (targetPath && isSensitiveCredentialPath(targetPath)) {
701
+ export function evaluateSafetyGuardHardRules({
702
+ tool = '',
703
+ opClass = '',
704
+ targetPath = '',
705
+ command = '',
706
+ content = '',
707
+ target = '',
708
+ replacement = '',
709
+ extraContent = '',
710
+ args = null,
711
+ board = null,
712
+ } = {}) {
713
+ const argObj = args && typeof args === 'object' ? args : {}
714
+ const resolvedPath = targetPath || (typeof argObj.path === 'string' ? argObj.path : '')
715
+ const resolvedCommand = command || (typeof argObj.command === 'string' ? argObj.command : (typeof argObj.cmd === 'string' ? argObj.cmd : ''))
716
+
717
+ if (resolvedPath && isSensitiveCredentialPath(resolvedPath)) {
561
718
  return {
562
719
  blocked: true,
563
720
  stage: 'safety_guard',
564
721
  rule: 'sensitive_credential',
565
- reason: `安全卫兵拦截访问敏感凭据文件:${path.basename(targetPath)}`,
722
+ reason: `安全卫兵拦截访问敏感凭据文件:${path.basename(resolvedPath)}`,
566
723
  badge: '🛡️ 卫兵拦凭据',
567
724
  }
568
725
  }
569
- if (command && commandTouchesSensitiveCredential(command)) {
726
+ if (resolvedCommand && commandTouchesSensitiveCredential(resolvedCommand)) {
570
727
  return {
571
728
  blocked: true,
572
729
  stage: 'safety_guard',
@@ -575,18 +732,34 @@ export function evaluateSafetyGuardHardRules({ tool = '', opClass = '', targetPa
575
732
  badge: '🛡️ 卫兵拦凭据命令',
576
733
  }
577
734
  }
578
- if (command && isDestructiveShellCommand(command)) {
735
+ if (resolvedCommand && isDestructiveShellCommand(resolvedCommand)) {
579
736
  return {
580
737
  blocked: true,
581
738
  stage: 'safety_guard',
582
739
  rule: 'destructive_command',
583
- reason: `安全卫兵拦截高危毁灭性系统命令:${clamp(command, 80)}`,
740
+ reason: `安全卫兵拦截高危毁灭性系统命令:${clamp(resolvedCommand, 80)}`,
584
741
  badge: '🛡️ 卫兵拦高危命令',
585
742
  }
586
743
  }
587
744
  if (opClass !== 'read' && opClass !== 'elevation_request') {
588
- const checkInput = targetPath || command
589
- const boundCheck = checkForbiddenBounds(board, tool, checkInput)
745
+ const checkInput = resolvedPath || resolvedCommand
746
+ const payloadParts = [
747
+ content,
748
+ target,
749
+ replacement,
750
+ extraContent,
751
+ argObj.content,
752
+ argObj.target,
753
+ argObj.replacement,
754
+ argObj.prompt,
755
+ argObj.message,
756
+ argObj.text,
757
+ argObj.body,
758
+ ]
759
+ .filter(v => v !== undefined && v !== null && String(v).trim())
760
+ .map(v => String(v).slice(0, 8192))
761
+ const mergedExtra = payloadParts.join('\n').slice(0, 12_288)
762
+ const boundCheck = checkForbiddenBounds(board, tool, checkInput, mergedExtra)
590
763
  if (boundCheck.blocked) {
591
764
  return {
592
765
  blocked: true,
@@ -847,6 +1020,7 @@ export async function executeChiefToolCall(deps, call, execCtx = {}) {
847
1020
  opClass,
848
1021
  targetPath: resolvedAbsTarget,
849
1022
  command: rawCommand,
1023
+ args,
850
1024
  cwd,
851
1025
  board,
852
1026
  })