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.
Files changed (34) hide show
  1. buddy_agent_auth/__init__.py +5 -0
  2. buddy_agent_auth/account_store.py +4 -0
  3. buddy_agent_auth/backend_profile.py +4 -0
  4. buddy_agent_auth/client.py +4 -0
  5. buddy_agent_auth/locking.py +81 -0
  6. buddy_agent_auth/providers/__init__.py +4 -0
  7. buddy_agent_auth/providers/base.py +9 -0
  8. buddy_agent_auth/providers/codebuddy/__init__.py +17 -0
  9. buddy_agent_auth/providers/codebuddy/account_store.py +506 -0
  10. buddy_agent_auth/providers/codebuddy/backend_profile.py +198 -0
  11. buddy_agent_auth/providers/codebuddy/client.py +666 -0
  12. buddy_agent_auth/providers/trae/__init__.py +27 -0
  13. buddy_agent_auth/providers/trae/aha_cache_codec.py +84 -0
  14. buddy_agent_auth/providers/trae/aha_device_cache.py +45 -0
  15. buddy_agent_auth/providers/trae/aha_device_service.py +325 -0
  16. buddy_agent_auth/providers/trae/aha_native_backend.py +61 -0
  17. buddy_agent_auth/providers/trae/aha_native_lifecycle.py +226 -0
  18. buddy_agent_auth/providers/trae/aha_native_semantics.py +67 -0
  19. buddy_agent_auth/providers/trae/aha_registration.py +157 -0
  20. buddy_agent_auth/providers/trae/aha_tiny_storage.py +135 -0
  21. buddy_agent_auth/providers/trae/app_storage.py +195 -0
  22. buddy_agent_auth/providers/trae/auth.py +362 -0
  23. buddy_agent_auth/providers/trae/client_metadata.py +102 -0
  24. buddy_agent_auth/providers/trae/credential_decrypt.py +111 -0
  25. buddy_agent_auth/providers/trae/credentials.py +39 -0
  26. buddy_agent_auth/providers/trae/device_hardware.py +377 -0
  27. buddy_agent_auth/providers/trae/diagnostics.py +38 -0
  28. buddy_agent_auth/providers/trae/login.py +415 -0
  29. buddy_agent_auth/providers/trae/login_identity.py +134 -0
  30. buddy_agent_auth/providers/trae/native_identity.py +111 -0
  31. buddy_agent_auth-0.1.0.dev1.dist-info/METADATA +40 -0
  32. buddy_agent_auth-0.1.0.dev1.dist-info/RECORD +34 -0
  33. buddy_agent_auth-0.1.0.dev1.dist-info/WHEEL +5 -0
  34. buddy_agent_auth-0.1.0.dev1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,666 @@
