creditdaddy 1.7.1 → 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 (73) 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/authDevice.js +3 -1
  16. package/src/bgdaemon.js +341 -341
  17. package/src/buildInfo.js +65 -32
  18. package/src/catpawClient.js +103 -103
  19. package/src/catpawLocal.js +236 -236
  20. package/src/checkin.js +11 -2
  21. package/src/codebuddyIdeLocal.js +381 -381
  22. package/src/constants.js +121 -116
  23. package/src/cookieSites.js +340 -301
  24. package/src/daemon.js +2682 -2415
  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 +2156 -1980
  32. package/src/i18n/ja.json +2156 -1980
  33. package/src/i18n/ko.json +2156 -1980
  34. package/src/i18n/zh-TW.json +2156 -1980
  35. package/src/i18n.js +47 -47
  36. package/src/lingxiClient.js +373 -332
  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/minimaxClient.js +86 -28
  45. package/src/minimaxGateway.js +520 -520
  46. package/src/minimaxLocal.js +344 -322
  47. package/src/mirasimClient.js +211 -211
  48. package/src/mirasimLocal.js +392 -392
  49. package/src/modelscopeClient.js +275 -275
  50. package/src/panel.html +5964 -5528
  51. package/src/prodIcons.json +7 -5
  52. package/src/providers.js +52 -4
  53. package/src/qoderApp.js +578 -578
  54. package/src/qoderClient.js +266 -266
  55. package/src/qoderUmid.js +199 -199
  56. package/src/quotaRefresh.js +119 -119
  57. package/src/refreshGuard.js +75 -75
  58. package/src/riverClient.js +372 -329
  59. package/src/store.js +3 -1
  60. package/src/tenrouterAccounts.js +18 -3
  61. package/src/traeAuth.js +601 -530
  62. package/src/traeClient.js +356 -337
  63. package/src/traeGateway.js +875 -812
  64. package/src/traeLocal.js +463 -371
  65. package/src/transfer.js +24 -1
  66. package/src/usageSync.js +535 -523
  67. package/src/winProc.js +134 -134
  68. package/src/workbuddyLocal.js +35 -4
  69. package/src/xiaomiMimoClient.js +206 -206
  70. package/src/zcodeAuth.js +131 -131
  71. package/src/zcodeGateway.js +850 -850
  72. package/src/zcodeLocal.js +340 -340
  73. package/src/zcrypto.js +160 -160
