tokensafe 2.7.0 → 2.7.2

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 (44) hide show
  1. package/bin/tokensafe +1 -1
  2. package/extensions/cursor-tokensafe/extension.js +21 -8
  3. package/hooks/claude_code_hook.py +13 -5
  4. package/hooks/cursor_hook.py +7 -4
  5. package/hooks/post_tool_use.py +24 -6
  6. package/hooks/pre_invocation.py +40 -27
  7. package/hooks/pre_tool_use.py +85 -83
  8. package/hooks/session_start.py +8 -4
  9. package/hooks/stop_hook.py +7 -4
  10. package/package.json +1 -1
  11. package/plugin.json +1 -1
  12. package/server.json +3 -3
  13. package/src/agent_firewall.py +38 -21
  14. package/src/cache_normalizer.py +39 -10
  15. package/src/cli.py +139 -83
  16. package/src/command_sanitizer.py +248 -136
  17. package/src/compactor.py +55 -25
  18. package/src/dashboard.py +17 -10
  19. package/src/deepseek_distiller.py +26 -17
  20. package/src/dependency_prefetcher.py +65 -40
  21. package/src/diff_slicer.py +23 -17
  22. package/src/distiller.py +45 -17
  23. package/src/distiller_cache.py +80 -48
  24. package/src/environment_auditor.py +34 -12
  25. package/src/governor.py +83 -26
  26. package/src/graph_engine.py +1 -1
  27. package/src/guard.py +316 -132
  28. package/src/history_compactor.py +57 -26
  29. package/src/installer.py +174 -131
  30. package/src/license_manager.py +12 -9
  31. package/src/loop_detector.py +68 -29
  32. package/src/mcp_server.py +206 -65
  33. package/src/metrics.py +141 -54
  34. package/src/paths.py +32 -6
  35. package/src/proxy.py +121 -52
  36. package/src/scoped_search.py +18 -6
  37. package/src/secret_redactor.py +78 -59
  38. package/src/slicer.py +15 -3
  39. package/src/team_cache.py +89 -16
  40. package/src/telemetry_sync.py +110 -39
  41. package/src/tokenizer.py +24 -13
  42. package/src/treesitter_backend.py +1 -0
  43. package/src/version_checker.py +67 -32
  44. package/src/weekly_digest.py +6 -3
package/src/guard.py CHANGED
@@ -13,10 +13,14 @@ Protects local workspaces and repository integrity by intercepting dangerous ope
13
13
 
14
14
  import os
15
15
  import re
16
+ import shlex
16
17
  import fnmatch
17
18
  import subprocess
18
19
  from typing import Tuple, Optional, Dict, Any, List, NamedTuple
19
20
  from src.secret_redactor import SecretRedactor
21
+ from src.command_sanitizer import CommandSanitizer
22
+
23
+ _TOKENSAFE_SRC_DIR = os.path.dirname(os.path.abspath(__file__))
20
24
 
21
25
  class GuardResult(NamedTuple):
22
26
  blocked: bool
@@ -50,6 +54,16 @@ class TokenSafeGuard:
50
54
  "services", "controllers", "models", "internal", "pkg", "hooks"
51
55
  )
52
56
 
57
+ _TEST_PATH_RE = re.compile(
58
+ r"(?:^|/)(?:__tests__|__mocks__|tests?|specs?|mocks?|fixtures?)(?:/|$)"
59
+ r"|(?:^|/)(?:test_[^/]+|mock_[^/]+|[^/]+_test\.[^/]+|[^/]+_spec\.[^/]+|[^/]+\.test\.[^/]+|[^/]+\.spec\.[^/]+|conftest\.py)$",
60
+ re.IGNORECASE,
61
+ )
62
+ _CODE_DIR_RE = re.compile(
63
+ r"(?:^|[\s/'\"=])(?:" + "|".join(CODE_DIRS) + r")(?:/|$|[\s'\"])"
64
+ )
65
+ _TEMPLATE_EXAMPLES = (".example", ".sample", ".template")
66
+
53
67
  @classmethod
54
68
  def is_doc_file(cls, file_path: str) -> bool:
55
69
  """Determines if the targeted file is documentation or non-executable text."""
@@ -59,11 +73,22 @@ class TokenSafeGuard:
59
73
 
60
74
  @classmethod
61
75
  def is_test_file(cls, file_path: str) -> bool:
62
- """Determines if the targeted file is part of a test suite or mock fixture."""
76
+ """Determines if the targeted file is part of a test suite or mock fixture using segment/filename boundaries."""
63
77
  if not file_path:
64
78
  return False
65
- p = file_path.lower()
66
- return any(part in p for part in ("test", "mock", "fixture", "spec", "__tests__"))
79
+ norm = file_path.replace("\\", "/")
80
+ return bool(cls._TEST_PATH_RE.search(norm))
81
+
82
+ @classmethod
83
+ def is_scanner_file(cls, file_path: str) -> bool:
84
+ """True only for TokenSafe's own guard/redactor modules (never arbitrary app/guard.py files)."""
85
+ if not file_path:
86
+ return False
87
+ abs_p = os.path.abspath(file_path)
88
+ return abs_p in (
89
+ os.path.join(_TOKENSAFE_SRC_DIR, "guard.py"),
90
+ os.path.join(_TOKENSAFE_SRC_DIR, "secret_redactor.py"),
91
+ )
67
92
 
