tokensafe 2.4.2 → 2.5.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.
@@ -11,8 +11,10 @@ import time
11
11
  import hmac
12
12
  import hashlib
13
13
  import base64
14
+ import platform
15
+ import uuid
14
16
  import threading
15
- from typing import Dict, Any, Tuple, Optional
17
+ from typing import Dict, Any, Tuple, Optional, List
16
18
 
17
19
  from src.paths import resolve_data_dir
18
20
 
@@ -21,15 +23,19 @@ DATA_DIR = resolve_data_dir()
21
23
  LICENSE_FILE = os.path.join(DATA_DIR, "license.json")
22
24
  GLOBAL_DATA_DIR = os.path.expanduser("~/.tokensafe")
23
25
  GLOBAL_LICENSE_FILE = os.path.join(GLOBAL_DATA_DIR, "license.json")
24
-
25
- # Master Public Key for client-side offline verification (RFC 8032 Ed25519)
26
- DEFAULT_ED25519_PUBLIC_KEY = os.environ.get("TOKENSAFE_PUBLIC_KEY", "3911e2ffe5ad07ee23be392b88f238af302f9d3a0bf51881de8b5e0e6af71430")
27
- # Pre-rotation public keys accepted for backwards compatibility
28
- LEGACY_ED25519_PUBLIC_KEYS = ("8a2c9d550180ab5b00a06174cb6aecfd712740c59d0bdcff66a56515348c855e",)
26
+ _DEFAULT_LICENSE_FILE = LICENSE_FILE
27
+ _DEFAULT_GLOBAL_LICENSE_FILE = GLOBAL_LICENSE_FILE
28
+
29
+ # Master Public Key for client-side offline verification (RFC 8032 Ed25519).
30
+ # Hardcoded intentionally so environment overrides cannot substitute an attacker key.
31
+ EMBEDDED_ED25519_PUBLIC_KEY = "3911e2ffe5ad07ee23be392b88f238af302f9d3a0bf51881de8b5e0e6af71430"
32
+ DEFAULT_ED25519_PUBLIC_KEY = EMBEDDED_ED25519_PUBLIC_KEY
33
+ # Retired keys (never include unit-test public keys here)
34
+ LEGACY_ED25519_PUBLIC_KEYS: Tuple[str, ...] = ()
29
35
  # Private key for cloud server signing (never distributed to client, loaded strictly from environment)
30
36
  DEFAULT_ED25519_PRIVATE_KEY = os.environ.get("TOKENSAFE_PRIVATE_KEY", "")
31
- # Rotated HMAC salt for backward compatibility with TS1 legacy licenses
32
- ROTATED_HMAC_SALT = os.environ.get("TOKENSAFE_HMAC_SALT", "ts-sec-rotated-7b3f9c2d1e0a4f5b6829e1c3a70428e5")
37
+ # Server-only HMAC salt for legacy TS1 migration (never hardcoded in clients)
38
+ ROTATED_HMAC_SALT = os.environ.get("TOKENSAFE_HMAC_SALT", "")
33
39
  DEFAULT_SIGNING_SALT = ROTATED_HMAC_SALT
34
40
 
35
41
  # ---------------------------------------------------------------------------
@@ -91,7 +97,7 @@ def _ed_decodepoint(s: bytes) -> Optional[list]:
91
97
  return None
92
98
  return pt
93
99
 
94
- def _ed25519_sign_bytes(msg: bytes, priv_bytes: bytes, pub_bytes: bytes) -> bytes:
100
+ def _ed25519_sign_bytes(msg: bytes, priv_bytes: bytes, pub_bytes: bytes = b"") -> bytes:
95
101
  try:
96
102
  from cryptography.hazmat.primitives.asymmetric import ed25519
97
103
  priv_obj = ed25519.Ed25519PrivateKey.from_private_bytes(priv_bytes)
@@ -99,10 +105,12 @@ def _ed25519_sign_bytes(msg: bytes, priv_bytes: bytes, pub_bytes: bytes) -> byte
99
105
  except Exception:
100
106
  h = hashlib.sha512(priv_bytes).digest()
101
107
  a = 2**254 + sum(2**i * _ed_bit(h, i) for i in range(3, 254))
