buddy-agent-auth 0.1.0.dev1__py3-none-any.whl
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.
- buddy_agent_auth/__init__.py +5 -0
- buddy_agent_auth/account_store.py +4 -0
- buddy_agent_auth/backend_profile.py +4 -0
- buddy_agent_auth/client.py +4 -0
- buddy_agent_auth/locking.py +81 -0
- buddy_agent_auth/providers/__init__.py +4 -0
- buddy_agent_auth/providers/base.py +9 -0
- buddy_agent_auth/providers/codebuddy/__init__.py +17 -0
- buddy_agent_auth/providers/codebuddy/account_store.py +506 -0
- buddy_agent_auth/providers/codebuddy/backend_profile.py +198 -0
- buddy_agent_auth/providers/codebuddy/client.py +666 -0
- buddy_agent_auth/providers/trae/__init__.py +27 -0
- buddy_agent_auth/providers/trae/aha_cache_codec.py +84 -0
- buddy_agent_auth/providers/trae/aha_device_cache.py +45 -0
- buddy_agent_auth/providers/trae/aha_device_service.py +325 -0
- buddy_agent_auth/providers/trae/aha_native_backend.py +61 -0
- buddy_agent_auth/providers/trae/aha_native_lifecycle.py +226 -0
- buddy_agent_auth/providers/trae/aha_native_semantics.py +67 -0
- buddy_agent_auth/providers/trae/aha_registration.py +157 -0
- buddy_agent_auth/providers/trae/aha_tiny_storage.py +135 -0
- buddy_agent_auth/providers/trae/app_storage.py +195 -0
- buddy_agent_auth/providers/trae/auth.py +362 -0
- buddy_agent_auth/providers/trae/client_metadata.py +102 -0
- buddy_agent_auth/providers/trae/credential_decrypt.py +111 -0
- buddy_agent_auth/providers/trae/credentials.py +39 -0
- buddy_agent_auth/providers/trae/device_hardware.py +377 -0
- buddy_agent_auth/providers/trae/diagnostics.py +38 -0
- buddy_agent_auth/providers/trae/login.py +415 -0
- buddy_agent_auth/providers/trae/login_identity.py +134 -0
- buddy_agent_auth/providers/trae/native_identity.py +111 -0
- buddy_agent_auth-0.1.0.dev1.dist-info/METADATA +40 -0
- buddy_agent_auth-0.1.0.dev1.dist-info/RECORD +34 -0
- buddy_agent_auth-0.1.0.dev1.dist-info/WHEEL +5 -0
- buddy_agent_auth-0.1.0.dev1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Application-owned device storage and account/device usage records."""
|
|
2
|
+
from contextlib import contextmanager
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
_reported_fallbacks: set[tuple[str, str]] = set()
|
|
11
|
+
_fallback_project_root: Path | None = None
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def configure_fallback(project_root: Path | None) -> None:
|
|
15
|
+
"""Set the legacy application fallback without importing that application."""
|
|
16
|
+
global _fallback_project_root
|
|
17
|
+
_fallback_project_root = Path(project_root) if project_root is not None else None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _python_profile_home(home: Path) -> Path | None:
|
|
21
|
+
"""Identify a matching Windows profile only from a per-user Python install."""
|
|
22
|
+
if os.name != 'nt':
|
|
23
|
+
return None
|
|
24
|
+
python_path = Path(sys._base_executable)
|
|
25
|
+
for candidate in python_path.parents:
|
|
26
|
+
if candidate.name.casefold() != home.name.casefold() or candidate.parent.name.casefold() != 'users':
|
|
27
|
+
continue
|
|
28
|
+
relative = python_path.relative_to(candidate)
|
|
29
|
+
parts = [part.casefold() for part in relative.parts]
|
|
30
|
+
if parts[:4] == ['appdata', 'local', 'programs', 'python']:
|
|
31
|
+
return candidate
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def root() -> Path:
|
|
36
|
+
override = os.environ.get('TRAE2API_HOME')
|
|
37
|
+
if override:
|
|
38
|
+
path = Path(override).expanduser()
|
|
39
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
40
|
+
return path
|
|
41
|
+
home = Path.home()
|
|
42
|
+
path = home / '.traeapi'
|
|
43
|
+
try:
|
|
44
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
45
|
+
return path
|
|
46
|
+
except PermissionError:
|
|
47
|
+
alternate = _python_profile_home(home)
|
|
48
|
+
candidates = []
|
|
49
|
+
if alternate is not None and alternate != home:
|
|
50
|
+
candidates.append(alternate / '.traeapi')
|
|
51
|
+
candidates.append((_fallback_project_root or Path.cwd()) / '.traeapi')
|
|
52
|
+
for fallback in candidates:
|
|
53
|
+
if fallback == path:
|
|
54
|
+
continue
|
|
55
|
+
try:
|
|
56
|
+
fallback.mkdir(parents=True, exist_ok=True)
|
|
57
|
+
except PermissionError:
|
|
58
|
+
continue
|
|
59
|
+
key = (str(path), str(fallback))
|
|
60
|
+
if key not in _reported_fallbacks:
|
|
61
|
+
_reported_fallbacks.add(key)
|
|
62
|
+
print(f'[trae2api] {path} is not writable; using {fallback}. '
|
|
63
|
+
'Set TRAE2API_HOME to select the storage directory.', file=sys.stderr)
|
|
64
|
+
return fallback
|
|
65
|
+
raise PermissionError(f"cannot initialize storage at {path} or fallback locations; "
|
|
66
|
+
"set TRAE2API_HOME to a writable directory") from None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@contextmanager
|
|
70
|
+
def _locked():
|
|
71
|
+
# OS-managed locks are released on process termination.
|
|
72
|
+
path = root() / '.storage.lock'
|
|
73
|
+
with path.open('a+b') as lock:
|
|
74
|
+
if os.name == 'nt':
|
|
75
|
+
import msvcrt
|
|
76
|
+
lock.seek(0)
|
|
77
|
+
if not lock.read(1):
|
|
78
|
+
lock.write(b'0')
|
|
79
|
+
lock.flush()
|
|
80
|
+
while True:
|
|
81
|
+
try:
|
|
82
|
+
lock.seek(0)
|
|
83
|
+
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
|
|
84
|
+
break
|
|
85
|
+
except OSError:
|
|
86
|
+
time.sleep(0.05)
|
|
87
|
+
else:
|
|
88
|
+
import fcntl
|
|
89
|
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
90
|
+
try:
|
|
91
|
+
yield
|
|
92
|
+
finally:
|
|
93
|
+
if os.name == 'nt':
|
|
94
|
+
lock.seek(0)
|
|
95
|
+
msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
|
|
96
|
+
else:
|
|
97
|
+
fcntl.flock(lock, fcntl.LOCK_UN)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def device_path(device_id: str) -> Path:
|
|
101
|
+
# Remote IDs are normally decimal; allow other safe IDs used by clients.
|
|
102
|
+
if (not isinstance(device_id, str) or not device_id or device_id in ('.', '..')
|
|
103
|
+
or any(c in device_id for c in '<>:"/\\|?*')
|
|
104
|
+
or any(ord(c) < 32 for c in device_id) or device_id[-1] in ' .'):
|
|
105
|
+
raise ValueError('device ID cannot be used as a directory name')
|
|
106
|
+
return root() / device_id / 'TinyStorage'
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def save_tiny_storage(identity) -> None:
|
|
110
|
+
from .aha_device_cache import DeviceRecord
|
|
111
|
+
from .login_identity import atomic_json
|
|
112
|
+
record = DeviceRecord.load(identity.device_cache, identity.hardware_uuid)
|
|
113
|
+
if not identity.registered or record is None:
|
|
114
|
+
return
|
|
115
|
+
path = device_path(record.device_id)
|
|
116
|
+
with _locked():
|
|
117
|
+
if path.exists():
|
|
118
|
+
data = json.loads(path.read_text(encoding='utf-8-sig'))
|
|
119
|
+
if not isinstance(data, dict) or not isinstance(data.get('tiny_storage_data', {}), dict):
|
|
120
|
+
raise ValueError('invalid application TinyStorage')
|
|
121
|
+
else:
|
|
122
|
+
data = {}
|
|
123
|
+
values = data.setdefault('tiny_storage_data', {})
|
|
124
|
+
values['aha.device.device_id'] = record.encoded()
|
|
125
|
+
if isinstance(identity.device_region, str):
|
|
126
|
+
values['aha_device_region'] = identity.device_region
|
|
127
|
+
atomic_json(path, data)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _read_pairs(path: Path) -> dict[str, str]:
|
|
131
|
+
if not path.exists():
|
|
132
|
+
return {}
|
|
133
|
+
data = json.loads(path.read_text(encoding='utf-8-sig'))
|
|
134
|
+
if not isinstance(data, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k, v in data.items()):
|
|
135
|
+
raise ValueError('invalid device_pair.json; refusing to overwrite it')
|
|
136
|
+
return data
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def resolve_pair(user_id: str, device_id: str, client, version: str):
|
|
140
|
+
"""Reuse the account binding, registering a device only on first use."""
|
|
141
|
+
from .login_identity import atomic_json
|
|
142
|
+
if not isinstance(user_id, str) or not user_id:
|
|
143
|
+
raise ValueError('check-in credentials must contain auth.userId')
|
|
144
|
+
from .device_hardware import Hardware
|
|
145
|
+
hardware = Hardware.for_account(user_id)
|
|
146
|
+
path = root() / 'device_pair.json'
|
|
147
|
+
# Hold the lock through registration to avoid two processes registering for
|
|
148
|
+
# the same previously unseen account at the same time.
|
|
149
|
+
with _locked():
|
|
150
|
+
data = _read_pairs(path)
|
|
151
|
+
if user_id not in data:
|
|
152
|
+
from .aha_registration import Registration, register, activate
|
|
153
|
+
from .aha_device_cache import DeviceRecord
|
|
154
|
+
pending_path = root() / 'device_pending.json'
|
|
155
|
+
if pending_path.exists():
|
|
156
|
+
pending = json.loads(pending_path.read_text(encoding='utf-8-sig'))
|
|
157
|
+
if not isinstance(pending, dict):
|
|
158
|
+
raise ValueError('invalid device_pending.json; refusing to overwrite it')
|
|
159
|
+
else:
|
|
160
|
+
pending = {}
|
|
161
|
+
if user_id in pending:
|
|
162
|
+
entry = pending[user_id]
|
|
163
|
+
if (not isinstance(entry, dict) or set(entry) != {'device_id', 'install_id', 'region', 'hardware_uuid'}
|
|
164
|
+
or any(not isinstance(value, str) or not value for value in entry.values())
|
|
165
|
+
or any(not entry[key].isascii() or not entry[key].isdecimal() or int(entry[key]) <= 0
|
|
166
|
+
for key in ('device_id', 'install_id'))
|
|
167
|
+
or entry['region'] not in ('CN', 'SG', 'US', 'USTTP')
|
|
168
|
+
or entry['hardware_uuid'] != hardware.pc_uuid):
|
|
169
|
+
raise ValueError('invalid pending device registration for this account')
|
|
170
|
+
registration = Registration(entry['device_id'], entry['install_id'], entry['region'])
|
|
171
|
+
else:
|
|
172
|
+
registration = register(client, hardware, version or None)
|
|
173
|
+
pending[user_id] = {'device_id': registration.device_id, 'install_id': registration.install_id,
|
|
174
|
+
'region': registration.region, 'hardware_uuid': hardware.pc_uuid}
|
|
175
|
+
atomic_json(pending_path, pending)
|
|
176
|
+
activate(client, registration, hardware, version or '3.4.20', require_confirmation=False)
|
|
177
|
+
device_id = registration.device_id
|
|
178
|
+
cache_path = device_path(device_id)
|
|
179
|
+
if cache_path.exists():
|
|
180
|
+
cache = json.loads(cache_path.read_text(encoding='utf-8-sig'))
|
|
181
|
+
if not isinstance(cache, dict) or not isinstance(cache.get('tiny_storage_data', {}), dict):
|
|
182
|
+
raise ValueError('invalid application TinyStorage')
|
|
183
|
+
else:
|
|
184
|
+
cache = {}
|
|
185
|
+
cache.setdefault('tiny_storage_data', {})['aha.device.device_id'] = (
|
|
186
|
+
DeviceRecord(device_id, registration.install_id, hardware.pc_uuid).encoded())
|
|
187
|
+
atomic_json(cache_path, cache)
|
|
188
|
+
data[user_id] = device_id
|
|
189
|
+
atomic_json(path, data)
|
|
190
|
+
del pending[user_id]
|
|
191
|
+
atomic_json(pending_path, pending)
|
|
192
|
+
else:
|
|
193
|
+
device_id = data[user_id]
|
|
194
|
+
device_path(device_id)
|
|
195
|
+
return device_id, hardware
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
"""Trae CN credential loader + token lifecycle.
|
|
2
|
+
|
|
3
|
+
Sources (reverse engineered from Trae CN 3.4.4):
|
|
4
|
+
- Credentials live in `%APPDATA%/Trae CN/User/globalStorage/storage.json` under
|
|
5
|
+
`iCubeAuthInfo://icube.cloudide` (AES-128-CBC wrapped, see credential_decrypt.py)
|
|
6
|
+
and the device ECDSA keypair under `iCubeAuthInfo://icube-dc:<deviceId>`.
|
|
7
|
+
- `POST {host}/trae/api/v3/oauth/ExchangeToken` exchanges a RefreshToken for a
|
|
8
|
+
fresh {Token, RefreshToken} pair. Requests carry an ECDSA P-256 DeviceProof:
|
|
9
|
+
payload = "POST\n/trae/api/v3/oauth/ExchangeToken\n{ClientID}\n{RefreshToken}\n{ts}\n{nonce}"
|
|
10
|
+
Signature = base64(ECDSA-P256-SHA256(payload))
|
|
11
|
+
- `POST {host}/api/v2/GetUserToken` (header `X-Cloudide-Token`) mints the
|
|
12
|
+
long-lived RS256 JWT that is sent as `Authorization: Cloud-IDE-JWT <jwt>`.
|
|
13
|
+
|
|
14
|
+
The proxy is read-only w.r.t. the Trae install by default: it re-reads the
|
|
15
|
+
current tokens from storage.json, so the IDE remains the source of truth.
|
|
16
|
+
RefreshToken rotation is only performed when the stored token is already
|
|
17
|
+
expired (opt-in via TRAE2API_ALLOW_ROTATION=1) because the server may
|
|
18
|
+
invalidate the previous refresh token, which would log out the running IDE.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import base64
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import secrets
|
|
26
|
+
import time
|
|
27
|
+
from dataclasses import dataclass, field
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
import httpx
|
|
31
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
32
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
33
|
+
|
|
34
|
+
from .credential_decrypt import decrypt_value
|
|
35
|
+
from .client_metadata import client_version
|
|
36
|
+
|
|
37
|
+
DEFAULT_CLIENT_ID = "ono9krqynydwx5" # Jy() default for TRAE (non-SOLO)
|
|
38
|
+
EXCHANGE_PATH = "/trae/api/v3/oauth/ExchangeToken"
|
|
39
|
+
IDE_VERSION = "3.4.4"
|
|
40
|
+
USER_AGENT = "trae-cn/3.4.4"
|
|
41
|
+
|
|
42
|
+
DEFAULT_STORAGE = Path(os.environ.get("APPDATA", "")) / "Trae CN" / "User" / "globalStorage" / "storage.json"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class DeviceInfo:
|
|
47
|
+
"""Defaults mirror the real Trae client fingerprint on this machine
|
|
48
|
+
(observed in %APPDATA%/Trae CN/logs/.../completion.log)."""
|
|
49
|
+
device_id: str = ""
|
|
50
|
+
machine_id: str = ""
|
|
51
|
+
platform_code: str = "IDE_PC"
|
|
52
|
+
device_type: str = "PC"
|
|
53
|
+
device_name: str = "trae2api"
|
|
54
|
+
device_model: str = "MS-7B89"
|
|
55
|
+
client_version: str = field(default_factory=client_version)
|
|
56
|
+
device_public_key: str = ""
|
|
57
|
+
device_brand: str = "MS-7B89"
|
|
58
|
+
device_cpu: str = "AMD"
|
|
59
|
+
os_info: str = "Windows"
|
|
60
|
+
os_version: str = "Windows 10 Education"
|
|
61
|
+
|
|
62
|
+
def to_payload(self) -> dict:
|
|
63
|
+
return {
|
|
64
|
+
"DeviceID": self.device_id,
|
|
65
|
+
"MachineID": self.machine_id,
|
|
66
|
+
"PlatformCode": self.platform_code,
|
|
67
|
+
"DeviceType": self.device_type,
|
|
68
|
+
"DeviceName": self.device_name,
|
|
69
|
+
"DeviceModel": self.device_model,
|
|
70
|
+
"ClientVersion": self.client_version,
|
|
71
|
+
"DevicePublicKey": self.device_public_key,
|
|
72
|
+
"DeviceBrand": self.device_brand,
|
|
73
|
+
"DeviceCPU": self.device_cpu,
|
|
74
|
+
"OSInfo": self.os_info,
|
|
75
|
+
"OSVersion": self.os_version,
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class TraeCredentials:
|
|
81
|
+
token: str = ""
|
|
82
|
+
refresh_token: str = ""
|
|
83
|
+
expired_at: str = ""
|
|
84
|
+
refresh_expired_at: str = ""
|
|
85
|
+
token_release_at: str = ""
|
|
86
|
+
user_id: str = ""
|
|
87
|
+
tenant_id: str = ""
|
|
88
|
+
host: str = "https://api.trae.cn"
|
|
89
|
+
region: str = "CN"
|
|
90
|
+
username: str = ""
|
|
91
|
+
jwt: str = ""
|
|
92
|
+
jwt_exp: float = 0.0
|
|
93
|
+
extra: dict = field(default_factory=dict)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _parse_iso(ts: str) -> float:
|
|
97
|
+
if not ts:
|
|
98
|
+
return 0.0
|
|
99
|
+
try:
|
|
100
|
+
from datetime import datetime, timezone
|
|
101
|
+
return datetime.fromisoformat(ts.replace("Z", "+00:00")).timestamp()
|
|
102
|
+
except Exception:
|
|
103
|
+
return 0.0
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _jwt_exp(jwt: str) -> float:
|
|
107
|
+
try:
|
|
108
|
+
payload_b64 = jwt.split(".")[1]
|
|
109
|
+
payload_b64 += "=" * (-len(payload_b64) % 4)
|
|
110
|
+
payload = json.loads(base64.urlsafe_b64decode(payload_b64))
|
|
111
|
+
return float(payload.get("exp", 0))
|
|
112
|
+
except Exception:
|
|
113
|
+
return 0.0
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class TraeAuth:
|
|
117
|
+
"""Loads Trae credentials and keeps a usable Cloud-IDE-JWT on hand."""
|
|
118
|
+
|
|
119
|
+
def __init__(
|
|
120
|
+
self,
|
|
121
|
+
storage_path: str | os.PathLike | None = None,
|
|
122
|
+
creds_file: str | os.PathLike | None = None,
|
|
123
|
+
client_id: str = DEFAULT_CLIENT_ID,
|
|
124
|
+
http: httpx.Client | None = None,
|
|
125
|
+
) -> None:
|
|
126
|
+
self.storage_path = Path(storage_path) if storage_path else DEFAULT_STORAGE
|
|
127
|
+
self.creds_file = Path(creds_file) if creds_file else Path.home() / ".traeapi" / "trae2api.json"
|
|
128
|
+
self.client_id = client_id
|
|
129
|
+
self.http = http or httpx.Client(timeout=30, headers={"User-Agent": USER_AGENT})
|
|
130
|
+
self.creds = TraeCredentials()
|
|
131
|
+
self.device = DeviceInfo()
|
|
132
|
+
self.private_key = None
|
|
133
|
+
|
|
134
|
+
# ---------- loading ----------
|
|
135
|
+
|
|
136
|
+
def load(self) -> TraeCredentials:
|
|
137
|
+
"""Load credentials: own file first, then live Trae storage.json."""
|
|
138
|
+
if self.creds_file.exists():
|
|
139
|
+
data = json.loads(self.creds_file.read_text(encoding="utf-8"))
|
|
140
|
+
auth = data.get("auth", data)
|
|
141
|
+
self.creds = TraeCredentials(
|
|
142
|
+
token=auth.get("token", ""),
|
|
143
|
+
refresh_token=auth.get("refreshToken", ""),
|
|
144
|
+
expired_at=auth.get("expiredAt", ""),
|
|
145
|
+
refresh_expired_at=auth.get("refreshExpiredAt", ""),
|
|
146
|
+
token_release_at=auth.get("tokenReleaseAt", ""),
|
|
147
|
+
user_id=auth.get("userId", ""),
|
|
148
|
+
host=auth.get("host", "https://api.trae.cn"),
|
|
149
|
+
region=(auth.get("userRegion") or {}).get("region", "CN") if isinstance(auth.get("userRegion"), dict) else str(auth.get("userRegion") or "CN"),
|
|
150
|
+
username=auth.get("username", ""),
|
|
151
|
+
jwt=auth.get("jwt", ""),
|
|
152
|
+
jwt_exp=auth.get("jwt_exp", 0.0),
|
|
153
|
+
extra=auth.get("extra", {}),
|
|
154
|
+
)
|
|
155
|
+
dev = data.get("device", {})
|
|
156
|
+
self.device = DeviceInfo(
|
|
157
|
+
device_id=dev.get("deviceId", ""),
|
|
158
|
+
machine_id=dev.get("machineId", ""),
|
|
159
|
+
device_name=dev.get("deviceName", "trae2api"),
|
|
160
|
+
device_model=dev.get("deviceModel", ""),
|
|
161
|
+
device_brand=dev.get("deviceBrand", ""),
|
|
162
|
+
device_cpu=dev.get("deviceCpu", ""),
|
|
163
|
+
client_version=dev.get("clientVersion") or client_version(),
|
|
164
|
+
os_info=dev.get("osInfo", "Windows"),
|
|
165
|
+
os_version=dev.get("osVersion", "10"),
|
|
166
|
+
)
|
|
167
|
+
if dev.get("privateKeyPEM"):
|
|
168
|
+
self.private_key = serialization.load_pem_private_key(dev["privateKeyPEM"].encode(), password=None)
|
|
169
|
+
self.device.device_public_key = self.private_key.public_key().public_bytes(
|
|
170
|
+
serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo
|
|
171
|
+
).decode()
|
|
172
|
+
if not self.creds.jwt and self.creds.token:
|
|
173
|
+
self.creds.jwt = self.creds.token
|
|
174
|
+
self.creds.jwt_exp = _jwt_exp(self.creds.jwt)
|
|
175
|
+
return self.creds
|
|
176
|
+
|
|
177
|
+
if self.storage_path.exists():
|
|
178
|
+
return self._load_from_trae_storage()
|
|
179
|
+
raise FileNotFoundError(
|
|
180
|
+
f"No credentials: neither {self.creds_file} nor Trae storage at {self.storage_path}"
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
def _load_from_trae_storage(self) -> TraeCredentials:
|
|
184
|
+
raw = json.loads(self.storage_path.read_text(encoding="utf-8"))
|
|
185
|
+
auth_plain = decrypt_value(raw["iCubeAuthInfo://icube.cloudide"])
|
|
186
|
+
if not auth_plain:
|
|
187
|
+
raise ValueError("Failed to decrypt iCubeAuthInfo://icube.cloudide")
|
|
188
|
+
auth = json.loads(auth_plain)
|
|
189
|
+
self.creds = TraeCredentials(
|
|
190
|
+
token=auth.get("token", ""),
|
|
191
|
+
refresh_token=auth.get("refreshToken", ""),
|
|
192
|
+
expired_at=auth.get("expiredAt", ""),
|
|
193
|
+
refresh_expired_at=auth.get("refreshExpiredAt", ""),
|
|
194
|
+
token_release_at=auth.get("tokenReleaseAt", ""),
|
|
195
|
+
user_id=auth.get("userId", ""),
|
|
196
|
+
host=auth.get("host", "https://api.trae.cn"),
|
|
197
|
+
region=(auth.get("userRegion") or {}).get("region", "CN"),
|
|
198
|
+
username=auth.get("account", {}).get("username", ""),
|
|
199
|
+
)
|
|
200
|
+
# device keypair (optional; needed only for refresh)
|
|
201
|
+
dc_key = next((k for k in raw if k.startswith("iCubeAuthInfo://icube-dc:")), None)
|
|
202
|
+
if dc_key:
|
|
203
|
+
dc_plain = decrypt_value(raw[dc_key])
|
|
204
|
+
if dc_plain:
|
|
205
|
+
dc = json.loads(dc_plain)
|
|
206
|
+
try:
|
|
207
|
+
self.private_key = serialization.load_pem_private_key(dc["privateKeyPEM"].encode(), password=None)
|
|
208
|
+
pub = self.private_key.public_key().public_bytes(
|
|
209
|
+
serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo
|
|
210
|
+
).decode()
|
|
211
|
+
self.device.device_public_key = pub
|
|
212
|
+
self.device.device_id = dc_key.rsplit(":", 1)[1]
|
|
213
|
+
except Exception:
|
|
214
|
+
self.private_key = None
|
|
215
|
+
# machineId from same file
|
|
216
|
+
mid = raw.get("telemetry.machineId")
|
|
217
|
+
if mid:
|
|
218
|
+
self.device.machine_id = mid
|
|
219
|
+
self.creds.jwt = self.creds.token
|
|
220
|
+
self.creds.jwt_exp = _jwt_exp(self.creds.jwt)
|
|
221
|
+
return self.creds
|
|
222
|
+
|
|
223
|
+
def save(self) -> None:
|
|
224
|
+
data = {
|
|
225
|
+
"auth": {
|
|
226
|
+
"token": self.creds.token,
|
|
227
|
+
"refreshToken": self.creds.refresh_token,
|
|
228
|
+
"expiredAt": self.creds.expired_at,
|
|
229
|
+
"refreshExpiredAt": self.creds.refresh_expired_at,
|
|
230
|
+
"tokenReleaseAt": self.creds.token_release_at,
|
|
231
|
+
"userId": self.creds.user_id,
|
|
232
|
+
"host": self.creds.host,
|
|
233
|
+
"userRegion": {"region": self.creds.region},
|
|
234
|
+
"username": self.creds.username,
|
|
235
|
+
"jwt": self.creds.jwt,
|
|
236
|
+
"jwt_exp": self.creds.jwt_exp,
|
|
237
|
+
"extra": self.creds.extra,
|
|
238
|
+
},
|
|
239
|
+
"device": {
|
|
240
|
+
"deviceId": self.device.device_id,
|
|
241
|
+
"machineId": self.device.machine_id,
|
|
242
|
+
"deviceName": self.device.device_name,
|
|
243
|
+
"deviceModel": self.device.device_model,
|
|
244
|
+
"deviceBrand": self.device.device_brand,
|
|
245
|
+
"deviceCpu": self.device.device_cpu,
|
|
246
|
+
"clientVersion": self.device.client_version,
|
|
247
|
+
"osInfo": self.device.os_info,
|
|
248
|
+
"osVersion": self.device.os_version,
|
|
249
|
+
"privateKeyPEM": self.private_key.private_bytes(
|
|
250
|
+
serialization.Encoding.PEM,
|
|
251
|
+
serialization.PrivateFormat.PKCS8,
|
|
252
|
+
serialization.NoEncryption(),
|
|
253
|
+
).decode() if self.private_key else "",
|
|
254
|
+
},
|
|
255
|
+
}
|
|
256
|
+
self.creds_file.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
257
|
+
|
|
258
|
+
# ---------- token lifecycle ----------
|
|
259
|
+
|
|
260
|
+
def token_valid(self, margin_sec: float = 3600) -> bool:
|
|
261
|
+
if not self.creds.jwt:
|
|
262
|
+
return False
|
|
263
|
+
exp = self.creds.jwt_exp or _jwt_exp(self.creds.jwt)
|
|
264
|
+
if not exp:
|
|
265
|
+
return False
|
|
266
|
+
return time.time() < exp - margin_sec
|
|
267
|
+
|
|
268
|
+
def cloudide_token_expired(self) -> bool:
|
|
269
|
+
exp = _parse_iso(self.creds.expired_at)
|
|
270
|
+
return bool(exp and time.time() > exp - 3600)
|
|
271
|
+
|
|
272
|
+
def get_jwt(self, force_refresh: bool = False) -> str:
|
|
273
|
+
"""Return a valid Cloud-IDE-JWT, refreshing as needed (non-destructive first)."""
|
|
274
|
+
if force_refresh or not self.token_valid():
|
|
275
|
+
self.refresh_jwt()
|
|
276
|
+
return self.creds.jwt
|
|
277
|
+
|
|
278
|
+
def refresh_jwt(self) -> str:
|
|
279
|
+
"""Mint a fresh JWT via /api/v2/GetUserToken from the cloudide token."""
|
|
280
|
+
if self.cloudide_token_expired():
|
|
281
|
+
allow_rotation = os.environ.get("TRAE2API_ALLOW_ROTATION") == "1"
|
|
282
|
+
if not allow_rotation:
|
|
283
|
+
raise RuntimeError(
|
|
284
|
+
"cloudide token expired; set TRAE2API_ALLOW_ROTATION=1 to rotate "
|
|
285
|
+
"the RefreshToken (this may log out the running Trae IDE)"
|
|
286
|
+
)
|
|
287
|
+
self.exchange_refresh_token()
|
|
288
|
+
url = f"{self.creds.host}/api/v2/GetUserToken"
|
|
289
|
+
r = self.http.post(url, json={}, headers={"X-Cloudide-Token": self.creds.token})
|
|
290
|
+
r.raise_for_status()
|
|
291
|
+
result = (r.json() or {}).get("Result") or {}
|
|
292
|
+
jwt = result.get("Token")
|
|
293
|
+
if not jwt:
|
|
294
|
+
raise RuntimeError(f"GetUserToken returned no Token: {list((r.json() or {}).keys())}")
|
|
295
|
+
self.creds.jwt = jwt
|
|
296
|
+
self.creds.jwt_exp = _jwt_exp(jwt)
|
|
297
|
+
if result.get("UserID"):
|
|
298
|
+
self.creds.user_id = str(result["UserID"])
|
|
299
|
+
if result.get("TenantID"):
|
|
300
|
+
self.creds.tenant_id = str(result["TenantID"])
|
|
301
|
+
return self.creds.jwt
|
|
302
|
+
|
|
303
|
+
# ---------- refresh token exchange (rotates; use carefully) ----------
|
|
304
|
+
|
|
305
|
+
def sign_device_proof(self, method: str, path: str) -> dict:
|
|
306
|
+
if self.private_key is None:
|
|
307
|
+
raise RuntimeError("device private key not loaded; cannot sign DeviceProof")
|
|
308
|
+
ts = int(time.time())
|
|
309
|
+
nonce = secrets.token_hex(16)
|
|
310
|
+
payload = "\n".join([method, path, self.client_id, self.creds.refresh_token, str(ts), nonce])
|
|
311
|
+
sig = self.private_key.sign(payload.encode(), ec.ECDSA(hashes.SHA256()))
|
|
312
|
+
return {"Signature": base64.b64encode(sig).decode(), "Timestamp": ts, "Nonce": nonce}
|
|
313
|
+
|
|
314
|
+
def exchange_refresh_token(self) -> dict:
|
|
315
|
+
"""POST /trae/api/v3/oauth/ExchangeToken (rotates the refresh token)."""
|
|
316
|
+
path = EXCHANGE_PATH
|
|
317
|
+
proof = self.sign_device_proof("POST", path)
|
|
318
|
+
body = {
|
|
319
|
+
"ClientID": self.client_id,
|
|
320
|
+
"ClientSecret": "",
|
|
321
|
+
"RefreshToken": self.creds.refresh_token,
|
|
322
|
+
"DeviceInfo": self.device.to_payload(),
|
|
323
|
+
"DeviceProof": proof,
|
|
324
|
+
"IDEVersion": IDE_VERSION,
|
|
325
|
+
}
|
|
326
|
+
r = self.http.post(f"{self.creds.host}{path}", json=body)
|
|
327
|
+
data = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}
|
|
328
|
+
err = (data.get("ResponseMetadata") or {}).get("Error") or {}
|
|
329
|
+
if err.get("Code"):
|
|
330
|
+
raise RuntimeError(f"ExchangeToken error {err.get('Code')}: {err.get('Message')}")
|
|
331
|
+
result = data.get("Result") or {}
|
|
332
|
+
token = result.get("Token")
|
|
333
|
+
if not token:
|
|
334
|
+
raise RuntimeError(f"ExchangeToken returned no Token (HTTP {r.status_code}): {r.text[:200]}")
|
|
335
|
+
self.creds.token = token
|
|
336
|
+
self.creds.refresh_token = result.get("RefreshToken", self.creds.refresh_token)
|
|
337
|
+
self.creds.expired_at = _ms_to_iso(result.get("TokenExpireAt"))
|
|
338
|
+
self.creds.refresh_expired_at = _ms_to_iso(result.get("RefreshExpireAt"))
|
|
339
|
+
self.creds.jwt = token
|
|
340
|
+
self.creds.jwt_exp = _jwt_exp(token)
|
|
341
|
+
return result
|
|
342
|
+
|
|
343
|
+
# ---------- headers ----------
|
|
344
|
+
|
|
345
|
+
def auth_headers(self) -> dict:
|
|
346
|
+
jwt = self.get_jwt()
|
|
347
|
+
return {
|
|
348
|
+
"Authorization": f"Cloud-IDE-JWT {jwt}",
|
|
349
|
+
"X-User-Region": self.creds.region,
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
def internal_headers(self) -> dict:
|
|
353
|
+
jwt = self.get_jwt()
|
|
354
|
+
return {"x-cloudide-token": jwt}
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _ms_to_iso(ms) -> str:
|
|
358
|
+
try:
|
|
359
|
+
from datetime import datetime, timezone
|
|
360
|
+
return datetime.fromtimestamp(float(ms) / 1000, tz=timezone.utc).isoformat().replace("+00:00", "Z")
|
|
361
|
+
except Exception:
|
|
362
|
+
return ""
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Read non-secret metadata from the local client and operating system."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import platform
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class InstalledClient:
|
|
15
|
+
app_version: str = ""
|
|
16
|
+
editor_version: str = "1.107.1"
|
|
17
|
+
name: str = "Trae CN"
|
|
18
|
+
ug_url: str = "https://api.trae.cn"
|
|
19
|
+
telemetry_enabled: bool = True
|
|
20
|
+
build_version: str = "local"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def installed_client() -> InstalledClient:
|
|
24
|
+
paths = []
|
|
25
|
+
if os.environ.get("TRAE2API_PRODUCT_JSON"):
|
|
26
|
+
paths.append(Path(os.environ["TRAE2API_PRODUCT_JSON"]))
|
|
27
|
+
if os.environ.get("LOCALAPPDATA"):
|
|
28
|
+
paths.append(Path(os.environ["LOCALAPPDATA"]) / "Programs/Trae CN/resources/app/product.json")
|
|
29
|
+
# Python is often installed in the same per-user Programs directory.
|
|
30
|
+
paths.append(Path(sys.base_prefix).parent.parent / "Trae CN/resources/app/product.json")
|
|
31
|
+
for path in paths:
|
|
32
|
+
try:
|
|
33
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
34
|
+
value = data.get("appVersion") if isinstance(data, dict) else None
|
|
35
|
+
if isinstance(value, str) and re.fullmatch(r"\d+\.\d+\.\d+(?:[-+][\w.-]+)?", value):
|
|
36
|
+
try:
|
|
37
|
+
package = json.loads(path.with_name("package.json").read_text(encoding="utf-8"))
|
|
38
|
+
except (OSError, ValueError):
|
|
39
|
+
package = {}
|
|
40
|
+
editor = package.get("version", "") if isinstance(package, dict) else ""
|
|
41
|
+
if not isinstance(editor, str) or not re.fullmatch(r"\d+\.\d+\.\d+(?:[-+][\w.-]+)?", editor):
|
|
42
|
+
editor = "1.107.1" # Reviewed 3.4.20 installation fallback.
|
|
43
|
+
ug = data.get("bootConfig", {}).get("ug", {}).get("trae", {}).get("normal")
|
|
44
|
+
name = data.get("nameShort")
|
|
45
|
+
return InstalledClient(value, editor, name if isinstance(name, str) and name else "Trae CN",
|
|
46
|
+
ug if isinstance(ug, str) and ug else "https://api.trae.cn",
|
|
47
|
+
data.get("enableTelemetry") is not False,
|
|
48
|
+
data.get("tronBuildVersion") or "local")
|
|
49
|
+
except (OSError, ValueError):
|
|
50
|
+
continue
|
|
51
|
+
return InstalledClient()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def installed_version() -> str:
|
|
55
|
+
return installed_client().app_version
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def client_version(fallback: str = "3.4.4") -> str:
|
|
59
|
+
return installed_version() or fallback
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def device_model() -> str:
|
|
63
|
+
"""Read the actual system product name; never use the account/device name."""
|
|
64
|
+
if sys.platform == "win32":
|
|
65
|
+
try:
|
|
66
|
+
import winreg
|
|
67
|
+
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\BIOS") as key:
|
|
68
|
+
value, _ = winreg.QueryValueEx(key, "SystemProductName")
|
|
69
|
+
return clean_model(value)
|
|
70
|
+
except OSError:
|
|
71
|
+
return ""
|
|
72
|
+
return ""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def clean_model(value: str) -> str:
|
|
76
|
+
# Same control-character filtering as the native HF helper.
|
|
77
|
+
return re.sub(r"[\x00-\x08\x0a-\x1f\x7f]", "", value) if isinstance(value, str) else ""
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def os_metadata() -> tuple[str, str]:
|
|
81
|
+
name = platform.system()
|
|
82
|
+
if name == "Windows":
|
|
83
|
+
# Node/libuv os.version() uses Windows' ProductName, including edition.
|
|
84
|
+
try:
|
|
85
|
+
import winreg
|
|
86
|
+
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
|
|
87
|
+
r"SOFTWARE\Microsoft\Windows NT\CurrentVersion") as key:
|
|
88
|
+
version, _ = winreg.QueryValueEx(key, "ProductName")
|
|
89
|
+
if isinstance(version, str) and version:
|
|
90
|
+
return "windows", version
|
|
91
|
+
except OSError:
|
|
92
|
+
pass
|
|
93
|
+
return "windows", f"Windows {platform.win32_ver()[0] or platform.release()}"
|
|
94
|
+
if name == "Darwin":
|
|
95
|
+
return "mac", f"macOS {platform.mac_ver()[0]}"
|
|
96
|
+
if name == "Linux":
|
|
97
|
+
try:
|
|
98
|
+
values = platform.freedesktop_os_release()
|
|
99
|
+
return "linux", values.get("PRETTY_NAME") or "Linux"
|
|
100
|
+
except OSError:
|
|
101
|
+
return "linux", "Linux"
|
|
102
|
+
return name.lower(), ""
|