creditdaddy 1.7.0 → 1.7.2

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.
@@ -0,0 +1,599 @@
1
+ /**
2
+ * Trae 国内站浏览器登录 — 官方客户端同款 OAuth 授权码 + PKCE(S256)闭环。
3
+ *
4
+ * 协议(2026-09/10 社区抓包固化,workbuddy-switch / muskke trae-api-proxy / 10router#99 三方互证):
5
+ * 1. 客户端构造授权 URL(22 参数,内层 `${loginHost}/authorization`,外层再包一层
6
+ * `/login?login_platform=trae&redirect_url=<内层>`——与真机客户端逐字一致):
7
+ * `client_id=ono9krqynydwx5`(TRAE 产品线固定钥匙)、`code_challenge`(PKCE S256)、
8
+ * `login_trace_id`(兼作 CSRF 绑定值)、`auth_callback_url=http://127.0.0.1:<port>/authorize`。
9
+ * 2. 用户在浏览器登录并点授权 → 授权页前端调 GetPCAuthCode(绑定 challenge)→
10
+ * 302 回 `auth_callback_url`,参数:`authCodeInfo`(URL 编码 JSON,含 AuthCode/ExpireAt)
11
+ * + `userInfo`(UserID/ScreenName)+ `host`(换票主机)+ `userRegion` + `loginTraceID`。
12
+ * 3. `POST ${host}/trae/api/v3/oauth/ExchangeToken`,body
13
+ * `{ClientID, AuthCode, CodeVerifier, DeviceInfo, IDEVersion}` 换 accessToken(Cloud-IDE-JWT)
14
+ * + refreshToken。AuthCode 交换**不需要私钥**(DeviceInfo.DevicePublicKey 声明设备身份,
15
+ * DeviceProof 是 refreshToken 刷新场景专属——本模块只管登录闭环,刷新链后续单独做)。
16
+ * 旧端点 `/cloudide/api/v3/trae/oauth/ExchangeToken`(扁平 body)仍活着,作兜底。
17
+ *
18
+ * ## 设备身份:自造独立指纹(每个账号一套,不与本机 Trae 客户端共用)
19
+ *
20
+ * muskke 证实**自造身份可完成完整登录**(machine_id 随机 UUID + 现场生成 DevicePublicKey)。
21
+ * workbuddy 记录的 20403「Token device not match」根因是授权 URL 与请求体**两处不同源**——
22
+ * 本模块 device_id / machine_id / DevicePublicKey 单点生成、三处同源,不会踩它。
23
+ * 自造还有两个好处:① 每个账号独立设备指纹,不触发共享设备风控(4017,trae2api-hub 实测);
24
+ * ② 不与本机 Trae 客户端抢身份。deviceId 用 16 位纯数字(签到接口风控要求,traeLocal 同款约束),
25
+ * keypair 为 EC P-256(与客户端同款),**私钥 JWK 落进账号 meta**——本仓库凭据本就明文落本地,
26
+ * 与现有安全姿态一致;buildExportPayload 只挑白名单字段,meta 不会跟着同步推去 10Router。
27
+ *
28
+ * ## ★ 回调监听的三条硬规矩(workbuddy 踩坑沉淀)
29
+ *
30
+ * 1. 授权页在「认证中,正在验证身份」阶段会**从浏览器侧探测本机回调端口**,探不到就不走完
31
+ * 授权。端口跟 `auth_callback_url` 声明的一致(muskke 证实可自选;workbuddy 观察到的
32
+ * 17388 是旧版本行为,真机 3.4.9 客户端用 3379——两处都试绑,URL 用绑上的那个)。
33
+ * 2. 探测请求**必须回 200 + CORS 头**(授权页是 https 源,跨源探测没有 CORS 头会被浏览器拦)。
34
+ * 端口上**第一条请求通常是探测而不是回调**,凭「是否带凭据标记」区分两者。
35
+ * 3. 带 `error=` 的也是真回调(拒绝回调),先于「无凭据=探测」判定,否则拒绝会被误当探测、
36
+ * 用户白等到超时。
37
+ *
38
+ * 与「本机导入」的关系:OAuth 登录拿到的是**独立的一条凭据链**(含 refreshToken,导入线没有),
39
+ * 不读写 Trae 客户端的 storage.json,互不作废。
40
+ */
41
+
42
+ import crypto from 'node:crypto';
43
+ import http from 'node:http';
44
+ import os from 'node:os';
45
+ import { FETCH_TIMEOUT_MS } from './constants.js';
46
+
47
+ /** 授权页域:国内站 www.trae.cn / 国际站 www.trae.ai(#99:两站同协议同 client_id,
48
+ * 账号不互通——站点由 GetLoginGuidance 返回的 LoginHost 权威决定)。 */
49
+ const CONSOLE_BASE_CN = 'https://www.trae.cn';
50
+ const CONSOLE_BASE_INTL = 'https://www.trae.ai';
51
+ const CLIENT_ID = 'ono9krqynydwx5';
52
+ const AUTH_FROM = 'trae';
53
+ /** 版本指纹常量:CN 来自真机客户端登录 URL 实抓样本(3.4.9 / 插件 2.3.97430);
54
+ * 国际版按 10R 口径(product.json 实测 3.6.4),上游更新后在此换。 */
55
+ const PLUGIN_VERSION = '2.3.97430';
56
+ const APP_VERSION_CN = '3.4.9';
57
+ const APP_VERSION_INTL = '3.6.4';
58
+ const APP_TYPE = 'stable';
59
+ /** 换票主机白名单(hostname 级):host 参数来自回调查询串(浏览器可控),拦 SSRF。
60
+ * CN 族 = api.trae.cn 系;国际族 = grow-normal 系(AuthCode v3 换票主机,10R #99 实测
61
+ * grow-normal.trae.ai / growsg-normal.trae.ai / USTTP 账号面 grow-normal.traeapi.us)
62
+ * + 老族兜底。回环放行是给本仓联调 / 测试用的。 */
63
+ const EXCHANGE_HOST_ALLOW_CN = ['api.trae.cn', 'api.trae.com.cn', 'api.marscode.cn', 'www.trae.cn'];
64
+ const EXCHANGE_HOST_ALLOW_INTL = ['grow-normal.trae.ai', 'growsg-normal.trae.ai', 'grow-normal.traeapi.us', 'api.trae.ai', 'api.marscode.com', 'www.trae.ai'];
65
+ const LOOPBACK_HOSTS = ['127.0.0.1', 'localhost', '::1', '[::1]'];
66
+ /** 换票回落主机:回调没带 host(上游版本差异)时用。CN 真机实测打 api.trae.cn;
67
+ * 国际按 10R authCodeOrigins 顺序(growsg 优先,USTTP 账号面 traeapi.us 兜底)。 */
68
+ const EXCHANGE_HOST_FALLBACK_CN = 'https://api.trae.cn';
69
+ const EXCHANGE_HOST_FALLBACK_INTL = 'https://growsg-normal.trae.ai';
70
+ /** 回调端口候选:真机 3.4.9 客户端用 3379;workbuddy 钉旧版观察到 17388。 */
71
+ const CALLBACK_PORTS = [3379, 17388];
72
+ const LOGIN_TIMEOUT_MS = 5 * 60_000;
73
+
74
+ /** 单次登录会话状态(进程内;sessionId 只在 start/poll 之间传递)。 */
75
+ const sessions = new Map();
76
+
77
+ function gcSessions() {
78
+ const now = Date.now();
79
+ for (const [k, s] of sessions) {
80
+ if (s.deadline < now) {
81
+ try { s.server.close(); } catch {}
82
+ sessions.delete(k);
83
+ }
84
+ }
85
+ }
86
+
87
+ /** 16 位纯数字设备号(首位 1-9;签到风控要求 x-device-id 是 16 位数字,traeLocal 同款约束)。 */
88
+ export function newDeviceId() {
89
+ const buf = crypto.randomBytes(16);
90
+ let out = String(1 + (buf[0] % 9));
91
+ for (let i = 1; i < 16; i++) out += String(buf[i] % 10);
92
+ return out;
93
+ }
94
+
95
+ /** EC P-256 设备密钥对(与客户端同款曲线)。公钥走 SPKI PEM 进 DeviceInfo;私钥 JWK 落 meta 供刷新链用。 */
96
+ export function newDeviceIdentity() {
97
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
98
+ return {
99
+ deviceId: newDeviceId(),
100
+ machineId: crypto.randomUUID(),
101
+ publicKeyPem: publicKey.export({ type: 'spki', format: 'pem' }),
102
+ privateKeyJwk: privateKey.export({ format: 'jwk' }),
103
+ };
104
+ }
105
+
106
+ function osProfile() {
107
+ const osName = os.type().replace(/_/g, ' ') || 'Windows';
108
+ return {
109
+ osName,
110
+ osVersion: os.release() || '',
111
+ deviceModel: `${os.platform()} ${os.arch()}`,
112
+ deviceBrand: osName,
113
+ deviceName: process.env.USERNAME || process.env.USER || os.hostname() || 'PC',
114
+ cpu: os.cpus()[0]?.model?.trim() || '',
115
+ };
116
+ }
117
+
118
+ /** 站点上下文:由 kind 归一('trae'=CN / 'trae-intl'=国际),集中全部按站点分叉的常量。 */
119
+ function siteContext(kind) {
120
+ return { intl: kind === 'trae-intl' };
121
+ }
122
+
123
+ /** 站点权威判定:LoginHost / 回调 host 反推(10R traeRegionFromHost 同款后缀表)。 */
124
+ function isIntlHost(host) {
125
+ const h = String(host || '').trim().toLowerCase().replace(/^https?:\/\//, '').split('/')[0];
126
+ if (!h) return null;
127
+ if (/(^|\.)trae\.cn$|(^|\.)trae\.com\.cn$|(^|\.)marscode\.cn$/.test(h)) return false;
128
+ if (/(^|\.)trae\.ai$|(^|\.)marscode\.com$|(^|\.)traeapi\.us$/.test(h)) return true;
129
+ return null;
130
+ }
131
+
132
+ /** 拼内层授权 URL(22 参数,顺序与真机客户端抓包逐字一致——不要按语义重排)。 */
133
+ export function buildAuthorizeUrl({ port, traceId, challenge, identity, intl = false }) {
134
+ const system = osProfile();
135
+ const callback = `http://127.0.0.1:${port}/authorize`;
136
+ const enc = encodeURIComponent;
137
+ const appVersion = intl ? APP_VERSION_INTL : APP_VERSION_CN;
138
+ const consoleBase = intl ? CONSOLE_BASE_INTL : CONSOLE_BASE_CN;
139
+ const inner = `${consoleBase}/authorization`
140
+ + `?login_version=1`
141
+ + `&auth_from=${AUTH_FROM}`
142
+ + `&login_channel=native_ide`
143
+ + `&plugin_version=${PLUGIN_VERSION}`
144
+ + `&auth_type=local`
145
+ + `&client_id=${CLIENT_ID}`
146
+ + `&redirect=0`
147
+ + `&login_trace_id=${traceId}`
148
+ + `&auth_callback_url=${enc(callback)}`
149
+ + `&machine_id=${identity.machineId}`
150
+ + `&device_id=${identity.deviceId}`
151
+ + `&x_device_id=${identity.deviceId}`
152
+ + `&x_machine_id=${identity.machineId}`
153
+ + `&x_device_brand=${enc(system.deviceModel)}`
154
+ + `&x_device_type=${enc(process.platform)}`
155
+ + `&x_os_version=${enc(system.osVersion)}`
156
+ + `&x_env=`
157
+ + `&x_app_version=${appVersion}`
158
+ + `&x_app_type=${APP_TYPE}`
159
+ + `&code_challenge=${challenge}`
160
+ + `&code_challenge_method=S256`
161
+ + `&channel_name=common`;
162
+ // 外层包装与真机客户端一致(/login?login_platform=trae&redirect_url=<内层>)
163
+ return `${consoleBase}/login?login_platform=trae&redirect_url=${enc(inner)}`;
164
+ }
165
+
166
+ /** 回调查询解析:先剥到 ? 后(req.url 带着路径前缀)、按 & 切 → 整体反复解码(浏览器/页面
167
+ * 可能二次编码)→ 第一个 = 切键值。JWT / refresh_token 的值里合法含 =(base64url 填充),
168
+ * 必须 split_once 而非按全部 = 切。 */
169
+ export function parseCallbackQuery(rawQuery) {
170
+ const out = {};
171
+ const raw = String(rawQuery || '');
172
+ const qi = raw.indexOf('?');
173
+ const qs = qi === -1 ? raw : raw.slice(qi + 1);
174
+ for (const pair of qs.split('&')) {
175
+ if (!pair) continue;
176
+ let decoded = pair;
177
+ for (let i = 0; i < 3; i++) {
178
+ const next = decoded.includes('%') ? decodeURIComponentSafe(decoded) : decoded;
179
+ if (next === decoded) break;
180
+ decoded = next;
181
+ }
182
+ const eq = decoded.indexOf('=');
183
+ if (eq === -1) out[decoded] = '';
184
+ else out[decoded.slice(0, eq)] = decoded.slice(eq + 1);
185
+ }
186
+ return out;
187
+ }
188
+
189
+ function decodeURIComponentSafe(s) {
190
+ try { return decodeURIComponent(s); } catch { return s; }
191
+ }
192
+
193
+ function jsonStringField(obj, keys) {
194
+ for (const k of keys) {
195
+ const v = obj?.[k];
196
+ if (typeof v === 'string' && v.trim()) return v.trim();
197
+ }
198
+ return null;
199
+ }
200
+
201
+ function jsonIntField(obj, keys) {
202
+ for (const k of keys) {
203
+ const v = Number(obj?.[k]);
204
+ if (Number.isFinite(v) && v > 0) return v;
205
+ }
206
+ return 0;
207
+ }
208
+
209
+ /** 解析回调参数 → {authCode, userInfo, host, region, intl, traceId, error}(muskke parseCallback 同款容错)。 */
210
+ export function parseCallbackParams(params) {
211
+ const raw = params.authCodeInfo || params.auth_code_info || params.AuthCodeInfo || '';
212
+ let authCode = jsonStringField(params, ['authCode', 'auth_code', 'AuthCode', 'authorization_code', 'code']);
213
+ let codeExpireAt = 0;
214
+ if (raw) {
215
+ let info = null;
216
+ try { info = JSON.parse(raw); } catch { /* 不是合法 JSON——按缺 AuthCode 走 */ }
217
+ authCode = authCode || jsonStringField(info, ['AuthCode', 'authCode', 'auth_code', 'code']);
218
+ codeExpireAt = jsonIntField(info, ['ExpireAt', 'expireAt', 'expiresAt']);
219
+ }
220
+ let user = null;
221
+ try { user = params.userInfo ? JSON.parse(params.userInfo) : null; } catch {}
222
+ const host = jsonStringField(params, ['host', 'apiHost', 'APIHost']);
223
+ const region = (jsonStringField(params, ['userRegion', 'user_region', 'LoginRegion', 'loginRegion']) || '').toLowerCase();
224
+ return {
225
+ authCode,
226
+ codeExpireAt,
227
+ // 旧契约兜底:部分版本直接在回调里带 token(muskke 同款容错)
228
+ directAccessToken: jsonStringField(params, ['accessToken', 'access_token', 'token']),
229
+ directRefreshToken: jsonStringField(params, ['refreshToken', 'refresh_token', 'RefreshToken']),
230
+ uid: user ? jsonStringField(user, ['UserID', 'userId', 'uid']) : null,
231
+ name: user ? jsonStringField(user, ['ScreenName', 'screenName', 'nickname']) : null,
232
+ host,
233
+ region,
234
+ // 站点权威判定:回调 host 反推(LoginHost 由 GetLoginGuidance 下发并跟 authorize 全程)
235
+ intl: isIntlHost(host),
236
+ traceId: jsonStringField(params, ['loginTraceID', 'loginTraceId', 'login_trace_id']),
237
+ error: jsonStringField(params, ['error', 'error_description']),
238
+ };
239
+ }
240
+
241
+ /** 换票主机白名单校验(hostname 级;按站点族放行,跨族一律回落本族 fallback——拦 SSRF
242
+ * 也拦「国内回调拿去国际端点换票」这类站错队)。回环放行给联调 / 测试。 */
243
+ export function resolveExchangeHost(host, { intl = false } = {}) {
244
+ const raw = String(host || '').trim().replace(/\/+$/, '');
245
+ const name = raw.split('://').pop()?.split('/')[0]?.split(':')[0]?.toLowerCase() || '';
246
+ const allow = intl ? EXCHANGE_HOST_ALLOW_INTL : EXCHANGE_HOST_ALLOW_CN;
247
+ const fallback = intl ? EXCHANGE_HOST_FALLBACK_INTL : EXCHANGE_HOST_FALLBACK_CN;
248
+ if (!name) return { host: fallback, usedFallback: 'missing' };
249
+ if (LOOPBACK_HOSTS.includes(name)) return { host: raw, usedFallback: null };
250
+ if (allow.includes(name)) return { host: raw.startsWith('http') ? raw : `https://${raw}`, usedFallback: null };
251
+ return { host: fallback, usedFallback: 'rejected' };
252
+ }
253
+
254
+ function deviceInfoPayload(identity, appVersion) {
255
+ const system = osProfile();
256
+ return {
257
+ DeviceID: identity.deviceId,
258
+ MachineID: identity.machineId,
259
+ PlatformCode: 'IDE_PC',
260
+ DeviceType: 'PC',
261
+ DeviceName: system.deviceName,
262
+ DeviceModel: system.deviceModel,
263
+ ClientVersion: appVersion,
264
+ DevicePublicKey: identity.publicKeyPem,
265
+ DeviceBrand: system.deviceBrand,
266
+ DeviceCPU: system.cpu,
267
+ OSInfo: system.osName,
268
+ OSVersion: system.osVersion,
269
+ };
270
+ }
271
+
272
+ /** 响应字段容错:v3 端点的真机契约是**嵌套 Result.***(10Router #99 换票对照实验:
273
+ * Result.Token / Result.RefreshToken / Result.RefreshExpireAt 毫秒)——HTTP 200 却按
274
+ * 扁平字段读会解析成「无 token」,误判失败降级旧端点吃 10101(2026-11-11 用户实测:
275
+ * 授权页成功、面板报 ExchangeToken/DeviceInfo: HTTP 200)。扁平形态保留兜底
276
+ * (更老的回调/端点形态,muskke TokenData 同款)。 */
277
+ function pickToken(body) {
278
+ const nested = (body?.Result && typeof body.Result === 'object') ? body.Result
279
+ : (body?.result && typeof body.result === 'object') ? body.result
280
+ : (body?.data && typeof body.data === 'object') ? body.data
281
+ : {};
282
+ return {
283
+ accessToken: jsonStringField(body, ['accessToken', 'access_token'])
284
+ || jsonStringField(nested, ['AccessToken', 'Token', 'accessToken', 'token']),
285
+ refreshToken: jsonStringField(body, ['refreshToken', 'refresh_token', 'RefreshToken'])
286
+ || jsonStringField(nested, ['RefreshToken', 'refreshToken', 'refresh_token']),
287
+ // RefreshExpireAt(毫秒)优先——v3 契约的 refresh 寿命字段;ExpiresAt 系兜底
288
+ expiresAtMs: jsonIntField(nested, ['RefreshExpireAt', 'ExpiresAt', 'expiresAt', 'expire_at'])
289
+ || jsonIntField(body, ['expiresAt', 'expires_at', 'ExpireAt', 'expireAt']),
290
+ expiresInSec: jsonIntField(body, ['expiresIn', 'expires_in'])
291
+ || jsonIntField(nested, ['ExpiresIn', 'expiresIn']),
292
+ };
293
+ }
294
+
295
+ async function postJson(url, payload, extraHeaders = {}) {
296
+ const res = await fetch(url, {
297
+ method: 'POST',
298
+ headers: {
299
+ 'Content-Type': 'application/json',
300
+ Accept: 'application/json',
301
+ // 客户端原样带着的空 token 头(workbuddy 抓包:缺失会被上游当非客户端流量)
302
+ 'x-cloudide-token': '',
303
+ 'X-App-Id': '6eefa01c-1036-4c7e-9ca5-d891f63bfcd8',
304
+ 'x-plugin-channel': 'icube-ai',
305
+ ...extraHeaders,
306
+ },
307
+ body: JSON.stringify(payload),
308
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
309
+ });
310
+ const text = await res.text().catch(() => '');
311
+ let body = null;
312
+ try { body = text ? JSON.parse(text) : null; } catch {}
313
+ return { res, body, text };
314
+ }
315
+
316
+ /** AuthCode 换 token:CN 真机验证的三段降级(新端点带 DeviceInfo → 旧端点扁平体 AuthCode/Code);
317
+ * 国际线保持 10R 实测的单段 v3(grow-normal 族未观察到需要降级,#99 全链验证)。 */
318
+ export async function exchangeAuthCode({ host, authCode, codeVerifier, identity, intl = false }) {
319
+ const appVersion = intl ? APP_VERSION_INTL : APP_VERSION_CN;
320
+ const attempts = intl
321
+ ? [
322
+ {
323
+ tag: 'ExchangeToken/DeviceInfo',
324
+ url: `${host}/trae/api/v3/oauth/ExchangeToken`,
325
+ payload: {
326
+ ClientID: CLIENT_ID,
327
+ AuthCode: authCode,
328
+ CodeVerifier: codeVerifier,
329
+ DeviceInfo: deviceInfoPayload(identity, appVersion),
330
+ IDEVersion: appVersion,
331
+ },
332
+ },
333
+ ]
334
+ : [
335
+ {
336
+ tag: 'ExchangeToken/DeviceInfo',
337
+ url: `${host}/trae/api/v3/oauth/ExchangeToken`,
338
+ payload: {
339
+ ClientID: CLIENT_ID,
340
+ AuthCode: authCode,
341
+ CodeVerifier: codeVerifier,
342
+ DeviceInfo: deviceInfoPayload(identity, appVersion),
343
+ IDEVersion: appVersion,
344
+ },
345
+ },
346
+ {
347
+ tag: 'ExchangeToken/AuthCode',
348
+ url: `${host}/cloudide/api/v3/trae/oauth/ExchangeToken`,
349
+ payload: { ClientID: CLIENT_ID, AuthCode: authCode, CodeVerifier: codeVerifier, DeviceID: identity.deviceId, PlatformCode: 'IDE_PC' },
350
+ },
351
+ {
352
+ tag: 'ExchangeToken/Code',
353
+ url: `${host}/cloudide/api/v3/trae/oauth/ExchangeToken`,
354
+ payload: { ClientID: CLIENT_ID, Code: authCode, CodeVerifier: codeVerifier, DeviceID: identity.deviceId, PlatformCode: 'IDE_PC' },
355
+ },
356
+ ];
357
+ const errors = [];
358
+ for (const a of attempts) {
359
+ let r;
360
+ try {
361
+ r = await postJson(a.url, a.payload);
362
+ } catch (e) {
363
+ errors.push(`${a.tag}: ${e.cause?.code || e.message}`);
364
+ continue;
365
+ }
366
+ const t = pickToken(r.body);
367
+ if (r.res.ok && t.accessToken) return { ...t, via: a.tag };
368
+ const msg = r.body?.message || r.body?.error || r.body?.msg || (r.text ? r.text.slice(0, 160) : '');
369
+ errors.push(`${a.tag}: HTTP ${r.res.status}${msg ? ' ' + msg : ''}`);
370
+ }
371
+ throw new Error('Trae 换票失败:' + errors.join(' | '));
372
+ }
373
+
374
+ /** 回调监听:只绑 127.0.0.1;探测回 200+CORS,凭据回调进会话后立刻收摊。 */
375
+ function startCallbackServer(session) {
376
+ const server = http.createServer((req, res) => {
377
+ const cors = {
378
+ 'Access-Control-Allow-Origin': '*',
379
+ 'Access-Control-Allow-Methods': 'GET, OPTIONS',
380
+ 'Access-Control-Allow-Headers': '*',
381
+ };
382
+ if (req.method === 'OPTIONS') {
383
+ res.writeHead(204, cors);
384
+ res.end();
385
+ return;
386
+ }
387
+ const params = parseCallbackQuery(req.url || '');
388
+ const hasCredential = ['authCodeInfo', 'code', 'AuthCode', 'accessToken', 'refreshToken', 'userJwt'].some((k) => params[k]);
389
+ if (session.error || session.result) {
390
+ // 已收摊的迟到请求(探测重复触发等):只应答不处理
391
+ res.writeHead(200, { ...cors, 'Content-Type': 'text/plain' });
392
+ res.end('ok');
393
+ return;
394
+ }
395
+ if (!hasCredential) {
396
+ if (params.error) {
397
+ // 拒绝回调也是真回调:必须先于「无凭据=探测」判定,否则用户白等到超时
398
+ session.error = `授权被拒绝或失败(${params.error})`;
399
+ finish(session);
400
+ }
401
+ // 在线探测:200 + CORS,响应体不含任何凭据
402
+ res.writeHead(200, { ...cors, 'Content-Type': 'text/plain' });
403
+ res.end('ok');
404
+ return;
405
+ }
406
+ session.result = params;
407
+ finish(session);
408
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
409
+ res.end('<!doctype html><meta charset="utf-8"><title>Trae 登录</title>'
410
+ + '<body style="font-family:system-ui;display:grid;place-items:center;height:100vh;margin:0">'
411
+ + '<div style="text-align:center"><div style="font-size:42px">✅</div>'
412
+ + '<p>授权成功,回到 CreditDaddy 面板即可(此页可以关掉)。</p></div></body>');
413
+ });
414
+ return server;
415
+ }
416
+
417
+ function finish(session) {
418
+ session.settledAt = Date.now();
419
+ // 拿到终态立即释放端口;稍等一拍再 close,给响应体留出发送时间
420
+ setTimeout(() => {
421
+ try { session.server.close(); } catch {}
422
+ }, 500).unref();
423
+ }
424
+
425
+ async function bindCallbackServer(session, ports) {
426
+ const errors = [];
427
+ for (const port of ports) {
428
+ try {
429
+ await new Promise((resolve, reject) => {
430
+ const onErr = (e) => { server.off('listening', onOk); reject(e); };
431
+ const onOk = () => { server.off('error', onErr); resolve(); };
432
+ const server = session.server;
433
+ server.once('error', onErr);
434
+ server.once('listening', onOk);
435
+ server.listen(port, '127.0.0.1');
436
+ });
437
+ return port;
438
+ } catch (e) {
439
+ errors.push(`${port}: ${e.code || e.message}`);
440
+ }
441
+ }
442
+ throw new Error(`Trae 回调端口都被占用(${errors.join(';')})——请关掉占用 3379/17388 的程序(可能是正在登录的 Trae 客户端)后重试`);
443
+ }
444
+
445
+ /** 发起一次浏览器授权登录。kind:'trae'(国内站)/ 'trae-intl'(国际站,10R #99 同协议)。
446
+ * 授权 URL 直接用本站 console 域(与真机客户端一致——客户端不打 GetLoginGuidance 拿
447
+ * 授权域,回调里的换票 host 由授权页下发,按站点白名单放行)。 */
448
+ export async function startTraeLogin(kind, { ports = CALLBACK_PORTS } = {}) {
449
+ const site = siteContext(kind === 'trae-intl' ? 'trae-intl' : 'trae');
450
+ gcSessions();
451
+ const identity = newDeviceIdentity();
452
+ const verifier = crypto.randomBytes(48).toString('base64url');
453
+ const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
454
+ const traceId = crypto.randomUUID();
455
+ const session = {
456
+ identity, verifier, traceId,
457
+ intl: site.intl,
458
+ result: null, error: null, settledAt: 0,
459
+ deadline: Date.now() + LOGIN_TIMEOUT_MS,
460
+ };
461
+ session.server = startCallbackServer(session);
462
+ const port = await bindCallbackServer(session, ports);
463
+ session.port = port;
464
+ const loginId = crypto.randomUUID();
465
+ sessions.set(loginId, session);
466
+ const url = buildAuthorizeUrl({ port, traceId, challenge, identity, intl: site.intl });
467
+ return {
468
+ url,
469
+ expiresInMs: LOGIN_TIMEOUT_MS,
470
+ intervalMs: 1500,
471
+ data: { loginId },
472
+ };
473
+ }
474
+
475
+ /**
476
+ * 轮询登录结果(authDevice 骨架约定):
477
+ * {status:'pending'} | {status:'ok', input} ;终态失败抛错。
478
+ * 成功后回调服务器与本地会话状态一并清理;authDevice 侧的 300s 会话过期自己兜底。
479
+ */
480
+ export async function pollTraeLogin(data) {
481
+ const session = sessions.get(data?.loginId);
482
+ if (!session) throw new Error('Trae 登录会话不存在或已超时,请重新发起');
483
+ if (session.error) {
484
+ sessions.delete(data.loginId);
485
+ throw new Error(session.error);
486
+ }
487
+ if (!session.result) {
488
+ if (Date.now() > session.deadline) {
489
+ sessions.delete(data.loginId);
490
+ try { session.server.close(); } catch {}
491
+ throw new Error('Trae 授权超时(5 分钟未完成),请重新发起');
492
+ }
493
+ return { status: 'pending' };
494
+ }
495
+
496
+ const params = session.result;
497
+ sessions.delete(data.loginId);
498
+ const info = parseCallbackParams(params);
499
+ if (info.error) throw new Error(`授权被拒绝:${info.error}`);
500
+ if (info.traceId && info.traceId !== session.traceId) {
501
+ throw new Error('回调 loginTraceID 与本次登录不匹配(CSRF 防护),请重新发起');
502
+ }
503
+ if (info.codeExpireAt) {
504
+ const expMs = info.codeExpireAt < 1e12 ? info.codeExpireAt * 1000 : info.codeExpireAt;
505
+ if (expMs <= Date.now()) throw new Error('回调里的 AuthCode 已过期,请重新发起');
506
+ }
507
+
508
+ // 旧契约直接带 token 的版本:跳过换票
509
+ if (info.directAccessToken && !info.authCode) {
510
+ const intlDirect = info.intl !== null ? info.intl : Boolean(session.intl);
511
+ return buildLoginResult({
512
+ accessToken: info.directAccessToken,
513
+ refreshToken: info.directRefreshToken,
514
+ identity: session.identity,
515
+ host: info.host,
516
+ region: info.region,
517
+ intl: intlDirect,
518
+ uid: info.uid,
519
+ name: info.name,
520
+ expiresAtMs: 0,
521
+ });
522
+ }
523
+ if (!info.authCode) throw new Error('回调里没有 AuthCode(授权页协议可能又变了),请重新发起或更新 CreditDaddy');
524
+
525
+ // 站点裁决:回调 host 反推 → 缺失/判不出时用本次登录的发起站点(startTraeLogin 定)
526
+ const intl = info.intl !== null ? info.intl : Boolean(session.intl);
527
+ const resolved = resolveExchangeHost(info.host, { intl });
528
+ const t = await exchangeAuthCode({ host: resolved.host, authCode: info.authCode, codeVerifier: session.verifier, identity: session.identity, intl });
529
+ return buildLoginResult({
530
+ accessToken: t.accessToken,
531
+ refreshToken: t.refreshToken,
532
+ identity: session.identity,
533
+ host: info.host || resolved.host,
534
+ region: info.region,
535
+ intl,
536
+ uid: info.uid,
537
+ name: info.name,
538
+ expiresAtMs: t.expiresAtMs,
539
+ expiresInSec: t.expiresInSec,
540
+ exchangeFallback: resolved.usedFallback,
541
+ });
542
+ }
543
+
544
+ function uidFromJwt(jwt) {
545
+ try {
546
+ const payload = JSON.parse(Buffer.from(jwt.split('.')[1], 'base64url').toString('utf8'));
547
+ return { uid: payload?.data?.id ? String(payload.data.id) : null, exp: Number(payload?.exp) || 0 };
548
+ } catch { return { uid: null, exp: 0 }; }
549
+ }
550
+
551
+ function buildLoginResult({ accessToken, refreshToken, identity, host, region, intl = false, uid, name, expiresAtMs, expiresInSec = 0, exchangeFallback }) {
552
+ const jwt = uidFromJwt(accessToken);
553
+ const finalUid = uid || jwt.uid || null;
554
+ let expiresAt = null;
555
+ if (expiresAtMs) expiresAt = new Date(expiresAtMs < 1e12 ? expiresAtMs * 1000 : expiresAtMs).toISOString();
556
+ else if (expiresInSec) expiresAt = new Date(Date.now() + expiresInSec * 1000).toISOString();
557
+ else if (jwt.exp) expiresAt = new Date(jwt.exp * 1000).toISOString();
558
+
559
+ const device = {
560
+ deviceId: identity.deviceId,
561
+ machineId: identity.machineId,
562
+ publicKeyPem: identity.publicKeyPem,
563
+ privateKeyJwk: identity.privateKeyJwk,
564
+ };
565
+ return {
566
+ status: 'ok',
567
+ input: {
568
+ provider: 'trae',
569
+ token: accessToken,
570
+ refreshToken: refreshToken || null,
571
+ expiresAt,
572
+ uid: finalUid,
573
+ name: name || (finalUid ? `Trae_${String(finalUid).slice(-6)}` : null),
574
+ email: null,
575
+ source: 'browser',
576
+ meta: {
577
+ loginVia: 'oauth-authcode',
578
+ traeDevice: device,
579
+ traeHost: host || null,
580
+ traeRegion: region || null,
581
+ // 国际账号标记(切客户端选 exe / 10R 推送护栏 / 签到额度跳过口径都读它)
582
+ ...(intl ? { isIntl: true } : {}),
583
+ traeExchangeFallback: exchangeFallback || undefined,
584
+ clientVersion: intl ? APP_VERSION_INTL : APP_VERSION_CN,
585
+ pluginVersion: PLUGIN_VERSION,
586
+ capturedAt: new Date().toISOString(),
587
+ },
588
+ },
589
+ };
590
+ }
591
+
592
+ /** 测试辅助:清空进程内会话(含关闭监听与 keep-alive 连接)。 */
593
+ export function _resetForTests() {
594
+ for (const [, s] of sessions) {
595
+ try { s.server.closeAllConnections?.(); } catch {}
596
+ try { s.server.close(); } catch {}
597
+ }
598
+ sessions.clear();
599
+ }
package/src/traeClient.js CHANGED
@@ -102,8 +102,30 @@ export function traeDevice(uid, storedDeviceId, attempt = 0) {
102
102
  };
103
103
  }
