tokensafe 1.1.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/proxy.py CHANGED
@@ -33,7 +33,23 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
33
33
  # Mute noisy default server logs
34
34
  pass
35
35
 
36
+ def _validate_origin(self) -> bool:
37
+ """Protects against DNS rebinding and cross-origin attacks from arbitrary browser origins."""
38
+ origin = self.headers.get("Origin", "")
39
+ if origin:
40
+ allowed_prefixes = ("http://127.0.0.1", "http://localhost", "https://tokensafe.dev")
41
+ if not any(origin.startswith(a) for a in allowed_prefixes):
42
+ self.send_response(403)
43
+ self.send_header("Content-Type", "application/json")
44
+ self.end_headers()
45
+ self.wfile.write(b'{"error": "Forbidden: Untrusted cross-origin request rejected"}')
46
+ return False
47
+ return True
48
+
36
49
  def do_GET(self):
50
+ if not self._validate_origin():
51
+ return
52
+
37
53
  tracker = MetricsTracker()
38
54
  dashboard = Dashboard(tracker)
39
55
 
@@ -62,6 +78,9 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
62
78
  self.end_headers()
63
79
 
64
80
  def do_POST(self):
81
+ if not self._validate_origin():
82
+ return
83
+
65
84
  if self.path.startswith("/v1/chat/completions"):
66
85
  self.handle_chat_completions()
67
86
  else:
@@ -77,9 +77,10 @@ class Skeletonizer:
77
77
  return "\n".join(out)
78
78
 
79
79
  @classmethod
80
- def get_skeleton_file(cls, original_path: str) -> Tuple[Optional[str], int, int]:
80
+ def get_skeleton_file(cls, original_path: str, target_symbol: Optional[str] = None) -> Tuple[Optional[str], int, int]:
81
81
  """
82
82
  Reads original_path, checks mtime cache, generates skeleton if modified or absent.
83
+ If target_symbol is provided, applies Graph-Guided AST skeletonization retaining 1-hop dependencies.
83
84
  Returns: (skeleton_path_or_none, orig_tokens, skeleton_tokens)
84
85
  """
85
86
  if not original_path or not os.path.exists(original_path):
@@ -95,9 +96,10 @@ class Skeletonizer:
95
96
  os.makedirs(cls.CACHE_DIR, exist_ok=True)
96
97
  path_hash = hashlib.md5(original_path.encode("utf-8")).hexdigest()[:8]
97
98
  base_name = os.path.basename(original_path)
98
- skeleton_filename = f"{path_hash}_{base_name}"
99
+ sym_suffix = f"_{target_symbol}" if target_symbol else ""
100
+ skeleton_filename = f"{path_hash}{sym_suffix}_{base_name}"
99
101
  skeleton_path = os.path.join(cls.CACHE_DIR, skeleton_filename)
100
- meta_path = os.path.join(cls.CACHE_DIR, f"{path_hash}_{base_name}.meta.json")
102
+ meta_path = os.path.join(cls.CACHE_DIR, f"{path_hash}{sym_suffix}_{base_name}.meta.json")
101
103
 
102
104
  # 1. Check incremental mtime cache
103
105
  if os.path.exists(skeleton_path) and os.path.exists(meta_path):
@@ -122,7 +124,18 @@ class Skeletonizer:
122
124
  return None, 0, 0
123
125
 
124
126
  ext = os.path.splitext(original_path)[1]
125
- skeleton_content = cls.skeletonize_code(code, ext)
127
+
128
+ # If target symbol specified, use Graph-Guided skeletonization
129
+ if target_symbol:
130
+ try:
131
+ from src.graph_engine import GraphEngine
132
+ graph, rel_path = GraphEngine.for_file(original_path)
133
+ graph_content = graph.graph_guided_skeletonize(original_path, target_symbol=target_symbol)
134
+ skeleton_content = graph_content if graph_content else cls.skeletonize_code(code, ext)
135
+ except Exception:
136
+ skeleton_content = cls.skeletonize_code(code, ext)
137
+ else:
138
+ skeleton_content = cls.skeletonize_code(code, ext)
126
139
 
127
140
  # Prefetch local dependency signatures
128
141
  from src.dependency_prefetcher import DependencyPrefetcher
@@ -134,13 +147,20 @@ class Skeletonizer:
134
147
  if skel_tokens >= orig_tokens * 0.7:
