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.
@@ -0,0 +1,332 @@
1
+ /**
2
+ * WPS 灵犀(lingxi.kdocs.cn)签到与灵点余额抓取(issue #53)。
3
+ *
4
+ * 接口(提案者 2026-11-06 本机实测):
5
+ * GET https://lingxi.kdocs.cn/api/public/v1/tasks
6
+ * data.tasks[] 里 task_key == 'daily_check_in',status 是 claimed / available
7
+ * POST https://lingxi.kdocs.cn/api/public/v1/tasks/daily_check_in/claim?date=YYYY-MM-DD
8
+ * → {"result":"ok","data":{"total_claimed_credits":...}}
9
+ * GET https://lingxi.kdocs.cn/api/public/v1/credits/balance
10
+ *
11
+ * 奖励:每天 100 灵点,七天一轮第七天 200(提案者实测,网上旧文「200/天」已过时)。
12
+ * 凭据 = WPS 会话 Cookie(wps_sid / kso_sid / rtk 等约 300+ 天),无签名参数。
13
+ * 幂等性提案者未验证:claimed 状态下不再 POST claim(先查 tasks,status=available 才 claim)。
14
+ *
15
+ * 首版边界(按 #53 讨论):签到 + 灵点余额;不做网关 / 对话补全(补全端点提案者未看清)。
16
+ * 灵点只在灵犀界面消费,官方无 API——推送 10Router 只带余额数字出卡。
17
+ */
18
+
19
+ import { fetchJsonRace } from './zcodeClient.js';
20
+ import { FETCH_TIMEOUT_MS } from './constants.js';
21
+ import { t } from './i18n.js';
22
+ import { snapshotAgeTag } from './externalQuota.js';
23
+
24
+ export const LINGXI_BASE = 'https://lingxi.kdocs.cn';
25
+ export const LINGXI_TASKS_URL = `${LINGXI_BASE}/api/public/v1/tasks`;
26
+ export const LINGXI_BALANCE_URL = `${LINGXI_BASE}/api/public/v1/credits/balance`;
27
+
28
+ export const DAILY_CHECK_IN_KEY = 'daily_check_in';
29
+
30
+ function lingxiHeaders(cookie) {
31
+ return {
32
+ Cookie: String(cookie || '').trim(),
33
+ Referer: `${LINGXI_BASE}/`,
34
+ Origin: LINGXI_BASE,
35
+ Accept: 'application/json, text/plain, */*',
36
+ 'User-Agent':
37
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
38
+ };
39
+ }
40
+
41
+ function doFetch(url, { method = 'GET', cookie, fetchImpl } = {}) {
42
+ const doIt = fetchImpl || ((u, init) => fetchJsonRace(u, { headers: init.headers, method, timeoutMs: FETCH_TIMEOUT_MS }));
43
+ return doIt(url, { headers: lingxiHeaders(cookie) });
44
+ }
45
+
46
+ function authErr(status) {
47
+ const e = new Error(`灵犀会话已失效(HTTP ${status})`);
48
+ e.auth = true;
49
+ return e;
50
+ }
51
+
52
+ /** 本地日 YYYY-MM-DD(claim 的 date 参数按提案者实测口径) */
53
+ function localDayKey(now = new Date()) {
54
+ const p = (n) => String(n).padStart(2, '0');
55
+ return `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())}`;
56
+ }
57
+
58
+ /**
59
+ * 任务面板:每日签到状态 + 智点余额/资源包一次拿全。
60
+ * @param {string} cookie
61
+ * @param {{ fetchImpl?: Function }} [opts]
62
+ * @returns {Promise<{ auth: boolean, checkedIn?: boolean, reward?: number, streakDays?: number,
63
+ * balance?: number, packs?: Array, raw?: object, code?: string }>}
64
+ * auth=false = 会话失效;其余字段尽力而为(接口各自独立,某一路失败不带该字段)
65
+ *
66
+ * 余额接口实测形状(2026-11-07 本机实证):
67
+ * { data: { bonus_credits: [{balance, value, consumed, expire_time, effect_time, sku_key}],
68
+ * purchased_credits: [...], total_bonus, total_purchased, total_balance, ... } }
69
+ * —— 余额看 total_balance(兜底 total_bonus + total_purchased);bonus_credits[] 是逐包资源
70
+ * (活动赠送 +800 / 任务奖励 +100 各一行,带有效期),推 10R 按 LongCat 逐包明细出卡。
71
+ */
72
+ export async function fetchLingxiStatus(cookie, { fetchImpl } = {}) {
73
+ const out = { auth: true };
74
+ // 1) 任务列表(探测 + 签到状态)
75
+ try {
76
+ const r = await doFetch(LINGXI_TASKS_URL, { cookie, fetchImpl });
77
+ if (r.status === 401 || r.status === 403) return { auth: false };
78
+ if (!r.ok) return { auth: false, code: `HTTP ${r.status}` };
79
+ const text = await r.text();
80
+ let data = null;
81
+ try { data = JSON.parse(text); } catch { return { auth: false, code: 'non-json' }; }
82
+ const tasks = data?.data?.tasks;
83
+ if (!Array.isArray(tasks)) return { auth: false, code: 'no-tasks' };
84
+ const daily = tasks.find((x) => x?.task_key === DAILY_CHECK_IN_KEY || x?.taskKey === DAILY_CHECK_IN_KEY);
85
+ if (daily) {
86
+ out.checkedIn = String(daily.status || '') === 'claimed';
87
+ const reward = Number(daily.reward_amount ?? daily.rewardAmount);
88
+ if (Number.isFinite(reward) && reward > 0) out.reward = reward;
89
+ const days = daily.extra?.check_in_days || daily.extra?.checkInDays;
90
+ if (Array.isArray(days)) out.streakDays = days.filter((d) => d?.claimed || d?.status === 'claimed').length;
91
+ }
92
+ out.raw = { tasks: tasks.length };
93
+ } catch (e) {
94
+ return { auth: false, code: e?.message || 'network' };
95
+ }
96
+ // 2) 智点余额 + 资源包明细(旁路:失败不推翻 auth 判定)
97
+ try {
98
+ const r = await doFetch(LINGXI_BALANCE_URL, { cookie, fetchImpl });
99
+ if (r.ok) {
100
+ const text = await r.text();
101
+ let data = null;
102
+ try { data = JSON.parse(text); } catch { data = null; }
103
+ const d = data?.data || {};
104
+ const bal = Number(d.total_balance ?? d.total_bonus);
105
+ if (Number.isFinite(bal)) out.balance = bal;
106
+ // 逐包:活动赠送(bonus)+ 购买(purchased)合并,每包 {balance, value, consumed, expireAt, kind}
107
+ const rows = [...(Array.isArray(d.bonus_credits) ? d.bonus_credits : []), ...(Array.isArray(d.purchased_credits) ? d.purchased_credits : [])];
108
+ const packs = rows
109
+ .map((p, i) => ({
110
+ id: `${p?.sku_key || 'pack'}-${i}`,
111
+ balance: Number(p?.balance) || 0,
112
+ total: Number(p?.value) || 0,
113
+ consumed: Number(p?.consumed) || 0,
114
+ expireAt: p?.expire_time ? new Date(p.expire_time).toISOString() : null,
115
+ kind: p?.sku_key === 'ai_credits_grant' ? 'grant' : String(p?.sku_key || ''),
116
+ }))
117
+ .filter((p) => p.total > 0 || p.balance > 0);
118
+ if (packs.length) out.packs = packs;
119
+ }
120
+ } catch { /* 余额拿不到不阻断 */ }
121
+ return out;
122
+ }
123
+
124
+ /** 资源包快照(进 meta.lingxiPacks,与 longcatPacks 同形) */
125
+ export function lingxiSnapshot(packs) {
126
+ return { packs, at: new Date().toISOString() };
127
+ }
128
+
129
+ /**
130
+ * 每日签到:先查任务状态(claimed 直接返回已签),available 才 POST claim。
131
+ * 幂等性未验证(提案者停在了风控边界),所以绝不盲打 claim。
132
+ * @returns {{ status: 'checked-in'|'already'|'failed', message: string, claimedAmount?: number }}
133
+ */
134
+ export async function checkinLingxi(account, ctx = {}) {
135
+ const cookie = account?.meta?.cookieSiteSession?.cookie;
136
+ if (!cookie) {
137
+ const e = new Error('灵犀会话缺失,请在「网页会话」页重新登录捕获');
138
+ e.auth = true;
139
+ throw e;
140
+ }
141
+ const log = ctx?.log;
142
+ // 1. 任务状态
143
+ let status;
144
+ try {
145
+ status = await fetchLingxiStatus(cookie, { fetchImpl: ctx?.fetchImpl });
146
+ } catch (e) {
147
+ return { status: 'failed', message: t('灵犀签到查询失败:{err}', { err: e.message }) };
148
+ }
149
+ if (!status.auth) {
150
+ const e = new Error('灵犀会话已失效,请到「网页会话」页重新登录捕获');
151
+ e.auth = true;
152
+ throw e;
153
+ }
154
+ const reward = status.reward ?? 100;
155
+ if (status.checkedIn) {
156
+ return {
157
+ status: 'already',
158
+ message: t('今日已签到(+{n} 灵点)', { n: reward }),
159
+ amount: reward,
160
+ streakDays: status.streakDays,
161
+ };
162
+ }
163
+ // 2. claim(仅 available 时)
164
+ const claimUrl = `${LINGXI_BASE}/api/public/v1/tasks/${DAILY_CHECK_IN_KEY}/claim?date=${localDayKey()}`;
165
+ let claimData = null;
166
+ try {
167
+ const r = await doFetch(claimUrl, { method: 'POST', cookie, fetchImpl: ctx?.fetchImpl });
168
+ const text = await r.text().catch(() => '');
169
+ if (r.status === 401 || r.status === 403) {
170
+ const e = new Error('灵犀会话已失效,请重新登录捕获');
171
+ e.auth = true;
172
+ throw e;
173
+ }
174
+ try { claimData = text ? JSON.parse(text) : null; } catch { claimData = null; }
175
+ if (!r.ok) {
176
+ return { status: 'failed', message: t('灵犀签到失败:HTTP {n} {msg}', { n: r.status, msg: (claimData?.message || claimData?.error || '').slice(0, 120) }) };
177
+ }
178
+ if (claimData && claimData.result !== 'ok' && claimData?.code && String(claimData.code) !== '0') {
179
+ // 服务端明确拒绝(如风控 / 重复):如实上抛,不猜
180
+ return { status: 'failed', message: t('灵犀签到被拒:{msg}', { msg: String(claimData.message || claimData.error || claimData.code).slice(0, 120) }) };
181
+ }
182
+ } catch (e) {
183
+ if (e.auth) throw e;
184
+ return { status: 'failed', message: t('灵犀签到失败:{err}', { err: e.message }) };
185
+ }
186
+
187
+ const claimed = Number(claimData?.data?.total_claimed_credits ?? claimData?.data?.totalClaimedCredits);
188
+ const pts = Number.isFinite(claimed) && claimed > 0 ? claimed : reward;
189
+ log?.('灵犀签到成功');
190
+ return {
191
+ status: 'checked-in',
192
+ message: t('签到成功(+{n} 灵点)', { n: pts }),
193
+ claimedAmount: pts,
194
+ amount: pts,
195
+ ...(Number.isFinite(status.balance) ? { balanceAfter: status.balance } : {}),
196
+ };
197
+ }
198
+
199
+ /**
200
+ * 灵点余额(quota 口径:remaining = 灵点余额)
201
+ */
202
+ export async function fetchLingxiQuota(account, ctx = {}) {
203
+ const cookie = account?.meta?.cookieSiteSession?.cookie;
204
+ if (!cookie) {
205
+ const e = new Error('灵犀会话缺失,请重新登录捕获');
206
+ e.auth = true;
207
+ throw e;
208
+ }
209
+ const status = await fetchLingxiStatus(cookie, { fetchImpl: ctx?.fetchImpl });
210
+ if (!status.auth) {
211
+ const e = new Error('灵犀会话已失效,请重新登录捕获');
212
+ e.auth = true;
213
+ throw e;
214
+ }
215
+ const balance = Number(status.balance);
216
+ return {
217
+ total: Number.isFinite(balance) ? balance : 0,
218
+ used: 0,
219
+ remaining: Number.isFinite(balance) ? balance : 0,
220
+ exceeded: false,
221
+ plan: t('灵点'),
222
+ planExpiresAt: null,
223
+ parts: Number.isFinite(balance) ? [{
224
+ name: t('灵点余额'),
225
+ total: balance,
226
+ used: 0,
227
+ remaining: balance,
228
+ recurring: true,
229
+ unit: '灵点',
230
+ }] : [],
231
+ empty: !Number.isFinite(balance) || balance <= 0,
232
+ };
233
+ }
234
+
235
+ /**
236
+ * 10Router 外部配额卡:智点储值卡 + 逐包明细(与 LongCat 资源包卡同款纪律)。
237
+ * - Balance 汇总行 = 全部包 balance 之和(isCreditBalance + summarizesDetail);
238
+ * - 逐包明细腿 = 每包一行(detailOnly,used=consumed、total=包总量、resetAt=包有效期),
239
+ * 活动赠送包带 giftPack 标记;0 余额包也出行(可见耗尽);
240
+ * - 拿不到任何包 → 单值余额卡兜底;连余额都拿不到 → message 状态卡。
241
+ */
242
+ export function buildLingxiQuotaPayload(account, liveData = null) {
243
+ const uid = account.uid || identityHashOfLocal(account) || 'default';
244
+ const cleanSource = `lingxi-${String(uid).toLowerCase().replace(/[^a-z0-9-]/g, '')}`.slice(0, 32);
245
+ const label = String(account?.name || '').trim() || t('WPS 灵犀');
246
+
247
+ if (liveData?.authInvalid) {
248
+ return {
249
+ source: cleanSource,
250
+ payload: {
251
+ provider: 'lingxi',
252
+ label,
253
+ message: liveData.error || t('灵犀会话已失效,请在 CreditDaddy「网页会话」页重新登录捕获'),
254
+ },
255
+ };
256
+ }
257
+
258
+ // live 优先,快照兜底(非 live 且 >24h 由 ageTag 标注陈粮)
259
+ let packs = liveData?.packs;
260
+ let ageTag = '';
261
+ if (!Array.isArray(packs)) {
262
+ const snap = account.meta?.quotaSnapshot;
263
+ packs = account.meta?.lingxiPacks?.packs;
264
+ ageTag = snapshotAgeTag(snap ?? account.meta?.lingxiPacks);
265
+ }
266
+ const active = (packs || []).filter((p) => p && Number.isFinite(Number(p.balance)));
267
+ const balance = active.length
268
+ ? active.reduce((s, p) => s + Math.max(0, Number(p.balance)), 0)
269
+ : Number(liveData?.balance);
270
+
271
+ const payload = {
272
+ provider: 'lingxi',
273
+ label,
274
+ plan: t('智点余额') + ageTag,
275
+ };
276
+
277
+ if (active.length && balance > 0) {
278
+ const pct1 = (rem, tot) => (tot > 0 ? Math.max(0, Math.min(100, Math.round((rem / tot) * 1000) / 10)) : 0);
279
+ const totalAll = active.reduce((s, p) => s + Math.max(0, Number(p.total) || 0), 0);
280
+ const usedAll = active.reduce((s, p) => s + Math.max(0, Number(p.consumed) || 0), 0);
281
+ payload.quotas = {
282
+ Balance: {
283
+ name: `${t('剩余')} ${balance} (${t('智点')})`,
284
+ used: usedAll,
285
+ total: totalAll,
286
+ remainingPercentage: pct1(balance, totalAll),
287
+ displayRemaining: true,
288
+ isCreditBalance: true,
289
+ summarizesDetail: true,
290
+ },
291
+ };
292
+ for (const [i, p] of active.entries()) {
293
+ const kind = p.kind === 'grant' || (p.total > 0 && p.consumed === 0 && !Number.isFinite(p.consumed));
294
+ payload.quotas[`Pack${i + 1}`] = {
295
+ name: kind ? t('活动赠送包') : t('智点包'),
296
+ used: Math.max(0, Number(p.consumed) || 0),
297
+ total: Math.max(0, Number(p.total) || 0) || Math.max(0, Number(p.balance) || 0),
298
+ remainingPercentage: pct1(Math.max(0, Number(p.balance)), Math.max(0, Number(p.total) || 0) || Math.max(0, Number(p.balance) || 0)),
299
+ displayRemaining: true,
300
+ isCreditBalance: true,
301
+ ...(p.kind === 'grant' ? { giftPack: true } : {}),
302
+ detailOnly: true,
303
+ resetAt: p.expireAt || undefined,
304
+ };
305
+ }
306
+ } else if (Number.isFinite(balance) && balance >= 0) {
307
+ // 拿不到逐包(旧快照 / 接口半程失败):单值余额卡兜底
308
+ payload.quotas = {
309
+ Balance: {
310
+ name: t('智点余额'),
311
+ used: 0,
312
+ total: Math.max(0, balance) || 0.000001,
313
+ displayRemaining: true,
314
+ isCreditBalance: true,
315
+ recurring: true,
316
+ },
317
+ };
318
+ } else {
319
+ payload.message = t('灵点余额暂不可查(会话失效请重新登录捕获,或官方接口异常稍后自动重试)');
320
+ }
321
+ return { source: cleanSource, payload };
322
+ }
323
+
324
+ // 本地身份哈希(避免与 cookieSites 循环依赖;口径同 identityHashOf)
325
+ function identityHashOfLocal(account) {
326
+ const v = account?.meta?.identityHash || account?.email || account?.name || '';
327
+ if (!v) return null;
328
+ let h = 0;
329
+ const s = String(v);
330
+ for (let i = 0; i < s.length; i++) h = ((h * 31 + s.charCodeAt(i)) | 0) >>> 0;
331
+ return 'ih' + h.toString(36);
332
+ }
@@ -181,6 +181,12 @@ async function pointsRecordsCall(base, token) {
181
181
  }