68
93
  @classmethod
69
94
  def inspect_file_write(cls, file_path: str, code_snippet: str) -> GuardResult:
@@ -76,7 +101,7 @@ class TokenSafeGuard:
76
101
 
77
102
  is_test = cls.is_test_file(file_path)
78
103
  is_doc = cls.is_doc_file(file_path)
79
- is_scanner = bool(file_path and os.path.basename(file_path) in ("guard.py", "secret_redactor.py"))
104
+ is_scanner = cls.is_scanner_file(file_path)
80
105
  skip_code_checks = is_test or is_doc or is_scanner
81
106
 
82
107
  # 1. Secret & Private Key Fallback Guard
@@ -90,20 +115,20 @@ class TokenSafeGuard:
90
115
 
91
116
  # 2. Insecure SSL/TLS Verification Bypass Detection
92
117
  if not skip_code_checks:
93
- # Python: verify=False in requests, httpx, urllib3, aiohttp
94
- if re.search(r"\bverify\s*=\s*False\b", code_snippet):
118
+ # Python: verify=False (requests, httpx, urllib3) or ssl=False / unverified context
119
+ if re.search(r"""(?:\bverify\s*=\s*False\b|\bssl\s*=\s*False\b|ssl\._create_unverified_context\s*\()""", code_snippet):
95
120
  return GuardResult(
96
121
  blocked=True,
97
122
  check_name="TLS_VERIFY_BYPASS",
98
123
  reason=(
99
- f"Insecure SSL/TLS verification bypass detected ('verify=False') in "
124
+ f"Insecure SSL/TLS verification bypass detected in "
100
125
  f"'{os.path.basename(file_path) if file_path else 'code'}'. "
101
126
  f"Disabling TLS certificate checks exposes connections to Man-in-the-Middle (MitM) attacks."
102
127
  )
103
128
  )
104
129
 
105
130
  # Node.js: NODE_TLS_REJECT_UNAUTHORIZED = '0' or rejectUnauthorized: false
106
- if re.search(r"""(?:NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['"]0['"]|\brejectUnauthorized\s*:\s*false\b)""", code_snippet):
131
+ if re.search(r"""(?:NODE_TLS_REJECT_UNAUTHORIZED(?:\s*["'\]]?\s*=\s*|["']?\s*:\s*)['"]0['"]|\b["']?rejectUnauthorized["']?\s*:\s*false\b)""", code_snippet):
107
132
  return GuardResult(
108
133
  blocked=True,
109
134
  check_name="TLS_VERIFY_BYPASS",
@@ -116,9 +141,11 @@ class TokenSafeGuard:
116
141
 
117
142
  # 3. Raw SQL Injection in Query Execution
118
143
  if not skip_code_checks:
119
- # Python: cursor.execute(f"...") or conn.execute(f"...")
144
+ _db_clients = r"(?:cursor|cur|conn|connection|db|pool|client|knex|session|sequelize|prisma)"
145
+ _sql_kw = r"(?:\s*SELECT|\s*INSERT|\s*UPDATE|\s*DELETE|\s*DROP|\s*ALTER|\s*TRUNCATE)"
146
+ # Python: f-string or + concatenation inside .execute()
120
147
  py_fstring_sql = re.search(
121
- r"""\b(?:cursor|conn|connection|db)\.execute\s*\(\s*f["'](?:\s*SELECT|\s*INSERT|\s*UPDATE|\s*DELETE|\s*DROP|\s*ALTER)""",
148
+ rf"""\b{_db_clients}\.execute\s*\(\s*(?:f["']{_sql_kw}|["']{_sql_kw}[^"']*["']\s*\+)""",
122
149
  code_snippet,
123
150
  re.IGNORECASE
124
151
  )
@@ -127,7 +154,7 @@ class TokenSafeGuard:
127
154
  blocked=True,
128
155
  check_name="SQL_INJECTION",
129
156
  reason=(
130
- f"Potential SQL injection detected: f-string interpolation inside query execution in "
157
+ f"Potential SQL injection detected: dynamic string interpolation inside query execution in "
131
158
  f"'{os.path.basename(file_path) if file_path else 'code'}'. "
132
159
  f"Use parameterized queries with bound placeholders ('?' or '%s') instead of dynamic string formatting."
133
160
  )
@@ -135,7 +162,7 @@ class TokenSafeGuard:
135
162
 
136
163
  # Python: .execute("... %s ..." % (...)) or .format(...)
137
164
  py_format_sql = re.search(
138
- r"""\b(?:cursor|conn|connection|db)\.execute\s*\(\s*["'](?:\s*SELECT|\s*INSERT|\s*UPDATE|\s*DELETE)[^"']+['"]\s*(?:%|\.format\s*\()""",
165
+ rf"""\b{_db_clients}\.execute\s*\(\s*["']{_sql_kw}[^"']+['"]\s*(?:%|\.format\s*\()""",
139
166
  code_snippet,
140
167
  re.IGNORECASE
141
168
  )
@@ -150,9 +177,9 @@ class TokenSafeGuard:
150
177
  )
