creditdaddy 1.7.2 → 1.8.0

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 (70) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +445 -440
  3. package/build.json +3 -3
  4. package/package.json +34 -34
  5. package/src/accounts.js +15 -0
  6. package/src/assets/donate-alipay.svg +1 -1
  7. package/src/assets/donate-ifdian.svg +1 -1
  8. package/src/assets/donate-wechat.svg +1 -1
  9. package/src/assets/providers/catpaw.png +0 -0
  10. package/src/assets/providers/codebuddy-ide.png +0 -0
  11. package/src/assets/providers/dumate.png +0 -0
  12. package/src/assets/providers/loomy.png +0 -0
  13. package/src/assets/providers/meoo.png +0 -0
  14. package/src/assets/providers/mirasim.png +0 -0
  15. package/src/bgdaemon.js +341 -341
  16. package/src/buildInfo.js +65 -65
  17. package/src/catpawClient.js +103 -103
  18. package/src/catpawLocal.js +236 -236
  19. package/src/checkin.js +7 -2
  20. package/src/codebuddyIdeLocal.js +381 -381
  21. package/src/constants.js +121 -117
  22. package/src/cookieSites.js +340 -301
  23. package/src/daemon.js +2682 -2443
  24. package/src/doubaoClient.js +167 -167
  25. package/src/dumateClient.js +517 -0
  26. package/src/dumateLocal.js +298 -0
  27. package/src/dumateQr.js +337 -0
  28. package/src/externalQuota.js +577 -574
  29. package/src/formatDuration.js +17 -17
  30. package/src/i18n/en.json +161 -7
  31. package/src/i18n/ja.json +161 -7
  32. package/src/i18n/ko.json +161 -7
  33. package/src/i18n/zh-TW.json +161 -7
  34. package/src/i18n.js +47 -47
  35. package/src/lingxiClient.js +373 -373
  36. package/src/localDetect.js +147 -147
  37. package/src/longcatClient.js +260 -260
  38. package/src/loomyAuth.js +230 -230
  39. package/src/loomyClient.js +366 -366
  40. package/src/loomyLocal.js +206 -206
  41. package/src/meooAuth.js +246 -0
  42. package/src/meooClient.js +250 -0
  43. package/src/minimaxGateway.js +520 -520
  44. package/src/minimaxLocal.js +344 -344
  45. package/src/mirasimClient.js +211 -211
  46. package/src/mirasimLocal.js +392 -392
  47. package/src/modelscopeClient.js +275 -275
  48. package/src/panel.html +374 -48
  49. package/src/prodIcons.json +7 -5
  50. package/src/providers.js +34 -0
  51. package/src/qoderApp.js +578 -578
  52. package/src/qoderClient.js +266 -266
  53. package/src/qoderUmid.js +199 -199
  54. package/src/quotaRefresh.js +119 -119
  55. package/src/refreshGuard.js +75 -75
  56. package/src/riverClient.js +372 -372
  57. package/src/store.js +2 -1
  58. package/src/tenrouterAccounts.js +237 -232
  59. package/src/traeAuth.js +601 -599
  60. package/src/traeClient.js +356 -360
  61. package/src/traeGateway.js +875 -875
  62. package/src/traeLocal.js +463 -371
  63. package/src/transfer.js +4 -0
  64. package/src/usageSync.js +535 -523
  65. package/src/winProc.js +134 -134
  66. package/src/xiaomiMimoClient.js +206 -206
  67. package/src/zcodeAuth.js +131 -131
  68. package/src/zcodeGateway.js +850 -850
  69. package/src/zcodeLocal.js +340 -340
  70. package/src/zcrypto.js +160 -160
