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,84 @@
|
|
|
1
|
+
"""Aha's reviewed cache envelope, for independent local records only.
|
|
2
|
+
|
|
3
|
+
Derived from pinned native instructions; no native runtime cache paths or
|
|
4
|
+
account material are accessed. SHA-512/AES use the existing crypto dependency.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import base64
|
|
9
|
+
import binascii
|
|
10
|
+
import hashlib
|
|
11
|
+
import hmac
|
|
12
|
+
import time
|
|
13
|
+
|
|
14
|
+
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
|
15
|
+
|
|
16
|
+
HEADER = bytes.fromhex("746305100000")
|
|
17
|
+
LEGACY_HEADER = bytes.fromhex("123920200203")
|
|
18
|
+
# XOR of the two public SDK constant tables at 0xc139780/0xc1397c0
|
|
19
|
+
# and 0xc139700/0xc139740. These are application constants, not user keys.
|
|
20
|
+
_SUFFIX = bytes.fromhex("4dd4c2e6b83162090e52b3c7a6733ba41cb2462b829ab58a196b39db57177524"
|
|
21
|
+
"f49baf7f08e8d68d26a72e37c1a95a2f1f05a51892aef2949732b62a38aadd58")
|
|
22
|
+
_LEGACY_SUFFIX = bytes.fromhex("490cc21292b05d0cc06ccbe91fb92e21b5a7c538811dc85e27a96e28104e1cf6"
|
|
23
|
+
"9c7166efab232807390da78a8b91e49c44b49a43feb941a1e46f2656e613e47b")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _seed_bytes(clock: int) -> bytes:
|
|
27
|
+
state = clock & 0xffffffff
|
|
28
|
+
result = bytearray()
|
|
29
|
+
for _ in range(32):
|
|
30
|
+
state = (state * 0x343fd + 0x269ec3) & 0xffffffff
|
|
31
|
+
result.append((state >> 16) & 255)
|
|
32
|
+
return bytes(result)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _key_iv(seed: bytes, legacy: bool = False) -> tuple[bytes, bytes]:
|
|
36
|
+
digest = hashlib.sha512(hashlib.sha512(seed).digest() + (_LEGACY_SUFFIX if legacy else _SUFFIX)).digest()
|
|
37
|
+
return digest[:16], digest[16:32]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def encrypt(value: bytes, *, clock: int | None = None) -> bytes:
|
|
41
|
+
seed = _seed_bytes(int(time.time()) if clock is None else clock)
|
|
42
|
+
key, iv = _key_iv(seed)
|
|
43
|
+
plain = hashlib.sha512(value).digest() + value
|
|
44
|
+
padding = 16 - len(plain) % 16
|
|
45
|
+
worker = Cipher(algorithms.AES(key), modes.CBC(iv)).encryptor()
|
|
46
|
+
return HEADER + seed + worker.update(plain + bytes([padding]) * padding) + worker.finalize()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def decrypt(value: bytes) -> bytes:
|
|
50
|
+
if len(value) < 118 or (len(value) - 38) % 16:
|
|
51
|
+
return b""
|
|
52
|
+
header = value[:6]
|
|
53
|
+
if header not in (HEADER, LEGACY_HEADER):
|
|
54
|
+
return b""
|
|
55
|
+
key, iv = _key_iv(value[6:38], header == LEGACY_HEADER)
|
|
56
|
+
worker = Cipher(algorithms.AES(key), modes.CBC(iv)).decryptor()
|
|
57
|
+
plain = worker.update(value[38:]) + worker.finalize()
|
|
58
|
+
padding = plain[-1]
|
|
59
|
+
# Native checks the last padding byte, not every PKCS#7 padding byte.
|
|
60
|
+
if not 1 <= padding <= 16:
|
|
61
|
+
return b""
|
|
62
|
+
plain = plain[:-padding]
|
|
63
|
+
if len(plain) <= 64 or not hmac.compare_digest(plain[:64], hashlib.sha512(plain[64:]).digest()):
|
|
64
|
+
return b""
|
|
65
|
+
return plain[64:]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def encode(value: bytes, *, clock: int | None = None) -> str:
|
|
69
|
+
return base64.b64encode(encrypt(value, clock=clock)).decode("ascii")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def decode_base64(value: str) -> bytes | None:
|
|
73
|
+
try:
|
|
74
|
+
raw = value.encode("ascii")
|
|
75
|
+
if len(raw) % 4:
|
|
76
|
+
return None
|
|
77
|
+
return base64.b64decode(raw, validate=True)
|
|
78
|
+
except (ValueError, binascii.Error, UnicodeError):
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def decode(value: str) -> bytes:
|
|
83
|
+
raw = decode_base64(value)
|
|
84
|
+
return decrypt(raw) if raw is not None else b""
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Native Aha record semantics and envelope, with legacy profile support."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
from .aha_cache_codec import decode, encode
|
|
8
|
+
from .aha_native_semantics import parse_uint64
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class DeviceRecord:
|
|
13
|
+
device_id: str = field(repr=False)
|
|
14
|
+
install_id: str = field(repr=False)
|
|
15
|
+
uuid: str = field(repr=False)
|
|
16
|
+
|
|
17
|
+
def as_dict(self) -> dict:
|
|
18
|
+
return {"device_id_str": self.device_id, "install_id_str": self.install_id,
|
|
19
|
+
"uuid": self.uuid, "version": "1.2"}
|
|
20
|
+
|
|
21
|
+
def encoded(self, *, clock: int | None = None) -> str:
|
|
22
|
+
raw = json.dumps(self.as_dict(), ensure_ascii=False, sort_keys=True,
|
|
23
|
+
separators=(",", ":")).encode("utf-8")
|
|
24
|
+
return encode(raw, clock=clock)
|
|
25
|
+
|
|
26
|
+
@classmethod
|
|
27
|
+
def load(cls, payload: object, hardware_uuid: str) -> DeviceRecord | None:
|
|
28
|
+
# An invalid device record is a cache miss, not a damaged login key.
|
|
29
|
+
if isinstance(payload, str):
|
|
30
|
+
try:
|
|
31
|
+
payload = json.loads(decode(payload))
|
|
32
|
+
except (ValueError, UnicodeError):
|
|
33
|
+
return None
|
|
34
|
+
if not isinstance(payload, dict) or payload.get("version") != "1.2":
|
|
35
|
+
return None
|
|
36
|
+
values = [payload.get(key) for key in ("device_id_str", "install_id_str", "uuid")]
|
|
37
|
+
if any(not isinstance(value, str) for value in values):
|
|
38
|
+
return None
|
|
39
|
+
device_id, install_id, cached_uuid = values
|
|
40
|
+
parsed = parse_uint64(device_id)
|
|
41
|
+
if not parsed.ok or not parsed.value:
|
|
42
|
+
return None
|
|
43
|
+
if cached_uuid != hardware_uuid:
|
|
44
|
+
return None
|
|
45
|
+
return cls(device_id, install_id, cached_uuid)
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"""Independent implementation of reviewed Aha device-ID service behavior.
|
|
2
|
+
|
|
3
|
+
The default operation is offline. Remote IDs come from a validated cache or
|
|
4
|
+
registration; the hardware UUID is exposed separately as the local fallback.
|
|
5
|
+
The native lifecycle accepts an explicit TinyStorage adapter (read-only by
|
|
6
|
+
default); the existing login adapter retains the independent identity store.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
from concurrent.futures import Future
|
|
12
|
+
from copy import deepcopy
|
|
13
|
+
from dataclasses import dataclass, field, replace
|
|
14
|
+
import threading
|
|
15
|
+
from typing import Callable, Literal
|
|
16
|
+
|
|
17
|
+
import httpx
|
|
18
|
+
|
|
19
|
+
from .aha_registration import Registration, activate, register
|
|
20
|
+
from .aha_device_cache import DeviceRecord
|
|
21
|
+
from .device_hardware import Hardware
|
|
22
|
+
from .login_identity import IdentityStore, LoginIdentity, new_key
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class DeviceIdResult:
|
|
27
|
+
identity: LoginIdentity = field(repr=False)
|
|
28
|
+
hardware: Hardware = field(repr=False)
|
|
29
|
+
source: Literal["local", "cache", "registration", "timeout", "native"]
|
|
30
|
+
main_device_id: str | None = field(default=None, repr=False)
|
|
31
|
+
sdk_device_id: str | None = field(default=None, repr=False)
|
|
32
|
+
sdk_install_id: str | None = field(default=None, repr=False)
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def device_id(self) -> str:
|
|
36
|
+
return self.main_device_id if self.main_device_id is not None else self.remote_device_id
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def remote_device_id(self) -> str:
|
|
40
|
+
if self.sdk_device_id is not None:
|
|
41
|
+
return self.sdk_device_id
|
|
42
|
+
return self.identity.device_id if self.identity.registered else "0"
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def install_id(self) -> str:
|
|
46
|
+
if self.sdk_install_id is not None:
|
|
47
|
+
return self.sdk_install_id
|
|
48
|
+
return self.identity.install_id if self.identity.registered else "0"
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def local_device_id(self) -> str:
|
|
52
|
+
return self.hardware.local_device_id if self.hardware.local_device_id is not None else self.hardware.pc_uuid
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def guaranteed_device_id(self) -> str:
|
|
56
|
+
return self.device_id if self.device_id != "0" else self.local_device_id
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class AhaDeviceService:
|
|
60
|
+
"""Resolve an independent device identity without implicit HTTP access.
|
|
61
|
+
|
|
62
|
+
``allow_network=True`` permits registration on a cache miss. Activation is
|
|
63
|
+
separate: ``require_activation=True`` is used by the existing login flow.
|
|
64
|
+
A cached registration can be returned before activation, as in native Aha.
|
|
65
|
+
``get_device_id_async`` models the native pending getter. The synchronous
|
|
66
|
+
method is a compatibility snapshot/registration adapter for existing login.
|
|
67
|
+
``start_native_mode`` selects the native lifecycle, including its retry
|
|
68
|
+
policy and cache adapter; login preparation retains its stricter policy.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def __init__(self, store: IdentityStore, *, http: httpx.Client | None = None,
|
|
72
|
+
version: str = "3.4.20", hardware_reader: Callable[[], Hardware] | None = None):
|
|
73
|
+
self.store = store
|
|
74
|
+
self.http = http
|
|
75
|
+
self.version = version
|
|
76
|
+
self.hardware_reader = hardware_reader
|
|
77
|
+
self._hardware: Hardware | None = None
|
|
78
|
+
self._state_lock = threading.RLock()
|
|
79
|
+
self._operation_lock = threading.RLock()
|
|
80
|
+
self._latest: DeviceIdResult | None = None
|
|
81
|
+
self._ready: Future[DeviceIdResult] = Future()
|
|
82
|
+
self._native = None
|
|
83
|
+
self._native_identity: LoginIdentity | None = None
|
|
84
|
+
|
|
85
|
+
def _native_result(self, device_id: str, *, main_id: str | None = None) -> DeviceIdResult:
|
|
86
|
+
with self._state_lock:
|
|
87
|
+
identity = deepcopy(self._native_identity)
|
|
88
|
+
# Reading an SDK ID does not bind our OAuth installation key to it.
|
|
89
|
+
if (identity.device_id != device_id or identity.install_id != self._native.install_id
|
|
90
|
+
or DeviceRecord.load(identity.device_cache, self._hardware.pc_uuid) is None):
|
|
91
|
+
identity.registered, identity.activated = False, False
|
|
92
|
+
return DeviceIdResult(identity, self._hardware, "native", main_id,
|
|
93
|
+
device_id, self._native.install_id)
|
|
94
|
+
|
|
95
|
+
def _read_hardware(self, *, native: bool = False) -> Hardware:
|
|
96
|
+
with self._state_lock:
|
|
97
|
+
if self._hardware is None:
|
|
98
|
+
self._hardware = (self.hardware_reader or (Hardware.read_native if native else Hardware.read))()
|
|
99
|
+
return self._hardware
|
|
100
|
+
|
|
101
|
+
def _publish(self, result: DeviceIdResult) -> None:
|
|
102
|
+
with self._state_lock:
|
|
103
|
+
# Keep a timed-out main ID until the real remote ID arrives.
|
|
104
|
+
if not (self._latest is not None and result.remote_device_id == "0"
|
|
105
|
+
and self._latest.source == "timeout"):
|
|
106
|
+
self._latest = deepcopy(result)
|
|
107
|
+
if result.remote_device_id != "0" and not self._ready.done():
|
|
108
|
+
self._ready.set_result(deepcopy(result))
|
|
109
|
+
|
|
110
|
+
async def get_device_id_async(self) -> DeviceIdResult:
|
|
111
|
+
"""Return cached remote ID or wait; cancellation does not cancel registration."""
|
|
112
|
+
if self._native is not None:
|
|
113
|
+
return self._native_result(await self._native.get_device_id())
|
|
114
|
+
with self._state_lock:
|
|
115
|
+
latest = self._latest
|
|
116
|
+
if latest is None:
|
|
117
|
+
latest = await asyncio.to_thread(self.get_device_id)
|
|
118
|
+
if latest.remote_device_id != "0":
|
|
119
|
+
return deepcopy(latest)
|
|
120
|
+
return deepcopy(await asyncio.shield(asyncio.wrap_future(self._ready)))
|
|
121
|
+
|
|
122
|
+
async def resolve_device_id_async(self, *, timeout: float = 40.0) -> DeviceIdResult:
|
|
123
|
+
"""JS-wrapper semantics: local main ID on timeout; accept late remote ID."""
|
|
124
|
+
if self._native is not None:
|
|
125
|
+
ids = await self._native.resolve(timeout=timeout)
|
|
126
|
+
return self._native_result(ids["remoteDeviceId"], main_id=ids["deviceId"])
|
|
127
|
+
# Reviewed iCubeDeviceRegister.js: O$=4e4 milliseconds.
|
|
128
|
+
if timeout < 0:
|
|
129
|
+
raise ValueError("timeout must be nonnegative")
|
|
130
|
+
# Initialize even for timeout=0, before wait_for can cancel the getter.
|
|
131
|
+
with self._state_lock:
|
|
132
|
+
initialized = self._latest is not None
|
|
133
|
+
if not initialized:
|
|
134
|
+
await asyncio.to_thread(self.get_device_id)
|
|
135
|
+
with self._state_lock:
|
|
136
|
+
if self._latest.remote_device_id != "0":
|
|
137
|
+
return deepcopy(self._latest)
|
|
138
|
+
try:
|
|
139
|
+
return await asyncio.wait_for(self.get_device_id_async(), timeout)
|
|
140
|
+
except asyncio.TimeoutError:
|
|
141
|
+
with self._state_lock:
|
|
142
|
+
# Registration may have resolved between timeout and this lock.
|
|
143
|
+
if self._latest.remote_device_id != "0":
|
|
144
|
+
return deepcopy(self._latest)
|
|
145
|
+
self._latest = replace(self._latest, source="timeout",
|
|
146
|
+
main_device_id=self._latest.local_device_id)
|
|
147
|
+
return deepcopy(self._latest)
|
|
148
|
+
|
|
149
|
+
async def register_device_async(self, *, require_activation: bool = False) -> DeviceIdResult:
|
|
150
|
+
"""Explicit registration entry point; never scheduled by an offline getter."""
|
|
151
|
+
if self._native is not None:
|
|
152
|
+
raise ValueError("native mode active; use its start/wait_worker lifecycle")
|
|
153
|
+
return await asyncio.to_thread(self.get_device_id, allow_network=True,
|
|
154
|
+
require_activation=require_activation)
|
|
155
|
+
|
|
156
|
+
def get_all_ids(self) -> dict[str, str]:
|
|
157
|
+
if self._native is not None:
|
|
158
|
+
return self._native.get_all_ids()
|
|
159
|
+
with self._state_lock:
|
|
160
|
+
latest = self._latest
|
|
161
|
+
if latest is None:
|
|
162
|
+
latest = self.get_device_id()
|
|
163
|
+
return {"deviceId": latest.device_id, "localDeviceId": latest.local_device_id,
|
|
164
|
+
"remoteDeviceId": latest.remote_device_id}
|
|
165
|
+
|
|
166
|
+
async def start_native_mode(self, *, allow_network: bool = False, backend=None,
|
|
167
|
+
app_region: str = "CN", region_record_ready: bool | None = None, storage=None,
|
|
168
|
+
native_cache: bool = False,
|
|
169
|
+
flags_2: bool = False, flags_3: bool = False,
|
|
170
|
+
sleep=asyncio.sleep):
|
|
171
|
+
"""Create the raw native lifecycle, outside stricter login policy.
|
|
172
|
+
|
|
173
|
+
Caller owns its lifetime and must await close(). Network startup is
|
|
174
|
+
explicit even when an HTTP client has already been configured.
|
|
175
|
+
"""
|
|
176
|
+
from .aha_native_lifecycle import NativeAhaDeviceService
|
|
177
|
+
from .aha_native_backend import NativeHttpBackend
|
|
178
|
+
from .aha_tiny_storage import RegionRecord, NativeTinyStorage
|
|
179
|
+
if native_cache:
|
|
180
|
+
if storage is not None:
|
|
181
|
+
raise ValueError("choose native_cache or an explicit storage adapter")
|
|
182
|
+
storage = NativeTinyStorage.for_native_client()
|
|
183
|
+
if self._native is not None:
|
|
184
|
+
if backend is not None and self._native.backend is None:
|
|
185
|
+
self._native.backend = backend
|
|
186
|
+
await self._native.start(allow_network=allow_network)
|
|
187
|
+
return self._native
|
|
188
|
+
def native_snapshot():
|
|
189
|
+
with self._operation_lock:
|
|
190
|
+
return self._resolve_identity(allow_network=False, require_activation=False, validate_hardware=False)
|
|
191
|
+
snapshot = await asyncio.to_thread(native_snapshot)
|
|
192
|
+
region = RegionRecord.load(snapshot.identity.device_region)
|
|
193
|
+
record = DeviceRecord(snapshot.remote_device_id, snapshot.install_id, snapshot.hardware.pc_uuid)
|
|
194
|
+
if not snapshot.identity.registered:
|
|
195
|
+
record = None
|
|
196
|
+
if storage is not None:
|
|
197
|
+
record = await asyncio.to_thread(storage.load_device, snapshot.hardware.pc_uuid)
|
|
198
|
+
region = await asyncio.to_thread(storage.load_region)
|
|
199
|
+
if region_record_ready is None:
|
|
200
|
+
region_record_ready = region.ready
|
|
201
|
+
if backend is None and self.http is not None:
|
|
202
|
+
backend = NativeHttpBackend(self.http, snapshot.hardware, self.version)
|
|
203
|
+
if allow_network and backend is None:
|
|
204
|
+
raise ValueError("native lifecycle requires an explicitly supplied HTTP client or backend")
|
|
205
|
+
async def save_cache(value: DeviceRecord):
|
|
206
|
+
if storage is not None:
|
|
207
|
+
await asyncio.to_thread(storage.save_device, value)
|
|
208
|
+
def persist():
|
|
209
|
+
with self.store.locked():
|
|
210
|
+
identity = self.store.load()
|
|
211
|
+
if identity.device_id != value.device_id:
|
|
212
|
+
identity.private_key_pem = new_key()
|
|
213
|
+
identity.device_id, identity.install_id = value.device_id, value.install_id
|
|
214
|
+
identity.hardware_uuid = value.uuid
|
|
215
|
+
identity.device_cache = value.encoded()
|
|
216
|
+
identity.registered, identity.activated = True, False
|
|
217
|
+
self.store.save(identity)
|
|
218
|
+
with self._state_lock:
|
|
219
|
+
self._native_identity = deepcopy(identity)
|
|
220
|
+
await asyncio.to_thread(persist)
|
|
221
|
+
async def update_region(country: str, source: str):
|
|
222
|
+
nonlocal region
|
|
223
|
+
incoming = RegionRecord(True, country, source)
|
|
224
|
+
region = region.updated(incoming)
|
|
225
|
+
# Native merges into its live optional value, but serializes the
|
|
226
|
+
# incoming RegionInfo argument (RVA 0x0284416f), not the merge.
|
|
227
|
+
if storage is not None:
|
|
228
|
+
await asyncio.to_thread(storage.save_region, incoming)
|
|
229
|
+
else:
|
|
230
|
+
def persist_region():
|
|
231
|
+
with self.store.locked():
|
|
232
|
+
identity = self.store.load()
|
|
233
|
+
identity.device_region = incoming.encoded()
|
|
234
|
+
self.store.save(identity)
|
|
235
|
+
await asyncio.to_thread(persist_region)
|
|
236
|
+
native = NativeAhaDeviceService(hardware_uuid=snapshot.hardware.pc_uuid, record=record,
|
|
237
|
+
local_device_id=snapshot.local_device_id,
|
|
238
|
+
app_region=app_region, region_record_ready=bool(region_record_ready),
|
|
239
|
+
flags_2=flags_2, flags_3=flags_3, backend=backend, save_cache=save_cache,
|
|
240
|
+
update_region=update_region, sleep=sleep)
|
|
241
|
+
self._native_identity = deepcopy(snapshot.identity)
|
|
242
|
+
self._native = native
|
|
243
|
+
native.start_wrapper()
|
|
244
|
+
await asyncio.sleep(0)
|
|
245
|
+
await native.start(allow_network=allow_network)
|
|
246
|
+
return native
|
|
247
|
+
|
|
248
|
+
def get_device_id(self, *, allow_network: bool = False,
|
|
249
|
+
require_activation: bool = False) -> DeviceIdResult:
|
|
250
|
+
if self._native is not None:
|
|
251
|
+
if allow_network or require_activation:
|
|
252
|
+
raise ValueError("native mode active; use its lifecycle, separate from login preparation")
|
|
253
|
+
ids = self._native.get_all_ids()
|
|
254
|
+
return self._native_result(ids["remoteDeviceId"], main_id=ids["deviceId"])
|
|
255
|
+
if not allow_network and not require_activation:
|
|
256
|
+
with self._state_lock:
|
|
257
|
+
if self._latest is not None and self._latest.remote_device_id != "0":
|
|
258
|
+
return deepcopy(self._latest)
|
|
259
|
+
# One native service instance owns one initialization/registration path.
|
|
260
|
+
# Serialize same-instance callers before the cross-process profile lock.
|
|
261
|
+
with self._operation_lock:
|
|
262
|
+
return self._resolve_identity(allow_network=allow_network, require_activation=require_activation)
|
|
263
|
+
|
|
264
|
+
def _resolve_identity(self, *, allow_network: bool, require_activation: bool,
|
|
265
|
+
validate_hardware: bool = True) -> DeviceIdResult:
|
|
266
|
+
hardware = self._read_hardware(native=not validate_hardware)
|
|
267
|
+
if validate_hardware and (not isinstance(hardware.pc_uuid, str) or not hardware.pc_uuid or hardware.pc_uuid == "0"):
|
|
268
|
+
raise ValueError("hardware UUID unavailable; refusing to invent a registered device")
|
|
269
|
+
with self.store.locked():
|
|
270
|
+
identity = self.store.load()
|
|
271
|
+
previous_device_id = identity.device_id
|
|
272
|
+
# Migrate our legacy record once; do not read native TinyStorage.
|
|
273
|
+
if identity.device_cache is None:
|
|
274
|
+
identity.device_cache = (DeviceRecord(identity.device_id, identity.install_id,
|
|
275
|
+
identity.hardware_uuid).encoded() if identity.registered else {})
|
|
276
|
+
self.store.save(identity)
|
|
277
|
+
record = DeviceRecord.load(identity.device_cache, hardware.pc_uuid)
|
|
278
|
+
if record is None:
|
|
279
|
+
# Invalidate only the device record view, preserving the stored
|
|
280
|
+
# installation key and old record until a registration succeeds.
|
|
281
|
+
identity = replace(identity, registered=False, activated=False)
|
|
282
|
+
else:
|
|
283
|
+
activated = (identity.activated and identity.device_id == record.device_id
|
|
284
|
+
and identity.install_id == record.install_id
|
|
285
|
+
and identity.hardware_uuid == hardware.pc_uuid)
|
|
286
|
+
identity = replace(identity, device_id=record.device_id, install_id=record.install_id,
|
|
287
|
+
hardware_uuid=hardware.pc_uuid, registered=True, activated=activated)
|
|
288
|
+
# Persist a new/migrated installation even if registration fails.
|
|
289
|
+
if not self.store.path.exists():
|
|
290
|
+
self.store.save(identity)
|
|
291
|
+
source = "cache" if identity.registered else "local"
|
|
292
|
+
# Publish initialized IDs before HTTP: the JS timeout must remain
|
|
293
|
+
# independent of a slow registration/activation operation.
|
|
294
|
+
self._publish(DeviceIdResult(replace(identity), hardware, source))
|
|
295
|
+
needs_registration = not identity.registered
|
|
296
|
+
needs_activation = require_activation and not identity.activated
|
|
297
|
+
if (needs_registration or needs_activation) and allow_network and self.http is None:
|
|
298
|
+
raise ValueError("network operation requires an explicitly supplied HTTP client")
|
|
299
|
+
if allow_network and needs_registration:
|
|
300
|
+
registration = register(self.http, hardware, self.version, strict_ids=require_activation)
|
|
301
|
+
if previous_device_id != registration.device_id:
|
|
302
|
+
identity.private_key_pem = new_key()
|
|
303
|
+
identity.device_id, identity.install_id = registration.device_id, registration.install_id
|
|
304
|
+
identity.hardware_uuid, identity.region = hardware.pc_uuid, registration.region
|
|
305
|
+
identity.registered, identity.activated = True, False
|
|
306
|
+
identity.device_cache = DeviceRecord(identity.device_id, identity.install_id, hardware.pc_uuid).encoded()
|
|
307
|
+
# Native registration also saves before activation. Failure of
|
|
308
|
+
# activation must not cause another installation registration.
|
|
309
|
+
self.store.save(identity)
|
|
310
|
+
source = "registration"
|
|
311
|
+
self._publish(DeviceIdResult(replace(identity), hardware, source))
|
|
312
|
+
if require_activation and identity.registered:
|
|
313
|
+
if any(not value.isascii() or not value.isdecimal() or int(value) <= 0
|
|
314
|
+
for value in (identity.device_id, identity.install_id)):
|
|
315
|
+
raise ValueError("login activation requires positive decimal device/install IDs")
|
|
316
|
+
if require_activation and not identity.activated:
|
|
317
|
+
if not allow_network:
|
|
318
|
+
raise ValueError("device activation not confirmed; network access is disabled")
|
|
319
|
+
activate(self.http, Registration(identity.device_id, identity.install_id, identity.region),
|
|
320
|
+
hardware, self.version)
|
|
321
|
+
identity.activated = True
|
|
322
|
+
self.store.save(identity)
|
|
323
|
+
result = DeviceIdResult(identity, hardware, source)
|
|
324
|
+
self._publish(result)
|
|
325
|
+
return result
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Explicit HTTP adapter for NativeAhaDeviceService; no account endpoints."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from .aha_native_lifecycle import RegisterReply, ActiveReply
|
|
10
|
+
from .aha_registration import REGISTER_URL, ACTIVE_URL, registration_request
|
|
11
|
+
from .device_hardware import Hardware
|
|
12
|
+
|
|
13
|
+
MAX_RESPONSE_SIZE = 0x100000 # DoRequest -> DownloadToString, RVA 0x02849f21.
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class NativeHttpBackend:
|
|
17
|
+
def __init__(self, client: httpx.Client, hardware: Hardware, version: str):
|
|
18
|
+
self.client, self.hardware, self.version = client, hardware, version
|
|
19
|
+
|
|
20
|
+
def _post(self, url: str, query: dict, body: bytes, headers: dict):
|
|
21
|
+
with self.client.stream("POST", url, params=query, content=body, headers=headers,
|
|
22
|
+
follow_redirects=True) as response:
|
|
23
|
+
result = bytearray()
|
|
24
|
+
for chunk in response.iter_bytes(65536):
|
|
25
|
+
if len(result) + len(chunk) > MAX_RESPONSE_SIZE:
|
|
26
|
+
return response.status_code, -1, b"", response.headers
|
|
27
|
+
result.extend(chunk)
|
|
28
|
+
return response.status_code, 0, bytes(result), response.headers
|
|
29
|
+
|
|
30
|
+
async def register(self, device_id: str, install_id: str) -> RegisterReply:
|
|
31
|
+
query, body = registration_request(self.hardware, self.version,
|
|
32
|
+
device_id=device_id, install_id=install_id)
|
|
33
|
+
try:
|
|
34
|
+
status, error, body, headers = await asyncio.to_thread(self._post, REGISTER_URL, query, body,
|
|
35
|
+
{"Content-Type": "application/json", "Content-Encoding": "gzip"})
|
|
36
|
+
except httpx.HTTPError:
|
|
37
|
+
# The state machine uses zero/nonzero. TTNet's precise error-number
|
|
38
|
+
# taxonomy is not synthesized by this HTTPX transport adapter.
|
|
39
|
+
return RegisterReply(status=0, net_error=-1)
|
|
40
|
+
try:
|
|
41
|
+
value = json.loads(body.decode("utf-8-sig"))
|
|
42
|
+
except (ValueError, UnicodeError):
|
|
43
|
+
value = None
|
|
44
|
+
return RegisterReply(value.get("device_id_str") if isinstance(value, dict) else None,
|
|
45
|
+
value.get("install_id_str") if isinstance(value, dict) else None,
|
|
46
|
+
status=status, net_error=error,
|
|
47
|
+
region_record_ready=True if "x-tt-store-region" in headers else None,
|
|
48
|
+
country_code=headers.get("x-tt-store-region"),
|
|
49
|
+
country_source=headers.get("x-tt-store-region-src", "did"))
|
|
50
|
+
|
|
51
|
+
async def activate(self, device_id: str, install_id: str) -> ActiveReply:
|
|
52
|
+
query = {"aid": "787976", "app_name": "Trae CN", "version_code": self.version,
|
|
53
|
+
"channel": "stable", "os": "Windows", "device_platform": "PC",
|
|
54
|
+
"device_id": device_id, "iid": install_id,
|
|
55
|
+
"pc_uuid": self.hardware.pc_uuid, "pc_serial": self.hardware.pc_serial}
|
|
56
|
+
try:
|
|
57
|
+
status, error, _, _ = await asyncio.to_thread(self._post, ACTIVE_URL, query, b"",
|
|
58
|
+
{"Content-Type": "application/json"})
|
|
59
|
+
return ActiveReply(status=status, net_error=error)
|
|
60
|
+
except httpx.HTTPError:
|
|
61
|
+
return ActiveReply(status=0, net_error=-1)
|