151
178
  )
152
179
 
153
- # JS/TS: db.query(`SELECT ... ${var}`) or pool.query(`... ${var}`)
180
+ # JS/TS: db.query(`SELECT ... ${var}`) or raw `+ var`
154
181
  js_template_sql = re.search(
155
- r"""\b(?:db|pool|client|connection|knex)\.(?:query|execute|raw)\s*\(\s*`(?:\s*SELECT|\s*INSERT|\s*UPDATE|\s*DELETE|\s*DROP)[^`]*\$\{[^}]+\}""",
182
+ rf"""\b{_db_clients}\.(?:query|execute|raw|\$queryRawUnsafe|\$executeRawUnsafe)\s*\(\s*(?:`{_sql_kw}[^`]*\$\{{[^}}]+\}}|["']{_sql_kw}[^"']*["']\s*\+)""",
156
183
  code_snippet,
157
184
  re.IGNORECASE
158
185
  )
@@ -161,9 +188,9 @@ class TokenSafeGuard:
161
188
  blocked=True,
162
189
  check_name="SQL_INJECTION",
163
190
  reason=(
164
- f"Potential SQL injection detected: template literal interpolation '${{...}}' inside query execution in "
191
+ f"Potential SQL injection detected: template literal or concatenation inside query execution in "
165
192
  f"'{os.path.basename(file_path) if file_path else 'code'}'. "
166
- f"Use parameterized queries with bound placeholders ('$1', '$2' or '?') instead of string template interpolation."
193
+ f"Use parameterized queries with bound placeholders ('$1', '$2' or '?') instead of string interpolation."
167
194
  )
168
195
  )
169
196
 
@@ -192,6 +219,46 @@ class TokenSafeGuard:
192
219
 
193
220
  return GuardResult(blocked=False)
194
221
 
222
+ @classmethod
223
+ def _tokenize_stage(cls, stage: str) -> List[str]:
224
+ try:
225
+ return shlex.split(stage)
226
+ except ValueError:
227
+ return stage.split()
228
+
229
+ @classmethod
230
+ def _stage_cmd_tokens(cls, stage: str) -> Tuple[str, List[str]]:
231
+ tokens = cls._tokenize_stage(stage)
232
+ i = 0
233
+ while i < len(tokens):
234
+ tok = tokens[i]
235
+ if tok in ("sudo", "env", "command", "time", "nohup"):
236
+ i += 1
237
+ continue
238
+ if "=" in tok and not tok.startswith("-") and tok.split("=", 1)[0].replace("_", "").isalnum():
239
+ i += 1
240
+ continue
241
+ break
242
+ if i >= len(tokens):
243
+ return "", []
244
+ return os.path.basename(tokens[i]), tokens[i + 1 :]
245
+
246
+ @classmethod
247
+ def _is_sensitive_filename(cls, path_arg: str) -> bool:
248
+ base = os.path.basename(path_arg.rstrip("/\\"))
249
+ if not base:
250
+ return False
251
+ low = base.lower()
252
+ if any(low.endswith(suf) for suf in cls._TEMPLATE_EXAMPLES):
253
+ return False
254
+ if low in cls.SENSITIVE_GIT_FILES:
255
+ return True
256
+ if low.startswith(".env."):
257
+ return True
258
+ if low.endswith((".pem", ".key")):
259
+ return True
260
+ return False
261
+
195
262
  @classmethod
196
263
  def inspect_command(cls, command: str, cwd: str = "") -> GuardResult:
