creditdaddy 1.6.3 → 1.6.6
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.
- package/README.md +1 -1
- package/bin/creditdaddy.js +22 -0
- package/build.json +3 -3
- package/package.json +2 -2
- package/src/checkin.js +8 -1
- package/src/constants.js +3 -1
- package/src/cookieSites.js +8 -1
- package/src/daemon.js +2255 -2062
- package/src/doubaoClient.js +0 -1
- package/src/i18n/en.json +97 -1
- package/src/i18n/ja.json +97 -1
- package/src/i18n/ko.json +97 -1
- package/src/i18n/zh-TW.json +97 -1
- package/src/loomyAuth.js +230 -0
- package/src/loomyClient.js +308 -0
- package/src/loomyLocal.js +200 -0
- package/src/minimaxGateway.js +66 -11
- package/src/panel.html +356 -57
- package/src/providers.js +9 -0
- package/src/qoderApp.js +23 -0
- package/src/qoderClient.js +15 -6
- package/src/quotaRefresh.js +5 -0
- package/src/store.js +9 -2
- package/src/tenrouter.js +50 -15
- package/src/tenrouterAccounts.js +1 -0
- package/src/traeClient.js +31 -9
- package/src/traeGateway.js +75 -13
- package/src/transfer.js +3 -0
- package/src/usageSync.js +11 -1
- package/src/workbuddyClient.js +1 -0
- package/src/workbuddyLocal.js +179 -16
- package/src/zcodeAutoClaim.js +15 -2
- package/src/zcodeClient.js +41 -7
- package/src/zcodeGateway.js +32 -2
package/src/workbuddyLocal.js
CHANGED
|
@@ -16,8 +16,128 @@ import fs from 'node:fs';
|
|
|
16
16
|
import os from 'node:os';
|
|
17
17
|
import path from 'node:path';
|
|
18
18
|
import crypto from 'node:crypto';
|
|
19
|
+
import cp from 'node:child_process';
|
|
19
20
|
import { inspectToken } from './workbuddyClient.js';
|
|
20
21
|
|
|
22
|
+
// ===================== WorkBuddy 5.6+ $wbEncrypted 信封加解密 =====================
|
|
23
|
+
|
|
24
|
+
export function isWbEncrypted(val) {
|
|
25
|
+
return !!val && typeof val === 'object' && !Array.isArray(val) && val.$wbEncrypted === 1 && typeof val.envelope === 'string';
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function buildEnvelopeAAD(env) {
|
|
29
|
+
const FRAMING_FIELD = 2, FMT_FIELD = 'WBEV1', AAD_DOMAIN = Buffer.from('WB-AAD\0', 'ascii');
|
|
30
|
+
const lp = (s) => { const b = Buffer.from(s, 'utf8'); const l = Buffer.alloc(4); l.writeUInt32BE(b.length); return Buffer.concat([l, b]); };
|
|
31
|
+
const u32 = (n) => { const b = Buffer.alloc(4); b.writeUInt32BE(n); return b; };
|
|
32
|
+
return Buffer.concat([
|
|
33
|
+
AAD_DOMAIN, Buffer.from([1]), lp(FMT_FIELD), lp('sym-v1'), u32(env.suite || 1),
|
|
34
|
+
lp(env.keyId || ''), Buffer.from([FRAMING_FIELD]), Buffer.from([0]), Buffer.from([0]),
|
|
35
|
+
]);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function openEnvelope(encObj, key) {
|
|
39
|
+
const env = JSON.parse(Buffer.from(encObj.envelope, 'base64').toString('utf8'));
|
|
40
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(env.nonce, 'base64'), { authTagLength: 16 });
|
|
41
|
+
decipher.setAAD(buildEnvelopeAAD(env));
|
|
42
|
+
decipher.setAuthTag(Buffer.from(env.authTag, 'base64'));
|
|
43
|
+
return Buffer.concat([decipher.update(Buffer.from(env.ciphertext, 'base64')), decipher.final()]).toString('utf8');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function sealEnvelope(plaintext, key, template = {}) {
|
|
47
|
+
const nonce = crypto.randomBytes(12);
|
|
48
|
+
const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce, { authTagLength: 16 });
|
|
49
|
+
const env = {
|
|
50
|
+
suite: template.suite || 1,
|
|
51
|
+
keyId: template.keyId || '',
|
|
52
|
+
nonce: nonce.toString('base64'),
|
|
53
|
+
};
|
|
54
|
+
cipher.setAAD(buildEnvelopeAAD(env));
|
|
55
|
+
const ciphertext = Buffer.concat([cipher.update(String(plaintext || ''), 'utf8'), cipher.final()]);
|
|
56
|
+
env.authTag = cipher.getAuthTag().toString('base64');
|
|
57
|
+
env.ciphertext = ciphertext.toString('base64');
|
|
58
|
+
return {
|
|
59
|
+
$wbEncrypted: 1,
|
|
60
|
+
envelope: Buffer.from(JSON.stringify(env)).toString('base64'),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
let cachedMasterKey = null;
|
|
65
|
+
let masterKeyFailAt = 0;
|
|
66
|
+
const KEY_RETRY_MS = 60000;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* 经 WorkBuddy 官方 Electron(ELECTRON_RUN_AS_NODE=1)子进程调用原生存储绑定提取密钥。
|
|
70
|
+
* 内存缓存,失败 60s 内退避;绝不写盘,绝不写日志。
|
|
71
|
+
*/
|
|
72
|
+
export function getWorkbuddyMasterKey(clientPath) {
|
|
73
|
+
if (cachedMasterKey) return cachedMasterKey;
|
|
74
|
+
if (masterKeyFailAt && Date.now() - masterKeyFailAt < KEY_RETRY_MS) return null;
|
|
75
|
+
const exe = clientPath || detectWorkbuddy().clientPath;
|
|
76
|
+
if (!exe) return null;
|
|
77
|
+
|
|
78
|
+
try {
|
|
79
|
+
const code = [
|
|
80
|
+
"const b = process._linkedBinding('electron_browser_workbuddy_storage');",
|
|
81
|
+
"const p = JSON.parse(b.loggerGet());",
|
|
82
|
+
"if (p && typeof p.atRestSecretKey === 'string') process.stdout.write(p.atRestSecretKey);",
|
|
83
|
+
].join('\n');
|
|
84
|
+
const r = cp.spawnSync(exe, ['-e', code], {
|
|
85
|
+
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
|
|
86
|
+
timeout: 5000,
|
|
87
|
+
encoding: 'utf8',
|
|
88
|
+
});
|
|
89
|
+
const keyRaw = String(r.stdout || '').trim();
|
|
90
|
+
if (r.status === 0 && keyRaw.length >= 16) {
|
|
91
|
+
cachedMasterKey = crypto.createHash('sha256').update(keyRaw, 'utf8').digest();
|
|
92
|
+
masterKeyFailAt = 0;
|
|
93
|
+
return cachedMasterKey;
|
|
94
|
+
}
|
|
95
|
+
} catch {
|
|
96
|
+
/* 子进程执行异常,进入退避 */
|
|
97
|
+
}
|
|
98
|
+
masterKeyFailAt = Date.now();
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function resetMasterKeyCacheForTest(key = null) {
|
|
103
|
+
cachedMasterKey = key;
|
|
104
|
+
masterKeyFailAt = 0;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 深度解密 JSON 中的 $wbEncrypted 信封,返回包含明文的浅拷贝/深拷贝 */
|
|
108
|
+
export function decryptSessionJson(session, clientPath) {
|
|
109
|
+
if (!session || typeof session !== 'object') return session;
|
|
110
|
+
let key = null;
|
|
111
|
+
const clone = JSON.parse(JSON.stringify(session));
|
|
112
|
+
|
|
113
|
+
const walk = (node) => {
|
|
114
|
+
if (!node || typeof node !== 'object') return;
|
|
115
|
+
if (Array.isArray(node)) {
|
|
116
|
+
for (const item of node) walk(item);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
for (const [k, v] of Object.entries(node)) {
|
|
120
|
+
if (isWbEncrypted(v)) {
|
|
121
|
+
if (!key) key = getWorkbuddyMasterKey(clientPath);
|
|
122
|
+
if (key) {
|
|
123
|
+
try {
|
|
124
|
+
node[k] = openEnvelope(v, key);
|
|
125
|
+
} catch {
|
|
126
|
+
/* 解密失败保留原信封 */
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
} else if (v && typeof v === 'object') {
|
|
130
|
+
walk(v);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
walk(clone);
|
|
136
|
+
return clone;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// ===================== 凭据与会话管理 =====================
|
|
140
|
+
|
|
21
141
|
export function workbuddyAuthDir() {
|
|
22
142
|
const home = os.homedir();
|
|
23
143
|
const tail = ['CodeBuddyExtension', 'Data', 'Public', 'auth'];
|
|
@@ -32,7 +152,9 @@ const CURRENT_RE = /^[a-z0-9-]+\.info$/i; // workbuddy-desktop.info
|
|
|
32
152
|
const HISTORY_RE = /^[a-z0-9-]+\.\d{4}-.*\.info$/i; // workbuddy-desktop.<时间戳>.<pid>.<uuid>.info
|
|
33
153
|
|
|
34
154
|
/** 会话 JSON → 账号记录(供 addAccount),不含网络请求 */
|
|
35
|
-
export function sessionToAccount(
|
|
155
|
+
export function sessionToAccount(rawSession, source, clientPath) {
|
|
156
|
+
// 如果会话包含 $wbEncrypted 信封,先进行安全解密
|
|
157
|
+
const session = decryptSessionJson(rawSession, clientPath);
|
|
36
158
|
const token = session?.auth?.accessToken;
|
|
37
159
|
if (typeof token !== 'string' || !token) return null;
|
|
38
160
|
const info = inspectToken(token);
|
|
@@ -40,8 +162,15 @@ export function sessionToAccount(session, source) {
|
|
|
40
162
|
const acc = session.account || {};
|
|
41
163
|
const auth = session.auth || {};
|
|
42
164
|
const iso = (ms) => (Number.isFinite(ms) ? new Date(ms).toISOString() : null);
|
|
43
|
-
|
|
44
|
-
|
|
165
|
+
|
|
166
|
+
// 手机号:优先未脱敏的 phoneNumber;若被客户端脱敏(含 *)或为空,回退到从 JWT 解析的大陆手机号
|
|
167
|
+
const rawPhone = typeof acc.phoneNumber === 'string' ? acc.phoneNumber.trim() : '';
|
|
168
|
+
const isRedacted = rawPhone.includes('*');
|
|
169
|
+
const phone = (!rawPhone || isRedacted) ? (info.phone || rawPhone || null) : rawPhone;
|
|
170
|
+
|
|
171
|
+
// 原 rawSession 结构原样保留在 meta.session,便于切换账号时原汁原味还原
|
|
172
|
+
const rawAuth = rawSession?.auth || auth;
|
|
173
|
+
const { accessToken: _a, refreshToken: _r, ...authRest } = rawAuth;
|
|
45
174
|
return {
|
|
46
175
|
provider: info.provider,
|
|
47
176
|
token,
|
|
@@ -54,11 +183,13 @@ export function sessionToAccount(session, source) {
|
|
|
54
183
|
meta: {
|
|
55
184
|
domain: auth.domain || info.host,
|
|
56
185
|
enterpriseId: acc.enterpriseId || null,
|
|
57
|
-
phone
|
|
186
|
+
phone,
|
|
58
187
|
refreshExpiresAt: iso(auth.refreshExpiresAt),
|
|
59
188
|
session: {
|
|
60
|
-
account:
|
|
61
|
-
|
|
189
|
+
account: rawSession?.account || acc,
|
|
190
|
+
auth: authRest,
|
|
191
|
+
accounts: Array.isArray(rawSession?.accounts) ? rawSession.accounts : (session.accounts || []),
|
|
192
|
+
...(Array.isArray(rawSession?.allAccounts || session.allAccounts) ? { allAccounts: rawSession?.allAccounts || session.allAccounts } : {}),
|
|
62
193
|
},
|
|
63
194
|
},
|
|
64
195
|
};
|
|
@@ -68,8 +199,9 @@ export function sessionToAccount(session, source) {
|
|
|
68
199
|
* 读取本机 WorkBuddy 会话:当前会话 + 历史会话(按 uid 去重,保留最新)。
|
|
69
200
|
* @returns {{ dir, accounts: Array<{...账号记录, current: boolean, file, fileTime}>, errors }}
|
|
70
201
|
*/
|
|
71
|
-
export function readWorkbuddySessions() {
|
|
72
|
-
const dir = workbuddyAuthDir();
|
|
202
|
+
export function readWorkbuddySessions(options = {}) {
|
|
203
|
+
const dir = options.dir || workbuddyAuthDir();
|
|
204
|
+
const clientPath = options.clientPath !== undefined ? options.clientPath : detectWorkbuddy().clientPath;
|
|
73
205
|
const out = { dir, accounts: [], errors: [] };
|
|
74
206
|
let names = [];
|
|
75
207
|
try { names = fs.readdirSync(dir); } catch { return out; }
|
|
@@ -80,7 +212,7 @@ export function readWorkbuddySessions() {
|
|
|
80
212
|
try {
|
|
81
213
|
const current = !HISTORY_RE.test(name);
|
|
82
214
|
if (current && fs.existsSync(`${file}.logged-out`)) continue; // 已登出
|
|
83
|
-
const rec = sessionToAccount(JSON.parse(fs.readFileSync(file, 'utf8')), current ? 'WorkBuddy 当前登录' : 'WorkBuddy 历史会话');
|
|
215
|
+
const rec = sessionToAccount(JSON.parse(fs.readFileSync(file, 'utf8')), current ? 'WorkBuddy 当前登录' : 'WorkBuddy 历史会话', clientPath);
|
|
84
216
|
if (!rec) continue;
|
|
85
217
|
const fileTime = fs.statSync(file).mtimeMs;
|
|
86
218
|
const item = { ...rec, current, file, fileTime };
|
|
@@ -104,13 +236,22 @@ export function currentWorkbuddyUid() {
|
|
|
104
236
|
// (无客户端时静默切换留下的空壳目录),拿目录判断会把没装客户端的机器误报成已安装。
|
|
105
237
|
const CLIENT_CANDIDATES = process.platform === 'win32'
|
|
106
238
|
? [
|
|
107
|
-
['Programs', 'CodeBuddy', 'CodeBuddy.exe'],
|
|
108
239
|
['Programs', 'WorkBuddy', 'WorkBuddy.exe'],
|
|
109
|
-
['
|
|
240
|
+
['Programs', 'WorkBuddyAI', 'WorkBuddyAI.exe'],
|
|
241
|
+
['Programs', 'CodeBuddy CN', 'CodeBuddy CN.exe'],
|
|
242
|
+
['Programs', 'CodeBuddy', 'CodeBuddy.exe'],
|
|
110
243
|
['WorkBuddy', 'WorkBuddy.exe'],
|
|
244
|
+
['WorkBuddyAI', 'WorkBuddyAI.exe'],
|
|
245
|
+
['CodeBuddy CN', 'CodeBuddy CN.exe'],
|
|
246
|
+
['CodeBuddy', 'CodeBuddy.exe'],
|
|
111
247
|
]
|
|
112
248
|
: process.platform === 'darwin'
|
|
113
|
-
? [
|
|
249
|
+
? [
|
|
250
|
+
'/Applications/WorkBuddy.app',
|
|
251
|
+
'/Applications/WorkBuddy AI.app',
|
|
252
|
+
'/Applications/CodeBuddy CN.app',
|
|
253
|
+
'/Applications/CodeBuddy.app',
|
|
254
|
+
]
|
|
114
255
|
: [];
|
|
115
256
|
|
|
116
257
|
/**
|
|
@@ -129,7 +270,7 @@ export function detectWorkbuddy() {
|
|
|
129
270
|
: cand;
|
|
130
271
|
try { if (fs.existsSync(p)) { clientPath = p; break; } } catch { /* 下一个候选 */ }
|
|
131
272
|
}
|
|
132
|
-
const sessions = dirExists ? readWorkbuddySessions() : { accounts: [] };
|
|
273
|
+
const sessions = dirExists ? readWorkbuddySessions({ dir, clientPath }) : { accounts: [] };
|
|
133
274
|
return {
|
|
134
275
|
dir,
|
|
135
276
|
dirExists,
|
|
@@ -141,9 +282,10 @@ export function detectWorkbuddy() {
|
|
|
141
282
|
|
|
142
283
|
/**
|
|
143
284
|
* 把账号写成 WorkBuddy 当前会话(切换账号)。需要账号带有导入时保存的会话信息。
|
|
285
|
+
* 如果原模板是 $wbEncrypted 信封格式,写回时将自动封包为合法信封。
|
|
144
286
|
* @returns {{ file, previousUid }}
|
|
145
287
|
*/
|
|
146
|
-
export function writeWorkbuddySession(account) {
|
|
288
|
+
export function writeWorkbuddySession(account, { clientPath } = {}) {
|
|
147
289
|
const s = account.meta?.session;
|
|
148
290
|
if (!s?.account) throw new Error('该账号缺少 WorkBuddy 会话信息,请从本机重新导入后再切换');
|
|
149
291
|
const dir = workbuddyAuthDir();
|
|
@@ -153,12 +295,33 @@ export function writeWorkbuddySession(account) {
|
|
|
153
295
|
try { previousUid = JSON.parse(fs.readFileSync(file, 'utf8'))?.account?.uid || null; } catch {}
|
|
154
296
|
|
|
155
297
|
const ms = (iso) => (iso ? new Date(iso).getTime() : undefined);
|
|
298
|
+
const rawAuth = s.auth || {};
|
|
299
|
+
|
|
300
|
+
// 判断是否需要信封封包写入(原会话 auth 字段包含 $wbEncrypted)
|
|
301
|
+
let isEncryptedTemplate = isWbEncrypted(rawAuth.accessToken) || isWbEncrypted(rawAuth.refreshToken);
|
|
302
|
+
let masterKey = null;
|
|
303
|
+
if (isEncryptedTemplate) {
|
|
304
|
+
masterKey = getWorkbuddyMasterKey(clientPath);
|
|
305
|
+
if (!masterKey) {
|
|
306
|
+
throw new Error('无法切换账号:目标账号为 WorkBuddy 5.6+ 加密凭据,但未能获取客户端解密密钥');
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const accessPayload = isEncryptedTemplate
|
|
311
|
+
? sealEnvelope(account.token, masterKey, isWbEncrypted(rawAuth.accessToken) ? JSON.parse(Buffer.from(rawAuth.accessToken.envelope, 'base64').toString('utf8')) : {})
|
|
312
|
+
: account.token;
|
|
313
|
+
|
|
314
|
+
const refreshVal = account.refreshToken || rawAuth.refreshToken;
|
|
315
|
+
const refreshPayload = isEncryptedTemplate && refreshVal
|
|
316
|
+
? sealEnvelope(refreshVal, masterKey, isWbEncrypted(rawAuth.refreshToken) ? JSON.parse(Buffer.from(rawAuth.refreshToken.envelope, 'base64').toString('utf8')) : {})
|
|
317
|
+
: refreshVal;
|
|
318
|
+
|
|
156
319
|
const session = {
|
|
157
320
|
account: s.account,
|
|
158
321
|
auth: {
|
|
159
322
|
...s.auth,
|
|
160
|
-
accessToken:
|
|
161
|
-
refreshToken:
|
|
323
|
+
accessToken: accessPayload,
|
|
324
|
+
refreshToken: refreshPayload,
|
|
162
325
|
expiresAt: ms(account.expiresAt) ?? s.auth?.expiresAt,
|
|
163
326
|
lastRefreshTime: Date.now(),
|
|
164
327
|
},
|
package/src/zcodeAutoClaim.js
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
|
|
14
14
|
import { logger } from './logger.js';
|
|
15
15
|
import { t } from './i18n.js';
|
|
16
|
-
import { fetchClaimPlans, claimPlan, fetchCaptchaConfig } from './zcodeClient.js';
|
|
16
|
+
import { fetchClaimPlans, claimPlan, fetchCaptchaConfig, ZCODE_KNOWN_CLAIM_PLANS } from './zcodeClient.js';
|
|
17
17
|
import { withAccounts } from './store.js';
|
|
18
18
|
|
|
19
19
|
// 额满(1005)时消费服务端 nextAt(plan.ends_at):
|
|
@@ -33,6 +33,9 @@ export function setZcodeCaptchaProvider(fn) { captchaProvider = typeof fn === 'f
|
|
|
33
33
|
export function hasZcodeCaptchaProvider() { return Boolean(captchaProvider); }
|
|
34
34
|
export function getZcodeCaptchaProvider() { return captchaProvider; }
|
|
35
35
|
|
|
36
|
+
/** 账号被删除时清掉额满暂休缓存(daemon DELETE /api/accounts/:id 调用;落盘份随账号一起删) */
|
|
37
|
+
export function forgetAccount(id) { snoozeUntil.delete(id); }
|
|
38
|
+
|
|
36
39
|
const grantsText = (plan) => (plan.grants && plan.grants.length ? plan.grants.join(';') : '');
|
|
37
40
|
|
|
38
41
|
/**
|
|
@@ -55,7 +58,12 @@ export async function zcodeAutoClaim(account) {
|
|
|
55
58
|
logger.debug('ZCODE-CLAIM', '{label} 活动查询失败:{err}', { label, err: e.message });
|
|
56
59
|
return null;
|
|
57
60
|
}
|
|
58
|
-
if (!plans.length)
|
|
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
|
+
}
|
|
59
67
|
|
|
60
68
|
const claims = [];
|
|
61
69
|
let anySuccess = false;
|
|
@@ -84,6 +92,9 @@ export async function zcodeAutoClaim(account) {
|
|
|
84
92
|
snoozeAt = Math.max(snoozeAt, Number(new Date(e.nextAt)) || 0);
|
|
85
93
|
}
|
|
86
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;
|
|
87
98
|
claims.push({ plan: planName, ok: false, message: e.message });
|
|
88
99
|
logger.warn('ZCODE-CLAIM', '{label} 领取「{plan}」失败:{err}', { label, plan: planName, err: e.message });
|
|
89
100
|
continue;
|
|
@@ -127,6 +138,8 @@ export async function zcodeAutoClaim(account) {
|
|
|
127
138
|
} catch {}
|
|
128
139
|
}
|
|
129
140
|
|
|
141
|
+
// 已知清单全部不可领(1001/1002 静默跳过)时 claims 为空:无事发生,不留痕迹
|
|
142
|
+
if (!claims.length) return null;
|
|
130
143
|
const names = claims.filter((c) => c.ok && !c.already).map((c) => c.plan);
|
|
131
144
|
const status = names.length ? 'checked-in'
|
|
132
145
|
: claims.every((c) => c.already) ? 'already'
|
package/src/zcodeClient.js
CHANGED
|
@@ -21,6 +21,7 @@ import https from 'node:https';
|
|
|
21
21
|
import os from 'node:os';
|
|
22
22
|
import path from 'node:path';
|
|
23
23
|
import tls from 'node:tls';
|
|
24
|
+
import { PassThrough } from 'node:stream';
|
|
24
25
|
import { execFile } from 'node:child_process';
|
|
25
26
|
import { FETCH_TIMEOUT_MS } from './constants.js';
|
|
26
27
|
import { defaultSecret, safeDecrypt } from './zcrypto.js';
|
|
@@ -237,10 +238,20 @@ async function fetchViaProxy(url, { method = 'GET', headers = {}, body = null, t
|
|
|
237
238
|
}
|
|
238
239
|
const done = (fn, arg) => { clearTimeout(deadline); signal?.removeEventListener('abort', onAbort); fn(arg); };
|
|
239
240
|
const req = (isHttps ? https : http).request(requestOpts, (res) => {
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
res.
|
|
241
|
+
// 流式转发:经代理的响应(含网关 SSE 补全)逐块到达,而不是整包收完才 resolve——
|
|
242
|
+
// 此前代理优先模式下客户端在整个生成期间一个字节都收不到,首 token 超时必然误报
|
|
243
|
+
const pass = new PassThrough();
|
|
244
|
+
res.pipe(pass);
|
|
245
|
+
res.on('error', (e) => pass.destroy(e));
|
|
246
|
+
// close 在正常收尾与异常中断时都会触发;complete=false = 没收完就被掐
|
|
247
|
+
// (abort/超时销毁 socket 后 res 不一定发 'error')。deadline 也在这里才清:
|
|
248
|
+
// 墙钟上限必须继续管住流式 body,与直连路径(AbortSignal 管到 body 结束)同口径
|
|
249
|
+
res.on('close', () => {
|
|
250
|
+
clearTimeout(deadline);
|
|
251
|
+
signal?.removeEventListener('abort', onAbort);
|
|
252
|
+
if (!res.complete) pass.destroy(new Error('连接中断'));
|
|
253
|
+
});
|
|
254
|
+
resolve(new Response(pass, { status: res.statusCode, headers: res.headers }));
|
|
244
255
|
});
|
|
245
256
|
req.on('error', (e) => done(reject, e));
|
|
246
257
|
req.on('timeout', () => req.destroy(new Error('请求超时')));
|
|
@@ -332,9 +343,21 @@ export async function fetchJsonRace(url, { method = 'GET', headers = {}, body =
|
|
|
332
343
|
if (errs.length > 1) {
|
|
333
344
|
const detail = errs.map(([w, e]) => `${w === 'direct' ? '直连' : '代理'}: ${e?.message || e}`).join(';');
|
|
334
345
|
const last = errs[errs.length - 1][1];
|
|
335
|
-
//
|
|
336
|
-
|
|
337
|
-
|
|
346
|
+
// 优先在最后一条错误上改写 message(保留 err.code / instanceof,调用方判定不受影响)。
|
|
347
|
+
// 但 AbortSignal.timeout / fetch 的 abort reason 是 DOMException——message 只有 getter,
|
|
348
|
+
// 赋值会抛 TypeError 把真实网络错误整个吞掉(2026-10-30 ZCode 活动查询报
|
|
349
|
+
// 「Cannot set property message」即此,真因被掩盖)。descriptor 不可写时退回包一层
|
|
350
|
+
// 普通 Error,原始错误挂 cause、code 透传。
|
|
351
|
+
try {
|
|
352
|
+
last.message = detail;
|
|
353
|
+
throw last;
|
|
354
|
+
} catch (e) {
|
|
355
|
+
if (e === last) throw last; // 赋值成功,原样上抛
|
|
356
|
+
const wrapped = new Error(detail); // 赋值抛错(getter-only message)
|
|
357
|
+
wrapped.cause = last;
|
|
358
|
+
if (last?.code) wrapped.code = last.code;
|
|
359
|
+
throw wrapped;
|
|
360
|
+
}
|
|
338
361
|
}
|
|
339
362
|
throw errs[0]?.[1] || new Error('fetch failed');
|
|
340
363
|
}
|
|
@@ -353,6 +376,17 @@ const CLAIM_FAIL = {
|
|
|
353
376
|
|
|
354
377
|
const platform = () => `${process.platform}-${process.arch === 'arm64' ? 'arm64' : process.arch === 'x64' ? 'x64' : process.arch}`;
|
|
355
378
|
|
|
379
|
+
/**
|
|
380
|
+
* 已知活动兜底清单:服务端偶尔把活动从 billing/preview 里藏起来(2026-10-30 WEEKEND BUILD
|
|
381
|
+
* 实测 preview 返回空 plans,但 claim 按 planId 直接可领、免验证码)。preview 查不到时
|
|
382
|
+
* 逐个试这里的 planId:1001/1002(不存在/已结束)当没有,1003 按已领口径,0 即领取成功。
|
|
383
|
+
* 活动过期后条目留在表里无害(claim 返回 1002 跳过);新活动出现时在此追加一行。
|
|
384
|
+
*/
|
|
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
|
+
];
|
|
389
|
+
|
|
356
390
|
export async function zaiHeaders(token, deviceMid) {
|
|
357
391
|
const ver = await zcodeAppVersion();
|
|
358
392
|
return {
|
package/src/zcodeGateway.js
CHANGED
|
@@ -108,6 +108,18 @@ function markRateLimited(id) {
|
|
|
108
108
|
/** 账号补全成功:清零连续 429 计数(下次 429 重新从 30 秒起算) */
|
|
109
109
|
function resetCoolingStreak(id) { coolingStreak.delete(id); }
|
|
110
110
|
|
|
111
|
+
/**
|
|
112
|
+
* 账号被删除时清掉它在各轮换 Map 里的残留(daemon DELETE /api/accounts/:id 调用)。
|
|
113
|
+
* 账号 id 每次导入都是新 UUID,删了不清理的话这些条目永远不会被任何人再触碰。
|
|
114
|
+
*/
|
|
115
|
+
export function forgetAccount(id) {
|
|
116
|
+
cooling.delete(id);
|
|
117
|
+
coolingStreak.delete(id);
|
|
118
|
+
dead.delete(id);
|
|
119
|
+
quotaCache.delete(id);
|
|
120
|
+
for (const [k, v] of sessionSticky) if (v?.accountId === id) sessionSticky.delete(k);
|
|
121
|
+
}
|
|
122
|
+
|
|
111
123
|
/**
|
|
112
124
|
* 测试专用:把某账号的冷却截止拨到指定时间戳(0 = 立即到期,用于快进冷却窗口)。
|
|
113
125
|
* 生产不走这里——冷却窗口只能自然到期。
|
|
@@ -402,6 +414,12 @@ function stickyFor(sessionId) {
|
|
|
402
414
|
/** 会话粘住的号仍可用才粘;否则落到轮转队首,由调用方重新绑定 */
|
|
403
415
|
function touchSticky(sessionId, accountId) {
|
|
404
416
|
if (!sessionId) return;
|
|
417
|
+
// 每段对话一个新 session id,安静会话的条目只有等它自己再被查到才会过期——
|
|
418
|
+
// 长期运行的网关上单调增长。超阈值时整表清一遍过期项。
|
|
419
|
+
if (sessionSticky.size > 500) {
|
|
420
|
+
const now = Date.now();
|
|
421
|
+
for (const [k, v] of sessionSticky) if (now - (v?.at || 0) >= SESSION_STICKY_TTL_MS) sessionSticky.delete(k);
|
|
422
|
+
}
|
|
405
423
|
sessionSticky.set(sessionId, { accountId, at: Date.now() });
|
|
406
424
|
}
|
|
407
425
|
/** 从上游 JSON 信封里取业务码;字符串数字("3007")也认,取不到返回 null */
|
|
@@ -563,6 +581,9 @@ export async function handleGateway(req, res) {
|
|
|
563
581
|
// (MaxListenersExceededWarning + 泄漏)。
|
|
564
582
|
const clientAbort = new AbortController();
|
|
565
583
|
req.once('close', () => { if (!res.writableEnded) clientAbort.abort(); });
|
|
584
|
+
// 优雅断开(客户端 fetch abort 在上游响应前)只触发 res 'close',不触发 req 'close'
|
|
585
|
+
// ——少这一个钩子,Ctrl+C 后整个重试循环(含验证码求解、账号轮换)还在为已死的客户端空跑
|
|
586
|
+
res.once('close', () => { if (!res.writableEnded) clientAbort.abort(); });
|
|
566
587
|
// 首发不带验证码(客户端真实流量多数直过);上游 3007/403 时求解并在此后的
|
|
567
588
|
// 尝试上挂新 token(zcode-api 同策略)。provider 为 null(NAS/CLI)时首过路径依然可用。
|
|
568
589
|
let captcha = null;
|
|
@@ -680,8 +701,17 @@ export async function handleGateway(req, res) {
|
|
|
680
701
|
}
|
|
681
702
|
}
|
|
682
703
|
} catch (e) {
|
|
683
|
-
|
|
684
|
-
|
|
704
|
+
if (clientAbort.signal.aborted) {
|
|
705
|
+
// 客户端主动断开(点停止/换一句)就会在这里结束——属正常收尾,不是故障,降为 debug
|
|
706
|
+
logger.debug('ZCODE-GW', '流式转发中断:{err}', { err: e.message });
|
|
707
|
+
} else {
|
|
708
|
+
// 上游中途断了:直接 res.end() 是无 message_stop 的裸 EOF,客户端只会报
|
|
709
|
+
// 「流意外结束」——按 Anthropic 协议补一帧 error 事件,把原因带出去
|
|
710
|
+
logger.warn('ZCODE-GW', '上游流中断:{err}', { err: e.message });
|
|
711
|
+
try {
|
|
712
|
+
res.write(`event: error\ndata: ${JSON.stringify({ type: 'error', error: { type: 'api_error', message: `上游流中断:${e.message}` } })}\n\n`);
|
|
713
|
+
} catch { /* 客户端已不在 */ }
|
|
714
|
+
}
|
|
685
715
|
}
|
|
686
716
|
res.end();
|
|
687
717
|
return true;
|