creditdaddy 1.7.0 → 1.7.1

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.
@@ -21,6 +21,9 @@ export const TENROUTER_PROVIDER_MAP = {
21
21
  'qoder-cn': 'qoder-cn',
22
22
  workbuddy: 'codebuddy-cn',
23
23
  'workbuddy-intl': 'codebuddy-intl',
24
+ minimax: 'minimax-code', // #55:MiniMax 国内订阅线 → 10R minimax-code
25
+ 'minimax-global': 'minimax-code-global', // #55:MiniMax 国际订阅线 → 10R minimax-code-global
26
+ trae: 'trae-cn', // #56:CD 的 Trae 线读国内客户端(#28)→ 10R trae-cn(条目钉死国内站)
24
27
  tokenharbor: 'tokenharbor-free', // #23:会话 cookie 只喂「额度监控卡」(freeTier,不走路由);tokenharbor 钱包卡留给 sk- 运输 key
25
28
  loomy: 'loomy',
26
29
  // zcode → glm:等 zcode 反代就绪后补一行(同步流程已就绪,无需改代码)
@@ -149,8 +152,15 @@ export async function syncAccountsTo10r({ endpoint, key, adminPassword, accounts
149
152
  // 按目标 10R 连接类型分组;无映射的产品(zcode/mirasim/catpaw 等)记入跳过原因
150
153
  const groups = new Map();
151
154
  const unmapped = new Map();
155
+ const traeIntl = [];
152
156
  for (const a of accounts || []) {
153
157
  if (!a || !a.token) continue;
158
+ // #56:CD 的 Trae 线只支持国内站(traeLocal 对国际版客户端的导入本来就只挂警告)。
159
+ // 国际版账号不往 trae-cn 里推——10R 拿国内端点打国际 token 必然 20101,宁可明说跳过。
160
+ if (a.provider === 'trae' && (a.meta?.isIntl || a.isIntl)) {
161
+ traeIntl.push(a);
162
+ continue;
163
+ }
154
164
  const target = mapProviderId(a.provider);
155
165
  if (!target) {
156
166
  if (a.provider) unmapped.set(a.provider, (unmapped.get(a.provider) || 0) + 1);
@@ -159,7 +169,7 @@ export async function syncAccountsTo10r({ endpoint, key, adminPassword, accounts
159
169
  if (!groups.has(target)) groups.set(target, []);
160
170
  groups.get(target).push(a);
161
171
  }
162
- if (!groups.size) throw new Error('没有可同步的账号(qoder / WorkBuddy 系列支持;zcode 待反代就绪后支持)');
172
+ if (!groups.size) throw new Error('没有可同步的账号(qoder / WorkBuddy / MiniMax / Loomy / Trae 系列);zcode 待反代就绪后支持');
163
173
 
164
174
  let channel = 'apikey';
165
175
  let cookie = null;
@@ -185,6 +195,7 @@ export async function syncAccountsTo10r({ endpoint, key, adminPassword, accounts
185
195
  if (sum('skipped')) parts.push(`已存在 ${sum('skipped')}`);
186
196
  if (sum('failed')) parts.push(`失败 ${sum('failed')}`);
187
197
  if (unmapped.size) parts.push('跳过 ' + [...unmapped].map(([p, n]) => `${p} ×${n}`).join('、'));
198
+ if (traeIntl.length) parts.push(`跳过 Trae 国际版 ×${traeIntl.length}(CreditDaddy 的 Trae 线仅支持国内站)`);
188
199
  // issue #44:Qoder 网页会话决定 10Router 端「套餐内 Credits」能不能显示。
189
200
  // OAuth 通道:10Router 导入时已逐账号探测,失效清单原样带回(deadNames);
190
201
  // 两条通道都要点名本地就没有会话的账号(apikey 通道 webSessions 恒为
@@ -0,0 +1,530 @@
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
+ /** 授权页域(国内站)。国际站是另一套域 + 另一把 client_id,等接国际线时再开。 */
48
+ const CONSOLE_BASE_CN = 'https://www.trae.cn';
49
+ const CLIENT_ID_CN = 'ono9krqynydwx5';
50
+ const AUTH_FROM = 'trae';
51
+ /** 版本指纹常量:来自真机客户端登录 URL 实抓样本(3.4.9 / 插件 2.3.97430),上游更新后在此换。 */
52
+ const PLUGIN_VERSION = '2.3.97430';
53
+ const APP_VERSION = '3.4.9';
54
+ const APP_TYPE = 'stable';
55
+ /** 换票主机白名单(CN 族,hostname 级):host 参数来自回调查询串(浏览器可控),拦 SSRF。
56
+ * 回环放行是给本仓联调 / 测试用的——真正要挡的是把 AuthCode+verifier 发去不相干的外部地址。 */
57
+ const EXCHANGE_HOST_ALLOW = ['api.trae.cn', 'api.trae.com.cn', 'api.marscode.cn', 'www.trae.cn'];
58
+ const LOOPBACK_HOSTS = ['127.0.0.1', 'localhost', '::1', '[::1]'];
59
+ /** 换票回落主机:回调没带 host(上游版本差异)时用。真机实测打 api.trae.cn。 */
60
+ const EXCHANGE_HOST_FALLBACK = 'https://api.trae.cn';
61
+ /** 回调端口候选:真机 3.4.9 客户端用 3379;workbuddy 钉旧版观察到 17388。 */
62
+ const CALLBACK_PORTS = [3379, 17388];
63
+ const LOGIN_TIMEOUT_MS = 5 * 60_000;
64
+
65
+ /** 单次登录会话状态(进程内;sessionId 只在 start/poll 之间传递)。 */
66
+ const sessions = new Map();
67
+
68
+ function gcSessions() {
69
+ const now = Date.now();
70
+ for (const [k, s] of sessions) {
71
+ if (s.deadline < now) {
72
+ try { s.server.close(); } catch {}
73
+ sessions.delete(k);
74
+ }
75
+ }
76
+ }
77
+
78
+ /** 16 位纯数字设备号(首位 1-9;签到风控要求 x-device-id 是 16 位数字,traeLocal 同款约束)。 */
79
+ export function newDeviceId() {
80
+ const buf = crypto.randomBytes(16);
81
+ let out = String(1 + (buf[0] % 9));
82
+ for (let i = 1; i < 16; i++) out += String(buf[i] % 10);
83
+ return out;
84
+ }
85
+
86
+ /** EC P-256 设备密钥对(与客户端同款曲线)。公钥走 SPKI PEM 进 DeviceInfo;私钥 JWK 落 meta 供刷新链用。 */
87
+ export function newDeviceIdentity() {
88
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
89
+ return {
90
+ deviceId: newDeviceId(),
91
+ machineId: crypto.randomUUID(),
92
+ publicKeyPem: publicKey.export({ type: 'spki', format: 'pem' }),
93
+ privateKeyJwk: privateKey.export({ format: 'jwk' }),
94
+ };
95
+ }
96
+
97
+ function osProfile() {
98
+ const osName = os.type().replace(/_/g, ' ') || 'Windows';
99
+ return {
100
+ osName,
101
+ osVersion: os.release() || '',
102
+ deviceModel: `${os.platform()} ${os.arch()}`,
103
+ deviceBrand: osName,
104
+ deviceName: process.env.USERNAME || process.env.USER || os.hostname() || 'PC',
105
+ cpu: os.cpus()[0]?.model?.trim() || '',
106
+ };
107
+ }
108
+
109
+ /** 拼内层授权 URL(22 参数,顺序与真机客户端抓包逐字一致——不要按语义重排)。 */
110
+ export function buildAuthorizeUrl({ port, traceId, challenge, identity }) {
111
+ const system = osProfile();
112
+ const callback = `http://127.0.0.1:${port}/authorize`;
113
+ const enc = encodeURIComponent;
114
+ const inner = `${CONSOLE_BASE_CN}/authorization`
115
+ + `?login_version=1`
116
+ + `&auth_from=${AUTH_FROM}`
117
+ + `&login_channel=native_ide`
118
+ + `&plugin_version=${PLUGIN_VERSION}`
119
+ + `&auth_type=local`
120
+ + `&client_id=${CLIENT_ID_CN}`
121
+ + `&redirect=0`
122
+ + `&login_trace_id=${traceId}`
123
+ + `&auth_callback_url=${enc(callback)}`
124
+ + `&machine_id=${identity.machineId}`
125
+ + `&device_id=${identity.deviceId}`
126
+ + `&x_device_id=${identity.deviceId}`
127
+ + `&x_machine_id=${identity.machineId}`
128
+ + `&x_device_brand=${enc(system.deviceModel)}`
129
+ + `&x_device_type=${enc(process.platform)}`
130
+ + `&x_os_version=${enc(system.osVersion)}`
131
+ + `&x_env=`
132
+ + `&x_app_version=${APP_VERSION}`
133
+ + `&x_app_type=${APP_TYPE}`
134
+ + `&code_challenge=${challenge}`
135
+ + `&code_challenge_method=S256`
136
+ + `&channel_name=common`;
137
+ // 外层包装与真机客户端一致(/login?login_platform=trae&redirect_url=<内层>)
138
+ return `${CONSOLE_BASE_CN}/login?login_platform=trae&redirect_url=${enc(inner)}`;
139
+ }
140
+
141
+ /** 回调查询解析:先剥到 ? 后(req.url 带着路径前缀)、按 & 切 → 整体反复解码(浏览器/页面
142
+ * 可能二次编码)→ 第一个 = 切键值。JWT / refresh_token 的值里合法含 =(base64url 填充),
143
+ * 必须 split_once 而非按全部 = 切。 */
144
+ export function parseCallbackQuery(rawQuery) {
145
+ const out = {};
146
+ const raw = String(rawQuery || '');
147
+ const qi = raw.indexOf('?');
148
+ const qs = qi === -1 ? raw : raw.slice(qi + 1);
149
+ for (const pair of qs.split('&')) {
150
+ if (!pair) continue;
151
+ let decoded = pair;
152
+ for (let i = 0; i < 3; i++) {
153
+ const next = decoded.includes('%') ? decodeURIComponentSafe(decoded) : decoded;
154
+ if (next === decoded) break;
155
+ decoded = next;
156
+ }
157
+ const eq = decoded.indexOf('=');
158
+ if (eq === -1) out[decoded] = '';
159
+ else out[decoded.slice(0, eq)] = decoded.slice(eq + 1);
160
+ }
161
+ return out;
162
+ }
163
+
164
+ function decodeURIComponentSafe(s) {
165
+ try { return decodeURIComponent(s); } catch { return s; }
166
+ }
167
+
168
+ function jsonStringField(obj, keys) {
169
+ for (const k of keys) {
170
+ const v = obj?.[k];
171
+ if (typeof v === 'string' && v.trim()) return v.trim();
172
+ }
173
+ return null;
174
+ }
175
+
176
+ function jsonIntField(obj, keys) {
177
+ for (const k of keys) {
178
+ const v = Number(obj?.[k]);
179
+ if (Number.isFinite(v) && v > 0) return v;
180
+ }
181
+ return 0;
182
+ }
183
+
184
+ /** 解析回调参数 → {authCode, userInfo, host, region, traceId, error}(muskke parseCallback 同款容错)。 */
185
+ export function parseCallbackParams(params) {
186
+ const raw = params.authCodeInfo || params.auth_code_info || params.AuthCodeInfo || '';
187
+ let authCode = jsonStringField(params, ['authCode', 'auth_code', 'AuthCode', 'authorization_code', 'code']);
188
+ let codeExpireAt = 0;
189
+ if (raw) {
190
+ let info = null;
191
+ try { info = JSON.parse(raw); } catch { /* 不是合法 JSON——按缺 AuthCode 走 */ }
192
+ authCode = authCode || jsonStringField(info, ['AuthCode', 'authCode', 'auth_code', 'code']);
193
+ codeExpireAt = jsonIntField(info, ['ExpireAt', 'expireAt', 'expiresAt']);
194
+ }
195
+ let user = null;
196
+ try { user = params.userInfo ? JSON.parse(params.userInfo) : null; } catch {}
197
+ const host = jsonStringField(params, ['host', 'apiHost', 'APIHost']);
198
+ const region = (jsonStringField(params, ['userRegion', 'user_region', 'LoginRegion', 'loginRegion']) || '').toLowerCase();
199
+ return {
200
+ authCode,
201
+ codeExpireAt,
202
+ // 旧契约兜底:部分版本直接在回调里带 token(muskke 同款容错)
203
+ directAccessToken: jsonStringField(params, ['accessToken', 'access_token', 'token']),
204
+ directRefreshToken: jsonStringField(params, ['refreshToken', 'refresh_token', 'RefreshToken']),
205
+ uid: user ? jsonStringField(user, ['UserID', 'userId', 'uid']) : null,
206
+ name: user ? jsonStringField(user, ['ScreenName', 'screenName', 'nickname']) : null,
207
+ host,
208
+ region,
209
+ traceId: jsonStringField(params, ['loginTraceID', 'loginTraceId', 'login_trace_id']),
210
+ error: jsonStringField(params, ['error', 'error_description']),
211
+ };
212
+ }
213
+
214
+ /** 换票主机白名单校验(hostname 级;回环放行给联调 / 测试,回环原样保留 scheme+端口)。 */
215
+ export function resolveExchangeHost(host) {
216
+ const raw = String(host || '').trim().replace(/\/+$/, '');
217
+ const name = raw.split('://').pop()?.split('/')[0]?.split(':')[0]?.toLowerCase() || '';
218
+ if (!name) return { host: EXCHANGE_HOST_FALLBACK, usedFallback: 'missing' };
219
+ if (LOOPBACK_HOSTS.includes(name)) return { host: raw, usedFallback: null };
220
+ if (EXCHANGE_HOST_ALLOW.includes(name)) return { host: raw.startsWith('http') ? raw : `https://${raw}`, usedFallback: null };
221
+ return { host: EXCHANGE_HOST_FALLBACK, usedFallback: 'rejected' };
222
+ }
223
+
224
+ function deviceInfoPayload(identity) {
225
+ const system = osProfile();
226
+ return {
227
+ DeviceID: identity.deviceId,
228
+ MachineID: identity.machineId,
229
+ PlatformCode: 'IDE_PC',
230
+ DeviceType: 'PC',
231
+ DeviceName: system.deviceName,
232
+ DeviceModel: system.deviceModel,
233
+ ClientVersion: APP_VERSION,
234
+ DevicePublicKey: identity.publicKeyPem,
235
+ DeviceBrand: system.deviceBrand,
236
+ DeviceCPU: system.cpu,
237
+ OSInfo: system.osName,
238
+ OSVersion: system.osVersion,
239
+ };
240
+ }
241
+
242
+ /** 响应字段容错:accessToken/refreshToken 驼峰为主(muskke TokenData 同款),下划线兜底。 */
243
+ function pickToken(body) {
244
+ return {
245
+ accessToken: jsonStringField(body || {}, ['accessToken', 'access_token', 'Token', 'token']),
246
+ refreshToken: jsonStringField(body || {}, ['refreshToken', 'refresh_token', 'RefreshToken']),
247
+ expiresAtMs: jsonIntField(body || {}, ['expiresAt', 'expires_at', 'ExpireAt', 'expireAt']),
248
+ expiresInSec: jsonIntField(body || {}, ['expiresIn', 'expires_in']),
249
+ };
250
+ }
251
+
252
+ async function postJson(url, payload, extraHeaders = {}) {
253
+ const res = await fetch(url, {
254
+ method: 'POST',
255
+ headers: {
256
+ 'Content-Type': 'application/json',
257
+ Accept: 'application/json',
258
+ // 客户端原样带着的空 token 头(workbuddy 抓包:缺失会被上游当非客户端流量)
259
+ 'x-cloudide-token': '',
260
+ 'X-App-Id': '6eefa01c-1036-4c7e-9ca5-d891f63bfcd8',
261
+ 'x-plugin-channel': 'icube-ai',
262
+ ...extraHeaders,
263
+ },
264
+ body: JSON.stringify(payload),
265
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
266
+ });
267
+ const text = await res.text().catch(() => '');
268
+ let body = null;
269
+ try { body = text ? JSON.parse(text) : null; } catch {}
270
+ return { res, body, text };
271
+ }
272
+
273
+ /** AuthCode 换 token:主端点(新协议,带 DeviceInfo)→ 旧端点扁平体(AuthCode / Code 两种历史拼法)。 */
274
+ export async function exchangeAuthCode({ host, authCode, codeVerifier, identity }) {
275
+ const attempts = [
276
+ {
277
+ tag: 'ExchangeToken/DeviceInfo',
278
+ url: `${host}/trae/api/v3/oauth/ExchangeToken`,
279
+ payload: {
280
+ ClientID: CLIENT_ID_CN,
281
+ AuthCode: authCode,
282
+ CodeVerifier: codeVerifier,
283
+ DeviceInfo: deviceInfoPayload(identity),
284
+ IDEVersion: APP_VERSION,
285
+ },
286
+ },
287
+ {
288
+ tag: 'ExchangeToken/AuthCode',
289
+ url: `${host}/cloudide/api/v3/trae/oauth/ExchangeToken`,
290
+ payload: { ClientID: CLIENT_ID_CN, AuthCode: authCode, CodeVerifier: codeVerifier, DeviceID: identity.deviceId, PlatformCode: 'IDE_PC' },
291
+ },
292
+ {
293
+ tag: 'ExchangeToken/Code',
294
+ url: `${host}/cloudide/api/v3/trae/oauth/ExchangeToken`,
295
+ payload: { ClientID: CLIENT_ID_CN, Code: authCode, CodeVerifier: codeVerifier, DeviceID: identity.deviceId, PlatformCode: 'IDE_PC' },
296
+ },
297
+ ];
298
+ const errors = [];
299
+ for (const a of attempts) {
300
+ let r;
301
+ try {
302
+ r = await postJson(a.url, a.payload);
303
+ } catch (e) {
304
+ errors.push(`${a.tag}: ${e.cause?.code || e.message}`);
305
+ continue;
306
+ }
307
+ const t = pickToken(r.body);
308
+ if (r.res.ok && t.accessToken) return { ...t, via: a.tag };
309
+ const msg = r.body?.message || r.body?.error || r.body?.msg || (r.text ? r.text.slice(0, 160) : '');
310
+ errors.push(`${a.tag}: HTTP ${r.res.status}${msg ? ' ' + msg : ''}`);
311
+ }
312
+ throw new Error('Trae 换票失败:' + errors.join(' | '));
313
+ }
314
+
315
+ /** 回调监听:只绑 127.0.0.1;探测回 200+CORS,凭据回调进会话后立刻收摊。 */
316
+ function startCallbackServer(session) {
317
+ const server = http.createServer((req, res) => {
318
+ const cors = {
319
+ 'Access-Control-Allow-Origin': '*',
320
+ 'Access-Control-Allow-Methods': 'GET, OPTIONS',
321
+ 'Access-Control-Allow-Headers': '*',
322
+ };
323
+ if (req.method === 'OPTIONS') {
324
+ res.writeHead(204, cors);
325
+ res.end();
326
+ return;
327
+ }
328
+ const params = parseCallbackQuery(req.url || '');
329
+ const hasCredential = ['authCodeInfo', 'code', 'AuthCode', 'accessToken', 'refreshToken', 'userJwt'].some((k) => params[k]);
330
+ if (session.error || session.result) {
331
+ // 已收摊的迟到请求(探测重复触发等):只应答不处理
332
+ res.writeHead(200, { ...cors, 'Content-Type': 'text/plain' });
333
+ res.end('ok');
334
+ return;
335
+ }
336
+ if (!hasCredential) {
337
+ if (params.error) {
338
+ // 拒绝回调也是真回调:必须先于「无凭据=探测」判定,否则用户白等到超时
339
+ session.error = `授权被拒绝或失败(${params.error})`;
340
+ finish(session);
341
+ }
342
+ // 在线探测:200 + CORS,响应体不含任何凭据
343
+ res.writeHead(200, { ...cors, 'Content-Type': 'text/plain' });
344
+ res.end('ok');
345
+ return;
346
+ }
347
+ session.result = params;
348
+ finish(session);
349
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
350
+ res.end('<!doctype html><meta charset="utf-8"><title>Trae 登录</title>'
351
+ + '<body style="font-family:system-ui;display:grid;place-items:center;height:100vh;margin:0">'
352
+ + '<div style="text-align:center"><div style="font-size:42px">✅</div>'
353
+ + '<p>授权成功,回到 CreditDaddy 面板即可(此页可以关掉)。</p></div></body>');
354
+ });
355
+ return server;
356
+ }
357
+
358
+ function finish(session) {
359
+ session.settledAt = Date.now();
360
+ // 拿到终态立即释放端口;稍等一拍再 close,给响应体留出发送时间
361
+ setTimeout(() => {
362
+ try { session.server.close(); } catch {}
363
+ }, 500).unref();
364
+ }
365
+
366
+ async function bindCallbackServer(session, ports) {
367
+ const errors = [];
368
+ for (const port of ports) {
369
+ try {
370
+ await new Promise((resolve, reject) => {
371
+ const onErr = (e) => { server.off('listening', onOk); reject(e); };
372
+ const onOk = () => { server.off('error', onErr); resolve(); };
373
+ const server = session.server;
374
+ server.once('error', onErr);
375
+ server.once('listening', onOk);
376
+ server.listen(port, '127.0.0.1');
377
+ });
378
+ return port;
379
+ } catch (e) {
380
+ errors.push(`${port}: ${e.code || e.message}`);
381
+ }
382
+ }
383
+ throw new Error(`Trae 回调端口都被占用(${errors.join(';')})——请关掉占用 3379/17388 的程序(可能是正在登录的 Trae 客户端)后重试`);
384
+ }
385
+
386
+ /** 发起一次浏览器授权登录。kind 预留:'trae'(国内站);国际线是另一套域 + 钥匙,暂不开。 */
387
+ export async function startTraeLogin(kind, { ports = CALLBACK_PORTS } = {}) {
388
+ if (kind && kind !== 'trae') throw new Error('暂只支持 Trae 国内站登录(国际线待接)');
389
+ gcSessions();
390
+ const identity = newDeviceIdentity();
391
+ const verifier = crypto.randomBytes(48).toString('base64url');
392
+ const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
393
+ const traceId = crypto.randomUUID();
394
+ const session = {
395
+ identity, verifier, traceId,
396
+ result: null, error: null, settledAt: 0,
397
+ deadline: Date.now() + LOGIN_TIMEOUT_MS,
398
+ };
399
+ session.server = startCallbackServer(session);
400
+ const port = await bindCallbackServer(session, ports);
401
+ session.port = port;
402
+ const loginId = crypto.randomUUID();
403
+ sessions.set(loginId, session);
404
+ const url = buildAuthorizeUrl({ port, traceId, challenge, identity });
405
+ return {
406
+ url,
407
+ expiresInMs: LOGIN_TIMEOUT_MS,
408
+ intervalMs: 1500,
409
+ data: { loginId },
410
+ };
411
+ }
412
+
413
+ /**
414
+ * 轮询登录结果(authDevice 骨架约定):
415
+ * {status:'pending'} | {status:'ok', input} ;终态失败抛错。
416
+ * 成功后回调服务器与本地会话状态一并清理;authDevice 侧的 300s 会话过期自己兜底。
417
+ */
418
+ export async function pollTraeLogin(data) {
419
+ const session = sessions.get(data?.loginId);
420
+ if (!session) throw new Error('Trae 登录会话不存在或已超时,请重新发起');
421
+ if (session.error) {
422
+ sessions.delete(data.loginId);
423
+ throw new Error(session.error);
424
+ }
425
+ if (!session.result) {
426
+ if (Date.now() > session.deadline) {
427
+ sessions.delete(data.loginId);
428
+ try { session.server.close(); } catch {}
429
+ throw new Error('Trae 授权超时(5 分钟未完成),请重新发起');
430
+ }
431
+ return { status: 'pending' };
432
+ }
433
+
434
+ const params = session.result;
435
+ sessions.delete(data.loginId);
436
+ const info = parseCallbackParams(params);
437
+ if (info.error) throw new Error(`授权被拒绝:${info.error}`);
438
+ if (info.traceId && info.traceId !== session.traceId) {
439
+ throw new Error('回调 loginTraceID 与本次登录不匹配(CSRF 防护),请重新发起');
440
+ }
441
+ if (info.codeExpireAt) {
442
+ const expMs = info.codeExpireAt < 1e12 ? info.codeExpireAt * 1000 : info.codeExpireAt;
443
+ if (expMs <= Date.now()) throw new Error('回调里的 AuthCode 已过期,请重新发起');
444
+ }
445
+
446
+ // 旧契约直接带 token 的版本:跳过换票
447
+ if (info.directAccessToken && !info.authCode) {
448
+ return buildLoginResult({
449
+ accessToken: info.directAccessToken,
450
+ refreshToken: info.directRefreshToken,
451
+ identity: session.identity,
452
+ host: info.host,
453
+ region: info.region,
454
+ uid: info.uid,
455
+ name: info.name,
456
+ expiresAtMs: 0,
457
+ });
458
+ }
459
+ if (!info.authCode) throw new Error('回调里没有 AuthCode(授权页协议可能又变了),请重新发起或更新 CreditDaddy');
460
+
461
+ const resolved = resolveExchangeHost(info.host);
462
+ const t = await exchangeAuthCode({ host: resolved.host, authCode: info.authCode, codeVerifier: session.verifier, identity: session.identity });
463
+ return buildLoginResult({
464
+ accessToken: t.accessToken,
465
+ refreshToken: t.refreshToken,
466
+ identity: session.identity,
467
+ host: info.host || resolved.host,
468
+ region: info.region,
469
+ uid: info.uid,
470
+ name: info.name,
471
+ expiresAtMs: t.expiresAtMs,
472
+ expiresInSec: t.expiresInSec,
473
+ exchangeFallback: resolved.usedFallback,
474
+ });
475
+ }
476
+
477
+ function uidFromJwt(jwt) {
478
+ try {
479
+ const payload = JSON.parse(Buffer.from(jwt.split('.')[1], 'base64url').toString('utf8'));
480
+ return { uid: payload?.data?.id ? String(payload.data.id) : null, exp: Number(payload?.exp) || 0 };
481
+ } catch { return { uid: null, exp: 0 }; }
482
+ }
483
+
484
+ function buildLoginResult({ accessToken, refreshToken, identity, host, region, uid, name, expiresAtMs, expiresInSec = 0, exchangeFallback }) {
485
+ const jwt = uidFromJwt(accessToken);
486
+ const finalUid = uid || jwt.uid || null;
487
+ let expiresAt = null;
488
+ if (expiresAtMs) expiresAt = new Date(expiresAtMs < 1e12 ? expiresAtMs * 1000 : expiresAtMs).toISOString();
489
+ else if (expiresInSec) expiresAt = new Date(Date.now() + expiresInSec * 1000).toISOString();
490
+ else if (jwt.exp) expiresAt = new Date(jwt.exp * 1000).toISOString();
491
+
492
+ const device = {
493
+ deviceId: identity.deviceId,
494
+ machineId: identity.machineId,
495
+ publicKeyPem: identity.publicKeyPem,
496
+ privateKeyJwk: identity.privateKeyJwk,
497
+ };
498
+ return {
499
+ status: 'ok',
500
+ input: {
501
+ provider: 'trae',
502
+ token: accessToken,
503
+ refreshToken: refreshToken || null,
504
+ expiresAt,
505
+ uid: finalUid,
506
+ name: name || (finalUid ? `Trae_${String(finalUid).slice(-6)}` : null),
507
+ email: null,
508
+ source: 'browser',
509
+ meta: {
510
+ loginVia: 'oauth-authcode',
511
+ traeDevice: device,
512
+ traeHost: host || null,
513
+ traeRegion: region || null,
514
+ traeExchangeFallback: exchangeFallback || undefined,
515
+ clientVersion: APP_VERSION,
516
+ pluginVersion: PLUGIN_VERSION,
517
+ capturedAt: new Date().toISOString(),
518
+ },
519
+ },
520
+ };
521
+ }
522
+
523
+ /** 测试辅助:清空进程内会话(含关闭监听与 keep-alive 连接)。 */
524
+ export function _resetForTests() {
525
+ for (const [, s] of sessions) {
526
+ try { s.server.closeAllConnections?.(); } catch {}
527
+ try { s.server.close(); } catch {}
528
+ }
529
+ sessions.clear();
530
+ }
@@ -81,6 +81,7 @@ export const stats = {
81
81
  lastCallAt: null,
82
82
  calls: 0,
83
83
  lastAccount: null,
84
+ lastAccountAt: null, // 「接口使用中」徽章的 30 分钟窗口锚点(面板 gwRecentWindow 内才亮)
84
85
  };
85
86
 
86
87
  const MIN_WEIGHT = 1;
@@ -135,6 +136,7 @@ export function __resetForTests() {
135
136
  stats.lastCallAt = null;
136
137
  stats.calls = 0;
137
138
  stats.lastAccount = null;
139
+ stats.lastAccountAt = null;
138
140
  }
139
141
 
140
142
  async function accountWeight(a) {
@@ -549,6 +551,7 @@ export async function handleGateway(req, res) {
549
551
  }
550
552
 
551
553
  stats.lastAccount = label;
554
+ stats.lastAccountAt = Date.now();
552
555
  resetCoolingStreak(account.id); // 成功一次即清零连续 429 计数
553
556
  logger.debug('TRAE-GW', '{label} 连接成功,开始流式输出 ({model})', { label, model: requestedModel });
554
557
 
@@ -788,6 +791,7 @@ export async function gatewayStatus() {
788
791
  lastCallAt: stats.lastCallAt,
789
792
  calls: stats.calls,
790
793
  lastAccount: stats.lastAccount,
794
+ lastAccountAt: stats.lastAccountAt,
791
795
  },
792
796
  accounts: all.length,
793
797
  // cooling 保持字符串数组(历史形状);冷却细节走 coolingDetail(与 zcodeGateway 同款)