tokensafe 2.5.2 → 2.6.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 CHANGED
@@ -343,7 +343,7 @@ More documentation: [docs/AGENT_SETUP.md](docs/AGENT_SETUP.md) · [docs/ARCHITEC
343
343
 
344
344
  ## Development and License
345
345
 
346
- The client runs on standard Python 3.10+ with zero mandatory runtime dependencies. An optional `cryptography` package accelerates license verification ([details](docs/AGENT_SETUP.md#6-optional-dependency-cryptography)).
346
+ The client runs on Python 3.10+ with `cryptography>=42.0` as its sole runtime dependency for Ed25519 license checks; all AST slicing, SQLite metrics, MCP tooling, and guardrails run on the standard library ([details](docs/AGENT_SETUP.md#6-runtime-dependency-cryptography)).
347
347
 
348
348
  ```bash
349
349
  # Run the unit test suite (compact failure report; full: --traceback / -v)
package/bin/tokensafe CHANGED
@@ -11,6 +11,16 @@ PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
11
11
  if PROJECT_ROOT not in sys.path:
12
12
  sys.path.insert(0, PROJECT_ROOT)
13
13
 
14
+ # If launched via system python3 without cryptography (PEP 668), re-exec in ~/.tokensafe/venv if present.
15
+ _venv_py = os.path.expanduser(
16
+ "~/.tokensafe/venv/Scripts/python.exe" if sys.platform == "win32" else "~/.tokensafe/venv/bin/python3"
17
+ )
18
+ if os.path.exists(_venv_py) and os.path.realpath(sys.executable) != os.path.realpath(_venv_py):
19
+ try:
20
+ import cryptography # noqa: F401
21
+ except ImportError:
22
+ os.execv(_venv_py, [_venv_py, __file__, *sys.argv[1:]])
23
+
14
24
  from src.cli import main
15
25
 
16
26
  if __name__ == "__main__":
package/bin/tokensafe.js CHANGED
@@ -8,25 +8,78 @@
8
8
  const { spawn, spawnSync } = require('child_process');
9
9
  const path = require('path');
10
10
  const fs = require('fs');
11
+ const os = require('os');
11
12
 
12
13
  const ROOT_DIR = path.resolve(__dirname, '..');
13
14
  const args = process.argv.slice(2);
15
+ const VENV_DIR = path.join(os.homedir(), '.tokensafe', 'venv');
14
16
 
15
- // Locate system Python 3 interpreter
17
+ function checkPython(cmd, requireCrypto) {
18
+ const probe = requireCrypto
19
+ ? 'import sys, cryptography; assert sys.version_info >= (3, 10)'
20
+ : 'import sys; assert sys.version_info >= (3, 10)';
21
+ try {
22
+ const res = spawnSync(cmd, ['-c', probe], { encoding: 'utf-8', stdio: 'pipe' });
23
+ return res.status === 0;
24
+ } catch (_) {
25
+ return false;
26
+ }
27
+ }
28
+
29
+ function bootstrapCryptography(basePython) {
30
+ console.error('⚡ Installing required dependency: cryptography>=42.0 ...');
31
+ // 1. Try user-site pip first (respects normal user environments)
32
+ const userPip = spawnSync(
33
+ basePython,
34
+ ['-m', 'pip', 'install', '--user', '--quiet', '--disable-pip-version-check', 'cryptography>=42.0'],
35
+ { encoding: 'utf-8', stdio: 'pipe' }
36
+ );
37
+ if (userPip.status === 0 && checkPython(basePython, true)) {
38
+ return basePython;
39
+ }
40
+
41
+ // 2. Fallback to isolated ~/.tokensafe/venv (handles PEP 668 externally-managed Python on macOS/Ubuntu)
42
+ fs.mkdirSync(path.dirname(VENV_DIR), { recursive: true });
43
+ const venvPy = process.platform === 'win32'
44
+ ? path.join(VENV_DIR, 'Scripts', 'python.exe')
45
+ : path.join(VENV_DIR, 'bin', 'python3');
46
+
47
+ if (!fs.existsSync(venvPy)) {
48
+ const mk = spawnSync(basePython, ['-m', 'venv', VENV_DIR], { encoding: 'utf-8', stdio: 'pipe' });
49
+ if (mk.status !== 0) return null;
50
+ }
51
+ const venvPip = spawnSync(
52
+ venvPy,
53
+ ['-m', 'pip', 'install', '--quiet', '--disable-pip-version-check', 'cryptography>=42.0'],
54
+ { encoding: 'utf-8', stdio: 'pipe' }
55
+ );
56
+ if (venvPip.status === 0 && checkPython(venvPy, true)) {
57
+ return venvPy;
58
+ }
59
+ return null;
60
+ }
61
+
62
+ // Locate Python 3.10+ interpreter with required `cryptography` package
16
63
  function findPython() {
17
- const candidates = ['python3', 'python'];
64
+ const venvPy = process.platform === 'win32'
65
+ ? path.join(VENV_DIR, 'Scripts', 'python.exe')
66
+ : path.join(VENV_DIR, 'bin', 'python3');
67
+ const candidates = [venvPy, 'python3', 'python'];
68
+
69
+ for (const cmd of candidates) {
70
+ if (cmd === venvPy && !fs.existsSync(venvPy)) continue;
71
+ if (checkPython(cmd, true)) return cmd;
72
+ }
73
+
18
74
  for (const cmd of candidates) {
19
- try {
20
- const res = spawnSync(cmd, ['-c', 'import sys; assert sys.version_info >= (3, 10)'], {
21
- encoding: 'utf-8',
22
- stdio: 'pipe'
23
- });
24
- if (res.status === 0) return cmd;
25
- if (res.error && res.error.code !== 'ENOENT') {
26
- console.error(`TokenSafe: python probe for '${cmd}' failed: ${res.error.message}`);
27
- }
28
- } catch (err) {
29
- console.error(`TokenSafe: python probe for '${cmd}' threw: ${err.message}`);
75
+ if (cmd === venvPy && !fs.existsSync(venvPy)) continue;
76
+ if (checkPython(cmd, false)) {
77
+ const bootstrapped = bootstrapCryptography(cmd);
78
+ if (bootstrapped) return bootstrapped;
79
+ console.error("\n❌ TokenSafe requires the Python 'cryptography>=42.0' package.");
80
+ console.error("Install it manually cleanly via:");
81
+ console.error(" pip install 'cryptography>=42.0'\n");
82
+ process.exit(1);
30
83
  }
31
84
  }
32
85
  return null;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "2.5.2",
4
+ "version": "2.6.0",
5
5
  "description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
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": "2.5.2",
4
+ "version": "2.6.0",
5
5
  "description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
6
6
  "logo": "assets/logo.svg",
7
7
  "author": {
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Reduce your AI bills by up to 99% locally: focused code, warm prompt caches & zero secret leaks.",
6
- "version": "2.5.2",
6
+ "version": "2.6.0",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -30,7 +30,7 @@
30
30
  "registryType": "npm",
31
31
  "registryBaseUrl": "https://registry.npmjs.org",
32
32
  "identifier": "tokensafe",
33
- "version": "2.5.2",
33
+ "version": "2.6.0",
34
34
  "runtimeHint": "npx",
35
35
  "transport": {
36
36
  "type": "stdio"
@@ -46,7 +46,7 @@
46
46
  "registryType": "pypi",
47
47
  "registryBaseUrl": "https://pypi.org",
48
48
  "identifier": "tokensafe",
49
- "version": "2.5.2",
49
+ "version": "2.6.0",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
@@ -1,6 +1,6 @@
1
1
  """
2
- Cryptographically secure, zero-dependency License Engine for TokenSafe.
3
- Supports offline-verifiable HMAC-SHA256 signed licenses and 7-day trials.
2
+ Cryptographically secure License Engine for TokenSafe.
3
+ Supports offline-verifiable Ed25519 (TS2) licenses, 7-day trials, and quota checks.
4
4
  Compatible with Stripe webhook lifecycle and B2B on-premise proxy deployments.
5
5
  """
6
6
 
@@ -39,103 +39,32 @@ ROTATED_HMAC_SALT = os.environ.get("TOKENSAFE_HMAC_SALT", "")
39
39
  DEFAULT_SIGNING_SALT = ROTATED_HMAC_SALT
40
40
 
41
41
  # ---------------------------------------------------------------------------
42
- # Zero-dependency RFC 8032 Ed25519 Implementation with Cryptography Fast-Path
42
+ # Required Cryptography-Backed RFC 8032 Ed25519 Verification & Signing
43
43
  # ---------------------------------------------------------------------------
44
- _ED25519_Q = 2**255 - 19
45
- _ED25519_L = 2**252 + 27742317777372353535851937790883648493
46
-
47
- def _ed_inv(x: int) -> int:
48
- return pow(x, _ED25519_Q - 2, _ED25519_Q)
49
-
50
- _ED_D = -121665 * _ed_inv(121666)
51
- _ED_I = pow(2, (_ED25519_Q - 1) // 4, _ED25519_Q)
52
-
53
- def _ed_xrecover(y: int) -> int:
54
- xx = (y * y - 1) * _ed_inv(_ED_D * y * y + 1)
55
- x = pow(xx, (_ED25519_Q + 3) // 8, _ED25519_Q)
56
- if (x * x - xx) % _ED25519_Q != 0:
57
- x = (x * _ED_I) % _ED25519_Q
58
- if x % 2 != 0:
59
- x = _ED25519_Q - x
60
- return x
61
-
62
- _ED_BY = 4 * _ed_inv(5)
63
- _ED_BX = _ed_xrecover(_ED_BY)
64
- _ED_B = [_ED_BX % _ED25519_Q, _ED_BY % _ED25519_Q]
65
-
66
- def _ed_add(p1: list, p2: list) -> list:
67
- x1, y1 = p1[0], p1[1]
68
- x2, y2 = p2[0], p2[1]
69
- x3 = (x1 * y2 + x2 * y1) * _ed_inv(1 + _ED_D * x1 * x2 * y1 * y2)
70
- y3 = (y1 * y2 + x1 * x2) * _ed_inv(1 - _ED_D * x1 * x2 * y1 * y2)
71
- return [x3 % _ED25519_Q, y3 % _ED25519_Q]
72
-
73
- def _ed_scalarmult(pt: list, e: int) -> list:
74
- if e == 0:
75
- return [0, 1]
76
- q = _ed_scalarmult(pt, e // 2)
77
- q = _ed_add(q, q)
78
- if e & 1:
79
- q = _ed_add(q, pt)
80
- return q
81
-
82
- def _ed_encodepoint(pt: list) -> bytes:
83
- x, y = pt[0], pt[1]
84
- bits = [(y >> i) & 1 for i in range(255)] + [x & 1]
85
- return bytes([sum([bits[i * 8 + j] << j for j in range(8)]) for i in range(32)])
86
-
87
- def _ed_bit(h: bytes, i: int) -> int:
88
- return (h[i // 8] >> (i % 8)) & 1
89
-
90
- def _ed_decodepoint(s: bytes) -> Optional[list]:
91
- y = sum(2**i * _ed_bit(s, i) for i in range(0, 255))
92
- x = _ed_xrecover(y)
93
- if x & 1 != _ed_bit(s, 255):
94
- x = _ED25519_Q - x
95
- pt = [x, y]
96
- if (-x * x + y * y - 1 - _ED_D * x * x * y * y) % _ED25519_Q != 0:
97
- return None
98
- return pt
99
-
100
- def _ed25519_sign_bytes(msg: bytes, priv_bytes: bytes, pub_bytes: bytes = b"") -> bytes:
44
+ def _load_ed25519_module():
101
45
  try:
102
46
  from cryptography.hazmat.primitives.asymmetric import ed25519
103
- priv_obj = ed25519.Ed25519PrivateKey.from_private_bytes(priv_bytes)
104
- return priv_obj.sign(msg)
105
- except Exception:
106
- h = hashlib.sha512(priv_bytes).digest()
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))
110
- r = int.from_bytes(hashlib.sha512(h[32:] + msg).digest(), "little")
111
- r_pt = _ed_scalarmult(_ED_B, r)
112
- r_bytes = _ed_encodepoint(r_pt)
113
- k = int.from_bytes(hashlib.sha512(r_bytes + derived_pub + msg).digest(), "little")
114
- s = (r + k * a) % _ED25519_L
115
- return r_bytes + int.to_bytes(s, 32, "little")
47
+ return ed25519
48
+ except ImportError as exc:
49
+ raise RuntimeError(
50
+ "TokenSafe requires 'cryptography>=42.0'. Install it via: pip install 'cryptography>=42.0'"
51
+ ) from exc
52
+
53
+
54
+ def _ed25519_sign_bytes(msg: bytes, priv_bytes: bytes, pub_bytes: bytes = b"") -> bytes:
55
+ ed25519 = _load_ed25519_module()
56
+ priv_obj = ed25519.Ed25519PrivateKey.from_private_bytes(priv_bytes)
57
+ return priv_obj.sign(msg)
58
+
116
59
 
117
60
  def _ed25519_verify_bytes(sig: bytes, msg: bytes, pub_bytes: bytes) -> bool:
118
61
  if len(sig) != 64 or len(pub_bytes) != 32:
119
62
  return False
63
+ ed25519 = _load_ed25519_module()
120
64
  try:
121
- from cryptography.hazmat.primitives.asymmetric import ed25519
122
65
  pub_obj = ed25519.Ed25519PublicKey.from_public_bytes(pub_bytes)
123
66
  pub_obj.verify(sig, msg)
124
67
  return True
125
- except Exception:
126
- pass
127
- try:
128
- r_pt = _ed_decodepoint(sig[:32])
129
- a_pt = _ed_decodepoint(pub_bytes)
130
- if r_pt is None or a_pt is None:
131
- return False
132
- s = int.from_bytes(sig[32:], "little")
133
- if s >= _ED25519_L:
134
- return False
135
- h = int.from_bytes(hashlib.sha512(sig[:32] + pub_bytes + msg).digest(), "little")
136
- v1 = _ed_scalarmult(_ED_B, s)
137
- v2 = _ed_add(r_pt, _ed_scalarmult(a_pt, h))
138
- return v1 == v2
139
68
  except Exception:
140
69
  return False
141
70
 
@@ -271,18 +200,22 @@ class LicenseManager:
271
200
  except Exception:
272
201
  return False, {}, "Invalid signature encoding"
273
202
 
274
- if not _ed25519_verify_bytes(sig_bytes, payload_bytes, pub_bytes):
275
- verified = False
276
- if not public_key:
203
+ try:
204
+ verified = _ed25519_verify_bytes(sig_bytes, payload_bytes, pub_bytes)
205
+ if not verified and not public_key:
277
206
  for leg_hex in LEGACY_ED25519_PUBLIC_KEYS:
278
207
  try:
279
208
  if _ed25519_verify_bytes(sig_bytes, payload_bytes, bytes.fromhex(leg_hex)):
280
209
  verified = True
281
210
  break
211
+ except RuntimeError:
212
+ raise
282
213
  except Exception:
283
214
  pass
284
- if not verified:
285
- return False, {}, "Invalid digital signature: license key has been tampered with or is counterfeit"
215
+ except RuntimeError as crypto_err:
216
+ return False, {}, str(crypto_err)
217
+ if not verified:
218
+ return False, {}, "Invalid digital signature: license key has been tampered with or is counterfeit"
286
219
 
287
220
  # 2. Legacy TS1 Verification (disabled offline to eliminate public-salt forgery)
288
221
  else:
package/src/mcp_server.py CHANGED
@@ -40,7 +40,7 @@ from src.license_manager import LicenseManager
40
40
 
41
41
  SERVER_INFO = {
42
42
  "name": "tokensafe-mcp",
43
- "version": "2.5.2"
43
+ "version": "2.6.0"
44
44
  }
45
45
 
46
46
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -276,7 +276,7 @@ class TelemetrySync:
276
276
  rollup_synced = bool(state.get("lifetime_rollup_synced", False))
277
277
  headers = {
278
278
  "Content-Type": "application/json",
279
- "User-Agent": "TokenSafe-Sync/2.5.2"
279
+ "User-Agent": "TokenSafe-Sync/2.6.0"
280
280
  }
281
281
  if active_key:
282
282
  headers["Authorization"] = f"Bearer {active_key}"
@@ -16,7 +16,7 @@ import urllib.request
16
16
  import urllib.error
17
17
  from typing import Dict, Any, Optional, Tuple
18
18
 
19
- CURRENT_VERSION = "2.5.2"
19
+ CURRENT_VERSION = "2.6.0"
20
20
  CACHE_TTL = 86400 # 24 hours
21
21
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
22
22
  # answer for a full day — otherwise an update released right after an outage