104
104
 
105
- function traeHeaders(jwt, dev) {
105
+ function traeHeaders(jwt, dev, intl = false) {
106
106
  const token = jwt.startsWith('Cloud-IDE-JWT ') ? jwt : `Cloud-IDE-JWT ${jwt.trim()}`;
107
+ if (intl) {
108
+ // 国际版(trae.ai / grow-normal 族,10R SOLO intl 网关口径):区域与包型跟着站点走
109
+ return {
110
+ accept: '*/*',
111
+ 'accept-language': 'en-US',
112
+ authorization: token,
113
+ 'content-type': 'application/json',
114
+ 'user-agent': 'VSCode 1.107.1 (TRAE SOLO INTL)',
115
+ 'x-market-client-id': 'VSCode 1.107.1',
116
+ 'x-market-user-id': dev.marketUserId,
117
+ 'x-user-region': 'SG',
118
+ 'x-device-id': dev.deviceId,
119
+ 'x-lgw-req-sdk-type': '3',
120
+ 'package-type': 'stable',
121
+ 'x-request-id': hex(16),
122
+ 'x-lscbd-aid': '787976',
123
+ 'x-lscbd-platform': process.platform === 'win32' ? 'windows' : process.platform,
124
+ 'app-version': '0.1.45',
125
+ 'x-tt-trace-id': `00-${hex(8)}-01`,
126
+ 'vscode-sessionid': dev.sessionId,
127
+ };
128
+ }
107
129
  return {
108
130
  accept: '*/*',
109
131
  'accept-language': 'zh-CN',
@@ -142,10 +164,11 @@ async function post(url, account, body = {}, attempt = 0, storedDeviceId) {
142
164
  const jwt = account.token;
143
165
  if (!jwt) throw new Error('账号缺少 Trae 登录 token(请到 Trae 客户端登录后用「本机导入」同步)');
144
166
  const uid = account.uid || uidFromJwt(jwt);
167
+ const intl = account.provider === 'trae-intl' || Boolean(account.meta?.isIntl);
145
168
  const dev = traeDevice(uid || 'anonymous', storedDeviceId !== undefined ? storedDeviceId : account.meta?.deviceId, attempt);
146
169
  const res = await fetchJsonRace(url, {
147
170
  method: 'POST',
148
- headers: traeHeaders(jwt, dev),
171
+ headers: traeHeaders(jwt, dev, intl),
149
172
  body: JSON.stringify(body),
150
173
  timeoutMs: FETCH_TIMEOUT_MS,
151
174
  });