@routinecrew/routinecode 2.31.57 → 2.31.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/bin/cli.sh +71 -41
  2. package/bin/prompt-vault.js +1 -1
  3. package/bin/rc-credit-turn.js +30 -4
  4. package/bin/rc-grant.js +79 -0
  5. package/bin/rc-login.js +23 -32
  6. package/bin/rc-team.js +592 -0
  7. package/bin/seal-open.js +5 -2
  8. package/hooks/lib/block_message.py +21 -19
  9. package/hooks/lib/i18n.py +17 -10
  10. package/hooks/lib/rt_cleanup.py +61 -0
  11. package/hooks/lib/scrub_stream.py +43 -0
  12. package/hooks/lib/secret_filter.py +443 -1
  13. package/hooks/lib/supplements_sig.py +70 -0
  14. package/hooks/post-knowledge-query.sh +14 -0
  15. package/hooks/post-secret-detect.sh +12 -27
  16. package/hooks/pre-account-guard.sh +6 -2
  17. package/hooks/pre-agent-spawn.mjs +1 -1
  18. package/hooks/pre-bash-guard.sh +11 -0
  19. package/hooks/pre-credit-guard.sh +36 -30
  20. package/hooks/pre-edit-domain-gate.sh +3 -1
  21. package/hooks/pre-edit-knowledge-gate.sh +3 -1
  22. package/hooks/pre-grep-guard.sh +18 -0
  23. package/hooks/pre-read-guard.sh +17 -0
  24. package/hooks/pre-read-knowledge-inject.sh +3 -1
  25. package/hooks/session-start.sh +47 -7
  26. package/hooks/stop-knowledge-remind.sh +45 -10
  27. package/hooks/tests/design09-client.test.py +10 -0
  28. package/hooks/tests/in-project-relax.test.py +2 -1
  29. package/hooks/tests/knowledge-loop.test.sh +89 -0
  30. package/hooks/tests/secret-guard-bypass.test.sh +107 -0
  31. package/hooks/tests/secret-guard.test.sh +2 -1
  32. package/hooks/tests/secret-premask.test.py +179 -0
  33. package/hooks/user-prompt-submit.sh +25 -19
  34. package/mcp-db-manager/dist/analyzers/duplicate-detector.js +1 -1
  35. package/mcp-db-manager/dist/core/model-parser.js +1 -1
  36. package/mcp-db-manager/dist/core/schema-reader.js +1 -1
  37. package/mcp-db-manager/dist/executors/migration-executor.js +1 -1
  38. package/mcp-db-manager/dist/generators/migration-generator.js +1 -1
  39. package/mcp-db-manager/dist/index.js +1 -1
  40. package/mcp-db-manager/dist/validators/schema-validator.js +1 -1
  41. package/mcp-dev-tester/dist/analyzers/auth-diagnoser.js +1 -1
  42. package/mcp-dev-tester/dist/analyzers/backend-analyzer.js +1 -1
  43. package/mcp-dev-tester/dist/analyzers/endpoint-diagnoser.js +1 -1
  44. package/mcp-dev-tester/dist/analyzers/frontend-analyzer.js +1 -1
  45. package/mcp-dev-tester/dist/analyzers/runtime-diagnoser.js +1 -1
  46. package/mcp-dev-tester/dist/analyzers/type-comparator.js +1 -1
  47. package/mcp-dev-tester/dist/analyzers/validation-diagnoser.js +1 -1
  48. package/mcp-dev-tester/dist/attestation.js +1 -1
  49. package/mcp-dev-tester/dist/browser/playwright-manager.js +1 -1
  50. package/mcp-dev-tester/dist/browser/ui-tester.js +1 -1
  51. package/mcp-dev-tester/dist/config/project-config.js +1 -1
  52. package/mcp-dev-tester/dist/index.js +1 -1
  53. package/mcp-dev-tester/dist/testers/api-tester.js +1 -1
  54. package/mcp-doc-fetcher/dist/index.js +1 -1
  55. package/mcp-html-renderer/dist/index.js +1 -1
  56. package/mcp-html-renderer/dist/preview.js +1 -1
  57. package/mcp-html-renderer/dist/template-engine.js +1 -1
  58. package/mcp-intelligence/dist/concept-catalog.js +1 -1
  59. package/mcp-intelligence/dist/concept-server-proxy.js +1 -1
  60. package/mcp-intelligence/dist/config-auth.js +1 -1
  61. package/mcp-intelligence/dist/contracts.generated.js +1 -1
  62. package/mcp-intelligence/dist/domain-templates.js +1 -1
  63. package/mcp-intelligence/dist/grounding.d.ts +1 -0
  64. package/mcp-intelligence/dist/grounding.d.ts.map +1 -1
  65. package/mcp-intelligence/dist/grounding.js +1 -1
  66. package/mcp-intelligence/dist/handlers.js +1 -1
  67. package/mcp-intelligence/dist/index.js +1 -1
  68. package/mcp-intelligence/dist/intelligence-file.js +1 -1
  69. package/mcp-intelligence/dist/knowledge-critic.js +1 -1
  70. package/mcp-intelligence/dist/knowledge-handlers.d.ts +20 -0
  71. package/mcp-intelligence/dist/knowledge-handlers.d.ts.map +1 -1
  72. package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
  73. package/mcp-intelligence/dist/mention-extractor.js +1 -1
  74. package/mcp-intelligence/dist/provenance.js +1 -1
  75. package/mcp-intelligence/dist/semantic-embedder.js +1 -1
  76. package/mcp-log-watcher/dist/config-auth.js +1 -1
  77. package/mcp-log-watcher/dist/file-watcher.js +1 -1
  78. package/mcp-log-watcher/dist/index.js +1 -1
  79. package/mcp-log-watcher/dist/known-solutions.js +1 -1
  80. package/mcp-log-watcher/dist/log-store.js +1 -1
  81. package/mcp-log-watcher/dist/websocket-server.js +1 -1
  82. package/mcp-plan-manager/dist/__tests__/plan-parser.test.js +1 -1
  83. package/mcp-plan-manager/dist/file-ops.js +1 -1
  84. package/mcp-plan-manager/dist/index.js +1 -1
  85. package/mcp-plan-manager/dist/plan-parser.js +1 -1
  86. package/mcp-project-context/dist/git-ops.js +1 -1
  87. package/mcp-project-context/dist/index.js +1 -1
  88. package/mcp-project-context/dist/project-analysis.js +1 -1
  89. package/mcp-routinecode/dist/agent-tracker.js +1 -1
  90. package/mcp-routinecode/dist/attestation.js +1 -1
  91. package/mcp-routinecode/dist/blast-radius.js +1 -1
  92. package/mcp-routinecode/dist/changeset.js +1 -1
  93. package/mcp-routinecode/dist/config-auth.js +1 -1
  94. package/mcp-routinecode/dist/contracts.generated.js +1 -1
  95. package/mcp-routinecode/dist/coverage.js +1 -1
  96. package/mcp-routinecode/dist/explorer-advisor.js +1 -1
  97. package/mcp-routinecode/dist/failure-tracker.js +1 -1
  98. package/mcp-routinecode/dist/file-lock-registry.js +1 -1
  99. package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
  100. package/mcp-routinecode/dist/index.js +1 -1
  101. package/mcp-routinecode/dist/known-solutions.js +1 -1
  102. package/mcp-routinecode/dist/ledger-miner.js +1 -1
  103. package/mcp-routinecode/dist/observed-draft.js +1 -1
  104. package/mcp-routinecode/dist/pattern-matcher.js +1 -1
  105. package/mcp-routinecode/dist/route-match.js +1 -1
  106. package/mcp-routinecode/dist/routines.js +1 -1
  107. package/mcp-routinecode/dist/rule-engine.js +1 -1
  108. package/mcp-routinecode/dist/rule-promoter.js +1 -1
  109. package/mcp-routinecode/dist/telemetry-analyzer.js +1 -1
  110. package/mcp-routinecode/dist/test-runner.js +1 -1
  111. package/mcp-routinecode/dist/verification.js +0 -0
  112. package/mcp-routinecode/dist/viral-loop.d.ts +68 -0
  113. package/mcp-routinecode/dist/viral-loop.js +1 -1
  114. package/package.json +1 -1
  115. package/plugin/agents/analyzer.md.sealed +1 -0
  116. package/plugin/agents/crawler.md.sealed +1 -0
  117. package/plugin/agents/explorer.md.sealed +1 -0
  118. package/plugin/agents/implementor.md.sealed +1 -0
  119. package/plugin/agents/looker.md.sealed +1 -0
  120. package/plugin/agents/planner.md.sealed +1 -0
  121. package/plugin/agents/recorder.md.sealed +1 -0
  122. package/plugin/agents/reviewer.md.sealed +1 -0
  123. package/plugin/agents/verifier.md.sealed +1 -0
  124. package/plugin/commands/analyze.md.sealed +1 -0
  125. package/plugin/commands/plan.md.sealed +1 -0
  126. package/plugin/commands/rc.md.sealed +1 -0
  127. package/plugin/commands/receipt.md.sealed +1 -0
  128. package/plugin/commands/recharge.md.sealed +1 -0
  129. package/plugin/commands/routines.md.sealed +1 -0
  130. package/plugin/commands/share.md.sealed +1 -0
  131. package/plugin/routinecode-prompt.md.sealed +1 -0
  132. package/bin/setup.js +0 -3