1
+ #!/usr/bin/env python3
2
+ """Minimal CodeBuddy external-link-v2 client demo.
3
+
4
+ The protocol is extracted from Tencent Cloud CodeBuddy's VSIX. This demo
5
+ uses only the Python standard library and stores the session locally with
6
+ 0600 permissions.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import copy
13
+ import json
14
+ import os
15
+ import pathlib
16
+ import sys
17
+ import tempfile
18
+ import threading
19
+ import time
20
+ import urllib.error
21
+ import urllib.parse
22
+ import urllib.request
23
+ import webbrowser
24
+ from typing import Any, Iterator
25
+
26
+ from buddy_agent_auth.locking import directory_lock
27
+ from .backend_profile import (
28
+ BackendProfile,
29
+ ResolvedBackend,
30
+ normalize_endpoint,
31
+ resolve_backend,
32
+ resolve_backend_from_args,
33
+ )
34
+
35
+
36
+ class CodeBuddyError(RuntimeError):
37
+ pass
38
+
39
+
40
+ def _load_json_bytes(raw: bytes) -> Any:
41
+ """按 utf-8 → gbk → cp936 → latin-1 依次解码并解析 JSON。
42
+
43
+ 兼容上游偶发返回非 UTF-8 字节(如 GBK)的情况,避免 `raw.decode("utf-8")`
44
+ 抛 `UnicodeDecodeError`。若所有编码都无法解析为合法 JSON,最终以
45
+ latin-1 解码后抛 `json.JSONDecodeError`,交由调用方统一处理。
46
+ """
47
+ for encoding in ("utf-8", "gbk", "cp936", "latin-1"):
48
+ try:
49
+ text = raw.decode(encoding)
50
+ except UnicodeDecodeError:
51
+ continue
52
+ try:
53
+ return json.loads(text)
54
+ except json.JSONDecodeError:
55
+ continue
56
+ # latin-1 能解码任意字节,故 decode 不会失败;走到这里仅当 JSON 结构非法。
57
+ return json.loads(raw.decode("latin-1"))
58
+
59
+
60
+ class CodeBuddyClient:
61
+ def __init__(
62
+ self,
63
+ endpoint: str | None = None,
64
+ platform: str = "VSCode",
65
+ session_file: pathlib.Path | str | None = None,
66
+ *,
67
+ backend: ResolvedBackend | BackendProfile | None = None,
68
+ profile: BackendProfile | None = None,
69
+ ) -> None:
70
+ if backend is not None and profile is not None:
71
+ raise ValueError("CodeBuddyClient 不能同时指定 backend 和 profile")
72
+ if profile is not None:
73
+ backend = profile
74
+ if isinstance(backend, ResolvedBackend):
75
+ if endpoint is None and session_file is None:
76
+ resolved_backend = backend
77
+ else:
78
+ resolved_backend = resolve_backend(
79
+ profile=backend.profile,
80
+ endpoint=endpoint or backend.endpoint,
81
+ session_file=session_file or backend.session_file,
82
+ environment={},
83
+ )
84
+ elif isinstance(backend, BackendProfile):
85
+ resolved_backend = resolve_backend(
86
+ profile=backend,
87
+ endpoint=endpoint,
88
+ session_file=session_file,
89
+ environment={},
90
+ )
91
+ else:
92
+ # Direct library callers historically defaulted to the domestic
93
+ # endpoint; environment precedence belongs to the CLI resolver.
94
+ resolved_backend = resolve_backend(
95
+ endpoint=endpoint,
96
+ session_file=session_file,
97
+ environment={},
98
+ )
99
+
100
+ self.backend = resolved_backend
101
+ self.profile = resolved_backend.profile
102
+ self.endpoint = resolved_backend.endpoint
103
+ self.platform = platform
104
+ self.prefix = self.profile.auth_prefix
105
+ self.session_file = resolved_backend.session_file
106
+ self._shared_lock = directory_lock(self.session_file.parent)
107
+ self._refresh_lock = directory_lock(self.session_file.parent / ".workbuddy-refresh" / self.session_file.name)
108
+ self._session_lock = threading.RLock()
109
+ self._auth_lock = threading.RLock()
110
+ self._session_generation = 0
111
+ self._persistence_enabled = True
112
+ self.session: dict[str, Any] = self._load_session()
113
+
114
+ def _load_session(self) -> dict[str, Any]:
115
+ try:
116
+ session = json.loads(self.session_file.read_text(encoding="utf-8"))
117
+ except FileNotFoundError:
118
+ return {}
119
+ except (OSError, json.JSONDecodeError) as exc:
120
+ raise CodeBuddyError(f"无法读取 session 文件: {self.session_file}: {exc}") from exc
121
+
122
+ if not isinstance(session, dict):
123
+ raise CodeBuddyError(f"session 文件格式无效(应为 JSON object): {self.session_file}")
124
+ self._validate_session_metadata(session)
125
+ return session
126
+
127
+ def _validate_session_metadata(self, session: dict[str, Any]) -> None:
128
+ """Reject credentials saved for a different backend or endpoint."""
129
+
130
+ stored_backend = session.get("backend")
131
+ stored_endpoint = session.get("endpoint")
132
+
133
+ # Sessions written before profile metadata was introduced are
134
+ # intentionally usable only by the domestic profile's default endpoint.
135
+ # This preserves the old default while preventing an old token from
136
+ # being sent to a custom or global endpoint.
137
+ if not stored_backend:
138
+ if self.profile.key != "domestic":
139
+ raise CodeBuddyError(
140
+ f"session 文件 {self.session_file} 没有 backend 元数据,"
141
+ "只能由 domestic profile 读取;请使用匹配的 --session-file。"
142
+ )
143
+ if self.endpoint != self.profile.default_endpoint:
144
+ raise CodeBuddyError(
145
+ f"session 文件 {self.session_file} 没有 backend/endpoint 元数据,"
146
+ "只能在 domestic profile 的默认 endpoint 下读取;"
147
+ "请使用匹配的 --session-file。"
148
+ )
149
+ if stored_endpoint:
150
+ try:
151
+ stored_endpoint = normalize_endpoint(str(stored_endpoint))
152
+ except ValueError:
153
+ stored_endpoint = ""
154
+ if stored_endpoint != self.endpoint:
155
+ raise CodeBuddyError(
156
+ f"session 文件 {self.session_file} 的 endpoint 与当前 backend 不匹配;"
157
+ "原文件未修改,请使用匹配的 --session-file。"
158
+ )
159
+ return
160
+
161
+ if stored_backend != self.profile.key:
162
+ raise CodeBuddyError(
163
+ f"session 文件 {self.session_file} 属于 backend={stored_backend!r},"
164
+ f"当前 backend={self.profile.key!r},backend 不匹配;原文件未修改。"
165
+ )
166
+
167
+ if not stored_endpoint:
168
+ raise CodeBuddyError(
169
+ f"session 文件 {self.session_file} 缺少 endpoint 元数据;原文件未修改。"
170
+ )
171
+
172
+ try:
173
+ normalized_stored_endpoint = normalize_endpoint(str(stored_endpoint))
174
+ except ValueError:
175
+ normalized_stored_endpoint = ""
176
+ if normalized_stored_endpoint != self.endpoint:
177
+ raise CodeBuddyError(
178
+ f"session 文件 {self.session_file} 的 endpoint 与当前 backend 不匹配;"
179
+ "原文件未修改,请使用匹配的 --session-file。"
180
+ )
181
+
182
+ def _snapshot_session(self) -> tuple[dict[str, Any], int]:
183
+ with self._session_lock:
184
+ return copy.deepcopy(self.session), self._session_generation
185
+
186
+ def _save_session(
187
+ self,
188
+ session: dict[str, Any],
189
+ *,
190
+ expected_generation: int | None = None,
191
+ ) -> bool:
192
+ with self._shared_lock:
193
+ if expected_generation is not None:
194
+ with self._session_lock:
195
+ if self.session_file.exists():
196
+ current = self._load_session()
197
+ if current != self.session:
198
+ self.session = current
199
+ self._session_generation += 1
200
+ return False
201
+ elif self.session_file.name.startswith("account-acct_") and self.session:
202
+ return False
203
+ return self._save_session_under_lock(session, expected_generation=expected_generation)
204
+
205
+ def _save_session_under_lock(self, session: dict[str, Any], *, expected_generation: int | None = None) -> bool:
206
+ persisted_session = dict(session)
207
+ persisted_session["backend"] = self.profile.key
208
+ persisted_session["endpoint"] = self.endpoint
209
+ with self._session_lock:
210
+ if not self._persistence_enabled:
211
+ return False
212
+ if (
213
+ expected_generation is not None
214
+ and self._session_generation != expected_generation
215
+ ):
216
+ return False
217
+ self.session_file.parent.mkdir(parents=True, exist_ok=True)
218
+ temp_name: str | None = None
219
+ try:
220
+ fd, temp_name = tempfile.mkstemp(
221
+ prefix=f".{self.session_file.name}.",
222
+ suffix=".tmp",
223
+ dir=self.session_file.parent,
224
+ )
225
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
226
+ json.dump(persisted_session, stream, ensure_ascii=False, indent=2)
227
+ stream.write("\n")
228
+ stream.flush()
229
+ os.fsync(stream.fileno())
230
+ os.replace(temp_name, self.session_file)
231
+ temp_name = None
232
+ try:
233
+ os.chmod(self.session_file, 0o600)
234
+ except OSError:
235
+ pass
236
+ except OSError as exc:
237
+ raise CodeBuddyError(
238
+ f"无法原子写入 session 文件: {self.session_file}"
239
+ ) from exc
240
+ finally:
241
+ if temp_name is not None:
242
+ try:
243
+ os.unlink(temp_name)
244
+ except OSError:
245
+ pass
246
+ self.session = persisted_session
247
+ self._session_generation += 1
248
+ return True
249
+
250
+ def _invalidate_persistence(self) -> None:
251
+ """Prevent an old client reference from recreating a removed session."""
252
+ with self._session_lock:
253
+ self._session_generation += 1
254
+ self._persistence_enabled = False
255
+
256
+ def _enable_persistence(self) -> None:
257
+ """Restore writes if a store deletion transaction was rolled back."""
258
+ with self._session_lock:
259
+ self._session_generation += 1
260
+ self._persistence_enabled = True
261
+
262
+ def _restore_session_snapshot(self, session: dict[str, Any]) -> None:
263
+ """Restore in-memory state after an account-store transaction fails."""
264
+ with self._session_lock:
265
+ self.session = copy.deepcopy(session)
266
+ self._session_generation += 1
267
+
268
+ def build_url(self, path: str) -> str:
269
+ """Build a URL from the resolved endpoint and a relative path."""
270
+
271
+ return f"{self.endpoint}/{path.lstrip('/')}"
272
+
273
+ def enterprise_models_path(self, enterprise_id: str) -> str:
274
+ """Return the profile-defined enterprise model-config path."""
275
+
276
+ return self.profile.enterprise_models_path.format(
277
+ enterpriseId=urllib.parse.quote(str(enterprise_id), safe="")
278
+ )
279
+
280
+ def _auth_path(self, suffix: str) -> str:
281
+ return f"/v2{self.profile.auth_prefix}{suffix}"
282
+
283
+ @staticmethod
284
+ def _unwrap(payload: Any) -> Any:
285
+ # CodeBuddy responses observed in the extension use {data: {data: ...}}.
286
+ if isinstance(payload, dict) and isinstance(payload.get("data"), dict):
287
+ nested = payload["data"]
288
+ if "data" in nested:
289
+ return nested["data"]
290
+ if isinstance(payload, dict) and "data" in payload:
291
+ return payload["data"]
292
+ return payload
293
+
294
+ def _request(
295
+ self,
296
+ method: str,
297
+ path: str,
298
+ *,
299
+ headers: dict[str, str] | None = None,
300
+ body: Any = None,
301
+ timeout: float = 30,
302
+ ) -> Any:
303
+ # 🔥 所有请求都必须包含这两个基础标识(匹配插件行为)
304
+ request_headers = {
305
+ "User-Agent": "Mozilla/5.0 (compatible; Genie-IDE/1.0)",
306
+ "X-Product-Code": "codebuddy",
307
+ }
308
+ # 关键修复:合并调用者传入的 headers
309
+ if headers:
310
+ request_headers.update(headers)
311
+
312
+ data = None
313
+ if body is not None:
314
+ data = json.dumps(body).encode("utf-8")
315
+ request_headers.setdefault("Content-Type", "application/json")
316
+ request = urllib.request.Request(
317
+ self.build_url(path),
318
+ data=data,
319
+ headers=request_headers,
320
+ method=method,
321
+ )
322
+ try:
323
+ with urllib.request.urlopen(request, timeout=timeout) as response:
324
+ raw = response.read()
325
+ content_type = response.headers.get("Content-Type", "")
326
+ except urllib.error.HTTPError as exc:
327
+ detail = exc.read().decode("utf-8", errors="replace")
328
+ raise CodeBuddyError(f"HTTP {exc.code} {path}: {detail[:1000]}") from exc
329
+ except urllib.error.URLError as exc:
330
+ raise CodeBuddyError(f"请求失败 {path}: {exc.reason}") from exc
331
+ if "json" not in content_type and not raw:
332
+ return None
333
+ try:
334
+ return _load_json_bytes(raw)
335
+ except json.JSONDecodeError as exc:
336
+ raise CodeBuddyError(f"{path} 返回的不是 JSON: {raw[:300]!r}") from exc
337
+
338
+ def auth_headers(self, *, access: bool = True, refresh: bool = False) -> dict[str, str]:
339
+ """构造认证 headers,模拟插件行为"""
340
+ self._get_machine_id()
341
+ session, _ = self._snapshot_session()
342
+ return self._auth_headers_for_session(session, access=access, refresh=refresh)
343
+
344
+ def _auth_headers_for_session(
345
+ self,
346
+ session: dict[str, Any],
347
+ *,
348
+ access: bool = True,
349
+ refresh: bool = False,
350
+ ) -> dict[str, str]:
351
+ account = session.get("account") or {}
352
+ auth = session.get("auth") or {}
353
+ headers: dict[str, str] = {
354
+ "X-Product-Code": "codebuddy",
355
+ "X-IDE-Type": "vscode",
356
+ "X-IDE-Name": "Visual Studio Code",
357
+ "X-IDE-Version": "1.70.2",
358
+ "X-Product-Version": "4.10.33259736",
359
+ "X-Machine-Id": str(session.get("machineId") or ""),
360
+ }
361
+ if account.get("uid"):
362
+ headers["X-User-Id"] = str(account["uid"])
363
+ if access and auth.get("accessToken"):
364
+ headers["Authorization"] = f"Bearer {auth['accessToken']}"
365
+ if refresh and auth.get("refreshToken"):
366
+ headers["X-Refresh-Token"] = str(auth["refreshToken"])
367
+ if account.get("enterpriseId"):
368
+ headers["X-Enterprise-Id"] = str(account["enterpriseId"])
369
+ headers["X-Tenant-Id"] = str(account["enterpriseId"])
370
+ if account.get("departmentInfo"):
371
+ headers["X-Department-Info"] = str(account["departmentInfo"])
372
+ domain = self._domain_for_token(auth)
373
+ if domain:
374
+ headers["X-Domain"] = domain
375
+ return headers
376
+
377
+ def _enterprise_headers(self, token: dict[str, Any] | None = None) -> dict[str, str]:
378
+ """构造企业认证 headers(模拟 VSIX enterpriseHeaders)"""
379
+ domain = self._domain_for_token(token)
380
+ return {"X-Domain": domain} if domain else {}
381
+
382
+ def _domain_for_token(self, token: dict[str, Any] | None = None) -> str:
383
+ """Use token.domain first, then the resolved endpoint authority."""
384
+
385
+ if token and token.get("domain"):
386
+ return str(token["domain"])
387
+ try:
388
+ return urllib.parse.urlsplit(self.endpoint).netloc
389
+ except ValueError:
390
+ return ""
391
+
392
+ def _get_machine_id(self) -> str:
393
+ """获取或生成机器ID(模拟VSCode的machineId)"""
394
+ import platform
395
+ import uuid
396
+ with self._shared_lock, self._session_lock:
397
+ self._sync_session_from_disk()
398
+ saved_machine_id = self.session.get("machineId")
399
+ if saved_machine_id:
400
+ return str(saved_machine_id)
401
+ try:
402
+ hostname = platform.node()
403
+ username = os.environ.get("USER") or os.environ.get("USERNAME") or "unknown"
404
+ seed = f"{hostname}-{username}"
405
+ machine_id = str(uuid.uuid5(uuid.NAMESPACE_DNS, seed))
406
+ except Exception:
407
+ machine_id = str(uuid.uuid4())
408
+ self._save_session({**self.session, "machineId": machine_id})
409
+ return machine_id
410
+
411
+ def begin_login(self) -> dict[str, str]:
412
+ """Request an authorization URL and state without opening a browser."""
413
+ no_auth = {
414
+ "X-No-Authorization": "true",
415
+ "X-No-User-Id": "true",
416
+ "X-No-Enterprise-Id": "true",
417
+ "X-No-Department-Info": "true",
418
+ }
419
+ state_payload = self._unwrap(
420
+ self._request(
421
+ "POST",
422
+ f"{self._auth_path('/auth/state')}?platform={urllib.parse.quote(self.platform)}",
423
+ headers={**self._enterprise_headers(), **no_auth},
424
+ body={},
425
+ )
426
+ )
427
+ if not isinstance(state_payload, dict) or not state_payload.get("authUrl"):
428
+ raise CodeBuddyError(f"登录状态响应缺少 authUrl: {state_payload!r}")
429
+ auth_url = str(state_payload["authUrl"])
430
+ state = state_payload.get("state")
431
+ if not state:
432
+ raise CodeBuddyError("登录状态响应缺少 state")
433
+ return {"auth_url": auth_url, "state": str(state)}
434
+
435
+ @staticmethod
436
+ def _check_login_cancelled(cancel_event: Any | None) -> None:
437
+ if cancel_event is not None and cancel_event.is_set():
438
+ raise CodeBuddyError("登录已取消")
439
+
440
+ @classmethod
441
+ def _wait_for_login_poll(cls, deadline: float, cancel_event: Any | None) -> None:
442
+ cls._check_login_cancelled(cancel_event)
443
+ remaining = deadline - time.monotonic()
444
+ if remaining <= 0:
445
+ return
446
+ pause = min(1.0, remaining)
447
+ if cancel_event is not None and hasattr(cancel_event, "wait"):
448
+ if cancel_event.wait(pause):
449
+ raise CodeBuddyError("登录已取消")
450
+ else:
451
+ time.sleep(pause)
452
+ cls._check_login_cancelled(cancel_event)
453
+
454
+ @staticmethod
455
+ def _account_has_uid(account: Any) -> bool:
456
+ return (
457
+ isinstance(account, dict)
458
+ and account.get("uid") is not None
459
+ and bool(str(account.get("uid")).strip())
460
+ )
461
+
462
+ def complete_login(
463
+ self,
464
+ challenge: dict[str, Any],
465
+ timeout: float = 300,
466
+ cancel_event: Any | None = None,
467
+ ) -> None:
468
+ """Poll the challenge until a token and uid-bearing account are ready.
469
+
470
+ One deadline covers both polling stages. No session state is saved
471
+ unless a token and an account with a uid have both been returned.
472
+ """
473
+ if not isinstance(challenge, dict) or not challenge.get("state"):
474
+ raise CodeBuddyError("登录 challenge 缺少 state")
475
+ try:
476
+ timeout_value = float(timeout)
477
+ except (TypeError, ValueError) as exc:
478
+ raise CodeBuddyError("登录超时时间无效") from exc
479
+ if timeout_value <= 0:
480
+ raise CodeBuddyError("登录超时时间必须大于 0")
481
+ state = str(challenge["state"])
482
+ state_query = urllib.parse.quote(state, safe="")
483
+ deadline = time.monotonic() + timeout_value
484
+ _, initial_generation = self._snapshot_session()
485
+ no_auth = {
486
+ "X-No-Authorization": "true",
487
+ "X-No-User-Id": "true",
488
+ "X-No-Enterprise-Id": "true",
489
+ "X-No-Department-Info": "true",
490
+ }
491
+ while time.monotonic() < deadline:
492
+ self._check_login_cancelled(cancel_event)
493
+ remaining = deadline - time.monotonic()
494
+ if remaining <= 0:
495
+ break
496
+ try:
497
+ token = self._unwrap(
498
+ self._request(
499
+ "GET",
500
+ f"{self._auth_path('/auth/token')}?state={state_query}",
501
+ headers={**self._enterprise_headers(), **no_auth},
502
+ timeout=min(30.0, remaining),
503
+ )
504
+ )
505
+ except CodeBuddyError:
506
+ token = None
507
+ if isinstance(token, dict) and token.get("accessToken"):
508
+ account = None
509
+ while time.monotonic() < deadline:
510
+ self._check_login_cancelled(cancel_event)
511
+ remaining = deadline - time.monotonic()
512
+ if remaining <= 0:
513
+ break
514
+ try:
515
+ account = self._unwrap(
516
+ self._request(
517
+ "GET",
518
+ f"{self._auth_path('/login/account')}?state={state_query}",
519
+ headers={
520
+ # 关键修复:必须包含完整的 enterprise headers(包括 X-Domain)
521
+ **self._enterprise_headers(token),
522
+ "Authorization": f"Bearer {token['accessToken']}",
523
+ "X-No-User-Id": "true",
524
+ "X-No-Enterprise-Id": "true",
525
+ "X-No-Department-Info": "true",
526
+ },
527
+ timeout=min(30.0, remaining),
528
+ )
529
+ )
530
+ self._check_login_cancelled(cancel_event)
531
+ if time.monotonic() >= deadline:
532
+ account = None
533
+ break
534
+ if self._account_has_uid(account):
535
+ break
536
+ account = None
537
+ except CodeBuddyError:
538
+ account = None
539
+ if account is not None:
540
+ break
541
+ self._wait_for_login_poll(deadline, cancel_event)
542
+
543
+ if self._account_has_uid(account):
544
+ self._check_login_cancelled(cancel_event)
545
+ if time.monotonic() >= deadline:
546
+ raise CodeBuddyError("登录超时:未能获取包含 uid 的账户信息")
547
+ session, _ = self._snapshot_session()
548
+ if not self._save_session(
549
+ {**session, "auth": token, "account": account},
550
+ expected_generation=initial_generation,
551
+ ):
552
+ raise CodeBuddyError("登录期间账号凭据已变化,请重新登录")
553
+ return
554
+ raise CodeBuddyError("登录超时:未能获取包含 uid 的账户信息")
555
+
556
+ self._wait_for_login_poll(deadline, cancel_event)
557
+
558
+ self._check_login_cancelled(cancel_event)
559
+ raise CodeBuddyError("登录超时:未能获取访问令牌")
560
+
561
+ def login(self, *, open_browser: bool = True, timeout: int = 300) -> None:
562
+ challenge = self.begin_login()
563
+ auth_url = challenge["auth_url"]
564
+ print(f"请在浏览器中完成登录:\n{auth_url}")
565
+ if open_browser:
566
+ webbrowser.open(auth_url)
567
+ self.complete_login(challenge, timeout=timeout)
568
+ account = self.session.get("account") or {}
569
+ print(f"登录成功,用户: {account.get('nickname') or account.get('uid', '<unknown>')}")
570
+
571
+ @staticmethod
572
+ def _token_headers(token: dict[str, Any]) -> dict[str, str]:
573
+ headers: dict[str, str] = {}
574
+ if token.get("accessToken"):
575
+ headers["Authorization"] = f"Bearer {token['accessToken']}"
576
+ if token.get("domain"):
577
+ headers["X-Domain"] = str(token["domain"])
578
+ return headers
579
+
580
+ def _sync_session_from_disk(self) -> bool:
581
+ """Reload under the shared directory lock before using credentials."""
582
+ with self._shared_lock:
583
+ if not self.session_file.exists():
584
+ if self.session_file.name.startswith("account-acct_"):
585
+ raise CodeBuddyError("账号 session 已被删除,请重新关联账号")
586
+ return False
587
+ disk = self._load_session()
588
+ with self._session_lock:
589
+ if disk == self.session:
590
+ return False
591
+ self.session = disk
592
+ self._session_generation += 1
593
+ return True
594
+
595
+ def refresh(self) -> bool:
596
+ with self._auth_lock, self._refresh_lock:
597
+ old_auth = self._snapshot_session()[0].get("auth") or {}
598
+ if self._sync_session_from_disk():
599
+ current = self._snapshot_session()[0].get("auth") or {}
600
+ expiry = int(current.get("expiresAt") or 0)
601
+ if (current.get("accessToken") and current.get("accessToken") != old_auth.get("accessToken")
602
+ and (not expiry or expiry > int(time.time() * 1000) + 60_000)):
603
+ return True
604
+ return self._refresh_locked()
605
+
606
+ def _refresh_locked(self) -> bool:
607
+ session, generation = self._snapshot_session()
608
+ auth = session.get("auth") or {}
609
+ refresh_token = auth.get("refreshToken")
610
+ if not refresh_token:
611
+ return False
612
+ self._get_machine_id()
613
+ session, generation = self._snapshot_session()
614
+ auth = session.get("auth") or {}
615
+ refresh_token = auth.get("refreshToken")
616
+ if not refresh_token:
617
+ return False
618
+ payload = self._unwrap(
619
+ self._request(
620
+ "POST",
621
+ self._auth_path("/auth/token/refresh"),
622
+ headers={
623
+ **self._auth_headers_for_session(session, access=False, refresh=True),
624
+ "X-Auth-Refresh-Source": "plugin",
625
+ },
626
+ body={},
627
+ )
628
+ )
629
+ if not isinstance(payload, dict) or not payload.get("accessToken"):
630
+ return False
631
+ saved = self._save_session(
632
+ {**session, "auth": payload}, expected_generation=generation
633
+ )
634
+ if saved:
635
+ return True
636
+ # A newer login or import completed while refresh was in flight.
637
+ current_auth = self._snapshot_session()[0].get("auth") or {}
638
+ current_expiry = int(current_auth.get("expiresAt") or 0)
639
+ return bool(
640
+ current_auth.get("accessToken")
641
+ and (not current_expiry or current_expiry > int(time.time() * 1000))
642
+ )
643
+
644
+ def ensure_authenticated(
645
+ self,
646
+ *,
647
+ open_browser: bool = True,
648
+ allow_login: bool = True,
649
+ ) -> None:
650
+ with self._auth_lock:
651
+ self._sync_session_from_disk()
652
+ # A preceding request may have refreshed the token while this
653
+ # caller waited for the per-client authentication lock.
654
+ auth = self._snapshot_session()[0].get("auth") or {}
655
+ now_ms = int(time.time() * 1000)
656
+ expires_at = int(auth.get("expiresAt") or 0)
657
+ if auth.get("accessToken") and (
658
+ not expires_at or expires_at > now_ms + 60_000
659
+ ):
660
+ return
661
+ if self.refresh():
662
+ print("access token 已刷新")
663
+ return
664
+ if not allow_login:
665
+ raise CodeBuddyError("当前账号需要重新登录;此请求禁止自动打开登录流程")
666
+ self.login(open_browser=open_browser)
@@ -0,0 +1,27 @@
1
+ """Trae CN credential sources and optional native-device verification."""
2
+ from pathlib import Path
3
+ from .native_identity import DeviceIdSource, NativeIdentity, NativeIdentityError
4
+
5
+
6
+ class TraeNativeProvider:
7
+ def __init__(self, *, directory: Path | None = None,
8
+ device_id_source: DeviceIdSource = 'get-device-id'):
9
+ self.directory = directory
10
+ self.device_id_source = device_id_source
11
+
12
+ def load(self) -> NativeIdentity:
13
+ if self.directory is None:
14
+ return NativeIdentity.load(device_id_source=self.device_id_source)
15
+ return NativeIdentity.load(self.directory, device_id_source=self.device_id_source)
16
+
17
+
18
+ def __getattr__(name):
19
+ # Optional Trae dependencies are loaded only when token lifecycle is used.
20
+ if name in ('TraeAuth', 'TraeCredentials'):
21
+ from . import auth
22
+ return getattr(auth, name)
23
+ raise AttributeError(name)
24
+
25
+
26
+ __all__ = ['DeviceIdSource', 'NativeIdentity', 'NativeIdentityError', 'TraeNativeProvider',
27
+ 'TraeAuth', 'TraeCredentials']