creditdaddy 1.7.2 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +701 -2
  2. package/README.md +454 -440
  3. package/bin/creditdaddy.js +6 -0
  4. package/build.json +3 -3
  5. package/package.json +34 -34
  6. package/src/accounts.js +15 -0
  7. package/src/assets/donate-alipay.svg +1 -1
  8. package/src/assets/donate-ifdian.svg +1 -1
  9. package/src/assets/donate-wechat.svg +1 -1
  10. package/src/assets/providers/catpaw.png +0 -0
  11. package/src/assets/providers/codebuddy-ide.png +0 -0
  12. package/src/assets/providers/dumate.png +0 -0
  13. package/src/assets/providers/loomy.png +0 -0
  14. package/src/assets/providers/meoo.png +0 -0
  15. package/src/assets/providers/mirasim.png +0 -0
  16. package/src/bgdaemon.js +341 -341
  17. package/src/buildInfo.js +65 -65
  18. package/src/catpawClient.js +103 -103
  19. package/src/catpawLocal.js +236 -236
  20. package/src/checkin.js +98 -5
  21. package/src/codebuddyIdeLocal.js +381 -381
  22. package/src/constants.js +121 -117
  23. package/src/cookieSites.js +340 -301
  24. package/src/daemon.js +2720 -2443
  25. package/src/doubaoClient.js +167 -167
  26. package/src/dumateClient.js +517 -0
  27. package/src/dumateLocal.js +298 -0
  28. package/src/dumateQr.js +337 -0
  29. package/src/externalQuota.js +577 -574
  30. package/src/formatDuration.js +17 -17
  31. package/src/i18n/en.json +257 -7
  32. package/src/i18n/ja.json +257 -7
  33. package/src/i18n/ko.json +257 -7
  34. package/src/i18n/zh-TW.json +257 -7
  35. package/src/i18n.js +47 -47
  36. package/src/lingxiClient.js +373 -373
  37. package/src/localDetect.js +147 -147
  38. package/src/longcatClient.js +260 -260
  39. package/src/loomyAuth.js +230 -230
  40. package/src/loomyClient.js +366 -366
  41. package/src/loomyLocal.js +206 -206
  42. package/src/meooAuth.js +246 -0
  43. package/src/meooClient.js +250 -0
  44. package/src/minimaxGateway.js +520 -520
  45. package/src/minimaxLocal.js +344 -344
  46. package/src/mirasimClient.js +211 -211
  47. package/src/mirasimLocal.js +392 -392
  48. package/src/modelscopeClient.js +275 -275
  49. package/src/panel.html +704 -85
  50. package/src/prodIcons.json +7 -5
  51. package/src/providers.js +34 -0
  52. package/src/qoderApp.js +578 -578
  53. package/src/qoderClient.js +266 -266
  54. package/src/qoderUmid.js +199 -199
  55. package/src/quotaRefresh.js +119 -119
  56. package/src/refreshGuard.js +75 -75
  57. package/src/riverClient.js +372 -372
  58. package/src/store.js +2 -1
  59. package/src/tenrouterAccounts.js +237 -232
  60. package/src/traeAuth.js +601 -599
  61. package/src/traeClient.js +356 -360
  62. package/src/traeGateway.js +875 -875
  63. package/src/traeLocal.js +463 -371
  64. package/src/transfer.js +4 -0
  65. package/src/usageSync.js +535 -523
  66. package/src/winProc.js +134 -134
  67. package/src/xiaomiMimoClient.js +206 -206
  68. package/src/zcodeAuth.js +131 -131
  69. package/src/zcodeAutoClaim.js +53 -6
  70. package/src/zcodeClient.js +55 -2
  71. package/src/zcodeGateway.js +850 -850
  72. package/src/zcodeLocal.js +340 -340
  73. package/src/zcrypto.js +160 -160
