tokensafe 1.2.0 → 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/README.md +52 -10
- package/bin/agy-tokens +4 -0
- package/bin/tokensafe.js +7 -0
- package/hooks/pre_invocation.py +23 -11
- package/package.json +6 -2
- package/plugin.json +1 -1
- package/src/__init__.py +1 -1
- package/src/benchmark.py +68 -9
- package/src/command_sanitizer.py +21 -12
- package/src/dashboard.py +13 -1
- package/src/graph_engine.py +4 -0
- package/src/installer.py +88 -1
- package/src/license_manager.py +157 -23
- package/src/mcp_server.py +24 -6
- package/src/metrics.py +45 -0
- package/src/proxy.py +19 -0
- package/src/version_checker.py +156 -0
- package/src/mailer.py +0 -327
package/src/license_manager.py
CHANGED
|
@@ -17,9 +17,113 @@ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
|
17
17
|
DATA_DIR = os.path.join(PROJECT_ROOT, "data")
|
|
18
18
|
LICENSE_FILE = os.path.join(DATA_DIR, "license.json")
|
|
19
19
|
|
|
20
|
-
# Master
|
|
21
|
-
|
|
22
|
-
|
|
20
|
+
# Master Public Key for client-side offline verification (RFC 8032 Ed25519)
|
|
21
|
+
DEFAULT_ED25519_PUBLIC_KEY = "244ea9d4a20e697578b7b7b31db71613c659678d221300dea1c5a03083bc90e9"
|
|
22
|
+
# Private key for cloud server signing (never distributed to untrusted clients)
|
|
23
|
+
DEFAULT_ED25519_PRIVATE_KEY = os.environ.get("TOKENSAFE_PRIVATE_KEY", "6785d298e2df4c2c305bd4956f124f038d2da5cbda7f4146513645f1733064c0")
|
|
24
|
+
# Rotated HMAC salt for backward compatibility with TS1 legacy licenses
|
|
25
|
+
ROTATED_HMAC_SALT = os.environ.get("TOKENSAFE_HMAC_SALT", "ts-sec-rotated-7b3f9c2d1e0a4f5b6829e1c3a70428e5")
|
|
26
|
+
DEFAULT_SIGNING_SALT = ROTATED_HMAC_SALT
|
|
27
|
+
|
|
28
|
+
# ---------------------------------------------------------------------------
|
|
29
|
+
# Zero-dependency RFC 8032 Ed25519 Implementation with Cryptography Fast-Path
|
|
30
|
+
# ---------------------------------------------------------------------------
|
|
31
|
+
_ED25519_Q = 2**255 - 19
|
|
32
|
+
_ED25519_L = 2**252 + 27742317777372353535851937790883648493
|
|
33
|
+
|
|
34
|
+
def _ed_inv(x: int) -> int:
|
|
35
|
+
return pow(x, _ED25519_Q - 2, _ED25519_Q)
|
|
36
|
+
|
|
37
|
+
_ED_D = -121665 * _ed_inv(121666)
|
|
38
|
+
_ED_I = pow(2, (_ED25519_Q - 1) // 4, _ED25519_Q)
|
|
39
|
+
|
|
40
|
+
def _ed_xrecover(y: int) -> int:
|
|
41
|
+
xx = (y * y - 1) * _ed_inv(_ED_D * y * y + 1)
|
|
42
|
+
x = pow(xx, (_ED25519_Q + 3) // 8, _ED25519_Q)
|
|
43
|
+
if (x * x - xx) % _ED25519_Q != 0:
|
|
44
|
+
x = (x * _ED_I) % _ED25519_Q
|
|
45
|
+
if x % 2 != 0:
|
|
46
|
+
x = _ED25519_Q - x
|
|
47
|
+
return x
|
|
48
|
+
|
|
49
|
+
_ED_BY = 4 * _ed_inv(5)
|
|
50
|
+
_ED_BX = _ed_xrecover(_ED_BY)
|
|
51
|
+
_ED_B = [_ED_BX % _ED25519_Q, _ED_BY % _ED25519_Q]
|
|
52
|
+
|
|
53
|
+
def _ed_add(p1: list, p2: list) -> list:
|
|
54
|
+
x1, y1 = p1[0], p1[1]
|
|
55
|
+
x2, y2 = p2[0], p2[1]
|
|
56
|
+
x3 = (x1 * y2 + x2 * y1) * _ed_inv(1 + _ED_D * x1 * x2 * y1 * y2)
|
|
57
|
+
y3 = (y1 * y2 + x1 * x2) * _ed_inv(1 - _ED_D * x1 * x2 * y1 * y2)
|
|
58
|
+
return [x3 % _ED25519_Q, y3 % _ED25519_Q]
|
|
59
|
+
|
|
60
|
+
def _ed_scalarmult(pt: list, e: int) -> list:
|
|
61
|
+
if e == 0:
|
|
62
|
+
return [0, 1]
|
|
63
|
+
q = _ed_scalarmult(pt, e // 2)
|
|
64
|
+
q = _ed_add(q, q)
|
|
65
|
+
if e & 1:
|
|
66
|
+
q = _ed_add(q, pt)
|
|
67
|
+
return q
|
|
68
|
+
|
|
69
|
+
def _ed_encodepoint(pt: list) -> bytes:
|
|
70
|
+
x, y = pt[0], pt[1]
|
|
71
|
+
bits = [(y >> i) & 1 for i in range(255)] + [x & 1]
|
|
72
|
+
return bytes([sum([bits[i * 8 + j] << j for j in range(8)]) for i in range(32)])
|
|
73
|
+
|
|
74
|
+
def _ed_bit(h: bytes, i: int) -> int:
|
|
75
|
+
return (h[i // 8] >> (i % 8)) & 1
|
|
76
|
+
|
|
77
|
+
def _ed_decodepoint(s: bytes) -> Optional[list]:
|
|
78
|
+
y = sum(2**i * _ed_bit(s, i) for i in range(0, 255))
|
|
79
|
+
x = _ed_xrecover(y)
|
|
80
|
+
if x & 1 != _ed_bit(s, 255):
|
|
81
|
+
x = _ED25519_Q - x
|
|
82
|
+
pt = [x, y]
|
|
83
|
+
if (-x * x + y * y - 1 - _ED_D * x * x * y * y) % _ED25519_Q != 0:
|
|
84
|
+
return None
|
|
85
|
+
return pt
|
|
86
|
+
|
|
87
|
+
def _ed25519_sign_bytes(msg: bytes, priv_bytes: bytes, pub_bytes: bytes) -> bytes:
|
|
88
|
+
try:
|
|
89
|
+
from cryptography.hazmat.primitives.asymmetric import ed25519
|
|
90
|
+
priv_obj = ed25519.Ed25519PrivateKey.from_private_bytes(priv_bytes)
|
|
91
|
+
return priv_obj.sign(msg)
|
|
92
|
+
except Exception:
|
|
93
|
+
h = hashlib.sha512(priv_bytes).digest()
|
|
94
|
+
a = 2**254 + sum(2**i * _ed_bit(h, i) for i in range(3, 254))
|
|
95
|
+
r = int.from_bytes(hashlib.sha512(h[32:] + msg).digest(), "little")
|
|
96
|
+
r_pt = _ed_scalarmult(_ED_B, r)
|
|
97
|
+
r_bytes = _ed_encodepoint(r_pt)
|
|
98
|
+
k = int.from_bytes(hashlib.sha512(r_bytes + pub_bytes + msg).digest(), "little")
|
|
99
|
+
s = (r + k * a) % _ED25519_L
|
|
100
|
+
return r_bytes + int.to_bytes(s, 32, "little")
|
|
101
|
+
|
|
102
|
+
def _ed25519_verify_bytes(sig: bytes, msg: bytes, pub_bytes: bytes) -> bool:
|
|
103
|
+
if len(sig) != 64 or len(pub_bytes) != 32:
|
|
104
|
+
return False
|
|
105
|
+
try:
|
|
106
|
+
from cryptography.hazmat.primitives.asymmetric import ed25519
|
|
107
|
+
pub_obj = ed25519.Ed25519PublicKey.from_public_bytes(pub_bytes)
|
|
108
|
+
pub_obj.verify(sig, msg)
|
|
109
|
+
return True
|
|
110
|
+
except Exception:
|
|
111
|
+
pass
|
|
112
|
+
try:
|
|
113
|
+
r_pt = _ed_decodepoint(sig[:32])
|
|
114
|
+
a_pt = _ed_decodepoint(pub_bytes)
|
|
115
|
+
if r_pt is None or a_pt is None:
|
|
116
|
+
return False
|
|
117
|
+
s = int.from_bytes(sig[32:], "little")
|
|
118
|
+
if s >= _ED25519_L:
|
|
119
|
+
return False
|
|
120
|
+
h = int.from_bytes(hashlib.sha512(sig[:32] + pub_bytes + msg).digest(), "little")
|
|
121
|
+
v1 = _ed_scalarmult(_ED_B, s)
|
|
122
|
+
v2 = _ed_add(r_pt, _ed_scalarmult(a_pt, h))
|
|
123
|
+
return v1 == v2
|
|
124
|
+
except Exception:
|
|
125
|
+
return False
|
|
126
|
+
|
|
23
127
|
|
|
24
128
|
class LicenseManager:
|
|
25
129
|
"""Manages TokenSafe subscription tiers, offline signature verification, and 7-day trials."""
|
|
@@ -37,18 +141,17 @@ class LicenseManager:
|
|
|
37
141
|
tier: str,
|
|
38
142
|
email: str,
|
|
39
143
|
duration_days: int = 30,
|
|
40
|
-
signing_key: str =
|
|
41
|
-
is_trial: bool = False
|
|
144
|
+
signing_key: Optional[str] = None,
|
|
145
|
+
is_trial: bool = False,
|
|
146
|
+
version: int = 2
|
|
42
147
|
) -> str:
|
|
43
148
|
"""
|
|
44
149
|
Generates a tamper-proof cryptographically signed license key.
|
|
45
|
-
Format:
|
|
150
|
+
- Version 2 (Default): Asymmetric Ed25519 signed (Format: TS2.<b64_payload>.<b64_sig>)
|
|
151
|
+
- Version 1: Legacy HMAC-SHA256 signed (Format: TS1.<b64_payload>.<sig_hex>)
|
|
46
152
|
"""
|
|
47
153
|
now = int(time.time())
|
|
48
|
-
if duration_days == 0
|
|
49
|
-
expires_at = 0 # Lifetime
|
|
50
|
-
else:
|
|
51
|
-
expires_at = now + (duration_days * 86400)
|
|
154
|
+
expires_at = 0 if duration_days == 0 else now + (duration_days * 86400)
|
|
52
155
|
|
|
53
156
|
payload = {
|
|
54
157
|
"tier": tier.lower(),
|
|
@@ -56,23 +159,36 @@ class LicenseManager:
|
|
|
56
159
|
"issued_at": now,
|
|
57
160
|
"expires_at": expires_at,
|
|
58
161
|
"trial": is_trial,
|
|
59
|
-
"v":
|
|
162
|
+
"v": version
|
|
60
163
|
}
|
|
61
164
|
|
|
62
165
|
payload_bytes = json.dumps(payload, sort_keys=True, separators=(',', ':')).encode("utf-8")
|
|
63
166
|
payload_b64 = base64.urlsafe_b64encode(payload_bytes).decode("ascii").rstrip("=")
|
|
64
167
|
|
|
65
|
-
|
|
168
|
+
if version == 2:
|
|
169
|
+
priv_hex = signing_key or DEFAULT_ED25519_PRIVATE_KEY
|
|
170
|
+
priv_bytes = bytes.fromhex(priv_hex)
|
|
171
|
+
pub_bytes = bytes.fromhex(DEFAULT_ED25519_PUBLIC_KEY)
|
|
172
|
+
sig_raw = _ed25519_sign_bytes(payload_bytes, priv_bytes, pub_bytes)
|
|
173
|
+
sig_b64 = base64.urlsafe_b64encode(sig_raw).decode("ascii").rstrip("=")
|
|
174
|
+
return f"TS2.{payload_b64}.{sig_b64}"
|
|
175
|
+
|
|
176
|
+
# Fallback to TS1 HMAC format
|
|
177
|
+
hmac_key = signing_key or ROTATED_HMAC_SALT
|
|
178
|
+
sig = hmac.new(hmac_key.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()[:32]
|
|
66
179
|
return f"TS1.{payload_b64}.{sig}"
|
|
67
180
|
|
|
68
181
|
@classmethod
|
|
69
182
|
def validate_license(
|
|
70
183
|
cls,
|
|
71
184
|
license_key: str,
|
|
72
|
-
|
|
185
|
+
public_key: Optional[str] = None
|
|
73
186
|
) -> Tuple[bool, Dict[str, Any], str]:
|
|
74
187
|
"""
|
|
75
188
|
Validates the license key signature and expiration.
|
|
189
|
+
Supports:
|
|
190
|
+
- TS2: Asymmetric Ed25519 verification using public key (Offline-safe, impossible to forge)
|
|
191
|
+
- TS1: Legacy HMAC-SHA256 verification with rotated salt
|
|
76
192
|
Returns (is_valid, payload_dict, reason_str).
|
|
77
193
|
"""
|
|
78
194
|
if not license_key or not isinstance(license_key, str):
|
|
@@ -80,22 +196,40 @@ class LicenseManager:
|
|
|
80
196
|
|
|
81
197
|
license_key = license_key.strip()
|
|
82
198
|
parts = license_key.split(".")
|
|
83
|
-
if len(parts) != 3 or parts[0]
|
|
84
|
-
return False, {}, "Invalid license key format (must start with TS1.)"
|
|
199
|
+
if len(parts) != 3 or parts[0] not in ("TS1", "TS2"):
|
|
200
|
+
return False, {}, "Invalid license key format (must start with TS2. or TS1.)"
|
|
85
201
|
|
|
86
|
-
payload_b64,
|
|
87
|
-
|
|
88
|
-
padded = payload_b64 + "=" * (-len(payload_b64) % 4)
|
|
202
|
+
schema_ver, payload_b64, sig_part = parts[0], parts[1], parts[2]
|
|
203
|
+
padded_payload = payload_b64 + "=" * (-len(payload_b64) % 4)
|
|
89
204
|
try:
|
|
90
|
-
payload_bytes = base64.urlsafe_b64decode(
|
|
205
|
+
payload_bytes = base64.urlsafe_b64decode(padded_payload.encode("ascii"))
|
|
91
206
|
payload = json.loads(payload_bytes.decode("utf-8"))
|
|
92
207
|
except Exception as e:
|
|
93
208
|
return False, {}, f"Corrupted license payload: {str(e)}"
|
|
94
209
|
|
|
95
|
-
#
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
210
|
+
# 1. Asymmetric Ed25519 Verification (TS2)
|
|
211
|
+
if schema_ver == "TS2":
|
|
212
|
+
pub_hex = public_key or DEFAULT_ED25519_PUBLIC_KEY
|
|
213
|
+
try:
|
|
214
|
+
pub_bytes = bytes.fromhex(pub_hex)
|
|
215
|
+
padded_sig = sig_part + "=" * (-len(sig_part) % 4)
|
|
216
|
+
sig_bytes = base64.urlsafe_b64decode(padded_sig.encode("ascii"))
|
|
217
|
+
except Exception:
|
|
218
|
+
return False, {}, "Invalid signature encoding"
|
|
219
|
+
|
|
220
|
+
if not _ed25519_verify_bytes(sig_bytes, payload_bytes, pub_bytes):
|
|
221
|
+
return False, {}, "Invalid digital signature: license key has been tampered with or is counterfeit"
|
|
222
|
+
|
|
223
|
+
# 2. Legacy TS1 Verification
|
|
224
|
+
else:
|
|
225
|
+
hmac_key = public_key or ROTATED_HMAC_SALT
|
|
226
|
+
expected_sig = hmac.new(hmac_key.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()[:32]
|
|
227
|
+
if not hmac.compare_digest(sig_part, expected_sig):
|
|
228
|
+
# Try fallback default salt if user had old key
|
|
229
|
+
old_salt = "ts-core-sec-9a4f8b2c1e7d3a506198fbcde40231aa"
|
|
230
|
+
fallback_sig = hmac.new(old_salt.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()[:32]
|
|
231
|
+
if not hmac.compare_digest(sig_part, fallback_sig):
|
|
232
|
+
return False, {}, "Invalid signature: legacy license key has been tampered with"
|
|
99
233
|
|
|
100
234
|
# Check expiration
|
|
101
235
|
now = int(time.time())
|
package/src/mcp_server.py
CHANGED
|
@@ -188,8 +188,15 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
188
188
|
return {"content": [{"type": "text", "text": dashboard.render_markdown()}]}
|
|
189
189
|
|
|
190
190
|
elif name == "get_architecture_graph":
|
|
191
|
-
target = args.get("project_path") or os.getcwd()
|
|
192
|
-
|
|
191
|
+
target = args.get("project_path") or args.get("root_dir") or args.get("path") or args.get("directory") or os.getcwd()
|
|
192
|
+
target_abs = os.path.abspath(target)
|
|
193
|
+
system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
|
|
194
|
+
if target_abs in system_roots:
|
|
195
|
+
return {
|
|
196
|
+
"isError": True,
|
|
197
|
+
"content": [{"type": "text", "text": "Error: Invalid or root project_path. Please specify an explicit 'project_path' pointing to your project directory."}]
|
|
198
|
+
}
|
|
199
|
+
graph = GraphEngine.get_instance(target_abs)
|
|
193
200
|
god_nodes = graph.get_god_nodes(7)
|
|
194
201
|
banner = graph.format_topology_banner()
|
|
195
202
|
payload = {
|
|
@@ -199,7 +206,9 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
199
206
|
"total_symbols": len(graph.symbols),
|
|
200
207
|
"god_nodes": god_nodes
|
|
201
208
|
}
|
|
202
|
-
|
|
209
|
+
# Cap estimated crawl tokens to max 50,000 to prevent runaway spikes on large/root dirs
|
|
210
|
+
capped_files = min(80, len(graph.file_symbols))
|
|
211
|
+
est_crawl_tokens = min(50000, max(5000, capped_files * 600))
|
|
203
212
|
topo_tokens = 250
|
|
204
213
|
tracker.record_event(
|
|
205
214
|
session_id="mcp_session",
|
|
@@ -211,11 +220,20 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
211
220
|
return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
|
|
212
221
|
|
|
213
222
|
elif name == "get_api_surface":
|
|
214
|
-
target = args.get("project_path") or os.getcwd()
|
|
215
|
-
|
|
223
|
+
target = args.get("project_path") or args.get("root_dir") or args.get("path") or args.get("directory") or os.getcwd()
|
|
224
|
+
target_abs = os.path.abspath(target)
|
|
225
|
+
system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
|
|
226
|
+
if target_abs in system_roots:
|
|
227
|
+
return {
|
|
228
|
+
"isError": True,
|
|
229
|
+
"content": [{"type": "text", "text": "Error: Invalid or root project_path. Please specify an explicit 'project_path' pointing to your project directory."}]
|
|
230
|
+
}
|
|
231
|
+
graph = GraphEngine.get_instance(target_abs)
|
|
216
232
|
surface_md = graph.generate_api_surface()
|
|
217
233
|
surface_tokens = count_tokens(surface_md)
|
|
218
|
-
|
|
234
|
+
# Cap estimated crawl tokens to max 60,000
|
|
235
|
+
capped_files = min(100, len(graph.file_symbols))
|
|
236
|
+
est_orig_tokens = min(60000, max(10000, capped_files * 600))
|
|
219
237
|
tracker.record_event(
|
|
220
238
|
session_id="mcp_session",
|
|
221
239
|
event_type="GRAPH_TOPOLOGY",
|
package/src/metrics.py
CHANGED
|
@@ -174,6 +174,51 @@ class MetricsTracker:
|
|
|
174
174
|
events.append(ev)
|
|
175
175
|
return events
|
|
176
176
|
|
|
177
|
+
def get_last_event(self, session_id: str, event_type: str) -> Optional[Dict[str, Any]]:
|
|
178
|
+
"""Returns the most recent event of a given type for a session."""
|
|
179
|
+
with self._get_connection() as conn:
|
|
180
|
+
cursor = conn.cursor()
|
|
181
|
+
cursor.execute("""
|
|
182
|
+
SELECT id, session_id, timestamp, event_type, original_tokens,
|
|
183
|
+
optimized_tokens, saved_tokens, reduction_pct, est_usd_saved, details
|
|
184
|
+
FROM events
|
|
185
|
+
WHERE session_id = ? AND event_type = ?
|
|
186
|
+
ORDER BY id DESC
|
|
187
|
+
LIMIT 1
|
|
188
|
+
""", (session_id, event_type))
|
|
189
|
+
row = cursor.fetchone()
|
|
190
|
+
if not row:
|
|
191
|
+
return None
|
|
192
|
+
res = dict(row)
|
|
193
|
+
try:
|
|
194
|
+
res["details"] = json.loads(res["details"])
|
|
195
|
+
except Exception:
|
|
196
|
+
pass
|
|
197
|
+
return res
|
|
198
|
+
|
|
199
|
+
def recalculate_sessions(self):
|
|
200
|
+
"""Recalculates sessions table aggregates directly from events table."""
|
|
201
|
+
with self._get_connection() as conn:
|
|
202
|
+
cursor = conn.cursor()
|
|
203
|
+
cursor.execute("DELETE FROM sessions")
|
|
204
|
+
cursor.execute("""
|
|
205
|
+
INSERT INTO sessions (
|
|
206
|
+
session_id, created_at, last_updated,
|
|
207
|
+
total_original_tokens, total_optimized_tokens,
|
|
208
|
+
total_saved_tokens, total_usd_saved
|
|
209
|
+
)
|
|
210
|
+
SELECT
|
|
211
|
+
session_id,
|
|
212
|
+
MIN(timestamp) as created_at,
|
|
213
|
+
MAX(timestamp) as last_updated,
|
|
214
|
+
COALESCE(SUM(original_tokens), 0) as total_original_tokens,
|
|
215
|
+
COALESCE(SUM(optimized_tokens), 0) as total_optimized_tokens,
|
|
216
|
+
COALESCE(SUM(saved_tokens), 0) as total_saved_tokens,
|
|
217
|
+
COALESCE(SUM(est_usd_saved), 0.0) as total_usd_saved
|
|
218
|
+
FROM events
|
|
219
|
+
GROUP BY session_id
|
|
220
|
+
""")
|
|
221
|
+
|
|
177
222
|
def reset(self):
|
|
178
223
|
"""Resets all metrics data."""
|
|
179
224
|
with self._get_connection() as conn:
|
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:
|
|
@@ -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
|