135
148
  return None, 0, 0
136
149
 
137
- header_comment = (
138
- f"// [TOCP AST Skeleton: {lines_count} lines folded into API signatures]\n"
139
- f"// [To inspect implementation of a specific method, call read_file with StartLine/EndLine]\n\n"
140
- ) if ext != ".py" else (
141
- f"# [TOCP AST Skeleton: {lines_count} lines folded into API signatures]\n"
142
- f"# [To inspect implementation of a specific method, call read_file with StartLine/EndLine]\n\n"
143
- )
150
+ if target_symbol:
151
+ header_comment = (
152
+ f"// [TokenSafe Graph-Guided Skeleton for '{target_symbol}': target & 1-hop dependencies kept full]\n\n"
153
+ ) if ext != ".py" else (
154
+ f"# [TokenSafe Graph-Guided Skeleton for '{target_symbol}': target & 1-hop dependencies kept full]\n\n"
155
+ )
156
+ else:
157
+ header_comment = (
158
+ f"// [TOCP AST Skeleton: {lines_count} lines folded into API signatures]\n"
159
+ f"// [To inspect implementation of a specific method, call read_file with StartLine/EndLine]\n\n"
160
+ ) if ext != ".py" else (
161
+ f"# [TOCP AST Skeleton: {lines_count} lines folded into API signatures]\n"
162
+ f"# [To inspect implementation of a specific method, call read_file with StartLine/EndLine]\n\n"
163
+ )
144
164
 
145
165
  full_content = header_comment + (prefetch_block + "\n" if prefetch_block else "") + skeleton_content
146
166
 
package/src/slicer.py CHANGED
@@ -91,7 +91,8 @@ class ToolSlicer:
91
91
  "original_tokens": total_tokens,
92
92
  "optimized_tokens": sliced_tokens,
93
93
  "lines_total": total_lines,
94
- "lines_sliced": (new_end - new_start + 1)
94
+ "lines_sliced": (new_end - new_start + 1),
95
+ "target_symbol": target_symbol
95
96
  }
96
97
  return overwrite, metrics
97
98
 