197
264
  """
@@ -202,57 +269,119 @@ class TokenSafeGuard:
202
269
  return GuardResult(blocked=False)
203
270
 
204
271
  cmd = command.strip()
272
+ stages = [st for _, st in CommandSanitizer.split_stages(cmd) if st]
205
273
 
206
- # 1. Destructive Unbounded File Deletion (rm -rf / or rm -rf ~ or rm -rf *)
207
- rm_dangerous = re.search(
208
- r"""\brm\s+(?:-[a-zA-Z]*[rf][a-zA-Z]*\s+)+(?:/|~|\$HOME|\.\.|\.|\.\/|\*|/\*|\.\/\*)(?:\s|$|;|&|\|)""",
209
- cmd
210
- )
211
- if rm_dangerous or re.search(r"""\brm\s+-[a-zA-Z]*[rf][a-zA-Z]*\s+--no-preserve-root\b""", cmd):
212
- return GuardResult(
213
- blocked=True,
214
- check_name="DESTRUCTIVE_RM",
215
- reason=(
216
- f"Destructive unbounded file deletion blocked: '{cmd}'. "
217
- f"Running 'rm -rf' on root, home, parent directories, or wildcards poses catastrophic data loss risk."
218
- )
219
- )
220
-
221
- # 2. Git Staging Protection for Sensitive Files (.env, private keys)
222
- # Explicit git add of sensitive file
223
- git_add_explicit = re.search(
224
- r"""\bgit\s+add\s+(?:.*?\s+)?(?:['"]?(?:\.env|\.env\.[a-zA-Z0-9_-]+|[^'"]*\.pem|[^'"]*\.key|id_rsa|id_ed25519|credentials\.json)['"]?)(?:\s|$|;|&|\|)""",
225
- cmd,
226
- re.IGNORECASE
227
- )
228
- if git_add_explicit:
229
- return GuardResult(
230
- blocked=True,
231
- check_name="GIT_SECRET_STAGING",
232
- reason=(
233
- f"Blocked staging of sensitive credential file into git repository: '{cmd}'. "
234
- f"Environment files and private keys must be added to .gitignore and never committed to source control."
235
- )
236
- )
237
-
238
- # Catch blanket 'git add .' or 'git add -A' when sensitive files exist in directory
239
- if re.search(r"""\bgit\s+(?:add\s+(?:\.|\-A|\*)|commit\s+-[a-zA-Z]*a)""", cmd):
240
- target_dir = cwd or os.getcwd()
241
- sensitive = cls._find_unignored_sensitive_file(target_dir)
242
- if sensitive:
274
+ # 1. Destructive Unbounded File Deletion (rm -rf /, rm -rf ~, rm -rf *, etc.)
275
+ _DANGEROUS_RM_TARGETS = {"", "/", "~", "~/", "~/*", "$HOME", "${HOME}", "..", ".", "./", "*", "/*", "./*"}
276
+ for stage in stages:
277
+ cmd_tok, cmd_args = cls._stage_cmd_tokens(stage)
278
+ if cmd_tok != "rm":
279
+ continue
280
+ has_rf = False
281
+ no_preserve_root = False
282
+ targets: List[str] = []
283
+ past_ddash = False
284
+ for a in cmd_args:
285
+ if a == "--" and not past_ddash:
286
+ past_ddash = True
287
+ continue
288
+ if not past_ddash and a.startswith("-"):
289
+ if a == "--no-preserve-root":
290
+ no_preserve_root = True
291
+ elif a in ("--recursive", "--force"):
292
+ has_rf = True
293
+ elif not a.startswith("--") and ("r" in a or "f" in a or "R" in a):
294
+ has_rf = True
295
+ else:
296
+ targets.append(a)
297
+ if no_preserve_root and has_rf:
243
298
  return GuardResult(
244
299
  blocked=True,
245
- check_name="GIT_SECRET_STAGING",
300
+ check_name="DESTRUCTIVE_RM",
246
301
  reason=(
247
- f"Blocked blanket git staging: '{cmd}'. "
248
- f"Unignored sensitive file '{sensitive}' detected in working tree. "
249
- f"Add '{sensitive}' to .gitignore or stage files explicitly to prevent credential leaks into git."
302
+ f"Destructive unbounded file deletion blocked: '{cmd}'. "
303
+ f"Running 'rm -rf' with --no-preserve-root poses catastrophic data loss risk."
250
304
  )
251
305
  )
