creditdaddy 1.7.2 → 1.8.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.
Files changed (73) hide show
  1. package/LICENSE +701 -2
  2. package/README.md +454 -440
  3. package/bin/creditdaddy.js +6 -0
  4. package/build.json +3 -3
  5. package/package.json +34 -34
  6. package/src/accounts.js +15 -0
  7. package/src/assets/donate-alipay.svg +1 -1
  8. package/src/assets/donate-ifdian.svg +1 -1
  9. package/src/assets/donate-wechat.svg +1 -1
  10. package/src/assets/providers/catpaw.png +0 -0
  11. package/src/assets/providers/codebuddy-ide.png +0 -0
  12. package/src/assets/providers/dumate.png +0 -0
  13. package/src/assets/providers/loomy.png +0 -0
  14. package/src/assets/providers/meoo.png +0 -0
  15. package/src/assets/providers/mirasim.png +0 -0
  16. package/src/bgdaemon.js +341 -341
  17. package/src/buildInfo.js +65 -65
  18. package/src/catpawClient.js +103 -103
  19. package/src/catpawLocal.js +236 -236
  20. package/src/checkin.js +98 -5
  21. package/src/codebuddyIdeLocal.js +381 -381
  22. package/src/constants.js +121 -117
  23. package/src/cookieSites.js +340 -301
  24. package/src/daemon.js +2720 -2443
  25. package/src/doubaoClient.js +167 -167
  26. package/src/dumateClient.js +517 -0
  27. package/src/dumateLocal.js +298 -0
  28. package/src/dumateQr.js +337 -0
  29. package/src/externalQuota.js +577 -574
  30. package/src/formatDuration.js +17 -17
  31. package/src/i18n/en.json +257 -7
  32. package/src/i18n/ja.json +257 -7
  33. package/src/i18n/ko.json +257 -7
  34. package/src/i18n/zh-TW.json +257 -7
  35. package/src/i18n.js +47 -47
  36. package/src/lingxiClient.js +373 -373
  37. package/src/localDetect.js +147 -147
  38. package/src/longcatClient.js +260 -260
  39. package/src/loomyAuth.js +230 -230
  40. package/src/loomyClient.js +366 -366
  41. package/src/loomyLocal.js +206 -206
  42. package/src/meooAuth.js +246 -0
  43. package/src/meooClient.js +250 -0
  44. package/src/minimaxGateway.js +520 -520
  45. package/src/minimaxLocal.js +344 -344
  46. package/src/mirasimClient.js +211 -211
  47. package/src/mirasimLocal.js +392 -392
  48. package/src/modelscopeClient.js +275 -275
  49. package/src/panel.html +704 -85
  50. package/src/prodIcons.json +7 -5
  51. package/src/providers.js +34 -0
  52. package/src/qoderApp.js +578 -578
  53. package/src/qoderClient.js +266 -266
  54. package/src/qoderUmid.js +199 -199
  55. package/src/quotaRefresh.js +119 -119
  56. package/src/refreshGuard.js +75 -75
  57. package/src/riverClient.js +372 -372
  58. package/src/store.js +2 -1
  59. package/src/tenrouterAccounts.js +237 -232
  60. package/src/traeAuth.js +601 -599
  61. package/src/traeClient.js +356 -360
  62. package/src/traeGateway.js +875 -875
  63. package/src/traeLocal.js +463 -371
  64. package/src/transfer.js +4 -0
  65. package/src/usageSync.js +535 -523
  66. package/src/winProc.js +134 -134
  67. package/src/xiaomiMimoClient.js +206 -206
  68. package/src/zcodeAuth.js +131 -131
  69. package/src/zcodeAutoClaim.js +53 -6
  70. package/src/zcodeClient.js +55 -2
  71. package/src/zcodeGateway.js +850 -850
  72. package/src/zcodeLocal.js +340 -340
  73. package/src/zcrypto.js +160 -160