108
+ # Always derive the RFC 8032 public point from priv_bytes so env/global overrides cannot desync H(R||A||M).
109
+ derived_pub = _ed_encodepoint(_ed_scalarmult(_ED_B, a))
102
110
  r = int.from_bytes(hashlib.sha512(h[32:] + msg).digest(), "little")
103
111
  r_pt = _ed_scalarmult(_ED_B, r)
104
112
  r_bytes = _ed_encodepoint(r_pt)
105
- k = int.from_bytes(hashlib.sha512(r_bytes + pub_bytes + msg).digest(), "little")
113
+ k = int.from_bytes(hashlib.sha512(r_bytes + derived_pub + msg).digest(), "little")
106
114
  s = (r + k * a) % _ED25519_L
107
115
  return r_bytes + int.to_bytes(s, 32, "little")
108
116
 
@@ -143,6 +151,7 @@ class LicenseManager:
143
151
  _VALIDATION_CACHE_LOCK = threading.Lock()
144
152
  _VALIDATION_CACHE_TTL = 3600.0 # 1 hour
145
153
  _VALIDATION_CACHE_MAX = 64
154
+ _QUOTA_TURN_COUNTERS: Dict[str, int] = {}
146
155
 
147
156
  TIERS = {
148
157
  "free": {"max_tokens_monthly": 500_000, "deepseek_cloud": False, "team_analytics": False},
@@ -151,6 +160,12 @@ class LicenseManager:
151
160
  "enterprise": {"max_tokens_monthly": None, "deepseek_cloud": True, "team_analytics": True, "self_hosted": True}
152
161
  }
153
162
 
163
+ @classmethod
164
+ def get_machine_fingerprint(cls) -> str:
165
+ """One-way anonymized machine identifier for server-side free-tier quota continuity."""
166
+ raw = f"ts:{platform.system()}:{platform.node()}:{uuid.getnode()}:{os.path.expanduser('~')}"
167
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32]
168
+
154
169
  @classmethod