306
+ if has_rf:
307
+ for tgt in targets:
308
+ norm_tgt = tgt.rstrip("/") if tgt != "/" else "/"
309
+ if tgt in _DANGEROUS_RM_TARGETS or norm_tgt in ("/", "~", "$HOME", "${HOME}", ".", "..", "*"):
310
+ return GuardResult(
311
+ blocked=True,
312
+ check_name="DESTRUCTIVE_RM",
313
+ reason=(
314
+ f"Destructive unbounded file deletion blocked: '{cmd}'. "
315
+ f"Running 'rm -rf' on root, home, parent directories, or wildcards poses catastrophic data loss risk."
316
+ )
317
+ )
318
+
319
+ # 2. Git Staging Protection for Sensitive Files (.env, private keys)
320
+ for stage in stages:
321
+ cmd_tok, cmd_args = cls._stage_cmd_tokens(stage)
322
+ if cmd_tok != "git":
323
+ continue
324
+ git_dir = cwd or os.getcwd()
325
+ sub_idx = 0
326
+ while sub_idx < len(cmd_args):
327
+ a = cmd_args[sub_idx]
328
+ if a == "-C" and sub_idx + 1 < len(cmd_args):
329
+ cand_dir = cmd_args[sub_idx + 1]
330
+ git_dir = cand_dir if os.path.isabs(cand_dir) else os.path.abspath(os.path.join(git_dir, cand_dir))
331
+ sub_idx += 2
332
+ elif a in ("-c", "--git-dir", "--work-tree") and sub_idx + 1 < len(cmd_args):
333
+ sub_idx += 2
334
+ elif a.startswith("-"):
335
+ sub_idx += 1
336
+ else:
337
+ break
338
+ subcmd = cmd_args[sub_idx] if sub_idx < len(cmd_args) else ""
339
+ sub_args = cmd_args[sub_idx + 1 :]
340
+
341
+ if subcmd == "add":
342
+ blanket = False
343
+ for a in sub_args:
344
+ if a in ("--all", "-A", ".", "./", "*"):
345
+ blanket = True
346
+ elif not a.startswith("-") and cls._is_sensitive_filename(a):
347
+ return GuardResult(
348
+ blocked=True,
349
+ check_name="GIT_SECRET_STAGING",
350
+ reason=(
351
+ f"Blocked staging of sensitive credential file into git repository: '{cmd}'. "
352
+ f"Environment files and private keys must be added to .gitignore and never committed to source control."
353
+ )
354
+ )
355
+ if blanket:
356
+ sensitive = cls._find_unignored_sensitive_file(git_dir)
357
+ if sensitive:
358
+ return GuardResult(
359
+ blocked=True,
360
+ check_name="GIT_SECRET_STAGING",
361
+ reason=(
362
+ f"Blocked blanket git staging: '{cmd}'. "
363
+ f"Unignored sensitive file '{sensitive}' detected in working tree. "
364
+ f"Add '{sensitive}' to .gitignore or stage files explicitly to prevent credential leaks into git."
365
+ )
366
+ )
367
+ elif subcmd == "commit":
368
+ if any(a == "--all" or (a.startswith("-") and not a.startswith("--") and "a" in a) for a in sub_args):
369
+ sensitive = cls._find_unignored_sensitive_file(git_dir)
370
+ if sensitive:
371
+ return GuardResult(
372
+ blocked=True,
373
+ check_name="GIT_SECRET_STAGING",
374
+ reason=(
375
+ f"Blocked blanket git staging: '{cmd}'. "
376
+ f"Unignored sensitive file '{sensitive}' detected in working tree. "
377
+ f"Add '{sensitive}' to .gitignore or stage files explicitly to prevent credential leaks into git."
378
+ )
379
+ )
252
380
 
253
- # 3. Network Data Exfiltration Prevention (piping secrets to curl/wget)
381
+ # 3. Network Data Exfiltration Prevention (piping or posting secrets to curl/wget/nc)
382
+ _SENS_EXFIL = r"(?:\.env(?:\.[\w-]+)?|id_rsa|id_ed25519|\.key|\.pem|credentials\.json|service_account\.json|secret|password|token)"
254
383
  exfil_pattern = re.search(
255
- r"""\b(?:curl|wget|nc|ncat|netcat)\b.*?(?:\$\(cat\s+[^)]*(?:\.env|id_rsa|\.key|\.pem|secret|password|token)[^)]*\)|`cat\s+[^`]*(?:\.env|id_rsa|\.key|\.pem|secret|password|token)[^`]*`|-d\s+@(?:[^\s]*(?:\.env|id_rsa|\.key|\.pem))|-F\s+[^=]*=@(?:[^\s]*(?:\.env|id_rsa|\.key|\.pem))|--post-file[=\s]+(?:[^\s]*(?:\.env|id_rsa|\.key|\.pem)))""",
384
+ rf"""(?:\b(?:curl|wget|nc|ncat|netcat)\b.*?(?:\$\(\s*(?:cat\s+)?<?\s*[^)]*{_SENS_EXFIL}[^)]*\)|`cat\s+[^`]*{_SENS_EXFIL}[^`]*`|(?:-d|--data|--data-binary|--data-raw|-T|--upload-file)[=\s]*@?[^\s]*{_SENS_EXFIL}|-F\s+[^=]*=@[^\s]*{_SENS_EXFIL}|--post-file[=\s]+[^\s]*{_SENS_EXFIL}|<\s*[^\s]*{_SENS_EXFIL})|\bcat\s+[^\s|]*{_SENS_EXFIL}\s*\|\s*(?:curl|wget|nc|ncat|netcat)\b)""",
256
385
  cmd,
257
386
  re.IGNORECASE
258
387
  )
@@ -267,20 +396,18 @@ class TokenSafeGuard:
267
396
  )
268
397
 
269
398
  # 4. Package Typosquatting / Hallucination Early Warning (Non-blocking warning)
270
- pkg_install_match = re.search(
271
- r"""\b(?:pip(?:3)?\s+install|npm\s+(?:i|install)|pnpm\s+add|yarn\s+add|bun\s+add)\s+([a-zA-Z0-9_\-\s@/]+)""",
399
+ for pkg_install_match in re.finditer(
400
+ r"""\b(?:pip(?:3)?\s+install|npm\s+(?:i|install)|pnpm\s+add|yarn\s+add|bun\s+add)\s+([^;&|\n]+)""",
272
401
  cmd
273
- )
274
- if pkg_install_match:
402
+ ):
275
403
  pkg_str = pkg_install_match.group(1)
276
404
  tokens = [t.strip().lower() for t in pkg_str.split() if t.strip() and not t.startswith("-")]
277
405
  for tok in tokens:
