@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51

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 (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +448 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +788 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +149 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3633 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +141 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +93 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +379 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +1011 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +288 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +426 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +400 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +716 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +59531 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1923 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,1514 @@
1
+ """Shared credential detection and redaction for Token Optimizer.
2
+
3
+ Provides compiled regex patterns for common API keys, tokens, and secrets,
4
+ plus scan/redact functions usable by bash compression, read cache, and
5
+ tool archive writers.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import re
14
+ import secrets
15
+ import subprocess
16
+ import sys
17
+ from datetime import datetime, timezone
18
+ from pathlib import Path
19
+ from typing import Dict, List, Optional, Tuple
20
+
21
+ # (label, compiled_regex) pairs. Label is used in redaction placeholders.
22
+ CREDENTIAL_PATTERNS: List[Tuple[str, "re.Pattern[str]"]] = [
23
+ ("AWS access key", re.compile(r"AKIA[0-9A-Z]{16}")),
24
+ # Anthropic first so a sk-ant- key keeps its own label; the generic sk- class
25
+ # carries "_" and "-" (sk-proj-..., sk-ant-api03-...) exactly like the TS engines.
26
+ ("Anthropic key", re.compile(r"sk-ant-[a-zA-Z0-9_\-]{20,}")),
27
+ ("OpenAI/Anthropic key", re.compile(r"sk-[a-zA-Z0-9_\-]{20,}")),
28
+ ("GitHub PAT classic", re.compile(r"ghp_[a-zA-Z0-9]{36}")),
29
+ ("GitHub OAuth token", re.compile(r"gho_[a-zA-Z0-9]{36}")),
30
+ ("GitHub user-to-server token", re.compile(r"ghu_[a-zA-Z0-9]{36}")),
31
+ ("GitHub server token", re.compile(r"ghs_[a-zA-Z0-9]{36}")),
32
+ ("GitHub refresh token", re.compile(r"ghr_[a-zA-Z0-9]{36}")),
33
+ ("GitHub fine-grained PAT", re.compile(r"github_pat_[a-zA-Z0-9_]{20,}")),
34
+ ("npm token", re.compile(r"npm_[a-zA-Z0-9]{36}")),
35
+ # Current Slack shapes: long dash-separated bodies (xoxb-1-2-<24 secret>),
36
+ # app-level tokens, and incoming-webhook URLs (the URL path IS the secret).
37
+ # Listed before the short legacy rows so the whole token is claimed, not just
38
+ # its numeric head. The legacy rows below still catch bodies under 20 characters.
39
+ ("Slack token", re.compile(r"xox[bpa]-[0-9A-Za-z\-]{20,}")),
40
+ ("Slack app-level token", re.compile(r"xapp-\d-[A-Z0-9]+-\d+-[0-9a-f]+")),
41
+ ("Slack webhook URL", re.compile(r"https://hooks\.slack\.com/services/[A-Za-z0-9/_-]+")),
42
+ ("Slack bot token", re.compile(r"xoxb-[0-9]+-[a-zA-Z0-9]+")),
43
+ ("Slack user token", re.compile(r"xoxp-[0-9]+-[a-zA-Z0-9]+")),
44
+ ("Slack app token", re.compile(r"xoxa-[0-9]+-[a-zA-Z0-9]+")),
45
+ ("Stripe live key", re.compile(r"sk_live_[a-zA-Z0-9]{24,}")),
46
+ ("Stripe test key", re.compile(r"sk_test_[a-zA-Z0-9]{24,}")),
47
+ ("Stripe restricted key", re.compile(r"rk_live_[a-zA-Z0-9]{24,}")),
48
+ ("HuggingFace token", re.compile(r"hf_[a-zA-Z0-9]{34}")),
49
+ # GitLab: personal/project/group access (glpat), deploy (gldt), runner (glrt),
50
+ # CI build (glcbt), pipeline trigger (glptt), feed (glft), incoming mail (glimt),
51
+ # agent for Kubernetes (glagent), SCIM (glsoat). Newer "routable" tokens carry
52
+ # dots (glpat-<body>.01.<suffix>), so the body class includes ".".
53
+ ("GitLab token", re.compile(r"gl(?:pat|dt|rt|cbt|ptt|ft|imt|agent|soat)-[a-zA-Z0-9_.\-]{20,}")),
54
+ # M-16: negative lookahead so the Bearer pattern doesn't re-match text
55
+ # inside its own redaction placeholder [CREDENTIAL REDACTED: Bearer token].
56
+ # The lookahead checks the text BEFORE Bearer, but Python regex doesn't
57
+ # support variable-width lookbehinds. Instead, redact_credentials protects
58
+ # placeholders with a sentinel before running patterns. The lookahead here
59
+ # is a defense-in-depth for direct pattern.search() callers.
60
+ # Same rule as the TS engines (keep the four in step). 16-character floor, and the value
61
+ # must look like a token: a digit, a token punctuation mark, an interior capital, or a
62
+ # run of 24+ plain letters (no English word is that long). "the bearer of bad news" and
63
+ # "Bearer responsibilities" are prose. Only the word "bearer" is case-insensitive; the
64
+ # interior-capital test must not be.
65
+ ("Bearer token", re.compile(
66
+ r"\b(?i:bearer)\s+"
67
+ r"(?=[A-Za-z0-9._~+/=-]*(?:[0-9._~+/=-]|[A-Za-z][A-Z])|[A-Za-z]{24})"
68
+ r"[A-Za-z0-9._~+/=-]{16,}\b")),
69
+ ("Google API key", re.compile(r"AIza[0-9A-Za-z_\-]{35}")),
70
+ ("Google OAuth token", re.compile(r"ya29\.[0-9A-Za-z_\-]{20,}")),
71
+ # Linear on adversarial input. The old form rescanned a long base64url run from every
72
+ # "eyJ" inside it (4 s at 100 KB). The first segment may not contain another "eyJ"
73
+ # (a JWT header never does), so each start stops at the next candidate. The pattern
74
+ # still opens with the literal, so clean text keeps the engine's fast prefix scan,
75
+ # and a JWT glued to other characters (MEDX-123456-eyJ..., xeyJ...) still matches.
76
+ ("JWT", re.compile(
77
+ r"eyJ(?:(?!eyJ)[A-Za-z0-9_\-]){10,}"
78
+ r"\.[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}")),
79
+ # Whole block: the key body is the secret, the BEGIN line is not. A block
80
+ # with no END (cut by a length limit, or still being typed) runs to the end
81
+ # of the text so a truncated body is never left behind.
82
+ ("PEM private key", re.compile(
83
+ r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|\Z)")),
84
+ ("Database URI", re.compile(r"(?:postgres|postgresql|mysql|mongodb|mongodb\+srv|redis)://[^:\s/]+:[^@\s]+@", re.I)),
85
+ ("HTTP basic auth URL", re.compile(r"https?://[^:\s/@]+:[^@\s]+@", re.I)),
86
+ # Credentials passed as URL query/matrix parameters OR OAuth-implicit-flow
87
+ # fragment params (e.g. ?token=..., ?api_key=..., ;password=..., #access_token=...).
88
+ # The named `keep` group captures the "?name="/"#name=" prefix so redaction
89
+ # preserves the parameter name and blanks only the value (see redact_credentials).
90
+ # The value class stops at the next delimiter (& # ; whitespace quote < >) but
91
+ # otherwise matches EVERYTHING — including brackets — so a secret that itself
92
+ # contains a `[` (common in passwords) is redacted whole, not leaked past the
93
+ # bracket. To still avoid re-wrapping an already-inserted "[CREDENTIAL REDACTED:
94
+ # ...]" placeholder (when the value is itself another credential shape an earlier
95
+ # pattern redacted, e.g. ?token=<Bearer ...>), a negative lookahead skips a value
96
+ # that begins with the placeholder rather than excluding brackets from real values.
97
+ ("URL auth param", re.compile(
98
+ r"(?P<keep>[?&#;](?:authorization|access[_-]?token|refresh[_-]?token|client[_-]?secret"
99
+ r"|session[_-]?token|id[_-]?token|api[_-]?key|sessionid|session|password|passwd|signature"
100
+ r"|secret|bearer|token|auth|sig|pwd|key|jwt)=)(?!\[CREDENTIAL REDACTED:)[^&#;\s\"'<>]+",
101
+ re.I,
102
+ )),
103
+ # M-12: mysql -p<password> (inline password after -p with no space).
104
+ # The -p flag is special: the password immediately follows with no = or space.
105
+ # N-3: re.I so "MySQL -pSECRET" (capitalized client name, as MySQL ships
106
+ # it) is redacted too; the anchor gate already lowercases, so gating is
107
+ # unaffected.
108
+ ("MySQL password flag", re.compile(
109
+ r"(?P<keep>\bmysql\s+.*?(?<!\S)(?-i:-p)\s*)(?!-)(?!\[CREDENTIAL REDACTED:)"
110
+ r"(?:\"[^\"\n]*\"|'[^'\n]*'|[^\s\"']+)",
111
+ re.I,
112
+ )),
113
+ # M-12: PGPASSWORD=, MYSQL_PWD=, and similar *_PASSWORD= / *_PWD= env assignments.
114
+ # These appear as shell command prefixes (FOO=bar cmd ...) or in config output.
115
+ ("Database env password", re.compile(
116
+ r"(?P<keep>\b(?:PGPASSWORD|MYSQL_PWD|REDIS_PASSWORD|MONGO_PASSWORD|DB_PASSWORD"
117
+ r"|DATABASE_PASSWORD|PGPASSWD)=(?P<oq>[\"\'])?)(?!\[CREDENTIAL REDACTED:)"
118
+ # An opened quote runs to its twin (a value with spaces is one secret);
119
+ # an unquoted value stops at whitespace or a quote.
120
+ r"(?(oq)(?:(?!(?P=oq))[^\n])+|[^\s\"'\n]+)",
121
+ re.I,
122
+ )),
123
+ # M-12: AWS secret access key (40-char base64). Distinct from the access key
124
+ # (AKIA prefix). Secret keys are mixed-case base64, 40 chars, no prefix.
125
+ # Use a context prefix to avoid false positives on random 40-char base64
126
+ # strings. No trailing \b because the secret may end with = or + (non-word).
127
+ ("AWS secret key", re.compile(
128
+ r"(?P<keep>\b(?:aws_secret_access_key|aws_secret|secret_access_key|SecretAccessKey)[\"\'\s:=]+)"
129
+ r"(?!\[CREDENTIAL REDACTED:)[A-Za-z0-9/+=]{40}",
130
+ re.I,
131
+ )),
132
+ # Inline CLI password flags. Two patterns:
133
+ # (a) Long forms (--password=V, --password V, --passwd=V, --passcode=V,
134
+ # --auth-token=V) — unambiguous, always redact.
135
+ # (b) Short forms (-p V, -a V) restricted to known password-carrying
136
+ # commands (sshpass, mysql, mariadb, redis-cli) to avoid false
137
+ # positives on -p port/plugin/preserve flags in other commands.
138
+ # The named `keep` group captures the flag (+ command context for short
139
+ # forms) so redaction preserves it and blanks only the value.
140
+ ("CLI password flag (long)", re.compile(
141
+ r"(?P<keep>(?:--password|--passwd|--passcode|--auth-token)(?![\w-])(?:\s*=\s*|\s+))"
142
+ r"(?!-)(?!\[CREDENTIAL REDACTED:)"
143
+ r"(?:\"[^\"\n]*\"|'[^'\n]*'|[^\s\"']+)",
144
+ re.I,
145
+ )),
146
+ ("CLI password flag (short)", re.compile(
147
+ r"(?P<keep>sshpass\b.*?(?<!\S)(?-i:-p)\s*"
148
+ r"|redis-cli\b.*?(?<!\S)(?-i:-a)\s+"
149
+ r"|mariadb\b.*?(?<!\S)(?-i:-p)\s*)"
150
+ r"(?!-)(?!\[CREDENTIAL REDACTED:)"
151
+ r"(?:\"[^\"\n]*\"|'[^'\n]*'|[^\s\"']+)",
152
+ re.I,
153
+ )),
154
+ ]
155
+
156
+ # Bare compiled patterns list for backward compat with bash_compress.py
157
+ PATTERNS_ONLY: List["re.Pattern[str]"] = [pat for _, pat in CREDENTIAL_PATTERNS]
158
+
159
+ # ---------------------------------------------------------------------------
160
+ # H-8: fast pre-check for credential redaction.
161
+ #
162
+ # The old redact_credentials ran 23 sequential re.sub() calls on the full
163
+ # text unconditionally: 97ms for 10K lines, 675ms for 50K lines, even when
164
+ # the text contained NO credentials (the common case for command output).
165
+ # Python's re engine uses backtracking, not a DFA, so combining all
166
+ # patterns into a single alternation is actually SLOWER (154ms for 10K
167
+ # clean lines) due to the complex NFA state per character.
168
+ #
169
+ # The fix: a fast prefix scan using simple string containment checks
170
+ # before any regex runs. If none of the credential prefixes appear in the
171
+ # text, skip all 23 re.sub() calls entirely. This makes clean text O(n)
172
+ # with a tiny constant (a single str.find pass per prefix), while text
173
+ # with credentials still gets the full sequential redaction (correctness
174
+ # preserved, no regex complexity change).
175
+ #
176
+ # The prefix list is derived from the literal prefixes of each pattern:
177
+ # "AKIA", "sk-", "ghp_", "gho_", "ghs_", "ghr_", "github_pat_", "npm_",
178
+ # "xoxb-", "xoxp-", "xoxa-", "sk_live_", "rk_live_", "hf_", "gl*-", "Bearer",
179
+ # "AIza", "ya29.", "eyJ", "-----BEGIN", and the URL scheme prefixes for
180
+ # database/basic-auth URIs. The URL auth param pattern has no single
181
+ # literal prefix (it matches parameter names), so we check for "=" as a
182
+ # coarse pre-filter — but only if other prefixes didn't already match.
183
+ # ---------------------------------------------------------------------------
184
+ _CREDENTIAL_PREFIXES: Tuple[str, ...] = (
185
+ "AKIA", "sk-", "ghp_", "gho_", "ghu_", "ghs_", "ghr_", "github_pat_",
186
+ "npm_", "xoxb-", "xoxp-", "xoxa-", "xapp-", "sk_live_", "sk_test_", "rk_live_", "hf_",
187
+ "glpat-", "gldt-", "glrt-", "glcbt-", "glptt-", "glft-", "glimt-", "glagent-", "glsoat-", # GitLab
188
+ "Bearer", "bearer", "AIza", "ya29.", "eyJ",
189
+ "-----BEGIN", # PEM private key
190
+ "postgres://", "postgresql://", "mysql://", "mongodb://",
191
+ "mongodb+srv://", "redis://", # database URI
192
+ "http://", "https://", # basic auth URL (coarse, but covers the pattern)
193
+ # M-12: new credential prefixes
194
+ "mysql ", # mysql -p<password>
195
+ "PGPASSWORD=", "MYSQL_PWD=", "REDIS_PASSWORD=", "MONGO_PASSWORD=",
196
+ "DB_PASSWORD=", "DATABASE_PASSWORD=", "PGPASSWD=",
197
+ "aws_secret", "secret_access_key", "SecretAccessKey",
198
+ )
199
+ # URL auth param parameter names (lowercase, checked case-insensitively).
200
+ _URL_AUTH_PARAM_NAMES: Tuple[str, ...] = (
201
+ "authorization=", "access_token=", "access-token=", "refresh_token=",
202
+ "refresh-token=", "client_secret=", "client-secret=", "session_token=",
203
+ "session-token=", "id_token=", "id-token=", "api_key=", "api-key=",
204
+ "sessionid=", "session=", "password=", "passwd=", "signature=",
205
+ "secret=", "bearer=", "token=", "auth=", "sig=", "pwd=", "key=",
206
+ "jwt=",
207
+ )
208
+
209
+
210
+ def _text_may_contain_credentials(text: str) -> bool:
211
+ """Fast prefix scan: return True if any credential prefix appears in text.
212
+
213
+ This is a coarse pre-filter using str.find (C-level, no regex engine).
214
+ False negatives would be a security bug, so every prefix is checked.
215
+ False positives are fine — the full regex suite runs and finds nothing.
216
+ """
217
+ for prefix in _CREDENTIAL_PREFIXES:
218
+ if prefix in text:
219
+ return True
220
+ # URL auth param names are case-insensitive in the pattern. Use a
221
+ # lowercase copy for the check.
222
+ lower = text.lower()
223
+ for name in _URL_AUTH_PARAM_NAMES:
224
+ if name in lower:
225
+ return True
226
+ return False
227
+
228
+
229
+ # ---------------------------------------------------------------------------
230
+ # Custom (user-defined) redaction patterns.
231
+ #
232
+ # Organizations have secret shapes no built-in list can know about: internal
233
+ # API keys, service tokens, record identifiers. Users add them in a JSON file
234
+ # instead of editing this module:
235
+ #
236
+ # <runtime-home>/token-optimizer/redact-patterns.json (default location)
237
+ #
238
+ # or point TOKEN_OPTIMIZER_REDACT_PATTERNS_FILE at another path (process env
239
+ # first, then the settings.json "env" block, like the other TOKEN_OPTIMIZER_*
240
+ # knobs). Format:
241
+ #
242
+ # {"patterns": [
243
+ # "acme_[A-Za-z0-9]{32}",
244
+ # {"label": "Acme service token", "regex": "(?P<keep>ACME_TOKEN=)\\S+",
245
+ # "ignore_case": true}
246
+ # ]}
247
+ #
248
+ # Custom patterns run BEFORE the built-ins: a fragment like
249
+ # "MEDX-123456-<jwt>" must be claimed whole by the org pattern, not left as a
250
+ # readable id prefix next to a "[CREDENTIAL REDACTED: JWT]" placeholder. They
251
+ # still cannot touch a "[CREDENTIAL REDACTED: ...]" placeholder that was
252
+ # already in the input (re-running redaction on archived text stays
253
+ # idempotent). They apply to redact_credentials() and scan_for_credentials(),
254
+ # i.e. everything written to disk. CREDENTIAL_PATTERNS and PATTERNS_ONLY stay
255
+ # the built-in set (import-time constants, used by compressors to decide which
256
+ # lines to keep verbatim).
257
+ #
258
+ # Loading is lazy (first redaction call) and cached per process. Two failure
259
+ # tiers, deliberately different:
260
+ #
261
+ # * A bad ENTRY (invalid regex, unsafe shape, over-broad) is skipped on its
262
+ # own with a recorded error; the rest of the file still loads.
263
+ # * A FILE that was configured or is present but cannot be trusted
264
+ # (unreadable, invalid JSON, wrong shape, a relative env path) makes
265
+ # redact_credentials() raise RedactionConfigError — every disk writer in
266
+ # the pipeline then skips persisting that content rather than storing text
267
+ # the user's own patterns were meant to cover. Fail closed, never open.
268
+ # ---------------------------------------------------------------------------
269
+ CUSTOM_PATTERNS_FILE_ENV = "TOKEN_OPTIMIZER_REDACT_PATTERNS_FILE"
270
+ CUSTOM_PATTERNS_FILENAME = "redact-patterns.json"
271
+ _CUSTOM_STATUS_FILENAME = "redact-patterns-status.json"
272
+ _CUSTOM_PROBE_CACHE_FILENAME = "redact-probe-cache.json"
273
+ _CUSTOM_DEFAULT_LABEL = "custom pattern"
274
+ _CUSTOM_MAX_FILE_BYTES = 1_048_576
275
+ _CUSTOM_MAX_PATTERNS = 200
276
+ _CUSTOM_MAX_REGEX_CHARS = 1000
277
+ _CUSTOM_MAX_LABEL_CHARS = 60
278
+ # Hard wall-clock budget for the whole safety-probe subprocess, and the max
279
+ # number of probe passes (each timeout rejects the in-flight pattern and the
280
+ # remainder get one more pass).
281
+ _CUSTOM_PROBE_TIMEOUT_SECONDS = 2.0
282
+ _CUSTOM_PROBE_MAX_PASSES = 3
283
+ # Probe children must not flash a console window when the hook runs under a
284
+ # GUI process on Windows; 0 is a no-op off Windows.
285
+ _NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
286
+ # Characters that would break the "[CREDENTIAL REDACTED: <label>]" placeholder
287
+ # (and _PLACEHOLDER_RE, which stops at "]") or the one-line archive format.
288
+ _LABEL_UNSAFE_RE = re.compile(r"[\]\[\x00-\x1f\x7f]")
289
+
290
+ _BUILTIN_KEYS = frozenset((pat.pattern, pat.flags) for _, pat in CREDENTIAL_PATTERNS)
291
+
292
+
293
+ class RedactionConfigError(RuntimeError):
294
+ """A configured custom redaction-pattern file could not be trusted.
295
+
296
+ Raised by redact_credentials() and scan_for_credentials() when the file the
297
+ user pointed us at (or dropped at the default location) is present but
298
+ unloadable — unreadable, malformed JSON, wrong top-level shape, or a
299
+ relative TOKEN_OPTIMIZER_REDACT_PATTERNS_FILE value. Distinct from a
300
+ per-entry rejection so callers that persist text can fail CLOSED: skip the
301
+ write entirely instead of storing content that org-specific secret shapes
302
+ were configured to cover.
303
+ """
304
+
305
+
306
+ class _CustomPatternState:
307
+ """Result of one load: the compiled patterns, where they came from, and
308
+ human-readable problems (for the security report and stderr)."""
309
+
310
+ __slots__ = ("patterns", "source", "errors", "duplicates", "rejected",
311
+ "failed", "failure", "file_hash")
312
+
313
+ def __init__(self) -> None:
314
+ self.patterns: List[Tuple[str, "re.Pattern[str]"]] = []
315
+ self.source: Optional[str] = None
316
+ self.errors: List[str] = []
317
+ self.duplicates: int = 0
318
+ self.rejected: int = 0
319
+ # failed/failure: the file itself could not be trusted — redaction must
320
+ # fail closed (raise) rather than run with fewer patterns than the user
321
+ # configured.
322
+ self.failed: bool = False
323
+ self.failure: Optional[str] = None
324
+ # sha256 of the file bytes actually read; keys the probe-verdict cache
325
+ # and the once-per-hash user warning. None when nothing was read.
326
+ self.file_hash: Optional[str] = None
327
+
328
+
329
+ _CUSTOM_STATE: Optional[_CustomPatternState] = None
330
+
331
+
332
+ def _warn(msg: str) -> None:
333
+ try:
334
+ print(f"[token-optimizer] {msg}", file=sys.stderr)
335
+ except Exception:
336
+ pass
337
+
338
+
339
+ def _settings_env_value(name: str) -> str:
340
+ """Read ``name`` from the settings.json "env" block. Never raises.
341
+
342
+ Delegates to runtime_env.settings_env_value — the same resolution the other
343
+ TOKEN_OPTIMIZER_* env knobs use (the user's global settings.json only;
344
+ project settings are not read by hooks)."""
345
+ try:
346
+ from runtime_env import settings_env_value
347
+ return settings_env_value(name)
348
+ except Exception:
349
+ return ""
350
+
351
+
352
+ def _default_custom_patterns_path() -> Optional[Path]:
353
+ try:
354
+ from runtime_env import runtime_home
355
+ return runtime_home() / "token-optimizer" / CUSTOM_PATTERNS_FILENAME
356
+ except Exception:
357
+ return None
358
+
359
+
360
+ def _resolve_custom_patterns_path() -> Tuple[Optional[Path], bool, Optional[str]]:
361
+ """Return (path, explicit, error). ``explicit`` is True when the user named
362
+ the file via TOKEN_OPTIMIZER_REDACT_PATTERNS_FILE. ``error`` is set when the
363
+ env value is unusable — a relative path would resolve against whatever cwd
364
+ the hook happened to launch with, so a repo could silently substitute its
365
+ own pattern file; only absolute paths are accepted."""
366
+ raw = os.environ.get(CUSTOM_PATTERNS_FILE_ENV, "").strip()
367
+ if not raw:
368
+ raw = _settings_env_value(CUSTOM_PATTERNS_FILE_ENV)
369
+ if not raw:
370
+ return _default_custom_patterns_path(), False, None
371
+ # Windows users often paste a quoted path into env vars; strip one
372
+ # surrounding quote pair before expansion.
373
+ if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in "\"'":
374
+ raw = raw[1:-1].strip()
375
+ if not raw:
376
+ return _default_custom_patterns_path(), False, None
377
+ path = Path(os.path.expanduser(os.path.expandvars(raw)))
378
+ if not path.is_absolute():
379
+ return (None, True,
380
+ f"{CUSTOM_PATTERNS_FILE_ENV} must be an absolute path "
381
+ f"(after ~ and env expansion), got {raw!r}")
382
+ return path, True, None
383
+
384
+
385
+ def _clean_label(raw: object) -> str:
386
+ if not isinstance(raw, str):
387
+ return _CUSTOM_DEFAULT_LABEL
388
+ label = _LABEL_UNSAFE_RE.sub("", raw).strip()
389
+ label = " ".join(label.split())[:_CUSTOM_MAX_LABEL_CHARS].strip()
390
+ return label or _CUSTOM_DEFAULT_LABEL
391
+
392
+
393
+ def _reject_entry(state: _CustomPatternState, msg: str) -> None:
394
+ """Skip one entry and record why. File-level failures use state.failed
395
+ instead — an entry rejection leaves the rest of the file usable."""
396
+ state.errors.append(msg)
397
+ state.rejected += 1
398
+
399
+
400
+ # --- ReDoS guards ------------------------------------------------------------
401
+ #
402
+ # Custom regexes run on the hook hot path against arbitrary tool output, and
403
+ # Python's re engine backtracks: a pathological pattern like (x+x+)+y does not
404
+ # error, it just burns exponential time and wedges the hook mid-write. Two
405
+ # layers keep that out:
406
+ #
407
+ # 1. _redos_lint — a syntactic check run at load time that rejects the two
408
+ # classic catastrophic shapes: an unbounded-quantified group whose body
409
+ # contains an unbounded quantifier ((x+x+)+), and an unbounded-quantified
410
+ # alternation whose branches overlap ((a|aa)+, including an empty branch).
411
+ # 2. _probe_candidates — anything subtler is measured, not guessed: every
412
+ # surviving pattern is run in a subprocess against adversarial probe
413
+ # strings under a hard time budget; a pattern that times out is rejected.
414
+ #
415
+ # The probe verdict is cached on disk keyed by the pattern file's sha256, so
416
+ # the subprocess only runs when the file changes — never per hook invocation.
417
+
418
+
419
+ def _quantifier_at(src: str, i: int) -> Tuple[int, bool]:
420
+ """Quantifier starting at ``i``: return (length, is_unbounded).
421
+
422
+ Unbounded means the repeat has no fixed upper bound: ``*``, ``+`` or
423
+ ``{n,}`` (lazy ``?`` suffix included). ``?`` and ``{n}``/``{n,m}`` are
424
+ bounded. Returns (0, False) when the char is not a quantifier — e.g. a
425
+ literal ``{`` that does not form ``{m}``/``{m,n}`` syntax.
426
+ """
427
+ if i >= len(src):
428
+ return 0, False
429
+ ch = src[i]
430
+ if ch in "*+":
431
+ j = i + 1
432
+ if j < len(src) and src[j] == "?":
433
+ j += 1
434
+ return j - i, True
435
+ if ch == "?":
436
+ j = i + 1
437
+ if j < len(src) and src[j] == "?":
438
+ j += 1
439
+ return j - i, False
440
+ if ch == "{":
441
+ m = re.match(r"\{(\d+)(?:,(\d*))?\}\??", src[i:])
442
+ if not m:
443
+ return 0, False
444
+ # {n} and {n,m} are bounded; only the open-ended {n,} form is not.
445
+ unbounded = "," in m.group(0) and not m.group(2)
446
+ return m.end(), unbounded
447
+ return 0, False
448
+
449
+
450
+ def _redos_lint(src: str) -> Optional[str]:
451
+ """Static check for catastrophic-backtracking shapes; error text or None.
452
+
453
+ Tracks a stack of group frames. Each frame records whether its body
454
+ contains an unbounded quantifier (``inner``) and the first literal char of
455
+ each top-level ``|`` branch. When a group closes with an unbounded
456
+ quantifier, an ``inner`` body means nested unbounded quantifiers and
457
+ overlapping branch starts mean an ambiguous alternation — both reject.
458
+ A quantified or inner-unbounded group marks its parent's ``inner`` too, so
459
+ shapes like ``((ab)+)+`` are caught at the outer level.
460
+ """
461
+ def _frame() -> dict:
462
+ # first: first literal char of the branch being scanned (None when it
463
+ # starts with a class/group/dot — i.e. we cannot tell); empty: branch
464
+ # has consumed no atom yet.
465
+ return {"inner": False, "branches": [], "first": None,
466
+ "awaiting_first": True, "empty": True}
467
+
468
+ stack = [_frame()]
469
+ i, n = 0, len(src)
470
+ while i < n:
471
+ ch = src[i]
472
+ cur = stack[-1]
473
+ if ch == "\\":
474
+ if i + 1 >= n:
475
+ break
476
+ nxt = src[i + 1]
477
+ if cur["awaiting_first"] and nxt not in "AbBZGz":
478
+ # Class escapes (\d \w \s ...) and the rest: the first char is
479
+ # unknowable statically. Escaped literals (\. \\ \[ ...) are.
480
+ cur["first"] = nxt if nxt not in "dDsSwW" else None
481
+ cur["awaiting_first"] = False
482
+ cur["empty"] = False
483
+ i += 2
484
+ continue
485
+ if ch == "[":
486
+ j = i + 1
487
+ if j < n and src[j] == "^":
488
+ j += 1
489
+ if j < n and src[j] == "]":
490
+ j += 1
491
+ while j < n:
492
+ if src[j] == "\\":
493
+ j += 1
494
+ elif src[j] == "]":
495
+ break
496
+ j += 1
497
+ if cur["awaiting_first"]:
498
+ cur["first"] = None
499
+ cur["awaiting_first"] = False
500
+ cur["empty"] = False
501
+ i = min(j + 1, n)
502
+ continue
503
+ if ch == "(":
504
+ # (?P=name) is a backreference atom and (?#...) a comment: both end
505
+ # at the next ")" and open no group frame.
506
+ if src.startswith("(?P=", i) or src.startswith("(?#", i):
507
+ end = src.find(")", i)
508
+ if cur["awaiting_first"] and src.startswith("(?P=", i):
509
+ cur["first"] = None
510
+ cur["awaiting_first"] = False
511
+ cur["empty"] = False
512
+ i = n if end < 0 else end + 1
513
+ continue
514
+ # (?imsx) sets flags inline — an atom, not a group.
515
+ m = re.match(r"\(\?[aiLmsux]+\)", src[i:])
516
+ if m:
517
+ i += m.end()
518
+ continue
519
+ # Every other "(..." opens a group frame: (?: (?= (?! (?<= (<!
520
+ # (?P<name> and scoped-flag (?imsx: bodies.
521
+ if src.startswith("(?P<", i):
522
+ gt = src.find(">", i)
523
+ i = n if gt < 0 else gt + 1
524
+ elif src[i:i + 4] in ("(?<=", "(?<!"):
525
+ i += 4
526
+ elif src.startswith("(?", i):
527
+ j = i + 2
528
+ while j < n and src[j] in "aiLmsux-":
529
+ j += 1
530
+ i = j + 1 if j < n and src[j] == ":" else i + 3
531
+ else:
532
+ i += 1
533
+ stack.append(_frame())
534
+ continue
535
+ if ch == "|":
536
+ cur["branches"].append((cur["first"], cur["empty"]))
537
+ cur["first"] = None
538
+ cur["awaiting_first"] = True
539
+ cur["empty"] = True
540
+ i += 1
541
+ continue
542
+ if ch == ")":
543
+ if len(stack) <= 1:
544
+ i += 1 # unmatched ")" — re.compile already reported it
545
+ continue
546
+ done = stack.pop()
547
+ done["branches"].append((done["first"], done["empty"]))
548
+ qlen, unbounded = _quantifier_at(src, i + 1)
549
+ if qlen == 0 and i + 1 < n and src[i + 1] == "?":
550
+ qlen = 1 # bounded (0-or-1) group repeat
551
+ if unbounded:
552
+ if done["inner"]:
553
+ return ("nested unbounded quantifiers can backtrack "
554
+ "exponentially (a repeated group containing "
555
+ "*, + or {n,})")
556
+ firsts = [f for f, _e in done["branches"] if f is not None]
557
+ if len(firsts) != len(set(firsts)) or any(
558
+ e for _f, e in done["branches"]):
559
+ return ("a repeated alternation with overlapping or empty "
560
+ "branches can backtrack exponentially")
561
+ # Propagate: a quantified group, or one containing an unbounded
562
+ # quantifier, makes the enclosing body ambiguously repeatable.
563
+ parent = stack[-1]
564
+ if done["inner"] or qlen:
565
+ parent["inner"] = True
566
+ if parent["awaiting_first"]:
567
+ parent["first"] = None
568
+ parent["awaiting_first"] = False
569
+ parent["empty"] = False
570
+ i += 1 + qlen
571
+ continue
572
+ if ch in "*+?{":
573
+ qlen, unbounded = _quantifier_at(src, i)
574
+ if qlen:
575
+ if unbounded:
576
+ cur["inner"] = True
577
+ i += qlen
578
+ continue
579
+ # else: a "{" that is not quantifier syntax — literal char below.
580
+ # Literal atom (anchors ^$ and "." can't be pinned to a first char).
581
+ if cur["awaiting_first"]:
582
+ cur["first"] = ch if ch not in "^$." else None
583
+ cur["awaiting_first"] = False
584
+ cur["empty"] = False
585
+ i += 1
586
+ return None
587
+
588
+
589
+ # A deliberately boring text sample: prose, code-ish lines, a URL, an email —
590
+ # what tool output looks like when it holds no secrets. A custom pattern that
591
+ # matches a single character or eats most of this would shred every archived
592
+ # output, not just secrets.
593
+ _BENIGN_SAMPLE = (
594
+ "The quick brown fox jumps over the lazy dog while the server hums.\n"
595
+ "def compute_total(items):\n"
596
+ " return sum(item.price for item in items)\n"
597
+ "See https://docs.example.com/setup for the install guide and notes.\n"
598
+ "User alice@example.com ran 3 reports at 12:30 and logged off.\n"
599
+ "warning: retry 2 of 5 in worker-7, elapsed 481 ms\n"
600
+ )
601
+ # Reject when a pattern's matches would cover more than this fraction of the
602
+ # benign sample (the `keep` group, which survives, is not counted).
603
+ _BENIGN_MAX_COVER = 0.5
604
+
605
+
606
+ def _broadness_error(pat: "re.Pattern[str]") -> Optional[str]:
607
+ """Reject patterns that would redact nearly everything they see."""
608
+ try:
609
+ covered = 0
610
+ limit = len(_BENIGN_SAMPLE) * _BENIGN_MAX_COVER
611
+ for m in pat.finditer(_BENIGN_SAMPLE):
612
+ width = m.end() - m.start()
613
+ if "keep" in pat.groupindex and m.group("keep") is not None:
614
+ ks, ke = m.span("keep")
615
+ width -= ke - ks
616
+ if width <= 1:
617
+ return "matches single characters; too broad to be a credential shape"
618
+ covered += width
619
+ if covered > limit:
620
+ return "matches most of an ordinary paragraph; too broad to be a credential shape"
621
+ except Exception:
622
+ return "could not be evaluated safely"
623
+ return None
624
+
625
+
626
+ def _compile_custom_entry(entry: object, index: int, state: _CustomPatternState,
627
+ seen: set, candidates: list) -> None:
628
+ where = f"entry {index}"
629
+ if isinstance(entry, str):
630
+ regex, label, ignore_case = entry, _CUSTOM_DEFAULT_LABEL, False
631
+ elif isinstance(entry, dict):
632
+ regex = entry.get("regex")
633
+ label = _clean_label(entry.get("label"))
634
+ ignore_case = entry.get("ignore_case", False)
635
+ if not isinstance(ignore_case, bool):
636
+ _reject_entry(state, f"{where}: ignore_case must be true or false")
637
+ return
638
+ else:
639
+ _reject_entry(state, f"{where}: must be a string or an object with a \"regex\" key")
640
+ return
641
+ if not isinstance(regex, str) or not regex.strip():
642
+ _reject_entry(state, f"{where}: regex is missing or empty")
643
+ return
644
+ if len(regex) > _CUSTOM_MAX_REGEX_CHARS:
645
+ _reject_entry(state, f"{where}: regex longer than {_CUSTOM_MAX_REGEX_CHARS} characters")
646
+ return
647
+ try:
648
+ pat = re.compile(regex, re.I if ignore_case else 0)
649
+ except (re.error, RecursionError, OverflowError, ValueError) as exc:
650
+ _reject_entry(state, f"{where}: invalid regex ({exc})")
651
+ return
652
+ # A pattern that matches the empty string would insert a placeholder
653
+ # between every character of every archived output.
654
+ try:
655
+ matches_empty = pat.search("") is not None
656
+ except Exception:
657
+ matches_empty = True
658
+ if matches_empty:
659
+ _reject_entry(state, f"{where}: regex matches empty text")
660
+ return
661
+ lint = _redos_lint(regex)
662
+ if lint:
663
+ _reject_entry(state, f"{where}: unsafe regex — {lint}")
664
+ return
665
+ broad = _broadness_error(pat)
666
+ if broad:
667
+ _reject_entry(state, f"{where}: {broad}")
668
+ return
669
+ key = (pat.pattern, pat.flags)
670
+ if key in _BUILTIN_KEYS or key in seen:
671
+ state.duplicates += 1
672
+ return
673
+ seen.add(key)
674
+ candidates.append((index, label, regex, ignore_case, pat))
675
+
676
+
677
+ # Probe strings: long single-class runs (where nested quantifiers blow up),
678
+ # near-miss shapes, and the benign sample. Kept small so a healthy pattern
679
+ # finishes in well under a millisecond each.
680
+ _PROBE_STRINGS: Tuple[str, ...] = (
681
+ "a" * 512,
682
+ "x" * 512,
683
+ "0" * 512,
684
+ "_" * 512,
685
+ "=" * 512,
686
+ "Aa" * 256,
687
+ "ab1_" * 128,
688
+ "https://example.com/" + "a" * 512,
689
+ "x" * 256 + "y",
690
+ _BENIGN_SAMPLE,
691
+ )
692
+
693
+ # Self-contained probe program (stdlib only): reads {"patterns": [...],
694
+ # "probes": [...]} on stdin, prints BEGIN <i> before each pattern and DONE <i>
695
+ # (or ERR <i> <class>) after it. The BEGIN/DONE markers let the parent tell —
696
+ # after killing a timed-out subprocess — exactly which pattern was in flight.
697
+ _PROBE_SNIPPET = (
698
+ "import json,re,sys\n"
699
+ "spec=json.load(sys.stdin)\n"
700
+ "probes=spec['probes']\n"
701
+ "for it in spec['patterns']:\n"
702
+ " i=it['index']\n"
703
+ " print('BEGIN',i,flush=True)\n"
704
+ " try:\n"
705
+ " pat=re.compile(it['regex'], re.I if it.get('ignore_case') else 0)\n"
706
+ " for s in probes:\n"
707
+ " pat.search(s)\n"
708
+ " except Exception as e:\n"
709
+ " print('ERR',i,type(e).__name__,flush=True)\n"
710
+ " continue\n"
711
+ " print('DONE',i,flush=True)\n"
712
+ "print('ALLDONE',flush=True)\n"
713
+ )
714
+
715
+
716
+ def _runtime_token_dir() -> Optional[Path]:
717
+ try:
718
+ from runtime_env import runtime_home
719
+ return runtime_home() / "token-optimizer"
720
+ except Exception:
721
+ return None
722
+
723
+
724
+ def _probe_cache_path() -> Optional[Path]:
725
+ d = _runtime_token_dir()
726
+ return d / _CUSTOM_PROBE_CACHE_FILENAME if d is not None else None
727
+
728
+
729
+ def _cached_probe_verdicts(file_hash: Optional[str]) -> Optional[Dict[int, Optional[str]]]:
730
+ """Probe verdicts for this exact file content, if a previous process
731
+ already ran the probe for it. The cache lives under the runtime home so it
732
+ is keyed to this machine's user, and the key is the file's sha256 — a file
733
+ edit is a new hash and gets probed fresh."""
734
+ path = _probe_cache_path()
735
+ if not file_hash or path is None:
736
+ return None
737
+ try:
738
+ data = json.loads(path.read_text(encoding="utf-8"))
739
+ rec = data.get(file_hash) if isinstance(data, dict) else None
740
+ if isinstance(rec, dict) and rec.get("complete") and isinstance(rec.get("verdicts"), dict):
741
+ return {int(k): v for k, v in rec["verdicts"].items()}
742
+ except Exception:
743
+ return None
744
+ return None
745
+
746
+
747
+ def _cache_probe_verdicts(file_hash: Optional[str], verdicts: Dict[int, Optional[str]]) -> None:
748
+ path = _probe_cache_path()
749
+ if not file_hash or path is None:
750
+ return
751
+ try:
752
+ path.parent.mkdir(parents=True, exist_ok=True)
753
+ data: dict = {}
754
+ if path.is_file():
755
+ try:
756
+ loaded = json.loads(path.read_text(encoding="utf-8"))
757
+ if isinstance(loaded, dict):
758
+ data = loaded
759
+ except Exception:
760
+ data = {}
761
+ data[file_hash] = {
762
+ "verdicts": {str(k): v for k, v in verdicts.items()},
763
+ "complete": True,
764
+ "probed_at": datetime.now(timezone.utc).isoformat(),
765
+ }
766
+ # Keep the cache small: retain the newest few file hashes.
767
+ while len(data) > 8:
768
+ data.pop(next(iter(data)))
769
+ tmp = path.with_suffix(".tmp")
770
+ tmp.write_text(json.dumps(data), encoding="utf-8")
771
+ os.replace(tmp, path)
772
+ except Exception:
773
+ pass
774
+
775
+
776
+ def _probe_pass(items: list) -> Tuple[Dict[int, Optional[str]], Optional[int], bool]:
777
+ """One probe subprocess over ``items``.
778
+
779
+ Returns (verdicts, inflight, finished): verdicts maps candidate index to
780
+ None (passed) or an error string; inflight is the index mid-probe when the
781
+ budget ran out (None unless the subprocess was killed); finished is True
782
+ when the subprocess reached the end of the list.
783
+ """
784
+ payload = {
785
+ "probes": list(_PROBE_STRINGS),
786
+ "patterns": [{"index": idx, "regex": regex, "ignore_case": ic}
787
+ for idx, _label, regex, ic, _pat in items],
788
+ }
789
+ try:
790
+ proc = subprocess.run(
791
+ [sys.executable or "python3", "-c", _PROBE_SNIPPET],
792
+ input=json.dumps(payload),
793
+ capture_output=True,
794
+ text=True,
795
+ timeout=_CUSTOM_PROBE_TIMEOUT_SECONDS,
796
+ creationflags=_NO_WINDOW,
797
+ )
798
+ out = proc.stdout or ""
799
+ except subprocess.TimeoutExpired as exc:
800
+ raw = exc.stdout or ""
801
+ out = raw.decode("utf-8", errors="replace") if isinstance(raw, bytes) else raw
802
+ except Exception:
803
+ # No interpreter to probe with — nothing in this batch is verified.
804
+ return ({idx: "safety probe could not run" for idx, *_ in items},
805
+ None, True)
806
+ verdicts: Dict[int, Optional[str]] = {}
807
+ inflight: Optional[int] = None
808
+ finished = False
809
+ for line in out.splitlines():
810
+ parts = line.split(None, 2)
811
+ if len(parts) < 2:
812
+ continue
813
+ tag = parts[0]
814
+ if tag == "BEGIN":
815
+ try:
816
+ inflight = int(parts[1])
817
+ except ValueError:
818
+ pass
819
+ elif tag == "DONE":
820
+ try:
821
+ verdicts[int(parts[1])] = None
822
+ except ValueError:
823
+ pass
824
+ inflight = None
825
+ elif tag == "ERR":
826
+ why = parts[2] if len(parts) > 2 else "error"
827
+ try:
828
+ verdicts[int(parts[1])] = f"failed its safety probe ({why})"
829
+ except ValueError:
830
+ pass
831
+ inflight = None
832
+ elif tag == "ALLDONE":
833
+ finished = True
834
+ return verdicts, inflight, finished
835
+
836
+
837
+ def _probe_candidates(candidates: list) -> Dict[int, Optional[str]]:
838
+ """Run every candidate pattern against the probe strings in a subprocess
839
+ with a hard time budget. A pattern that cannot finish is rejected — the
840
+ cost of a slow regex is paid on every archived output, forever, so only
841
+ patterns proven fast are loaded. Rejects conservatively when the probe
842
+ itself cannot run."""
843
+ verdicts: Dict[int, Optional[str]] = {}
844
+ pending = list(candidates)
845
+ for _attempt in range(_CUSTOM_PROBE_MAX_PASSES):
846
+ if not pending:
847
+ break
848
+ part, inflight, finished = _probe_pass(pending)
849
+ verdicts.update(part)
850
+ if inflight is not None:
851
+ verdicts[inflight] = ("safety probe timed out; pattern may "
852
+ "backtrack catastrophically")
853
+ if finished:
854
+ break
855
+ pending = [c for c in pending if c[0] not in verdicts]
856
+ for c in pending:
857
+ verdicts.setdefault(c[0], "safety probe did not complete")
858
+ return verdicts
859
+
860
+
861
+ def _run_safety_probe(state: _CustomPatternState, candidates: list) -> None:
862
+ """Move candidates that pass the probe into state.patterns."""
863
+ if not candidates:
864
+ return
865
+ verdicts = _cached_probe_verdicts(state.file_hash)
866
+ if verdicts is None:
867
+ verdicts = _probe_candidates(candidates)
868
+ _cache_probe_verdicts(state.file_hash, verdicts)
869
+ for index, label, _regex, _ic, pat in candidates:
870
+ err = verdicts.get(index)
871
+ if err:
872
+ _reject_entry(state, f"entry {index}: {err}")
873
+ else:
874
+ state.patterns.append((label, pat))
875
+
876
+
877
+ def _persist_custom_status(state: _CustomPatternState) -> None:
878
+ """Best-effort record of the last load under the runtime home, so the
879
+ outcome is inspectable even when the hook that hit it is long gone."""
880
+ if state.source is None and not state.failed:
881
+ return # feature not in use — don't create noise
882
+ d = _runtime_token_dir()
883
+ if d is None:
884
+ return
885
+ try:
886
+ d.mkdir(parents=True, exist_ok=True)
887
+ payload = {
888
+ "source": state.source,
889
+ "sha256": state.file_hash,
890
+ "active": not state.failed,
891
+ "failure": state.failure,
892
+ "patterns_loaded": len(state.patterns),
893
+ "entries_rejected": state.rejected,
894
+ "duplicates_skipped": state.duplicates,
895
+ "errors": list(state.errors)[:20],
896
+ "updated_at": datetime.now(timezone.utc).isoformat(),
897
+ }
898
+ tmp = d / (_CUSTOM_STATUS_FILENAME + ".tmp")
899
+ tmp.write_text(json.dumps(payload, indent=2), encoding="utf-8")
900
+ os.replace(tmp, d / _CUSTOM_STATUS_FILENAME)
901
+ except Exception:
902
+ pass
903
+
904
+
905
+ def _fail(state: _CustomPatternState, msg: str) -> _CustomPatternState:
906
+ state.failed = True
907
+ state.failure = msg
908
+ state.errors.append(msg)
909
+ return state
910
+
911
+
912
+ def _load_custom_patterns() -> _CustomPatternState:
913
+ state = _CustomPatternState()
914
+ try:
915
+ path, explicit, resolve_error = _resolve_custom_patterns_path()
916
+ if resolve_error is not None:
917
+ state.source = os.environ.get(CUSTOM_PATTERNS_FILE_ENV, "").strip() or None
918
+ return _fail(state, resolve_error)
919
+ if path is None:
920
+ return state
921
+ state.source = str(path)
922
+ try:
923
+ is_file = path.is_file()
924
+ size = path.stat().st_size if is_file else 0
925
+ except OSError as exc:
926
+ return _fail(state, f"could not stat file ({exc.__class__.__name__}: {exc})")
927
+ if not is_file:
928
+ if explicit:
929
+ return _fail(
930
+ state,
931
+ f"{CUSTOM_PATTERNS_FILE_ENV} points to a path that is "
932
+ "missing or not a regular file")
933
+ return state
934
+ if size > _CUSTOM_MAX_FILE_BYTES:
935
+ return _fail(state, "file is larger than 1 MB; not loaded")
936
+ try:
937
+ # utf-8-sig: Windows Notepad saves UTF-8 with a BOM.
938
+ raw_bytes = path.read_bytes()
939
+ except OSError as exc:
940
+ return _fail(state, f"could not read file ({exc.__class__.__name__}: {exc})")
941
+ state.file_hash = hashlib.sha256(raw_bytes).hexdigest()
942
+ try:
943
+ data = json.loads(raw_bytes.decode("utf-8-sig"))
944
+ except (ValueError, UnicodeDecodeError) as exc:
945
+ return _fail(state, f"could not parse file ({exc.__class__.__name__}: {exc})")
946
+ entries = data.get("patterns") if isinstance(data, dict) else None
947
+ if not isinstance(entries, list):
948
+ return _fail(state, 'top level must be an object with a "patterns" list')
949
+ if len(entries) > _CUSTOM_MAX_PATTERNS:
950
+ state.errors.append(
951
+ f"{len(entries)} patterns listed; only the first {_CUSTOM_MAX_PATTERNS} are used"
952
+ )
953
+ entries = entries[:_CUSTOM_MAX_PATTERNS]
954
+ seen: set = set()
955
+ candidates: list = []
956
+ for i, entry in enumerate(entries, 1):
957
+ _compile_custom_entry(entry, i, state, seen, candidates)
958
+ _run_safety_probe(state, candidates)
959
+ except Exception as exc: # pragma: no cover - defense in depth
960
+ _fail(state, f"unexpected error ({exc.__class__.__name__})")
961
+ return state
962
+
963
+
964
+ def _custom_state() -> _CustomPatternState:
965
+ global _CUSTOM_STATE
966
+ if _CUSTOM_STATE is None:
967
+ state = _load_custom_patterns()
968
+ _CUSTOM_STATE = state
969
+ _persist_custom_status(state)
970
+ for err in state.errors:
971
+ _warn(f"custom redaction patterns ({state.source}): {err}")
972
+ return _CUSTOM_STATE
973
+
974
+
975
+ def _raise_if_inactive(state: _CustomPatternState) -> None:
976
+ if state.failed:
977
+ raise RedactionConfigError(
978
+ f"custom credential redaction is inactive: {state.failure} "
979
+ f"(file: {state.source})"
980
+ )
981
+
982
+
983
+ def get_custom_patterns() -> List[Tuple[str, "re.Pattern[str]"]]:
984
+ """User-defined (label, compiled_regex) pairs, loaded once per process.
985
+
986
+ Raises RedactionConfigError when the configured file failed to load —
987
+ callers that persist text must not proceed unredacted."""
988
+ state = _custom_state()
989
+ _raise_if_inactive(state)
990
+ return list(state.patterns)
991
+
992
+
993
+ def custom_patterns_status() -> dict:
994
+ """Summary for diagnostics: count, labels, source path, problems. Never
995
+ raises — the security report reads this even when loading failed."""
996
+ state = _custom_state()
997
+ return {
998
+ "active": not state.failed,
999
+ "failure": state.failure,
1000
+ "count": len(state.patterns),
1001
+ "labels": [label for label, _ in state.patterns],
1002
+ "source": state.source,
1003
+ "sha256": state.file_hash,
1004
+ "errors": list(state.errors),
1005
+ "rejected": state.rejected,
1006
+ "duplicates_skipped": state.duplicates,
1007
+ }
1008
+
1009
+
1010
+ _WARNED_HASHES: set = set()
1011
+
1012
+
1013
+ def pop_redaction_warning() -> Optional[str]:
1014
+ """A one-time, user-facing warning that custom redaction is inactive.
1015
+
1016
+ Returns the message once per pattern-file content hash (persisted under
1017
+ the runtime home, so it survives across the short-lived hook processes),
1018
+ and None on repeat calls or when nothing is wrong. Hooks fold the returned
1019
+ text into their own ``{"systemMessage": ...}`` stdout envelope — a bare
1020
+ extra JSON line could break hosts that parse hook stdout as a single JSON
1021
+ document."""
1022
+ try:
1023
+ state = _custom_state()
1024
+ except Exception:
1025
+ return None
1026
+ if not state.failed:
1027
+ return None
1028
+ key = state.file_hash or hashlib.sha256(
1029
+ f"{state.source}|{state.failure}".encode("utf-8", errors="replace")
1030
+ ).hexdigest()
1031
+ if key in _WARNED_HASHES:
1032
+ return None
1033
+ try:
1034
+ d = _runtime_token_dir()
1035
+ flag = d / f"redact-warning-{key[:16]}.flag" if d is not None else None
1036
+ if flag is not None and flag.exists():
1037
+ _WARNED_HASHES.add(key)
1038
+ return None
1039
+ if d is not None:
1040
+ d.mkdir(parents=True, exist_ok=True)
1041
+ flag.write_text("warned\n", encoding="utf-8")
1042
+ except Exception:
1043
+ pass
1044
+ _WARNED_HASHES.add(key)
1045
+ return ("[Token Optimizer] Custom credential redaction is INACTIVE: "
1046
+ f"{state.failure} (file: {state.source}). Tool outputs and file "
1047
+ "contents are not being written to local caches until the pattern "
1048
+ "file is fixed or removed.")
1049
+
1050
+
1051
+ def reset_custom_patterns_cache() -> None:
1052
+ """Forget the loaded custom patterns (tests, long-lived processes)."""
1053
+ global _CUSTOM_STATE
1054
+ _CUSTOM_STATE = None
1055
+
1056
+
1057
+ def scan_for_credentials(text: str) -> List[Tuple[str, str, int]]:
1058
+ """Scan text for credentials. Returns [(label, matched_text, line_number), ...].
1059
+
1060
+ Matching is per line and mirrors redact_credentials ordering: custom
1061
+ patterns claim each line first, then the built-ins. Text already inside a
1062
+ ``[CREDENTIAL REDACTED: ...]`` placeholder is skipped for both, so a label
1063
+ or marker inside a placeholder never produces a phantom hit.
1064
+ """
1065
+ state = _custom_state()
1066
+ _raise_if_inactive(state)
1067
+ ordered = list(state.patterns) + CREDENTIAL_PATTERNS
1068
+ results = []
1069
+ for line_num, line in enumerate(text.splitlines()):
1070
+ # Split the line on placeholders and scan only the gaps.
1071
+ last = 0
1072
+ segments = []
1073
+ for m in _PLACEHOLDER_RE.finditer(line):
1074
+ if m.start() > last:
1075
+ segments.append(line[last:m.start()])
1076
+ # A forged "[CREDENTIAL REDACTED: <real secret>]" can hide a
1077
+ # credential in the label slot — scan the interior too. A hit whose
1078
+ # label equals the whole interior is the placeholder's own label
1079
+ # describing itself, never a phantom hit.
1080
+ interior = m.group(0)[len("[CREDENTIAL REDACTED: "):-1]
1081
+ for label, pat in ordered:
1082
+ m2 = pat.search(interior)
1083
+ if m2 and not (label == interior and m2.group() == interior):
1084
+ results.append((label, m2.group(), line_num))
1085
+ last = m.end()
1086
+ if last < len(line):
1087
+ segments.append(line[last:])
1088
+ for segment in segments:
1089
+ for label, pat in ordered:
1090
+ m = pat.search(segment)
1091
+ if m:
1092
+ results.append((label, m.group(), line_num))
1093
+ return results
1094
+
1095
+
1096
+ # M-16: regex to find already-redacted placeholders so they can be protected
1097
+ # from re-matching during a second redaction pass.
1098
+ # The interior is a label (60 characters at most, see _CUSTOM_MAX_LABEL_CHARS), so the
1099
+ # bound is generous. Unbounded, an unclosed "[CREDENTIAL REDACTED: " rescanned to the end
1100
+ # of the text from every start (quadratic). An over-long interior is not a placeholder:
1101
+ # it is scanned like any other text, so it cannot smuggle a secret.
1102
+ _PLACEHOLDER_RE = re.compile(r"\[CREDENTIAL REDACTED: [^\]]{1,256}\]")
1103
+ # The sentinel carries a per-call random nonce (see _new_placeholder_sentinel):
1104
+ # input that happens to contain a fixed sentinel string could otherwise be
1105
+ # swapped for a protected placeholder, shifting every placeholder after it.
1106
+ _PLACEHOLDER_SENTINEL_PREFIX = "\x00\x01REDACTED"
1107
+
1108
+
1109
+ def _new_placeholder_sentinel(text: str) -> str:
1110
+ while True:
1111
+ sentinel = f"{_PLACEHOLDER_SENTINEL_PREFIX}{secrets.token_hex(8)}\x00\x01"
1112
+ if sentinel not in text:
1113
+ return sentinel
1114
+
1115
+ # Per-pattern literal anchors (checked on a lowercased copy of the ORIGINAL
1116
+ # text, once, before the loop). A pattern whose anchors are all absent cannot
1117
+ # match, so its re.sub() is skipped. This is what makes clean-but-URL-bearing
1118
+ # output cheap: the global prefix scan above fires on any "https://", after
1119
+ # which the three M-12 patterns and the two URI patterns used to cost more
1120
+ # than everything else combined (measured 24ms -> 55ms per 10K realistic
1121
+ # lines on the first H-8 attempt). Substitutions only remove secrets and add
1122
+ # placeholders, never new anchors, so a pre-loop check stays sound.
1123
+ _PATTERN_ANCHORS = {
1124
+ # Only the patterns that are expensive to run (case-insensitive
1125
+ # alternations, or a scheme scan) are gated. The literal-prefix patterns
1126
+ # (AKIA..., ghp_..., xoxb-...) are already a fast scan in the regex engine
1127
+ # and cost less than an extra anchor check would.
1128
+ "Bearer token": ("bearer",),
1129
+ "Database URI": ("://",),
1130
+ "HTTP basic auth URL": ("://",),
1131
+ "URL auth param": ("=",),
1132
+ "MySQL password flag": ("mysql",),
1133
+ "Database env password": ("password=", "pwd=", "passwd=",
1134
+ "password='", "password=\"", "pwd='", "pwd=\"",
1135
+ "passwd='", "passwd=\""),
1136
+ "AWS secret key": ("aws_secret", "secret_access_key", "secretaccesskey"),
1137
+ "CLI password flag (long)": ("--password", "--passwd", "--passcode", "--auth-token"),
1138
+ "CLI password flag (short)": ("sshpass", "mariadb", "redis-cli"),
1139
+ }
1140
+
1141
+
1142
+ # ---------------------------------------------------------------------------
1143
+ # Generic secret assignment: NAME=value, NAME: value, "name": "value".
1144
+ #
1145
+ # The closed env-name list above only knows seven names. Anything else
1146
+ # (API_KEY=..., SECRET_KEY=..., a YAML "password: ...", a JSON "api_key": "...",
1147
+ # a quoted value with spaces) used to reach disk as typed. One rule covers the
1148
+ # class, and it is the SAME rule the three TypeScript engines run (openclaw,
1149
+ # pi, opencode redact.ts; keep the four in step): a name that contains KEY,
1150
+ # TOKEN, SECRET, PASSWORD, PASSWD, PWD or CREDENTIAL (optionally plural, and the
1151
+ # next character is not a letter, so "tokenizer" and "keyboard" are not names),
1152
+ # then "=" or ":", then a value. The NAME and the surrounding quotes stay, the
1153
+ # VALUE goes whole, quoted values with spaces included.
1154
+ #
1155
+ # Skipped values: an existing placeholder, a plain number up to 6 digits
1156
+ # (max_tokens=4096, tokens: 1200), true/false/yes/no/on/off/null/none/nil/
1157
+ # undefined, a type name (string, number, int...), a call or index (len(x),
1158
+ # os.environ['X'], Optional[str]), a $VAR / ${VAR} / $(cmd) reference, an empty
1159
+ # string, and the operators ==, => and :=.
1160
+ #
1161
+ # Before a COLON the keyword KEY only
1162
+ # counts inside a compound (api_key, x-api-key, SECRET_KEY, apiKey), so React
1163
+ # "key: item.id", JSON "key": "user_id", "primary key: id", "monkey: banana" and
1164
+ # "hotkey: ctrl+k" stay readable. With "=" bare KEY=value is still hidden.
1165
+ #
1166
+ # Two refinements the TS engines do not have, both kept because Python tests already
1167
+ # pin them: "key" inside another word (monkey=, turkey=, donkey=) is not a name unless
1168
+ # a known qualifier leads it (apikey, secretkey) or the K is capitalised (apiKey), and
1169
+ # a name that ends in a quantity or locator (token_type, token_count, KEY_FILE,
1170
+ # SECRET_NAME) holds no secret.
1171
+ #
1172
+ # The optional opening quote is taken atomically (lookahead plus backreference):
1173
+ # when a skip rule rejects the value after the quote, the engine must not retry
1174
+ # with the quote counted as part of the value (that would redact max_tokens="4096"
1175
+ # and re-wrap a placeholder). The TS engines backtrack there.
1176
+ #
1177
+ # Cost follows the keyword hits, not the words: str.find per keyword (C speed)
1178
+ # locates candidates and the regex is tried only there.
1179
+ # ---------------------------------------------------------------------------
1180
+ _ASSIGN_RE = re.compile(
1181
+ r"(?P<head>(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PWD|CREDENTIAL)(?:e?s)?(?![A-Za-z])"
1182
+ r"(?=(?P<tail>[A-Za-z0-9_.-]{0,80}))(?P=tail)[\"']?[ \t]*[=:][ \t]*(?=(?P<oq>[\"']?))(?P=oq))"
1183
+ r"(?![=>:])(?!(?<=\")\"|(?<=')')(?!\"\"|'')"
1184
+ r"(?!\x00)(?!\[(?:CREDENTIAL )?REDACTED)"
1185
+ r"(?!-?\d{1,6}(?:[.,]\d+)?[kKmM%]?[\"']?(?![\w$]))"
1186
+ r"(?!(?:true|false|yes|no|on|off|null|none|nil|undefined)[\"']?(?![\w$]))"
1187
+ r"(?!(?:string|number|boolean|bool|str|int|float|any|unknown|object|void)(?![\w$]))"
1188
+ r"(?![A-Za-z_][\w.]*[(\[])(?!\$[{(])(?!\$[A-Z_][A-Z0-9_]*(?![\w$]))"
1189
+ r"(?:(?<=\")[^\"\n]+(?=\")|(?<=')[^'\n]+(?=')|\S+)",
1190
+ re.I,
1191
+ )
1192
+ _ASSIGN_KEYWORDS = ("key", "token", "secret", "password", "passwd", "pwd", "credential")
1193
+ _ASSIGN_KEYWORD_RE = re.compile("|".join(_ASSIGN_KEYWORDS), re.I)
1194
+ _ASSIGN_PLACEHOLDER = "[CREDENTIAL REDACTED: Secret assignment]"
1195
+ _ASSIGN_QUALIFIERS = (
1196
+ "api", "access", "auth", "secret", "private", "public", "client", "session",
1197
+ "refresh", "bearer", "app", "db", "user", "admin", "root", "master", "signing",
1198
+ "encryption", "license", "ssh", "gpg", "jwt", "oauth", "service", "webhook",
1199
+ )
1200
+ _ASSIGN_LOCATOR_SUFFIX_RE = re.compile(
1201
+ r"[_.\-]*(?:path|file|dir|url|uri|name|id|count|limit|max|min|size|length|len|"
1202
+ r"ttl|expiry|expires|type|field|header|endpoint|regex|budget|label)s?", re.I)
1203
+
1204
+
1205
+ def _assign_key_before_colon_ok(text: str, start: int, head: str) -> bool:
1206
+ """KEY before ':' needs a compound: "_" or "-" in front, or a capital K after a lowercase letter."""
1207
+ sep_at = min((i for i in (head.find("="), head.find(":")) if i != -1), default=-1)
1208
+ if sep_at == -1 or head[sep_at] != ":":
1209
+ return True
1210
+ prev = text[start - 1] if start > 0 else ""
1211
+ return prev in ("_", "-") or (text[start] == "K" and prev.islower())
1212
+
1213
+
1214
+ def _next_keyword(text: str, low: Optional[str], pos: int, nxt: Dict[str, int]) -> Optional[Tuple[int, int]]:
1215
+ """Span of the next keyword at or after pos. With a lowercase twin of the text,
1216
+ str.find per keyword (each cached until passed); otherwise the regex."""
1217
+ if low is None:
1218
+ m = _ASSIGN_KEYWORD_RE.search(text, pos)
1219
+ return (m.start(), m.end()) if m else None
1220
+ best = -1
1221
+ best_kw = ""
1222
+ for kw in _ASSIGN_KEYWORDS:
1223
+ at = nxt[kw]
1224
+ if at != -1 and at < pos:
1225
+ at = nxt[kw] = low.find(kw, pos)
1226
+ if at != -1 and (best == -1 or at < best):
1227
+ best, best_kw = at, kw
1228
+ return None if best == -1 else (best, best + len(best_kw))
1229
+
1230
+
1231
+ def _redact_assignments(text: str) -> str:
1232
+ low = text.lower()
1233
+ if len(low) != len(text): # a few Unicode letters change length when lowered
1234
+ low = None
1235
+ nxt = {kw: (low.find(kw) if low is not None else -1) for kw in _ASSIGN_KEYWORDS}
1236
+ if low is not None and all(v == -1 for v in nxt.values()):
1237
+ return text
1238
+ out: List[str] = []
1239
+ copied = 0
1240
+ pos = 0
1241
+ n = len(text)
1242
+ while pos < n:
1243
+ span = _next_keyword(text, low, pos, nxt)
1244
+ if span is None:
1245
+ break
1246
+ start = span[0]
1247
+ pos = start + 1
1248
+ m = _ASSIGN_RE.match(text, start)
1249
+ if m is None:
1250
+ continue
1251
+ head = m.group("head")
1252
+ if _ASSIGN_LOCATOR_SUFFIX_RE.fullmatch(m.group("tail")):
1253
+ continue
1254
+ if text[start:start + 3].lower() == "key":
1255
+ if not _assign_key_before_colon_ok(text, start, head):
1256
+ continue
1257
+ if start > 0 and text[start - 1].isalpha() and text[start] != "K" \
1258
+ and not text[:start].lower().endswith(_ASSIGN_QUALIFIERS):
1259
+ continue
1260
+ out.append(text[copied:m.end("head")])
1261
+ out.append(_ASSIGN_PLACEHOLDER)
1262
+ copied = pos = m.end()
1263
+ if not out:
1264
+ return text
1265
+ out.append(text[copied:])
1266
+ return "".join(out)
1267
+
1268
+
1269
+ # ---------------------------------------------------------------------------
1270
+ # Command-syntax secrets: credentials that sit in a shell command's own grammar
1271
+ # rather than in a token shape (curl -u user:pass, --token VALUE, user:pass@host
1272
+ # with no scheme, echo SECRET | docker login, Windows net use / cmdkey).
1273
+ #
1274
+ # These rules are only safe on COMMAND text. In free output they would rewrite
1275
+ # prose ("mailto:me@x.com", "echo hi | wc"), so redact_credentials runs them
1276
+ # only when the caller says command=True. The same rules serve
1277
+ # deterministic_candidates (via scrub_command_syntax), so there is one copy.
1278
+ # ---------------------------------------------------------------------------
1279
+ _ARG = r"(?:\"[^\"]*\"|'[^']*'|[^\s\"']+)"
1280
+ # curl -u user:pass, --user user:pass, --proxy-user ... (value must contain a colon,
1281
+ # and not be a bare uid:gid like docker's `-u 1000:1000`)
1282
+ _USER_FLAG_RE = re.compile(r"(?<![\w-])(-u|-U|--user|--proxy-user)(\s+|=)?(" + _ARG + ")")
1283
+ _SECRET_FLAG_RE = re.compile(
1284
+ r"(?<![\w-])(--(?:password|passwd|pass|pwd|passphrase|secret|client-secret|token|auth-token|"
1285
+ r"access-token|api-key|apikey|api_key))(\s+|=)(?!-)(" + _ARG + ")",
1286
+ re.I,
1287
+ )
1288
+ # scheme://user:pass@host (any scheme: ftp, ssh, amqp, https...). Greedy to the last
1289
+ # `@` before the path, so a password containing `@` is covered whole.
1290
+ _URL_USERINFO_RE = re.compile(r"(://)[^\s/\"':@]+:[^\s/\"']*@")
1291
+ # user:pass@host with no scheme (rsync, scp, git remotes). Docker digest refs
1292
+ # (image:tag@sha256:...) and Windows paths are not credentials.
1293
+ _BARE_USERINFO_RE = re.compile(r"(?<![\w/@.:+\\-])[\w.+-]+:[^\s/\\@\"':]+@(?!sha\d+:)(?=[A-Za-z0-9])")
1294
+ # echo/printf <anything> | cmd : the piped argument is, in practice, the secret that
1295
+ # the next command reads from stdin. Flags (-n, -e) survive; quoted args may hold `|`.
1296
+ _PIPED_ECHO_RE = re.compile(
1297
+ r"(?<![\w/.-])(echo|printf)(\s+(?:-[A-Za-z]+\s+)*)"
1298
+ r"((?:\"[^\"]*\"|'[^']*'|[^|;&\n\"'])+?)(\s*)\|(?!\|)"
1299
+ )
1300
+ # Windows: `net use [dev:] \\srv\share [password] [/user:name]` and `... /user:name password`,
1301
+ # `cmdkey /pass:...`. `*` (prompt for the password) is not a secret.
1302
+ _NET_USE_PW_BEFORE_RE = re.compile(r"(\bnet\s+use\s+(?:[A-Za-z]:\s+|\*\s+)?\\\\\S+\s+)(?![/*-])(\S+)(?=\s|$)", re.I)
1303
+ _NET_USE_PW_AFTER_RE = re.compile(r"(\bnet\s+use\b[^|;&\n]*?/user:\S+\s+)(?![/*-])(\S+)", re.I)
1304
+ _WIN_USER_RE = re.compile(r"(/user:)\S+", re.I)
1305
+ _WIN_PASS_RE = re.compile(r"(/(?:pass|password|passwd|pwd):)\S+", re.I)
1306
+
1307
+
1308
+ class CommandMarks:
1309
+ """What each command-syntax rule writes in place of the secret."""
1310
+ __slots__ = ("creds", "arg", "secret", "user")
1311
+
1312
+ def __init__(self, creds: str, arg: str, secret: str, user: str):
1313
+ self.creds, self.arg, self.secret, self.user = creds, arg, secret, user
1314
+
1315
+
1316
+ # Redaction output: the standard labeled placeholder.
1317
+ _REDACT_MARKS = CommandMarks(
1318
+ creds="[CREDENTIAL REDACTED: user:password]",
1319
+ arg="[CREDENTIAL REDACTED: piped value]",
1320
+ secret="[CREDENTIAL REDACTED: command secret]",
1321
+ user="[CREDENTIAL REDACTED: Windows user]",
1322
+ )
1323
+
1324
+
1325
+ def scrub_command_syntax(text: str, marks: "CommandMarks" = _REDACT_MARKS) -> str:
1326
+ """Blank credentials that live in a command's syntax (see block comment above)."""
1327
+ def _user_flag_sub(m: "re.Match[str]") -> str:
1328
+ value = m.group(3).strip("\"'")
1329
+ if ":" not in value or re.fullmatch(r"\d+:\d+", value):
1330
+ return m.group(0)
1331
+ return f"{m.group(1)}{m.group(2) or ''}{marks.creds}"
1332
+
1333
+ text = _URL_USERINFO_RE.sub(lambda m: f"{m.group(1)}{marks.creds}@", text)
1334
+ text = _PIPED_ECHO_RE.sub(lambda m: f"{m.group(1)}{m.group(2)}{marks.arg}{m.group(4)}|", text)
1335
+ text = _USER_FLAG_RE.sub(_user_flag_sub, text)
1336
+ text = _SECRET_FLAG_RE.sub(lambda m: f"{m.group(1)}{m.group(2)}{marks.secret}", text)
1337
+ text = _NET_USE_PW_BEFORE_RE.sub(lambda m: f"{m.group(1)}{marks.secret}", text)
1338
+ text = _NET_USE_PW_AFTER_RE.sub(lambda m: f"{m.group(1)}{marks.secret}", text)
1339
+ text = _WIN_PASS_RE.sub(lambda m: f"{m.group(1)}{marks.secret}", text)
1340
+ text = _WIN_USER_RE.sub(lambda m: f"{m.group(1)}{marks.user}", text)
1341
+ text = _BARE_USERINFO_RE.sub(lambda m: f"{marks.creds}@", text)
1342
+ return text
1343
+
1344
+
1345
+ def _sub_with_placeholder(pat: "re.Pattern[str]", label: str, text: str) -> str:
1346
+ # A function replacement, not a template string: a custom label is user
1347
+ # text and must never be interpreted as a backreference ("\\1", "\\g<0>").
1348
+ placeholder = f"[CREDENTIAL REDACTED: {label}]"
1349
+ if "keep" in pat.groupindex:
1350
+ def _repl(m):
1351
+ if m.group("keep") is None:
1352
+ if m.start() == m.end():
1353
+ return m.group(0)
1354
+ return placeholder
1355
+ ks, ke = m.span("keep")
1356
+ # The kept group covers the whole match: nothing to redact.
1357
+ if ks == m.start() and ke == m.end():
1358
+ return m.group(0)
1359
+ # Keep the group where it sits; replace what comes before and/or
1360
+ # after it. Built-in patterns always put `keep` first, so for them
1361
+ # this is exactly "<keep>[CREDENTIAL REDACTED: label]".
1362
+ return ((placeholder if ks > m.start() else "")
1363
+ + m.group("keep")
1364
+ + (placeholder if ke < m.end() else ""))
1365
+ else:
1366
+ def _repl(m):
1367
+ # Zero-width matches (\b, lookaheads) would otherwise sprinkle
1368
+ # placeholders between characters without removing anything.
1369
+ if m.start() == m.end():
1370
+ return m.group(0)
1371
+ return placeholder
1372
+ return pat.sub(_repl, text)
1373
+
1374
+
1375
+ def redact_credentials(text: str, *, command: bool = False) -> str:
1376
+ """Replace credential matches with [CREDENTIAL REDACTED: <type>] placeholders.
1377
+
1378
+ A pattern may define a named `keep` group for a non-secret prefix that should
1379
+ survive redaction (e.g. the "?token=" part of a URL auth parameter); only the
1380
+ value after it is replaced. Patterns without a `keep` group redact the whole
1381
+ match, unchanged.
1382
+
1383
+ H-8: uses a fast prefix scan to skip all re.sub() calls when the text
1384
+ contains no credential prefixes (the common case for clean command output).
1385
+ This makes clean text O(n) with a tiny constant instead of O(n × 28) regex
1386
+ passes. Text with credentials still gets the full sequential redaction,
1387
+ preserving correctness and the existing two-phase ordering (standalone
1388
+ credentials before URL auth params, so the negative lookahead works).
1389
+
1390
+ Custom patterns run BEFORE the built-ins, on the segments between
1391
+ pre-existing placeholders. A custom shape wins over a built-in on overlap —
1392
+ that precedence is deliberate, so an org pattern can claim a whole
1393
+ composite fragment (e.g. "MEDX-123456-<jwt>") instead of leaving a readable
1394
+ prefix beside a built-in placeholder.
1395
+
1396
+ M-16: protects already-redacted [CREDENTIAL REDACTED: ...] placeholders
1397
+ from re-matching by replacing them with a sentinel before redaction and
1398
+ restoring them after. This fixes the Bearer pattern re-matching "Bearer
1399
+ token" inside its own placeholder, which nested placeholders on re-runs.
1400
+
1401
+ command=True marks the text as a shell command (not output or prose) and also
1402
+ runs the command-syntax rules: curl -u user:pass, --token VALUE, scheme-less
1403
+ user:pass@host, echo SECRET | cmd, Windows net use. Every writer that persists
1404
+ command text passes it.
1405
+
1406
+ Raises RedactionConfigError when a configured custom pattern file failed
1407
+ to load — callers persisting the result must treat that as "do not write".
1408
+ """
1409
+ state = _custom_state()
1410
+ # A configured-but-broken pattern file must not silently degrade to
1411
+ # built-ins only: the caller is about to persist this text, and the user's
1412
+ # own secret shapes would leak. Fail closed — the writer skips the write.
1413
+ _raise_if_inactive(state)
1414
+
1415
+ # Custom patterns run BEFORE the built-ins, but only on the text between
1416
+ # pre-existing placeholders (_redact_custom splits on _PLACEHOLDER_RE, so
1417
+ # an existing "[CREDENTIAL REDACTED: ...]" can never be re-matched or
1418
+ # corrupted). Running first is what lets an org pattern claim a fragment
1419
+ # like "MEDX-123456-<jwt>" whole instead of leaving the id prefix behind.
1420
+ if state.patterns:
1421
+ text = _redact_custom(text, state.patterns)
1422
+
1423
+ # M-16: protect placeholders from re-matching — both the ones that were in
1424
+ # the input and the ones the custom patterns just inserted. The interior is
1425
+ # a LABEL slot, not a payload slot: a forged "[CREDENTIAL REDACTED: <real
1426
+ # secret>]" used to ride the sentinel protection verbatim into every
1427
+ # persistence boundary. Scan each interior and replace a credential match
1428
+ # with its label, so a legit placeholder survives unchanged (the only
1429
+ # self-matching label is "Bearer token", which substitutes to itself) while
1430
+ # a smuggled secret collapses to e.g. "GitHub PAT classic".
1431
+ placeholders = []
1432
+ ordered = list(state.patterns) + CREDENTIAL_PATTERNS
1433
+ sentinel = _new_placeholder_sentinel(text)
1434
+
1435
+ def _clean_interior(ph):
1436
+ interior = ph[len("[CREDENTIAL REDACTED: "):-1]
1437
+ if _text_may_contain_credentials(interior):
1438
+ for label, pat in ordered:
1439
+ interior = pat.sub(
1440
+ lambda m, lbl=label: (
1441
+ m.group(0) if m.start() == m.end() else lbl
1442
+ ),
1443
+ interior,
1444
+ )
1445
+ return "[CREDENTIAL REDACTED: " + interior + "]"
1446
+
1447
+ def _save_placeholder(m):
1448
+ placeholders.append(_clean_interior(m.group(0)))
1449
+ return sentinel
1450
+ if "[CREDENTIAL REDACTED:" in text:
1451
+ text = _PLACEHOLDER_RE.sub(_save_placeholder, text)
1452
+
1453
+ # H-8: fast path — skip all regex work if no credential prefix is present.
1454
+ lowered = text.lower()
1455
+ for label, pat in CREDENTIAL_PATTERNS:
1456
+ anchors = _PATTERN_ANCHORS.get(label)
1457
+ if anchors and not any(a in lowered for a in anchors):
1458
+ continue
1459
+ text = _sub_with_placeholder(pat, label, text)
1460
+
1461
+ # Command-syntax shapes (command text only), then generic NAME=value /
1462
+ # NAME: value secrets. Both run after the specific shapes so a labelled
1463
+ # placeholder from a rule above is never overwritten.
1464
+ if command:
1465
+ text = scrub_command_syntax(text)
1466
+ text = _redact_assignments(text)
1467
+
1468
+ # M-16: restore protected placeholders.
1469
+ for ph in placeholders:
1470
+ text = text.replace(sentinel, ph, 1)
1471
+ return text
1472
+
1473
+
1474
+ def _redact_custom(text: str, custom: List[Tuple[str, "re.Pattern[str]"]]) -> str:
1475
+ for label, pat in custom:
1476
+ parts = []
1477
+ last = 0
1478
+ for m in _PLACEHOLDER_RE.finditer(text):
1479
+ parts.append(_sub_with_placeholder(pat, label, text[last:m.start()]))
1480
+ parts.append(m.group(0))
1481
+ last = m.end()
1482
+ parts.append(_sub_with_placeholder(pat, label, text[last:]))
1483
+ text = "".join(parts)
1484
+ return text
1485
+
1486
+
1487
+ def redact_credentials_deep(value):
1488
+ """Apply redact_credentials to every string in a nested structure.
1489
+
1490
+ One pass over a whole checkpoint/handoff state so a NEW string field can
1491
+ never bypass the credential pass — the failure mode the per-field
1492
+ redactors had (open_questions, todos, agent descriptions and paths were
1493
+ persisted verbatim because nobody listed them).
1494
+
1495
+ Rebuilds dicts, lists, tuples and sets preserving container type; keys
1496
+ are redacted too (a key derived from transcript text is attacker
1497
+ content). Non-strings pass through unchanged. Returns a new structure;
1498
+ the input is not mutated.
1499
+
1500
+ Raises RedactionConfigError exactly like redact_credentials — callers
1501
+ persisting the result must treat that as "do not write".
1502
+ """
1503
+ if isinstance(value, str):
1504
+ return redact_credentials(value)
1505
+ if isinstance(value, dict):
1506
+ return {
1507
+ redact_credentials_deep(k): redact_credentials_deep(v)
1508
+ for k, v in value.items()
1509
+ }
1510
+ if isinstance(value, (list, tuple)):
1511
+ return type(value)(redact_credentials_deep(v) for v in value)
1512
+ if isinstance(value, (set, frozenset)):
1513
+ return type(value)(redact_credentials_deep(v) for v in value)
1514
+ return value