@@ -0,0 +1,298 @@
1
+ /**
2
+ * DuMate 百度搭子(个人版)桌面客户端本机凭据读取。
3
+ *
4
+ * 凭据存储(Windows,2026-11-13 本机实测 v1.0.91/1.0.92):
5
+ * %APPDATA%\qianfan-desktop-app\auth.json
6
+ * { cookies: <base64 密文>, activeProviderType: 'bce'|'enterprise',
7
+ * accountProfiles: [{ profileId, loginType, bceUserId, bceAccountId, displayName, encryptedCookies }],
8
+ * activeProfileId }
9
+ * %APPDATA%\qianfan-desktop-app\.cookie-key 32 字节 AES-256-GCM 密钥(0600)
10
+ * 密文格式(app.asar 注释定版):base64( iv(12) || authTag(16) || ciphertext )
11
+ * 明文 = Electron cookie 数组 [{ name, value, domain, hostOnly, path, secure, httpOnly, expirationDate, … }]
12
+ *
13
+ * 个人版(loginType=bce)会话即 console.bce.baidu.com 的浏览器 Cookie 罐(BDUSS / bce-user-info 等),
14
+ * 与 10Router dumate 渠道(PR #113)消费的凭据同形——导入后直接可同步。
15
+ * 企业版(enterprise)凭据形状不同,首版不导入。
16
+ *
17
+ * 安全纪律:密钥与明文 Cookie 只在本机进程内流转,不落日志、不出本机。
18
+ */
19
+
20
+ import fs from 'node:fs';
21
+ import os from 'node:os';
22
+ import path from 'node:path';
23
+ import crypto from 'node:crypto';
24
+ import { execFileSync } from 'node:child_process';
25
+ import { procRunningCached } from './winProc.js';
26
+ import { t } from './i18n.js';
27
+
28
+ const EXE_NAMES = ['DuMate.exe'];
29
+
30
+ export function dumateDataDir() {
31
+ if (process.env.DUMATE_DATA_DIR) return process.env.DUMATE_DATA_DIR;
32
+ if (process.platform === 'win32') {
33
+ return path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'qianfan-desktop-app');
34
+ }
35
+ // Linux 侧 Go 后端用 $HOME/.config 承载(app.asar 注释口径);mac 未实测
36
+ return path.join(os.homedir(), '.config', 'qianfan-desktop-app');
37
+ }
38
+
39
+ export function authFile() { return path.join(dumateDataDir(), 'auth.json'); }
40
+ export function cookieKeyFile() { return path.join(dumateDataDir(), '.cookie-key'); }
41
+
42
+ function readJson(file) {
43
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
44
+ }
45
+
46
+ /** AES-256-GCM 解密:base64( iv(12) || authTag(16) || ciphertext ) → cookie 数组 */
47
+ export function decryptDumateCookies(encrypted, key) {
48
+ const raw = Buffer.from(String(encrypted || ''), 'base64');
49
+ if (raw.length < 28 || !key || key.length !== 32) return null;
50
+ try {
51
+ const d = crypto.createDecipheriv('aes-256-gcm', key, raw.subarray(0, 12));
52
+ d.setAuthTag(raw.subarray(12, 28));
53
+ const out = Buffer.concat([d.update(raw.subarray(28)), d.final()]).toString('utf8');
54
+ const arr = JSON.parse(out);
55
+ return Array.isArray(arr) ? arr : null;
56
+ } catch { return null; }
57
+ }
58
+
59
+ /** AES-256-GCM 加密(客户端同款布局):cookie 数组 → base64( iv(12) || authTag(16) || ciphertext ) */
60
+ export function encryptDumateCookies(cookies, key) {
61
+ const iv = crypto.randomBytes(12);
62
+ const c = crypto.createCipheriv('aes-256-gcm', key, iv);
63
+ const ct = Buffer.concat([c.update(JSON.stringify(cookies), 'utf8'), c.final()]);
64
+ return Buffer.concat([iv, c.getAuthTag(), ct]).toString('base64');
65
+ }
66
+
67
+ /** 过滤已过期 cookie(expirationDate 为秒级 unix;session cookie 无该字段) */
68
+ export function filterExpiredCookies(cookies, nowSec = Date.now() / 1000) {
69
+ return (cookies || []).filter((c) => c && c.name && (!c.expirationDate || c.expirationDate > nowSec));
70
+ }
71
+
72
+ /**
73
+ * 读本机全部个人版(bce)账号凭据 → [{ uid, displayName, cookies, cookieHeader, profileId, active }]
74
+ * 未安装 / 未登录 / 解密失败返回 []。
75
+ */
76
+ export function readDumateProfiles() {
77
+ const j = readJson(authFile());
78
+ if (!j) return [];
79
+ let key = null;
80
+ try { key = fs.readFileSync(cookieKeyFile()); } catch { return []; }
81
+ const profiles = Array.isArray(j.accountProfiles) && j.accountProfiles.length
82
+ ? j.accountProfiles
83
+ : (j.cookies ? [{ profileId: j.activeProfileId || 'legacy', loginType: j.activeProviderType || 'bce', bceUserId: null, displayName: null, encryptedCookies: j.cookies }] : []);
84
+ const out = [];
85
+ for (const p of profiles) {
86
+ if (!p || (p.loginType && p.loginType !== 'bce')) continue; // 企业版首版不导入
87
+ const cookies = filterExpiredCookies(decryptDumateCookies(p.encryptedCookies, key));
88
+ if (!cookies || !cookies.length) continue;
89
+ // 个人版会话必须含 BDUSS 与 bce-user-info(10R dumate 同款判定)
90
+ if (!cookies.some((c) => c.name === 'bce-user-info') || !cookies.some((c) => String(c.name).startsWith('BDUSS'))) continue;
91
+ out.push({
92
+ profileId: p.profileId || null,
93
+ uid: p.bceUserId || p.bceAccountId || null,
94
+ displayName: p.displayName || null,
95
+ active: p.profileId === j.activeProfileId,
96
+ cookies,
97
+ cookieHeader: cookies.map((c) => `${c.name}=${c.value}`).join('; '),
98
+ });
99
+ }
100
+ return out;
101
+ }
102
+
103
+ /** 当前激活的个人版账号(无则 null) */
104
+ export function readDumateCredential() {
105
+ const list = readDumateProfiles();
106
+ return list.find((p) => p.active) || list[0] || null;
107
+ }
108
+
109
+ export function dumateRunningCached() {
110
+ return procRunningCached(EXE_NAMES);
111
+ }
112
+
113
+ export function candidateClientPath() {
114
+ if (process.platform !== 'win32') return null;
115
+ const candidates = [
116
+ path.join(process.env.LOCALAPPDATA || '', 'Programs', 'DuMate', 'DuMate.exe'),
117
+ 'C:\\Program Files\\DuMate\\DuMate.exe',
118
+ 'C:\\Program Files (x86)\\DuMate\\DuMate.exe',
119
+ ];
120
+ return candidates.find((p) => fs.existsSync(p)) || null;
121
+ }
122
+
123
+ /** 本机 DuMate 综合探测(/api/status 用) */
124
+ export function detectDumate() {
125
+ const cred = readDumateCredential();
126
+ const clientPath = candidateClientPath();
127
+ return {
128
+ dataDir: dumateDataDir(),
129
+ exists: fs.existsSync(authFile()),
130
+ signedIn: Boolean(cred),
131
+ clientInstalled: Boolean(clientPath),
132
+ clientPath,
133
+ running: dumateRunningCached(),
134
+ credential: cred ? {
135
+ uid: cred.uid,
136
+ displayName: cred.displayName,
137
+ profiles: readDumateProfiles().length,
138
+ } : null,
139
+ };
140
+ }
141
+
142
+ /**
143
+ * 本机当前登录 → 标准化账号对象(供「添加账号 → 本机导入」)。
144
+ * token = 全量 Cookie 串(10R dumate 渠道 apiKey 同形)。
145
+ */
146
+ export async function liveToAccount() {
147
+ const cred = readDumateCredential();
148
+ if (!cred) return null;
149
+ const name = cred.displayName
150
+ ? `DuMate (${cred.displayName})`
151
+ : (cred.uid ? `DuMate (${String(cred.uid).slice(0, 6)}…)` : 'DuMate (本机)');
152
+ return {
153
+ provider: 'dumate',
154
+ token: cred.cookieHeader,
155
+ refreshToken: null,
156
+ uid: cred.uid,
157
+ name,
158
+ expiresAt: null,
159
+ source: 'local-app',
160
+ meta: {
161
+ dumateProfileId: cred.profileId,
162
+ displayName: cred.displayName,
163
+ capturedAt: new Date().toISOString(),
164
+ },
165
+ };
166
+ }
167
+
168
+ /* ───────────────────── 账号切换(写客户端凭据,Loomy hardSwitch 同构) ─────────────────────
169
+ *
170
+ * 客户端切换事务(asar createSwitchAccountProfileHandler):停运行时服务 → 解密目标
171
+ * profile → Chromium session 清场换 Cookie → 提交 active 槽(顶层 cookies 重加密 +
172
+ * activeProfileId/activeProviderType)。而启动路径 setCookieProvider(getDecryptedCookies)
173
+ * —— Go 侧代理直接消费 auth.json 注入 Cookie,所以 CD 冷状态重写 auth.json 即完成切换:
174
+ * 杀壳与全部 Go 服务 → 写文件(原子)→ 延时复核(防退出清理回写)→ 面板重开客户端。
175
+ * 与 Loomy 同款注意:客户端窗口的 Chromium 罐残留旧账号 Cookie 时,界面身份可能仍旧,
176
+ * 以控制台 API 实际身份为准(必要时客户端内退出重登)。
177
+ */
178
+
179
+ const SERVICE_EXES = ['DuMate.exe', 'dumate-main-server.exe', 'dumate-base-proxy.exe', 'dumate-router.exe', 'dumate-opencode.exe', 'dumate-na.exe'];
180
+
181
+ const nap = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
182
+ const napAsync = (ms) => new Promise((r) => setTimeout(r, ms));
183
+
184
+ /** 杀客户端壳 + 全部 Go 后端服务(切换期间它们缓存旧账号身份) */
185
+ export function terminateDumate({ timeoutMs = 8000 } = {}) {
186
+ if (process.platform !== 'win32') return { closed: false, supported: false };
187
+ const anyRunning = () => SERVICE_EXES.some((exe) => {
188
+ try {
189
+ const out = execFileSync('tasklist.exe', ['/FI', `IMAGENAME eq ${exe}`, '/NH'],
190
+ { windowsHide: true, encoding: 'utf8', timeout: 8000 });
191
+ return out.toLowerCase().includes(exe.toLowerCase()) && !/no tasks|没有找到|没有任务/i.test(out);
192
+ } catch { return false; }
193
+ });
194
+ if (!anyRunning()) return { closed: false, running: false };
195
+ for (const exe of SERVICE_EXES) {
196
+ try { execFileSync('taskkill.exe', ['/IM', exe, '/T', '/F'], { windowsHide: true, stdio: 'ignore', timeout: 15_000 }); } catch {}
197
+ }
198
+ let deadline = Date.now() + timeoutMs;
199
+ while (Date.now() < deadline && anyRunning()) nap(250);
200
+ return { closed: !anyRunning(), running: anyRunning() };
201
+ }
202
+
203
+ /** 按 CD 账号找目标 profile:优先 meta.dumateProfileId,回落 BDUSS + bce-user-info 值全等匹配 */
204
+ function findTargetProfile(account) {
205
+ const j = readJson(authFile());
206
+ if (!j) return null;
207
+ const key = fs.readFileSync(cookieKeyFile());
208
+ const profiles = readDumateProfiles(); // 已过滤企业版/过期 cookie
209
+ const wantHeader = String(account?.token || '');
210
+ const extract = (header, name) => {
211
+ for (const seg of String(header || '').split(';')) {
212
+ const i = seg.indexOf('=');
213
+ if (i > 0 && seg.slice(0, i).trim() === name) return seg.slice(i + 1).trim();
214
+ }
215
+ return null;
216
+ };
217
+ const wantBduss = extract(wantHeader, 'BDUSS') || extract(wantHeader, 'BDUSS_BFESS');
218
+ const wantUi = extract(wantHeader, 'bce-user-info');
219
+ const byId = account?.meta?.dumateProfileId
220
+ ? profiles.find((p) => p.profileId === account.meta.dumateProfileId)
221
+ : null;
222
+ if (byId) return byId;
223
+ if (wantBduss) {
224
+ return profiles.find((p) => {
225
+ const bduss = extract(p.cookieHeader, 'BDUSS') || extract(p.cookieHeader, 'BDUSS_BFESS');
226
+ if (wantUi) {
227
+ const ui = extract(p.cookieHeader, 'bce-user-info');
228
+ if (bduss === wantBduss && ui === wantUi) return true;
229
+ }
230
+ return bduss === wantBduss;
231
+ }) || null;
232
+ }
233
+ return null;
234
+ }
235
+
236
+ function readAuthStore() {
237
+ const j = readJson(authFile());
238
+ if (!j) return null;
239
+ let key = null;
240
+ try { key = fs.readFileSync(cookieKeyFile()); } catch { return null; }
241
+ return { j, key };
242
+ }
243
+
244
+ function writeAuthStore(j) {
245
+ const tmp = `${authFile()}.tmp-${crypto.randomUUID()}`;
246
+ fs.writeFileSync(tmp, JSON.stringify(j, null, 2) + '\n', 'utf8');
247
+ fs.renameSync(tmp, authFile());
248
+ }
249
+
250
+ /**
251
+ * 硬切换:杀客户端 + 服务 → 重写 auth.json active 槽(顶层 cookies 重加密)→ 延时复核。
252
+ * requireClient=false 仅供测试注入(非 Windows 验证写入/复核逻辑)。
253
+ */
254
+ export async function hardSwitchDumate(account, { requireClient = true } = {}) {
255
+ if (!account?.token) throw new Error(t('目标账号缺少会话 Cookie'));
256
+ if (requireClient && !candidateClientPath()) {
257
+ const err = new Error(process.platform === 'win32'
258
+ ? t('本机未安装 DuMate 客户端,无法切换(切换是把登录写入客户端凭据,由客户端应用)')
259
+ : t('DuMate 客户端仅支持 Windows,本平台无法切换'));
260
+ err.dumateNotInstalled = true;
261
+ throw err;
262
+ }
263
+ const store = readAuthStore();
264
+ if (!store) throw new Error(t('未读到 DuMate 客户端凭据库(auth.json / .cookie-key)'));
265
+ const { j, key } = store;
266
+
267
+ const target = findTargetProfile(account);
268
+ if (!target) {
269
+ throw new Error(t('目标账号不是本机 DuMate 客户端已登录的账号,无法写入切换(请先在客户端登录该账号后本机导入)'));
270
+ }
271
+ if (target.active) {
272
+ return { switched: false, alreadyActive: true, closedClient: false, verified: true };
273
+ }
274
+ const validCookies = filterExpiredCookies(target.cookies || []);
275
+ if (!validCookies.length) {
276
+ throw new Error(t('DuMate 目标账号凭据已过期(全部 Cookie 过期),请在客户端重新登录后再切换'));
277
+ }
278
+
279
+ const wasRunning = dumateRunningCached();
280
+ const term = terminateDumate();
281
+ const closedClient = wasRunning && term.running === false;
282
+
283
+ const next = {
284
+ ...j,
285
+ activeProviderType: 'bce',
286
+ activeProfileId: target.profileId,
287
+ cookies: encryptDumateCookies(validCookies, key),
288
+ };
289
+ writeAuthStore(next);
290
+ await napAsync(1200);
291
+ let verified = readDumateCredential()?.profileId === target.profileId;
292
+ if (!verified) {
293
+ writeAuthStore(next);
294
+ await napAsync(1200);
295
+ verified = readDumateCredential()?.profileId === target.profileId;
296
+ }
297
+ return { switched: true, alreadyActive: false, closedClient, verified };
298
+ }
@@ -0,0 +1,337 @@
1
+ /**
2
+ * DuMate 百度搭子扫码登录 —— 纯 HTTP 重实现百度 Passport(tangram)二维码流程,无头无浏览器。
3
+ * 协议与 10Router open-sse/shared/dumate/qr.js + session.js 同源(c50d22a6,已在线上 10R 实测可用):
4
+ *
5
+ * 1. GET passport.baidu.com/v2/api/getqrcode?tpl=bceplat&gid=<guid>&callback=<jsonp>
6
+ * → { sign, imgurl }
7
+ * 2. GET /v2/api/qrcode?sign=..&lp=pc&qrloginfrom=pc → 二维码 PNG(守护进程侧取回转 data URI,
8
+ * 面板无需直连 passport.baidu.com)
9
+ * 3. GET /channel/unicast?channel_id=<sign>&tpl=bceplat(30s 长轮询)
10
+ * errno==1 → 继续等
11
+ * errno==0 && channel_v.status==1 → 已扫码待确认
12
+ * errno==0 && channel_v.status==0 → 已确认 → 第 4 步
13
+ * errno==50000 → 风控拦截
14
+ * 4. GET /v3/login/main/qrbdusslogin?bduss=<channel_v.v>&u=<enc(channel_v.u)>…
15
+ * → errInfo.no==0,Set-Cookie 落 Passport cookies(BDUSS/STOKEN/PTOKEN/UBI/BAIDUID)
16
+ * 5. 跟随 data.u 跳转链进入 console.bce.baidu.com → bce-sessionid;缺失时回落
17
+ * quickLogin 快捷登录链(登录页「快捷登录」按钮的同款 wap 链)。
18
+ * 6. 保留 bce-sessionid + Passport cookies,串成凭据头(与 10R dumate 渠道 apiKey 同形)。
19
+ *
20
+ * qrbdusslogin 的坑(逆向 SDK 得出,照抄 10R 口径):
21
+ * - `u` 在线上只编码一次(SDK 先 decodeURIComponent(channel_v.u) 再由 jsonp 层编码一次),
22
+ * 双重编码会被百度回 errInfo.no=200;
23
+ * - channel_v.u 可为空——SDK 回落到页面配置的回跳地址,这里用 DuMate 控制台 URL;
24
+ * - apiver/tt/lang/maskId/fileId 是 SDK 自动补的参数,缺了同样 no=200;
25
+ * - 响应是 JSONP 包着一个单引号键的 JS 对象字面量——严格 JSON.parse 会挂,字段提取带正则兜底。
26
+ *
27
+ * 状态机:starting | waiting | scanned | confirming | authorized | success | expired | cancelled | error
28
+ * `authorized` = 凭据已在会话里,由 daemon 路由负责入库 + 校验后置 success。
29
+ * 凭据只在本机会话内流转,日志绝不落 Cookie / token 值。
30
+ */
31
+
32
+ import { randomBytes } from 'node:crypto';
33
+ import { FETCH_TIMEOUT_MS } from './constants.js';
34
+ import { healDumateCookies } from './dumateClient.js';
35
+
36
+ export const DUMATE_QR_CONSOLE_URL = 'https://console.bce.baidu.com/dumate/channel';
37
+ export const DUMATE_QR_UA =
38
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36';
39
+
40
+ const QR_TTL_MS = 10 * 60_000; // 百度二维码有效期约 10 分钟
41
+ const SESSION_KEEP_MS = 15 * 60_000;
42
+
43
+ const PASSPORT_NAMES = ['BDUSS', 'BDUSS_BFESS', 'STOKEN', 'PTOKEN', 'UBI', 'UBI_BFESS', 'BAIDUID', 'BAIDUID_BFESS', 'PASSID'];
44
+ const PASSPORT_HOST_ONLY = new Set(['STOKEN', 'PTOKEN', 'UBI', 'UBI_BFESS', 'PASSID']);
45
+
46
+ const bare = (d) => String(d || '').replace(/^\./, '').toLowerCase();
47
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
48
+ const logPage = () => encodeURIComponent(`traceId:pc_loginv5_${Math.floor(Date.now() / 1000)},logPage:loginv5`);
49
+ const guid = () => [7, 4, 4, 4, 12].map((n) => randomBytes(8).toString('hex').toUpperCase().slice(0, n)).join('-');
50
+ const unjsonp = (t) => { const m = /^[^(]*\(([\s\S]*)\)\s*;?\s*$/.exec(t); return JSON.parse(m ? m[1] : t); };
51
+ const jsoNo = (t) => { const m = /"no"\s*:\s*"?\s*(-?\d+)/.exec(t); return m ? +m[1] : null; };
52
+ const jsoU = (t) => { const m = /"u"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(t); return m ? m[1].replace(/\\\//g, '/').replace(/\\\\/g, '\\') : null; };
53
+
54
+ /** 域感知 cookie 罐(够用即可:name/value/domain,header(host) 按域过滤) */
55
+ export class Jar {
56
+ constructor() { this.cookies = []; }
57
+ add(name, value, domain) {
58
+ if (!name) return;
59
+ this.cookies = this.cookies.filter((c) => !(c.name === name && bare(c.domain) === bare(domain)));
60
+ this.cookies.push({ name, value: String(value ?? ''), domain: domain || '' });
61
+ }
62
+ addSetCookie(list, host) {
63
+ for (const raw of list || []) {
64
+ const first = String(raw).split(';')[0];
65
+ const i = first.indexOf('=');
66
+ if (i <= 0) continue;
67
+ const name = first.slice(0, i).trim();
68
+ const value = first.slice(i + 1).trim();
69
+ const dm = /domain=([^;]+)/i.exec(String(raw));
70
+ this.add(name, value, dm ? dm[1].trim() : host);
71
+ }
72
+ }
73
+ header(host) {
74
+ const h = bare(host);
75
+ return this.cookies
76
+ .filter((c) => { const d = bare(c.domain); return !d || h === d || h.endsWith('.' + d); })
77
+ .map((c) => `${c.name}=${c.value}`).join('; ');
78
+ }
79
+ has(name) { return this.cookies.some((c) => c.name === name && c.value); }
80
+ all() { return this.cookies.slice(); }
81
+ }
82
+
83
+ /** 只留控制台会话 + Passport 集(照抄 10R keepCookie 口径) */
84
+ export function keepCookie(c) {
85
+ if (c.name === 'bce-sessionid') return true;
86
+ if (/^bce/i.test(c.name)) return false;
87
+ const d = bare(c.domain);
88
+ return d === 'baidu.com' || d === 'passport.baidu.com';
89
+ }
90
+
91
+ async function fetchGet(url, jar, timeoutMs, s) {
92
+ const ctl = new AbortController();
93
+ const timer = setTimeout(() => ctl.abort(), timeoutMs || FETCH_TIMEOUT_MS);
94
+ if (s) s.ctl = ctl;
95
+ try {
96
+ const res = await fetch(url, {
97
+ method: 'GET',
98
+ redirect: 'manual',
99
+ signal: ctl.signal,
100
+ headers: {
101
+ 'User-Agent': DUMATE_QR_UA,
102
+ Accept: '*/*',
103
+ Referer: 'https://login.bce.baidu.com/',
104
+ ...(jar ? { Cookie: jar.header(new URL(url).hostname) } : {}),
105
+ },
106
+ });
107
+ if (jar) jar.addSetCookie(res.headers.getSetCookie ? res.headers.getSetCookie() : [res.headers.get('set-cookie')], new URL(url).hostname);
108
+ const body = Buffer.from(await res.arrayBuffer());
109
+ return { status: res.status, headers: res.headers, body };
110
+ } catch (e) {
111
+ if (s && s.cancelled) return { status: 0, headers: new Headers(), body: Buffer.alloc(0) };
112
+ throw e;
113
+ } finally { clearTimeout(timer); }
114
+ }
115
+
116
+ /* ---------------- 快捷登录链(bce-sessionid 缺失时的兜底,可独立复用) ---------------- */
117
+
118
+ const reauthError = (msg) => Object.assign(new Error(msg), { reauth: true });
119
+ const b64urlJson = (o) => Buffer.from(JSON.stringify(o), 'utf8').toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
120
+
121
+ /** 校验 Passport 并取账号名:{ username, portraitUrl } 或 null */
122
+ export async function qrPortrait(pp) {
123
+ const jar = new Jar();
124
+ for (const c of pp) jar.add(c.name, c.value, c.domain || '.baidu.com');
125
+ const r = await fetchGet('https://login.bce.baidu.com/passport-portrait', jar, 20_000);
126
+ try {
127
+ const j = JSON.parse(r.body.toString('utf8'));
128
+ if (j && j.success && j.result && j.result.username) return j.result;
129
+ } catch { /* 非 JSON = 未登录 */ }
130
+ return null;
131
+ }
132
+
133
+ /**
134
+ * 用 Passport cookies(必须含 BDUSS/BDUSS_BFSS)换全套控制台会话。
135
+ * @returns {{ cookies: Array<{name,value,domain}>, account: string }}
136
+ */
137
+ export async function qrQuickLogin(pp) {
138
+ if (!pp.some((c) => c.name === 'BDUSS' || c.name === 'BDUSS_BFESS')) {
139
+ throw reauthError('no Baidu passport cookie (BDUSS) — cannot log in');
140
+ }
141
+ const jar = new Jar();
142
+ for (const c of pp) jar.add(c.name, c.value, c.domain || '.baidu.com');
143
+ // 登录页 JS 在出示「快捷登录」前写入的标记 cookie,缺了会被弹回登录页
144
+ for (const [n, v] of [
145
+ ['bce-login-type', 'PASSPORT'],
146
+ ['bce-login-type-detail', 'SHARED_PASSPORT'],
147
+ ['bce-fe-load-type', 'self'],
148
+ ['x-bce-login-redirect-url', DUMATE_QR_CONSOLE_URL],
149
+ ['x-bce-login-redirect-url-console', DUMATE_QR_CONSOLE_URL],
150
+ ]) jar.add(n, v, '.bce.baidu.com');
151
+
152
+ const pf = await qrPortrait(pp).catch(() => null);
153
+ if (!pf) throw reauthError('Baidu passport session rejected (BDUSS not accepted) — re-login required');
154
+
155
+ let url = 'https://login.bce.baidu.com/postlogin/passport/wap'
156
+ + '?activate=true&passportShared=true&redirect=' + DUMATE_QR_CONSOLE_URL
157
+ + '&ocpcContext=' + b64urlJson({ portraitUrl: pf.portraitUrl || '', username: pf.username });
158
+
159
+ for (let hop = 0; hop < 10; hop++) {
160
+ const r = await fetchGet(url, jar, 20_000);
161
+ const loc = r.headers.get('location');
162
+ if (!loc) {
163
+ const onConsole = /^https:\/\/console\.bce\.baidu\.com\//.test(url);
164
+ const hasSess = jar.has('bce-sessionid');
165
+ if (onConsole && r.status === 200 && hasSess) {
166
+ // 控制台首页不一定下发 bce-user-info,缺了就用 dumate 应用 token 接口补齐账户 ID
167
+ let cookies = jar.all();
168
+ if (!jar.has('bce-user-info')) {
169
+ const healed = await healDumateCookies(cookies).catch(() => null);
170
+ if (healed) cookies = healed;
171
+ }
172
+ return { cookies, account: pf.username };
173
+ }
174
+ break;
175
+ }
176
+ url = new URL(loc, url).href;
177
+ }
178
+ if (!jar.has('bce-sessionid')) {
179
+ throw reauthError('quick-login did not establish a console session (passport rejected or risk check) — re-login required');
180
+ }
181
+ throw new Error('quick-login redirect chain never reached the console: ' + url.slice(0, 120));
182
+ }
183
+
184
+ /* ---------------- 会话表与后台流程 ---------------- */
185
+
186
+ const sessions = new Map();
187
+ let seq = 0;
188
+
189
+ function gc() {
190
+ const now = Date.now();
191
+ for (const [k, s] of sessions) if (s.doneAt && now - s.doneAt > SESSION_KEEP_MS) sessions.delete(k);
192
+ }
193
+
194
+ export function finishQr(s, status, error) {
195
+ if (s.doneAt && s.status !== 'authorized') return;
196
+ s.status = status;
197
+ if (error) s.error = error;
198
+ s.doneAt = Date.now();
199
+ }
200
+
201
+ export function pubQr(s) {
202
+ const o = { sid: s.id, status: s.status };
203
+ if (s.qr && ['waiting', 'scanned', 'confirming'].includes(s.status)) { o.qr = s.qr; o.expiresAt = s.expiresAt; }
204
+ if (s.error) o.error = s.error;
205
+ if (s.account) o.account = s.account;
206
+ return o;
207
+ }
208
+
209
+ export function getQrSession(sid) { gc(); return sessions.get(String(sid || '')) || null; }
210
+
211
+ /** 开新扫码会话;同一实例上未完成的旧会话先取消 */
212
+ export function startQrSession() {
213
+ gc();
214
+ for (const s of sessions.values()) if (!s.doneAt) { s.cancelled = true; try { s.ctl?.abort(); } catch { /* noop */ } }
215
+ const s = { id: 'dmqr-' + (++seq) + '-' + randomBytes(4).toString('hex'), status: 'starting', cancelled: false, doneAt: 0 };
216
+ sessions.set(s.id, s);
217
+ runQr(s).catch(() => finishQr(s, 'error', 'QR flow crashed'));
218
+ return s;
219
+ }
220
+
221
+ export function cancelQrSession(sid) {
222
+ const s = getQrSession(sid);
223
+ if (!s || s.doneAt) return false;
224
+ s.cancelled = true;
225
+ try { s.ctl?.abort(); } catch { /* noop */ }
226
+ finishQr(s, 'cancelled');
227
+ return true;
228
+ }
229
+
230
+ async function runQr(s) {
231
+ const jar = new Jar();
232
+ const GID = guid(), CB = 'tangram_guid_' + Date.now(), LP = logPage();
233
+ try {
234
+ // 1) 取码
235
+ const r1 = await fetchGet(
236
+ `https://passport.baidu.com/v2/api/getqrcode?lp=pc&qrloginfrom=pc&gid=${GID}&callback=${CB}&apiver=v3&tt=${Date.now()}&tpl=bceplat&logPage=${LP}&_=${Date.now()}`,
237
+ jar, 20_000, s);
238
+ if (s.cancelled) return;
239
+ let j1 = null; try { j1 = unjsonp(r1.body.toString('utf8')); } catch { /* 下面统一处理 */ }
240
+ if (!j1 || +j1.errno !== 0 || !j1.sign) throw new Error('QR generation failed: errno=' + (j1 ? j1.errno : r1.status));
241
+ const sign = j1.sign;
242
+
243
+ // 2) 二维码图片(守护进程侧取回 → data URI)
244
+ const imgUrl = 'https://' + String(j1.imgurl || 'passport.baidu.com/v2/api/qrcode?sign=' + sign).replace(/^https?:\/\//, '')
245
+ + `&lp=pc&qrloginfrom=pc&logPage=${LP}`;
246
+ const r2 = await fetchGet(imgUrl, jar, 20_000, s);
247
+ if (s.cancelled) return;
248
+ if (r2.status !== 200 || !/image/.test(String(r2.headers.get('content-type') || ''))) {
249
+ throw new Error('QR image fetch failed: HTTP ' + r2.status);
250
+ }
251
+ s.qr = 'data:image/png;base64,' + r2.body.toString('base64');
252
+ s.expiresAt = Date.now() + QR_TTL_MS;
253
+ s.status = 'waiting';
254
+
255
+ // 3) unicast 长轮询,直到确认 / 过期 / 取消
256
+ let cv = null, errs = 0;
257
+ while (!s.cancelled) {
258
+ if (Date.now() > s.expiresAt) { finishQr(s, 'expired'); return; }
259
+ let d = null;
260
+ try {
261
+ const r3 = await fetchGet(
262
+ `https://passport.baidu.com/channel/unicast?channel_id=${sign}&gid=${GID}&tpl=bceplat&_sdkFrom=1&callback=${CB}&apiver=v3&tt=${Date.now()}&_=${Date.now()}`,
263
+ jar, 40_000, s);
264
+ if (s.cancelled) return;
265
+ d = unjsonp(r3.body.toString('utf8'));
266
+ errs = 0;
267
+ } catch (e) {
268
+ if (s.cancelled) return;
269
+ if (++errs >= 5) throw new Error('scan-status polling failed: ' + e.message);
270
+ await sleep(2000); continue;
271
+ }
272
+ if (+d.errno === 50000) throw new Error('Baidu risk control blocked this QR login — retry later or use local import');
273
+ let cvo = null; try { cvo = typeof d.channel_v === 'string' ? JSON.parse(d.channel_v) : d.channel_v; } catch { /* 继续轮询 */ }
274
+ if (cvo && +cvo.status === 0) { cv = cvo; break; }
275
+ if (cvo && +cvo.status === 1 && s.status === 'waiting') s.status = 'scanned';
276
+ }
277
+ if (s.cancelled || !cv || !cv.v) {
278
+ if (!s.cancelled) finishQr(s, 'error', 'login confirmed but no ticket was returned');
279
+ return;
280
+ }
281
+ s.status = 'confirming';
282
+
283
+ // 4) qrbdusslogin——落 Passport cookies;cv.u 为空回落控制台 URL(与 SDK 缺省同口径)
284
+ const r4 = await fetchGet(
285
+ `https://passport.baidu.com/v3/login/main/qrbdusslogin?v=${Date.now()}`
286
+ + `&bduss=${encodeURIComponent(cv.v)}&u=${encodeURIComponent(cv.u || DUMATE_QR_CONSOLE_URL)}`
287
+ + `&loginVersion=v5&qrcode=1&tpl=bceplat&maskId=&fileId=&lang=&apiver=v3&tt=${Date.now()}&callback=${CB}&_=${Date.now()}`,
288
+ jar, 20_000, s);
289
+ if (s.cancelled) return;
290
+ const body4 = r4.body.toString('utf8');
291
+ let j4 = null; try { j4 = unjsonp(body4); } catch { /* 对象字面量 body——正则兜底 */ }
292
+ const no = j4 && j4.errInfo ? +j4.errInfo.no : jsoNo(body4);
293
+ if (no !== 0) throw new Error('login confirm failed: errInfo.no=' + (no == null ? r4.status : no));
294
+ const ret = (j4 && j4.data && j4.data.u) || jsoU(body4) || cv.u;
295
+
296
+ // 5) 跟随回跳链进控制台
297
+ if (ret) {
298
+ let url = ret;
299
+ for (let hop = 0; hop < 10; hop++) {
300
+ const rr = await fetchGet(url, jar, 20_000, s);
301
+ if (s.cancelled) return;
302
+ const loc = rr.headers.get('location');
303
+ if (!loc) break;
304
+ url = new URL(loc, url).href;
305
+ }
306
+ }
307
+
308
+ // 6) bce-sessionid 缺失 → 快捷登录链兜底
309
+ if (!jar.has('bce-sessionid')) {
310
+ const pp = jar.all().filter((c) => PASSPORT_NAMES.includes(c.name));
311
+ if (pp.some((c) => c.name === 'BDUSS' || c.name === 'BDUSS_BFESS')) {
312
+ const out = await qrQuickLogin(pp);
313
+ for (const c of out.cookies) jar.add(c.name, c.value, c.domain);
314
+ s.account = out.account || s.account;
315
+ }
316
+ }
317
+ const kept = jar.all().filter(keepCookie);
318
+ if (!kept.some((c) => c.name === 'bce-sessionid' && c.value)) {
319
+ throw new Error('QR login succeeded but no console session was established (missing bce-sessionid)');
320
+ }
321
+ if (!kept.some((c) => c.name === 'BDUSS' || c.name === 'BDUSS_BFESS')) {
322
+ // 没有 Passport cookie 只影响后续静默续期,不阻断本次登录
323
+ }
324
+ s.credCookies = kept;
325
+ s.status = 'authorized';
326
+ } catch (e) {
327
+ if (!s.cancelled) finishQr(s, 'error', String(e && e.message || e).split('\n')[0].slice(0, 200));
328
+ } finally {
329
+ if (s.cancelled && !s.doneAt) finishQr(s, 'cancelled');
330
+ s.ctl = null;
331
+ }
332
+ }
333
+
334
+ /** 凭据头(daemon 路由在 authorized 后取用入库) */
335
+ export function credHeaderOf(s) {
336
+ return (s?.credCookies || []).map((c) => `${c.name}=${c.value}`).join('; ');
337
+ }