@@ -1,275 +1,275 @@
1
- /**
2
- * ModelScope 魔搭(modelscope.cn)魔粒(Magicube)余额抓取(CD#25)。
3
- *
4
- * 凭据 = havana 登录会话 cookie(阿里账号体系);API 面走 `<host>/openapi/v1/…`:
5
- * - GET /openapi/v1/magicubes/balance 余额(每日魔粒额度自动发放,无签到动作端点)
6
- * - GET /api/v1/users/login/info 身份 userInfo(Name)
7
- * - GET /api/v1/users/info 身份 accountInfo(email / email_extra[])
8
- * 端点事实源:2026-10-14 前端 chunk 考古(86 chunk 无 claim/signIn POST——「Login Reward」
9
- * 为登录自动入账,「Daily Magicube Rewards!」为入账提示弹层)。
10
- *
11
- * 安全纪律:会话 cookie 只存本机账号库(0600),推 10Router 只带魔粒余额数字。
12
- */
13
-
14
- import { fetchJsonRace } from './zcodeClient.js';
15
- import { FETCH_TIMEOUT_MS } from './constants.js';
16
- import { t } from './i18n.js';
17
- import { snapshotAgeTag } from './externalQuota.js';
18
-
19
- export const MS_BASE = 'https://modelscope.cn';
20
- export const MS_BALANCE_URL = `${MS_BASE}/openapi/v1/magicubes/balance`;
21
- export const MS_TRANSACTIONS_URL = `${MS_BASE}/openapi/v1/magicubes/transactions`;
22
- // 身份走账号体系(前端 axios baseURL = `${host}/api`,非 /openapi)——2026-10-14 端点探测:
23
- // GET /api/v1/users/login/info → Data{Name,…}(initializeUserInfo 源头)
24
- // GET /api/v1/users/info → Data{email, email_extra[],…}(getAccountInfo 源头)
25
- // 注意这两条响应信封是**大写** {Code,Message,Success,Data};magicubes 走 /openapi 是小写。
26
- export const MS_LOGIN_INFO_URL = `${MS_BASE}/api/v1/users/login/info`;
27
- export const MS_USER_INFO_URL = `${MS_BASE}/api/v1/users/info`;
28
-
29
- const MS_UA =
30
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36';
31
-
32
- function msHeaders(cookie) {
33
- return {
34
- Accept: 'application/json, text/plain, */*',
35
- Cookie: String(cookie || '').trim(),
36
- Referer: `${MS_BASE}/magicube/usage?tab=earn`,
37
- 'User-Agent': MS_UA,
38
- };
39
- }
40
-
41
- /**
42
- * 从魔粒余额响应里提取余额数字。事实源(2026-10-14 前端 store 映射):
43
- * `balance: e?.total_balance || 0, available_balance: e?.available_balance || 0`
44
- * 卡面口径对齐官方「My Magicubes」= total_balance(UI 的 balance 即它);
45
- * available_balance 作兜底(可用口径)。其余键为演化兜底。
46
- */
47
- export function parseMagicubeBalance(body) {
48
- const d = body?.data || body?.result || body || {};
49
- const cand = [
50
- d.total_balance, d.totalBalance,
51
- d.available_balance, d.availableBalance,
52
- d.balance, d.amount, d.total, d.magicube, d.magicubes, d.available,
53
- d.balance?.amount, d.balance?.total, body?.balance,
54
- ];
55
- for (const v of cand) {
56
- const n = Number(v);
57
- if (Number.isFinite(n) && n >= 0) return Math.round(n * 100) / 100;
58
- }
59
- return null;
60
- }
61
-
62
- /**
63
- * 身份:`GET /api/v1/users/login/info`(userInfo,Name)+ `GET /api/v1/users/info`
64
- * (accountInfo,`email` / `email_extra[]`——顶栏 findLast(e => e.email === u?.email && e.identity === 'user'))。
65
- * 信封大写 `{Code,Message,Success,Data}`(前端 `accountInfo:(await Yi())?.Data`),兼容小写兜底。
66
- * 宽容解析,抽不到返 null。
67
- */
68
- export function parseMsIdentity(body) {
69
- const d = body?.Data || body?.data || body?.result || body || {};
70
- const id = d.user_id || d.userId || d.id || d.uid || d.UserID || d.UserId || null;
71
- const email = d.email || d.Email || d.user_email || d.mail
72
- || (Array.isArray(d.email_extra) ? (d.email_extra.find((e) => e?.identity === 'user')?.email || d.email_extra[0]?.email) : null)
73
- || null;
74
- const name = d.Name || d.name || d.user_name || d.nick || null;
75
- return { id: id ? String(id) : null, email: email ? String(email) : null, name: name ? String(name) : null };
76
- }
77
-
78
- /**
79
- * 用会话 cookie 探测魔粒余额(捕获验证 + 推卡 live 读共用)。
80
- * 401/403 → 会话失效;200 但解析不出 → 结构变化(分开归类,对齐既有探测口径)。
81
- * @returns {Promise<{ok: boolean, balance?: number, identity?: object, raw?: object, error?: string, status?: number}>}
82
- */
83
- export async function fetchMagicubeBalance(cookie, { fetchImpl } = {}) {
84
- const doFetch = fetchImpl || ((u, init) => fetchJsonRace(u, { headers: init.headers, timeoutMs: FETCH_TIMEOUT_MS, method: init.method }));
85
- try {
86
- const res = await doFetch(MS_BALANCE_URL, { headers: msHeaders(cookie) });
87
- if (res.status === 401 || res.status === 403) return { ok: false, status: res.status, authExpired: true, error: `会话失效(HTTP ${res.status})` };
88
- if (!res.ok) return { ok: false, status: res.status, error: `HTTP ${res.status}` };
89
- const body = await res.json().catch(() => null);
90
- const balance = parseMagicubeBalance(body);
91
- if (balance === null) {
92
- // 失败时把响应字段名带进错误(只记键名不记值)——字段演化时一眼定位
93
- const keys = Object.keys(body?.data && typeof body.data === 'object' ? body.data : body || {}).slice(0, 12).join(',');
94
- return { ok: false, status: res.status, error: `未能从响应中提取魔粒余额(响应字段:${keys || '空'})`, raw: body };
95
- }
96
- // 身份尽力而为:users/login/info(Name)+ users/info(email/email_extra)双向合并;失败不挡余额
97
- let identity = null;
98
- for (const url of [MS_LOGIN_INFO_URL, MS_USER_INFO_URL]) {
99
- try {
100
- const r2 = await doFetch(url, { method: 'GET', headers: msHeaders(cookie) });
101
- if (!r2.ok) continue;
102
- const b2 = await r2.json().catch(() => null);
103
- const parsed = parseMsIdentity(b2);
104
- const keys = Object.keys(b2?.Data && typeof b2.Data === 'object' ? b2.Data : b2?.data && typeof b2.data === 'object' ? b2.data : b2 || {}).slice(0, 12).join(',');
105
- // 合并而非首中即停:login/info 带 Name、users/info 带 email——互补
106
- identity = {
107
- id: identity?.id || parsed.id || null,
108
- email: identity?.email || parsed.email || null,
109
- name: identity?.name || parsed.name || null,
110
- keys: [identity?.keys, keys].filter(Boolean).join(' | '),
111
- };
112
- if (identity.email && identity.name && identity.id) break;
113
- } catch { /* 下一个兜底 */ }
114
- }
115
- return { ok: true, balance, identity, raw: body };
116
- } catch (e) {
117
- return { ok: false, error: e?.message || String(e) };
118
- }
119
- }
120
-
121
- /**
122
- * 发放记录(transactions)→ 今日/长期拆分。项形(2026-10-14 前端映射):
123
- * { type: 'EARN' | 'SPEND_CONFIRM' | 'EXPIRE', expire_days, total_amount ?? amount, date | gmt_created }
124
- * 有效期字段是 **expire_days**(前端行渲染 `e.expire_days>1 ? 有效期{days}天 : 有效期{day}天`)——
125
- * 缺失按未知处理(归长期),绝不折算成 1 天误吞进今日。
126
- * 口径:**今日发放** = 今日获得且 `expire_days<=1` 的 EARN 之和(官方「每日发放 有效期1天」);
127
- * **长期** = total_balance − 今日(吸收消耗/过期误差,与官方发放记录页对得上:300 = 200 + 50 + 50)。
128
- */
129
- export function parseMagicubeLedger(items, totalBalance, now = Date.now()) {
130
- const list = Array.isArray(items) ? items : [];
131
- const d0 = new Date(now);
132
- const todayStr = `${d0.getFullYear()}-${String(d0.getMonth() + 1).padStart(2, '0')}-${String(d0.getDate()).padStart(2, '0')}`;
133
- let today = 0;
134
- for (const it of list) {
135
- if (!it || it.type !== 'EARN') continue;
136
- const days = Number(it.expire_days ?? it.days);
137
- const amt = Number(it.total_amount ?? it.amount);
138
- // 仅 (0,1] 天有效才算今日发放;expire_days=0(长期有效)/缺失/90 天均归长期
139
- if (!Number.isFinite(days) || days <= 0 || days > 1 || !Number.isFinite(amt) || amt < 0) continue;
140
- const day = String(it.date || it.gmt_created || '').split(' ')[0].split('T')[0].trim();
141
- if (day === todayStr) today += amt;
142
- }
143
- const total = Number(totalBalance);
144
- if (Number.isFinite(total)) today = Math.min(today, Math.max(0, total));
145
- return { today: Math.round(today * 100) / 100, long: Number.isFinite(total) ? Math.round(Math.max(0, total - today) * 100) / 100 : null };
146
- }
147
-
148
- /** 发放记录拉取(拆分用,fail-soft:失败返回 null,卡面回退单值) */
149
- export async function fetchMagicubeLedger(cookie, totalBalance, { fetchImpl } = {}) {
150
- const doFetch = fetchImpl || ((u, init) => fetchJsonRace(u, { headers: init.headers, timeoutMs: FETCH_TIMEOUT_MS }));
151
- try {
152
- const res = await doFetch(`${MS_TRANSACTIONS_URL}?page=1&page_size=50`, { headers: msHeaders(cookie) });
153
- if (!res.ok) return null;
154
- const body = await res.json().catch(() => null);
155
- const d = body?.data;
156
- const items = Array.isArray(d) ? d : (d?.list || d?.records || d?.items || body?.list || body?.records || []);
157
- return parseMagicubeLedger(items, totalBalance);
158
- } catch { return null; }
159
- }
160
-
161
- /**
162
- * 一次跑齐「余额 + 身份 + 流水拆分」——捕获入库与就地重探共用。
163
- * @returns {Promise<{ok: boolean, error?: string, status?: number, balance?: number,
164
- * identity?: string|null, keys?: string, msSession?: object, msBalance?: object, ledger?: object}>}
165
- */
166
- export async function probeMagicubeSession(cookie, { fetchImpl } = {}) {
167
- const bal = await fetchMagicubeBalance(cookie, { fetchImpl });
168
- if (!bal.ok) return { ok: false, error: bal.error, status: bal.status };
169
- const ledger = await fetchMagicubeLedger(cookie, bal.balance, { fetchImpl }).catch(() => null);
170
- const s = bal.identity || {};
171
- const hasIdentity = Boolean(s.id || s.email || s.name);
172
- return {
173
- ok: true,
174
- balance: bal.balance,
175
- identity: s.email || s.name || s.id || null,
176
- keys: s.keys || '',
177
- msSession: hasIdentity ? s : {},
178
- ledger,
179
- msBalance: {
180
- amount: bal.balance,
181
- today: ledger?.today ?? null,
182
- long: ledger?.long ?? null,
183
- at: new Date().toISOString(),
184
- },
185
- };
186
- }
187
-
188
- /**
189
- * 组装 ModelScope 魔粒余额的 10Router external-quota 载荷(储值计数卡)。
190
- * 有拆分时:汇总行名 = 副标题「今日发放 X · 长期 Y (魔粒)」+ 逐包明细两腿(今日 1 天有效 / 长期);
191
- * 无拆分回退单值行。label = 账号别名(10R「同名认领」匹配键)。
192
- * @param {object} account
193
- * @param {{ balance?: number, ledger?: object, error?: string, authInvalid?: boolean }} [liveData]
194
- * authInvalid = live 拉取明确 401/403(魔搭会话失效)——不回退旧快照,降级 message 状态卡
195
- */
196
- export function buildModelScopeQuotaPayload(account, liveData = null) {
197
- const sess = account?.meta?.msSession || {};
198
- const userId = account?.uid || sess.id || '';
199
- const short = String(userId).toLowerCase().replace(/[^a-z0-9-]/g, '').slice(0, 24);
200
- const source = short ? `modelscope-${short}`.slice(0, 32) : `modelscope-${(account?.id || 'default').slice(0, 24)}`;
201
- const nameStr = String(account?.name || '').trim();
202
- const email = sess.email || /[\w.+-]+@[\w-]+\.[\w.]+/.exec(nameStr)?.[0] || '';
203
-
204
- if (liveData?.authInvalid) {
205
- return {
206
- source,
207
- payload: {
208
- provider: 'modelscope',
209
- label: (nameStr || (email ? `ModelScope (${email})` : 'ModelScope')).slice(0, 100),
210
- message: liveData.error || t('ModelScope 会话已失效,请在 CreditDaddy「网页会话」页重新登录捕获'),
211
- },
212
- };
213
- }
214
-
215
- let balance = liveData?.balance;
216
- let ageTag = '';
217
- if (!Number.isFinite(balance)) {
218
- const snap = account?.meta?.quotaSnapshot;
219
- balance = Number(snap?.total ?? account?.meta?.msBalance?.amount);
220
- // 快照回退(非 live):距今 >24h 的陈粮在副标题标注数据时刻(可见性兜底)
221
- ageTag = snapshotAgeTag(snap?.at ? snap : account?.meta?.msBalance);
222
- }
223
- const ledger = liveData?.ledger || account?.meta?.msBalance || null;
224
-
225
- // label = 账号别名(用户可改)——10R「同名认领」的匹配键
226
- const label = (nameStr || (email ? `ModelScope (${email})` : 'ModelScope')).slice(0, 100);
227
- const payload = {
228
- provider: 'modelscope',
229
- label,
230
- plan: t('魔粒余额') + ageTag,
231
- };
232
-
233
- if (Number.isFinite(balance) && balance >= 0) {
234
- const total = Math.max(0, balance) || 0.000001;
235
- const hasSplit = ledger && Number.isFinite(ledger.today) && Number.isFinite(ledger.long);
236
- const name = hasSplit
237
- ? t('今日发放 {today} · 长期 {long} (魔粒)', { today: Number(ledger.today).toFixed(0), long: Number(ledger.long).toFixed(0) })
238
- : t('魔粒余额(个)');
239
- payload.quotas = {
240
- Balance: {
241
- name,
242
- used: 0,
243
- total,
244
- remainingPercentage: balance > 0 ? 100 : 0,
245
- displayRemaining: true,
246
- isCreditBalance: true,
247
- summarizesDetail: true,
248
- },
249
- };
250
- if (hasSplit) {
251
- payload.quotas.Today = {
252
- name: t('今日发放(1 天有效)'),
253
- used: 0,
254
- total: Math.max(0.000001, Number(ledger.today) || 0.000001),
255
- remainingPercentage: Number(ledger.today) > 0 ? 100 : 0,
256
- displayRemaining: true,
257
- isCreditBalance: true,
258
- detailOnly: true,
259
- };
260
- payload.quotas.LongTerm = {
261
- name: t('长期余额'),
262
- used: 0,
263
- total: Math.max(0.000001, Number(ledger.long) || 0.000001),
264
- remainingPercentage: Number(ledger.long) > 0 ? 100 : 0,
265
- displayRemaining: true,
266
- isCreditBalance: true,
267
- detailOnly: true,
268
- };
269
- }
270
- } else {
271
- payload.message = liveData?.error || t('ModelScope 会话已失效,请在 CreditDaddy「网页会话」页重新登录捕获');
272
- }
273
-
274
- return { source, payload };
275
- }
1
+ /**
2
+ * ModelScope 魔搭(modelscope.cn)魔粒(Magicube)余额抓取(CD#25)。
3
+ *
4
+ * 凭据 = havana 登录会话 cookie(阿里账号体系);API 面走 `<host>/openapi/v1/…`:
5
+ * - GET /openapi/v1/magicubes/balance 余额(每日魔粒额度自动发放,无签到动作端点)
6
+ * - GET /api/v1/users/login/info 身份 userInfo(Name)
7
+ * - GET /api/v1/users/info 身份 accountInfo(email / email_extra[])
8
+ * 端点事实源:2026-10-14 前端 chunk 考古(86 chunk 无 claim/signIn POST——「Login Reward」
9
+ * 为登录自动入账,「Daily Magicube Rewards!」为入账提示弹层)。
10
+ *
11
+ * 安全纪律:会话 cookie 只存本机账号库(0600),推 10Router 只带魔粒余额数字。
12
+ */
13
+
14
+ import { fetchJsonRace } from './zcodeClient.js';
15
+ import { FETCH_TIMEOUT_MS } from './constants.js';
16
+ import { t } from './i18n.js';
17
+ import { snapshotAgeTag } from './externalQuota.js';
18
+
19
+ export const MS_BASE = 'https://modelscope.cn';
20
+ export const MS_BALANCE_URL = `${MS_BASE}/openapi/v1/magicubes/balance`;
21
+ export const MS_TRANSACTIONS_URL = `${MS_BASE}/openapi/v1/magicubes/transactions`;
22
+ // 身份走账号体系(前端 axios baseURL = `${host}/api`,非 /openapi)——2026-10-14 端点探测:
23
+ // GET /api/v1/users/login/info → Data{Name,…}(initializeUserInfo 源头)
24
+ // GET /api/v1/users/info → Data{email, email_extra[],…}(getAccountInfo 源头)
25
+ // 注意这两条响应信封是**大写** {Code,Message,Success,Data};magicubes 走 /openapi 是小写。
26
+ export const MS_LOGIN_INFO_URL = `${MS_BASE}/api/v1/users/login/info`;
27
+ export const MS_USER_INFO_URL = `${MS_BASE}/api/v1/users/info`;
28
+
29
+ const MS_UA =
30
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36';
31
+
32
+ function msHeaders(cookie) {
33
+ return {
34
+ Accept: 'application/json, text/plain, */*',
35
+ Cookie: String(cookie || '').trim(),
36
+ Referer: `${MS_BASE}/magicube/usage?tab=earn`,
37
+ 'User-Agent': MS_UA,
38
+ };
39
+ }
40
+
41
+ /**
42
+ * 从魔粒余额响应里提取余额数字。事实源(2026-10-14 前端 store 映射):
43
+ * `balance: e?.total_balance || 0, available_balance: e?.available_balance || 0`
44
+ * 卡面口径对齐官方「My Magicubes」= total_balance(UI 的 balance 即它);
45
+ * available_balance 作兜底(可用口径)。其余键为演化兜底。
46
+ */
47
+ export function parseMagicubeBalance(body) {
48
+ const d = body?.data || body?.result || body || {};
49
+ const cand = [
50
+ d.total_balance, d.totalBalance,
51
+ d.available_balance, d.availableBalance,
52
+ d.balance, d.amount, d.total, d.magicube, d.magicubes, d.available,
53
+ d.balance?.amount, d.balance?.total, body?.balance,
54
+ ];
55
+ for (const v of cand) {
56
+ const n = Number(v);
57
+ if (Number.isFinite(n) && n >= 0) return Math.round(n * 100) / 100;
58
+ }
59
+ return null;
60
+ }
61
+
62
+ /**
63
+ * 身份:`GET /api/v1/users/login/info`(userInfo,Name)+ `GET /api/v1/users/info`
64
+ * (accountInfo,`email` / `email_extra[]`——顶栏 findLast(e => e.email === u?.email && e.identity === 'user'))。
65
+ * 信封大写 `{Code,Message,Success,Data}`(前端 `accountInfo:(await Yi())?.Data`),兼容小写兜底。
66
+ * 宽容解析,抽不到返 null。
67
+ */
68
+ export function parseMsIdentity(body) {
69
+ const d = body?.Data || body?.data || body?.result || body || {};
70
+ const id = d.user_id || d.userId || d.id || d.uid || d.UserID || d.UserId || null;
71
+ const email = d.email || d.Email || d.user_email || d.mail
72
+ || (Array.isArray(d.email_extra) ? (d.email_extra.find((e) => e?.identity === 'user')?.email || d.email_extra[0]?.email) : null)
73
+ || null;
74
+ const name = d.Name || d.name || d.user_name || d.nick || null;
75
+ return { id: id ? String(id) : null, email: email ? String(email) : null, name: name ? String(name) : null };
76
+ }
77
+
78
+ /**
79
+ * 用会话 cookie 探测魔粒余额(捕获验证 + 推卡 live 读共用)。
80
+ * 401/403 → 会话失效;200 但解析不出 → 结构变化(分开归类,对齐既有探测口径)。
81
+ * @returns {Promise<{ok: boolean, balance?: number, identity?: object, raw?: object, error?: string, status?: number}>}
82
+ */
83
+ export async function fetchMagicubeBalance(cookie, { fetchImpl } = {}) {
84
+ const doFetch = fetchImpl || ((u, init) => fetchJsonRace(u, { headers: init.headers, timeoutMs: FETCH_TIMEOUT_MS, method: init.method }));
85
+ try {
86
+ const res = await doFetch(MS_BALANCE_URL, { headers: msHeaders(cookie) });
87
+ if (res.status === 401 || res.status === 403) return { ok: false, status: res.status, authExpired: true, error: `会话失效(HTTP ${res.status})` };
88
+ if (!res.ok) return { ok: false, status: res.status, error: `HTTP ${res.status}` };
89
+ const body = await res.json().catch(() => null);
90
+ const balance = parseMagicubeBalance(body);
91
+ if (balance === null) {
92
+ // 失败时把响应字段名带进错误(只记键名不记值)——字段演化时一眼定位
93
+ const keys = Object.keys(body?.data && typeof body.data === 'object' ? body.data : body || {}).slice(0, 12).join(',');
94
+ return { ok: false, status: res.status, error: `未能从响应中提取魔粒余额(响应字段:${keys || '空'})`, raw: body };
95
+ }
96
+ // 身份尽力而为:users/login/info(Name)+ users/info(email/email_extra)双向合并;失败不挡余额
97
+ let identity = null;
98
+ for (const url of [MS_LOGIN_INFO_URL, MS_USER_INFO_URL]) {
99
+ try {
100
+ const r2 = await doFetch(url, { method: 'GET', headers: msHeaders(cookie) });
101
+ if (!r2.ok) continue;
102
+ const b2 = await r2.json().catch(() => null);
103
+ const parsed = parseMsIdentity(b2);
104
+ const keys = Object.keys(b2?.Data && typeof b2.Data === 'object' ? b2.Data : b2?.data && typeof b2.data === 'object' ? b2.data : b2 || {}).slice(0, 12).join(',');
105
+ // 合并而非首中即停:login/info 带 Name、users/info 带 email——互补
106
+ identity = {
107
+ id: identity?.id || parsed.id || null,
108
+ email: identity?.email || parsed.email || null,
109
+ name: identity?.name || parsed.name || null,
110
+ keys: [identity?.keys, keys].filter(Boolean).join(' | '),
111
+ };
112
+ if (identity.email && identity.name && identity.id) break;
113
+ } catch { /* 下一个兜底 */ }
114
+ }
115
+ return { ok: true, balance, identity, raw: body };
116
+ } catch (e) {
117
+ return { ok: false, error: e?.message || String(e) };
118
+ }
119
+ }
120
+
121
+ /**
122
+ * 发放记录(transactions)→ 今日/长期拆分。项形(2026-10-14 前端映射):
123
+ * { type: 'EARN' | 'SPEND_CONFIRM' | 'EXPIRE', expire_days, total_amount ?? amount, date | gmt_created }
124
+ * 有效期字段是 **expire_days**(前端行渲染 `e.expire_days>1 ? 有效期{days}天 : 有效期{day}天`)——
125
+ * 缺失按未知处理(归长期),绝不折算成 1 天误吞进今日。
126
+ * 口径:**今日发放** = 今日获得且 `expire_days<=1` 的 EARN 之和(官方「每日发放 有效期1天」);
127
+ * **长期** = total_balance − 今日(吸收消耗/过期误差,与官方发放记录页对得上:300 = 200 + 50 + 50)。
128
+ */
129
+ export function parseMagicubeLedger(items, totalBalance, now = Date.now()) {
130
+ const list = Array.isArray(items) ? items : [];
131
+ const d0 = new Date(now);
132
+ const todayStr = `${d0.getFullYear()}-${String(d0.getMonth() + 1).padStart(2, '0')}-${String(d0.getDate()).padStart(2, '0')}`;
133
+ let today = 0;
134
+ for (const it of list) {
135
+ if (!it || it.type !== 'EARN') continue;
136
+ const days = Number(it.expire_days ?? it.days);
137
+ const amt = Number(it.total_amount ?? it.amount);
138
+ // 仅 (0,1] 天有效才算今日发放;expire_days=0(长期有效)/缺失/90 天均归长期
139
+ if (!Number.isFinite(days) || days <= 0 || days > 1 || !Number.isFinite(amt) || amt < 0) continue;
140
+ const day = String(it.date || it.gmt_created || '').split(' ')[0].split('T')[0].trim();
141
+ if (day === todayStr) today += amt;
142
+ }
143
+ const total = Number(totalBalance);
144
+ if (Number.isFinite(total)) today = Math.min(today, Math.max(0, total));
145
+ return { today: Math.round(today * 100) / 100, long: Number.isFinite(total) ? Math.round(Math.max(0, total - today) * 100) / 100 : null };
146
+ }
147
+
148
+ /** 发放记录拉取(拆分用,fail-soft:失败返回 null,卡面回退单值) */
149
+ export async function fetchMagicubeLedger(cookie, totalBalance, { fetchImpl } = {}) {
150
+ const doFetch = fetchImpl || ((u, init) => fetchJsonRace(u, { headers: init.headers, timeoutMs: FETCH_TIMEOUT_MS }));
151
+ try {
152
+ const res = await doFetch(`${MS_TRANSACTIONS_URL}?page=1&page_size=50`, { headers: msHeaders(cookie) });
153
+ if (!res.ok) return null;
154
+ const body = await res.json().catch(() => null);
155
+ const d = body?.data;
156
+ const items = Array.isArray(d) ? d : (d?.list || d?.records || d?.items || body?.list || body?.records || []);
157
+ return parseMagicubeLedger(items, totalBalance);
158
+ } catch { return null; }
159
+ }
160
+
161
+ /**
162
+ * 一次跑齐「余额 + 身份 + 流水拆分」——捕获入库与就地重探共用。
163
+ * @returns {Promise<{ok: boolean, error?: string, status?: number, balance?: number,
164
+ * identity?: string|null, keys?: string, msSession?: object, msBalance?: object, ledger?: object}>}
165
+ */
166
+ export async function probeMagicubeSession(cookie, { fetchImpl } = {}) {
167
+ const bal = await fetchMagicubeBalance(cookie, { fetchImpl });
168
+ if (!bal.ok) return { ok: false, error: bal.error, status: bal.status };
169
+ const ledger = await fetchMagicubeLedger(cookie, bal.balance, { fetchImpl }).catch(() => null);
170
+ const s = bal.identity || {};
171
+ const hasIdentity = Boolean(s.id || s.email || s.name);
172
+ return {
173
+ ok: true,
174
+ balance: bal.balance,
175
+ identity: s.email || s.name || s.id || null,
176
+ keys: s.keys || '',
177
+ msSession: hasIdentity ? s : {},
178
+ ledger,
179
+ msBalance: {
180
+ amount: bal.balance,
181
+ today: ledger?.today ?? null,
182
+ long: ledger?.long ?? null,
183
+ at: new Date().toISOString(),
184
+ },
185
+ };
186
+ }
187
+
188
+ /**
189
+ * 组装 ModelScope 魔粒余额的 10Router external-quota 载荷(储值计数卡)。
190
+ * 有拆分时:汇总行名 = 副标题「今日发放 X · 长期 Y (魔粒)」+ 逐包明细两腿(今日 1 天有效 / 长期);
191
+ * 无拆分回退单值行。label = 账号别名(10R「同名认领」匹配键)。
192
+ * @param {object} account
193
+ * @param {{ balance?: number, ledger?: object, error?: string, authInvalid?: boolean }} [liveData]
194
+ * authInvalid = live 拉取明确 401/403(魔搭会话失效)——不回退旧快照,降级 message 状态卡
195
+ */
196
+ export function buildModelScopeQuotaPayload(account, liveData = null) {
197
+ const sess = account?.meta?.msSession || {};
198
+ const userId = account?.uid || sess.id || '';
199
+ const short = String(userId).toLowerCase().replace(/[^a-z0-9-]/g, '').slice(0, 24);
200
+ const source = short ? `modelscope-${short}`.slice(0, 32) : `modelscope-${(account?.id || 'default').slice(0, 24)}`;
201
+ const nameStr = String(account?.name || '').trim();
202
+ const email = sess.email || /[\w.+-]+@[\w-]+\.[\w.]+/.exec(nameStr)?.[0] || '';
203
+
204
+ if (liveData?.authInvalid) {
205
+ return {
206
+ source,
207
+ payload: {
208
+ provider: 'modelscope',
209
+ label: (nameStr || (email ? `ModelScope (${email})` : 'ModelScope')).slice(0, 100),
210
+ message: liveData.error || t('ModelScope 会话已失效,请在 CreditDaddy「网页会话」页重新登录捕获'),
211
+ },
212
+ };
213
+ }
214
+
215
+ let balance = liveData?.balance;
216
+ let ageTag = '';
217
+ if (!Number.isFinite(balance)) {
218
+ const snap = account?.meta?.quotaSnapshot;
219
+ balance = Number(snap?.total ?? account?.meta?.msBalance?.amount);
220
+ // 快照回退(非 live):距今 >24h 的陈粮在副标题标注数据时刻(可见性兜底)
221
+ ageTag = snapshotAgeTag(snap?.at ? snap : account?.meta?.msBalance);
222
+ }
223
+ const ledger = liveData?.ledger || account?.meta?.msBalance || null;
224
+
225
+ // label = 账号别名(用户可改)——10R「同名认领」的匹配键
226
+ const label = (nameStr || (email ? `ModelScope (${email})` : 'ModelScope')).slice(0, 100);
227
+ const payload = {
228
+ provider: 'modelscope',
229
+ label,
230
+ plan: t('魔粒余额') + ageTag,
231
+ };
232
+
233
+ if (Number.isFinite(balance) && balance >= 0) {
234
+ const total = Math.max(0, balance) || 0.000001;
235
+ const hasSplit = ledger && Number.isFinite(ledger.today) && Number.isFinite(ledger.long);
236
+ const name = hasSplit
237
+ ? t('今日发放 {today} · 长期 {long} (魔粒)', { today: Number(ledger.today).toFixed(0), long: Number(ledger.long).toFixed(0) })
238
+ : t('魔粒余额(个)');
239
+ payload.quotas = {
240
+ Balance: {
241
+ name,
242
+ used: 0,
243
+ total,
244
+ remainingPercentage: balance > 0 ? 100 : 0,
245
+ displayRemaining: true,
246
+ isCreditBalance: true,
247
+ summarizesDetail: true,
248
+ },
249
+ };
250
+ if (hasSplit) {
251
+ payload.quotas.Today = {
252
+ name: t('今日发放(1 天有效)'),
253
+ used: 0,
254
+ total: Math.max(0.000001, Number(ledger.today) || 0.000001),
255
+ remainingPercentage: Number(ledger.today) > 0 ? 100 : 0,
256
+ displayRemaining: true,
257
+ isCreditBalance: true,
258
+ detailOnly: true,
259
+ };
260
+ payload.quotas.LongTerm = {
261
+ name: t('长期余额'),
262
+ used: 0,
263
+ total: Math.max(0.000001, Number(ledger.long) || 0.000001),
264
+ remainingPercentage: Number(ledger.long) > 0 ? 100 : 0,
265
+ displayRemaining: true,
266
+ isCreditBalance: true,
267
+ detailOnly: true,
268
+ };
269
+ }
270
+ } else {
271
+ payload.message = liveData?.error || t('ModelScope 会话已失效,请在 CreditDaddy「网页会话」页重新登录捕获');
272
+ }
273
+
274
+ return { source, payload };
275
+ }