creditdaddy 1.6.7 → 1.7.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.
@@ -1,167 +1,167 @@
1
- /**
2
- * ZCode 活动自动领取 — 签到调度器每轮调用。
3
- *
4
- * 策略(对齐用户手动路径,逐级尝试):
5
- * 1. billing/preview 查可领活动;为空 → 无事可做(返回 null,不留痕迹)
6
- * 2. 先直接 claim(不带验证码:服务端未风控时可直接成功)
7
- * 3. 返回 3007/3001(需要验证码 / 参数被拒)且有验证码提供者 → 拉 captcha 配置,
8
- * 让提供者(桌面版的隐藏窗口跑阿里云验证码 SDK 静默验证)拿 captchaVerifyParam 后重试
9
- * 4. 没有提供者(NAS / 纯 CLI)或验证码需要人工 → 标记「需手动领取」,卡片上提示
10
- * - 1003(已领取过)按成功口径处理并记忆
11
- * 结果写入账号 lastResult(签到日历记忆用的是 status checked-in/already,第二天照常重查 preview)
12
- */
13
-
14
- import { logger } from './logger.js';
15
- import { t } from './i18n.js';
16
- import { fetchClaimPlans, claimPlan, fetchCaptchaConfig, ZCODE_KNOWN_CLAIM_PLANS } from './zcodeClient.js';
17
- import { withAccounts } from './store.js';
18
-
19
- // 额满(1005)时消费服务端 nextAt(plan.ends_at):
20
- // 下轮自动轮询(claimIntervalMin 分钟一触)在 nextAt 之前跳过该号,不做无谓抢。
21
- // 进程内缓存 + 落盘 account.meta.zcodeClaimNextAt 双轨(重启保护)。
22
- const snoozeUntil = new Map(); // accountId → ms 时间戳
23
-
24
- function snoozeUntilMs(account) {
25
- const meta = Number(new Date(account?.meta?.zcodeClaimNextAt || 0)) || 0;
26
- const proc = snoozeUntil.get(account.id) || 0;
27
- return Math.max(meta, proc);
28
- }
29
-
30
- // 桌面版(Electron 主进程)注册的隐藏窗口验证码实现;NAS / CLI 为 null(走「需手动领取」分支)
31
- let captchaProvider = null;
32
- export function setZcodeCaptchaProvider(fn) { captchaProvider = typeof fn === 'function' ? fn : null; }
33
- export function hasZcodeCaptchaProvider() { return Boolean(captchaProvider); }
34
- export function getZcodeCaptchaProvider() { return captchaProvider; }
35
-
36
- /** 账号被删除时清掉额满暂休缓存(daemon DELETE /api/accounts/:id 调用;落盘份随账号一起删) */
37
- export function forgetAccount(id) { snoozeUntil.delete(id); }
38
-
39
- const grantsText = (plan) => (plan.grants && plan.grants.length ? plan.grants.join(';') : '');
40
-
41
- /**
42
- * 为单个 ZCode 账号执行一次自动领取。
43
- * @returns {null | { status, message, claims: Array }} null = preview 为空或查询失败(已记日志,不上卡片)
44
- */
45
- export async function zcodeAutoClaim(account) {
46
- const label = account.name || account.uid || account.id;
47
- {
48
- const until = snoozeUntilMs(account);
49
- if (until && until > Date.now()) {
50
- logger.debug('ZCODE-CLAIM', '{label} 名额已领完,跳过直到 {until}(服务端计划结束点)', { label, until: new Date(until).toISOString() });
51
- return null;
52
- }
53
- }
54
- let plans;
55
- try {
56
- plans = (await fetchClaimPlans(account)).plans;
57
- } catch (e) {
58
- logger.debug('ZCODE-CLAIM', '{label} 活动查询失败:{err}', { label, err: e.message });
59
- return null;
60
- }
61
- if (!plans.length) {
62
- // preview 为空 ≠ 无事可做:服务端偶尔把活动从列表里藏起来(2026-10-30 WEEKEND BUILD
63
- // 实测 preview 返回空但 claim 按 planId 直接可领)。把已知清单合成伪 plan 走同一条
64
- // 领取链路:1001/1002(不存在/已结束)在 catch 里静默跳过,不进卡片。
65
- plans = ZCODE_KNOWN_CLAIM_PLANS.map((k) => ({ planId: k.planId, name: k.name || k.planId, description: '', priority: 0, grants: [], known: true }));
66
- }
67
-
68
- const claims = [];
69
- let anySuccess = false;
70
- let needManual = false;
71
-
72
- let snoozeAt = 0;
73
- for (const plan of plans) {
74
- const planName = plan.name || plan.planId;
75
- // 第 2 步:先试不带验证码
76
- try {
77
- const r = await claimPlan(account, plan.planId, {});
78
- // startsAt 是「到账时间」:活动权益常带 effective_at(如当天 23:00),
79
- // 领到了但余额里还没有——不把这个时间带出去,面板只能显示冷冰冰的
80
- // 「待生效」,用户以为没领上。
81
- claims.push({ plan: planName, via: 'direct', ok: true, startsAt: r?.startsAt || null });
82
- anySuccess = true;
83
- logger.info('ZCODE-CLAIM', '{label} 已领取「{plan}」(免验证码){grants}', { label, plan: planName, grants: grantsText(plan) ? ':' + grantsText(plan) : '' });
84
- continue;
85
- } catch (e) {
86
- if (e.code === 1003) {
87
- claims.push({ plan: planName, ok: true, already: true });
88
- logger.info('ZCODE-CLAIM', '{label}「{plan}」已领取过', { label, plan: planName });
89
- continue;
90
- }
91
- if (e.code === 1005 && e.nextAt) {
92
- snoozeAt = Math.max(snoozeAt, Number(new Date(e.nextAt)) || 0);
93
- }
94
- if (e.code !== 3007 && e.code !== 3001) {
95
- // 1001/1002 = 已知清单兜底里的活动不存在/已结束:静默跳过(不进卡片、不算失败)。
96
- // 只对 known 兜底项生效——preview 列表里的真实活动若返回 1002 仍要如实记失败
97
- if ((e.code === 1001 || e.code === 1002) && plan.known === true) continue;
98
- claims.push({ plan: planName, ok: false, message: e.message });
99
- logger.warn('ZCODE-CLAIM', '{label} 领取「{plan}」失败:{err}', { label, plan: planName, err: e.message });
100
- continue;
101
- }
102
- }
103
- // 第 3 步:需要验证码
104
- if (!captchaProvider) {
105
- needManual = true;
106
- claims.push({ plan: planName, ok: false, needManual: true });
107
- logger.info('ZCODE-CLAIM', '{label}「{plan}」需要验证码,本环境无法自动通过,请在面板手动领取', { label, plan: planName });
108
- continue;
109
- }
110
- try {
111
- const cfg = await fetchCaptchaConfig();
112
- if (!cfg.enabled || !cfg.sceneId) throw new Error('验证码配置不可用');
113
- const { captchaParam, region } = await captchaProvider(cfg);
114
- const r2 = await claimPlan(account, plan.planId, { captchaParam, region });
115
- claims.push({ plan: planName, via: 'captcha', ok: true, startsAt: r2?.startsAt || null });
116
- anySuccess = true;
117
- logger.info('ZCODE-CLAIM', '{label} 已领取「{plan}」(静默验证码){grants}', { label, plan: planName, grants: grantsText(plan) ? ':' + grantsText(plan) : '' });
118
- } catch (e2) {
119
- if (e2.code === 1005 && e2.nextAt) {
120
- snoozeAt = Math.max(snoozeAt, Number(new Date(e2.nextAt)) || 0);
121
- }
122
- needManual = true;
123
- claims.push({ plan: planName, ok: false, needManual: true, message: e2.message });
124
- logger.warn('ZCODE-CLAIM', '{label}「{plan}」验证码未完成:{err}(可在面板手动领取)', { label, plan: planName, err: e2.message });
125
- }
126
- }
127
- // 1005 名额已满 → 按服务端 ends_at 将本账号挂进跳过窗口,下一轮自动轮询在该时间点前不再空打
128
- if (snoozeAt > 0) {
129
- snoozeUntil.set(account.id, snoozeAt);
130
- try {
131
- await withAccounts((list) => {
132
- const cur = list.find((a) => a.id === account.id);
133
- if (cur) {
134
- cur.meta = cur.meta && typeof cur.meta === 'object' && !Array.isArray(cur.meta) ? cur.meta : {};
135
- cur.meta.zcodeClaimNextAt = new Date(snoozeAt).toISOString();
136
- }
137
- });
138
- } catch {}
139
- }
140
-
141
- // 已知清单全部不可领(1001/1002 静默跳过)时 claims 为空:无事发生,不留痕迹
142
- if (!claims.length) return null;
143
- const names = claims.filter((c) => c.ok && !c.already).map((c) => c.plan);
144
- const status = names.length ? 'checked-in'
145
- : claims.every((c) => c.already) ? 'already'
146
- : 'failed';
147
- // 到账时间:新领的活动若带 effective_at(当天稍晚才进余额),把时间写进消息——
148
- // 否则面板只显示「待生效」,用户无法判断是没领上还是要等。
149
- const fmtAt = (iso) => {
150
- if (!iso) return '';
151
- const d = new Date(iso);
152
- if (Number.isNaN(d.getTime())) return '';
153
- const p2 = (n) => String(n).padStart(2, '0');
154
- const now = new Date();
155
- const sameDay = d.toDateString() === now.toDateString();
156
- const hm = `${p2(d.getHours())}:${p2(d.getMinutes())}`;
157
- return sameDay ? hm : `${d.getMonth() + 1}-${p2(d.getDate())} ${hm}`;
158
- };
159
- const starts = claims.filter((c) => c.ok && c.startsAt && new Date(c.startsAt).getTime() > Date.now());
160
- const startsText = starts.length ? `(${fmtAt(starts[0].startsAt)} 到账)` : '';
161
- const message = status === 'checked-in'
162
- ? `已领取:${names.join('、')}${claims.some((c) => c.via === 'captcha') ? '(静默验证码)' : ''}${startsText}`
163
- : status === 'already' ? '活动均已领取过'
164
- : needManual ? `有 ${claims.filter((c) => c.needManual).length} 个活动需要验证码,请在面板手动领取`
165
- : `领取失败:${claims.filter((c) => !c.ok).map((c) => c.message).filter(Boolean)[0] || '未知错误'}`;
166
- return { status, message, claims };
167
- }
1
+ /**
2
+ * ZCode 活动自动领取 — 签到调度器每轮调用。
3
+ *
4
+ * 策略(对齐用户手动路径,逐级尝试):
5
+ * 1. billing/preview 查可领活动;为空 → 无事可做(返回 null,不留痕迹)
6
+ * 2. 先直接 claim(不带验证码:服务端未风控时可直接成功)
7
+ * 3. 返回 3007/3001(需要验证码 / 参数被拒)且有验证码提供者 → 拉 captcha 配置,
8
+ * 让提供者(桌面版的隐藏窗口跑阿里云验证码 SDK 静默验证)拿 captchaVerifyParam 后重试
9
+ * 4. 没有提供者(NAS / 纯 CLI)或验证码需要人工 → 标记「需手动领取」,卡片上提示
10
+ * - 1003(已领取过)按成功口径处理并记忆
11
+ * 结果写入账号 lastResult(签到日历记忆用的是 status checked-in/already,第二天照常重查 preview)
12
+ */
13
+
14
+ import { logger } from './logger.js';
15
+ import { t } from './i18n.js';
16
+ import { fetchClaimPlans, claimPlan, fetchCaptchaConfig } from './zcodeClient.js';
17
+ import { withAccounts } from './store.js';
18
+
19
+ // 额满(1005)时消费服务端 nextAt(plan.ends_at):
20
+ // 下轮自动轮询(claimIntervalMin 分钟一触)在 nextAt 之前跳过该号,不做无谓抢。
21
+ // 进程内缓存 + 落盘 account.meta.zcodeClaimNextAt 双轨(重启保护)。
22
+ const snoozeUntil = new Map(); // accountId → ms 时间戳
23
+
24
+ function snoozeUntilMs(account) {
25
+ const meta = Number(new Date(account?.meta?.zcodeClaimNextAt || 0)) || 0;
26
+ const proc = snoozeUntil.get(account.id) || 0;
27
+ return Math.max(meta, proc);
28
+ }
29
+
30
+ // 桌面版(Electron 主进程)注册的隐藏窗口验证码实现;NAS / CLI 为 null(走「需手动领取」分支)
31
+ let captchaProvider = null;
32
+ export function setZcodeCaptchaProvider(fn) { captchaProvider = typeof fn === 'function' ? fn : null; }
33
+ export function hasZcodeCaptchaProvider() { return Boolean(captchaProvider); }
34
+ export function getZcodeCaptchaProvider() { return captchaProvider; }
35
+
36
+ /** 账号被删除时清掉额满暂休缓存(daemon DELETE /api/accounts/:id 调用;落盘份随账号一起删) */
37
+ export function forgetAccount(id) { snoozeUntil.delete(id); }
38
+
39
+ const grantsText = (plan) => (plan.grants && plan.grants.length ? plan.grants.join(';') : '');
40
+
41
+ /**
42
+ * 为单个 ZCode 账号执行一次自动领取。
43
+ * @returns {null | { status, message, claims: Array }} null = preview 为空或查询失败(已记日志,不上卡片)
44
+ */
45
+ export async function zcodeAutoClaim(account) {
46
+ const label = account.name || account.uid || account.id;
47
+ {
48
+ const until = snoozeUntilMs(account);
49
+ if (until && until > Date.now()) {
50
+ logger.debug('ZCODE-CLAIM', '{label} 名额已领完,跳过直到 {until}(服务端计划结束点)', { label, until: new Date(until).toISOString() });
51
+ return null;
52
+ }
53
+ }
54
+ let plans;
55
+ try {
56
+ plans = (await fetchClaimPlans(account)).plans;
57
+ } catch (e) {
58
+ logger.debug('ZCODE-CLAIM', '{label} 活动查询失败:{err}', { label, err: e.message });
59
+ return null;
60
+ }
61
+ if (!plans.length) {
62
+ // 没有可领活动就如实返回 null(不落卡片、不报错)。
63
+ // fetchClaimPlans 已经把 billing/preview 与 marketing/touch 两路合并过,
64
+ // 空结果就是服务端真的没投放——不再拿硬编码 planId 去撞(会随活动换代失效)。
65
+ return null;
66
+ }
67
+
68
+ const claims = [];
69
+ let anySuccess = false;
70
+ let needManual = false;
71
+
72
+ let snoozeAt = 0;
73
+ for (const plan of plans) {
74
+ const planName = plan.name || plan.planId;
75
+ // 第 2 步:先试不带验证码
76
+ try {
77
+ const r = await claimPlan(account, plan.planId, {});
78
+ // startsAt 是「到账时间」:活动权益常带 effective_at(如当天 23:00),
79
+ // 领到了但余额里还没有——不把这个时间带出去,面板只能显示冷冰冰的
80
+ // 「待生效」,用户以为没领上。
81
+ claims.push({ plan: planName, via: 'direct', ok: true, startsAt: r?.startsAt || null });
82
+ anySuccess = true;
83
+ logger.info('ZCODE-CLAIM', '{label} 已领取「{plan}」(免验证码){grants}', { label, plan: planName, grants: grantsText(plan) ? ':' + grantsText(plan) : '' });
84
+ continue;
85
+ } catch (e) {
86
+ if (e.code === 1003) {
87
+ claims.push({ plan: planName, ok: true, already: true });
88
+ logger.info('ZCODE-CLAIM', '{label}「{plan}」已领取过', { label, plan: planName });
89
+ continue;
90
+ }
91
+ if (e.code === 1005 && e.nextAt) {
92
+ snoozeAt = Math.max(snoozeAt, Number(new Date(e.nextAt)) || 0);
93
+ }
94
+ if (e.code !== 3007 && e.code !== 3001) {
95
+ // 1001/1002 = 已知清单兜底里的活动不存在/已结束:静默跳过(不进卡片、不算失败)。
96
+ // 只对 known 兜底项生效——preview 列表里的真实活动若返回 1002 仍要如实记失败
97
+ if ((e.code === 1001 || e.code === 1002) && plan.known === true) continue;
98
+ claims.push({ plan: planName, ok: false, message: e.message });
99
+ logger.warn('ZCODE-CLAIM', '{label} 领取「{plan}」失败:{err}', { label, plan: planName, err: e.message });
100
+ continue;
101
+ }
102
+ }
103
+ // 第 3 步:需要验证码
104
+ if (!captchaProvider) {
105
+ needManual = true;
106
+ claims.push({ plan: planName, ok: false, needManual: true });
107
+ logger.info('ZCODE-CLAIM', '{label}「{plan}」需要验证码,本环境无法自动通过,请在面板手动领取', { label, plan: planName });
108
+ continue;
109
+ }
110
+ try {
111
+ const cfg = await fetchCaptchaConfig();
112
+ if (!cfg.enabled || !cfg.sceneId) throw new Error('验证码配置不可用');
113
+ const { captchaParam, region } = await captchaProvider(cfg);
114
+ const r2 = await claimPlan(account, plan.planId, { captchaParam, region });
115
+ claims.push({ plan: planName, via: 'captcha', ok: true, startsAt: r2?.startsAt || null });
116
+ anySuccess = true;
117
+ logger.info('ZCODE-CLAIM', '{label} 已领取「{plan}」(静默验证码){grants}', { label, plan: planName, grants: grantsText(plan) ? ':' + grantsText(plan) : '' });
118
+ } catch (e2) {
119
+ if (e2.code === 1005 && e2.nextAt) {
120
+ snoozeAt = Math.max(snoozeAt, Number(new Date(e2.nextAt)) || 0);
121
+ }
122
+ needManual = true;
123
+ claims.push({ plan: planName, ok: false, needManual: true, message: e2.message });
124
+ logger.warn('ZCODE-CLAIM', '{label}「{plan}」验证码未完成:{err}(可在面板手动领取)', { label, plan: planName, err: e2.message });
125
+ }
126
+ }
127
+ // 1005 名额已满 → 按服务端 ends_at 将本账号挂进跳过窗口,下一轮自动轮询在该时间点前不再空打
128
+ if (snoozeAt > 0) {
129
+ snoozeUntil.set(account.id, snoozeAt);
130
+ try {
131
+ await withAccounts((list) => {
132
+ const cur = list.find((a) => a.id === account.id);
133
+ if (cur) {
134
+ cur.meta = cur.meta && typeof cur.meta === 'object' && !Array.isArray(cur.meta) ? cur.meta : {};
135
+ cur.meta.zcodeClaimNextAt = new Date(snoozeAt).toISOString();
136
+ }
137
+ });
138
+ } catch {}
139
+ }
140
+
141
+ // 已知清单全部不可领(1001/1002 静默跳过)时 claims 为空:无事发生,不留痕迹
142
+ if (!claims.length) return null;
143
+ const names = claims.filter((c) => c.ok && !c.already).map((c) => c.plan);
144
+ const status = names.length ? 'checked-in'
145
+ : claims.every((c) => c.already) ? 'already'
146
+ : 'failed';
147
+ // 到账时间:新领的活动若带 effective_at(当天稍晚才进余额),把时间写进消息——
148
+ // 否则面板只显示「待生效」,用户无法判断是没领上还是要等。
149
+ const fmtAt = (iso) => {
150
+ if (!iso) return '';
151
+ const d = new Date(iso);
152
+ if (Number.isNaN(d.getTime())) return '';
153
+ const p2 = (n) => String(n).padStart(2, '0');
154
+ const now = new Date();
155
+ const sameDay = d.toDateString() === now.toDateString();
156
+ const hm = `${p2(d.getHours())}:${p2(d.getMinutes())}`;
157
+ return sameDay ? hm : `${d.getMonth() + 1}-${p2(d.getDate())} ${hm}`;
158
+ };
159
+ const starts = claims.filter((c) => c.ok && c.startsAt && new Date(c.startsAt).getTime() > Date.now());
160
+ const startsText = starts.length ? `(${fmtAt(starts[0].startsAt)} 到账)` : '';
161
+ const message = status === 'checked-in'
162
+ ? `已领取:${names.join('、')}${claims.some((c) => c.via === 'captcha') ? '(静默验证码)' : ''}${startsText}`
163
+ : status === 'already' ? '活动均已领取过'
164
+ : needManual ? `有 ${claims.filter((c) => c.needManual).length} 个活动需要验证码,请在面板手动领取`
165
+ : `领取失败:${claims.filter((c) => !c.ok).map((c) => c.message).filter(Boolean)[0] || '未知错误'}`;
166
+ return { status, message, claims };
167
+ }
@@ -304,8 +304,11 @@ function combineSignals({ wallSignal, connectSignal, external }) {
304
304
  * 跑几分钟,不能因为「连接快、生成慢」被误杀。
305
305
  * 不传 connectMs 时退回单段 timeoutMs(旧行为,所有既有调用方不受影响)。
306
306
  */
307
- export async function fetchJsonRace(url, { method = 'GET', headers = {}, body = null, timeoutMs = 15000, connectMs = null, signal = null, preferProxy = false, redirect = 'manual' } = {}) {
308
- const useProxy = Boolean(effectiveProxy()) && !proxyBypass(url);
307
+ export async function fetchJsonRace(url, { method = 'GET', headers = {}, body = null, timeoutMs = 15000, connectMs = null, signal = null, preferProxy = false, redirect = 'manual', directOnly = false } = {}) {
308
+ // directOnly:强制直连、永不走代理。用于「响应按来源 IP 变化」的端点
309
+ //(client/configs 的验证码 region 按出口 IP 下发 cn/sgp,region 与场景不匹配 → 验证恒失败)。
310
+ // 集中出口仍归这里管:不设代理时行为不变,双路聚合报错也照常(issue #31 的教训不回退)。
311
+ const useProxy = !directOnly && Boolean(effectiveProxy()) && !proxyBypass(url);
309
312
  const twoPhase = Number.isFinite(connectMs) && connectMs > 0 && connectMs < timeoutMs;
310
313
  // 超时信号必须每次尝试各建一个:共用一个的话,代理优先模式下第一条路吃完 timeoutMs,
311
314
  // 兜底那条就对着已触发的 signal 发请求,必定瞬间失败——「代理优先」就此形同虚设
@@ -377,15 +380,186 @@ const CLAIM_FAIL = {
377
380
  const platform = () => `${process.platform}-${process.arch === 'arm64' ? 'arm64' : process.arch === 'x64' ? 'x64' : process.arch}`;
378
381
 
379
382
  /**
380
- * 已知活动兜底清单:服务端偶尔把活动从 billing/preview 里藏起来(2026-10-30 WEEKEND BUILD
381
- * 实测 preview 返回空 plans,但 claim 按 planId 直接可领、免验证码)。preview 查不到时
382
- * 逐个试这里的 planId:1001/1002(不存在/已结束)当没有,1003 按已领口径,0 即领取成功。
383
- * 活动过期后条目留在表里无害(claim 返回 1002 跳过);新活动出现时在此追加一行。
383
+ * 已知活动兜底清单(**仅作最后兜底**,正常路径不依赖它)。
384
+ *
385
+ * ⚠️ 教训(2026-11-04):曾经把这里当成主路径,结果活动一换 ID 就全废——
386
+ * 用户看到的是「活动已结束」+「打开验证码也没用」,功能形同虚设。
387
+ * 真正的解法是 billing/preview 之前先上报激活事件(见 reportActivationEvents),
388
+ * 服务端才会把这个客户端当活跃端并下发活动列表。
389
+ *
390
+ * **2026-11-04 最终定论:这个清单已彻底废弃,只留空数组占位。**
391
+ * 真机实测证明活动 ID 会换(1102 → gb-1104),任何硬编码都必然过期;
392
+ * 而正确来源是 `/api/v1/marketing/touch` 的 deliveries——官方客户端就是从那里拿 plan_id 的。
393
+ * 见 fetchMarketingClaimPlans()。留着空数组只是为了让旧的调用方不用改。
384
394
  */
385
- export const ZCODE_KNOWN_CLAIM_PLANS = [
386
- { planId: 'zcode-v3-start-plan-1102', name: 'ZCODE GLOBAL BUILD' },
387
- { planId: 'zcode-v3-start-plan-1030-wk', name: 'ZCODE WEEKEND BUILD' },
388
- ];
395
+ export const ZCODE_KNOWN_CLAIM_PLANS = [];
396
+
397
+ // ── 活动发现:marketing/touch(官方客户端的真实来源) ──
398
+ // 服务端把活动卡投放放在这里,billing/preview 对隐藏活动返回空。
399
+ // deliveries[].banner.buttons[].action = { type:'claim_zcode_plan', args:{ plan_id } }
400
+ // 同一条 delivery 的 args.zcode_plan 里带完整权益(name / grant_units / effective_at / ends_at)。
401
+ // 2026-11-04 真机实测:preview 空、marketing/touch 返回 plan_id = zcode-v3-start-plan-gb-1104。
402
+ const MARKETING_TOUCH_URL = 'https://zcode.z.ai/api/v1/marketing/touch';
403
+
404
+ /** 递归收集一个对象里所有 claim_zcode_plan 动作的 plan_id */
405
+ export function collectClaimActions(node, out) {
406
+ if (!node || typeof node !== 'object') return;
407
+ if (Array.isArray(node)) { node.forEach((x) => collectClaimActions(x, out)); return; }
408
+ if (node.type === 'claim_zcode_plan' && node.args && typeof node.args.plan_id === 'string') {
409
+ out.add(node.args.plan_id.trim());
410
+ }
411
+ for (const v of Object.values(node)) collectClaimActions(v, out);
412
+ }
413
+
414
+ /** 递归找 zcode_plan 元数据(name / grant_units / 时间) */
415
+ export function collectPlanMeta(node, out) {
416
+ if (!node || typeof node !== 'object') return;
417
+ if (Array.isArray(node)) { node.forEach((x) => collectPlanMeta(x, out)); return; }
418
+ const zp = node.zcode_plan;
419
+ if (zp && typeof zp === 'object' && typeof zp.plan_id === 'string') {
420
+ const id = zp.plan_id.trim();
421
+ if (id && !out.has(id)) {
422
+ const grants = (Array.isArray(zp.entitlements) ? zp.entitlements : []).map((e) => {
423
+ const units = Number(e.grant_units) || 0;
424
+ const shown = units >= 1e8 ? +(units / 1e8).toFixed(1) + '亿' : units >= 1e4 ? +(units / 1e4).toFixed(1) + '万' : String(units);
425
+ return `${e.show_name || '额度'} · ${shown} Token(一次性)`;
426
+ });
427
+ out.set(id, {
428
+ name: zp.name || id,
429
+ description: '',
430
+ grants,
431
+ priority: Number(zp.priority) || 0,
432
+ startsAt: Number(zp.starts_at) || null,
433
+ endsAt: Number(zp.ends_at) || null,
434
+ });
435
+ }
436
+ }
437
+ for (const v of Object.values(node)) collectPlanMeta(v, out);
438
+ }
439
+
440
+ /**
441
+ * 从 marketing/touch 发现可领取的活动(含隐藏活动)。
442
+ * 这是官方客户端的真实数据源,比 billing/preview 更可靠——preview 对隐藏活动返回空。
443
+ *
444
+ * @returns {Promise<Array<{planId,name,description,grants,priority,source}>>}
445
+ */
446
+ export async function fetchMarketingClaimPlans(account) {
447
+ const mid = ensureVirtualDeviceMid(account);
448
+ const ids = new Set();
449
+ const metas = new Map();
450
+ let lastErr = null;
451
+ // 三个候选 token 里只有一个是 billing 权限的(真机实测 token#1 有效),逐个试
452
+ for (const t of candidateTokens(account)) {
453
+ try {
454
+ const res = await fetchJsonRace(`${MARKETING_TOUCH_URL}?seq=${Date.now() % 1_000_000}`, {
455
+ headers: await zaiHeaders(t, mid),
456
+ timeoutMs: FETCH_TIMEOUT_MS,
457
+ });
458
+ const text = await res.text();
459
+ let v;
460
+ try { v = JSON.parse(text); } catch { continue; }
461
+ if (Number(v?.code) !== 0) { lastErr = v?.msg || `code ${v?.code}`; continue; }
462
+ const deliveries = v?.data?.deliveries;
463
+ if (!Array.isArray(deliveries) || !deliveries.length) continue;
464
+ for (const d of deliveries) {
465
+ collectClaimActions(d, ids);
466
+ collectPlanMeta(d, metas);
467
+ }
468
+ if (ids.size) break; // 拿到就停,不必再试其它 token
469
+ } catch (e) { lastErr = e.message; }
470
+ }
471
+ if (!ids.size) return { plans: [], error: lastErr };
472
+ const plans = [...ids].map((id) => {
473
+ const m = metas.get(id) || {};
474
+ return {
475
+ planId: id,
476
+ name: m.name || id,
477
+ description: m.description || '',
478
+ grants: m.grants || [],
479
+ priority: m.priority || 0,
480
+ startsAt: m.startsAt,
481
+ endsAt: m.endsAt,
482
+ source: 'marketing',
483
+ };
484
+ });
485
+ plans.sort((a, b) => b.priority - a.priority);
486
+ return { plans, error: null };
487
+ }
488
+
489
+ // ── 激活事件上报(活动领取的前置条件) ──
490
+ // 移植自 zcode-switch(MIT)claim.rs 的 report_activation_events。
491
+ // 服务端按「活跃客户端」判定活动资格:不上报 app_launch / app_daily_active 时,
492
+ // billing/preview 恒返回空 plans,claim 也会被当成非活跃端拒绝。
493
+ // 这就是「只能在官方客户端里领」的根因——官方客户端启动时天天在报这些事件。
494
+ const EVENT_REPORT_URL = 'https://zcode.z.ai/api/v1/event/report';
495
+ const ACTIVATION_EVENTS = ['app_launch', 'app_daily_active'];
496
+ const SCREEN_RESOLUTION = '2560x1440';
497
+
498
+ /** 从凭据里取遥测用的 user_id(oauth:<provider>:user_info 解密后的 id / user_id) */
499
+ function telemetryUserId(account) {
500
+ const creds = account?.meta?.credentials || {};
501
+ const secret = defaultSecret(os.homedir());
502
+ const provider = (safeDecrypt(creds['oauth:active_provider'], secret) || 'zai').trim() || 'zai';
503
+ const raw = creds[`oauth:${provider}:user_info`];
504
+ if (typeof raw !== 'string' || !raw) return null;
505
+ try {
506
+ const info = JSON.parse(safeDecrypt(raw, secret) || raw);
507
+ const pick = (k) => { const v = info?.[k]; return typeof v === 'string' && v.trim() ? v.trim() : null; };
508
+ return pick('id') || pick('user_id') || null;
509
+ } catch { return null; }
510
+ }
511
+
512
+ /**
513
+ * 上报激活事件(活动领取前调用)。
514
+ * 返回 { reported: boolean, userId, error? }——失败不阻塞领取,只是 preview 可能拿不到活动。
515
+ */
516
+ export async function reportActivationEvents(account) {
517
+ const userId = telemetryUserId(account);
518
+ if (!userId) return { reported: false, userId: null, error: '凭据里没有 user_info,无法上报激活事件' };
519
+ const deviceMid = ensureVirtualDeviceMid(account);
520
+ const ver = await zcodeAppVersion();
521
+ const token = claimToken(account);
522
+ const osCategory = process.platform === 'win32' ? 'windows' : process.platform === 'darwin' ? 'macos' : 'linux';
523
+ const osVersion = os.release();
524
+ for (const element of ACTIVATION_EVENTS) {
525
+ const body = {
526
+ event_id: crypto.randomUUID(),
527
+ client_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'Asia/Shanghai',
528
+ client_language: 'zh-CN',
529
+ element_name: element,
530
+ event_region: 'app',
531
+ event_type: 'view',
532
+ event_text: '',
533
+ event_extra_detail: {},
534
+ user_id: userId,
535
+ screen_resolution: SCREEN_RESOLUTION,
536
+ app_version: ver,
537
+ device_os_category: osCategory,
538
+ device_os_version: osVersion,
539
+ device_mid: deviceMid,
540
+ mac_id: '',
541
+ marketing_params: '{}',
542
+ };
543
+ try {
544
+ const res = await fetchJsonRace(EVENT_REPORT_URL, {
545
+ method: 'POST',
546
+ headers: { ...(await zaiHeaders(token, deviceMid)), 'Content-Type': 'application/json' },
547
+ body,
548
+ timeoutMs: 10_000,
549
+ });
550
+ const text = await res.text();
551
+ let v;
552
+ try { v = JSON.parse(text); } catch { v = { code: res.status }; }
553
+ const code = Number(v?.code ?? -1);
554
+ if (code !== 0) {
555
+ return { reported: false, userId, error: `激活事件 ${element} 上报被拒(code ${code}${v?.msg ? ':' + v.msg : ''})` };
556
+ }
557
+ } catch (e) {
558
+ return { reported: false, userId, error: `激活事件 ${element} 上报失败:${e.message}` };
559
+ }
560
+ }
561
+ return { reported: true, userId };
562
+ }
389
563
 
390
564
  export async function zaiHeaders(token, deviceMid) {
391
565
  const ver = await zcodeAppVersion();
@@ -649,21 +823,87 @@ export async function fetchZcodeQuota(account) {
649
823
 
650
824
  // ── 活动领取 ──
651
825
 
652
- /** 可领取的活动列表。账户当前没有可领活动时返回 [](不是错误)。 */
826
+ /**
827
+ * 可领取的活动列表。账户当前没有可领活动时返回 [](不是错误)。
828
+ *
829
+ * ⚠️ 顺序很重要:必须**先上报激活事件**(app_launch / app_daily_active)再查 preview。
830
+ * 服务端按「活跃客户端」判定活动资格——不上报时 preview 恒返回空 plans,
831
+ * 于是只能靠硬编码 planId 撞运气,活动一换 ID 就全废(2026-11-04 实践教训)。
832
+ * 移植自 zcode-switch(MIT)claim.rs:claim_refresh 里 report_activation_events → preview_plans。
833
+ */
653
834
  export async function fetchClaimPlans(account) {
654
835
  const token = claimToken(account);
655
- const v = await getJson(
656
- `${BILLING_PREVIEW_URL}?app_version=${await zcodeAppVersion()}&platform=${platform()}`,
657
- await zaiHeaders(token, ensureVirtualDeviceMid(account)),
658
- );
659
- if (v?.code !== 0) throw new Error(v?.msg || v?.message || `查询活动列表失败(code ${v?.code})`);
660
- return { plans: normalizePlans(v), serverTime: v?.data?.server_time ? new Date(v.data.server_time * 1000).toISOString() : null };
836
+ // 激活事件失败不阻塞查询(服务端偶尔抖动),但要让调用方知道结果用于诊断
837
+ const activation = await reportActivationEvents(account).catch((e) => ({ reported: false, error: e.message }));
838
+
839
+ // 两路合并取并集:
840
+ // preview —— 公开活动(非隐藏)
841
+ // marketing/touch —— 投放活动(含隐藏活动,官方客户端用的就是这个)
842
+ // 只靠 preview 会导致「客户端有卡、我们空」,2026-11-04 实测正是此情况。
843
+ let previewPlans = [];
844
+ let serverTime = null;
845
+ let previewErr = null;
846
+ try {
847
+ const v = await getJson(
848
+ `${BILLING_PREVIEW_URL}?app_version=${await zcodeAppVersion()}&platform=${platform()}`,
849
+ await zaiHeaders(token, ensureVirtualDeviceMid(account)),
850
+ );
851
+ if (v?.code === 0) {
852
+ previewPlans = normalizePlans(v);
853
+ serverTime = v?.data?.server_time ? new Date(v.data.server_time * 1000).toISOString() : null;
854
+ } else previewErr = v?.msg || v?.message || `code ${v?.code}`;
855
+ } catch (e) { previewErr = e.message; }
856
+
857
+ const marketing = await fetchMarketingClaimPlans(account).catch((e) => ({ plans: [], error: e.message }));
858
+
859
+ const byId = new Map();
860
+ for (const p of [...previewPlans, ...(marketing.plans || [])]) {
861
+ if (!p?.planId) continue;
862
+ const prev = byId.get(p.planId);
863
+ // 同一活动两路都有时,营销侧的权益信息更全(带 grant_units / 生效时间),优先保留
864
+ if (!prev || (p.grants || []).length > (prev.grants || []).length) byId.set(p.planId, p);
865
+ }
866
+ const plans = [...byId.values()].sort((a, b) => (b.priority || 0) - (a.priority || 0));
867
+
868
+ // 两路都失败才算真失败;任一路有结果就返回(空列表 = 确实没有可领活动)
869
+ if (!plans.length && previewErr && marketing.error) {
870
+ throw new Error(previewErr || marketing.error);
871
+ }
872
+ return {
873
+ plans,
874
+ serverTime,
875
+ activation,
876
+ diagnostics: {
877
+ preview: { count: previewPlans.length, error: previewErr },
878
+ marketing: { count: (marketing.plans || []).length, error: marketing.error },
879
+ },
880
+ };
661
881
  }
662
882
 
663
883
  /** 验证码配置(无需登录)。当前服务端未下发时返回 { enabled: false }。 */
664
884
  export async function fetchCaptchaConfig() {
665
885
  // 公开端点:不带任何鉴权头(空 token 会生成畸形的 "Authorization: Bearer ",被上游判为 3001)
666
- const v = await getJson(CLIENT_CONFIGS_URL);
886
+ //
887
+ // ⚠️ 这个请求**必须直连**,不能走代理:服务端按来源 IP 下发验证码区域
888
+ // (国内 IP → region:"cn",海外 IP → region:"sgp")。而阿里云验证码的场景是在
889
+ // cn 场景签发的,region 与场景不匹配时人机验证永远无法通过 → claim 恒 3007。
890
+ // 2026-11-04 实测:经新加坡出口拿到 region:"sgp",直连拿到 region:"cn"。
891
+ // directOnly 走集中出口的直连路(不再裸 fetch 绕过传输层——1.7.0 审计发现);
892
+ // 直连不可达时才退回带代理的统一出口,至少还能拿到一份配置。
893
+ // 注意 fetchJsonRace 返回 Response,必须先 text() 再 parse——
894
+ // 直接把 Response 当 JSON 用会让 `v.code` 恒 undefined → 配置永远判失败(本文件 1.7.0 回归)。
895
+ let v;
896
+ try {
897
+ const res = await fetchJsonRace(CLIENT_CONFIGS_URL, {
898
+ headers: { Accept: 'application/json' },
899
+ timeoutMs: FETCH_TIMEOUT_MS,
900
+ directOnly: true,
901
+ });
902
+ const text = await res.text();
903
+ try { v = JSON.parse(text); } catch { v = { code: res.status, msg: text.slice(0, 120) }; }
904
+ } catch {
905
+ v = await getJson(CLIENT_CONFIGS_URL);
906
+ }
667
907
  if (v?.code !== 0) throw new Error('获取验证码配置失败');
668
908
  const c = v?.data?.configs?.captcha || {};
669
909
  return {