@@ -0,0 +1,517 @@
1
+ /**
2
+ * DuMate 百度搭子(console.bce.baidu.com / dumate.cn)网页会话与每日登录积分领取。
3
+ *
4
+ * 协议与 10Router PR #113(open-sse/services/dumate.js 及 dumateCheckin.js)完全对齐:
5
+ * 1. 网关 token 换取(验证会话连通性):
6
+ * GET https://console.bce.baidu.com/api/dumate/app/token/get
7
+ * - 带 Cookie 头(需含 BDUSS 与 bce-user-info)
8
+ * - 成功返回 { code: 0, success: true, result: { token, expired_at } }
9
+ * - 失败(重定向到登录页、返回 HTML 登录页或 JSON message 含“过期/登录”)判为会话失效
10
+ * 2. 每日登录积分领取:
11
+ * POST https://console.bce.baidu.com/api/dumate/points/loginBonus
12
+ * - 请求头带 csrftoken(从 bce-user-info 解码取得)、Cookie、Origin/Referer
13
+ * - 接口自带幂等,成功返回 { code: 0, success: true }
14
+ * 3. 凭据 = 百度控制台会话 Cookie(支持 raw Cookie 字符串或 JSON array),
15
+ * 捕获后可直接同步至 10Router(映射为 dumate 连接,以 Cookie 作为 apiKey)。
16
+ */
17
+
18
+ import { fetchJsonRace } from './zcodeClient.js';
19
+ import { FETCH_TIMEOUT_MS } from './constants.js';
20
+ import { t } from './i18n.js';
21
+
22
+ export const DUMATE_CONSOLE_ORIGIN = 'https://console.bce.baidu.com';
23
+ export const DUMATE_CONSOLE_HOST = 'console.bce.baidu.com';
24
+ export const DUMATE_TOKEN_URL = `${DUMATE_CONSOLE_ORIGIN}/api/dumate/app/token/get`;
25
+ export const DUMATE_LOGIN_BONUS_URL = `${DUMATE_CONSOLE_ORIGIN}/api/dumate/points/loginBonus`;
26
+ export const DUMATE_QUOTA_OVERVIEW_URL = `${DUMATE_CONSOLE_ORIGIN}/api/dumate/points/quota_overview`;
27
+ export const DUMATE_USER_INFO_URL = `${DUMATE_CONSOLE_ORIGIN}/api/dumate/user/info`;
28
+ export const DUMATE_INVITE_GET_URL = `${DUMATE_CONSOLE_ORIGIN}/api/dumate/invitation_code/get`;
29
+ export const DUMATE_INVITE_REDEEM_URL = `${DUMATE_CONSOLE_ORIGIN}/api/dumate/invitation_code/redeem`;
30
+ export const DUMATE_INVITED_COUNT_URL = `${DUMATE_CONSOLE_ORIGIN}/api/dumate/invitation_code/invited/count`;
31
+ /** 个人版官网(邀请分享链接同客户端口径) */
32
+ export const DUMATE_HOME_URL = 'https://www.dumate.cn/?track=yqyl';
33
+ /** 个人版登录入口(客户端 login-config 现网值,from=oa_dumate 标记个人版渠道) */
34
+ export const DUMATE_LOGIN_URL = 'https://login.bce.baidu.com/?from=oa_dumate&redirect=https%3A%2F%2Fconsole.bce.baidu.com%2F';
35
+ export const DUMATE_USER_AGENT =
36
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36';
37
+
38
+ function normCookie(c) {
39
+ return { name: String(c.name), value: String(c.value ?? ''), domain: String(c.domain || '') };
40
+ }
41
+
42
+ /**
43
+ * 将传入的 Cookie 凭据(字符串、JSON 数组或包含 cookies 的对象)归一化为 [{ name, value, domain }]
44
+ */
45
+ export function parseDumateCookies(input) {
46
+ if (!input) return [];
47
+ if (Array.isArray(input)) return input.filter((c) => c && c.name).map(normCookie);
48
+ if (typeof input === 'object') return Array.isArray(input.cookies) ? parseDumateCookies(input.cookies) : [];
49
+ const text = String(input).trim();
50
+ if (!text) return [];
51
+ if (text.startsWith('[') || text.startsWith('{')) {
52
+ try {
53
+ return parseDumateCookies(JSON.parse(text));
54
+ } catch {
55
+ return [];
56
+ }
57
+ }
58
+ const raw = text.replace(/^cookie:\s*/i, '');
59
+ return raw
60
+ .split(';')
61
+ .map((part) => part.trim())
62
+ .filter(Boolean)
63
+ .map((part) => {
64
+ const eq = part.indexOf('=');
65
+ if (eq <= 0) return null;
66
+ return { name: part.slice(0, eq).trim(), value: part.slice(eq + 1).trim(), domain: '' };
67
+ })
68
+ .filter(Boolean);
69
+ }
70
+
71
+ function domainMatches(cookie, host) {
72
+ if (!cookie.domain) return true;
73
+ const d = cookie.domain.replace(/^\./, '');
74
+ return host === d || host.endsWith(`.${d}`);
75
+ }
76
+
77
+ /** 按目标 host 生成过滤后的 Cookie 头字符串 */
78
+ export function buildDumateCookieHeader(cookies, host = DUMATE_CONSOLE_HOST) {
79
+ const list = Array.isArray(cookies) ? cookies : parseDumateCookies(cookies);
80
+ return list
81
+ .filter((c) => c.name && domainMatches(c, host))
82
+ .map((c) => `${c.name}=${c.value}`)
83
+ .join('; ');
84
+ }
85
+
86
+ /**
87
+ * 从 bce-user-info Cookie 提取 csrftoken(URL 解码并去除两边引号)
88
+ */
89
+ export function extractDumateCsrfToken(cookies, host = DUMATE_CONSOLE_HOST) {
90
+ const list = Array.isArray(cookies) ? cookies : parseDumateCookies(cookies);
91
+ const c = list.find((x) => x.name === 'bce-user-info' && domainMatches(x, host));
92
+ if (!c?.value) return '';
93
+ let v = c.value;
94
+ try {
95
+ v = decodeURIComponent(v);
96
+ } catch {
97
+ /* keep raw */
98
+ }
99
+ return v.replace(/^["']+|["']+$/g, '');
100
+ }
101
+
102
+ /**
103
+ * 从 bce-user-info 中提取标识 ID(若包含形如 timestamp|userId 则提取后半段)
104
+ */
105
+ export function extractDumateUserId(cookies) {
106
+ const token = extractDumateCsrfToken(cookies);
107
+ if (!token) return null;
108
+ const parts = token.split('|');
109
+ if (parts.length >= 2 && parts[1]) {
110
+ return parts[1].trim();
111
+ }
112
+ return token;
113
+ }
114
+
115
+ /**
116
+ * 补齐 bce-user-info:扫码登录、本机导入拿到的会话常常只有 BDUSS / bce-sessionid,
117
+ * 而领取接口需要 csrftoken,其值就是 bce-user-info 的原文(等于 bce 账户 ID)。
118
+ * 控制台首页不一定下发该 cookie,这里调 /api/dumate/app/token/get,
119
+ * 从 Set-Cookie 的 bce-login-accountid 取账户 ID 补上。
120
+ * @returns {Promise<Array|null>} 补好后的 cookie 数组;无需补或失败返回 null
121
+ */
122
+ export async function healDumateCookies(cookies, fetchImpl) {
123
+ const list = Array.isArray(cookies) ? cookies : parseDumateCookies(cookies);
124
+ if (list.some((c) => c.name === 'bce-user-info' && c.value)) return null;
125
+ const doIt = fetchImpl || ((u, init) => fetchJsonRace(u, { ...init, timeoutMs: FETCH_TIMEOUT_MS }));
126
+ try {
127
+ const res = await doIt(`${DUMATE_CONSOLE_ORIGIN}/api/dumate/app/token/get`, {
128
+ method: 'GET',
129
+ headers: {
130
+ Cookie: buildDumateCookieHeader(list),
131
+ Accept: 'application/json',
132
+ Origin: DUMATE_CONSOLE_ORIGIN,
133
+ Referer: `${DUMATE_CONSOLE_ORIGIN}/dumate/channel`,
134
+ 'User-Agent': DUMATE_USER_AGENT,
135
+ },
136
+ redirect: 'manual',
137
+ });
138
+ if (res.status < 200 || res.status >= 300) return null;
139
+ const raw = typeof res.headers?.getSetCookie === 'function' ? res.headers.getSetCookie() : [];
140
+ const extra = [];
141
+ let accountId = '';
142
+ for (const item of raw) {
143
+ const [pair] = String(item).split(';');
144
+ const i = pair.indexOf('=');
145
+ if (i <= 0) continue;
146
+ const name = pair.slice(0, i).trim();
147
+ const value = pair.slice(i + 1).trim();
148
+ if (!name) continue;
149
+ if (name === 'bce-login-accountid') {
150
+ try {
151
+ accountId = decodeURIComponent(value);
152
+ } catch {
153
+ accountId = value;
154
+ }
155
+ }
156
+ extra.push({ name, value, domain: DUMATE_CONSOLE_HOST });
157
+ }
158
+ if (!accountId) return null;
159
+ const kept = list.filter((c) => !extra.some((e) => e.name === c.name));
160
+ return [...kept, ...extra, { name: 'bce-user-info', value: accountId, domain: DUMATE_CONSOLE_HOST }];
161
+ } catch {
162
+ return null;
163
+ }
164
+ }
165
+
166
+ /**
167
+ * 账号脱敏掩码显示
168
+ */
169
+ export function maskDumateUserId(id) {
170
+ const s = String(id ?? '');
171
+ if (s.length >= 7) return s.slice(0, 3) + '****' + s.slice(-3);
172
+ if (s.length >= 4) return s.slice(0, 1) + '****' + s.slice(-1);
173
+ return '****';
174
+ }
175
+
176
+ export function parseConsoleJson(text) {
177
+ try {
178
+ const parsed = JSON.parse(text);
179
+ if (parsed && typeof parsed === 'object') return parsed;
180
+ } catch {
181
+ /* fall through */
182
+ }
183
+ return null;
184
+ }
185
+
186
+ export function consoleMessage(payload) {
187
+ const m = payload?.message;
188
+ if (typeof m === 'string') return m;
189
+ if (m && typeof m === 'object') return m.global || JSON.stringify(m);
190
+ return '';
191
+ }
192
+
193
+ /**
194
+ * 验证百度搭子会话并换取网关 token:
195
+ * @returns {Promise<{ auth: boolean, ok: boolean, token?: string, expiredAt?: string, code?: string|number, error?: string }>}
196
+ */
197
+ export async function verifyDumateSession(credentialInput, { fetchImpl } = {}) {
198
+ const cookies = parseDumateCookies(credentialInput);
199
+ const header = buildDumateCookieHeader(cookies);
200
+ if (!header) {
201
+ return { auth: false, ok: false, error: t('缺少 Cookie(需包含 console.bce.baidu.com 的 Cookie)') };
202
+ }
203
+ const doIt = fetchImpl || ((u, init) => fetchJsonRace(u, { ...init, timeoutMs: FETCH_TIMEOUT_MS }));
204
+
205
+ try {
206
+ const res = await doIt(DUMATE_TOKEN_URL, {
207
+ method: 'GET',
208
+ headers: {
209
+ Cookie: header,
210
+ 'User-Agent': DUMATE_USER_AGENT,
211
+ Accept: 'application/json',
212
+ Referer: `${DUMATE_CONSOLE_ORIGIN}/`,
213
+ },
214
+ redirect: 'manual',
215
+ });
216
+
217
+ if (res.status >= 300 && res.status < 400) {
218
+ return { auth: false, ok: false, error: t('DuMate 登录态已失效(控制台重定向到登录页)') };
219
+ }
220
+
221
+ const text = await res.text().catch(() => '');
222
+ const payload = parseConsoleJson(text);
223
+ if (!payload) {
224
+ return { auth: false, ok: false, error: t('DuMate 登录态已失效(控制台返回登录页)') };
225
+ }
226
+
227
+ const msg = consoleMessage(payload);
228
+ if (payload.code !== 0 || payload.success === false || !payload.result?.token) {
229
+ const expired = /登录|过期|login/i.test(msg);
230
+ return { auth: !expired, ok: false, code: payload.code, error: msg || `code=${payload.code}` };
231
+ }
232
+
233
+ return {
234
+ auth: true,
235
+ ok: true,
236
+ token: payload.result.token,
237
+ expiredAt: payload.result.expired_at,
238
+ };
239
+ } catch (err) {
240
+ return { auth: true, ok: false, error: err?.message || t('网络请求异常') };
241
+ }
242
+ }
243
+
244
+ /**
245
+ * 每日领取登录积分:
246
+ * @returns {Promise<{ status: 'checked-in'|'already'|'failed', claimedAmount?: number, message?: string, error?: string, authExpired?: boolean }>}
247
+ */
248
+ export async function checkinDumate(account, { fetchImpl, persistCookieJar } = {}) {
249
+ const cookie = account?.meta?.cookieSiteSession?.cookie || account?.token || '';
250
+ let cookies = parseDumateCookies(cookie);
251
+ let csrftoken = extractDumateCsrfToken(cookies);
252
+
253
+ // 会话里缺 bce-user-info 时先补齐(扫码登录、本机导入常见)
254
+ if (!csrftoken) {
255
+ const healed = await healDumateCookies(cookies, fetchImpl).catch(() => null);
256
+ if (healed) {
257
+ cookies = healed;
258
+ csrftoken = extractDumateCsrfToken(cookies);
259
+ // heal 出的完整罐回写账号库(persistCookieJar 由 refreshContext 提供)——
260
+ // 不落库的话每次领取都得现补一轮 token/get
261
+ if (typeof persistCookieJar === 'function') {
262
+ try { await persistCookieJar(buildDumateCookieHeader(cookies)); } catch { /* 回写失败不阻断领取 */ }
263
+ }
264
+ }
265
+ }
266
+
267
+ if (!csrftoken) {
268
+ return { status: 'failed', error: t('Cookie 缺少 bce-user-info(无法生成 csrftoken)') };
269
+ }
270
+
271
+ const doIt = fetchImpl || ((u, init) => fetchJsonRace(u, { ...init, timeoutMs: FETCH_TIMEOUT_MS }));
272
+
273
+ try {
274
+ const res = await doIt(DUMATE_LOGIN_BONUS_URL, {
275
+ method: 'POST',
276
+ headers: {
277
+ Cookie: buildDumateCookieHeader(cookies),
278
+ csrftoken,
279
+ 'Content-Type': 'application/json',
280
+ Accept: 'application/json',
281
+ 'X-Requested-With': 'XMLHttpRequest',
282
+ Origin: DUMATE_CONSOLE_ORIGIN,
283
+ Referer: `${DUMATE_CONSOLE_ORIGIN}/`,
284
+ 'User-Agent': DUMATE_USER_AGENT,
285
+ },
286
+ body: '{}',
287
+ redirect: 'manual',
288
+ });
289
+
290
+ if (res.status >= 300 && res.status < 400) {
291
+ return { status: 'failed', error: t('登录态已失效(重定向到登录页)'), authExpired: true };
292
+ }
293
+
294
+ const text = await res.text().catch(() => '');
295
+ const payload = parseConsoleJson(text);
296
+ if (!payload) {
297
+ return { status: 'failed', error: t('登录态已失效(控制台返回登录页)'), authExpired: true };
298
+ }
299
+
300
+ if (payload.success === true && payload.code === 0) {
301
+ return {
302
+ status: 'checked-in',
303
+ message: t('已领取今日登录赠送积分'),
304
+ };
305
+ }
306
+
307
+ const msg = consoleMessage(payload);
308
+ const expired = /登录|过期|login/i.test(msg);
309
+ return {
310
+ status: 'failed',
311
+ error: msg || `code=${payload.code}`,
312
+ authExpired: expired,
313
+ };
314
+ } catch (err) {
315
+ return { status: 'failed', error: err?.message || t('网络请求异常') };
316
+ }
317
+ }
318
+
319
+ /** 个人版控制台请求头(Cookie + csrftoken,与客户端 bceConsoleRequest 同口径) */
320
+ export function dumateConsoleHeaders(credentialInput, { json = false } = {}) {
321
+ const cookies = parseDumateCookies(credentialInput);
322
+ const h = {
323
+ Cookie: buildDumateCookieHeader(cookies),
324
+ Accept: 'application/json',
325
+ 'User-Agent': DUMATE_USER_AGENT,
326
+ Origin: DUMATE_CONSOLE_ORIGIN,
327
+ Referer: `${DUMATE_CONSOLE_ORIGIN}/`,
328
+ 'X-Requested-With': 'XMLHttpRequest',
329
+ };
330
+ const csrf = extractDumateCsrfToken(cookies);
331
+ if (csrf) h.csrftoken = csrf;
332
+ if (json) h['Content-Type'] = 'application/json';
333
+ return h;
334
+ }
335
+
336
+ /**
337
+ * 个人版身份:GET /api/dumate/user/info → { bceUserId, displayName, userId, firstLoginBonus }
338
+ * @returns {Promise<{auth: boolean, ok: boolean, uid?: string, displayName?: string, code?: string|number, error?: string}>}
339
+ */
340
+ export async function fetchDumateIdentity(credentialInput, { fetchImpl } = {}) {
341
+ const doIt = fetchImpl || ((u, init) => fetchJsonRace(u, { ...init, timeoutMs: FETCH_TIMEOUT_MS }));
342
+ try {
343
+ const res = await doIt(DUMATE_USER_INFO_URL, { method: 'GET', headers: dumateConsoleHeaders(credentialInput), redirect: 'manual' });
344
+ if (res.status >= 300 && res.status < 400) return { auth: false, ok: false, error: t('DuMate 登录态已失效(控制台重定向到登录页)') };
345
+ const payload = parseConsoleJson(await res.text().catch(() => ''));
346
+ if (!payload) return { auth: false, ok: false, error: t('DuMate 登录态已失效(控制台返回登录页)') };
347
+ if (payload.code !== 0 || payload.success === false) {
348
+ const msg = consoleMessage(payload);
349
+ return { auth: !/登录|过期|login/i.test(msg), ok: false, code: payload.code, error: msg || `code=${payload.code}` };
350
+ }
351
+ const r = payload.result || {};
352
+ return { auth: true, ok: true, uid: r.bceUserId || r.userId || null, displayName: r.displayName || null };
353
+ } catch (err) {
354
+ return { auth: true, ok: false, error: err?.message || t('网络请求异常') };
355
+ }
356
+ }
357
+
358
+ /**
359
+ * 我的邀请码:GET /api/dumate/invitation_code/get → { invitationCode, type, activityId }
360
+ */
361
+ export async function fetchDumateMyInviteCode(credentialInput, { fetchImpl } = {}) {
362
+ const doIt = fetchImpl || ((u, init) => fetchJsonRace(u, { ...init, timeoutMs: FETCH_TIMEOUT_MS }));
363
+ try {
364
+ const res = await doIt(DUMATE_INVITE_GET_URL, { method: 'GET', headers: dumateConsoleHeaders(credentialInput), redirect: 'manual' });
365
+ if (res.status >= 300 && res.status < 400) return { auth: false, ok: false, error: t('DuMate 登录态已失效(控制台重定向到登录页)') };
366
+ const payload = parseConsoleJson(await res.text().catch(() => ''));
367
+ if (!payload) return { auth: false, ok: false, error: t('DuMate 登录态已失效(控制台返回登录页)') };
368
+ if (payload.code !== 0 || payload.success === false) {
369
+ const msg = consoleMessage(payload);
370
+ return { auth: !/登录|过期|login/i.test(msg), ok: false, code: payload.code, error: msg || `code=${payload.code}` };
371
+ }
372
+ return { auth: true, ok: true, code: payload.result?.invitationCode || null, type: payload.result?.type || null, activityId: payload.result?.activityId || null };
373
+ } catch (err) {
374
+ return { auth: true, ok: false, error: err?.message || t('网络请求异常') };
375
+ }
376
+ }
377
+
378
+ /**
379
+ * 兑换邀请码:POST /api/dumate/invitation_code/redeem
380
+ * body 与客户端同口径:{ invitationCode, timezone, source: 'pc' }(双方各 +2000 积分,每号仅一次)
381
+ */
382
+ export async function redeemDumateInviteCode(credentialInput, code, { fetchImpl } = {}) {
383
+ const clean = String(code || '').trim();
384
+ if (!clean) return { ok: false, error: t('邀请码不能为空') };
385
+ const doIt = fetchImpl || ((u, init) => fetchJsonRace(u, { ...init, timeoutMs: FETCH_TIMEOUT_MS }));
386
+ try {
387
+ const res = await doIt(DUMATE_INVITE_REDEEM_URL, {
388
+ method: 'POST',
389
+ headers: dumateConsoleHeaders(credentialInput, { json: true }),
390
+ body: JSON.stringify({ invitationCode: clean, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, source: 'pc' }),
391
+ redirect: 'manual',
392
+ });
393
+ if (res.status >= 300 && res.status < 400) return { ok: false, authExpired: true, error: t('登录态已失效(重定向到登录页)') };
394
+ const payload = parseConsoleJson(await res.text().catch(() => ''));
395
+ if (!payload) return { ok: false, authExpired: true, error: t('登录态已失效(控制台返回登录页)') };
396
+ if (payload.code !== 0 || payload.success === false) {
397
+ const msg = consoleMessage(payload);
398
+ return { ok: false, authExpired: /登录|过期|login/i.test(msg), error: msg || `code=${payload.code}` };
399
+ }
400
+ return { ok: true, message: typeof payload.message === 'string' ? payload.message : '', result: payload.result ?? null };
401
+ } catch (err) {
402
+ return { ok: false, error: err?.message || t('网络请求异常') };
403
+ }
404
+ }
405
+
406
+ /**
407
+ * 额度查询(DuMate 个人版积分概览)
408
+ * 对齐客户端积分明细(quota_overview 接口):
409
+ * - 订阅积分(subscription)
410
+ * - 赠送积分(login_bonus / event_bonus 等)
411
+ * - 增购积分(plan_point)
412
+ * - 最近到期时间(nearestExpiryPackage)
413
+ */
414
+ export async function fetchDumateQuota(account, { fetchImpl } = {}) {
415
+ const cookie = account?.meta?.cookieSiteSession?.cookie || account?.token || '';
416
+ const doIt = fetchImpl || ((u, init) => fetchJsonRace(u, { ...init, timeoutMs: FETCH_TIMEOUT_MS }));
417
+
418
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || 'Asia/Shanghai';
419
+ const url = `${DUMATE_QUOTA_OVERVIEW_URL}?timezone=${encodeURIComponent(tz)}&clientType=desktop&ignoreLoginBonus=true`;
420
+
421
+ const res = await doIt(url, {
422
+ method: 'GET',
423
+ headers: dumateConsoleHeaders(cookie),
424
+ redirect: 'manual',
425
+ });
426
+
427
+ if (res.status >= 300 && res.status < 400) {
428
+ const err = new Error(t('DuMate 登录态已失效(控制台重定向到登录页)'));
429
+ err.auth = true;
430
+ throw err;
431
+ }
432
+
433
+ const text = await res.text().catch(() => '');
434
+ const payload = parseConsoleJson(text);
435
+ if (!payload) {
436
+ const err = new Error(t('DuMate 登录态已失效(控制台返回登录页)'));
437
+ err.auth = true;
438
+ throw err;
439
+ }
440
+
441
+ if (payload.code !== 0 || payload.success === false) {
442
+ const msg = consoleMessage(payload);
443
+ const expired = /登录|过期|login/i.test(msg);
444
+ const err = new Error(msg || `code=${payload.code}`);
445
+ err.auth = expired;
446
+ throw err;
447
+ }
448
+
449
+ const r = payload.result || {};
450
+ const total = parseFloat(r.totalPoints) || 0;
451
+ const used = parseFloat(r.usedPoints) || 0;
452
+ const remaining = Math.max(0, total - used);
453
+
454
+ const parts = [];
455
+ const subs = Array.isArray(r.subscription) ? r.subscription.filter((s) => s.status === 'active') : [];
456
+ const incs = Array.isArray(r.incremental) ? r.incremental.filter((s) => s.status === 'active') : [];
457
+
458
+ const fmtDate = (sec) => (Number(sec) > 0 ? new Date(sec * 1000).toISOString() : null);
459
+
460
+ for (const s of subs) {
461
+ const pTotal = parseFloat(s.totalPoints) || 0;
462
+ const pUsed = parseFloat(s.usedPoints) || 0;
463
+ const pRem = Math.max(0, pTotal - pUsed);
464
+ parts.push({
465
+ name: s.packageType === 'plan_experience' ? t('体验版订阅积分') : t('订阅积分'),
466
+ total: pTotal,
467
+ used: pUsed,
468
+ remaining: pRem,
469
+ recurring: true,
470
+ expiresAt: fmtDate(s.pointsExpireDate || s.expireDate),
471
+ });
472
+ }
473
+
474
+ for (const s of incs) {
475
+ const pTotal = parseFloat(s.totalPoints) || 0;
476
+ const pUsed = parseFloat(s.usedPoints) || 0;
477
+ const pRem = Math.max(0, pTotal - pUsed);
478
+ const isLoginBonus = s.source === 'login_bonus';
479
+ const isGrant = s.packageType === 'grant_point' || s.packageType === 'event_bonus';
480
+ const name = isLoginBonus ? t('登录赠送积分') : (isGrant ? t('赠送积分') : t('增购积分'));
481
+ parts.push({
482
+ name,
483
+ total: pTotal,
484
+ used: pUsed,
485
+ remaining: pRem,
486
+ recurring: false,
487
+ expiresAt: fmtDate(s.pointsExpireDate || s.expireDate),
488
+ });
489
+ }
490
+
491
+ // 找最近到期包的到期时间
492
+ let nearestExp = null;
493
+ const allActive = [...subs, ...incs].filter((p) => p.pointsExpireDate || p.expireDate);
494
+ allActive.sort((a, b) => (a.pointsExpireDate || a.expireDate) - (b.pointsExpireDate || b.expireDate));
495
+ if (allActive.length > 0) {
496
+ nearestExp = fmtDate(allActive[0].pointsExpireDate || allActive[0].expireDate);
497
+ }
498
+
499
+ // 付费套餐(客户端同款 currentPlanType 口径):plan_pro / plan_max / plan_team = 付费,
500
+ // plan_experience = 免费体验版不出徽章。取档位最高的一单。
501
+ const PLAN_RANK = { plan_max: 3, plan_pro: 2, plan_team: 2 };
502
+ const PLAN_LABEL = { plan_max: 'Max', plan_pro: 'PRO', plan_team: 'Team' };
503
+ const topPaid = [...subs].sort((a, b) => (PLAN_RANK[b.packageType] || 0) - (PLAN_RANK[a.packageType] || 0))[0];
504
+ const plan = topPaid && PLAN_RANK[topPaid.packageType] ? PLAN_LABEL[topPaid.packageType] : null;
505
+
506
+ return {
507
+ unit: '积分',
508
+ total,
509
+ used,
510
+ remaining,
511
+ parts: parts.length > 0 ? parts : [{ name: t('可用积分'), total, used, remaining }],
512
+ expiresAt: nearestExp,
513
+ exceeded: remaining <= 0,
514
+ plan,
515
+ planExpiresAt: topPaid ? fmtDate(topPaid.expireDate || topPaid.pointsExpireDate) : null,
516
+ };
517
+ }