package/hooks/lib/i18n.py CHANGED
@@ -241,6 +241,13 @@ STRINGS = {
241
241
  "zh": "[SECRET-GUARD:{severity}] 在 {tool_name} 响应中检测到 {count} 个敏感信息({summary})— 已在服务器传输前脱敏。以下是脱敏内容:",
242
242
  "es": "[SECRET-GUARD:{severity}] {count} secreto(s) ({summary}) detectado(s) en respuesta de {tool_name} — redactado antes de transmisión. Contenido redactado:",
243
243
  },
244
+ "secret.detect_notice": {
245
+ "en": "[SECRET-GUARD:{severity}] {count} secret-like value(s) ({summary}) appeared in the {tool_name} output. Do not repeat them in replies, commits, files or logs. To view a secret file safely, Read it (values are masked automatically).",
246
+ "ko": "[SECRET-GUARD:{severity}] {tool_name} 출력에 민감값으로 보이는 항목 {count}건({summary})이 있습니다. 응답·커밋·파일·로그에 옮기지 마세요. 비밀 파일은 Read 로 열면 값이 자동 마스킹됩니다.",
247
+ "ja": "[SECRET-GUARD:{severity}] {tool_name} の出力に機密値と思われる項目が {count}件({summary})あります。返信・コミット・ファイル・ログに転記しないでください。秘密ファイルは Read で開くと値が自動マスクされます。",
248
+ "zh": "[SECRET-GUARD:{severity}] {tool_name} 输出中出现 {count} 个疑似敏感值({summary})。请勿在回复、提交、文件或日志中重复。用 Read 打开秘密文件会自动遮盖值。",
249
+ "es": "[SECRET-GUARD:{severity}] {count} valor(es) sensibles ({summary}) aparecieron en la salida de {tool_name}. No los repitas en respuestas, commits, archivos ni logs. Usa Read para ver archivos secretos (los valores se enmascaran).",
250
+ },
244
251
  "secret.redact_footer": {
245
252
  "en": "[SECRET-GUARD] The content above was read locally but only the redacted version is sent to Anthropic API. If you need the original, check directly in your local shell/editor.",
246
253
  "ko": "[SECRET-GUARD] 위 본문은 local에서는 정상 읽혔으나 Anthropic API로는 redact된 버전만 전송된다. secret 원문이 필요하면 local shell/editor에서 직접 확인할 것.",
@@ -462,18 +469,18 @@ STRINGS = {
462
469
 
463
470
  # ── Credit Guard ──
464
471
  "credit.block_fallback": {
465
- "en": "[CREDIT-GUARD] Credit exhausted. Run /share to recharge.",
466
- "ko": "[CREDIT-GUARD] Credit이 소진되었습니다. /share 로 충전하세요.",
467
- "ja": "[CREDIT-GUARD] クレジットを使い切りました。/share で補充してください。",
468
- "zh": "[CREDIT-GUARD] 积分已用完。运行 /share 充值。",
469
- "es": "[CREDIT-GUARD] Crédito agotado. Ejecuta /share para recargar.",
472
+ "en": "[CREDIT-GUARD] Credit exhausted. Run /recharge to recharge.",
473
+ "ko": "[CREDIT-GUARD] Credit이 소진되었습니다. /recharge 로 충전하세요.",
474
+ "ja": "[CREDIT-GUARD] クレジットを使い切りました。/recharge で補充してください。",
475
+ "zh": "[CREDIT-GUARD] 积分已用完。运行 /recharge 充值。",
476
+ "es": "[CREDIT-GUARD] Crédito agotado. Ejecuta /recharge para recargar.",
470
477
  },
471
478
  "credit.low_warning": {
472
- "en": "⚠️ Credit balance: {balance}/50 — running low. Recharge with /share.",
473
- "ko": "⚠️ Credit 잔액: {balance}/50 — 곧 소진됩니다. /share 로 미리 충전하세요.",
474
- "ja": "⚠️ クレジット残高: {balance}/50 — まもなく枯渇します。/share で補充してください。",
475
- "zh": "⚠️ 积分余额: {balance}/50 — 即将用完。请使用 /share 充值。",
476
- "es": "⚠️ Saldo de crédito: {balance}/50 — casi agotado. Recarga con /share.",
479
+ "en": "⚠️ Credit balance: {balance}/50 — running low. Recharge with /recharge.",
480
+ "ko": "⚠️ Credit 잔액: {balance}/50 — 곧 소진됩니다. /recharge 로 미리 충전하세요.",
481
+ "ja": "⚠️ クレジット残高: {balance}/50 — まもなく枯渇します。/recharge で補充してください。",
482
+ "zh": "⚠️ 积分余额: {balance}/50 — 即将用完。请使用 /recharge 充值。",
483
+ "es": "⚠️ Saldo de crédito: {balance}/50 — casi agotado. Recarga con /recharge.",
477
484
  },
478
485
 
479
486
  # ── Escalation (pre-edit-check.sh) ──
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env python3
2
+ """Sealed Core 세션 임시 복호본(~/.routinecode/.rt/*) 정리.
3
+
4
+ bin/cli.sh 는 seal-open 에 RC_LAUNCH_PID=$$ 를 넘기고, 곧 exec 로 Claude Code 가 된다(PID 유지).
5
+ 그래서 복호본 폴더 이름 '<pid>-<rand>' 의 pid 는 그 세션의 Claude Code 프로세스다.
6
+ - pid 프로세스가 살아 있으면 보존(세션 중 프롬프트 파일을 다시 읽어도 안전).
7
+ - pid 가 종료됐으면 삭제.
8
+ - pid 재사용 대비: 7일 지난 것은 무조건 삭제.
9
+ - pid 없는 이전 형식: 기존 규칙대로 60분 지나면 삭제.
10
+ 항상 exit 0 (session-start 를 막지 않는다).
11
+ """
12
+ import os
13
+ import re
14
+ import shutil
15
+ import sys
16
+ import time
17
+
18
+ RT = os.path.join(os.path.expanduser('~'), '.routinecode', '.rt')
19
+ MAX_AGE = 7 * 24 * 3600
20
+ LEGACY_AGE = 60 * 60
21
+
22
+
23
+ def alive(pid):
24
+ try:
25
+ os.kill(pid, 0)
26
+ return True
27
+ except ProcessLookupError:
28
+ return False
29
+ except PermissionError:
30
+ return True # 존재하지만 다른 사용자 — 보수적으로 살아 있음
31
+ except Exception:
32
+ return True
33
+
34
+
35
+ def main():
36
+ if not os.path.isdir(RT):
37
+ return
38
+ now = time.time()
39
+ for name in os.listdir(RT):
40
+ p = os.path.join(RT, name)
41
+ if not os.path.isdir(p) or os.path.islink(p):
42
+ continue
43
+ try:
44
+ age = now - os.stat(p).st_mtime
45
+ except Exception:
46
+ continue
47
+ m = re.match(r'^(\d+)-', name)
48
+ if m:
49
+ remove = age > MAX_AGE or not alive(int(m.group(1)))
50
+ else:
51
+ remove = age > LEGACY_AGE
52
+ if remove:
53
+ shutil.rmtree(p, ignore_errors=True)
54
+
55
+
56
+ if __name__ == '__main__':
57
+ try:
58
+ main()
59
+ except Exception:
60
+ pass
61
+ sys.exit(0)
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env python3
2
+ """scrub_stream — Bash 출력 필터 (pre-bash-guard 가 비밀 파일·환경변수 덤프 명령을 감쌀 때 사용).
3
+
4
+ stdin 을 줄 단위로 읽어 비밀 값을 MASK_TOKEN 으로 바꿔 stdout 에 즉시 흘린다.
5
+ 가리는 값: argv 로 받은 비밀 파일에서 뽑은 값 + 이름이 비밀스러운 환경변수 값 + 알려진 토큰 패턴.
6
+ 출력이 모델에 도달하기 '전'에 가려지는 유일한 Bash 경로다(PostToolUse 는 이미 전달된 출력을 못 바꾼다).
7
+
8
+ 사용: <cmd> 2>&1 | python3 scrub_stream.py [secret_file ...]
9
+ """
10
+ import os
11
+ import sys
12
+
13
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
14
+
15
+
16
+ def main():
17
+ try:
18
+ import secret_filter as sf
19
+ values = sf.scrub_values_for(sys.argv[1:])
20
+ policy = sf.load_policy()
21
+ token = sf.MASK_TOKEN
22
+ except Exception:
23
+ sf = None
24
+ values, policy, token = [], None, '***MASKED***'
25
+ out = sys.stdout
26
+ for line in sys.stdin:
27
+ for v in values:
28
+ if v in line:
29
+ line = line.replace(v, token)
30
+ if sf is not None:
31
+ try:
32
+ line, _ = sf.redact(line, policy)
33
+ except Exception:
34
+ pass
35
+ out.write(line)
36
+ out.flush()
37
+
38
+
39
+ if __name__ == '__main__':
40
+ try:
41
+ main()
42
+ except (BrokenPipeError, KeyboardInterrupt):
43
+ pass
@@ -113,7 +113,7 @@ REDACT_PATTERNS: List[Tuple[re.Pattern, str, str]] = [
113
113
  # 값 separator `:` 또는 `=` 모두. 값은 4자 이상.
114
114
  # 값에서 `*` 제외 + 뒤에 `*` 없음 → 이미 마스킹된 토큰(예: ghp_***REDACTED***)을
115
115
  # 다시 매칭하는 이중 카운트를 방지(특정 토큰 패턴이 먼저 실행되어 마스킹됨).
116
- (re.compile(r'(?i)(?<![\w-])([a-z0-9_.-]*(?:passwords?|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|secret[_-]?key|private[_-]?key|client[_-]?secret|access[_-]?token|auth[_-]?token|passphrase|credentials?))\s*[:=]\s*["\']?(?!(?:ghp_|gho_|ghs_|ghu_|github_pat_|npm_|sk-|sk_live_|rk_live_|pk_live_|AKIA|ASIA|xox|SG\.|eyJ))([^\s"\'&;,}*]{4,})(?!\*)["\']?'),
116
+ (re.compile(r'(?i)(?<![\w-])([a-z0-9_.-]*(?:passwords?|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|secret[_-]?key|private[_-]?key|client[_-]?secret|access[_-]?token|auth[_-]?token|passphrase|credentials?))\s*[:=]\s*["\']?(?!(?:ghp_|gho_|ghs_|ghu_|github_pat_|npm_|sk-|sk_live_|rk_live_|pk_live_|AKIA|ASIA|xox|SG\.|eyJ))(?!(?:process\.env|import\.meta\.env|os\.environ|os\.getenv|getenv\(|env\(|ENV\[|z\.|Joi\.|new |await |\(|\$\{|\{\{|<|`))(?!(?:string|number|boolean|undefined|null|None|str|int|bool|Optional|required|function|Secret|SecretStr)\b)(?![A-Za-z_$][\w$]*(?:\.[\w$]+)+(?:[\s,;)\]}]|$)|[A-Za-z_$][\w$]*(?:\.[\w$]+)*\()([^\s"\'&;,}*]{4,})(?!\*)["\']?'),
117
117
  r'\1=***REDACTED***', 'kv_secret'),
118
118
  # --token / --password CLI flags
119
119
  (re.compile(r'(--(?:token|password|pass|secret|api-key)[= ])[^\s"\']+'), r'\1***REDACTED***', 'cli_flag'),
@@ -220,6 +220,9 @@ CORE_PROTECTED_PATH_GLOBS = [
220
220
  # 사용자 홈 내부 config — .routinecode/ 하위 모든 json (런타임 apiKey·정책 등 모든 설정)
221
221
  '**/.routinecode/*.json',
222
222
  '**/.routinecode/**/*.json',
223
+ '**/.routinecode/*.json.*',
224
+ # Sealed Core 세션 임시 복호본(메인 프롬프트 평문) — 세션 동안만 존재, 모델 경유 읽기 차단
225
+ '**/.routinecode/.rt/**',
223
226
  # RoutineCode 설치물 hooks — 방어 로직 전체 (routinecode/ 로 스코프).
224
227
  # prefix 열거 대신 hooks/ 하위 모든 로직·설정 파일을 포괄 → 신규 훅 추가 시 자동 보호.
225
228
  '**/routinecode/hooks/*.sh',
@@ -227,6 +230,9 @@ CORE_PROTECTED_PATH_GLOBS = [
227
230
  '**/routinecode/hooks/*.js',
228
231
  '**/routinecode/hooks/*.json',
229
232
  '**/routinecode/hooks/lib/*',
233
+ # Claude Code 플러그인 캐시 — setup 이 마켓플레이스로 등록하면 CC 가 plugin/ 을 여기로 복사한다
234
+ # (프롬프트·에이전트 정의 평문 사본). 설치본과 같은 자산이므로 같은 수준으로 보호.
235
+ '**/plugins/cache/routinecode-marketplace/**',
230
236
  ]
231
237
 
232
238
  # 명시적 허용 (공개 키는 민감 아님)
@@ -1019,6 +1025,50 @@ def _is_runtime_config_rule(rule):
1019
1025
  return '.routinecode/' in _normalize_rule(rule)
1020
1026
 
1021
1027
 
1028
+ _RC_PKG_NAME = '@routinecrew/' + 'routinecode'
1029
+ _RC_SEG_RE = re.compile(r'(?:^|[/\\])routinecode(?=[/\\])')
1030
+ _pkg_root_cache: dict = {}
1031
+
1032
+
1033
+ def _is_rc_package_dir(d: str) -> bool:
1034
+ """d 가 실제 RoutineCode 패키지(설치본·dev 체크아웃) 루트인가 — package.json name 으로 판정."""
1035
+ if d in _pkg_root_cache:
1036
+ return _pkg_root_cache[d]
1037
+ ok = False
1038
+ try:
1039
+ with open(os.path.join(d, 'package.json'), encoding='utf-8') as fh:
1040
+ ok = json.load(fh).get('name') == _RC_PKG_NAME
1041
+ except Exception:
1042
+ ok = False
1043
+ _pkg_root_cache[d] = ok
1044
+ return ok
1045
+
1046
+
1047
+ def _rc_scoped_rule(rule: str) -> bool:
1048
+ """`routinecode/` 세그먼트나 plugin/routinecode-prompt.md 로 스코프된 '설치물' 규칙인가.
1049
+ (홈 런타임 config·플러그인 캐시 규칙은 패키지 판정 대상이 아님)"""
1050
+ r = _normalize_rule(rule)
1051
+ return ('/routinecode/' in r or r.endswith('/plugin/routinecode-prompt.md')) and \
1052
+ '.routinecode/' not in r and 'plugins/cache/' not in r
1053
+
1054
+
1055
+ def _path_in_rc_package(p: str) -> bool:
1056
+ """경로가 실제 RoutineCode 패키지 안인가. 이름만 같은 사용자 레포(예: ~/work/routinecode)는 False.
1057
+ 존재하지 않는 경로도 False — 보호할 실물이 없다."""
1058
+ if not p:
1059
+ return False
1060
+ # npm 설치 위치(node_modules/@routinecrew/routinecode)는 존재 여부와 무관하게 설치물로 본다
1061
+ if '/node_modules/' + _RC_PKG_NAME + '/' in p.replace('\\', '/') + '/':
1062
+ return True
1063
+ cands = []
1064
+ for m in _RC_SEG_RE.finditer(p):
1065
+ cands.append(p[:m.end()])
1066
+ i = p.rfind('/plugin/')
1067
+ if i > 0:
1068
+ cands.append(p[:i])
1069
+ return any(_is_rc_package_dir(c) for c in cands)
1070
+
1071
+
1022
1072
  def _core_path_verdict(path: str, policy: Policy) -> Tuple[bool, Optional[str]]:
1023
1073
  """CORE 소스보호 판정만 수행. (banned, rule).
1024
1074
 
@@ -1047,17 +1097,56 @@ def _core_path_verdict(path: str, policy: Policy) -> Tuple[bool, Optional[str]]:
1047
1097
  continue
1048
1098
  elif _dev_mode() or _is_dev_source_path(real):
1049
1099
  continue
1100
+ # 이름만 'routinecode' 인 사용자 레포/가상 경로는 보호 대상 아님(거짓 차단 방지)
1101
+ if _rc_scoped_rule(rule) and not any(_path_in_rc_package(t) for t in targets):
1102
+ continue
1050
1103
  return True, rule
1051
1104
  return False, None
1052
1105
 
1053
1106
 
1107
+ def _rc_mentions_all_benign(cmd: str) -> bool:
1108
+ """명령 속 `routinecode/<자산>` 언급이 전부 '실물 RoutineCode 패키지가 아닌' 리터럴 경로인가.
1109
+ 변수·명령치환·글롭이 섞인 단어는 해석 불가 → 실물로 간주(False). 상대경로는 선두 cd·cwd 기준.
1110
+ True 면 사용자 레포 이름이 routinecode 이거나 테스트 문자열일 뿐이므로 CORE 차단하지 않는다."""
1111
+ words = re.findall(r'\S*routinecode[/\\]\S*', cmd)
1112
+ if not words:
1113
+ return False
1114
+ m_cd = re.match(r'\s*cd\s+([^\s;&|]+)\s*(?:&&|;|\|)', cmd)
1115
+ base = os.path.abspath(os.path.expanduser(m_cd.group(1))) if m_cd else os.getcwd()
1116
+ for w in words:
1117
+ if any(ch in w for ch in '$`*?[{()'):
1118
+ return False
1119
+ w = w.strip('\'"`;&|<>)')
1120
+ if '=' in w:
1121
+ w = w.split('=', 1)[1]
1122
+ p = os.path.expanduser(w)
1123
+ if not os.path.isabs(p):
1124
+ p = os.path.join(base, p)
1125
+ p = os.path.normpath(p)
1126
+ try:
1127
+ rp = os.path.realpath(p)
1128
+ except Exception:
1129
+ rp = p
1130
+ if _path_in_rc_package(p) or _path_in_rc_package(rp):
1131
+ return False
1132
+ return True
1133
+
1134
+
1054
1135
  def _core_command_verdict(cmd: str, policy: Policy) -> Tuple[bool, Optional[str]]:
1055
1136
  """CORE 명령 패턴 판정만 수행. (banned, rule). dev 소스 대상 명령은 완화(config 리터럴 제외)."""
1056
1137
  _dev = _dev_mode() or _cmd_targets_dev_source(cmd)
1057
1138
  _touches_cfg = bool(re.search(r'\.routinecode[/\\]', cmd))
1139
+ _benign = None
1058
1140
  for raw_pat in policy.core_commands:
1059
1141
  try:
1060
1142
  if re.search(raw_pat, cmd, re.IGNORECASE):
1143
+ # 설치물 패턴(routinecode/hooks·plugin·mcp-·engine)인데 언급된 경로가 전부 실물 패키지가
1144
+ # 아니면(이름만 같은 사용자 레포·테스트 문자열) 차단하지 않는다.
1145
+ if 'routinecode[' in raw_pat and not _touches_cfg:
1146
+ if _benign is None:
1147
+ _benign = _rc_mentions_all_benign(cmd)
1148
+ if _benign:
1149
+ continue
1061
1150
  # .routinecode/ 리터럴을 건드리는 bash 명령은 dev 모드여도 계속 차단한다.
1062
1151
  # 이유: 값-스크럽(collect_protected_values)이 **-glob(.routinecode/*.json)을
1063
1152
  # 성능상 건너뛰어 bash stdout 에는 apiKey 백스톱이 없다. Read 는
@@ -1298,6 +1387,359 @@ def check_bash_command(cmd: str, policy: Optional[Policy] = None) -> Tuple[bool,
1298
1387
  return False, None, []
1299
1388
 
1300
1389
 
1390
+ # ─── 비밀 파일 사전 마스킹 (2026-10-16) ─────────────────────────────────
1391
+ # PostToolUse 는 이미 모델에 전달된 도구 출력을 바꾸지 못한다(실측: 원본과 사본이 둘 다 전달됨).
1392
+ # 그래서 비밀 '값'은 도구가 실행되기 전에 막는다:
1393
+ # - Read/Grep 이 비밀 파일을 가리키면 → 값이 마스킹된 사본 경로로 바꿔 읽힌다(키 이름은 그대로).
1394
+ # - Bash 명령이 비밀 파일·환경변수 덤프를 건드리면 → 출력이 scrub_stream.py 를 거쳐 나오게 감싼다.
1395
+ # 접근 자체는 막지 않는다(개발자는 자기 설정을 참조할 수 있어야 한다) — 값만 모델에 가지 않는다.
1396
+
1397
+ _TEMPLATE_SUFFIXES = ('.example', '.sample', '.template', '.tmpl', '.dist', '.defaults')
1398
+ MASK_TOKEN = '***MASKED***'
1399
+ MASK_HEADER = '# [RoutineCode] 값이 마스킹된 사본입니다(키 이름만 표시). 값 변경은 사용자에게 요청하세요.\n'
1400
+ _MASK_MAX_BYTES = 1024 * 1024
1401
+ _KV_LINE_RE = re.compile(r'^(\s*(?:export\s+)?[A-Za-z_][\w.\-]*\s*[=:]\s*)(.*?)(\s*)$')
1402
+ _JSON_STR_KV_RE = re.compile(r'("(?:[^"\\]|\\.)*"\s*:\s*)"((?:[^"\\]|\\.)*)"')
1403
+ _PEM_RE = re.compile(r'(-----BEGIN [^-]+-----)(.*?)(-----END [^-]+-----)', re.S)
1404
+ _URL_CRED_RE = re.compile(r'^([a-z][a-z0-9+.\-]*://)([^/@\s]+)@', re.I)
1405
+ _PUBLIC_VALUE_RE = re.compile(r'^(?:-?\d+(?:\.\d+)?|true|false|yes|no|on|off|null|none|development|production|test|staging|local|localhost|127\.0\.0\.1|0\.0\.0\.0)$', re.I)
1406
+ _SECRET_ENV_NAME_RE = re.compile(r'(SECRET|TOKEN|PASSWORD|PASSWD|PASS|PWD|API_?KEY|PRIVATE|CREDENTIAL|AUTH|SESSION|COOKIE|DSN|DATABASE_URL|_KEY$)', re.I)
1407
+
1408
+
1409
+ def is_secret_file(path: str, policy: Optional[Policy] = None) -> bool:
1410
+ """generic 비밀 파일(.env·키·자격증명 등)인가. 템플릿(.env.example 등)과 allowlist 는 제외."""
1411
+ if not isinstance(path, str) or not path:
1412
+ return False
1413
+ if policy is None:
1414
+ policy = load_policy()
1415
+ real = _normalize_path(path)
1416
+ lexical = _lexical_path(path)
1417
+ targets = {real, lexical}
1418
+ basenames = {os.path.basename(t) for t in targets}
1419
+ if any(b.lower().endswith(_TEMPLATE_SUFFIXES) for b in basenames):
1420
+ return False
1421
+
1422
+ def _m(rule):
1423
+ nr = _normalize_rule(rule)
1424
+ return any(fnmatch.fnmatch(t, nr) for t in targets) or any(fnmatch.fnmatch(b, nr) for b in basenames)
1425
+
1426
+ if any(_m(r) for r in policy.path_allowlist):
1427
+ return False
1428
+ return any(_m(r) for r in list(policy.secret_paths) + list(policy.redact_only_paths))
1429
+
1430
+
1431
+ def core_dir_scope(path: str) -> bool:
1432
+ """Grep 등 '디렉터리 단위' 검색이 RoutineCode 설치물(또는 그것을 담은 상위 디렉터리)을 훑는가.
1433
+ dev 소스 체크아웃은 제외(개발자 무마찰). 파일 경로 판정은 _core_path_verdict 가 담당."""
1434
+ if not isinstance(path, str) or not path:
1435
+ return False
1436
+ try:
1437
+ real = os.path.realpath(os.path.expanduser(path))
1438
+ except Exception:
1439
+ return False
1440
+ if not os.path.isdir(real) or _is_dev_source_path(real):
1441
+ return False
1442
+ if _is_rc_package_dir(real) or _path_in_rc_package(real + '/'):
1443
+ return True
1444
+ if '/plugins/cache/routinecode-marketplace' in real + '/':
1445
+ return True
1446
+ for sub in ('routinecode', os.path.join('@routinecrew', 'routinecode'),
1447
+ os.path.join('node_modules', '@routinecrew', 'routinecode'),
1448
+ 'routinecode-marketplace'):
1449
+ c = os.path.join(real, sub)
1450
+ if os.path.isdir(c) and (_is_rc_package_dir(c) or sub == 'routinecode-marketplace'):
1451
+ return True
1452
+ return False
1453
+
1454
+
1455
+ def _mask_value(v: str) -> str:
1456
+ raw = v.strip()
1457
+ q = ''
1458
+ if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in '"\'':
1459
+ q, raw = raw[0], raw[1:-1]
1460
+ if not raw or _PUBLIC_VALUE_RE.match(raw):
1461
+ return v
1462
+ m = _URL_CRED_RE.match(raw)
1463
+ if m: # 접속 URL — 자격(user:pass)만 가리고 호스트·DB 명은 남김(개발 참조용)
1464
+ return q + m.group(1) + MASK_TOKEN + '@' + raw[m.end():] + q
1465
+ return q + MASK_TOKEN + q
1466
+
1467
+
1468
+ def mask_secret_text(content: str) -> Tuple[str, int]:
1469
+ """비밀 파일 내용에서 값만 마스킹. (masked, count). 키 이름·주석·구조는 유지."""
1470
+ n = 0
1471
+
1472
+ def _pem(m):
1473
+ nonlocal n
1474
+ n += 1
1475
+ return m.group(1) + '\n' + MASK_TOKEN + '\n' + m.group(3)
1476
+
1477
+ content = _PEM_RE.sub(_pem, content)
1478
+ stripped = content.lstrip()
1479
+ if stripped.startswith('{') or stripped.startswith('['): # JSON 자격증명 파일
1480
+ def _js(m):
1481
+ nonlocal n
1482
+ mv = _mask_value(m.group(2))
1483
+ if mv != m.group(2):
1484
+ n += 1
1485
+ return m.group(1) + '"' + mv + '"'
1486
+ return _JSON_STR_KV_RE.sub(_js, content), n
1487
+ out = []
1488
+ for line in content.splitlines(keepends=True):
1489
+ body = line.rstrip('\r\n')
1490
+ nl = line[len(body):]
1491
+ st = body.strip()
1492
+ if not st or st.startswith(('#', ';', '//')) or st == MASK_TOKEN or st.startswith('-----'):
1493
+ out.append(line)
1494
+ continue
1495
+ m = _KV_LINE_RE.match(body)
1496
+ if m:
1497
+ mv = _mask_value(m.group(2))
1498
+ if mv != m.group(2):
1499
+ n += 1
1500
+ out.append(m.group(1) + mv + m.group(3) + nl)
1501
+ continue
1502
+ # 구조 없는 줄(키 파일 본문·토큰 한 줄 등) — 값 토큰만 가린다
1503
+ toks = [t for t in _VALUE_SPLIT_RE.split(body) if _is_value_token(t.strip('"\'`'))]
1504
+ for t in sorted(set(toks), key=len, reverse=True):
1505
+ body = body.replace(t, MASK_TOKEN)
1506
+ n += 1
1507
+ out.append(body + nl)
1508
+ return ''.join(out), n
1509
+
1510
+
1511
+ def masked_copy_path(path: str) -> Optional[str]:
1512
+ """비밀 파일의 값-마스킹 사본을 만들어 경로 반환. 원본이 없거나 너무 크면 None."""
1513
+ import hashlib
1514
+ import tempfile
1515
+ try:
1516
+ real = os.path.realpath(os.path.expanduser(path))
1517
+ if not os.path.isfile(real) or os.path.getsize(real) > _MASK_MAX_BYTES:
1518
+ return None
1519
+ with open(real, 'rb') as fh:
1520
+ raw = fh.read()
1521
+ if b'\x00' in raw[:8192]: # 바이너리 키스토어(.p12/.jks) — 내용 대신 안내만
1522
+ masked = MASK_HEADER + '# (binary secret file — content not shown)\n'
1523
+ else:
1524
+ masked = MASK_HEADER + mask_secret_text(raw.decode('utf-8', errors='replace'))[0]
1525
+ d = os.path.join(tempfile.gettempdir(), 'rc-masked-%d' % os.getuid(),
1526
+ hashlib.sha256(real.encode('utf-8')).hexdigest()[:16])
1527
+ os.makedirs(d, mode=0o700, exist_ok=True)
1528
+ out = os.path.join(d, os.path.basename(real) or 'secret')
1529
+ fd = os.open(out + '.tmp', os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
1530
+ with os.fdopen(fd, 'w', encoding='utf-8') as fh:
1531
+ fh.write(masked)
1532
+ os.replace(out + '.tmp', out)
1533
+ return out
1534
+ except Exception:
1535
+ return None
1536
+
1537
+
1538
+ _ENV_DUMP_RE = re.compile(
1539
+ r'(?:^|[\s;|&(])(?:printenv|export\s+-p|declare\s+-x|set)\s*(?:$|[;|&)>])'
1540
+ r'|(?:^|[\s;|&(])env\s*(?:$|[;|&)>])'
1541
+ r'|/proc/[^\s]*/environ'
1542
+ r'|docker\s+(?:inspect|compose\s+config)|kubectl\s+get\s+secrets?'
1543
+ r'|\$\{?[A-Z_]*(?:SECRET|TOKEN|PASSWORD|PASS|API_?KEY|PRIVATE|CREDENTIAL)[A-Z_]*')
1544
+
1545
+
1546
+ # ─── Bash 우회 접근 방어 (2026-10-16) ─────────────────────────
1547
+ # 리터럴 경로 탐지만으로는 `".con""fig"`(따옴표 이어붙이기)·변수 경로·인라인 스크립트로 우회된다.
1548
+ # ① 셸 단어 단위(shlex)로 다시 읽어 따옴표 조각·단순 변수 대입·글롭·디렉토리 참조를 해석하고
1549
+ # ② 정적으로 해석 불가능한 명령(인라인 인터프리터·eval·디코딩·find -exec·xargs 등)은
1550
+ # 경로와 무관하게 출력 필터를 강제한다 — 필터는 '모든 보호 파일의 값'을 가리므로 접근 방식과 무관하다.
1551
+ _OPAQUE_CMD_RE = re.compile(
1552
+ r'(?:^|[\s;|&(`])(?:'
1553
+ r'eval|exec'
1554
+ r'|(?:python[\d.]*|pypy[\d.]*)\s+(?:-[A-Za-z]*c|-\s|-$|-[A-Za-z]*m\s)'
1555
+ r'|(?:node|bun|deno)\s+(?:-e|-p|--eval|--print|eval|-\s|-$)'
1556
+ r'|(?:perl|ruby)\s+(?:-[A-Za-z]*e)'
1557
+ r'|php\s+-r|osascript\s+-e|awk\s+[^|;&]*\bgetline\b'
1558
+ r'|xargs|base64\s+(?:-d|-D|--decode)|xxd\s+-r|openssl\s+(?:enc|base64)'
1559
+ r')(?=[\s;|&)]|$)'
1560
+ r'|\bfind\b[^|;&]*\s-(?:exec|execdir|ok|okdir|fprint\w*)\b'
1561
+ r'|(?:python[\d.]*|node|bun|deno|perl|ruby|php|sh|bash|zsh)\s*(?:-\s*)?<<' # 인터프리터 + heredoc 스크립트
1562
+ r'|\$\'[^\']*\\[0-7xu]' # $'\x2e' ANSI-C 이스케이프
1563
+ r'|["\'][^"\'\s]*["\']["\']' # "a""b" / 'a''b' 따옴표 이어붙이기
1564
+ )
1565
+ _ASSIGN_RE = re.compile(r'^(?:export\s+|local\s+|readonly\s+|declare\s+(?:-\w+\s+)*)?([A-Za-z_]\w*)=(.*)$', re.S)
1566
+ _VAR_REF_RE = re.compile(r'\$\{([A-Za-z_]\w*)(?:[:?\-+=][^}]*)?\}|\$([A-Za-z_]\w*)')
1567
+ _BG_JOB_RE = re.compile(r'(?<![&>|])&(?![&>])\s*(?:$|[;\n)])') # 단독 & (백그라운드 작업)
1568
+
1569
+
1570
+ def _shell_words(cmd: str) -> List[str]:
1571
+ """명령을 셸 단어로 분해 — 따옴표 조각은 이어붙여진다(`".con""fig"` → `.config`). 실패 시 관용적으로 분해."""
1572
+ import shlex
1573
+ words: List[str] = []
1574
+ for seg in re.split(r'&&|\|\||[;|\n]', cmd):
1575
+ seg = seg.strip()
1576
+ if not seg:
1577
+ continue
1578
+ try:
1579
+ lx = shlex.shlex(seg, posix=True, punctuation_chars='()<>')
1580
+ lx.whitespace_split = True
1581
+ words.extend(t for t in lx if t)
1582
+ except Exception:
1583
+ words.extend(w.strip('\'"') for w in seg.split())
1584
+ return words
1585
+
1586
+
1587
+ def _resolve_word_paths(words: List[str]) -> List[str]:
1588
+ """단어 목록에서 경로 후보 산출 — 같은 명령 안의 단순 대입(NAME=값)을 `$NAME` 에 치환하고 `NAME=경로` 값도 후보로."""
1589
+ env: dict = {}
1590
+ out: List[str] = []
1591
+ for w in words:
1592
+ m = _ASSIGN_RE.match(w)
1593
+ if m:
1594
+ val = _VAR_REF_RE.sub(lambda r: env.get(r.group(1) or r.group(2), r.group(0)), m.group(2))
1595
+ env[m.group(1)] = val
1596
+ out.append(val)
1597
+ continue
1598
+ if '$' in w:
1599
+ w = _VAR_REF_RE.sub(lambda r: env.get(r.group(1) or r.group(2), os.environ.get(r.group(1) or r.group(2), r.group(0))), w)
1600
+ out.append(w)
1601
+ # --opt=경로 / 리다이렉트 결합(<경로) 형태
1602
+ if '=' in w and w.startswith('-'):
1603
+ out.append(w.split('=', 1)[1])
1604
+ return out
1605
+
1606
+
1607
+ def bash_secret_targets(cmd: str, policy: Optional[Policy] = None) -> Tuple[List[str], bool]:
1608
+ """명령이 읽을 수 있는 비밀 파일 목록(실존) + '출력 필터 강제' 여부.
1609
+
1610
+ 두 번째 값이 True 인 경우: 환경변수 덤프, 또는 정적으로 경로를 확정할 수 없는 불투명 명령
1611
+ (인라인 인터프리터·eval·디코딩·find -exec·xargs·따옴표 조각 경로 등). 이때 필터는 감지된
1612
+ 파일과 무관하게 정책의 모든 보호 파일 값을 가린다(scrub_values_for).
1613
+ 백그라운드 작업(단독 &)은 파이프 래핑 시 종료를 기다려 멈추므로 불투명 사유만으로는 감싸지 않는다.
1614
+ """
1615
+ if not isinstance(cmd, str) or not cmd:
1616
+ return [], False
1617
+ if policy is None:
1618
+ policy = load_policy()
1619
+ files = []
1620
+ seen = set()
1621
+ m_cd = re.match(r'\s*cd\s+([^\s;&|]+)\s*(?:&&|;|\|)', cmd)
1622
+ base = os.path.abspath(os.path.expanduser(m_cd.group(1).strip('\'"'))) if m_cd else os.getcwd()
1623
+ cands = list(_iter_command_path_tokens(cmd))
1624
+ cands += [t for t in re.findall(r'(?<![\w$/~.\-])(\.?[\w.\-]+(?:/[\w.\-]+)*)', cmd)
1625
+ if not t.startswith(('/', '~', '-'))]
1626
+ cands += _resolve_word_paths(_shell_words(cmd))
1627
+ try:
1628
+ protected = _iter_protected_concrete_paths(policy)
1629
+ except Exception:
1630
+ protected = []
1631
+
1632
+ def _consider(p: str) -> None:
1633
+ try:
1634
+ p = os.path.realpath(p)
1635
+ except Exception:
1636
+ pass
1637
+ if p in seen:
1638
+ return
1639
+ seen.add(p)
1640
+ try:
1641
+ if os.path.isfile(p):
1642
+ if is_secret_file(p, policy) or p in protected:
1643
+ files.append(p)
1644
+ elif os.path.isdir(p):
1645
+ # 디렉토리 단위 접근(grep -r, tar, cp -r, rsync) — 그 아래 보호 파일 포함
1646
+ pref = os.path.realpath(p).rstrip('/') + '/'
1647
+ for f in protected:
1648
+ if f.startswith(pref) and f not in seen:
1649
+ seen.add(f)
1650
+ files.append(f)
1651
+ except Exception:
1652
+ return
1653
+
1654
+ for tok in cands:
1655
+ tok = tok.strip('\'"`')
1656
+ if not tok or len(tok) > 4096 or tok.startswith('-'):
1657
+ continue
1658
+ p = os.path.expanduser(tok)
1659
+ if not os.path.isabs(p):
1660
+ p = os.path.join(base, p)
1661
+ p = os.path.normpath(p)
1662
+ if any(ch in p for ch in '*?['):
1663
+ try:
1664
+ for g in _glob.glob(p)[:64]:
1665
+ _consider(g)
1666
+ except Exception:
1667
+ pass
1668
+ continue
1669
+ _consider(p)
1670
+ force = bool(_ENV_DUMP_RE.search(cmd))
1671
+ if not force and _OPAQUE_CMD_RE.search(cmd) and not _BG_JOB_RE.search(cmd):
1672
+ force = True
1673
+ return files, force
1674
+
1675
+
1676
+ def value_masked_copy_path(path: str, policy: Optional[Policy] = None) -> Optional[str]:
1677
+ """보호 파일이 아닌데 보호 값(사본·덤프)을 담은 파일 → 값만 가린 사본 경로. 해당 없으면 None.
1678
+
1679
+ Bash 로 복사해 둔 `/tmp/x` 를 Read/Grep 하는 우회를 막는다. 1MB 초과·바이너리는 검사하지 않는다.
1680
+ """
1681
+ import hashlib
1682
+ import tempfile
1683
+ try:
1684
+ real = os.path.realpath(os.path.expanduser(path))
1685
+ if not os.path.isfile(real) or os.path.getsize(real) > _MASK_MAX_BYTES:
1686
+ return None
1687
+ if policy is None:
1688
+ policy = load_policy()
1689
+ values = collect_protected_values(policy)
1690
+ if not values:
1691
+ return None
1692
+ if real in set(_iter_protected_concrete_paths(policy)):
1693
+ return None # 보호 파일 자체는 masked_copy_path 담당
1694
+ with open(real, 'rb') as fh:
1695
+ raw = fh.read()
1696
+ if b'\x00' in raw[:8192]:
1697
+ return None
1698
+ text = raw.decode('utf-8', errors='replace')
1699
+ if not any(v in text for v in values):
1700
+ return None
1701
+ red, _n = redact_known_values(text, policy)
1702
+ d = os.path.join(tempfile.gettempdir(), 'rc-masked-%d' % os.getuid(),
1703
+ 'v' + hashlib.sha256(real.encode('utf-8')).hexdigest()[:15])
1704
+ os.makedirs(d, mode=0o700, exist_ok=True)
1705
+ out = os.path.join(d, os.path.basename(real) or 'file')
1706
+ fd = os.open(out + '.tmp', os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
1707
+ with os.fdopen(fd, 'w', encoding='utf-8') as fh:
1708
+ fh.write(MASK_HEADER + red)
1709
+ os.replace(out + '.tmp', out)
1710
+ return out
1711
+ except Exception:
1712
+ return None
1713
+
1714
+
1715
+ def wrap_bash_for_scrub(cmd: str, files: List[str], lib_dir: str) -> str:
1716
+ """명령 출력을 scrub_stream.py 로 통과시키도록 감싼다. 종료코드는 pipefail 로 보존(bash·zsh 공통).
1717
+ 원 명령은 base64 로 실어 따옴표 문제를 없앤다. 파이프 안이라 cd 등 셸 상태는 유지되지 않는다."""
1718
+ import shlex
1719
+ b64 = base64.b64encode(cmd.encode('utf-8')).decode('ascii')
1720
+ scrub = 'python3 ' + shlex.quote(os.path.join(lib_dir, 'scrub_stream.py')) + \
1721
+ ''.join(' ' + shlex.quote(f) for f in files)
1722
+ return ("( set -o pipefail; { eval \"$(printf '%s' '" + b64 + "' | base64 --decode)\"; } 2>&1 | " + scrub + " )")
1723
+
1724
+
1725
+ def scrub_values_for(files: List[str]) -> List[str]:
1726
+ """scrub_stream 이 가릴 값: 비밀 파일에서 뽑은 값 + 이름이 비밀스러운 환경변수 값."""
1727
+ vals = set()
1728
+ for f in files:
1729
+ plain, _enc = _extract_values_from_file(f)
1730
+ vals |= set(plain)
1731
+ # 감지 여부와 무관하게 정책의 모든 보호 파일 값(+인코딩형)도 가린다 — 경로를 숨긴 접근(따옴표 조각·
1732
+ # 변수·인라인 스크립트)으로 읽어도 출력에서는 걸린다.
1733
+ try:
1734
+ vals |= set(collect_protected_values())
1735
+ except Exception:
1736
+ pass
1737
+ for k, v in os.environ.items():
1738
+ if v and len(v) >= 6 and _SECRET_ENV_NAME_RE.search(k) and not _PUBLIC_VALUE_RE.match(v):
1739
+ vals.add(v)
1740
+ return sorted(vals, key=len, reverse=True)
1741
+
1742
+
1301
1743
  def summarize_matches(matches: List[SecretMatch]) -> str:
1302
1744
  """Build a user-facing summary of detected secrets."""
1303
1745
  if not matches: