tokensafe 4.3.2 → 4.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.3.2",
2
+ "version": "4.3.3",
3
3
  "name": "tokensafe",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "author": {
@@ -22,7 +22,7 @@ PROJECT_ROOT = os.path.dirname(HOOK_DIR)
22
22
  if PROJECT_ROOT not in sys.path:
23
23
  sys.path.insert(0, PROJECT_ROOT)
24
24
 
25
- from src.adapter_core import TOKENSAFE_DIRECTIVES, compact_for_injection, guard_command, guard_write
25
+ from src.adapter_core import TOKENSAFE_DIRECTIVES, compact_for_injection, extract_write_content, guard_command, guard_file_content, guard_write
26
26
 
27
27
  AGENT = "claude_code"
28
28
 
@@ -200,6 +200,18 @@ def handle(event: str, payload: dict) -> dict:
200
200
  file_path = str(tool_input.get("file_path") or tool_input.get("Path") or tool_input.get("path") or "")
201
201
  content = tool_input.get("content") or tool_input.get("Content") or tool_input.get("file_text") or ""
202
202
  append = bool(tool_input.get("append") or tool_input.get("Append") or False)
203
+ # Security first (parity with the Antigravity path): hardcoded
204
+ # secrets / TLS bypass / SQLi / CORS never reach disk, before any
205
+ # egress-economy steering.
206
+ sec_verdict = guard_file_content(file_path, str(content or ""), AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
207
+ if sec_verdict["decision"] == "deny":
208
+ return {
209
+ "hookSpecificOutput": {
210
+ "hookEventName": "PreToolUse",
211
+ "permissionDecision": "deny",
212
+ "permissionDecisionReason": sec_verdict["reason"],
213
+ }
214
+ }
203
215
  verdict = guard_write(file_path, str(content or ""), append, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
204
216
  if verdict["decision"] == "deny":
205
217
  return {
@@ -218,6 +230,19 @@ def handle(event: str, payload: dict) -> dict:
218
230
  }
219
231
  }
220
232
  elif tool in ("Edit", "MultiEdit", "edit_file", "replace_file_content"):
233
+ # Security first (parity with the Antigravity path): deny hardcoded
234
+ # secrets / TLS bypass / SQLi / CORS in the replacement text before
235
+ # the stale-file check (deny outranks ask).
236
+ sec_file = str(tool_input.get("file_path") or tool_input.get("Path") or tool_input.get("path") or "")
237
+ sec_verdict = guard_file_content(sec_file, extract_write_content(tool, tool_input), AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
238
+ if sec_verdict["decision"] == "deny":
239
+ return {
240
+ "hookSpecificOutput": {
241
+ "hookEventName": "PreToolUse",
242
+ "permissionDecision": "deny",
243
+ "permissionDecisionReason": sec_verdict["reason"],
244
+ }
245
+ }
221
246
  # Stale-file edit guard: when the target changed on disk since the
222
247
  # model last saw it (build output, linters, another session), the
223
248
  # edit either corrupts content or fails and forces a costly full
@@ -10,6 +10,9 @@ Honest capability matrix (per official Cursor hooks docs):
10
10
  beforeSubmitPrompt -> allow/deny ONLY (no injection in Cursor yet):
11
11
  records nothing, always allows. Kept as a no-op
12
12
  so the hook wiring is future-proof.
13
+ beforeEditFile -> allow/deny: secret/TLS/SQL gate on edit payloads,
14
+ wired opportunistically (inert where the host
15
+ never fires this event).
13
16
  stop / afterFileEdit -> observational no-ops.
14
17
 
15
18
  IMPORTANT: Cursor BLOCKS the action when a hook prints invalid JSON.
@@ -26,7 +29,7 @@ PROJECT_ROOT = os.path.dirname(HOOK_DIR)
26
29
  if PROJECT_ROOT not in sys.path:
27
30
  sys.path.insert(0, PROJECT_ROOT)
28
31
 
29
- from src.adapter_core import guard_command, guard_read
32
+ from src.adapter_core import extract_write_content, guard_command, guard_file_content, guard_read
30
33
 
31
34
  AGENT = "cursor"
32
35
 
@@ -56,6 +59,19 @@ def handle(event: str, payload: dict) -> dict:
56
59
  return {"permission": "deny", "user_message": verdict["reason"]}
57
60
  return {"permission": "allow"}
58
61
 
62
+ if event == "beforeEditFile":
63
+ # Opportunistic security gate on edit payloads (hardcoded secrets /
64
+ # TLS bypass / SQLi / CORS — parity with the Antigravity path).
65
+ # Unknown/absent content fields fail open to allow.
66
+ edit_path = str(payload.get("file_path") or payload.get("path") or "")
67
+ tool_hint = "MultiEdit" if isinstance(payload.get("edits"), list) else "Edit"
68
+ edit_content = extract_write_content(tool_hint, payload)
69
+ if edit_content:
70
+ verdict = guard_file_content(edit_path, edit_content, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
71
+ if verdict["decision"] == "deny":
72
+ return {"permission": "deny", "user_message": verdict["reason"]}
73
+ return {"permission": "allow"}
74
+
59
75
  if event == "beforeSubmitPrompt":
60
76
  # Cursor cannot inject context (allow/deny only). Nothing honest to
61
77
  # record: the model still sees the full prompt. Always allow.
@@ -81,7 +97,7 @@ def main():
81
97
  response = _allow(event)
82
98
  if not isinstance(response, dict) or not response:
83
99
  response = _allow(event)
84
- if event in ("beforeShellExecution", "beforeReadFile", "beforeSubmitPrompt", "stop"):
100
+ if event in ("beforeShellExecution", "beforeEditFile", "beforeReadFile", "beforeSubmitPrompt", "stop"):
85
101
  try:
86
102
  from src.telemetry_sync import TelemetrySync
87
103
  TelemetrySync.sync_background(throttle_seconds=0.0 if event == "stop" else 20.0)
@@ -24,7 +24,9 @@ if PROJECT_ROOT not in sys.path:
24
24
  from src.adapter_core import (
25
25
  TOKENSAFE_DIRECTIVES,
26
26
  compact_for_injection,
27
+ extract_write_content,
27
28
  guard_command,
29
+ guard_file_content,
28
30
  guard_read,
29
31
  guard_write,
30
32
  )
@@ -140,6 +142,17 @@ def handle(event: str, payload: dict) -> dict:
140
142
  file_path = str(tool_input.get("file_path") or tool_input.get("Path") or tool_input.get("path") or "")
141
143
  content = tool_input.get("content") or tool_input.get("Content") or tool_input.get("file_text") or ""
142
144
  append = bool(tool_input.get("append") or tool_input.get("Append") or False)
145
+ # Security first (parity with the Antigravity path): hardcoded
146
+ # secrets / TLS bypass / SQLi / CORS never reach disk.
147
+ sec_verdict = guard_file_content(file_path, str(content or ""), AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
148
+ if sec_verdict["decision"] == "deny":
149
+ return {
150
+ "hookSpecificOutput": {
151
+ "hookEventName": "PreToolUse",
152
+ "permissionDecision": "deny",
153
+ "permissionDecisionReason": sec_verdict["reason"],
154
+ }
155
+ }
143
156
  verdict = guard_write(file_path, str(content or ""), append, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
144
157
  if verdict["decision"] == "deny":
145
158
  return {
@@ -158,6 +171,20 @@ def handle(event: str, payload: dict) -> dict:
158
171
  }
159
172
  }
160
173
 
174
+ elif tool in ("Edit", "MultiEdit", "edit_file"):
175
+ # Security parity: deny hardcoded secrets / TLS bypass / SQLi /
176
+ # CORS in the replacement text before the edit lands.
177
+ edit_path = str(tool_input.get("file_path") or tool_input.get("Path") or tool_input.get("path") or "")
178
+ sec_verdict = guard_file_content(edit_path, extract_write_content(tool, tool_input), AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
179
+ if sec_verdict["decision"] == "deny":
180
+ return {
181
+ "hookSpecificOutput": {
182
+ "hookEventName": "PreToolUse",
183
+ "permissionDecision": "deny",
184
+ "permissionDecisionReason": sec_verdict["reason"],
185
+ }
186
+ }
187
+
161
188
  elif tool in ("Read", "read_file", "view_file"):
162
189
  file_path = str(tool_input.get("file_path") or tool_input.get("path") or tool_input.get("Path") or "")
163
190
  verdict = guard_read(file_path, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.3.2",
3
+ "version": "4.3.3",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "homepage": "https://tokensafe.dev",
6
6
  "license": "MIT",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.3.2",
4
+ "version": "4.3.3",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.3.2",
4
+ "version": "4.3.3",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "logo": "assets/logo.png",
7
7
  "developerName": "TokenSafe",
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
6
- "version": "4.3.2",
6
+ "version": "4.3.3",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -23,7 +23,7 @@
23
23
  "registryType": "npm",
24
24
  "registryBaseUrl": "https://registry.npmjs.org",
25
25
  "identifier": "tokensafe",
26
- "version": "4.3.2",
26
+ "version": "4.3.3",
27
27
  "runtimeHint": "npx",
28
28
  "transport": {
29
29
  "type": "stdio"
@@ -39,7 +39,7 @@
39
39
  "registryType": "pypi",
40
40
  "registryBaseUrl": "https://pypi.org",
41
41
  "identifier": "tokensafe",
42
- "version": "4.3.2",
42
+ "version": "4.3.3",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -297,6 +297,67 @@ def guard_read(file_path: str, agent: str, session_id: str = "", transcript_path
297
297
  return result
298
298
 
299
299
 
300
+ def extract_write_content(tool_name: str, tool_input: Dict[str, Any]) -> str:
301
+ """Collects the text an Edit-family tool would put on disk: Write content
302
+ variants, Edit new_string, MultiEdit edits[].new_string, Antigravity
303
+ Replacement. Empty when the payload carries no writable text."""
304
+ if not isinstance(tool_input, dict):
305
+ return ""
306
+ if tool_name == "MultiEdit":
307
+ edits = tool_input.get("edits")
308
+ if isinstance(edits, list):
309
+ return "\n".join(
310
+ str((e or {}).get("new_string") or "")
311
+ for e in edits if isinstance(e, dict)
312
+ )
313
+ return ""
314
+ for key in ("new_string", "NewString", "new_str", "Replacement", "content", "Content", "file_text"):
315
+ if tool_input.get(key):
316
+ return str(tool_input.get(key))
317
+ return ""
318
+
319
+
320
+ def guard_file_content(file_path: str, content: str, agent: str = "", session_id: str = "", transcript_path: str = "") -> Dict[str, Any]:
321
+ """Pre-write SECURITY guard shared by every agent hook: runs
322
+ TokenSafeGuard.inspect_file_write (SECRET_FALLBACK, TLS_VERIFY_BYPASS,
323
+ SQL_INJECTION, INSECURE_CORS) on the payload about to hit disk. Previously
324
+ only the Antigravity path enforced this; Claude Code / ZCode / Cursor /
325
+ Kimi native Write/Edit bypassed the check entirely. Same deny/ask/allow
326
+ result shape as guard_command/guard_write. Fail-open like every adapter
327
+ guard path."""
328
+ result = {"decision": "allow", "reason": "", "saved_tokens": 0}
329
+ if not content or not isinstance(content, str):
330
+ return result
331
+ try:
332
+ from src.guard import TokenSafeGuard
333
+ guard_res = TokenSafeGuard.inspect_file_write(file_path or "", content)
334
+ except Exception:
335
+ return result
336
+ if guard_res.blocked:
337
+ est = max(1, count_tokens(content))
338
+ tracker = _get_tracker()
339
+ if tracker:
340
+ try:
341
+ tracker.record_event(
342
+ session_id=session_id or f"hook_{agent}",
343
+ event_type=f"GUARD_{guard_res.check_name}",
344
+ original_tokens=est,
345
+ optimized_tokens=0,
346
+ details={"agent": agent, "tool": "write",
347
+ "target_file": os.path.basename(file_path) if file_path else "unknown",
348
+ "reason": guard_res.reason,
349
+ "model": resolve_event_model(transcript_path, session_id)},
350
+ )
351
+ except Exception:
352
+ pass
353
+ result.update({
354
+ "decision": "deny",
355
+ "reason": f"🛡️ TokenSafe Guard: {guard_res.reason}",
356
+ "saved_tokens": est,
357
+ })
358
+ return result
359
+
360
+
300
361
  def guard_write(file_path: str, content: str, append: bool = False, agent: str = "", session_id: str = "", transcript_path: str = "") -> Dict[str, Any]:
301
362
  """Pre-write egress guard (v3.0.0): full-file Write over an existing file
302
363
  burns expensive OUTPUT tokens. Policy:
package/src/guard.py CHANGED
@@ -260,6 +260,72 @@ class TokenSafeGuard:
260
260
  return True
261
261
  return False
262
262
 
263
+ _GIT_COMMIT_VALUE_FLAGS = frozenset({
264
+ "-m", "--message", "-F", "--file", "-t", "--template",
265
+ "-C", "--reuse-message", "-c", "--reedit-message",
266
+ "--fixup", "--squash", "--author", "--date", "--cleanup",
267
+ })
268
+
269
+ @classmethod
270
+ def _partial_commit_sensitive_path(cls, sub_args: List[str]) -> Optional[str]:
271
+ """Sensitive file targeted by a partial commit ('git commit <path>',
272
+ 'git commit --only <path>'), or None. Flag VALUES (-m "msg", --author,
273
+ --fixup ...) are skipped so commit messages can never false-positive."""
274
+ skip_next = False
275
+ for a in sub_args:
276
+ if skip_next:
277
+ skip_next = False
278
+ continue
279
+ if a.startswith("--only=") or a.startswith("--include="):
280
+ cand = a.split("=", 1)[1]
281
+ if cls._is_sensitive_filename(cand):
282
+ return cand
283
+ continue
284
+ if a in cls._GIT_COMMIT_VALUE_FLAGS:
285
+ skip_next = True
286
+ continue
287
+ if a.startswith("-"):
288
+ continue
289
+ if cls._is_sensitive_filename(a):
290
+ return a
291
+ return None
292
+
293
+ @classmethod
294
+ def _stash_sensitive_target(cls, stash_args: List[str], git_dir: str) -> Optional[str]:
295
+ """Sensitive file a 'git stash push/save' would capture, or None.
296
+ Covers explicit pathspecs and untracked sweeps ('-u' / '-a')."""
297
+ include_untracked = False
298
+ saw_subcmd = False
299
+ skip_next = False
300
+ pathspecs: List[str] = []
301
+ for a in stash_args:
302
+ if skip_next:
303
+ skip_next = False
304
+ continue
305
+ if a in ("push", "save") and not saw_subcmd:
306
+ saw_subcmd = True
307
+ continue
308
+ if a in ("-m", "--message"):
309
+ skip_next = True
310
+ continue
311
+ if a.startswith("-m") and a != "-m":
312
+ continue
313
+ if a in ("-u", "-a", "--include-untracked", "--all") or (
314
+ a.startswith("-") and not a.startswith("--") and "u" in a
315
+ ):
316
+ include_untracked = True
317
+ continue
318
+ if a.startswith("-"):
319
+ continue
320
+ saw_subcmd = True
321
+ pathspecs.append(a)
322
+ for p in pathspecs:
323
+ if cls._is_sensitive_filename(p):
324
+ return p
325
+ if include_untracked and not pathspecs:
326
+ return cls._find_unignored_sensitive_file(git_dir)
327
+ return None
328
+
263
329
  @classmethod
264
330
  def inspect_command(cls, command: str, cwd: str = "") -> GuardResult:
265
331
  """
@@ -408,6 +474,29 @@ class TokenSafeGuard:
408
474
  f"Add '{sensitive}' to .gitignore or stage files explicitly to prevent credential leaks into git."
409
475
  )
410
476
  )
477
+ partial = cls._partial_commit_sensitive_path(sub_args)
478
+ if partial:
479
+ return GuardResult(
480
+ blocked=True,
481
+ check_name="GIT_SECRET_STAGING",
482
+ reason=(
483
+ f"Blocked partial git commit of a sensitive credential file: '{cmd}'. "
484
+ f"'{partial}' is an environment file or private key and must never "
485
+ f"be committed to source control."
486
+ )
487
+ )
488
+ elif subcmd == "stash":
489
+ stash_sensitive = cls._stash_sensitive_target(sub_args, git_dir)
490
+ if stash_sensitive:
491
+ return GuardResult(
492
+ blocked=True,
493
+ check_name="GIT_SECRET_STAGING",
494
+ reason=(
495
+ f"Blocked git stash capture of a sensitive credential file: '{cmd}'. "
496
+ f"'{stash_sensitive}' would be stored inside the stash object; "
497
+ f"add it to .gitignore instead of stashing it."
498
+ )
499
+ )
411
500
 
412
501
  # 2b. Secret-File Read Interception: reading credential stores (.env, private
413
502
  # keys, credential bundles) pulls live secrets into the model context —
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "4.3.2"
45
+ "version": "4.3.3"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
package/src/metrics.py CHANGED
@@ -38,6 +38,7 @@ ESTIMATED_EVENT_TYPES = frozenset({
38
38
  "LOOP_GUARD",
39
39
  "SCOPED_SEARCH",
40
40
  "DIR_LIST",
41
+ "OUTPUT_GUARD",
41
42
  "GUARD_SECRET",
42
43
  "GUARD_DESTRUCTIVE",
43
44
  "GUARD_TLS_VERIFY_BYPASS",
@@ -48,9 +49,13 @@ ESTIMATED_EVENT_TYPES = frozenset({
48
49
 
49
50
  def resolve_measurement(event_type: str, explicit: Optional[str] = None) -> str:
50
51
  """Resolves the measurement label for an event: explicit override wins,
51
- then the estimated-type map, then 'measured'."""
52
+ then the GUARD_ counterfactual prefix (blocked payloads never reach the
53
+ model, so every GUARD_* event is a heuristic guess regardless of the
54
+ historical check-name list), then the estimated-type map, then 'measured'."""
52
55
  if explicit in ("measured", "estimated"):
53
56
  return explicit
57
+ if event_type.startswith("GUARD_"):
58
+ return "estimated"
54
59
  return "estimated" if event_type in ESTIMATED_EVENT_TYPES else "measured"
55
60
 
56
61
  _METRICS_INIT_LOCK = threading.Lock()
@@ -241,7 +241,7 @@ class TelemetrySync:
241
241
  current_last_id = last_id
242
242
  headers = {
243
243
  "Content-Type": "application/json",
244
- "User-Agent": "TokenSafe-Sync/4.3.2"
244
+ "User-Agent": "TokenSafe-Sync/4.3.3"
245
245
  }
246
246
  if active_key:
247
247
  headers["Authorization"] = f"Bearer {active_key}"
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "4.3.2"
20
+ CURRENT_VERSION = "4.3.3"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage