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,415 @@
|
|
|
1
|
+
"""Independent OAuth login flow for Trae CN with a persistent device profile.
|
|
2
|
+
|
|
3
|
+
Reverse engineered from out-build/vs/code/electron-main/oauth/marscode/ (login.js,
|
|
4
|
+
userLogin/loginUrlBuilder.js, oauthLocalServer.js):
|
|
5
|
+
|
|
6
|
+
1. Resolve/register real hardware, persist its remote device ID and ECDSA
|
|
7
|
+
P-256 keypair independently, and generate a fresh PKCE pair (S256).
|
|
8
|
+
2. Serve a one-shot local HTTP server on 127.0.0.1:<random> listening for
|
|
9
|
+
GET /authorize (also /login-confirm, /login-success).
|
|
10
|
+
3. Open the browser at
|
|
11
|
+
{consoleHost}/authorization?login_version=1&auth_from=trae&login_channel=native_ide
|
|
12
|
+
&auth_type=local&client_id={ClientID}&redirect=0&login_trace_id={uuid}
|
|
13
|
+
&auth_callback_url=http://127.0.0.1:{port}/authorize&machine_id=...&device_id=...
|
|
14
|
+
&x_device_id=...&x_machine_id=...&x_device_brand=...&x_device_type=...
|
|
15
|
+
&x_os_version=...&x_app_version=...&x_app_type=trae
|
|
16
|
+
&code_challenge={S256}&code_challenge_method=S256
|
|
17
|
+
4. The web app redirects back with authCodeInfo={"AuthCode": "..."} (URL-encoded JSON).
|
|
18
|
+
5. POST {apiHost}/trae/api/v3/oauth/ExchangeToken
|
|
19
|
+
{ClientID, AuthCode, CodeVerifier, DeviceInfo, IDEVersion} (no DeviceProof)
|
|
20
|
+
-> Result.{Token, RefreshToken, TokenExpireAt, TokenExpireDuration, RefreshExpireAt}
|
|
21
|
+
6. POST {apiHost}/cloudide/api/v3/trae/GetUserInfo (x-cloudide-token) for the profile.
|
|
22
|
+
7. Persist everything to trae2api.json (same format TraeAuth.load() consumes).
|
|
23
|
+
|
|
24
|
+
Usage: python -m buddy_agent_auth.providers.trae.login [--timeout 1800] [--no-browser]
|
|
25
|
+
"""
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import base64
|
|
29
|
+
import hashlib
|
|
30
|
+
import json
|
|
31
|
+
import os
|
|
32
|
+
import secrets
|
|
33
|
+
import threading
|
|
34
|
+
import time
|
|
35
|
+
import uuid
|
|
36
|
+
import webbrowser
|
|
37
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
38
|
+
from pathlib import Path
|
|
39
|
+
from urllib.parse import parse_qs, urlencode, urlparse
|
|
40
|
+
|
|
41
|
+
import httpx
|
|
42
|
+
|
|
43
|
+
from cryptography.hazmat.primitives import serialization
|
|
44
|
+
|
|
45
|
+
from .auth import DEFAULT_CLIENT_ID, TraeAuth
|
|
46
|
+
from .client_metadata import client_version, device_model, installed_client, os_metadata
|
|
47
|
+
from .device_hardware import Hardware, manufacturer, cpu_brand
|
|
48
|
+
from .login_identity import IdentityStore
|
|
49
|
+
from .aha_device_service import AhaDeviceService
|
|
50
|
+
|
|
51
|
+
CONSOLE_HOST = os.environ.get("TRAE2API_CONSOLE_HOST", "https://www.trae.cn")
|
|
52
|
+
API_HOST = os.environ.get("TRAE2API_API_HOST", "https://api.trae.cn")
|
|
53
|
+
SUCCESS_HTML = "<html><body><h3>trae2api: login received. You can close this tab.</h3></body></html>"
|
|
54
|
+
|
|
55
|
+
_legacy_credentials_file: Path | None = None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def configure_legacy_credentials(path: Path | None) -> None:
|
|
59
|
+
global _legacy_credentials_file
|
|
60
|
+
_legacy_credentials_file = Path(path) if path is not None else None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def default_credentials_file() -> Path:
|
|
64
|
+
if _legacy_credentials_file is not None:
|
|
65
|
+
return _legacy_credentials_file
|
|
66
|
+
from .app_storage import root
|
|
67
|
+
return root() / "trae2api.json"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class TraeLoginFlow:
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
client_id: str = DEFAULT_CLIENT_ID,
|
|
74
|
+
console_host: str = CONSOLE_HOST,
|
|
75
|
+
api_host: str = API_HOST,
|
|
76
|
+
creds_file: str | os.PathLike | None = None,
|
|
77
|
+
device_name: str | None = None,
|
|
78
|
+
http: httpx.Client | None = None,
|
|
79
|
+
) -> None:
|
|
80
|
+
self.client_id = client_id
|
|
81
|
+
self.console_host = console_host.rstrip("/")
|
|
82
|
+
self.api_host = api_host.rstrip("/")
|
|
83
|
+
self.creds_file = Path(creds_file) if creds_file else default_credentials_file()
|
|
84
|
+
|
|
85
|
+
self.http = http or httpx.Client(timeout=60, trust_env=False)
|
|
86
|
+
self._owns_http = http is None
|
|
87
|
+
self.identity_store = IdentityStore(self.creds_file)
|
|
88
|
+
with self.identity_store.locked():
|
|
89
|
+
self.identity = self.identity_store.load()
|
|
90
|
+
self.identity_store.save(self.identity)
|
|
91
|
+
self.device_id = self.identity.device_id
|
|
92
|
+
self.machine_id = self.identity.machine_id
|
|
93
|
+
self.device_name = device_name or f"{os.environ.get('USERNAME') or os.environ.get('USER') or 'trae'}2api"
|
|
94
|
+
self.client_version = client_version("3.4.20")
|
|
95
|
+
self.device_model = device_model()
|
|
96
|
+
self.device_brand = manufacturer()
|
|
97
|
+
self.os_name, self.os_version = os_metadata()
|
|
98
|
+
self.device_cpu = cpu_brand()
|
|
99
|
+
self.private_key_pem = self.identity.private_key_pem
|
|
100
|
+
self.public_key_pem = self.identity.public_key_pem
|
|
101
|
+
product = installed_client()
|
|
102
|
+
self.user_agent = f"VSCode {product.editor_version} ({product.name})"
|
|
103
|
+
self.plugin_version = product.build_version
|
|
104
|
+
self.http.headers["User-Agent"] = self.user_agent
|
|
105
|
+
|
|
106
|
+
# PKCE (Mxe(): verifier 48 random bytes base64url, challenge sha256 b64url)
|
|
107
|
+
self.code_verifier = base64.urlsafe_b64encode(secrets.token_bytes(48)).decode().rstrip("=")
|
|
108
|
+
self.code_challenge = base64.urlsafe_b64encode(
|
|
109
|
+
hashlib.sha256(self.code_verifier.encode()).digest()
|
|
110
|
+
).decode().rstrip("=")
|
|
111
|
+
|
|
112
|
+
self.login_trace_id = str(uuid.uuid4())
|
|
113
|
+
self.result: dict = {}
|
|
114
|
+
self.error_code: str | None = None
|
|
115
|
+
self._server: ThreadingHTTPServer | None = None
|
|
116
|
+
self._done = threading.Event()
|
|
117
|
+
|
|
118
|
+
def prepare_device(self) -> None:
|
|
119
|
+
"""Register once, resume activation if needed, and reuse the same key."""
|
|
120
|
+
result = AhaDeviceService(self.identity_store, http=self.http, version=self.client_version).get_device_id(
|
|
121
|
+
allow_network=True, require_activation=True)
|
|
122
|
+
identity, hardware = result.identity, result.hardware
|
|
123
|
+
self.identity = identity
|
|
124
|
+
self.device_id, self.machine_id = identity.device_id, identity.machine_id
|
|
125
|
+
self.private_key_pem, self.public_key_pem = identity.private_key_pem, identity.public_key_pem
|
|
126
|
+
self.device_model, self.device_brand, self.device_cpu = hardware.model, hardware.brand, hardware.cpu
|
|
127
|
+
self.os_name, self.os_version = hardware.os_name, hardware.os_version
|
|
128
|
+
|
|
129
|
+
# ---------- local callback server ----------
|
|
130
|
+
|
|
131
|
+
def _start_server(self) -> int:
|
|
132
|
+
flow = self
|
|
133
|
+
|
|
134
|
+
class Handler(BaseHTTPRequestHandler):
|
|
135
|
+
def do_GET(self): # noqa: N802
|
|
136
|
+
parsed = urlparse(self.path)
|
|
137
|
+
qs = {k: v[0] for k, v in parse_qs(parsed.query).items()}
|
|
138
|
+
if parsed.path == "/authorize":
|
|
139
|
+
err = qs.get("error_code")
|
|
140
|
+
if err:
|
|
141
|
+
flow.error_code = err
|
|
142
|
+
auth_info_raw = qs.get("authCodeInfo", "")
|
|
143
|
+
try:
|
|
144
|
+
auth_info = json.loads(auth_info_raw) if auth_info_raw else {}
|
|
145
|
+
except json.JSONDecodeError:
|
|
146
|
+
auth_info = {}
|
|
147
|
+
auth_code = auth_info.get("AuthCode", "") if isinstance(auth_info, dict) else ""
|
|
148
|
+
if isinstance(auth_code, str) and auth_code:
|
|
149
|
+
flow.result["AuthCode"] = auth_code
|
|
150
|
+
flow.result["userInfo"] = qs.get("userInfo", "")
|
|
151
|
+
self._respond(SUCCESS_HTML)
|
|
152
|
+
flow._done.set()
|
|
153
|
+
elif err:
|
|
154
|
+
self._respond("<html><body>Login failed.</body></html>", 400)
|
|
155
|
+
flow._done.set()
|
|
156
|
+
else:
|
|
157
|
+
self._respond("<html><body>Missing authorization code.</body></html>", 400)
|
|
158
|
+
elif parsed.path in ("/login-confirm", "/login-success"):
|
|
159
|
+
self._respond("<html><body>Waiting for authorization callback.</body></html>")
|
|
160
|
+
else:
|
|
161
|
+
self._respond("<html><body>unknown path</body></html>", 404)
|
|
162
|
+
|
|
163
|
+
def _respond(self, body: str, code: int = 200) -> None:
|
|
164
|
+
data = body.encode("utf-8")
|
|
165
|
+
self.send_response(code)
|
|
166
|
+
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
167
|
+
self.send_header("Content-Length", str(len(data)))
|
|
168
|
+
self.end_headers()
|
|
169
|
+
self.wfile.write(data)
|
|
170
|
+
|
|
171
|
+
def log_message(self, fmt, *args): # silence default logging
|
|
172
|
+
pass
|
|
173
|
+
|
|
174
|
+
self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
175
|
+
port = self._server.server_address[1]
|
|
176
|
+
t = threading.Thread(target=self._server.serve_forever, daemon=True)
|
|
177
|
+
t.start()
|
|
178
|
+
return port
|
|
179
|
+
|
|
180
|
+
# ---------- login url ----------
|
|
181
|
+
|
|
182
|
+
def build_login_url(self, port: int) -> str:
|
|
183
|
+
callback = f"http://127.0.0.1:{port}/authorize"
|
|
184
|
+
params = {
|
|
185
|
+
"login_version": "1",
|
|
186
|
+
"auth_from": "trae",
|
|
187
|
+
"login_channel": "native_ide",
|
|
188
|
+
"plugin_version": self.plugin_version,
|
|
189
|
+
"auth_type": "local",
|
|
190
|
+
"client_id": self.client_id,
|
|
191
|
+
"redirect": "0",
|
|
192
|
+
"login_trace_id": self.login_trace_id,
|
|
193
|
+
"auth_callback_url": callback,
|
|
194
|
+
"machine_id": self.machine_id,
|
|
195
|
+
"device_id": self.device_id,
|
|
196
|
+
"x_device_id": self.device_id,
|
|
197
|
+
"x_machine_id": self.machine_id,
|
|
198
|
+
"x_device_brand": self.device_model,
|
|
199
|
+
"x_device_type": self.os_name,
|
|
200
|
+
"x_os_version": self.os_version,
|
|
201
|
+
"x_app_version": self.client_version,
|
|
202
|
+
"x_app_type": "trae",
|
|
203
|
+
"code_challenge": self.code_challenge,
|
|
204
|
+
"code_challenge_method": "S256",
|
|
205
|
+
}
|
|
206
|
+
return f"{self.console_host}/authorization?{urlencode(params)}"
|
|
207
|
+
|
|
208
|
+
# ---------- exchange ----------
|
|
209
|
+
|
|
210
|
+
def _device_info(self) -> dict:
|
|
211
|
+
return {
|
|
212
|
+
"DeviceID": self.device_id,
|
|
213
|
+
"MachineID": self.machine_id,
|
|
214
|
+
"PlatformCode": "IDE_PC",
|
|
215
|
+
"DeviceType": "PC",
|
|
216
|
+
"DeviceName": self.device_name,
|
|
217
|
+
"DeviceModel": self.device_model,
|
|
218
|
+
"ClientVersion": self.client_version,
|
|
219
|
+
"DevicePublicKey": self.public_key_pem,
|
|
220
|
+
"DeviceBrand": self.device_brand,
|
|
221
|
+
"DeviceCPU": self.device_cpu,
|
|
222
|
+
"OSInfo": self.os_name,
|
|
223
|
+
"OSVersion": self.os_version,
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
def _post_json(self, url: str, body: dict, token: str = "") -> dict:
|
|
227
|
+
try:
|
|
228
|
+
response = self.http.post(url, content=json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode(),
|
|
229
|
+
headers={"Content-Type": "application/json", "x-cloudide-token": token,
|
|
230
|
+
"User-Agent": self.user_agent}, follow_redirects=False)
|
|
231
|
+
except httpx.HTTPError as exc:
|
|
232
|
+
raise ValueError(f"login network error ({type(exc).__name__}); not retried") from None
|
|
233
|
+
if response.status_code != 200:
|
|
234
|
+
raise ValueError(f"login request failed: HTTP {response.status_code}")
|
|
235
|
+
try:
|
|
236
|
+
data = response.json()
|
|
237
|
+
except ValueError:
|
|
238
|
+
raise ValueError("login endpoint returned invalid JSON") from None
|
|
239
|
+
if not isinstance(data, dict):
|
|
240
|
+
raise ValueError("login endpoint returned an invalid object")
|
|
241
|
+
return data
|
|
242
|
+
|
|
243
|
+
def exchange_auth_code(self, auth_code: str) -> dict:
|
|
244
|
+
url = f"{self.api_host}/trae/api/v3/oauth/ExchangeToken"
|
|
245
|
+
body = {
|
|
246
|
+
"ClientID": self.client_id,
|
|
247
|
+
"AuthCode": auth_code,
|
|
248
|
+
"CodeVerifier": self.code_verifier,
|
|
249
|
+
"DeviceInfo": self._device_info(),
|
|
250
|
+
"IDEVersion": self.client_version,
|
|
251
|
+
}
|
|
252
|
+
data = self._post_json(url, body)
|
|
253
|
+
metadata = data.get("ResponseMetadata") or {}
|
|
254
|
+
if not isinstance(metadata, dict):
|
|
255
|
+
raise RuntimeError("ExchangeToken returned invalid metadata")
|
|
256
|
+
err = metadata.get("Error") or {}
|
|
257
|
+
if not isinstance(err, dict):
|
|
258
|
+
raise RuntimeError("ExchangeToken returned an invalid error object")
|
|
259
|
+
if err.get("Code"):
|
|
260
|
+
raise RuntimeError("ExchangeToken was rejected by the server")
|
|
261
|
+
result = data.get("Result") or {}
|
|
262
|
+
if not isinstance(result, dict) or not isinstance(result.get("Token"), str) or not result["Token"]:
|
|
263
|
+
raise RuntimeError("ExchangeToken returned no valid Token")
|
|
264
|
+
return result
|
|
265
|
+
|
|
266
|
+
def fetch_user_info(self, token: str) -> dict:
|
|
267
|
+
url = f"{self.api_host}/cloudide/api/v3/trae/GetUserInfo"
|
|
268
|
+
body = {"ReqSource": "IDE", "IDEVersion": self.client_version}
|
|
269
|
+
data = self._post_json(url, body, token=token)
|
|
270
|
+
metadata = data.get("ResponseMetadata") or {}
|
|
271
|
+
if not isinstance(metadata, dict) or metadata.get("Error"):
|
|
272
|
+
raise RuntimeError("GetUserInfo was rejected by the server")
|
|
273
|
+
result = data.get("Result")
|
|
274
|
+
if not isinstance(result, dict):
|
|
275
|
+
raise RuntimeError("GetUserInfo returned no user profile")
|
|
276
|
+
return result
|
|
277
|
+
|
|
278
|
+
# ---------- orchestration ----------
|
|
279
|
+
|
|
280
|
+
def start(self, open_browser: bool = True, timeout_sec: float = 1800.0, log=print) -> TraeAuth:
|
|
281
|
+
try:
|
|
282
|
+
self.prepare_device()
|
|
283
|
+
return self._login(open_browser, timeout_sec, log)
|
|
284
|
+
finally:
|
|
285
|
+
if self._server is not None:
|
|
286
|
+
self._server.shutdown()
|
|
287
|
+
self._server.server_close()
|
|
288
|
+
self._server = None
|
|
289
|
+
if self._owns_http:
|
|
290
|
+
self.http.close()
|
|
291
|
+
|
|
292
|
+
def _login(self, open_browser: bool, timeout_sec: float, log) -> TraeAuth:
|
|
293
|
+
port = self._start_server()
|
|
294
|
+
url = self.build_login_url(port)
|
|
295
|
+
log("=" * 70)
|
|
296
|
+
log("trae2api login: open this URL in your browser and complete sign-in:")
|
|
297
|
+
log(url)
|
|
298
|
+
log("=" * 70)
|
|
299
|
+
if open_browser:
|
|
300
|
+
try:
|
|
301
|
+
webbrowser.open(url)
|
|
302
|
+
except Exception:
|
|
303
|
+
pass
|
|
304
|
+
if not self._done.wait(timeout_sec):
|
|
305
|
+
raise TimeoutError("login timed out waiting for the OAuth callback")
|
|
306
|
+
if self.error_code and "AuthCode" not in self.result:
|
|
307
|
+
raise RuntimeError("browser authorization failed")
|
|
308
|
+
auth_code = self.result["AuthCode"]
|
|
309
|
+
log("[login] received auth code, exchanging tokens ...")
|
|
310
|
+
result = self.exchange_auth_code(auth_code)
|
|
311
|
+
log("[login] exchange ok, fetching user info ...")
|
|
312
|
+
profile = self.fetch_user_info(result["Token"])
|
|
313
|
+
if not profile.get("UserID"):
|
|
314
|
+
raise RuntimeError("GetUserInfo did not identify the logged-in account; credentials were not replaced")
|
|
315
|
+
|
|
316
|
+
auth = TraeAuth(creds_file=self.creds_file)
|
|
317
|
+
auth.creds.token = result["Token"]
|
|
318
|
+
auth.creds.refresh_token = result.get("RefreshToken", "")
|
|
319
|
+
auth.creds.expired_at = _iso_from_ms_or_iso(result.get("TokenExpireAt"), result.get("TokenExpireDuration"))
|
|
320
|
+
auth.creds.refresh_expired_at = _iso_from_ms_or_iso(result.get("RefreshExpireAt"))
|
|
321
|
+
auth.creds.token_release_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
|
322
|
+
auth.creds.user_id = str(profile.get("UserID") or result.get("UserID") or "")
|
|
323
|
+
auth.creds.host = self.api_host
|
|
324
|
+
auth.creds.region = profile.get("AIRegion") or profile.get("Region") or "CN"
|
|
325
|
+
auth.creds.username = profile.get("ScreenName", "")
|
|
326
|
+
auth.creds.jwt = result["Token"]
|
|
327
|
+
from .auth import _jwt_exp
|
|
328
|
+
auth.creds.jwt_exp = _jwt_exp(result["Token"])
|
|
329
|
+
auth.creds.extra = {"tenant_id": profile.get("TenantID", "")}
|
|
330
|
+
|
|
331
|
+
auth.device.device_id = self.device_id
|
|
332
|
+
auth.device.machine_id = self.machine_id
|
|
333
|
+
auth.device.device_name = self.device_name
|
|
334
|
+
auth.device.device_model = self.device_model
|
|
335
|
+
auth.device.device_brand = self.device_brand
|
|
336
|
+
auth.device.client_version = self.client_version
|
|
337
|
+
auth.device.device_public_key = self.public_key_pem
|
|
338
|
+
auth.device.device_cpu = self.device_cpu
|
|
339
|
+
auth.device.os_info = self.os_name
|
|
340
|
+
auth.device.os_version = self.os_version
|
|
341
|
+
auth.private_key = serialization.load_pem_private_key(self.private_key_pem.encode(), password=None)
|
|
342
|
+
|
|
343
|
+
# Save through a private temporary file so a failed write does not
|
|
344
|
+
# truncate the previous independent login. Native storage is untouched.
|
|
345
|
+
import tempfile
|
|
346
|
+
with self.identity_store.locked():
|
|
347
|
+
current = self.identity_store.load()
|
|
348
|
+
if current.as_dict() != self.identity.as_dict():
|
|
349
|
+
auth.http.close()
|
|
350
|
+
raise RuntimeError("independent device profile changed during login; credentials were not replaced")
|
|
351
|
+
fd, name = tempfile.mkstemp(prefix=".login-", suffix=".secret", dir=self.creds_file.parent)
|
|
352
|
+
os.close(fd)
|
|
353
|
+
try:
|
|
354
|
+
auth.creds_file = Path(name)
|
|
355
|
+
auth.save()
|
|
356
|
+
os.replace(name, self.creds_file)
|
|
357
|
+
finally:
|
|
358
|
+
auth.creds_file = self.creds_file
|
|
359
|
+
if os.path.exists(name):
|
|
360
|
+
os.unlink(name)
|
|
361
|
+
log(f"[login] credentials saved to {self.creds_file}")
|
|
362
|
+
log(f"[login] user {auth.creds.user_id} ({auth.creds.username or 'unknown'}) region={auth.creds.region}")
|
|
363
|
+
log(f"[login] token expires {auth.creds.expired_at}, refresh expires {auth.creds.refresh_expired_at}")
|
|
364
|
+
return auth
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _iso_from_ms_or_iso(value, duration_ms=None) -> str:
|
|
368
|
+
from datetime import datetime, timezone
|
|
369
|
+
try:
|
|
370
|
+
if value is None and duration_ms:
|
|
371
|
+
return datetime.fromtimestamp(time.time() + float(duration_ms) / 1000, tz=timezone.utc).isoformat().replace("+00:00", "Z")
|
|
372
|
+
if value is None:
|
|
373
|
+
return ""
|
|
374
|
+
v = float(value)
|
|
375
|
+
if v > 10_000_000_000: # ms epoch
|
|
376
|
+
return datetime.fromtimestamp(v / 1000, tz=timezone.utc).isoformat().replace("+00:00", "Z")
|
|
377
|
+
if v > 10_000_000: # s epoch
|
|
378
|
+
return datetime.fromtimestamp(v, tz=timezone.utc).isoformat().replace("+00:00", "Z")
|
|
379
|
+
except (TypeError, ValueError):
|
|
380
|
+
pass
|
|
381
|
+
return str(value or "")
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def run_login(timeout_sec: float = 1800.0, open_browser: bool = True,
|
|
385
|
+
creds_file: str | os.PathLike | None = None, prepare_only: bool = False) -> TraeAuth | None:
|
|
386
|
+
flow = TraeLoginFlow(creds_file=creds_file)
|
|
387
|
+
if prepare_only:
|
|
388
|
+
try:
|
|
389
|
+
flow.prepare_device()
|
|
390
|
+
print(json.dumps({"action": "device_prepared", "registered": flow.identity.registered,
|
|
391
|
+
"activated": flow.identity.activated}))
|
|
392
|
+
finally:
|
|
393
|
+
flow.http.close()
|
|
394
|
+
return None
|
|
395
|
+
return flow.start(open_browser=open_browser, timeout_sec=timeout_sec)
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def main(argv=None) -> int:
|
|
399
|
+
import argparse
|
|
400
|
+
parser = argparse.ArgumentParser(prog="buddy-trae-login")
|
|
401
|
+
parser.add_argument("--timeout", type=float, default=1800.0)
|
|
402
|
+
parser.add_argument("--no-browser", action="store_true")
|
|
403
|
+
parser.add_argument("--creds")
|
|
404
|
+
parser.add_argument("--prepare-device", action="store_true")
|
|
405
|
+
args = parser.parse_args(argv)
|
|
406
|
+
try:
|
|
407
|
+
run_login(timeout_sec=args.timeout, open_browser=not args.no_browser,
|
|
408
|
+
creds_file=args.creds, prepare_only=args.prepare_device)
|
|
409
|
+
except (ValueError, RuntimeError, OSError, TimeoutError) as exc:
|
|
410
|
+
parser.exit(1, f"Login failed: {exc}\n")
|
|
411
|
+
return 0
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
if __name__ == "__main__":
|
|
415
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Independent, persistent login device identity; never reads native credentials."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from contextlib import contextmanager
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import secrets
|
|
11
|
+
import tempfile
|
|
12
|
+
|
|
13
|
+
from cryptography.hazmat.primitives import serialization
|
|
14
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def atomic_json(path: Path, value: dict) -> None:
|
|
18
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
19
|
+
fd, name = tempfile.mkstemp(prefix=".login-", suffix=".secret", dir=path.parent)
|
|
20
|
+
try:
|
|
21
|
+
with os.fdopen(fd, "w", encoding="utf-8") as output:
|
|
22
|
+
json.dump(value, output, ensure_ascii=False, indent=2)
|
|
23
|
+
output.write("\n")
|
|
24
|
+
output.flush()
|
|
25
|
+
os.fsync(output.fileno())
|
|
26
|
+
os.replace(name, path)
|
|
27
|
+
finally:
|
|
28
|
+
if os.path.exists(name):
|
|
29
|
+
os.unlink(name)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def new_key() -> str:
|
|
33
|
+
return ec.generate_private_key(ec.SECP256R1()).private_bytes(
|
|
34
|
+
serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()).decode()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class LoginIdentity:
|
|
39
|
+
machine_id: str = field(repr=False)
|
|
40
|
+
private_key_pem: str = field(repr=False)
|
|
41
|
+
device_id: str = field(default="", repr=False)
|
|
42
|
+
install_id: str = field(default="", repr=False)
|
|
43
|
+
registered: bool = False
|
|
44
|
+
activated: bool = False
|
|
45
|
+
region: str = "CN"
|
|
46
|
+
hardware_uuid: str = field(default="", repr=False)
|
|
47
|
+
device_cache: object = field(default=None, repr=False)
|
|
48
|
+
device_region: object = field(default=None, repr=False)
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def public_key_pem(self) -> str:
|
|
52
|
+
key = serialization.load_pem_private_key(self.private_key_pem.encode(), password=None)
|
|
53
|
+
if not isinstance(key, ec.EllipticCurvePrivateKey) or not isinstance(key.curve, ec.SECP256R1):
|
|
54
|
+
raise ValueError("independent device key must use ECDSA P-256")
|
|
55
|
+
return key.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo).decode()
|
|
56
|
+
|
|
57
|
+
def as_dict(self) -> dict:
|
|
58
|
+
result = {"version": 1, "machineId": self.machine_id, "privateKeyPEM": self.private_key_pem,
|
|
59
|
+
"deviceId": self.device_id, "installId": self.install_id, "registered": self.registered,
|
|
60
|
+
"activated": self.activated, "region": self.region, "hardwareUuid": self.hardware_uuid}
|
|
61
|
+
if self.device_cache is not None:
|
|
62
|
+
result["ahaDeviceCache"] = self.device_cache
|
|
63
|
+
if self.device_region is not None:
|
|
64
|
+
result["ahaDeviceRegion"] = self.device_region
|
|
65
|
+
return result
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class IdentityStore:
|
|
69
|
+
def __init__(self, credentials: Path):
|
|
70
|
+
self.credentials = credentials
|
|
71
|
+
self.path = credentials.with_name(credentials.stem + ".device.secret")
|
|
72
|
+
|
|
73
|
+
@contextmanager
|
|
74
|
+
def locked(self):
|
|
75
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
76
|
+
lock = self.path.with_name(self.path.name + ".lock.secret")
|
|
77
|
+
try:
|
|
78
|
+
fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
79
|
+
except FileExistsError:
|
|
80
|
+
raise ValueError("another login is using this independent device profile") from None
|
|
81
|
+
try:
|
|
82
|
+
os.close(fd)
|
|
83
|
+
yield
|
|
84
|
+
finally:
|
|
85
|
+
lock.unlink()
|
|
86
|
+
|
|
87
|
+
def load(self) -> LoginIdentity:
|
|
88
|
+
if self.path.exists():
|
|
89
|
+
try:
|
|
90
|
+
data = json.loads(self.path.read_text(encoding="utf-8"))
|
|
91
|
+
if data.get("version") != 1:
|
|
92
|
+
raise ValueError()
|
|
93
|
+
identity = LoginIdentity(data["machineId"], data["privateKeyPEM"], data["deviceId"],
|
|
94
|
+
data["installId"], data["registered"], data["activated"], data["region"], data["hardwareUuid"],
|
|
95
|
+
data.get("ahaDeviceCache") if data.get("ahaDeviceCache") is not None else
|
|
96
|
+
({} if "ahaDeviceCache" in data else None), data.get("ahaDeviceRegion"))
|
|
97
|
+
if (not isinstance(identity.machine_id, str) or not identity.machine_id
|
|
98
|
+
or type(identity.registered) is not bool or type(identity.activated) is not bool
|
|
99
|
+
or identity.activated and not identity.registered):
|
|
100
|
+
raise ValueError()
|
|
101
|
+
if identity.registered:
|
|
102
|
+
if any(not isinstance(value, str) for value in
|
|
103
|
+
(identity.device_id, identity.install_id, identity.hardware_uuid)):
|
|
104
|
+
raise ValueError()
|
|
105
|
+
# New records have their own native-compatible cache
|
|
106
|
+
# validator; legacy profiles retain the old strict check.
|
|
107
|
+
if identity.device_cache is None and (not identity.device_id.isdecimal()
|
|
108
|
+
or int(identity.device_id) <= 0 or not identity.install_id.isdecimal()
|
|
109
|
+
or int(identity.install_id) <= 0 or not identity.hardware_uuid):
|
|
110
|
+
raise ValueError()
|
|
111
|
+
identity.public_key_pem
|
|
112
|
+
return identity
|
|
113
|
+
except (KeyError, TypeError, ValueError, AttributeError):
|
|
114
|
+
raise ValueError("invalid independent device profile; refusing to replace its identity") from None
|
|
115
|
+
# Migrate only the explicitly selected independent credential file.
|
|
116
|
+
# Old random device IDs are retained as unverified until registration.
|
|
117
|
+
device = {}
|
|
118
|
+
if self.credentials.exists():
|
|
119
|
+
try:
|
|
120
|
+
data = json.loads(self.credentials.read_text(encoding="utf-8"))
|
|
121
|
+
device = data.get("device", {})
|
|
122
|
+
if not isinstance(device, dict):
|
|
123
|
+
raise ValueError()
|
|
124
|
+
except (ValueError, AttributeError):
|
|
125
|
+
raise ValueError("invalid existing independent credentials") from None
|
|
126
|
+
identity = LoginIdentity(device.get("machineId") or hashlib.sha256(secrets.token_bytes(32)).hexdigest(),
|
|
127
|
+
device.get("privateKeyPEM") or new_key(), device.get("deviceId") or "")
|
|
128
|
+
identity.public_key_pem
|
|
129
|
+
return identity
|
|
130
|
+
|
|
131
|
+
def save(self, identity: LoginIdentity) -> None:
|
|
132
|
+
atomic_json(self.path, identity.as_dict())
|
|
133
|
+
from .app_storage import save_tiny_storage
|
|
134
|
+
save_tiny_storage(identity)
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Read native credentials, optionally verifying an existing native device."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import re
|
|
9
|
+
from typing import Literal
|
|
10
|
+
|
|
11
|
+
from .credential_decrypt import decrypt_value
|
|
12
|
+
|
|
13
|
+
DeviceIdSource = Literal["existing", "get-device-id"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class NativeIdentityError(ValueError):
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def native_user_data() -> Path:
|
|
21
|
+
location = os.environ.get("TRAE2API_USER_DATA")
|
|
22
|
+
if location:
|
|
23
|
+
return Path(location)
|
|
24
|
+
if os.environ.get("APPDATA"):
|
|
25
|
+
return Path(os.environ["APPDATA"]) / "Trae CN"
|
|
26
|
+
raise NativeIdentityError("native user-data directory unavailable; set TRAE2API_USER_DATA")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class NativeIdentity:
|
|
31
|
+
user_data: Path
|
|
32
|
+
user_id: str = field(repr=False)
|
|
33
|
+
token: str = field(repr=False)
|
|
34
|
+
device_id: str = field(repr=False)
|
|
35
|
+
session: str
|
|
36
|
+
user_region: str
|
|
37
|
+
device_id_source: DeviceIdSource = "get-device-id"
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def load(cls, directory: Path | None = None, *,
|
|
41
|
+
device_id_source: DeviceIdSource = "get-device-id") -> "NativeIdentity":
|
|
42
|
+
if device_id_source not in ("existing", "get-device-id"):
|
|
43
|
+
raise NativeIdentityError("unsupported native device ID source")
|
|
44
|
+
root = directory if directory is not None else native_user_data()
|
|
45
|
+
try:
|
|
46
|
+
raw = json.loads((root / "User/globalStorage/storage.json").read_text(encoding="utf-8"))
|
|
47
|
+
except (OSError, ValueError):
|
|
48
|
+
raise NativeIdentityError("cannot read native credential storage; sign in to Trae CN first") from None
|
|
49
|
+
if not isinstance(raw, dict):
|
|
50
|
+
raise NativeIdentityError("invalid native credential storage")
|
|
51
|
+
encrypted = raw.get("iCubeAuthInfo://icube.cloudide")
|
|
52
|
+
try:
|
|
53
|
+
plain = decrypt_value(encrypted) if isinstance(encrypted, str) else None
|
|
54
|
+
auth = json.loads(plain) if plain else {}
|
|
55
|
+
except Exception:
|
|
56
|
+
raise NativeIdentityError("cannot decode native login") from None
|
|
57
|
+
if not isinstance(auth, dict):
|
|
58
|
+
raise NativeIdentityError("invalid native login")
|
|
59
|
+
token, user_id, account = auth.get("token"), auth.get("userId"), auth.get("account")
|
|
60
|
+
if not isinstance(token, str) or not token or not isinstance(user_id, str) or not user_id:
|
|
61
|
+
raise NativeIdentityError("native login is missing its token or account ID")
|
|
62
|
+
if not isinstance(account, dict) or account.get("scope") != "marscode":
|
|
63
|
+
raise NativeIdentityError("native check-in requires a CN marscode account")
|
|
64
|
+
# Account-bound devices are resolved by app_storage after authentication.
|
|
65
|
+
# Neither native device cache nor session logs are needed for this mode.
|
|
66
|
+
if device_id_source == "get-device-id":
|
|
67
|
+
return cls(root, user_id, token, "", "", "CN", device_id_source)
|
|
68
|
+
|
|
69
|
+
try:
|
|
70
|
+
sessions = sorted((p for p in (root / "logs").iterdir()
|
|
71
|
+
if p.is_dir() and re.fullmatch(r"\d{8}T\d{6}", p.name)),
|
|
72
|
+
key=lambda p: p.name, reverse=True)
|
|
73
|
+
if not sessions:
|
|
74
|
+
raise NativeIdentityError("no native session log available to verify the remote device ID")
|
|
75
|
+
log = sessions[0] / "main.log"
|
|
76
|
+
if log.stat().st_size > 32 * 1024 * 1024:
|
|
77
|
+
raise NativeIdentityError("native session log exceeds the verification size limit")
|
|
78
|
+
text = log.read_text(encoding="utf-8", errors="replace")
|
|
79
|
+
except OSError:
|
|
80
|
+
raise NativeIdentityError("cannot read the latest native session log; start Trae CN first") from None
|
|
81
|
+
|
|
82
|
+
resolved = list(re.finditer(r"\[ICDRS\] \(init\) resolve rdid:\s*([^\s,]+)", text))
|
|
83
|
+
initialized = list(re.finditer(
|
|
84
|
+
r"\[ICDRS\] \(init\) initialization done, did:\s*([^\s,]+), ldid:\s*([^\s,]+), rdid:\s*([^\s,]+)", text)
|
|
85
|
+
)
|
|
86
|
+
if not resolved or not initialized:
|
|
87
|
+
raise NativeIdentityError("latest native session has no completed remote device resolution")
|
|
88
|
+
initialized_id, local_id, remote_id = initialized[-1].groups()
|
|
89
|
+
device_id = resolved[-1][1]
|
|
90
|
+
# A late resolution after initialization updates both live IDs.
|
|
91
|
+
initialized_after_resolution = initialized[-1].start() > resolved[-1].start()
|
|
92
|
+
if (device_id in ("", "0") or device_id == local_id
|
|
93
|
+
or (initialized_after_resolution and (initialized_id != device_id or remote_id != device_id))):
|
|
94
|
+
raise NativeIdentityError("native session device evidence is inconsistent or uses a local fallback")
|
|
95
|
+
if "iCubeAuthInfo://icube-dc:" + device_id not in raw:
|
|
96
|
+
raise NativeIdentityError("native remote device ID does not match a native OAuth device record")
|
|
97
|
+
|
|
98
|
+
regions = []
|
|
99
|
+
for line in text.splitlines():
|
|
100
|
+
if "getStoreRegion" in line:
|
|
101
|
+
regions.extend(re.findall(r'''["']?region["']?\s*[:=]\s*["']?(CN|SG|US|USTTP|UNKNOWN)\b''', line))
|
|
102
|
+
# This mode is for the reviewed CN installation. Never substitute the
|
|
103
|
+
# independent proxy credential's AIRegion for a native store region.
|
|
104
|
+
if not regions:
|
|
105
|
+
raise NativeIdentityError("native store region unavailable in the latest session log")
|
|
106
|
+
return cls(root, user_id, token, device_id, sessions[0].name, regions[-1], device_id_source)
|
|
107
|
+
|
|
108
|
+
def ensure_current(self) -> None:
|
|
109
|
+
current = type(self).load(self.user_data, device_id_source=self.device_id_source)
|
|
110
|
+
if current != self:
|
|
111
|
+
raise NativeIdentityError("native login, device, region or session changed; rerun the command")
|