tokensafe 2.5.1 → 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.1",
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.1",
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.1",
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.1",
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.1",
49
+ "version": "2.6.0",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
package/src/installer.py CHANGED
@@ -814,34 +814,109 @@ class AgentInstaller:
814
814
  return restarted
815
815
 
816
816
  @staticmethod
817
- def _find_npm(home: Optional[str] = None) -> Optional[str]:
818
- """Locates an npm executable even in a clean non-interactive environment.
817
+ def _semver_dir_key(name: str) -> Tuple[int, ...]:
818
+ """Parses a version directory name like 'v24.14.0' into a numeric sort key."""
819
+ parts = re.findall(r"\d+", name or "")
820
+ return tuple(int(p) for p in parts[:4]) if parts else (0,)
819
821
 
820
- The updater dialog runs via `do shell script` + login shell, where .zshrc
821
- (and therefore nvm) is never sourced; PATH-only discovery made the npm
822
- channel silently skip updates. Falls back to well-known locations."""
823
- found = shutil.which("npm")
824
- if found:
825
- return found
822
+ @staticmethod
823
+ def _npm_subprocess_env(npm_bin: str) -> Dict[str, str]:
824
+ """Builds an env where `#!/usr/bin/env node` resolves the sibling node binary.
825
+
826
+ Under `do shell script` + login shell, nvm's bin dir is missing from PATH
827
+ or shadowed by `/usr/local/bin`. Running `<nvm>/bin/npm` without its own
828
+ bin directory first on PATH causes `env node` to execute `/usr/local/bin/node`,
829
+ making npm look at `/usr/local/lib` instead of the nvm prefix.
830
+ """
831
+ env = os.environ.copy()
832
+ bin_dir = os.path.dirname(os.path.abspath(npm_bin))
833
+ if bin_dir:
834
+ current_path = env.get("PATH", "")
835
+ path_parts = [p for p in current_path.split(os.pathsep) if p]
836
+ if not path_parts or os.path.normpath(path_parts[0]) != os.path.normpath(bin_dir):
837
+ env["PATH"] = f"{bin_dir}{os.pathsep}{current_path}" if current_path else bin_dir
838
+ return env
839
+
840
+ @staticmethod
841
+ def _find_npm_candidates(home: Optional[str] = None) -> List[str]:
842
+ """Discovers all executable npm binaries across PATH, project prefix, nvm, fnm, volta, and system dirs."""
826
843
  base = home or HOME
827
- candidates: List[str] = []
844
+ raw_candidates: List[str] = []
845
+
846
+ # 1. If running out of an npm node_modules install, include its own bin/npm first.
847
+ if os.path.basename(os.path.dirname(PROJECT_ROOT)) == "node_modules":
848
+ nm_parent = os.path.dirname(os.path.dirname(PROJECT_ROOT))
849
+ if os.path.basename(nm_parent) == "lib":
850
+ prefix = os.path.dirname(nm_parent)
851
+ raw_candidates.append(os.path.join(prefix, "bin", "npm"))
852
+ else:
853
+ raw_candidates.append(os.path.join(nm_parent, "npm.cmd"))
854
+ raw_candidates.append(os.path.join(nm_parent, "bin", "npm"))
855
+
856
+ # 2. PATH-resolved npm (note: on macOS login shells this may be /usr/local/bin/npm
857
+ # shadowing nvm, so we must NOT stop after checking only this one).
858
+ for exe in ("npm", "npm.cmd"):
859
+ found = shutil.which(exe)
860
+ if found:
861
+ raw_candidates.append(found)
862
+
863
+ # 3. nvm Node installations (newest semver first).
828
864
  nvm_dir = os.path.join(base, ".nvm", "versions", "node")
829
865
  try:
830
866
  if os.path.isdir(nvm_dir):
