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,111 @@
1
+ """Trae state.vscdb credential decryption.
2
+
3
+ Reverse engineered from Trae CN 3.4.4 out-build/vs/base/common/byteCrypto.js.
4
+
5
+ Scheme (function H1/YVe encrypt, b2/GVe decrypt):
6
+ header = bytes([116, 99, 5, 16, 0, 0]) + 32-byte random key
7
+ payload= AES-128-CBC( SHA512(plaintext)[:64] + plaintext, key, iv )
8
+ key/iv derivation (Fle):
9
+ buf = 128 bytes
10
+ buf[0:64] = SHA512(key)
11
+ buf[64:128]= XOR_TABLES (Gle[i] ^ zle[i], 64 bytes)
12
+ buf[0:64] = SHA512(buf) # overwrite
13
+ aesKey = buf[0:16], iv = buf[16:32]
14
+ value stored base64(header+payload) in ItemTable under the storage key.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import base64
19
+ import hashlib
20
+ import sqlite3
21
+ import sys
22
+
23
+ HEADER = bytes([116, 99, 5, 16, 0, 0]) # "tc" v5 AES
24
+
25
+ GLE = bytes([82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251,
26
+ 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203,
27
+ 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78,
28
+ 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37])
29
+ ZLE = bytes([31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95,
30
+ 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239,
31
+ 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97,
32
+ 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125])
33
+ XOR_TABLES = bytes(g ^ z for g, z in zip(GLE, ZLE))
34
+
35
+ KEY_LEN = 32 # S2
36
+ HASH_PREFIX = 64 # Qh (SHA512)
37
+ HEADER_LEN = 6 # W1
38
+
39
+
40
+ def derive_key_iv(key: bytes, version: bytes = b"AES") -> tuple[bytes, bytes]:
41
+ buf = bytearray(128) # Qh + PN = 64 + 64
42
+ buf[0:64] = hashlib.sha512(key).digest()
43
+ if version == b"AES":
44
+ buf[64:128] = XOR_TABLES
45
+ else: # AES_PRIVATE variant (Vle ^ qle)
46
+ raise ValueError("AES_PRIVATE variant not needed here")
47
+ buf[0:64] = hashlib.sha512(bytes(buf)).digest()
48
+ return bytes(buf[0:16]), bytes(buf[16:32]) # AES128 key + 16-byte IV
49
+
50
+
51
+ def decrypt_blob(data: bytes) -> bytes | None:
52
+ if len(data) < HEADER_LEN + KEY_LEN + 16:
53
+ return None
54
+ if data[0:6] != HEADER:
55
+ return None
56
+ key = data[6:38]
57
+ aes_key, iv = derive_key_iv(key)
58
+
59
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
60
+
61
+ dec = Cipher(algorithms.AES(aes_key), modes.CBC(iv)).decryptor()
62
+ padded = dec.update(data[38:]) + dec.finalize()
63
+ # strip PKCS7
64
+ pad = padded[-1]
65
+ if not 1 <= pad <= 16 or padded[-pad:] != bytes([pad]) * pad:
66
+ return None
67
+ plain = padded[:-pad]
68
+ if len(plain) < HASH_PREFIX:
69
+ return None
70
+ digest, payload = plain[:HASH_PREFIX], plain[HASH_PREFIX:]
71
+ if hashlib.sha512(payload).digest() != digest:
72
+ return None
73
+ return payload
74
+
75
+
76
+ def decrypt_value(b64_value: str) -> str | None:
77
+ try:
78
+ raw = base64.b64decode(b64_value)
79
+ except Exception:
80
+ return None
81
+ out = decrypt_blob(raw)
82
+ return out.decode("utf-8", "replace") if out is not None else None
83
+
84
+
85
+ def dump_state(db_path: str, only_keys: list[str] | None = None) -> dict[str, str]:
86
+ con = sqlite3.connect(db_path)
87
+ try:
88
+ rows = con.execute("SELECT key, value FROM ItemTable").fetchall()
89
+ finally:
90
+ con.close()
91
+ result: dict[str, str] = {}
92
+ for key, value in rows:
93
+ if not isinstance(value, str):
94
+ continue
95
+ if only_keys and not any(k in key for k in only_keys):
96
+ continue
97
+ plain = decrypt_value(value)
98
+ if plain is not None:
99
+ result[key] = plain
100
+ return result
101
+
102
+
103
+ if __name__ == "__main__":
104
+ db = sys.argv[1] if len(sys.argv) > 1 else "notes/state-copy.vscdb"
105
+ wanted = sys.argv[2].split(",") if len(sys.argv) > 2 else ["iCubeAuthInfo"]
106
+ found = dump_state(db, wanted)
107
+ for k, v in found.items():
108
+ print(f"===== {k} ({len(v)} chars) =====")
109
+ print(v if len(v) < 4000 else v[:4000] + f"...(+{len(v)-4000})")
110
+ if not found:
111
+ print("No decryptable values for:", wanted)
@@ -0,0 +1,39 @@
1
+ """Read and validate Trae credential files without device-registration side effects."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import json
6
+ from pathlib import Path
7
+ import time
8
+
9
+
10
+ def reject_expired_token(token: str) -> None:
11
+ """Use JWT expiry for local diagnostics, not authentication."""
12
+ parts = token.split('.')
13
+ if len(parts) != 3:
14
+ return
15
+ try:
16
+ payload = json.loads(base64.urlsafe_b64decode(parts[1] + '=' * (-len(parts[1]) % 4)))
17
+ expiry = payload.get('exp') if isinstance(payload, dict) else None
18
+ except (ValueError, UnicodeError):
19
+ return
20
+ if type(expiry) in (int, float) and expiry <= time.time():
21
+ raise ValueError('login token expired; sign in to Trae again')
22
+
23
+
24
+ def load_file(path: str | Path) -> tuple[dict, dict, str, str]:
25
+ """Return auth/device metadata and validated token/device ID."""
26
+ data = json.loads(Path(path).read_text(encoding='utf-8'))
27
+ if not isinstance(data, dict):
28
+ raise ValueError('credentials must be a JSON object')
29
+ auth, device = data.get('auth', data), data.get('device', {})
30
+ if not isinstance(auth, dict) or not isinstance(device, dict):
31
+ raise ValueError('credentials auth and device must be JSON objects')
32
+ token = auth.get('token') or auth.get('jwt')
33
+ if 'deviceId' not in device:
34
+ device = auth
35
+ device_id = device.get('deviceId')
36
+ if not isinstance(token, str) or not token or not isinstance(device_id, str) or not device_id or device_id == '0':
37
+ raise ValueError('credentials must contain auth.token (or auth.jwt) and device.deviceId (or legacy auth.deviceId)')
38
+ reject_expired_token(token)
39
+ return auth, device, token, device_id
@@ -0,0 +1,377 @@
1
+ """Sample Windows hardware once and derive per-call registration metadata."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import asdict, dataclass, field, replace
5
+ import ctypes
6
+ import json
7
+ import platform
8
+ import secrets
9
+ import string
10
+ import threading
11
+ import struct
12
+ import subprocess
13
+ import uuid
14
+
15
+ from .client_metadata import device_model, os_metadata
16
+
17
+
18
+ def registry_text(path: str, name: str) -> str:
19
+ if platform.system() != "Windows":
20
+ return ""
21
+ import winreg
22
+ try:
23
+ with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) as key:
24
+ value, _ = winreg.QueryValueEx(key, name)
25
+ return value.strip() if isinstance(value, str) else ""
26
+ except OSError:
27
+ return ""
28
+
29
+
30
+ def manufacturer() -> str:
31
+ return registry_text(r"HARDWARE\DESCRIPTION\System\BIOS", "SystemManufacturer")
32
+
33
+
34
+ def cpu_brand() -> str:
35
+ return registry_text(r"HARDWARE\DESCRIPTION\System\CentralProcessor\0", "ProcessorNameString")
36
+
37
+
38
+ def uuid_from_smbios(data: bytes, *, allow_unset: bool = False) -> str:
39
+ """Parse RawSMBIOSData and the type-1 UUID using native Windows byte order."""
40
+ if len(data) < 8:
41
+ raise ValueError("invalid SMBIOS firmware data")
42
+ length = struct.unpack_from("<I", data, 4)[0]
43
+ if length > len(data) - 8:
44
+ raise ValueError("truncated SMBIOS firmware data")
45
+ pos, end = 8, 8 + length
46
+ while pos + 4 <= end:
47
+ kind, size = data[pos], data[pos + 1]
48
+ if size < 4 or pos + size > end:
49
+ break
50
+ if kind == 1 and size >= 25:
51
+ raw = data[pos + 8:pos + 24]
52
+ if allow_unset or raw not in (b"\0" * 16, b"\xff" * 16):
53
+ return str(uuid.UUID(bytes_le=raw)).upper()
54
+ strings_end = data.find(b"\0\0", pos + size, end)
55
+ if strings_end < 0 or kind == 127:
56
+ break
57
+ pos = strings_end + 2
58
+ raise ValueError("no valid hardware UUID in SMBIOS")
59
+
60
+
61
+ def _smbios_uuid() -> str:
62
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
63
+ firmware = kernel.GetSystemFirmwareTable
64
+ firmware.argtypes = [ctypes.c_uint32, ctypes.c_uint32, ctypes.c_void_p, ctypes.c_uint32]
65
+ firmware.restype = ctypes.c_uint32
66
+ provider = int.from_bytes(b"RSMB", "big")
67
+ size = firmware(provider, 0, None, 0)
68
+ if not size or size > 16 * 1024 * 1024:
69
+ raise ValueError("cannot read SMBIOS hardware UUID")
70
+ buffer = ctypes.create_string_buffer(size)
71
+ read = firmware(provider, 0, buffer, size)
72
+ if read != size:
73
+ raise ValueError("SMBIOS hardware information changed while reading")
74
+ return uuid_from_smbios(buffer.raw, allow_unset=True)
75
+
76
+
77
+ def _wmi_uuid() -> str | None:
78
+ # Fixed, read-only query. Never interpolate hardware values into a shell.
79
+ command = ("$ErrorActionPreference='Stop'; "
80
+ "Get-CimInstance -Query 'SELECT UUID FROM Win32_ComputerSystemProduct' | "
81
+ "Select-Object -First 1 -ExpandProperty UUID | ConvertTo-Json -Compress")
82
+ try:
83
+ result = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", command],
84
+ capture_output=True, timeout=15, check=True,
85
+ creationflags=subprocess.CREATE_NO_WINDOW)
86
+ value = json.loads(result.stdout.decode("utf-8-sig"))
87
+ return value if isinstance(value, str) else None
88
+ except (OSError, subprocess.SubprocessError, ValueError, UnicodeError):
89
+ return None
90
+
91
+
92
+ def device_uuids() -> tuple[str, str]:
93
+ """Registration UUID may use WMI; localDeviceId keeps DeviceInfo's UUID."""
94
+ if platform.system() != "Windows":
95
+ raise ValueError("standalone device registration currently supports Windows hardware only")
96
+ try:
97
+ local = _smbios_uuid()
98
+ except (OSError, ValueError):
99
+ local = ""
100
+ try:
101
+ parsed = uuid.UUID(local)
102
+ local = str(parsed).upper()
103
+ if parsed.int not in (0, (1 << 128) - 1):
104
+ return local, local
105
+ except ValueError:
106
+ pass
107
+ # Native checks VT_BSTR, converts UTF-16 to UTF-8, then copies verbatim.
108
+ # A failed WMI lookup retains the original DeviceInfo UUID.
109
+ fallback = _wmi_uuid()
110
+ return (fallback if fallback is not None else local), local
111
+
112
+
113
+ def system_uuid() -> str:
114
+ value, _ = device_uuids()
115
+ if not value:
116
+ raise ValueError("cannot read a hardware UUID from SMBIOS or WMI")
117
+ return value
118
+
119
+
120
+ def _disk_serial_from_drive(index: int) -> str:
121
+ if platform.system() != "Windows":
122
+ return ""
123
+ from ctypes import wintypes
124
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
125
+ kernel.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD,
126
+ ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
127
+ kernel.CreateFileW.restype = wintypes.HANDLE
128
+ kernel.DeviceIoControl.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.c_void_p,
129
+ wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p]
130
+ kernel.CloseHandle.argtypes = [wintypes.HANDLE]
131
+ handle = kernel.CreateFileW(r"\\.\PhysicalDrive" + str(index), 0, 3, None, 3, 0, None)
132
+ if handle == ctypes.c_void_p(-1).value:
133
+ return ""
134
+ try:
135
+ query = ctypes.create_string_buffer(12) # StorageDeviceProperty, PropertyStandardQuery.
136
+ output = ctypes.create_string_buffer(4096)
137
+ returned = wintypes.DWORD()
138
+ if not kernel.DeviceIoControl(handle, 0x2D1400, query, len(query), output,
139
+ len(output), ctypes.byref(returned), None) or returned.value < 28:
140
+ return ""
141
+ offset = struct.unpack_from("<I", output.raw, 24)[0]
142
+ if offset < 36 or offset >= returned.value:
143
+ return ""
144
+ return output.raw[offset:returned.value].split(b"\0")[0].decode("ascii", errors="ignore").strip()
145
+ finally:
146
+ kernel.CloseHandle(handle)
147
+
148
+
149
+ def _disk_count() -> int:
150
+ import winreg
151
+ try:
152
+ with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\disk\Enum") as key:
153
+ value, kind = winreg.QueryValueEx(key, "Count")
154
+ return min(value, 10) if kind == winreg.REG_DWORD and type(value) is int and value > 0 else 0
155
+ except OSError:
156
+ return 0
157
+
158
+
159
+ def _os_disk_number() -> int:
160
+ from ctypes import wintypes
161
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
162
+ kernel.GetWindowsDirectoryW.argtypes = [wintypes.LPWSTR, wintypes.UINT]
163
+ directory = ctypes.create_unicode_buffer(32768)
164
+ length = kernel.GetWindowsDirectoryW(directory, len(directory))
165
+ if not 2 <= length < len(directory) or directory.value[1] != ":":
166
+ return -1
167
+ kernel.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD,
168
+ ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
169
+ kernel.CreateFileW.restype = wintypes.HANDLE
170
+ kernel.DeviceIoControl.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.c_void_p,
171
+ wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p]
172
+ kernel.CloseHandle.argtypes = [wintypes.HANDLE]
173
+ handle = kernel.CreateFileW("\\\\.\\" + directory.value[:2], 0, 3, None, 3, 0, None)
174
+ if handle == ctypes.c_void_p(-1).value:
175
+ return -1
176
+ try:
177
+ output, returned = ctypes.create_string_buffer(4096), wintypes.DWORD()
178
+ if (kernel.DeviceIoControl(handle, 0x560000, None, 0, output, len(output),
179
+ ctypes.byref(returned), None) and returned.value >= 32
180
+ and struct.unpack_from("<I", output.raw)[0]):
181
+ return struct.unpack_from("<I", output.raw, 8)[0]
182
+ return -1
183
+ finally:
184
+ kernel.CloseHandle(handle)
185
+
186
+
187
+ def disk_serial() -> str:
188
+ """Enumerate up to ten disks; prefer disk 0, OS disk, then first valid disk."""
189
+ if platform.system() != "Windows":
190
+ return ""
191
+ serials = {index: _disk_serial_from_drive(index) for index in range(_disk_count())}
192
+ if serials.get(0):
193
+ return serials[0]
194
+ system_disk = _os_disk_number() if serials else -1
195
+ if serials.get(system_disk):
196
+ return serials[system_disk]
197
+ return next((value for value in serials.values() if value), "")
198
+
199
+
200
+ MAC_CACHE_KEY = r"Software\DeviceInfo\MacAddr"
201
+
202
+
203
+ def _read_mac_cache() -> str:
204
+ import winreg
205
+ try:
206
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, MAC_CACHE_KEY) as key:
207
+ value, kind = winreg.QueryValueEx(key, "mac")
208
+ if kind == winreg.REG_BINARY and isinstance(value, bytes) and 0 < len(value) <= 256:
209
+ return value.decode("ascii")
210
+ return ""
211
+ except (OSError, UnicodeError):
212
+ return ""
213
+
214
+
215
+ def _write_mac_cache(value: str) -> None:
216
+ import winreg
217
+ try:
218
+ with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, MAC_CACHE_KEY, 0, winreg.KEY_SET_VALUE) as key:
219
+ winreg.SetValueEx(key, "mac", 0, winreg.REG_BINARY, value.encode("ascii"))
220
+ except OSError:
221
+ pass # Native also continues with the sampled address if caching fails.
222
+
223
+
224
+ def mac_address() -> str:
225
+ """Native HKCU cache first, then adapters; persist a real sampled address."""
226
+ if platform.system() != "Windows":
227
+ return ""
228
+ cached = _read_mac_cache()
229
+ if cached:
230
+ return cached
231
+ value = _adapter_mac_address()
232
+ if value:
233
+ _write_mac_cache(value)
234
+ return value
235
+
236
+
237
+ def _adapter_mac_address() -> str:
238
+ if platform.system() != "Windows":
239
+ return ""
240
+ api = ctypes.WinDLL("iphlpapi").GetAdaptersAddresses
241
+ api.argtypes = [ctypes.c_ulong, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_void_p,
242
+ ctypes.POINTER(ctypes.c_ulong)]
243
+ api.restype = ctypes.c_ulong
244
+ size = ctypes.c_ulong(15000)
245
+ buffer = ctypes.create_string_buffer(size.value)
246
+ result = api(0, 0, None, buffer, ctypes.byref(size))
247
+ if result == 111 and size.value <= 1024 * 1024:
248
+ buffer = ctypes.create_string_buffer(size.value)
249
+ result = api(0, 0, None, buffer, ctypes.byref(size))
250
+ if result:
251
+ return ""
252
+ pointer = ctypes.addressof(buffer)
253
+ end = pointer + len(buffer)
254
+ visited = set()
255
+ while pointer and pointer not in visited and ctypes.addressof(buffer) <= pointer <= end - 96:
256
+ visited.add(pointer)
257
+ row = ctypes.string_at(pointer, 96)
258
+ length = struct.unpack_from("<I", row, 88)[0]
259
+ if 0 < length <= 8:
260
+ address = row[80:80 + length]
261
+ if any(address):
262
+ return "-".join(f"{byte:02X}" for byte in address)
263
+ pointer = struct.unpack_from("<Q", row, 8)[0]
264
+ return ""
265
+
266
+
267
+ _baseline_lock = threading.Lock()
268
+ _baseline: "Hardware | None" = None
269
+
270
+
271
+ def _drift_serial(value: str) -> str:
272
+ # Keep length, punctuation and character classes, changing up to six
273
+ # trailing alphanumeric characters. Missing values remain missing.
274
+ chars = list(value)
275
+ positions = [i for i, char in enumerate(chars) if char in string.ascii_letters + string.digits][-6:]
276
+ for i in positions:
277
+ alphabet = (string.digits if chars[i] in string.digits else
278
+ string.ascii_uppercase if chars[i] in string.ascii_uppercase else string.ascii_lowercase)
279
+ options = alphabet.replace(chars[i], "")
280
+ chars[i] = secrets.choice(options)
281
+ return "".join(chars)
282
+
283
+
284
+ def _drift_mac(value: str) -> str:
285
+ # Preserve the textual form where possible and mark the address locally
286
+ # administered and unicast. Unrecognized or absent values are left intact.
287
+ separator = "-" if "-" in value else ":"
288
+ parts = value.split(separator)
289
+ if len(parts) != 6 or any(len(part) != 2 or any(c not in string.hexdigits for c in part) for part in parts):
290
+ return value
291
+ address = [int(part, 16) for part in parts]
292
+ address[0] = (address[0] | 2) & 0xFE
293
+ # Each trailing byte changes from its baseline value.
294
+ address[3:] = [(byte + 1 + secrets.randbelow(255)) % 256 for byte in address[3:]]
295
+ return separator.join(f"{byte:02X}" for byte in address)
296
+
297
+
298
+ @dataclass(frozen=True)
299
+ class Hardware:
300
+ pc_uuid: str = field(repr=False)
301
+ pc_serial: str = field(repr=False)
302
+ model: str
303
+ brand: str
304
+ cpu: str
305
+ os_name: str
306
+ os_version: str
307
+ os_release: str
308
+ mac: str = field(default="", repr=False)
309
+ local_device_id: str | None = field(default=None, repr=False)
310
+
311
+ @classmethod
312
+ def read(cls, user_id: str | None = None) -> "Hardware":
313
+ result = cls.read_native(user_id) if user_id is not None else cls.read_native()
314
+ if not result.pc_uuid:
315
+ raise ValueError("cannot read a hardware UUID from SMBIOS or WMI")
316
+ return result
317
+
318
+ @classmethod
319
+ def for_account(cls, user_id: str) -> "Hardware":
320
+ """Return the persisted device profile for an account, creating it once."""
321
+ if not isinstance(user_id, str) or not user_id:
322
+ raise ValueError("account ID is required for hardware profile")
323
+ from .app_storage import _locked, root
324
+ from .login_identity import atomic_json
325
+ path = root() / "device_hardware.json"
326
+ with _locked():
327
+ if path.exists():
328
+ profiles = json.loads(path.read_text(encoding="utf-8-sig"))
329
+ if not isinstance(profiles, dict):
330
+ raise ValueError("invalid device_hardware.json; refusing to overwrite it")
331
+ else:
332
+ profiles = {}
333
+ if user_id in profiles:
334
+ try:
335
+ values = profiles[user_id]
336
+ if not isinstance(values, dict) or set(values) != set(cls.__dataclass_fields__):
337
+ raise ValueError()
338
+ if any(not isinstance(value, str) for key, value in values.items()
339
+ if key != "local_device_id"):
340
+ raise ValueError()
341
+ if values["local_device_id"] is not None and not isinstance(values["local_device_id"], str):
342
+ raise ValueError()
343
+ result = cls(**values)
344
+ except (TypeError, ValueError):
345
+ raise ValueError("invalid account hardware profile; refusing to overwrite it") from None
346
+ else:
347
+ baseline = cls.read_real()
348
+ if not baseline.pc_uuid:
349
+ raise ValueError("cannot read a hardware UUID from SMBIOS or WMI")
350
+ new_uuid = str(uuid.uuid4()).upper()
351
+ local_uuid = (new_uuid if baseline.local_device_id == baseline.pc_uuid else
352
+ str(uuid.uuid4()).upper() if baseline.local_device_id else baseline.local_device_id)
353
+ result = replace(baseline, pc_uuid=new_uuid, local_device_id=local_uuid,
354
+ pc_serial=_drift_serial(baseline.pc_serial), mac=_drift_mac(baseline.mac))
355
+ profiles[user_id] = asdict(result)
356
+ atomic_json(path, profiles)
357
+ from .diagnostics import get_logger
358
+ get_logger().info(json.dumps({"kind": "account_hardware", "user_id": user_id, **asdict(result)}, ensure_ascii=False))
359
+ return result
360
+
361
+ @classmethod
362
+ def read_native(cls, user_id: str | None = None) -> "Hardware":
363
+ """Use the account profile, or the real hardware when no account is known."""
364
+ return cls.for_account(user_id) if user_id is not None else cls.read_real()
365
+
366
+ @classmethod
367
+ def read_real(cls) -> "Hardware":
368
+ """Return the unmodified hardware snapshot used to validate native cache."""
369
+ global _baseline
370
+ with _baseline_lock:
371
+ if _baseline is None:
372
+ name, version = os_metadata()
373
+ registration_uuid, local_uuid = device_uuids()
374
+ _baseline = cls(registration_uuid, disk_serial(), device_model(), manufacturer(), cpu_brand(),
375
+ name, version, platform.version() if name == "windows" else platform.release(),
376
+ mac_address(), local_uuid)
377
+ return _baseline
@@ -0,0 +1,38 @@
1
+ """Trae authentication and device diagnostics, independent of host applications."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ import sys
6
+ import time
7
+ from pathlib import Path
8
+
9
+ _logger: logging.Logger | None = None
10
+ _log_directory: Path | None = None
11
+
12
+
13
+ def configure_log_directory(directory: Path | None) -> None:
14
+ global _log_directory
15
+ _log_directory = Path(directory) if directory is not None else None
16
+
17
+
18
+ def get_logger() -> logging.Logger:
19
+ global _logger
20
+ if _logger is not None:
21
+ return _logger
22
+ logger = logging.getLogger('trae2api.debug')
23
+ logger.setLevel(logging.DEBUG)
24
+ logger.propagate = False
25
+ if not logger.handlers:
26
+ stream = logging.StreamHandler(sys.stderr)
27
+ stream.setFormatter(logging.Formatter('[trae2api] %(message)s'))
28
+ logger.addHandler(stream)
29
+ try:
30
+ directory = _log_directory or Path.cwd() / 'logs'
31
+ directory.mkdir(parents=True, exist_ok=True)
32
+ output = logging.FileHandler(directory / f"debug-{time.strftime('%Y%m%d')}.log", encoding='utf-8')
33
+ output.setFormatter(logging.Formatter('%(message)s'))
34
+ logger.addHandler(output)
35
+ except OSError:
36
+ pass
37
+ _logger = logger
38
+ return logger