155
170
  def generate_license(
156
171
  cls,
@@ -198,8 +213,10 @@ class LicenseManager:
198
213
  sig_b64 = base64.urlsafe_b64encode(sig_raw).decode("ascii").rstrip("=")
199
214
  return f"TS2.{payload_b64}.{sig_b64}"
200
215
 
201
- # Fallback to TS1 HMAC format
202
- hmac_key = signing_key or ROTATED_HMAC_SALT
216
+ # Fallback to TS1 HMAC format (server/test explicit signing_key only)
217
+ hmac_key = signing_key or ROTATED_HMAC_SALT or os.environ.get("TOKENSAFE_HMAC_SALT", "")
218
+ if not hmac_key:
219
+ raise ValueError("TOKENSAFE_HMAC_SALT is required to sign legacy TS1 licenses.")
203
220
  sig = hmac.new(hmac_key.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()[:32]
204
221
  return f"TS1.{payload_b64}.{sig}"
205
222
 
@@ -207,13 +224,14 @@ class LicenseManager:
207
224
  def validate_license(
208
225
  cls,
209
226
  license_key: str,
210
- public_key: Optional[str] = None
227
+ public_key: Optional[str] = None,
228
+ allow_legacy_ts1: bool = False,
211
229
  ) -> Tuple[bool, Dict[str, Any], str]:
212
230
  """
213
231
  Validates the license key signature and expiration.
214
232
  Supports:
215
- - TS2: Asymmetric Ed25519 verification using public key (Offline-safe, impossible to forge)
216
- - TS1: Legacy HMAC-SHA256 verification with rotated salt
233
+ - TS2: Asymmetric Ed25519 verification using embedded public key (Offline-safe, impossible to forge)
234
+ - TS1: Legacy HMAC-SHA256 rejected offline (server-side migration only when allow_legacy_ts1=True)
217
235
  Returns (is_valid, payload_dict, reason_str).
218
236
  """
219
237
  if not license_key or not isinstance(license_key, str):
@@ -224,7 +242,8 @@ class LicenseManager:
224
242
  # Fast path: recently verified signature (avoids ~0.6s pure-Python Ed25519
225
243
  # verification on every hook invocation when the 'cryptography' package is absent)
226
244
  now = time.time()
227
- cache_key = f"{public_key or ''}|{license_key}"
245
+ effective_pub = public_key or DEFAULT_ED25519_PUBLIC_KEY
246
+ cache_key = f"{effective_pub}|{int(bool(allow_legacy_ts1))}|{license_key}"
228
247
  with cls._VALIDATION_CACHE_LOCK:
229
248
  cached = cls._VALIDATION_CACHE.get(cache_key)
230
249
  if cached and now < cached[1]:
@@ -244,7 +263,7 @@ class LicenseManager:
244
263
 
245
264
  # 1. Asymmetric Ed25519 Verification (TS2)
246
265
  if schema_ver == "TS2":
247
- pub_hex = public_key or os.environ.get("TOKENSAFE_PUBLIC_KEY") or DEFAULT_ED25519_PUBLIC_KEY
266
+ pub_hex = public_key or DEFAULT_ED25519_PUBLIC_KEY
248
267
  try:
249
268
  pub_bytes = bytes.fromhex(pub_hex)
250
269
  padded_sig = sig_part + "=" * (-len(sig_part) % 4)
@@ -265,16 +284,20 @@ class LicenseManager:
265
284
  if not verified:
266
285
  return False, {}, "Invalid digital signature: license key has been tampered with or is counterfeit"
267
286
 
268
- # 2. Legacy TS1 Verification
287
+ # 2. Legacy TS1 Verification (disabled offline to eliminate public-salt forgery)
269
288
  else:
270
- hmac_key = public_key or ROTATED_HMAC_SALT
289
+ if not allow_legacy_ts1:
290
+ return (
291
+ False,
292
+ {},
293
+ "Legacy TS1 offline verification is disabled; reconnect to upgrade to a TS2 Ed25519 license.",
294
+ )
295
+ hmac_key = public_key or ROTATED_HMAC_SALT or os.environ.get("TOKENSAFE_HMAC_SALT", "")
296
+ if not hmac_key:
297
+ return False, {}, "Legacy TS1 verification requires server-side HMAC salt configuration"
271
298
  expected_sig = hmac.new(hmac_key.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()[:32]
272
299
  if not hmac.compare_digest(sig_part, expected_sig):
273
- # Try fallback default salt if user had old key
274
- old_salt = "ts-core-sec-9a4f8b2c1e7d3a506198fbcde40231aa"
275
- fallback_sig = hmac.new(old_salt.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()[:32]
276
- if not hmac.compare_digest(sig_part, fallback_sig):
277
- return False, {}, "Invalid signature: legacy license key has been tampered with"
300
+ return False, {}, "Invalid signature: legacy license key has been tampered with"
278
301
 
279
302
  # Check expiration
280
303
  now = int(time.time())
@@ -297,40 +320,81 @@ class LicenseManager:
297
320
  return True, payload, "License is active and valid"
298
321
 
299
322
  @classmethod
300
- def get_active_license(cls) -> Tuple[str, Dict[str, Any]]:
301
- """Retrieves active license from env or data/license.json, falling back to free tier."""
302
- key = os.environ.get("TOKENSAFE_LICENSE_KEY", "").strip()
303
- if not key and os.path.exists(LICENSE_FILE):
323
+ def _candidate_license_files(cls) -> List[str]:
324
+ """Returns license.json paths to inspect, honoring explicit TOKENSAFE_DATA_DIR and test patches."""
325
+ explicit_dir = os.environ.get("TOKENSAFE_DATA_DIR", "").strip()
326
+ if LICENSE_FILE != _DEFAULT_LICENSE_FILE:
327
+ paths = [LICENSE_FILE]
328
+ if GLOBAL_LICENSE_FILE != _DEFAULT_GLOBAL_LICENSE_FILE:
329
+ paths.append(GLOBAL_LICENSE_FILE)
330
+ elif explicit_dir:
331
+ paths = [os.path.join(explicit_dir, "license.json")]
332
+ else:
333
+ paths = [LICENSE_FILE, GLOBAL_LICENSE_FILE]
334
+
335
+ seen = set()
336
+ unique: List[str] = []
337
+ for p in paths:
338
+ ap = os.path.abspath(p)
339
+ if ap not in seen:
340
+ seen.add(ap)
341
+ unique.append(p)
342
+ return unique
343
+
344
+ @classmethod
345
+ def _resolve_active_license_record(cls) -> Tuple[Optional[Tuple[str, Dict[str, Any]]], str]:
346
+ """Selects the freshest valid license across env and candidate files."""
347
+ env_key = os.environ.get("TOKENSAFE_LICENSE_KEY", "").strip()
348
+ if env_key:
349
+ valid, payload, _ = cls.validate_license(env_key)
350
+ return ((env_key, payload) if valid else None), env_key
351
+
352
+ best_valid: Optional[Tuple[Tuple[int, int, float], str, Dict[str, Any]]] = None
353
+ best_raw: Optional[Tuple[Tuple[int, float], str]] = None
354
+
355
+ for path in cls._candidate_license_files():
356
+ if not os.path.exists(path):
357
+ continue
304
358
  try:
305
- with open(LICENSE_FILE, "r", encoding="utf-8") as f:
359
+ with open(path, "r", encoding="utf-8") as f:
306
360
  data = json.load(f)
307
- key = data.get("license_key", "").strip()
361
+ candidate = str(data.get("license_key", "")).strip()
362
+ if not candidate:
363
+ continue
364
+ saved_at = int(data.get("saved_at") or 0)
365
+ mtime = os.path.getmtime(path)
308
366
  except Exception:
309
- pass
367
+ continue
310
368
 
311
- if key:
312
- valid, payload, msg = cls.validate_license(key)
369
+ raw_rank = (saved_at, mtime)
370
+ if best_raw is None or raw_rank > best_raw[0]:
371
+ best_raw = (raw_rank, candidate)
372
+
373
+ valid, payload, _ = cls.validate_license(candidate)
313
374
  if valid:
314
- return payload.get("tier", "solo"), payload
375
+ issued_at = int(payload.get("issued_at") or 0)
376
+ valid_rank = (saved_at, issued_at, mtime)
377
+ if best_valid is None or valid_rank > best_valid[0]:
378
+ best_valid = (valid_rank, candidate, payload)
379
+
380
+ if best_valid is not None:
381
+ return (best_valid[1], best_valid[2]), best_valid[1]
382
+ return None, (best_raw[1] if best_raw is not None else "")
383
+
384
+ @classmethod
385
+ def get_active_license(cls) -> Tuple[str, Dict[str, Any]]:
386
+ """Retrieves active license from env or persistent license.json files, falling back to free tier."""
387
+ resolved, _ = cls._resolve_active_license_record()
388
+ if resolved is not None:
389
+ _, payload = resolved
390
+ return payload.get("tier", "solo"), payload
315
391
 
316
392
  return "free", {"tier": "free", "max_tokens_monthly": 500_000}
317
393
 
318
394
  @classmethod
319
395
  def get_active_license_key(cls) -> str:
320
- """Retrieves active raw license key string from env or persistent license.json files."""
321
- key = os.environ.get("TOKENSAFE_LICENSE_KEY", "").strip()
322
- if not key:
323
- for p in (LICENSE_FILE, GLOBAL_LICENSE_FILE):
324
- if os.path.exists(p):
325
- try:
326
- with open(p, "r", encoding="utf-8") as f:
327
- data = json.load(f)
328
- candidate = data.get("license_key", "").strip()
329
- if candidate:
330
- key = candidate
331
- break
332
- except Exception:
333
- pass
396
+ """Retrieves the freshest active raw license key string from env or persistent license.json files."""
397
+ _, key = cls._resolve_active_license_record()
334
398
  return key
335
399
 
336
400
  @classmethod
@@ -349,9 +413,11 @@ class LicenseManager:
349
413
  "saved_at": int(time.time())
350
414
  }
351
415
 
352
- for target_dir, target_file in ((DATA_DIR, LICENSE_FILE), (GLOBAL_DATA_DIR, GLOBAL_LICENSE_FILE)):
416
+ for target_file in cls._candidate_license_files():
417
+ target_dir = os.path.dirname(target_file)
353
418
  try:
354
- os.makedirs(target_dir, exist_ok=True)
419
+ if target_dir:
420
+ os.makedirs(target_dir, exist_ok=True)
355
421
  with open(target_file, "w", encoding="utf-8") as f:
356
422
  json.dump(record, f, indent=2)
357
423
  except Exception:
@@ -403,14 +469,16 @@ class LicenseManager:
403
469
  if exceeded:
404
470
  warning = (
405
471
  f"⚡ **TokenSafe Quota Alert**: Community Edition limit reached "
406
- f"({monthly_saved:,}/{max_tokens:,} tokens saved this month). "
407
- f"Advanced optimization is throttled. Upgrade to Solo for unlimited optimization: `tokensafe activate <key>` or visit https://tokensafe.dev."
472
+ f"({monthly_saved:,}/{max_tokens:,} measured tokens saved this month). "
473
+ f"Graph/signature AST slicing, pointer dedup, history compaction & KV-cache prefix locking are paused "
474
+ f"(Security Guard stays active). Upgrade to Solo ($9/mo) or 7-Day Team Trial: "
475
+ f"`tokensafe activate <key>` or visit https://tokensafe.dev/#pricing"
408
476
  )
409
477
  elif monthly_saved >= int(max_tokens * 0.85):
410
478
  warning = (
411
479
  f"⚡ **TokenSafe Quota Notice**: Community Edition is at {int(monthly_saved / max_tokens * 100)}% of monthly limit "
412
- f"({monthly_saved:,}/{max_tokens:,} tokens). "
413
- f"Upgrade to Solo for unlimited optimization: `tokensafe activate <key>` or https://tokensafe.dev."
480
+ f"({monthly_saved:,}/{max_tokens:,} measured tokens). "
481
+ f"Upgrade to Solo for unlimited optimization: `tokensafe activate <key>` or https://tokensafe.dev/#pricing"
414
482
  )
415
483
 
416
484
  return {
@@ -418,5 +486,46 @@ class LicenseManager:
418
486
  "is_quota_exceeded": exceeded,
419
487
  "monthly_limit": max_tokens,
420
488
  "monthly_saved": monthly_saved,
489
+ "remaining_tokens": max(0, max_tokens - monthly_saved),
421
490
  "warning": warning
422
491
  }
492
+
493
+ @classmethod
494
+ def should_emit_quota_banner(
495
+ cls,
496
+ tracker: Optional[Any] = None,
497
+ session_id: str = "default_session",
498
+ every_n_turns: int = 5,
499
+ ) -> bool:
500
+ """Returns True on turn #1 of quota exceedance per session and every N turns thereafter."""
501
+ sid = session_id or "default_session"
502
+ n = max(1, int(every_n_turns or 5))
503
+ if tracker is not None and hasattr(tracker, "_get_connection"):
504
+ try:
505
+ with tracker._get_connection() as conn:
506
+ conn.execute("""
507
+ CREATE TABLE IF NOT EXISTS quota_banner_state (
508
+ session_id TEXT PRIMARY KEY,
509
+ turns INTEGER NOT NULL DEFAULT 0,
510
+ updated_at INTEGER NOT NULL
511
+ )
512
+ """)
513
+ row = conn.execute(
514
+ "SELECT turns FROM quota_banner_state WHERE session_id = ?",
515
+ (sid,),
516
+ ).fetchone()
517
+ turn_no = (int(row["turns"]) if row else 0) + 1
518
+ conn.execute("""
519
+ INSERT INTO quota_banner_state (session_id, turns, updated_at)
520
+ VALUES (?, ?, ?)
521
+ ON CONFLICT(session_id) DO UPDATE SET
522
+ turns = excluded.turns,
523
+ updated_at = excluded.updated_at
524
+ """, (sid, turn_no, int(time.time())))
525
+ return turn_no == 1 or (turn_no % n == 0)
526
+ except Exception:
527
+ pass
528
+ with cls._VALIDATION_CACHE_LOCK:
529
+ turn_no = cls._QUOTA_TURN_COUNTERS.get(sid, 0) + 1
530
+ cls._QUOTA_TURN_COUNTERS[sid] = turn_no
531
+ return turn_no == 1 or (turn_no % n == 0)