package/src/zcodeAuth.js CHANGED
@@ -1,131 +1,131 @@
1
- /**
2
- * ZCode 浏览器登录 — 与 ZCode 客户端的「CLI 轮询登录」同一协议(无需 zcode:// 回调,任何浏览器都能用):
3
- *
4
- * 1. POST https://zcode.z.ai/api/v1/oauth/cli/init Authorization: Bearer <本地随机 poll token>
5
- * {provider: 'bigmodel' | 'zai'} → {flow_id, authorize_url, expires_at, poll_interval_sec}
6
- * authorize_url 的回调指向 zcode.z.ai 自己的 /oauth/cli/callback,由服务端完成换 token
7
- * 2. 用户在浏览器(桌面版为隐私窗口)打开 authorize_url 登录授权
8
- * 3. GET /api/v1/oauth/cli/poll/{flow_id}(同一 poll token)→ status pending / ready / failed
9
- * ready 时带 token(zcode JWT)、user、bigmodel{access_token, refresh_token} 或 zai{access_token}
10
- * 4. Z.ai 的 access_token 还要换一次业务 token:POST https://api.z.ai/api/auth/z/login {token}
11
- *
12
- * 拿到的凭据按客户端 credentials.json 的格式(enc:v1 加密)组装,存进账号 meta,
13
- * 之后与「本机导入」的账号完全一样:可查额度、可一键切换到 ZCode 客户端。
14
- */
15
-
16
- import crypto from 'node:crypto';
17
- import * as zc from './zcrypto.js';
18
- import { zcodePaths } from './zcodeLocal.js';
19
- import { FETCH_TIMEOUT_MS } from './constants.js';
20
-
21
- const API_BASE = 'https://zcode.z.ai';
22
- const ZAI_BUSINESS_LOGIN_URL = 'https://api.z.ai/api/auth/z/login';
23
-
24
- async function fetchJson(url, init = {}) {
25
- const res = await fetch(url, { ...init, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
26
- const text = await res.text();
27
- let body = null;
28
- try { body = text ? JSON.parse(text) : null; } catch {}
29
- return { res, body };
30
- }
31
-
32
- const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
33
-
34
- /** kind: 'zcode-bigmodel'(智谱 BigModel)| 'zcode-zai'(Z.ai 国际) */
35
- export async function startZcodeLogin(kind) {
36
- const provider = kind === 'zcode-zai' ? 'zai' : 'bigmodel';
37
- const pollToken = crypto.randomBytes(32).toString('hex');
38
- const { res, body } = await fetchJson(API_BASE + '/api/v1/oauth/cli/init', {
39
- method: 'POST',
40
- headers: { Authorization: 'Bearer ' + pollToken, 'Content-Type': 'application/json', Accept: 'application/json' },
41
- body: JSON.stringify({ provider }),
42
- });
43
- const d = body?.data;
44
- if (!res.ok || body?.code !== 0 || !str(d?.flow_id) || !str(d?.authorize_url)) {
45
- throw new Error('ZCode 登录初始化失败:' + (body?.msg || 'HTTP ' + res.status));
46
- }
47
- if (!d.authorize_url.startsWith('https://')) throw new Error('ZCode 登录初始化返回了非 https 授权地址');
48
- const expiresInMs = Number.isFinite(d.expires_at) ? d.expires_at * 1000 - Date.now() : 5 * 60e3;
49
- return {
50
- url: d.authorize_url,
51
- expiresInMs: Math.max(60e3, Math.min(expiresInMs, 15 * 60e3)),
52
- intervalMs: Math.max(1000, (Number(d.poll_interval_sec) || 2) * 1000),
53
- data: { provider, flowId: d.flow_id, pollToken },
54
- };
55
- }
56
-
57
- /** 单次轮询:{status:'pending'} | {status:'ok', input};失败抛错 */
58
- export async function pollZcodeLogin(data) {
59
- const { res, body } = await fetchJson(API_BASE + '/api/v1/oauth/cli/poll/' + encodeURIComponent(data.flowId), {
60
- headers: { Authorization: 'Bearer ' + data.pollToken, Accept: 'application/json' },
61
- });
62
- if (res.status >= 500 || res.status === 408 || res.status === 429) return { status: 'pending' };
63
- if (!res.ok || body?.code !== 0) throw new Error('ZCode 授权失败:' + (body?.msg || 'HTTP ' + res.status));
64
- const d = body.data || {};
65
- if (d.status === 'pending') return { status: 'pending' };
66
- if (d.status === 'failed') throw new Error('ZCode 授权失败(用户取消或授权被拒绝)');
67
- if (d.status !== 'ready') throw new Error('ZCode 授权返回未知状态:' + d.status);
68
-
69
- const jwt = str(d.token);
70
- const user = d.user && typeof d.user === 'object' ? d.user : {};
71
- const userId = user.user_id !== undefined && user.user_id !== null ? String(user.user_id) : null;
72
- let accessToken = data.provider === 'zai' ? str(d.zai?.access_token) : str(d.bigmodel?.access_token) || str(d.bigmodel?.accessToken);
73
- const refreshToken = data.provider === 'bigmodel' ? str(d.bigmodel?.refresh_token) || str(d.bigmodel?.refreshToken) : null;
74
- if (!jwt || !accessToken || !userId) throw new Error('ZCode 授权返回缺少 token / 用户信息(上游结构可能变化)');
75
- if (data.provider === 'zai') accessToken = await resolveZaiBusinessToken(accessToken);
76
-
77
- return { status: 'ok', input: buildAccountInput({ provider: data.provider, jwt, accessToken, refreshToken, user, userId }) };
78
- }
79
-
80
- /** Z.ai OAuth token → 业务 access token(与客户端 ZaiBusinessTokenResolver 一致) */
81
- async function resolveZaiBusinessToken(oauthToken) {
82
- const { res, body } = await fetchJson(ZAI_BUSINESS_LOGIN_URL, {
83
- method: 'POST',
84
- headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
85
- body: JSON.stringify({ token: oauthToken }),
86
- });
87
- const ok = res.ok && (body?.code === undefined || body.code === 0 || body.code === 200) && body?.success !== false;
88
- const t = str(body?.data?.access_token) || str(body?.data?.accessToken);
89
- if (!ok || !t) throw new Error('Z.ai 业务 token 交换失败:' + (body?.msg || 'HTTP ' + res.status));
90
- return t;
91
- }
92
-
93
- /** 按 ZCode credentials.json 的键名组装并用本机密钥加密(与客户端写出的格式一致) */
94
- export function buildCredentials({ provider, jwt, accessToken, refreshToken, user, userId }, secret) {
95
- const label = str(user.name) || str(user.email) || userId;
96
- const userInfo = {
97
- id: userId, username: label, displayName: label,
98
- ...(str(user.avatar) ? { avatarUrl: user.avatar } : {}),
99
- rawProfile: user,
100
- };
101
- const enc = (v) => zc.encryptWithSecret(v, secret);
102
- const creds = {
103
- 'oauth:active_provider': enc(provider),
104
- [`oauth:${provider}:access_token`]: enc(accessToken),
105
- [`oauth:${provider}:user_info`]: enc(JSON.stringify(userInfo)),
106
- zcodejwttoken: enc(jwt),
107
- };
108
- if (refreshToken) creds[`oauth:${provider}:refresh_token`] = enc(refreshToken);
109
- return creds;
110
- }
111
-
112
- function buildAccountInput(parts) {
113
- const secret = zc.defaultSecret(zcodePaths().home);
114
- const credentials = buildCredentials(parts, secret);
115
- const id = zc.identityWithSecret(credentials, secret);
116
- return {
117
- provider: 'zcode',
118
- token: `zcode-creds:${parts.userId}`, // 与本机导入同一标记,同一用户自动去重 / 续期
119
- uid: parts.userId,
120
- name: zc.identityLabel(id),
121
- email: str(parts.user.email),
122
- source: 'browser',
123
- // 不带 config / deviceMid:同一账号再次登录时保留已保存的客户端配置与虚拟设备 ID
124
- meta: {
125
- credentials,
126
- canonicalHash: zc.canonicalHash(credentials),
127
- capturedAt: new Date().toISOString(),
128
- loginProvider: parts.provider,
129
- },
130
- };
131
- }
1
+ /**
2
+ * ZCode 浏览器登录 — 与 ZCode 客户端的「CLI 轮询登录」同一协议(无需 zcode:// 回调,任何浏览器都能用):
3
+ *
4
+ * 1. POST https://zcode.z.ai/api/v1/oauth/cli/init Authorization: Bearer <本地随机 poll token>
5
+ * {provider: 'bigmodel' | 'zai'} → {flow_id, authorize_url, expires_at, poll_interval_sec}
6
+ * authorize_url 的回调指向 zcode.z.ai 自己的 /oauth/cli/callback,由服务端完成换 token
7
+ * 2. 用户在浏览器(桌面版为隐私窗口)打开 authorize_url 登录授权
8
+ * 3. GET /api/v1/oauth/cli/poll/{flow_id}(同一 poll token)→ status pending / ready / failed
9
+ * ready 时带 token(zcode JWT)、user、bigmodel{access_token, refresh_token} 或 zai{access_token}
10
+ * 4. Z.ai 的 access_token 还要换一次业务 token:POST https://api.z.ai/api/auth/z/login {token}
11
+ *
12
+ * 拿到的凭据按客户端 credentials.json 的格式(enc:v1 加密)组装,存进账号 meta,
13
+ * 之后与「本机导入」的账号完全一样:可查额度、可一键切换到 ZCode 客户端。
14
+ */
15
+
16
+ import crypto from 'node:crypto';
17
+ import * as zc from './zcrypto.js';
18
+ import { zcodePaths } from './zcodeLocal.js';
19
+ import { FETCH_TIMEOUT_MS } from './constants.js';
20
+
21
+ const API_BASE = 'https://zcode.z.ai';
22
+ const ZAI_BUSINESS_LOGIN_URL = 'https://api.z.ai/api/auth/z/login';
23
+
24
+ async function fetchJson(url, init = {}) {
25
+ const res = await fetch(url, { ...init, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
26
+ const text = await res.text();
27
+ let body = null;
28
+ try { body = text ? JSON.parse(text) : null; } catch {}
29
+ return { res, body };
30
+ }
31
+
32
+ const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
33
+
34
+ /** kind: 'zcode-bigmodel'(智谱 BigModel)| 'zcode-zai'(Z.ai 国际) */
35
+ export async function startZcodeLogin(kind) {
36
+ const provider = kind === 'zcode-zai' ? 'zai' : 'bigmodel';
37
+ const pollToken = crypto.randomBytes(32).toString('hex');
38
+ const { res, body } = await fetchJson(API_BASE + '/api/v1/oauth/cli/init', {
39
+ method: 'POST',
40
+ headers: { Authorization: 'Bearer ' + pollToken, 'Content-Type': 'application/json', Accept: 'application/json' },
41
+ body: JSON.stringify({ provider }),
42
+ });
43
+ const d = body?.data;
44
+ if (!res.ok || body?.code !== 0 || !str(d?.flow_id) || !str(d?.authorize_url)) {
45
+ throw new Error('ZCode 登录初始化失败:' + (body?.msg || 'HTTP ' + res.status));
46
+ }
47
+ if (!d.authorize_url.startsWith('https://')) throw new Error('ZCode 登录初始化返回了非 https 授权地址');
48
+ const expiresInMs = Number.isFinite(d.expires_at) ? d.expires_at * 1000 - Date.now() : 5 * 60e3;
49
+ return {
50
+ url: d.authorize_url,
51
+ expiresInMs: Math.max(60e3, Math.min(expiresInMs, 15 * 60e3)),
52
+ intervalMs: Math.max(1000, (Number(d.poll_interval_sec) || 2) * 1000),
53
+ data: { provider, flowId: d.flow_id, pollToken },
54
+ };
55
+ }
56
+
57
+ /** 单次轮询:{status:'pending'} | {status:'ok', input};失败抛错 */
58
+ export async function pollZcodeLogin(data) {
59
+ const { res, body } = await fetchJson(API_BASE + '/api/v1/oauth/cli/poll/' + encodeURIComponent(data.flowId), {
60
+ headers: { Authorization: 'Bearer ' + data.pollToken, Accept: 'application/json' },
61
+ });
62
+ if (res.status >= 500 || res.status === 408 || res.status === 429) return { status: 'pending' };
63
+ if (!res.ok || body?.code !== 0) throw new Error('ZCode 授权失败:' + (body?.msg || 'HTTP ' + res.status));
64
+ const d = body.data || {};
65
+ if (d.status === 'pending') return { status: 'pending' };
66
+ if (d.status === 'failed') throw new Error('ZCode 授权失败(用户取消或授权被拒绝)');
67
+ if (d.status !== 'ready') throw new Error('ZCode 授权返回未知状态:' + d.status);
68
+
69
+ const jwt = str(d.token);
70
+ const user = d.user && typeof d.user === 'object' ? d.user : {};
71
+ const userId = user.user_id !== undefined && user.user_id !== null ? String(user.user_id) : null;
72
+ let accessToken = data.provider === 'zai' ? str(d.zai?.access_token) : str(d.bigmodel?.access_token) || str(d.bigmodel?.accessToken);
73
+ const refreshToken = data.provider === 'bigmodel' ? str(d.bigmodel?.refresh_token) || str(d.bigmodel?.refreshToken) : null;
74
+ if (!jwt || !accessToken || !userId) throw new Error('ZCode 授权返回缺少 token / 用户信息(上游结构可能变化)');
75
+ if (data.provider === 'zai') accessToken = await resolveZaiBusinessToken(accessToken);
76
+
77
+ return { status: 'ok', input: buildAccountInput({ provider: data.provider, jwt, accessToken, refreshToken, user, userId }) };
78
+ }
79
+
80
+ /** Z.ai OAuth token → 业务 access token(与客户端 ZaiBusinessTokenResolver 一致) */
81
+ async function resolveZaiBusinessToken(oauthToken) {
82
+ const { res, body } = await fetchJson(ZAI_BUSINESS_LOGIN_URL, {
83
+ method: 'POST',
84
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
85
+ body: JSON.stringify({ token: oauthToken }),
86
+ });
87
+ const ok = res.ok && (body?.code === undefined || body.code === 0 || body.code === 200) && body?.success !== false;
88
+ const t = str(body?.data?.access_token) || str(body?.data?.accessToken);
89
+ if (!ok || !t) throw new Error('Z.ai 业务 token 交换失败:' + (body?.msg || 'HTTP ' + res.status));
90
+ return t;
91
+ }
92
+
93
+ /** 按 ZCode credentials.json 的键名组装并用本机密钥加密(与客户端写出的格式一致) */
94
+ export function buildCredentials({ provider, jwt, accessToken, refreshToken, user, userId }, secret) {
95
+ const label = str(user.name) || str(user.email) || userId;
96
+ const userInfo = {
97
+ id: userId, username: label, displayName: label,
98
+ ...(str(user.avatar) ? { avatarUrl: user.avatar } : {}),
99
+ rawProfile: user,
100
+ };
101
+ const enc = (v) => zc.encryptWithSecret(v, secret);
102
+ const creds = {
103
+ 'oauth:active_provider': enc(provider),
104
+ [`oauth:${provider}:access_token`]: enc(accessToken),
105
+ [`oauth:${provider}:user_info`]: enc(JSON.stringify(userInfo)),
106
+ zcodejwttoken: enc(jwt),
107
+ };
108
+ if (refreshToken) creds[`oauth:${provider}:refresh_token`] = enc(refreshToken);
109
+ return creds;
110
+ }
111
+
112
+ function buildAccountInput(parts) {
113
+ const secret = zc.defaultSecret(zcodePaths().home);
114
+ const credentials = buildCredentials(parts, secret);
115
+ const id = zc.identityWithSecret(credentials, secret);
116
+ return {
117
+ provider: 'zcode',
118
+ token: `zcode-creds:${parts.userId}`, // 与本机导入同一标记,同一用户自动去重 / 续期
119
+ uid: parts.userId,
120
+ name: zc.identityLabel(id),
121
+ email: str(parts.user.email),
122
+ source: 'browser',
123
+ // 不带 config / deviceMid:同一账号再次登录时保留已保存的客户端配置与虚拟设备 ID
124
+ meta: {
125
+ credentials,
126
+ canonicalHash: zc.canonicalHash(credentials),
127
+ capturedAt: new Date().toISOString(),
128
+ loginProvider: parts.provider,
129
+ },
130
+ };
131
+ }
@@ -27,6 +27,34 @@ function snoozeUntilMs(account) {
27
27
  return Math.max(meta, proc);
28
28
  }
29
29
 
30
+ // ── 验证码失败退避(2026-11-17 用户实测「验证码失败还重复尝试,有封号风险」)──
31
+ // 3007 两轮验证码全拒后(needManual 路径),原实现只标卡片、不设任何退避——下一个
32
+ // tick(最短 1 分钟)原样再撞一轮,用户配 5 分钟周期时一天空撞 288 次失败验证码 + claim,
33
+ // 正是风控眼里的「高频失败画像」,有封号风险。现按连续失败轮数指数退避:
34
+ // 1 轮失败 → 30 分钟;2 轮 → 1 小时;3 轮 → 2 小时;封顶 6 小时。
35
+ // 退避只压自动轮询(手动领取照常直进,见 zcodeAutoClaim 的 source 参数);成功或 1003
36
+ // 即清零。进程内缓存即可——重启清零重新从 30 分钟起步,比落盘更保守也更简单。
37
+ const CAPTCHA_BACKOFF_MS = [0, 30 * 60_000, 60 * 60_000, 120 * 60_000, 360 * 60_000];
38
+ const captchaFailCount = new Map(); // accountId → 连续「两轮验证码全拒」次数
39
+ const captchaBackoffUntil = new Map(); // accountId → ms 时间戳
40
+
41
+ function captchaBackoffMs(account) {
42
+ return captchaBackoffUntil.get(account.id) || 0;
43
+ }
44
+
45
+ function recordCaptchaFailure(account) {
46
+ const n = (captchaFailCount.get(account.id) || 0) + 1;
47
+ captchaFailCount.set(account.id, n);
48
+ const ms = CAPTCHA_BACKOFF_MS[Math.min(n, CAPTCHA_BACKOFF_MS.length - 1)];
49
+ captchaBackoffUntil.set(account.id, Date.now() + ms);
50
+ return { fails: n, backoffMin: Math.round(ms / 60_000) };
51
+ }
52
+
53
+ function recordCaptchaSuccess(account) {
54
+ captchaFailCount.delete(account.id);
55
+ captchaBackoffUntil.delete(account.id);
56
+ }
57
+
30
58
  // 桌面版(Electron 主进程)注册的隐藏窗口验证码实现;NAS / CLI 为 null(走「需手动领取」分支)
31
59
  let captchaProvider = null;
32
60
  export function setZcodeCaptchaProvider(fn) { captchaProvider = typeof fn === 'function' ? fn : null; }
@@ -34,20 +62,34 @@ export function hasZcodeCaptchaProvider() { return Boolean(captchaProvider); }
34
62
  export function getZcodeCaptchaProvider() { return captchaProvider; }
35
63
 
36
64
  /** 账号被删除时清掉额满暂休缓存(daemon DELETE /api/accounts/:id 调用;落盘份随账号一起删) */
37
- export function forgetAccount(id) { snoozeUntil.delete(id); }
65
+ export function forgetAccount(id) {
66
+ snoozeUntil.delete(id);
67
+ captchaFailCount.delete(id);
68
+ captchaBackoffUntil.delete(id);
69
+ }
70
+
71
+ /** 测试辅助:清空全部进程内暂休/退避状态(跨用例状态泄漏防线) */
72
+ export function _resetBackoffForTests() {
73
+ snoozeUntil.clear();
74
+ captchaFailCount.clear();
75
+ captchaBackoffUntil.clear();
76
+ }
38
77
 
39
78
  const grantsText = (plan) => (plan.grants && plan.grants.length ? plan.grants.join(';') : '');
40
79
 
41
80
  /**
42
81
  * 为单个 ZCode 账号执行一次自动领取。
82
+ * @param {{ source?: 'auto'|'manual' }} opts source='manual'(用户手动点领取)跳过暂休窗口——
83
+ * 暂休只保护自动轮询不空打,不该挡用户的手(手动被静默吞掉比多打一次 claim 更伤信任)。
43
84
  * @returns {null | { status, message, claims: Array }} null = preview 为空或查询失败(已记日志,不上卡片)
44
85
  */
45
- export async function zcodeAutoClaim(account) {
86
+ export async function zcodeAutoClaim(account, { source = 'auto' } = {}) {
46
87
  const label = account.name || account.uid || account.id;
47
- {
48
- const until = snoozeUntilMs(account);
88
+ if (source !== 'manual') {
89
+ const until = Math.max(snoozeUntilMs(account), captchaBackoffMs(account));
49
90
  if (until && until > Date.now()) {
50
- logger.debug('ZCODE-CLAIM', '{label} 名额已领完,跳过直到 {until}(服务端计划结束点)', { label, until: new Date(until).toISOString() });
91
+ const isBackoff = captchaBackoffMs(account) > Date.now();
92
+ logger.debug('ZCODE-CLAIM', '{label} 自动轮询暂休到 {until}({why})', { label, until: new Date(until).toISOString(), why: isBackoff ? '验证码连续失败退避' : '服务端计划结束点' });
51
93
  return null;
52
94
  }
53
95
  }
@@ -80,12 +122,14 @@ export async function zcodeAutoClaim(account) {
80
122
  // 「待生效」,用户以为没领上。
81
123
  claims.push({ plan: planName, via: 'direct', ok: true, startsAt: r?.startsAt || null });
82
124
  anySuccess = true;
125
+ recordCaptchaSuccess(account); // 任何成功都清验证码退避计数
83
126
  logger.info('ZCODE-CLAIM', '{label} 已领取「{plan}」(免验证码){grants}', { label, plan: planName, grants: grantsText(plan) ? ':' + grantsText(plan) : '' });
84
127
  continue;
85
128
  } catch (e) {
86
129
  if (e.code === 1003) {
87
130
  claims.push({ plan: planName, ok: true, already: true });
88
131
  logger.info('ZCODE-CLAIM', '{label}「{plan}」已领取过', { label, plan: planName });
132
+ recordCaptchaSuccess(account); // 已领过=服务端认识这个号,清退避
89
133
  continue;
90
134
  }
91
135
  if (e.code === 1005 && e.nextAt) {
@@ -125,6 +169,7 @@ export async function zcodeAutoClaim(account) {
125
169
  }
126
170
  claims.push({ plan: planName, via: 'captcha', ok: true, startsAt: r2?.startsAt || null });
127
171
  anySuccess = true;
172
+ recordCaptchaSuccess(account);
128
173
  logger.info('ZCODE-CLAIM', '{label} 已领取「{plan}」(静默验证码){grants}', { label, plan: planName, grants: grantsText(plan) ? ':' + grantsText(plan) : '' });
129
174
  } catch (e2) {
130
175
  if (e2.code === 1005 && e2.nextAt) {
@@ -134,9 +179,11 @@ export async function zcodeAutoClaim(account) {
134
179
  //(claim 前置校验比验证码本身更严),如实带原始报错引导用户去客户端
135
180
  needManual = true;
136
181
  claims.push({ plan: planName, ok: false, needManual: true, message: e2.message });
137
- logger.warn('ZCODE-CLAIM', '{label}「{plan}」验证码未完成:{err}(可在面板手动领取或到官方客户端领取)', { label, plan: planName, err: e2.message });
182
+ const bf = recordCaptchaFailure(account); // 指数退避:连续全拒自动轮逐轮拉长间隔(防高频失败画像触发风控/封号)
183
+ logger.warn('ZCODE-CLAIM', '{label}「{plan}」验证码未完成:{err}(可在面板手动领取或到官方客户端领取)。自动轮退避 {min} 分钟(连续第 {n} 轮全拒)', { label, plan: planName, err: e2.message, min: bf.backoffMin, n: bf.fails });
138
184
  }
139
185
  }
186
+ // 验证码退避优先级高于 1005 暂休(退避更短更保守,取较早到期者由两把锁共同约束)
140
187
  // 1005 名额已满 → 按服务端 ends_at 将本账号挂进跳过窗口,下一轮自动轮询在该时间点前不再空打
141
188
  if (snoozeAt > 0) {
142
189
  snoozeUntil.set(account.id, snoozeAt);
@@ -100,14 +100,27 @@ function netPref() {
100
100
  autoClaimUntil: Number.isFinite(j.autoClaimUntil) ? j.autoClaimUntil : null,
101
101
  claimIntervalMin: Number.isFinite(j.claimIntervalMin) ? Number(j.claimIntervalMin) : null,
102
102
  claimWindowMin: Number.isFinite(j.claimWindowMin) ? Number(j.claimWindowMin) : null,
103
+ dailyPlanEnabled: j.dailyPlan?.enabled === true,
104
+ dailyPlanHour: Number.isFinite(j.dailyPlan?.hour) ? Math.round(j.dailyPlan.hour) : null,
105
+ dailyPlanMinute: Number.isFinite(j.dailyPlan?.minute) ? Math.round(j.dailyPlan.minute) : null,
106
+ dailyPlanLastDay: typeof j.dailyPlan?.lastRunDay === 'string' ? j.dailyPlan.lastRunDay : null,
103
107
  };
104
- } catch { netPrefCache = { proxyFirst: false, proxyUrl: null, autoClaim: false, autoClaimUntil: null, claimIntervalMin: null, claimWindowMin: null }; }
108
+ } catch { netPrefCache = { proxyFirst: false, proxyUrl: null, autoClaim: false, autoClaimUntil: null, claimIntervalMin: null, claimWindowMin: null, dailyPlanEnabled: false, dailyPlanHour: null, dailyPlanMinute: null, dailyPlanLastDay: null }; }
105
109
  return netPrefCache;
106
110
  }
107
111
  function writeNetPref(p) {
108
112
  netPrefCache = p;
109
113
  fs.mkdirSync(codeHome(), { recursive: true, mode: 0o700 });
110
- fs.writeFileSync(NET_PREFS_FILE(), JSON.stringify({ proxyFirst: p.proxyFirst, proxyUrl: p.proxyUrl, autoClaim: p.autoClaim, autoClaimUntil: p.autoClaimUntil || null, claimIntervalMin: p.claimIntervalMin ?? null, claimWindowMin: p.claimWindowMin ?? null }, null, 2), { mode: 0o600 });
114
+ fs.writeFileSync(NET_PREFS_FILE(), JSON.stringify({
115
+ proxyFirst: p.proxyFirst, proxyUrl: p.proxyUrl, autoClaim: p.autoClaim, autoClaimUntil: p.autoClaimUntil || null,
116
+ claimIntervalMin: p.claimIntervalMin ?? null, claimWindowMin: p.claimWindowMin ?? null,
117
+ dailyPlan: {
118
+ enabled: p.dailyPlanEnabled === true,
119
+ hour: p.dailyPlanHour ?? 8,
120
+ minute: p.dailyPlanMinute ?? 0,
121
+ lastRunDay: p.dailyPlanLastDay || null,
122
+ },
123
+ }, null, 2), { mode: 0o600 });
111
124
  }
112
125
  export function proxyFirst() { return netPref().proxyFirst; }
113
126
  export function proxyUrl() { return netPref().proxyUrl; }
@@ -158,6 +171,46 @@ export function setClaimWindowMin(v) {
158
171
  if (!Number.isFinite(n) || n < 0 || n > 1440 || (n > 0 && n < 5)) throw new Error('运行时长需为 0(一直运行)或 5–1440 分钟');
159
172
  writeNetPref({ ...netPref(), claimWindowMin: n });
160
173
  }
174
+
175
+ // ── 每日定时计划:每天 HH:MM 到点自动开启一轮「自动领取计划」窗口(复用轮询周期/运行时长)──
176
+ // 动机:活动包由服务端在每日 0 点左右刷新放出,用户想让机器在每天早上 8 点自动开始轮询,
177
+ // 而不是每天手动点一次「保存并启用」。计划本身落 zcode-net.json(0600),重启后仍生效。
178
+ // 防重跑:lastRunDay 记业务日(本地日历日),一天只触发一次;手动停用不受影响——
179
+ // 计划到点会重新拉起窗口,用户手动关掉的是「这一轮」,第二天计划照常。
180
+
181
+ /** 每日计划配置。hour 0–23(默认 8),minute 0–59(默认 0);enabled 默认关 */
182
+ export function dailyClaimPlan() {
183
+ const p = netPref();
184
+ const hour = Number.isFinite(p.dailyPlanHour) && p.dailyPlanHour >= 0 && p.dailyPlanHour <= 23 ? p.dailyPlanHour : 8;
185
+ const minute = Number.isFinite(p.dailyPlanMinute) && p.dailyPlanMinute >= 0 && p.dailyPlanMinute <= 59 ? p.dailyPlanMinute : 0;
186
+ return { enabled: p.dailyPlanEnabled === true, hour, minute, lastRunDay: p.dailyPlanLastDay };
187
+ }
188
+ export function setDailyClaimPlan({ enabled, hour, minute } = {}) {
189
+ const cur = dailyClaimPlan();
190
+ let h = cur.hour;
191
+ let m = cur.minute;
192
+ if (hour !== undefined) {
193
+ const n = Math.round(Number(hour));
194
+ if (!Number.isFinite(n) || n < 0 || n > 23) throw new Error('计划时间的小时需在 0–23 之间');
195
+ h = n;
196
+ }
197
+ if (minute !== undefined) {
198
+ const n = Math.round(Number(minute));
199
+ if (!Number.isFinite(n) || n < 0 || n > 59) throw new Error('计划时间的分钟需在 0–59 之间');
200
+ m = n;
201
+ }
202
+ writeNetPref({
203
+ ...netPref(),
204
+ dailyPlanEnabled: enabled !== undefined ? enabled === true : cur.enabled,
205
+ dailyPlanHour: h,
206
+ dailyPlanMinute: m,
207
+ dailyPlanLastDay: cur.lastRunDay,
208
+ });
209
+ }
210
+ /** 记录「业务日 <day> 已按计划跑过」(防同日重触发;重启后状态仍在文件里) */
211
+ export function markDailyClaimRan(day) {
212
+ writeNetPref({ ...netPref(), dailyPlanLastDay: String(day || '') });
213
+ }
161
214
  export function setProxyFirst(v) { writeNetPref({ ...netPref(), proxyFirst: v === true }); }
162
215
  export function setProxyUrl(u) {
163
216
  const t = typeof u === 'string' ? u.trim() : '';