182
182
 
183
183
  /** 积分档案初始化(客户端登录后必调的 first-login,幂等)。尽力而为,失败交给余额重试暴露。 */
184
+ export async function fetchLoomyFirstLogin(account) {
185
+ const token = sessionOf(account);
186
+ if (!token) throw new Error('账号缺少 session token');
187
+ await pointsFirstLogin(pointsBaseOf(account), token);
188
+ }
189
+
184
190
  async function pointsFirstLogin(base, token) {
185
191
  try {
186
192
  await fetch(`${base}/api/v1/points/first-login`, {
@@ -268,6 +274,58 @@ export async function fetchLoomyActivation(account) {
268
274
  return { activated: Boolean(d.activated), appliedInvitationCode: d.appliedInvitationCode || null };
269
275
  }
270
276
 
277
+ /**
278
+ * 我的邀请码列表:GET /api/v1/invitation-codes → data.data.list[](协议逆向自客户端
279
+ * points-service.queryInvitationCodes + 设置页「邀请有礼」,2026-11-06 从 app.asar 实证)。
280
+ * 客户端 bundle 里按 {code, usedCount, limit} 解析,但生产端实测(2026-11-06)字段是
281
+ * {inviteCode, usedCount, maxUses, status}——两种形状都归一化,以实测 wire 为准。
282
+ * 客户端在列表为空时会先调 first-login 初始化积分档案再重查(新号可能还没建档)。
283
+ */
284
+ export async function fetchLoomyMyInviteCodes(account) {
285
+ const token = sessionOf(account);
286
+ if (!token) throw new Error('账号缺少 session token');
287
+ let res;
288
+ try {
289
+ res = await fetch(`${pointsBaseOf(account)}/api/v1/invitation-codes`, {
290
+ method: 'GET',
291
+ headers: { token },
292
+ signal: AbortSignal.timeout(12000),
293
+ });
294
+ } catch (e) {
295
+ const err = new Error(`Loomy 邀请码查询网络失败: ${e.message}`);
296
+ err.transient = true;
297
+ throw err;
298
+ }
299
+ const text = await res.text().catch(() => '');
300
+ let data = null;
301
+ if (text) { try { data = JSON.parse(text); } catch { data = null; } }
302
+ if (data?.code === '100002' || data?.code === '020002') {
303
+ const err = new Error('Loomy session 已失效,请重新登录');
304
+ err.auth = true;
305
+ throw err;
306
+ }
307
+ if (!res.ok) {
308
+ throw new Error(`Loomy 邀请码查询 HTTP ${res.status}: ${(data?.desc || data?.message || text.slice(0, 120) || '').trim()}`);
309
+ }
310
+ if (!data) throw new Error(`Loomy 邀请码查询返回了非 JSON 数据 (HTTP ${res.status})`);
311
+ if (data?.code && !LOOMY_POINTS_OK_CODES.has(data.code)) {
312
+ throw new Error(data.desc || data.message || `Loomy 邀请码查询错误 (${data.code})`);
313
+ }
314
+ const list = Array.isArray(data?.data?.list) ? data.data.list : [];
315
+ return list
316
+ .map((x) => {
317
+ const limit = Number(x?.maxUses ?? x?.limit) || 0;
318
+ return {
319
+ id: String(x?.id ?? x?.inviteCode ?? x?.code ?? ''),
320
+ code: String(x?.inviteCode || x?.code || '').trim(),
321
+ usedCount: Number(x?.usedCount) || 0,
322
+ limit,
323
+ status: String(x?.status || '').trim(),
324
+ };
325
+ })
326
+ .filter((x) => x.code);
327
+ }
328
+
271
329
  /** 绑定邀请码:POST /api/v1/points/activation {inviteCode} → 服务端 +5000 永久积分(每号一次) */
272
330
  export async function bindLoomyInviteCode(account, code) {
273
331
  const token = sessionOf(account);
package/src/loomyLocal.js CHANGED
@@ -15,6 +15,7 @@ import os from 'node:os';
15
15
  import path from 'node:path';
16
16
  import crypto from 'node:crypto';
17
17
  import { execFileSync } from 'node:child_process';
18
+ import { procRunningCached } from './winProc.js';
18
19
 
19
20
  const EXE_NAME = 'Loomy.exe';
20
21
 
@@ -76,6 +77,11 @@ export function loomyRunning() {
76
77
  } catch { return false; }
77
78
  }
78
79
 
80
+ /** 轮询口径(/api/status 用):读 winProc 全量快照,不 spawn;switchTo/terminate 仍走 loomyRunning()。 */
81
+ export function loomyRunningCached() {
82
+ return procRunningCached([EXE_NAME]);
83
+ }
84
+
79
85
  /** 获取本机 Loomy.exe 路径 */
80
86
  export function candidateClientPath() {
81
87
  if (process.platform !== 'win32') return null;
@@ -98,7 +104,7 @@ export function detectLoomy() {
98
104
  signedIn: Boolean(cred),
99
105
  clientInstalled: Boolean(clientPath),
100
106
  clientPath,
101
- running: loomyRunning(),
107
+ running: loomyRunningCached(),
102
108
  credential: cred ? {
103
109
  userid: cred.userid,
104
110
  phone: cred.phone ? `${cred.phone.slice(0, 3)}****${cred.phone.slice(-4)}` : null,
@@ -2,16 +2,19 @@
2
2
  * MiniMax Code 浏览器登录 — 官方 OAuth 设备码授权(RFC 8628 + S256 PKCE),
3
3
  * 与客户端「扫码登录」同一协议,任何浏览器 / 桌面版隐私窗口都能完成,无需 zcode:// 式本地回调。
4
4
  *
5
- * 1. POST https://account.minimax.cn/oauth2/device/code
5
+ * 1. POST {account}/oauth2/device/code
6
6
  * {client_id:mcode-public, scope:agent.default, audience:agent-backend,
7
7
  * code_challenge:<S256>, code_challenge_method:S256}
8
8
  * → {device_code, user_code, verification_uri_complete, expires_in:300, interval:3}
9
- * 2. 用户在浏览器打开 verification_uri_complete(account.minimax.cn/oauth-authorize?user_code=…)登录授权
10
- * 3. POST https://account.minimax.cn/oauth2/token
9
+ * 2. 用户在浏览器打开 verification_uri_complete(account.minimax.(cn|io)/oauth-authorize?user_code=…)登录授权
10
+ * 3. POST {account}/oauth2/token
11
11
  * {grant_type:urn:ietf:params:oauth:grant-type:device_code, device_code, client_id, code_verifier}
12
12
  * → 未授权时 400 authorization_pending / slow_down(继续等);授权后 200
13
13
  * {access_token, refresh_token, expires_in, …}
14
14
  *
15
+ * 双渠道(issue #54):CN 用 account.minimax.cn,国际(minimax-global)用 account.minimax.io
16
+ * (@mavis/oauth-core endpoint-config ACCOUNT_ORIGINS 实证,协议 / client 完全一致)。
17
+ *
15
18
  * 与「本机导入」的关键区别:设备码登录拿到的是**独立 loginEpoch** 的一条新 refresh token 链,
16
19
  * 不与本机 ~/.minimax 客户端共用凭据,因此 CreditDaddy 自行刷新不会作废客户端的 token(消除轮换互斥)。
17
20
  * 故本流程**绝不回写** auth.json,device 账号自持凭据链。
@@ -20,10 +23,8 @@
20
23
  import crypto from 'node:crypto';
21
24
  import { fetchJsonRace } from './zcodeClient.js';
22
25
  import { FETCH_TIMEOUT_MS } from './constants.js';
23
- import { MINIMAX_ACCOUNT_BASE, fetchMiniMaxProfile } from './minimaxClient.js';
26
+ import { MINIMAX_FLAVORS, fetchMiniMaxProfile } from './minimaxClient.js';
24
27
 
25
- const DEVICE_CODE_URL = `${MINIMAX_ACCOUNT_BASE}/oauth2/device/code`;
26
- const TOKEN_URL = `${MINIMAX_ACCOUNT_BASE}/oauth2/token`;
27
28
  const CLIENT_ID = 'mcode-public';
28
29
  const SCOPE = 'agent.default';
29
30
  const AUDIENCE = 'agent-backend';
@@ -48,11 +49,12 @@ async function postForm(url, fields) {
48
49
  return { res, body, text };
49
50
  }
50
51
 
51
- /** 发起设备码授权,返回浏览器授权地址与轮询参数 */
52
- export async function startMiniMaxLogin() {
52
+ /** 发起设备码授权,返回浏览器授权地址与轮询参数(flavor: 'cn' 国内 / 'global' 国际) */
53
+ export async function startMiniMaxLogin(flavor = 'cn') {
54
+ const accountBase = MINIMAX_FLAVORS[flavor]?.account || MINIMAX_FLAVORS.cn.account;
53
55
  const verifier = base64Url(crypto.randomBytes(32));
54
56
  const challenge = base64Url(crypto.createHash('sha256').update(verifier).digest());
55
- const { res, body, text } = await postForm(DEVICE_CODE_URL, {
57
+ const { res, body, text } = await postForm(accountBase + '/oauth2/device/code', {
56
58
  client_id: CLIENT_ID, scope: SCOPE, audience: AUDIENCE,
57
59
  code_challenge: challenge, code_challenge_method: 'S256',
58
60
  });
@@ -65,7 +67,7 @@ export async function startMiniMaxLogin() {
65
67
  url,
66
68
  expiresInMs: Math.max(60e3, (Number(body.expires_in) || 300) * 1000),
67
69
  intervalMs: Math.max(2000, (Number(body.interval) || 3) * 1000),
68
- data: { deviceCode: body.device_code, verifier, userCode: body.user_code || null },
70
+ data: { deviceCode: body.device_code, verifier, userCode: body.user_code || null, flavor },
69
71
  };
70
72
  }
71
73
 
@@ -74,7 +76,9 @@ export async function startMiniMaxLogin() {
74
76
  * authorization_pending / slow_down 视为继续等待;其余错误抛出(终态失败)。
75
77
  */
76
78
  export async function pollMiniMaxLogin(data) {
77
- const { res, body, text } = await postForm(TOKEN_URL, {
79
+ const flavor = data?.flavor === 'global' ? 'global' : 'cn';
80
+ const accountBase = MINIMAX_FLAVORS[flavor].account;
81
+ const { res, body, text } = await postForm(accountBase + '/oauth2/token', {
78
82
  grant_type: DEVICE_GRANT,
79
83
  device_code: data.deviceCode,
80
84
  client_id: CLIENT_ID,
@@ -98,7 +102,7 @@ export async function pollMiniMaxLogin(data) {
98
102
 
99
103
  // best-effort 取资料补全 uid / 昵称 / 邮箱;失败不阻断(uid 为空则按 token 去重)
100
104
  let profile = null;
101
- try { profile = await fetchMiniMaxProfile(accessToken); } catch {}
105
+ try { profile = await fetchMiniMaxProfile(accessToken, { flavor }); } catch {}
102
106
 
103
107
  const uid = profile?.userId || null;
104
108
  const name = profile?.name || (uid ? `MiniMax_${String(uid).slice(-6)}` : null);
@@ -106,7 +110,7 @@ export async function pollMiniMaxLogin(data) {
106
110
  return {
107
111
  status: 'ok',
108
112
  input: {
109
- provider: 'minimax',
113
+ provider: flavor === 'global' ? 'minimax-global' : 'minimax',
110
114
  token: accessToken,
111
115
  refreshToken,
112
116
  expiresAt,
@@ -1,21 +1,44 @@
1
1
  /**
2
2
  * MiniMax Code 服务端 API 客户端 — 用户信息、额度查询、每日签到与 Token 续期。
3
3
  *
4
- * 官方标准端点:
5
- * - 用户资料:GET https://agent.minimax.cn/matrix/api/v1/user/profile
6
- * - 额度查询:POST https://agent.minimax.cn/matrix/api/v1/commerce/get_membership_info
7
- * - 签到状态:GET https://agent.minimax.cn/minimax-cloud/api/v1/signin/status?timezone_offset=28800&is_desktop=1&client=desktop
8
- * - 签到领取:POST https://agent.minimax.cn/minimax-cloud/api/v1/signin/claim?timezone_offset=28800&is_desktop=1&client=desktop
9
- * - Token 续期:POST https://account.minimax.cn/oauth2/token
4
+ * 双渠道(issue #54):国内 / 国际同协议同 client(mcode-public),只换域名——
5
+ * CN https://agent.minimax.cn + https://account.minimax.cn(官方客户端 NEXT_PUBLIC_LOCALE=zh)
6
+ * Intl https://agent.minimax.io + https://account.minimax.io(NEXT_PUBLIC_LOCALE=en)
7
+ * 端点实证:@mavis/oauth-core/dist/endpoint-config.js 的 ACCOUNT_ORIGINS(2026-11-07 从
8
+ * 官方客户端 app.asar 拆包),与本机 ~/.minimax/auth/prod/<region>/mcode-public/ 布局互证。
9
+ *
10
+ * 官方标准端点(CN,intl 同路径):
11
+ * - 用户资料:GET {agent}/matrix/api/v1/user/profile
12
+ * - 额度查询:POST {agent}/matrix/api/v1/commerce/get_membership_info
13
+ * - 签到状态:GET {agent}/minimax-cloud/api/v1/signin/status?timezone_offset=28800&is_desktop=1&client=desktop
14
+ * - 签到领取:POST {agent}/minimax-cloud/api/v1/signin/claim?timezone_offset=28800&is_desktop=1&client=desktop
15
+ * - Token 续期:POST {account}/oauth2/token
10
16
  *
11
17
  * 补全模型网关端点:
12
- * - Anthropic 兼容端点:POST https://agent.minimax.cn/mavis/api/v1/llm/v1/messages
18
+ * - Anthropic 兼容端点:POST {agent}/mavis/api/v1/llm/v1/messages
13
19
  */
14
20
 
15
21
  import { fetchJsonRace } from './zcodeClient.js';
16
22
  import { withRefreshDedupe, refreshFpDead } from './refreshGuard.js';
17
23
  import { FETCH_TIMEOUT_MS } from './constants.js';
18
24
 
25
+ /** MiniMax 渠道档位:cn(国内,agent.minimax.cn)/ global(国际,agent.minimax.io) */
26
+ export const MINIMAX_FLAVORS = {
27
+ cn: { agent: 'https://agent.minimax.cn', account: 'https://account.minimax.cn' },
28
+ global: { agent: 'https://agent.minimax.io', account: 'https://account.minimax.io' },
29
+ };
30
+
31
+ /** 账号档位判定:provider 为 minimax-global 或 meta.minimaxFlavor 标记的走国际线,其余国内 */
32
+ export function minimaxFlavorOf(account) {
33
+ if (account?.provider === 'minimax-global') return 'global';
34
+ return account?.meta?.minimaxFlavor === 'global' ? 'global' : 'cn';
35
+ }
36
+
37
+ function basesOf(account) {
38
+ return MINIMAX_FLAVORS[minimaxFlavorOf(account)] || MINIMAX_FLAVORS.cn;
39
+ }
40
+
41
+ // 兼容旧引用(网关 / minimaxLocal 等按 CN 域名直连的地方);新代码请用 basesOf(account)
19
42
  export const MINIMAX_AGENT_BASE = 'https://agent.minimax.cn';
20
43
  export const MINIMAX_ACCOUNT_BASE = 'https://account.minimax.cn';
21
44
  export const MINIMAX_MESSAGES_URL = `${MINIMAX_AGENT_BASE}/mavis/api/v1/llm/v1/messages`;
@@ -26,6 +49,21 @@ export const SIGNIN_STATUS_URL = `${MINIMAX_AGENT_BASE}/minimax-cloud/api/v1/sig
26
49
  export const SIGNIN_CLAIM_URL = `${MINIMAX_AGENT_BASE}/minimax-cloud/api/v1/signin/claim?timezone_offset=28800&is_desktop=1&client=desktop`;
27
50
  export const TOKEN_REFRESH_URL = `${MINIMAX_ACCOUNT_BASE}/oauth2/token`;
28
51
 
52
+ /** 按账号档位解析各端点(CN / 国际只差域名,路径完全一致) */
53
+ export function minimaxEndpointsOf(account) {
54
+ const { agent, account: accountBase } = basesOf(account);
55
+ return {
56
+ agent,
57
+ account: accountBase,
58
+ messagesUrl: `${agent}/mavis/api/v1/llm/v1/messages`,
59
+ profileUrl: `${agent}/matrix/api/v1/user/profile`,
60
+ membershipUrl: `${agent}/matrix/api/v1/commerce/get_membership_info`,
61
+ signinStatusUrl: `${agent}/minimax-cloud/api/v1/signin/status?timezone_offset=28800&is_desktop=1&client=desktop`,
62
+ signinClaimUrl: `${agent}/minimax-cloud/api/v1/signin/claim?timezone_offset=28800&is_desktop=1&client=desktop`,
63
+ tokenRefreshUrl: `${accountBase}/oauth2/token`,
64
+ };
65
+ }
66
+
29
67
  /** 时间戳宽容转换(口径同 traeClient.iso):≤1e11 视为秒,否则视为毫秒;0/无效 → null */
30
68
  function isoMs(v) {
31
69
  const n = Number(v);
@@ -47,7 +85,7 @@ function authHeaders(token) {
47
85
  * @param {string} refreshToken
48
86
  * @returns {Promise<{accessToken: string, refreshToken: string, expiresIn: number}>}
49
87
  */
50
- export async function refreshMiniMaxToken(refreshToken) {
88
+ export async function refreshMiniMaxToken(refreshToken, { flavor = 'cn' } = {}) {
51
89
  if (!refreshToken) throw new Error('缺少 refreshToken');
52
90
  const form = new URLSearchParams();
53
91
  form.set('grant_type', 'refresh_token');
@@ -56,7 +94,7 @@ export async function refreshMiniMaxToken(refreshToken) {
56
94
  form.set('scope', 'agent.default');
57
95
  form.set('audience', 'agent-backend');
58
96
 
59
- const res = await fetchJsonRace(TOKEN_REFRESH_URL, {
97
+ const res = await fetchJsonRace(MINIMAX_FLAVORS[flavor].account + '/oauth2/token', {
60
98
  method: 'POST',
61
99
  headers: {
62
100
  'Content-Type': 'application/x-www-form-urlencoded',
@@ -117,7 +155,7 @@ export function refreshAccountToken(account, ctx = {}) {
117
155
  } catch {}
118
156
  ctx.log?.('MiniMax token 已过期,正在自动刷新…');
119
157
  try {
120
- const refreshed = await refreshMiniMaxToken(a.refreshToken);
158
+ const refreshed = await refreshMiniMaxToken(a.refreshToken, { flavor: minimaxFlavorOf(a) });
121
159
  const expiresAt = new Date(Date.now() + refreshed.expiresIn * 1000).toISOString();
122
160
  const creds = {
123
161
  token: refreshed.accessToken,
@@ -166,8 +204,8 @@ export function refreshAccountToken(account, ctx = {}) {
166
204
  /**
167
205
  * 获取用户信息
168
206
  */
169
- export async function fetchMiniMaxProfile(token) {
170
- const res = await fetchJsonRace(PROFILE_URL, {
207
+ export async function fetchMiniMaxProfile(token, { flavor = 'cn' } = {}) {
208
+ const res = await fetchJsonRace(MINIMAX_FLAVORS[flavor].agent + '/matrix/api/v1/user/profile', {
171
209
  headers: authHeaders(token),
172
210
  timeoutMs: FETCH_TIMEOUT_MS,
173
211
  });
@@ -206,8 +244,9 @@ export async function verifyMiniMaxAccount(account) {
206
244
  * 查询额度 (quota)
207
245
  */
208
246
  export async function fetchMiniMaxQuota(account, ctx = {}) {
247
+ const { membershipUrl } = minimaxEndpointsOf(account);
209
248
  return withMiniMaxAuth(account, async (token) => {
210
- const res = await fetchJsonRace(MEMBERSHIP_URL, {
249
+ const res = await fetchJsonRace(membershipUrl, {
211
250
  method: 'POST',
212
251
  headers: {
213
252
  ...authHeaders(token),
@@ -292,9 +331,10 @@ export function normalizeMiniMaxQuota(data) {
292
331
  * @returns {Promise<{checkedToday: boolean, streakDays: number, points: number, bonusPoints: number}|null>}
293
332
  */
294
333
  export async function fetchMiniMaxCheckinStatus(account, ctx = {}) {
334
+ const { signinStatusUrl } = minimaxEndpointsOf(account);
295
335
  try {
296
336
  return await withMiniMaxAuth(account, async (token) => {
297
- const statusRes = await fetchJsonRace(SIGNIN_STATUS_URL, {
337
+ const statusRes = await fetchJsonRace(signinStatusUrl, {
298
338
  headers: authHeaders(token),
299
339
  timeoutMs: FETCH_TIMEOUT_MS,
300
340
  });
@@ -319,9 +359,10 @@ export async function fetchMiniMaxCheckinStatus(account, ctx = {}) {
319
359
  * 每日自动签到 (checkin)
320
360
  */
321
361
  export async function checkinMiniMax(account, ctx = {}) {
362
+ const { signinStatusUrl, signinClaimUrl } = minimaxEndpointsOf(account);
322
363
  return withMiniMaxAuth(account, async (token) => {
323
364
  // 1. 查询签到状态
324
- const statusRes = await fetchJsonRace(SIGNIN_STATUS_URL, {
365
+ const statusRes = await fetchJsonRace(signinStatusUrl, {
325
366
  headers: authHeaders(token),
326
367
  timeoutMs: FETCH_TIMEOUT_MS,
327
368
  });
@@ -350,7 +391,7 @@ export async function checkinMiniMax(account, ctx = {}) {
350
391
  }
351
392
 
352
393
  // 2. 发起签到 claim
353
- const claimRes = await fetchJsonRace(SIGNIN_CLAIM_URL, {
394
+ const claimRes = await fetchJsonRace(signinClaimUrl, {
354
395
  method: 'POST',
355
396
  headers: authHeaders(token),
356
397
  timeoutMs: FETCH_TIMEOUT_MS,