831
- # Newest installed node version wins.
832
- for version_dir in sorted(os.listdir(nvm_dir), reverse=True):
833
- candidates.append(os.path.join(nvm_dir, version_dir, "bin", "npm"))
867
+ for version_dir in sorted(
868
+ os.listdir(nvm_dir),
869
+ key=AgentInstaller._semver_dir_key,
870
+ reverse=True,
871
+ ):
872
+ raw_candidates.append(os.path.join(nvm_dir, version_dir, "bin", "npm"))
834
873
  except OSError:
835
874
  pass
836
- candidates += [
875
+
876
+ # 4. Other popular Node version managers + system/Homebrew locations.
877
+ raw_candidates.append(os.path.join(base, ".volta", "bin", "npm"))
878
+ raw_candidates.append(os.path.join(base, ".nodenv", "shims", "npm"))
879
+ raw_candidates.append(os.path.join(base, ".fnm", "aliases", "default", "bin", "npm"))
880
+ fnm_versions = os.path.join(base, ".local", "share", "fnm", "node-versions")
881
+ try:
882
+ if os.path.isdir(fnm_versions):
883
+ for version_dir in sorted(
884
+ os.listdir(fnm_versions),
885
+ key=AgentInstaller._semver_dir_key,
886
+ reverse=True,
887
+ ):
888
+ raw_candidates.append(os.path.join(fnm_versions, version_dir, "installation", "bin", "npm"))
889
+ except OSError:
890
+ pass
891
+
892
+ raw_candidates += [
837
893
  "/opt/homebrew/bin/npm",
838
894
  "/usr/local/bin/npm",
839
895
  "/usr/bin/npm",
840
896
  ]
841
- for cand in candidates:
897
+
898
+ seen = set()
899
+ unique: List[str] = []
900
+ for cand in raw_candidates:
901
+ if not cand:
902
+ continue
903
+ norm = os.path.normpath(os.path.abspath(cand))
904
+ if norm in seen:
905
+ continue
842
906
  if os.path.isfile(cand) and os.access(cand, os.X_OK):
843
- return cand
844
- return None
907
+ seen.add(norm)
908
+ unique.append(cand)
909
+ return unique
910
+
911
+ @staticmethod
912
+ def _find_npm(home: Optional[str] = None) -> Optional[str]:
913
+ """Locates an npm executable even in a clean non-interactive environment.
914
+
915
+ The updater dialog runs via `do shell script` + login shell, where .zshrc
916
+ (and therefore nvm) is never sourced; PATH-only discovery made the npm
917
+ channel silently skip updates. Falls back to well-known locations."""
918
+ candidates = AgentInstaller._find_npm_candidates(home=home)
919
+ return candidates[0] if candidates else None
845
920
 
846
921
  @classmethod
847
922
  def self_update(cls):
@@ -867,26 +942,50 @@ class AgentInstaller:
867
942
  except Exception as e:
868
943
  print(f" {YELLOW}⚠{RESET} Git pull skipped: {e}")
869
944
 
870
- # 2. Check npm global
871
- # The updater dialog runs via `do shell script` + login shell, which skips
872
- # .zshrc — nvm is NOT on PATH there, so PATH-only discovery silently
873
- # downgraded the npm channel (the active one for many installs).
874
- npm_bin = cls._find_npm()
875
- if npm_bin:
876
- try:
877
- res = subprocess.run([npm_bin, "list", "-g", "--depth=0", "tokensafe"], capture_output=True, text=True, timeout=15)
878
- if "tokensafe@" in res.stdout:
879
- print(f" {CYAN}→{RESET} Updating global npm package (npm install -g tokensafe@latest)...")
880
- up_res = subprocess.run([npm_bin, "install", "-g", "tokensafe@latest"], capture_output=True, text=True, timeout=120)
881
- if up_res.returncode == 0:
882
- print(f" {GREEN}✔{RESET} npm package upgraded successfully.")
883
- else:
884
- detail = (up_res.stderr or up_res.stdout or "").strip()[:200]
885
- print(f" {YELLOW}⚠{RESET} npm upgrade failed: {detail}")
886
- else:
887
- print(f" {CYAN}ℹ{RESET} tokensafe not installed via npm — skipping npm channel.")
888
- except Exception as e:
889
- print(f" {YELLOW}⚠{RESET} npm update skipped: {e}")
945
+ # 2. Check npm global across all discovered Node/npm prefixes
946
+ # A macOS login shell may have /usr/local/bin/npm on PATH ahead of nvm,
947
+ # and `#!/usr/bin/env node` inside nvm's npm also resolves /usr/local/bin/node
948
+ # unless npm's own bin dir is prepended to PATH.
949
+ primary_npm = cls._find_npm()
950
+ upgraded_npm_bins: List[str] = []
951
+ if primary_npm:
952
+ npm_candidates = cls._find_npm_candidates()
953
+ norm_seen = {os.path.normpath(os.path.abspath(p)) for p in npm_candidates}
954
+ if os.path.normpath(os.path.abspath(primary_npm)) not in norm_seen:
955
+ npm_candidates.insert(0, primary_npm)
956
+
957
+ found_npm_install = False
958
+ for npm_bin in npm_candidates:
959
+ npm_env = cls._npm_subprocess_env(npm_bin)
960
+ try:
961
+ res = subprocess.run(
962
+ [npm_bin, "list", "-g", "--depth=0", "tokensafe"],
963
+ env=npm_env,
964
+ capture_output=True,
965
+ text=True,
966
+ timeout=15,
967
+ )
968
+ if "tokensafe@" in (res.stdout or ""):
969
+ found_npm_install = True
970
+ print(f" {CYAN}→{RESET} Updating global npm package via {npm_bin} (npm install -g tokensafe@latest)...")
971
+ up_res = subprocess.run(
972
+ [npm_bin, "install", "-g", "tokensafe@latest"],
973
+ env=npm_env,
974
+ capture_output=True,
975
+ text=True,
976
+ timeout=120,
977
+ )
978
+ if up_res.returncode == 0:
979
+ print(f" {GREEN}✔{RESET} npm package upgraded successfully.")
980
+ upgraded_npm_bins.append(npm_bin)
981
+ else:
982
+ detail = (up_res.stderr or up_res.stdout or "").strip()[:200]
983
+ print(f" {YELLOW}⚠{RESET} npm upgrade failed: {detail}")
984
+ except Exception as e:
985
+ print(f" {YELLOW}⚠{RESET} npm update check failed ({npm_bin}): {e}")
986
+
987
+ if not found_npm_install:
988
+ print(f" {CYAN}ℹ{RESET} tokensafe not installed via npm — skipping npm channel.")
890
989
  else:
891
990
  print(f" {YELLOW}⚠{RESET} npm not found — skipping npm channel.")
892
991
 
@@ -932,9 +1031,17 @@ class AgentInstaller:
932
1031
  except Exception:
933
1032
  pass
934
1033
  try:
935
- tokensafe_bin = shutil.which("tokensafe")
1034
+ tokensafe_bin = None
1035
+ for npm_bin in upgraded_npm_bins:
1036
+ cand_bin = os.path.join(os.path.dirname(npm_bin), "tokensafe.cmd" if os.name == "nt" else "tokensafe")
1037
+ if os.path.isfile(cand_bin) and os.access(cand_bin, os.X_OK):
1038
+ tokensafe_bin = cand_bin
1039
+ break
1040
+ if not tokensafe_bin:
1041
+ tokensafe_bin = shutil.which("tokensafe")
936
1042
  sync_cmd = [tokensafe_bin, "version", "--check"] if tokensafe_bin else [sys.executable, os.path.join(PROJECT_ROOT, "src", "cli.py"), "version", "--check"]
937
- subprocess.run(sync_cmd, capture_output=True, text=True, timeout=5)
1043
+ sync_env = cls._npm_subprocess_env(tokensafe_bin) if tokensafe_bin else None
1044
+ subprocess.run(sync_cmd, env=sync_env, capture_output=True, text=True, timeout=5)
938
1045
  except Exception:
939
1046
  pass
940
1047
 
@@ -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.1"
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.1"
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.1"
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