@@ -0,0 +1,156 @@
1
+ """
2
+ TokenSafe Version Checker & Passive Nudge Engine.
3
+ Maintains a 24h cached version status to provide zero-latency terminal banners,
4
+ soft update recommendations, and critical forced update notifications.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import json
10
+ import time
11
+ import re
12
+ import urllib.parse
13
+ import urllib.request
14
+ import urllib.error
15
+ from typing import Dict, Any, Optional, Tuple
16
+
17
+ CURRENT_VERSION = "1.3.0"
18
+ CACHE_TTL = 86400 # 24 hours
19
+
20
+ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
+ DATA_DIR = os.path.join(PROJECT_ROOT, "data")
22
+ CACHE_FILE = os.path.join(DATA_DIR, "version_cache.json")
23
+ CLOUD_CHECK_URL = os.environ.get("TOKENSAFE_VERSION_URL", "https://api.tokensafe.dev/api/version/check")
24
+
25
+ # ANSI color codes
26
+ RESET = "\033[0m"
27
+ BOLD = "\033[1m"
28
+ GREEN = "\033[32m"
29
+ CYAN = "\033[36m"
30
+ YELLOW = "\033[33m"
31
+ RED = "\033[31m"
32
+ DIM = "\033[2m"
33
+
34
+ def semver_tuple(v_str: str) -> Tuple[int, ...]:
35
+ """Parses semver string like '1.2.0' into numeric tuple (1, 2, 0)."""
36
+ if not v_str:
37
+ return (0, 0, 0)
38
+ clean = re.sub(r"^[^\d]*", "", str(v_str).strip())
39
+ parts = clean.split(".")
40
+ nums = []
41
+ for p in parts[:3]:
42
+ m = re.match(r"\d+", p)
43
+ nums.append(int(m.group(0)) if m else 0)
44
+ while len(nums) < 3:
45
+ nums.append(0)
46
+ return tuple(nums)
47
+
48
+ class VersionChecker:
49
+ """Manages cached client-side version discovery and CLI banners."""
50
+
51
+ @classmethod
52
+ def get_cache_path(cls) -> str:
53
+ os.makedirs(DATA_DIR, exist_ok=True)
54
+ return CACHE_FILE
55
+
56
+ @classmethod
57
+ def load_cache(cls) -> Optional[Dict[str, Any]]:
58
+ cache_path = cls.get_cache_path()
59
+ if not os.path.exists(cache_path):
60
+ return None
61
+ try:
62
+ with open(cache_path, "r", encoding="utf-8") as f:
63
+ return json.load(f)
64
+ except Exception:
65
+ return None
66
+
67
+ @classmethod
68
+ def save_cache(cls, data: Dict[str, Any]):
69
+ cache_path = cls.get_cache_path()
70
+ try:
71
+ with open(cache_path, "w", encoding="utf-8") as f:
72
+ json.dump(data, f, indent=2)
73
+ except Exception:
74
+ pass
75
+
76
+ @classmethod
77
+ def check_version(
78
+ cls,
79
+ current_version: str = CURRENT_VERSION,
80
+ license_key: str = "",
81
+ force_fetch: bool = False,
82
+ timeout: float = 1.5
83
+ ) -> Dict[str, Any]:
84
+ """
85
+ Retrieves version status. Returns cached result if within TTL,
86
+ otherwise makes a fast network request (< 1.5s timeout).
87
+ Falls back gracefully on network or offline scenarios.
88
+ """
89
+ now = int(time.time())
90
+ cached = cls.load_cache()
91
+
92
+ if not force_fetch and cached:
93
+ checked_at = cached.get("checked_at", 0)
94
+ if now - checked_at < CACHE_TTL:
95
+ return cached
96
+
97
+ # Default payload
98
+ payload = {
99
+ "checked_at": now,
100
+ "client_version": current_version,
101
+ "latest_version": current_version,
102
+ "min_supported_version": "1.1.0",
103
+ "update_available": False,
104
+ "force_update": False,
105
+ "message": f"TokenSafe is up to date (v{current_version}).",
106
+ "update_command": "tokensafe update"
107
+ }
108
+
109
+ try:
110
+ params = f"?version={urllib.parse.quote(current_version)}&license={urllib.parse.quote(license_key)}"
111
+ url = f"{CLOUD_CHECK_URL}{params}"
112
+ req = urllib.request.Request(
113
+ url,
114
+ headers={"User-Agent": f"TokenSafe-CLI/{current_version}"}
115
+ )
116
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
117
+ if resp.status == 200:
118
+ data = json.loads(resp.read().decode("utf-8"))
119
+ data["checked_at"] = now
120
+ cls.save_cache(data)
121
+ return data
122
+ except Exception:
123
+ pass
124
+
125
+ # Stale cache fallback if available
126
+ if cached:
127
+ return cached
128
+ cls.save_cache(payload)
129
+ return payload
130
+
131
+ @classmethod
132
+ def get_banner(cls, current_version: str = CURRENT_VERSION, license_key: str = "") -> Optional[str]:
133
+ """
134
+ Returns a styled ANSI banner string if an update is available or required,
135
+ or None if up to date.
136
+ """
137
+ info = cls.check_version(current_version=current_version, license_key=license_key)
138
+ force_update = info.get("force_update", False)
139
+ update_available = info.get("update_available", False)
140
+ latest = info.get("latest_version", current_version)
141
+ cmd = info.get("update_command", "tokensafe update")
142
+
143
+ if force_update:
144
+ return (
145
+ f"\n{RED}{BOLD}╔════════════════════════════════════════════════════════════════════════╗{RESET}\n"
146
+ f"{RED}{BOLD}║ 🚨 CRITICAL UPDATE REQUIRED: TokenSafe v{current_version} is deprecated! ║{RESET}\n"
147
+ f"{RED}║ Please run {BOLD}{cmd}{RESET}{RED} immediately to continue using TokenSafe. ║{RESET}\n"
148
+ f"{RED}{BOLD}╚════════════════════════════════════════════════════════════════════════╝{RESET}\n"
149
+ )
150
+ elif update_available:
151
+ return (
152
+ f"\n{CYAN}💡 TokenSafe update available: {DIM}v{current_version}{RESET}{CYAN} → {GREEN}{BOLD}v{latest}{RESET}{CYAN}"
153
+ f" (run {BOLD}{cmd}{RESET}{CYAN} to upgrade){RESET}\n"
154
+ )
155
+
156
+ return None