278
406
  if tok.startswith("@"):
279
- # Scoped package e.g. @org/pkg or @org/pkg@1.0.0
280
407
  sub = tok[1:]
281
408
  base_pkg = sub.split("@")[0].strip()
282
409
  else:
283
- base_pkg = tok.split("==")[0].split("@")[0].strip()
410
+ base_pkg = re.split(r"[=<>~!@\[\]]", tok, maxsplit=1)[0].strip()
284
411
 
285
412
  if base_pkg in cls.KNOWN_TYPOSQUATS or f"@{base_pkg}" in cls.KNOWN_TYPOSQUATS:
286
413
  return GuardResult(
@@ -304,59 +431,101 @@ class TokenSafeGuard:
304
431
 
305
432
  return GuardResult(blocked=False)
306
433
 
434
+ @classmethod
435
+ def _has_code_target_in_args(cls, cmd_tok: str, cmd_args: List[str]) -> bool:
436
+ """Separates grep/rg/find pattern vs path args so grep 'app' server.log is not flagged."""
437
+ positionals: List[str] = []
438
+ skip_next = False
439
+ value_flags = {"-e", "-f", "-m", "-A", "-B", "-C", "-g", "--glob", "--type", "-t", "-name", "-iname", "-path"}
440
+ for a in cmd_args:
441
+ if skip_next:
442
+ skip_next = False
443
+ continue
444
+ if a in value_flags:
445
+ skip_next = True
446
+ continue
447
+ if a.startswith("-"):
448
+ continue
449
+ positionals.append(a)
450
+
451
+ # For grep/egrep/rg without -e, the first positional is the PATTERN; remaining positionals are PATHS.
452
+ if cmd_tok in ("grep", "egrep", "rg", "ripgrep"):
453
+ has_e = any(a == "-e" or a.startswith("--regexp") for a in cmd_args)
454
+ path_args = positionals if has_e else positionals[1:]
455
+ else:
456
+ path_args = positionals
457
+
458
+ for p in path_args:
459
+ low_p = p.lower()
460
+ if any(low_p.endswith(ext) or ext in low_p for ext in cls.CODE_EXTENSIONS):
461
+ return True
462
+ segs = [s for s in re.split(r"[/\\]", p.strip("\"'")) if s]
463
+ if any(s in cls.CODE_DIRS for s in segs):
464
+ return True
465
+ return False
466
+
307
467
  @classmethod
308
468
  def _check_raw_code_search(cls, cmd: str) -> Optional[str]:
309
469
  """
310
470
  Detects unconstrained terminal code searches (grep/rg/find targeting source files).
311
- Enforces use of TokenSafe MCP tools (smart_read_file, get_architecture_graph).
312
- Excludes safe pipe filters (e.g., git log | grep, ps | grep, npm test | grep).
471
+ Quote-aware splitting catches piped bypasses (rg foo src/ | head) while
472
+ allowing safe process pipe filters (ps aux | grep node, cat server.log | grep app).
313
473
  """
314
- # Split compound commands (&&, ||, ;)
315
- stages = [s.strip() for s in re.split(r'(?:&&|\|\||;)', cmd) if s.strip()]
316
-
317
- for stage in stages:
318
- pipe_parts = [p.strip() for p in stage.split('|')]
319
-
320
- # If grep is preceded by a non-code command (ps, git log, docker, npm test), it's a pipe filter
321
- if len(pipe_parts) > 1:
322
- first_part = pipe_parts[0]
323
- is_file_dump = bool(re.search(r'\b(cat|less|more)\s+[\w\.\/\-]+', first_part))
324
- if not is_file_dump:
325
- continue
326
-
327
- sub_cmd = pipe_parts[-1]
328
-
329
- # 1. Check for grep / egrep / ripgrep (rg)
330
- grep_match = re.search(r'\b(grep|egrep|rg|ripgrep)\b', sub_cmd)
331
- if grep_match:
332
- has_code_ext = any(ext in sub_cmd for ext in cls.CODE_EXTENSIONS)
333
- has_code_dir = any(re.search(rf'\b{re.escape(d)}(?:/|\b)', sub_cmd) for d in cls.CODE_DIRS)
334
- # '-rn' / '-Rn' are the canonical recursive forms — the flag
335
- # regex must accept letters after r/R, plus the long --recursive.
336
- is_recursive_all = bool(re.search(r'\b(grep|egrep)\b.*?\s(?:-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)\b', sub_cmd)) or \
337
- bool(re.search(r'\brg\b', sub_cmd))
338
-
339
- if has_code_ext or has_code_dir or is_recursive_all:
340
- return (
341
- f"Raw terminal code search blocked: '{sub_cmd}'. "
342
- f"TokenSafe Protocol mandates using MCP tools to prevent context window bloat:\n"
343
- f"• To search keywords, symbols, or configs: call 'tokensafe:scoped_search(query, scope)'\n"
344
- f"• To inspect definitions/symbols in a file: call 'tokensafe:smart_read_file(path, symbol)'\n"
345
- f"• To locate God Nodes & architecture: call 'tokensafe:get_architecture_graph(project_path)'\n"
346
- f"• To inspect project exports & types: call 'tokensafe:get_api_surface(project_path)'"
474
+ pairs = CommandSanitizer.split_stages(cmd)
475
+ # Group pipeline chains separated by && / || / ; / \n
476
+ pipelines: List[List[str]] = []
477
+ for op, stage in pairs:
478
+ if op == "|" and pipelines:
479
+ pipelines[-1].append(stage)
480
+ else:
481
+ pipelines.append([stage])
482
+
483
+ for pipe_parts in pipelines:
484
+ first_tok, first_args = cls._stage_cmd_tokens(pipe_parts[0])
485
+ targets_to_check: List[str] = []
486
+ if len(pipe_parts) == 1:
487
+ targets_to_check = [pipe_parts[0]]
488
+ else:
489
+ if first_tok in ("grep", "egrep", "rg", "ripgrep", "find") or (first_tok == "git" and "grep" in first_args[:3]):
490
+ targets_to_check.append(pipe_parts[0])
491
+ if first_tok in ("cat", "less", "more"):
492
+ if any(any(a.lower().endswith(ext) for ext in cls.CODE_EXTENSIONS) for a in first_args):
493
+ targets_to_check.append(pipe_parts[-1])
494
+
495
+ for sub_cmd in targets_to_check:
496
+ cmd_tok, cmd_args = cls._stage_cmd_tokens(sub_cmd)
497
+ is_git_grep = cmd_tok == "git" and "grep" in cmd_args[:3]
498
+
499
+ if cmd_tok in ("grep", "egrep", "rg", "ripgrep") or is_git_grep:
500
+ effective_args = cmd_args[cmd_args.index("grep") + 1:] if is_git_grep else cmd_args
501
+ has_code_ext = any(ext in sub_cmd for ext in cls.CODE_EXTENSIONS)
502
+ has_code_dir = cls._has_code_target_in_args("grep" if is_git_grep else cmd_tok, effective_args)
503
+ is_recursive_grep = (cmd_tok in ("grep", "egrep") or is_git_grep) and any(
504
+ (a.startswith("-") and not a.startswith("--") and ("r" in a or "R" in a)) or a == "--recursive"
505
+ for a in effective_args
347
506
  )
507
+ is_rg = cmd_tok in ("rg", "ripgrep")
508
+
509
+ if has_code_ext or has_code_dir or is_recursive_grep or is_rg:
510
+ return (
511
+ f"Raw terminal code search blocked: '{sub_cmd}'. "
512
+ f"TokenSafe Protocol mandates using MCP tools to prevent context window bloat:\n"
513
+ f"• To search keywords, symbols, or configs: call 'tokensafe:scoped_search(query, scope)'\n"
514
+ f"• To inspect definitions/symbols in a file: call 'tokensafe:smart_read_file(path, symbol)'\n"
515
+ f"• To locate God Nodes & architecture: call 'tokensafe:get_architecture_graph(project_path)'\n"
516
+ f"• To inspect project exports & types: call 'tokensafe:get_api_surface(project_path)'"
517
+ )
348
518
 
349
- # 2. Check for find on source code
350
- find_match = re.search(r'\bfind\b\s+([\w\.\/\-]+)', sub_cmd)
351
- if find_match:
352
- has_code_ext = any(ext in sub_cmd for ext in cls.CODE_EXTENSIONS)
353
- has_code_dir = any(re.search(rf'\b{re.escape(d)}(?:/|\b)', sub_cmd) for d in cls.CODE_DIRS)
354
- if has_code_ext or has_code_dir:
355
- return (
356
- f"Raw file crawl via 'find' blocked: '{sub_cmd}'. "
357
- f"Use 'tokensafe:scoped_search(query)' or 'tokensafe:get_architecture_graph(project_path)' "
358
- f"instead of scanning directory trees."
359
- )
519
+ elif cmd_tok == "find":
520
+ has_code_ext = any(ext in sub_cmd for ext in cls.CODE_EXTENSIONS)
521
+ has_code_dir = cls._has_code_target_in_args(cmd_tok, cmd_args) or bool(cls._CODE_DIR_RE.search(sub_cmd))
522
+ is_root_file_crawl = any(a in (".", "./") for a in cmd_args[:2]) and ("-type" in cmd_args and "f" in cmd_args)
523
+ if has_code_ext or has_code_dir or is_root_file_crawl:
524
+ return (
525
+ f"Raw file crawl via 'find' blocked: '{sub_cmd}'. "
526
+ f"Use 'tokensafe:scoped_search(query)' or 'tokensafe:get_architecture_graph(project_path)' "
527
+ f"instead of scanning directory trees."
528
+ )
360
529
 
361
530
  return None
362
531
 
@@ -364,12 +533,13 @@ class TokenSafeGuard:
364
533
  def _find_unignored_sensitive_file(cls, target_dir: str) -> Optional[str]:
365
534
  """
366
535
  Returns the repo-relative path of the first unignored sensitive file, or None.
367
- Prefers `git status --porcelain -uall` (exact .gitignore semantics incl.
368
- negation and nested ignore files) over crawling the tree with os.walk,
369
- which was both slow on large repos and inaccurate about ignore rules.
536
+ Prefers `git status --porcelain -uall` (skipping deleted 'D' entries).
370
537
  """
371
538
  def _is_sensitive_name(name: str) -> bool:
372
- return name in cls.SENSITIVE_GIT_FILES or (name.startswith(".env") and not name.endswith(".example"))
539
+ low = name.lower()
540
+ if any(low.endswith(suf) for suf in cls._TEMPLATE_EXAMPLES):
541
+ return False
542
+ return name in cls.SENSITIVE_GIT_FILES or (name.startswith(".env") and not any(low.endswith(suf) for suf in cls._TEMPLATE_EXAMPLES))
373
543
 
374
544
  # 1. Fast & exact: ask git itself (only lists non-ignored files).
375
545
  try:
@@ -379,7 +549,8 @@ class TokenSafeGuard:
379
549
  )
380
550
  if res.returncode == 0:
381
551
  for line in res.stdout.splitlines():
382
- # Format: "XY PATH" (path may be quoted; renames use "old -> new")
552
+ if len(line) >= 2 and line[:2] in (" D", "D ", "DD"):
553
+ continue
383
554
  path_part = line[3:].strip() if len(line) > 3 else ""
384
555
  if path_part.startswith('"') and path_part.endswith('"'):
385
556
  path_part = path_part[1:-1]
@@ -390,37 +561,50 @@ class TokenSafeGuard:
390
561
  except Exception:
391
562
  pass
392
563
 
393
- # 2. Fallback: bounded manual walk with naive gitignore matching.
564
+ # 2. Fallback: bounded manual walk with cached .gitignore patterns
565
+ ignore_patterns = cls._load_gitignore_patterns(target_dir)
394
566
  for root, dirs, files in os.walk(target_dir):
395
- # Prune common heavy/inert subtrees
396
567
  dirs[:] = [d for d in dirs if d not in (".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", ".next", ".turbo")]
397
568
  for f in files:
398
569
  if _is_sensitive_name(f):
399
570
  full = os.path.join(root, f)
400
571
  rel_path = os.path.relpath(full, target_dir)
401
- if not cls._is_git_ignored(full, target_dir):
572
+ if not cls._matches_gitignore(full, target_dir, ignore_patterns):
402
573
  return rel_path
403
574
  return None
404
575
 
405
- @classmethod
406
- def _is_git_ignored(cls, file_path: str, repo_root: str) -> bool:
407
- """Checks if a file is covered by .gitignore in the repository."""
576
+ @staticmethod
577
+ def _load_gitignore_patterns(repo_root: str) -> List[str]:
408
578
  gitignore_path = os.path.join(repo_root, ".gitignore")
579
+ patterns: List[str] = []
409
580
  if not os.path.exists(gitignore_path):
410
- return False
581
+ return patterns
411
582
  try:
412
- filename = os.path.basename(file_path)
413
- rel_path = os.path.relpath(file_path, repo_root).replace("\\", "/")
414
583
  with open(gitignore_path, "r", encoding="utf-8", errors="replace") as f:
415
584
  for raw_line in f:
416
585
  line = raw_line.strip()
417
- if not line or line.startswith("#"):
418
- continue
419
- clean_pattern = line.lstrip("/")
420
- if fnmatch.fnmatch(filename, clean_pattern) or fnmatch.fnmatch(rel_path, clean_pattern):
421
- return True
422
- if clean_pattern.endswith("/") and rel_path.startswith(clean_pattern):
423
- return True
586
+ if line and not line.startswith("#") and not line.startswith("!"):
587
+ patterns.append(line.lstrip("/"))
424
588
  except Exception:
425
589
  pass
590
+ return patterns
591
+
592
+ @staticmethod
593
+ def _matches_gitignore(file_path: str, repo_root: str, patterns: List[str]) -> bool:
594
+ if not patterns:
595
+ return False
596
+ filename = os.path.basename(file_path)
597
+ rel_path = os.path.relpath(file_path, repo_root).replace("\\", "/")
598
+ for clean_pattern in patterns:
599
+ if fnmatch.fnmatch(filename, clean_pattern) or fnmatch.fnmatch(rel_path, clean_pattern):
600
+ return True
601
+ if clean_pattern.endswith("/") and rel_path.startswith(clean_pattern):
602
+ return True
603
+ if "/" not in clean_pattern and rel_path.startswith(clean_pattern + "/"):
604
+ return True
426
605
  return False
606
+
607
+ @classmethod
608
+ def _is_git_ignored(cls, file_path: str, repo_root: str) -> bool:
609
+ """Checks if a file is covered by .gitignore in the repository."""
610
+ return cls._matches_gitignore(file_path, repo_root, cls._load_gitignore_patterns(repo_root))