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.
- package/LICENSE +701 -2
- package/README.md +454 -440
- package/bin/creditdaddy.js +6 -0
- package/build.json +3 -3
- package/package.json +34 -34
- package/src/accounts.js +15 -0
- package/src/assets/donate-alipay.svg +1 -1
- package/src/assets/donate-ifdian.svg +1 -1
- package/src/assets/donate-wechat.svg +1 -1
- package/src/assets/providers/catpaw.png +0 -0
- package/src/assets/providers/codebuddy-ide.png +0 -0
- package/src/assets/providers/dumate.png +0 -0
- package/src/assets/providers/loomy.png +0 -0
- package/src/assets/providers/meoo.png +0 -0
- package/src/assets/providers/mirasim.png +0 -0
- package/src/bgdaemon.js +341 -341
- package/src/buildInfo.js +65 -65
- package/src/catpawClient.js +103 -103
- package/src/catpawLocal.js +236 -236
- package/src/checkin.js +98 -5
- package/src/codebuddyIdeLocal.js +381 -381
- package/src/constants.js +121 -117
- package/src/cookieSites.js +340 -301
- package/src/daemon.js +2720 -2443
- package/src/doubaoClient.js +167 -167
- package/src/dumateClient.js +517 -0
- package/src/dumateLocal.js +298 -0
- package/src/dumateQr.js +337 -0
- package/src/externalQuota.js +577 -574
- package/src/formatDuration.js +17 -17
- package/src/i18n/en.json +257 -7
- package/src/i18n/ja.json +257 -7
- package/src/i18n/ko.json +257 -7
- package/src/i18n/zh-TW.json +257 -7
- package/src/i18n.js +47 -47
- package/src/lingxiClient.js +373 -373
- package/src/localDetect.js +147 -147
- package/src/longcatClient.js +260 -260
- package/src/loomyAuth.js +230 -230
- package/src/loomyClient.js +366 -366
- package/src/loomyLocal.js +206 -206
- package/src/meooAuth.js +246 -0
- package/src/meooClient.js +250 -0
- package/src/minimaxGateway.js +520 -520
- package/src/minimaxLocal.js +344 -344
- package/src/mirasimClient.js +211 -211
- package/src/mirasimLocal.js +392 -392
- package/src/modelscopeClient.js +275 -275
- package/src/panel.html +704 -85
- package/src/prodIcons.json +7 -5
- package/src/providers.js +34 -0
- package/src/qoderApp.js +578 -578
- package/src/qoderClient.js +266 -266
- package/src/qoderUmid.js +199 -199
- package/src/quotaRefresh.js +119 -119
- package/src/refreshGuard.js +75 -75
- package/src/riverClient.js +372 -372
- package/src/store.js +2 -1
- package/src/tenrouterAccounts.js +237 -232
- package/src/traeAuth.js +601 -599
- package/src/traeClient.js +356 -360
- package/src/traeGateway.js +875 -875
- package/src/traeLocal.js +463 -371
- package/src/transfer.js +4 -0
- package/src/usageSync.js +535 -523
- package/src/winProc.js +134 -134
- package/src/xiaomiMimoClient.js +206 -206
- package/src/zcodeAuth.js +131 -131
- package/src/zcodeAutoClaim.js +53 -6
- package/src/zcodeClient.js +55 -2
- package/src/zcodeGateway.js +850 -850
- package/src/zcodeLocal.js +340 -340
- package/src/zcrypto.js +160 -160
package/src/zcodeGateway.js
CHANGED
|
@@ -1,850 +1,850 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* ZCode 免费额度网关 — Start Plan 体验包(GLM-5.3-Flash)的本地补全代理。
|
|
3
|
-
*
|
|
4
|
-
* 数据面:POST /gateway/zcode/v1/messages(Anthropic /v1/messages 形态,10router
|
|
5
|
-
* 建一个 anthropic-compatible 自定义节点指向这里即可)。
|
|
6
|
-
*
|
|
7
|
-
* 链路:账号轮转(store 里 provider=zcode、可解析出 zcodejwttoken 的账号;
|
|
8
|
-
* 每个请求换一个队首,多任务分摊到各账号,见 rotationQueue)
|
|
9
|
-
* → 验证码(复用桌面版注册的隐藏窗口 provider,与活动领取共用同一个求解器)
|
|
10
|
-
* → POST zcode.z.ai/api/v1/zcode-plan/anthropic/v1/messages
|
|
11
|
-
* → SSE / JSON 原样流式回传。
|
|
12
|
-
*
|
|
13
|
-
* 失败分类:3007/3012(验证码)→ 作废 token 重解重试;401(JWT 失效)→ 拉黑账号;
|
|
14
|
-
* 402/额度不足 → 标记耗尽;429 → 冷却(退避阶梯 30s → 1min → 2min → 5min → 10min 封顶,成功即清零)。
|
|
15
|
-
* 全部失败返回 502 + 各账号结论。
|
|
16
|
-
*
|
|
17
|
-
* 仅限本机回路使用:daemon 只绑 127.0.0.1,网关不做鉴权(跨机场景需要先给
|
|
18
|
-
* daemon 加绑定/密钥,见 README)。NAS/纯 CLI 环境没有验证码提供者,网关开不了。
|
|
19
|
-
*/
|
|
20
|
-
|
|
21
|
-
import { claimToken, fetchCaptchaConfig, fetchJsonRace, fetchZcodeQuota } from './zcodeClient.js';
|
|
22
|
-
import { readFileSync } from 'node:fs';
|
|
23
|
-
import path from 'node:path';
|
|
24
|
-
import { fileURLToPath } from 'node:url';
|
|
25
|
-
|
|
26
|
-
// ZCode 客户端 plan 请求形状(从本机客户端真实流量捕获的载荷模板:系统提示词数组 +
|
|
27
|
-
// currentDate 提醒块 + metadata 会话形状)。网关请求镜像此形状——这就是 405/3012 风控的通过票。
|
|
28
|
-
// 提示词已脱敏(去掉抓包来源的用户路径/会话 id),避免把第三方隐私随请求外发(见 issue #16)。
|
|
29
|
-
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
30
|
-
let PLAN_SHAPE = null;
|
|
31
|
-
try { PLAN_SHAPE = JSON.parse(readFileSync(path.join(__dirname, 'zcodePlanShape.json'), 'utf8')); } catch {}
|
|
32
|
-
|
|
33
|
-
import { getZcodeCaptchaProvider } from './zcodeAutoClaim.js';
|
|
34
|
-
import { gatewayHostSuggestion } from './tenrouter.js';
|
|
35
|
-
|
|
36
|
-
// 整链补全提供者(桌面版注册):隐藏窗口内「真 Chromium 求解验证码 + 同源发起补全」,
|
|
37
|
-
// 规避 Node fetch 的 TLS 指纹风控。签名 ({ captchaCfg, jwt, rawBody }) → { status, contentType, body }。
|
|
38
|
-
let completionProvider = null;
|
|
39
|
-
export function setZcodeCompletionProvider(fn) { completionProvider = typeof fn === 'function' ? fn : null; }
|
|
40
|
-
export function getZcodeCompletionProvider() { return completionProvider; }
|
|
41
|
-
import { loadAccounts, loadSettings, saveSettings, loadState, withState } from './store.js';
|
|
42
|
-
import crypto from 'node:crypto';
|
|
43
|
-
import os from 'node:os';
|
|
44
|
-
import { logger, summarizeAttempts } from './logger.js';
|
|
45
|
-
import { t } from './i18n.js';
|
|
46
|
-
import { formatDurationMs } from './formatDuration.js';
|
|
47
|
-
|
|
48
|
-
const PLAN_MESSAGES_URL = 'https://zcode.z.ai/api/v1/zcode-plan/anthropic/v1/messages';
|
|
49
|
-
const CAPTCHA_CACHE_TTL_MS = 30_000;
|
|
50
|
-
const ACCOUNT_COOLING_MS = 5 * 60_000; // 额度不足(402)等「非限流」失败的冷却
|
|
51
|
-
const MAX_ATTEMPTS = 6;
|
|
52
|
-
// 429 限流的退避阶梯:30s → 1min → 2min → 5min → 10min,之后一直停在 10min。
|
|
53
|
-
// 前四档基本翻倍(上游限流窗口多在分钟级,起步 30s 能快速恢复),
|
|
54
|
-
// 2min → 5min 那跳是陡的(×2.5):说明再往后就是真被持续限流了,给到 10min 兜底后不再涨,
|
|
55
|
-
// 避免「一直被限流的号」被永久排除在轮换之外。见 markRateLimited。
|
|
56
|
-
const RATE_LIMIT_BACKOFF_MS = [30_000, 60_000, 120_000, 300_000, 600_000];
|
|
57
|
-
// 上游补全墙钟上限(响应头到齐后 body 仍可流式跑这么久)
|
|
58
|
-
const UPSTREAM_TIMEOUT_MS = 600_000;
|
|
59
|
-
// 连接段(DNS/TCP/TLS/首字节)限时:上游黑洞挂死时几秒内换下一条路 / 代理兜底,
|
|
60
|
-
// 而不是吊满 10 分钟——这是「网关很慢 / 卡住」体感的主要来源
|
|
61
|
-
const UPSTREAM_CONNECT_MS = 15_000;
|
|
62
|
-
|
|
63
|
-
// ── 开关(持久化在 settings.zcodeGateway) ──
|
|
64
|
-
|
|
65
|
-
export async function gatewayEnabled() {
|
|
66
|
-
return (await loadSettings()).zcodeGateway === true;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
export async function setGatewayEnabled(v) {
|
|
70
|
-
const on = v === true;
|
|
71
|
-
await saveSettings({ zcodeGateway: on });
|
|
72
|
-
// 开启网关视为「重新开始」:清掉进程内的拉黑/冷却状态,
|
|
73
|
-
// 否则重新登录导入后旧黑名单仍会把账号挡在轮换队列外(与 MiniMax 网关同款 bug)。
|
|
74
|
-
if (on) {
|
|
75
|
-
dead.clear();
|
|
76
|
-
cooling.clear();
|
|
77
|
-
coolingStreak.clear();
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
// ── 账号轮换状态(进程内;重启即清零) ──
|
|
82
|
-
|
|
83
|
-
let rrIndex = 0;
|
|
84
|
-
const cooling = new Map(); // accountId → 冷却截止(ms)
|
|
85
|
-
// accountId → 连续 429 次数(成功即清零):决定本次 429 走到退避阶梯的哪一档
|
|
86
|
-
const coolingStreak = new Map();
|
|
87
|
-
const dead = new Map(); // accountId → 拉黑时的凭据指纹(指纹变化 = 已重新登录导入,自动复活)
|
|
88
|
-
// 会话粘滞(用户选 A):sessionId → { accountId, at }。同一段对话的多轮固定用同一个号,
|
|
89
|
-
// TTL 到期让位给轮转,避免冷会话长期占号。声明放这里是因为 __resetForTests 要清它。
|
|
90
|
-
const sessionSticky = new Map();
|
|
91
|
-
|
|
92
|
-
function markCooling(id, ms = ACCOUNT_COOLING_MS) { cooling.set(id, Date.now() + ms); }
|
|
93
|
-
|
|
94
|
-
/**
|
|
95
|
-
* 429 限流:按连续次数走退避阶梯(30s → 1min → 2min → 5min → 10min 封顶)。
|
|
96
|
-
* 上游限流窗口通常在分钟级,从 30s 起步能快速恢复,又不会像固定 5 分钟那样
|
|
97
|
-
* 一直撞在限流窗口里(日志里清一色「冷却 5 分钟」就是这么来的)。
|
|
98
|
-
* 成功时 resetCoolingStreak 清零,所以偶发 429 不会累积。
|
|
99
|
-
*/
|
|
100
|
-
function markRateLimited(id) {
|
|
101
|
-
const streak = (coolingStreak.get(id) || 0) + 1;
|
|
102
|
-
coolingStreak.set(id, streak);
|
|
103
|
-
const ms = RATE_LIMIT_BACKOFF_MS[Math.min(streak, RATE_LIMIT_BACKOFF_MS.length) - 1];
|
|
104
|
-
cooling.set(id, Date.now() + ms);
|
|
105
|
-
return ms;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
/** 账号补全成功:清零连续 429 计数(下次 429 重新从 30 秒起算) */
|
|
109
|
-
function resetCoolingStreak(id) { coolingStreak.delete(id); }
|
|
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
|
-
|
|
123
|
-
/**
|
|
124
|
-
* 测试专用:把某账号的冷却截止拨到指定时间戳(0 = 立即到期,用于快进冷却窗口)。
|
|
125
|
-
* 生产不走这里——冷却窗口只能自然到期。
|
|
126
|
-
*/
|
|
127
|
-
export function __setCoolingForTests(accountId, untilMs) { cooling.set(accountId, untilMs); }
|
|
128
|
-
|
|
129
|
-
/** 测试专用:清空进程内轮换/冷却/拉黑/验证码缓存/统计状态 */
|
|
130
|
-
export function __resetForTests() {
|
|
131
|
-
rrIndex = 0;
|
|
132
|
-
cooling.clear();
|
|
133
|
-
coolingStreak.clear();
|
|
134
|
-
dead.clear();
|
|
135
|
-
quotaCache.clear();
|
|
136
|
-
sessionSticky.clear();
|
|
137
|
-
marksHydrated = false;
|
|
138
|
-
captchaCache = null;
|
|
139
|
-
stats.lastCallAt = null;
|
|
140
|
-
stats.calls = 0;
|
|
141
|
-
stats.lastAccount = null;
|
|
142
|
-
recentEntries.length = 0;
|
|
143
|
-
}
|
|
144
|
-
function markDead(account) {
|
|
145
|
-
dead.set(account.id, credFingerprint(account));
|
|
146
|
-
cooling.set(account.id, Number.MAX_SAFE_INTEGER);
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/** 拉黑时的凭据指纹:重新登录/重新导入会整体替换 meta.credentials,指纹变化即可复活 */
|
|
150
|
-
function credFingerprint(a) {
|
|
151
|
-
return `${a.meta?.credentials?.zcodejwttoken || ''}|${a.token || ''}`;
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
/**
|
|
155
|
-
* 账号是否仍处于拉黑状态。拉黑记的是「当时那份凭据」的指纹:
|
|
156
|
-
* 重新登录导入换了 JWT 后指纹不匹配 → 自动复活(清黑名单与冷却)。
|
|
157
|
-
*/
|
|
158
|
-
function isDead(account) {
|
|
159
|
-
const fp = dead.get(account.id);
|
|
160
|
-
if (fp === undefined) return false;
|
|
161
|
-
if (fp === credFingerprint(account)) return true;
|
|
162
|
-
dead.delete(account.id);
|
|
163
|
-
cooling.delete(account.id);
|
|
164
|
-
coolingStreak.delete(account.id);
|
|
165
|
-
logger.info('ZCODE-GW', '{label} 凭据已更新,解除拉黑', { label: account.name || account.uid || account.id });
|
|
166
|
-
return false;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/**
|
|
170
|
-
* 可参与轮换的账号(有可解析 plan JWT、未冷却/未拉黑),队首 = 本次主用号。
|
|
171
|
-
* @param {string|null} sessionId 调用方带来的会话标识;命中粘滞时该号优先
|
|
172
|
-
*/
|
|
173
|
-
async function rotationQueue(sessionId = null) {
|
|
174
|
-
const all = (await loadAccounts()).filter((a) => a.provider === 'zcode');
|
|
175
|
-
await hydrateMarks();
|
|
176
|
-
const now = Date.now();
|
|
177
|
-
const ready = [];
|
|
178
|
-
for (const a of all) {
|
|
179
|
-
if (isDead(a)) continue;
|
|
180
|
-
if (isQuotaExhausted(a.id)) continue; // 0 额度打标,不再轮换
|
|
181
|
-
if ((cooling.get(a.id) || 0) > now) continue;
|
|
182
|
-
try { claimToken(a); ready.push(a); } catch { /* 快照里没有 plan JWT,跳过 */ }
|
|
183
|
-
}
|
|
184
|
-
if (!ready.length) return [];
|
|
185
|
-
|
|
186
|
-
// 会话粘滞优先:同一段对话的多轮固定用同一个号(用户选 A)。
|
|
187
|
-
// 粘住的号必须仍在可用集里——被拉黑/冷却/打标后粘滞自动让位给轮转。
|
|
188
|
-
if (sessionId) {
|
|
189
|
-
const pinned = stickyFor(sessionId);
|
|
190
|
-
if (pinned) {
|
|
191
|
-
const hit = ready.find((a) => a.id === pinned);
|
|
192
|
-
if (hit) return [hit, ...ready.filter((a) => a.id !== pinned)];
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
// 轮转:每个请求换一个队首,让多任务分摊到各账号(rrIndex 是「下一轮的起点」,
|
|
197
|
-
// 每轮自增 1)。老实现只把 rrIndex 归一化到 ready.length 内、从不自增,
|
|
198
|
-
// 于是队首恒为账号库里的第一个号——「多任务全走一个账号」就是这么来的。
|
|
199
|
-
const start = rrIndex % ready.length;
|
|
200
|
-
rrIndex += 1;
|
|
201
|
-
return [...ready.slice(start), ...ready.slice(0, start)];
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
/** 队列为空时说清原因(与 rotationQueue 同序分类)——额度耗尽不该提示「重新登录导入」 */
|
|
205
|
-
async function unavailableReason() {
|
|
206
|
-
const all = (await loadAccounts()).filter((a) => a.provider === 'zcode');
|
|
207
|
-
if (!all.length) return '没有 ZCode 账号:请在 ZCode 登录后本机导入';
|
|
208
|
-
const now = Date.now();
|
|
209
|
-
const n = { dead: 0, exhausted: 0, cooling: 0, noJwt: 0 };
|
|
210
|
-
for (const a of all) {
|
|
211
|
-
if (isDead(a)) n.dead++;
|
|
212
|
-
else if (isQuotaExhausted(a.id)) n.exhausted++;
|
|
213
|
-
else if ((cooling.get(a.id) || 0) > now) n.cooling++;
|
|
214
|
-
else n.noJwt++; // 未拉黑/未打标/未冷却却不在队列 → 快照里没有可解析的 plan JWT
|
|
215
|
-
}
|
|
216
|
-
if (n.noJwt === all.length) {
|
|
217
|
-
return '没有可用的 ZCode 账号(需要账号快照里有 zcodejwttoken:在 ZCode 重新登录后本机导入)';
|
|
218
|
-
}
|
|
219
|
-
const parts = [];
|
|
220
|
-
if (n.exhausted) parts.push(`${n.exhausted} 个额度耗尽(${Math.round(QUOTA_TTL_MS / 60_000)} 分钟内自动重探,无需重新登录)`);
|
|
221
|
-
if (n.cooling) parts.push(`${n.cooling} 个临时冷却中(稍后自动恢复)`);
|
|
222
|
-
if (n.dead) parts.push(`${n.dead} 个 JWT 已失效(需在 ZCode 重新登录后本机导入)`);
|
|
223
|
-
if (n.noJwt) parts.push(`${n.noJwt} 个缺少 zcodejwttoken(需在 ZCode 重新登录后本机导入)`);
|
|
224
|
-
return `没有可用的 ZCode 账号:${parts.join(';')}`;
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
// ── 验证码(与活动领取共用桌面版隐藏窗口求解器;30s 内复用同一 token) ──
|
|
228
|
-
|
|
229
|
-
let captchaCache = null; // { param, region, at }
|
|
230
|
-
|
|
231
|
-
// 调用统计(进程内):面板「10Router 已接入」活标签的数据源
|
|
232
|
-
const stats = { lastCallAt: null, calls: 0, lastAccount: null };
|
|
233
|
-
const RECENT_ACCOUNTS_MAX = 4; // 面板「接口使用中」徽标的覆盖范围:窗口内最近服役过的前 N 个号
|
|
234
|
-
// 「接口使用中」只认近 30 分钟内真正服役过的号(2026-11-07 用户反馈:无时间衰减时
|
|
235
|
-
// 调用过一次的号永远挂着徽章,四张卡全亮,看起来像只剩一个号在轮转)。
|
|
236
|
-
const RECENT_WINDOW_MS = 30 * 60_000;
|
|
237
|
-
const recentEntries = []; // { label, at } 最新在前,按 label 去重(保留最新一次)
|
|
238
|
-
function recordRecentAccount(label, at = Date.now()) {
|
|
239
|
-
if (!label) return;
|
|
240
|
-
recentEntries.unshift({ label, at });
|
|
241
|
-
const seen = new Set();
|
|
242
|
-
for (let i = recentEntries.length - 1; i >= 0; i--) {
|
|
243
|
-
if (seen.has(recentEntries[i].label)) recentEntries.splice(i, 1);
|
|
244
|
-
else seen.add(recentEntries[i].label);
|
|
245
|
-
}
|
|
246
|
-
if (recentEntries.length > 32) recentEntries.length = 32;
|
|
247
|
-
}
|
|
248
|
-
/** 窗口内的服役名单(最新在前、去重、封顶):gatewayStatus.recentAccounts 的口径。 */
|
|
249
|
-
export function recentLabelsInWindow(entries, now = Date.now(), windowMs = RECENT_WINDOW_MS, cap = RECENT_ACCOUNTS_MAX) {
|
|
250
|
-
const seen = new Set();
|
|
251
|
-
const out = [];
|
|
252
|
-
for (const e of entries) {
|
|
253
|
-
if (!e || typeof e.at !== 'number' || now - e.at > windowMs) continue;
|
|
254
|
-
if (seen.has(e.label)) continue;
|
|
255
|
-
seen.add(e.label);
|
|
256
|
-
out.push(e.label);
|
|
257
|
-
if (out.length >= cap) break;
|
|
258
|
-
}
|
|
259
|
-
return out;
|
|
260
|
-
}
|
|
261
|
-
/** 测试专用:注入指定时间的服役记录(控制窗口过滤的新旧)。 */
|
|
262
|
-
export function _recordRecentForTests(label, at) {
|
|
263
|
-
recordRecentAccount(label, at);
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
// 额度打标:0 额度账号不再轮换(额度缓存 10 分钟,到期自动重探;
|
|
267
|
-
// 1005/1113 失败时也会即时探测确认——剩余>0 视为瞬时错误继续用)
|
|
268
|
-
const QUOTA_TTL_MS = 10 * 60_000;
|
|
269
|
-
const quotaCache = new Map(); // accountId → { remaining, at }
|
|
270
|
-
|
|
271
|
-
let marksHydrated = false;
|
|
272
|
-
async function hydrateMarks() {
|
|
273
|
-
if (marksHydrated) return;
|
|
274
|
-
marksHydrated = true;
|
|
275
|
-
try {
|
|
276
|
-
const st = await loadState();
|
|
277
|
-
const saved = st?.zcodeGatewayExhausted || {};
|
|
278
|
-
for (const [id, e] of Object.entries(saved)) {
|
|
279
|
-
if (e && Date.now() - e.at < QUOTA_TTL_MS && !quotaCache.has(id)) quotaCache.set(id, e);
|
|
280
|
-
}
|
|
281
|
-
} catch { /* 状态读不到就从零开始 */ }
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
async function persistMark(accountId, entry) {
|
|
285
|
-
try {
|
|
286
|
-
await withState((st) => {
|
|
287
|
-
st.zcodeGatewayExhausted = { ...(st.zcodeGatewayExhausted || {}), [accountId]: entry };
|
|
288
|
-
});
|
|
289
|
-
} catch { /* 持久化失败不影响内存态 */ }
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/**
|
|
293
|
-
* 账号刚领到新额度(活动领取成功):清掉耗尽打标(内存 + state.json)和额度不足导致的冷却,
|
|
294
|
-
* 让它立刻回到轮换——否则要等打标 10 分钟 / 冷却 30 分钟到期。JWT 拉黑不受影响。
|
|
295
|
-
*/
|
|
296
|
-
export async function clearQuotaMark(accountId) {
|
|
297
|
-
quotaCache.delete(accountId);
|
|
298
|
-
if (!dead.has(accountId)) cooling.delete(accountId);
|
|
299
|
-
resetCoolingStreak(accountId); // 领到新额度 = 状态已恢复,429 计数重新从 30 秒起算
|
|
300
|
-
try {
|
|
301
|
-
await withState((st) => {
|
|
302
|
-
if (st?.zcodeGatewayExhausted?.[accountId]) delete st.zcodeGatewayExhausted[accountId];
|
|
303
|
-
});
|
|
304
|
-
} catch { /* 持久化失败不影响内存态 */ }
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
function isQuotaExhausted(id) {
|
|
308
|
-
const q = quotaCache.get(id);
|
|
309
|
-
return Boolean(q && Date.now() - q.at < QUOTA_TTL_MS && q.remaining <= 0);
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
async function probeQuota(account) {
|
|
313
|
-
const r = await fetchZcodeQuota(account).catch(() => null);
|
|
314
|
-
const remaining = Number(r?.remaining);
|
|
315
|
-
if (Number.isFinite(remaining)) {
|
|
316
|
-
quotaCache.set(account.id, { remaining, at: Date.now() });
|
|
317
|
-
return remaining;
|
|
318
|
-
}
|
|
319
|
-
return null;
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
async function ensureCaptcha(force = false) {
|
|
323
|
-
if (!force && captchaCache && Date.now() - captchaCache.at < CAPTCHA_CACHE_TTL_MS) return captchaCache;
|
|
324
|
-
const provider = getZcodeCaptchaProvider();
|
|
325
|
-
if (!provider) {
|
|
326
|
-
throw Object.assign(new Error('本环境没有验证码提供者(网关补全需要桌面版 CreditDaddy 运行)'), { code: 'NO_CAPTCHA_PROVIDER' });
|
|
327
|
-
}
|
|
328
|
-
const cfg = await fetchCaptchaConfig();
|
|
329
|
-
if (!cfg.enabled || !cfg.sceneId) {
|
|
330
|
-
throw Object.assign(new Error('验证码配置不可用'), { code: 'NO_CAPTCHA_CONFIG' });
|
|
331
|
-
}
|
|
332
|
-
const { captchaParam, region } = await provider(cfg);
|
|
333
|
-
captchaCache = { param: captchaParam, region, at: Date.now() };
|
|
334
|
-
return captchaCache;
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
function invalidateCaptcha() { captchaCache = null; }
|
|
338
|
-
|
|
339
|
-
// ── 数据面 ──
|
|
340
|
-
|
|
341
|
-
/** 友好化上游错误描述 */
|
|
342
|
-
function formatUpstreamError(status, text) {
|
|
343
|
-
const content = String(text || '').trim();
|
|
344
|
-
|
|
345
|
-
// HTML 错误页面 → 提取关键信息
|
|
346
|
-
if (content.includes('<html>') || content.includes('<h1>')) {
|
|
347
|
-
const titleMatch = content.match(/<h1[^>]*>(.*?)<\/h1>/i);
|
|
348
|
-
if (titleMatch) return `HTML 错误页:${titleMatch[1].trim()}`;
|
|
349
|
-
return 'HTML 错误页(上游服务异常)';
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
// JSON 错误 → 提取业务码和消息
|
|
353
|
-
try {
|
|
354
|
-
const json = JSON.parse(content);
|
|
355
|
-
const codes = [json.code, json.status, json.error?.code];
|
|
356
|
-
const codeStr = codes.find(c => typeof c === 'number');
|
|
357
|
-
const msg = json.message || json.error?.message || '';
|
|
358
|
-
return codeStr ? (msg ? `[code:${codeStr}] ${msg}` : `[code:${codeStr}]`) : '未知错误';
|
|
359
|
-
} catch {
|
|
360
|
-
// 普通文本错误 → 截断显示
|
|
361
|
-
const preview = content.length > 60 ? `${content.slice(0, 60)}...` : content;
|
|
362
|
-
return preview || '(无响应内容)';
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
function readRawBody(req, limitBytes = 20 * 1024 * 1024) {
|
|
367
|
-
return new Promise((resolve, reject) => {
|
|
368
|
-
const chunks = [];
|
|
369
|
-
let size = 0;
|
|
370
|
-
req.on('data', (c) => {
|
|
371
|
-
size += c.length;
|
|
372
|
-
if (size > limitBytes) {
|
|
373
|
-
// 只 pause 不 destroy:destroy 会把 socket 打死,调用方随后写的 413 就发不出去,
|
|
374
|
-
// 客户端只看到 ECONNRESET,分不清「自己请求体写太大」和「网络断了」。
|
|
375
|
-
// 响应写完(res 'finish')再由调用方收尾断开。
|
|
376
|
-
req.pause();
|
|
377
|
-
reject(Object.assign(new Error(`request body too large (limit ${Math.floor(limitBytes / 1024 / 1024)}MB)`), { status: 413 }));
|
|
378
|
-
return;
|
|
379
|
-
}
|
|
380
|
-
chunks.push(c);
|
|
381
|
-
});
|
|
382
|
-
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
383
|
-
req.on('error', reject);
|
|
384
|
-
});
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
// 业务码可能包在 HTTP 200 里(上游对部分错误回 200 + {code}),两类都要看。
|
|
388
|
-
// 裸数字必须加 \b 词边界:否则 "code":4010 会被当成 401 认证失败(→ 账号被永久拉黑),
|
|
389
|
-
// 耗时 10050ms / request-id=11137 / 30071 也会被当成额度耗尽或验证码(→ 冷却 30 分钟 / 空跑一次验证码)。
|
|
390
|
-
const isCaptchaError = (status, text) =>
|
|
391
|
-
status === 405 || /"code"\s*:\s*(3007|3012)\b|\b(3007|3012)\b|captcha|unusual activity/i.test(text);
|
|
392
|
-
|
|
393
|
-
const isAuthError = (status, text) =>
|
|
394
|
-
status === 401 || /"code"\s*:\s*401\b|\b401\b|令牌已过期|验证不正确/.test(text);
|
|
395
|
-
|
|
396
|
-
const isExhausted = (status, text) =>
|
|
397
|
-
status === 402 || /"code"\s*:\s*(1005|1113)\b|\b(1113|1005)\b|余额不足|无可用资源包|exceed quota|insufficient/i.test(text);
|
|
398
|
-
|
|
399
|
-
// 上游成功也会带 code(0 / 200),别把它们当业务错误——与 zcodeClient.businessOk 同一口径
|
|
400
|
-
const BUSINESS_OK = new Set([0, 200]);
|
|
401
|
-
|
|
402
|
-
/**
|
|
403
|
-
* 从调用方 body 的 metadata 里取会话标识。宽容解析三种形状:
|
|
404
|
-
* {"user_id": "{\"session_id\":\"ses_x\",\"account_uuid\":\"...\"}"} (上游同形,最常见)
|
|
405
|
-
* {"session_id": "ses_x"} (裸字段)
|
|
406
|
-
* {"user_id": "ses_x"} (字符串直给)
|
|
407
|
-
* @returns {{sessionId: string|null, accountUuid: string|null}}
|
|
408
|
-
*/
|
|
409
|
-
export function parseSessionMeta(metadata) {
|
|
410
|
-
const out = { sessionId: null, accountUuid: null };
|
|
411
|
-
if (!metadata || typeof metadata !== 'object') return out;
|
|
412
|
-
// 顶层直给的会话字段也算(调用方可能直接放 metadata.session_id)
|
|
413
|
-
out.sessionId = String(metadata.session_id || metadata.conversation_id || metadata.chat_id || '').slice(0, 64) || null;
|
|
414
|
-
const uid = metadata.user_id ?? metadata.userId ?? metadata.user;
|
|
415
|
-
let obj = null;
|
|
416
|
-
if (typeof uid === 'object') obj = uid;
|
|
417
|
-
else if (typeof uid === 'string') {
|
|
418
|
-
const s = uid.trim();
|
|
419
|
-
if (!s) return out;
|
|
420
|
-
if (s.startsWith('{')) {
|
|
421
|
-
try { obj = JSON.parse(s); } catch { out.sessionId = s.slice(0, 64); return out; }
|
|
422
|
-
} else out.sessionId = s.slice(0, 64);
|
|
423
|
-
}
|
|
424
|
-
if (obj && typeof obj === 'object') {
|
|
425
|
-
out.sessionId = String(obj.session_id || obj.sessionId || obj.conversation_id || obj.chat_id || out.sessionId || '').slice(0, 64) || out.sessionId;
|
|
426
|
-
out.accountUuid = String(obj.account_uuid || obj.accountUuid || '').slice(0, 64) || null;
|
|
427
|
-
}
|
|
428
|
-
return out;
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
// ── 会话粘滞:同一会话的多轮对话固定用同一个号 ──
|
|
432
|
-
// 用户选 A:同一段对话不跳号(跳号会让上下文承接出现割裂),新会话才轮转。
|
|
433
|
-
// 只粘「活着的」会话:TTL 到期即让位给轮转,避免某个冷会话长期占着一个号不放。
|
|
434
|
-
const SESSION_STICKY_TTL_MS = 30 * 60_000;
|
|
435
|
-
|
|
436
|
-
/** 取会话当前粘住的号(过期即失效) */
|
|
437
|
-
function stickyFor(sessionId) {
|
|
438
|
-
const e = sessionSticky.get(sessionId);
|
|
439
|
-
if (!e) return null;
|
|
440
|
-
if (Date.now() - e.at >= SESSION_STICKY_TTL_MS) {
|
|
441
|
-
sessionSticky.delete(sessionId);
|
|
442
|
-
return null;
|
|
443
|
-
}
|
|
444
|
-
return e.accountId;
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
/** 会话粘住的号仍可用才粘;否则落到轮转队首,由调用方重新绑定 */
|
|
448
|
-
function touchSticky(sessionId, accountId) {
|
|
449
|
-
if (!sessionId) return;
|
|
450
|
-
// 每段对话一个新 session id,安静会话的条目只有等它自己再被查到才会过期——
|
|
451
|
-
// 长期运行的网关上单调增长。超阈值时整表清一遍过期项。
|
|
452
|
-
if (sessionSticky.size > 500) {
|
|
453
|
-
const now = Date.now();
|
|
454
|
-
for (const [k, v] of sessionSticky) if (now - (v?.at || 0) >= SESSION_STICKY_TTL_MS) sessionSticky.delete(k);
|
|
455
|
-
}
|
|
456
|
-
sessionSticky.set(sessionId, { accountId, at: Date.now() });
|
|
457
|
-
}
|
|
458
|
-
/** 从上游 JSON 信封里取业务码;字符串数字("3007")也认,取不到返回 null */
|
|
459
|
-
function businessCode(v) {
|
|
460
|
-
if (!v || typeof v !== 'object' || v.code === undefined || v.code === null) return null;
|
|
461
|
-
const n = Number(v.code);
|
|
462
|
-
return Number.isFinite(n) ? n : null;
|
|
463
|
-
}
|
|
464
|
-
// 组装与 ZCode 客户端真实流量一致的 plan 请求(镜像 R1 捕获,2026-09-29)
|
|
465
|
-
function buildPlanRequest(rawBody, { token, userId }) {
|
|
466
|
-
const ver = '3.14.3';
|
|
467
|
-
let bodyObj;
|
|
468
|
-
try { bodyObj = JSON.parse(rawBody); } catch { bodyObj = null; }
|
|
469
|
-
if (!bodyObj || typeof bodyObj !== 'object') bodyObj = { model: 'glm-5.3-flash', messages: [] };
|
|
470
|
-
const rawMeta = parseSessionMeta(bodyObj.metadata);
|
|
471
|
-
// 客户端形状:system = ZCode 系统提示词数组;首条 user 消息前插 currentDate 提醒块;
|
|
472
|
-
// metadata.user_id = 会话形状字符串
|
|
473
|
-
if (PLAN_SHAPE) {
|
|
474
|
-
bodyObj.system = PLAN_SHAPE.system;
|
|
475
|
-
const msgs = Array.isArray(bodyObj.messages) ? bodyObj.messages : [];
|
|
476
|
-
const reminderText = PLAN_SHAPE.reminderText
|
|
477
|
-
? PLAN_SHAPE.reminderText.replace(/Today's date is [^.]+\./, `Today's date is ${new Date().toISOString().slice(0, 10)}.`)
|
|
478
|
-
: null;
|
|
479
|
-
if (reminderText) {
|
|
480
|
-
const first = msgs[0];
|
|
481
|
-
const firstIsUser = first?.role === 'user';
|
|
482
|
-
const already = firstIsUser && typeof first.content === 'string' && first.content.includes('<system-reminder>');
|
|
483
|
-
if (!already) {
|
|
484
|
-
const block = { type: 'text', text: reminderText };
|
|
485
|
-
if (firstIsUser && Array.isArray(first.content)) first.content = [block, ...first.content];
|
|
486
|
-
else if (firstIsUser) first.content = [block, { type: 'text', text: String(first.content ?? '') }];
|
|
487
|
-
else msgs.unshift({ role: 'user', content: [block, { type: 'text', text: '.' }] });
|
|
488
|
-
}
|
|
489
|
-
bodyObj.messages = msgs;
|
|
490
|
-
}
|
|
491
|
-
// 会话标识:调用方传了就原样透传(会话粘滞的锚点),没传才随机生成。
|
|
492
|
-
// 注意上游只认这一个字段——网关此前每次都 new 一个新 session_id,
|
|
493
|
-
// 于是上游眼里每请求都是新会话,同一段对话的上下文连续性也丢了。
|
|
494
|
-
bodyObj.metadata = {
|
|
495
|
-
user_id: JSON.stringify({
|
|
496
|
-
account_uuid: rawMeta?.accountUuid || '',
|
|
497
|
-
session_id: rawMeta?.sessionId || 'ses_' + crypto.randomUUID().slice(0, 16),
|
|
498
|
-
}),
|
|
499
|
-
};
|
|
500
|
-
}
|
|
501
|
-
const headers = {
|
|
502
|
-
'Content-Type': 'application/json',
|
|
503
|
-
Accept: '*/*',
|
|
504
|
-
'accept-encoding': 'identity', // 网关不做压缩透传——转发链上有字符串化环节,gzip 字节会损坏
|
|
505
|
-
'User-Agent': `ZCode/${ver} ai-sdk/anthropic/3.0.81`,
|
|
506
|
-
'X-ZCode-App-Version': ver,
|
|
507
|
-
'X-ZCode-Agent': 'glm',
|
|
508
|
-
'X-Title': 'Z Code@cli',
|
|
509
|
-
'HTTP-Referer': 'https://zcode.z.ai',
|
|
510
|
-
'X-Client-Language': 'zh-CN',
|
|
511
|
-
'X-Client-Timezone': Intl.DateTimeFormat().resolvedOptions().timeZone || 'Asia/Shanghai',
|
|
512
|
-
'X-Platform': 'win32-x64',
|
|
513
|
-
'X-Os-Category': 'windows',
|
|
514
|
-
'X-Os-Version': os.release?.() || '10.0.19045',
|
|
515
|
-
'X-Release-Channel': 'production',
|
|
516
|
-
'x-zcode-session-type': 'main',
|
|
517
|
-
'x-zcode-trace-id': crypto.randomUUID(),
|
|
518
|
-
'x-request-id': crypto.randomUUID(),
|
|
519
|
-
'anthropic-version': '2023-06-01',
|
|
520
|
-
Authorization: `Bearer ${token}`,
|
|
521
|
-
};
|
|
522
|
-
return { headers, body: JSON.stringify(bodyObj) };
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
const LOOPBACK_RE = /^(::1|::ffff:127\.0\.0\.1|127\.0\.0\.1)$/;
|
|
526
|
-
function isLoopbackRemote(remote) {
|
|
527
|
-
return !remote || LOOPBACK_RE.test(String(remote));
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
/** 规范化远端地址(剥 IPv4-mapped IPv6 前缀),与白名单条目比对 */
|
|
531
|
-
export function remoteHost(remote) {
|
|
532
|
-
return String(remote || '').replace(/^::ffff:/i, '').trim();
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
/** 白名单匹配:精确 IP / 主机名,或 `*` 结尾的前缀通配(如 192.168.31.*) */
|
|
536
|
-
export function remoteAllowed(remote, allowList) {
|
|
537
|
-
const host = remoteHost(remote);
|
|
538
|
-
if (!host) return false;
|
|
539
|
-
return (Array.isArray(allowList) ? allowList : []).some((entry) => {
|
|
540
|
-
const e = String(entry || '').trim();
|
|
541
|
-
if (!e) return false;
|
|
542
|
-
if (e.endsWith('*')) {
|
|
543
|
-
// 通配要求带点段尾:防止 192.168.31.1* 这类把 .100-.199 整段一起放行的怪手。
|
|
544
|
-
// 要扩整段子网,把写法统一为 192.168.31.*(带尾句点)。
|
|
545
|
-
const prefix = e.slice(0, -1);
|
|
546
|
-
if (!prefix.endsWith('.')) return false;
|
|
547
|
-
return host.toLowerCase().startsWith(prefix.toLowerCase());
|
|
548
|
-
}
|
|
549
|
-
return host.toLowerCase() === e.toLowerCase();
|
|
550
|
-
});
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
/**
|
|
554
|
-
* 网关数据面入口。返回 true 表示响应已写出(含失败结论)。
|
|
555
|
-
*
|
|
556
|
-
* 访问控制:本机回环始终放行;开局域网后仅 IP 白名单内的机器可访问——
|
|
557
|
-
* zcode-free 本就是 10Router 侧免授权供应商,10Router 所在机器加白即可,不再保留虚拟 key 鉴权。
|
|
558
|
-
*/
|
|
559
|
-
export async function handleGateway(req, res) {
|
|
560
|
-
if (req.method !== 'POST') {
|
|
561
|
-
res.writeHead(405, { 'Content-Type': 'application/json' });
|
|
562
|
-
return res.end(JSON.stringify({ error: 'POST /gateway/zcode/v1/messages(Anthropic /v1/messages 形态)' }));
|
|
563
|
-
}
|
|
564
|
-
// settings 一次读齐:开关 + 局域网鉴权共用,省掉一次 settings.json 磁盘读(热路径每请求都走)
|
|
565
|
-
const settings = await loadSettings();
|
|
566
|
-
if (settings.zcodeGateway !== true) {
|
|
567
|
-
res.writeHead(503, { 'Content-Type': 'application/json' });
|
|
568
|
-
return res.end(JSON.stringify({ error: 'ZCode 免费额度网关未开启(面板 → ZCode → 网关开关)' }));
|
|
569
|
-
}
|
|
570
|
-
// 首发不带验证码(客户端真实流量多数直过),所以纯 daemon / NAS 也能用;
|
|
571
|
-
// 只有当上游索要验证码且本环境没有求解提供者时才失败(见 attempts 汇总)。
|
|
572
|
-
|
|
573
|
-
// 鉴权:本机回环免密;开局域网后仅白名单内 IP 免密直连(如 10Router 所在机器——zcode-free 本就是免授权供应商)
|
|
574
|
-
const remote = (req.socket && req.socket.remoteAddress) || '';
|
|
575
|
-
if (!isLoopbackRemote(remote)) {
|
|
576
|
-
if (settings.zcodeGatewayLan !== true) {
|
|
577
|
-
res.writeHead(403, { 'Content-Type': 'application/json' });
|
|
578
|
-
return res.end(JSON.stringify({ error: '网关未允许局域网访问(面板 → ZCode → 接口设置)' }));
|
|
579
|
-
}
|
|
580
|
-
if (!remoteAllowed(remote, settings.zcodeGatewayAllow)) {
|
|
581
|
-
res.writeHead(403, { 'Content-Type': 'application/json' });
|
|
582
|
-
return res.end(JSON.stringify({ error: `来源 ${remoteHost(remote) || '未知'} 不在网关 IP 白名单内(面板 → ZCode → 接口设置里添加)` }));
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
let rawBody;
|
|
587
|
-
try { rawBody = await readRawBody(req); } catch (e) {
|
|
588
|
-
res.writeHead(e.status || 400, { 'Content-Type': 'application/json' });
|
|
589
|
-
// 超限时请求体还没读完:先把 413 发出去,发完再断开,避免客户端继续往这灌数据
|
|
590
|
-
res.on('finish', () => req.destroy());
|
|
591
|
-
return res.end(JSON.stringify({ error: e.message }));
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
// 会话标识在 body 里(不在头里):客户端/10Router 若传了 metadata.user_id
|
|
595
|
-
// 就作为粘滞锚点;没传则 sessionId 为 null,纯轮转。
|
|
596
|
-
let sessionId = null;
|
|
597
|
-
try {
|
|
598
|
-
const parsed = JSON.parse(rawBody);
|
|
599
|
-
sessionId = parseSessionMeta(parsed?.metadata)?.sessionId;
|
|
600
|
-
} catch { /* 非 JSON 体走轮转 */ }
|
|
601
|
-
|
|
602
|
-
const queue = await rotationQueue(sessionId);
|
|
603
|
-
if (!queue.length) {
|
|
604
|
-
res.writeHead(503, { 'Content-Type': 'application/json' });
|
|
605
|
-
return res.end(JSON.stringify({ error: await unavailableReason() }));
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
stats.lastCallAt = new Date().toISOString();
|
|
609
|
-
stats.calls += 1;
|
|
610
|
-
|
|
611
|
-
const attempted = [];
|
|
612
|
-
// 客户端断开 → 取消当前上游请求。整个重试循环共用一个 controller/listener:
|
|
613
|
-
// 放在循环里每轮 new + req.on('close') 会在同一 req 上累积最多 MAX_ATTEMPTS 个监听器
|
|
614
|
-
// (MaxListenersExceededWarning + 泄漏)。
|
|
615
|
-
const clientAbort = new AbortController();
|
|
616
|
-
req.once('close', () => { if (!res.writableEnded) clientAbort.abort(); });
|
|
617
|
-
// 优雅断开(客户端 fetch abort 在上游响应前)只触发 res 'close',不触发 req 'close'
|
|
618
|
-
// ——少这一个钩子,Ctrl+C 后整个重试循环(含验证码求解、账号轮换)还在为已死的客户端空跑
|
|
619
|
-
res.once('close', () => { if (!res.writableEnded) clientAbort.abort(); });
|
|
620
|
-
// 首发不带验证码(客户端真实流量多数直过);上游 3007/403 时求解并在此后的
|
|
621
|
-
// 尝试上挂新 token(zcode-api 同策略)。provider 为 null(NAS/CLI)时首过路径依然可用。
|
|
622
|
-
let captcha = null;
|
|
623
|
-
for (let i = 0; i < Math.min(MAX_ATTEMPTS, queue.length * 2); i++) {
|
|
624
|
-
const account = queue[i % queue.length];
|
|
625
|
-
// 本轮已被打标/冷却/拉黑的号不再重打(第二圈只为验证码重试准备)
|
|
626
|
-
if (isDead(account) || isQuotaExhausted(account.id) || (cooling.get(account.id) || 0) > Date.now()) continue;
|
|
627
|
-
const label = account.name || account.uid || account.id;
|
|
628
|
-
let token;
|
|
629
|
-
try { token = claimToken(account); } catch (e) {
|
|
630
|
-
attempted.push({ account: label, ok: false, error: e.message });
|
|
631
|
-
markDead(account);
|
|
632
|
-
continue;
|
|
633
|
-
}
|
|
634
|
-
|
|
635
|
-
let upstream;
|
|
636
|
-
try {
|
|
637
|
-
// 请求面完全镜像 ZCode 客户端真实流量(R1 捕获):全套 identity 头 + 客户端
|
|
638
|
-
// 系统提示词/提醒块/metadata 形状。验证码不预挂——服务端未风控时直过;
|
|
639
|
-
// 返回 3007/403 再求解挂上重试(zcode-api 同策略)。
|
|
640
|
-
const built = buildPlanRequest(rawBody, { token, userId: account.uid });
|
|
641
|
-
const headers = captcha
|
|
642
|
-
? { ...built.headers, 'X-Aliyun-Captcha-Verify-Param': captcha.param, 'X-Aliyun-Captcha-Verify-Region': captcha.region }
|
|
643
|
-
: built.headers;
|
|
644
|
-
upstream = await fetchJsonRace(PLAN_MESSAGES_URL, {
|
|
645
|
-
method: 'POST',
|
|
646
|
-
headers,
|
|
647
|
-
body: built.body,
|
|
648
|
-
timeoutMs: UPSTREAM_TIMEOUT_MS,
|
|
649
|
-
connectMs: UPSTREAM_CONNECT_MS,
|
|
650
|
-
signal: clientAbort.signal,
|
|
651
|
-
});
|
|
652
|
-
} catch (e) {
|
|
653
|
-
if (clientAbort.signal.aborted) return; // 客户端先断了
|
|
654
|
-
attempted.push({ account: label, ok: false, error: e.message });
|
|
655
|
-
continue;
|
|
656
|
-
}
|
|
657
|
-
|
|
658
|
-
if (upstream.ok) {
|
|
659
|
-
// 上游会把业务错误包在 HTTP 200 + application/json 里(非 SSE)——先验形再转发,
|
|
660
|
-
// 否则客户端拿到「200 但不是 Message」的假成功(cc CLI 的 StreamNoEventsError 就是它)
|
|
661
|
-
const ct = (upstream.headers.get('content-type') || '').toLowerCase();
|
|
662
|
-
if (ct.includes('application/json')) {
|
|
663
|
-
const text = await upstream.text().catch(() => '');
|
|
664
|
-
let v;
|
|
665
|
-
try { v = JSON.parse(text); } catch { v = null; }
|
|
666
|
-
const code = businessCode(v);
|
|
667
|
-
// 上游成功信封也可能带 code(0 / 200),那不是业务错误;字符串数字("3007")同样要拦
|
|
668
|
-
if (code !== null && !BUSINESS_OK.has(code)) {
|
|
669
|
-
if (isCaptchaError(200, text)) {
|
|
670
|
-
invalidateCaptcha();
|
|
671
|
-
attempted.push({ account: label, ok: false, error: '验证码被拒(200 业务码)', captcha: true });
|
|
672
|
-
try { captcha = await ensureCaptcha(true); } catch { captcha = null; }
|
|
673
|
-
continue;
|
|
674
|
-
}
|
|
675
|
-
if (isAuthError(200, text)) {
|
|
676
|
-
markDead(account);
|
|
677
|
-
attempted.push({ account: label, ok: false, error: 'JWT 已失效,账号拉黑' });
|
|
678
|
-
logger.warn('ZCODE-GW', '{label} JWT 失效(200 业务码)', { label });
|
|
679
|
-
continue;
|
|
680
|
-
}
|
|
681
|
-
if (isExhausted(200, text)) {
|
|
682
|
-
const remaining = await probeQuota(account).catch(() => null);
|
|
683
|
-
if (remaining === null) {
|
|
684
|
-
// 探不到额度 ≠ 确认耗尽:不打标(否则一次查询失败就把号挡 10 分钟),只短冷却
|
|
685
|
-
markCooling(account.id, 2 * 60_000);
|
|
686
|
-
attempted.push({ account: label, ok: false, error: '额度被拒且额度查询失败,短冷却' });
|
|
687
|
-
} else if (remaining <= 0) {
|
|
688
|
-
// 确认 0 额度 → 打标(持久化到 state.json,重启不复轮换)
|
|
689
|
-
const entry = { remaining, at: Date.now() };
|
|
690
|
-
quotaCache.set(account.id, entry);
|
|
691
|
-
await persistMark(account.id, entry);
|
|
692
|
-
attempted.push({ account: label, ok: false, error: `额度耗尽(剩余 ${remaining}),已打标` });
|
|
693
|
-
} else {
|
|
694
|
-
// 还有额度却被拒 → 瞬时错误,短冷却继续用
|
|
695
|
-
markCooling(account.id, 2 * 60_000);
|
|
696
|
-
attempted.push({ account: label, ok: false, error: `额度接口瞬时拒绝(剩余 ${remaining})` });
|
|
697
|
-
}
|
|
698
|
-
continue;
|
|
699
|
-
}
|
|
700
|
-
logger.warn('ZCODE-GW', '{label} 上游 200 业务错误:{err} ({snippet})', { label, err: formatUpstreamError(200, text), snippet: text.slice(0, 80) });
|
|
701
|
-
res.writeHead(502, { 'Content-Type': 'application/json' });
|
|
702
|
-
res.end(text);
|
|
703
|
-
return true;
|
|
704
|
-
}
|
|
705
|
-
// 真 Message(非流式)——原样转发
|
|
706
|
-
logger.debug('ZCODE-GW', '{label} 补全成功 ({status})', { label, status: upstream.status });
|
|
707
|
-
stats.lastAccount = label;
|
|
708
|
-
recordRecentAccount(label);
|
|
709
|
-
cooling.delete(account.id);
|
|
710
|
-
resetCoolingStreak(account.id);
|
|
711
|
-
touchSticky(sessionId, account.id); // 会话粘住这个号,后续轮不再跳
|
|
712
|
-
res.writeHead(upstream.status, { 'Content-Type': ct || 'application/json', 'Cache-Control': 'no-cache' });
|
|
713
|
-
res.end(text);
|
|
714
|
-
return true;
|
|
715
|
-
}
|
|
716
|
-
logger.debug('ZCODE-GW', '{label} 补全成功 ({status})', { label, status: upstream.status });
|
|
717
|
-
stats.lastAccount = label;
|
|
718
|
-
recordRecentAccount(label);
|
|
719
|
-
cooling.delete(account.id);
|
|
720
|
-
resetCoolingStreak(account.id);
|
|
721
|
-
touchSticky(sessionId, account.id); // 会话粘住这个号,后续轮不再跳
|
|
722
|
-
// 注意:undici 已自动解压上游 gzip——body 是明文,绝不能再带 content-encoding 头
|
|
723
|
-
// (带着会让客户端对明文做 gunzip → 乱码)
|
|
724
|
-
const out = {
|
|
725
|
-
'Content-Type': upstream.headers.get('content-type') || 'application/json',
|
|
726
|
-
'Cache-Control': 'no-cache',
|
|
727
|
-
};
|
|
728
|
-
res.writeHead(upstream.status, out);
|
|
729
|
-
try {
|
|
730
|
-
const reader = upstream.body.getReader();
|
|
731
|
-
for (;;) {
|
|
732
|
-
const { done, value } = await reader.read();
|
|
733
|
-
if (done) break;
|
|
734
|
-
if (!res.write(Buffer.from(value))) {
|
|
735
|
-
await new Promise((r) => res.once('drain', r));
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
} catch (e) {
|
|
739
|
-
if (clientAbort.signal.aborted) {
|
|
740
|
-
// 客户端主动断开(点停止/换一句)就会在这里结束——属正常收尾,不是故障,降为 debug
|
|
741
|
-
logger.debug('ZCODE-GW', '流式转发中断:{err}', { err: e.message });
|
|
742
|
-
} else {
|
|
743
|
-
// 上游中途断了:直接 res.end() 是无 message_stop 的裸 EOF,客户端只会报
|
|
744
|
-
// 「流意外结束」——按 Anthropic 协议补一帧 error 事件,把原因带出去
|
|
745
|
-
logger.warn('ZCODE-GW', '上游流中断:{err}', { err: e.message });
|
|
746
|
-
try {
|
|
747
|
-
res.write(`event: error\ndata: ${JSON.stringify({ type: 'error', error: { type: 'api_error', message: `上游流中断:${e.message}` } })}\n\n`);
|
|
748
|
-
} catch { /* 客户端已不在 */ }
|
|
749
|
-
}
|
|
750
|
-
}
|
|
751
|
-
res.end();
|
|
752
|
-
return true;
|
|
753
|
-
}
|
|
754
|
-
|
|
755
|
-
const text = await upstream.text().catch(() => '');
|
|
756
|
-
// 验证码类失败:作废 token 并强制重解(有提供者时下一次尝试带上新 token)
|
|
757
|
-
if (isCaptchaError(upstream.status, text)) {
|
|
758
|
-
invalidateCaptcha();
|
|
759
|
-
attempted.push({ account: label, ok: false, error: `验证码被拒(${upstream.status})`, captcha: true });
|
|
760
|
-
logger.warn('ZCODE-GW', '{label} 验证码被拒 ({err})', { label, err: formatUpstreamError(upstream.status, text) });
|
|
761
|
-
try { captcha = await ensureCaptcha(true); } catch (e) {
|
|
762
|
-
logger.warn('ZCODE-GW', '验证码重解失败:{err}', { err: e.message });
|
|
763
|
-
captcha = null;
|
|
764
|
-
}
|
|
765
|
-
continue;
|
|
766
|
-
}
|
|
767
|
-
if (isAuthError(upstream.status, text)) {
|
|
768
|
-
markDead(account);
|
|
769
|
-
attempted.push({ account: label, ok: false, error: 'JWT 已失效,账号拉黑(重新登录后再导入)' });
|
|
770
|
-
logger.debug('ZCODE-GW', '{label} JWT 失效,拉黑', { label });
|
|
771
|
-
continue;
|
|
772
|
-
}
|
|
773
|
-
if (isExhausted(upstream.status, text)) {
|
|
774
|
-
markCooling(account.id, 30 * 60_000);
|
|
775
|
-
attempted.push({ account: label, ok: false, error: '额度不足/无资源包' });
|
|
776
|
-
logger.debug('ZCODE-GW', '{label} 额度不足 ({status})', { label, status: upstream.status });
|
|
777
|
-
continue;
|
|
778
|
-
}
|
|
779
|
-
if (upstream.status === 429) {
|
|
780
|
-
const ms = markRateLimited(account.id);
|
|
781
|
-
const dur = formatDurationMs(ms);
|
|
782
|
-
const streak = coolingStreak.get(account.id);
|
|
783
|
-
attempted.push({ account: label, ok: false, error: `429 限流,冷却 ${dur}` });
|
|
784
|
-
logger.debug('ZCODE-GW', '{label} 429 限流,冷却 {dur}(连续第 {streak} 次)', { label, dur, streak });
|
|
785
|
-
continue;
|
|
786
|
-
}
|
|
787
|
-
// 其他错误:友好化展示 + 原样透传给客户端
|
|
788
|
-
const errorSummary = formatUpstreamError(upstream.status, text);
|
|
789
|
-
logger.warn('ZCODE-GW', '{label} 上游错误 {status} — {summary}', { label, status: upstream.status, summary: errorSummary });
|
|
790
|
-
res.writeHead(upstream.status, { 'Content-Type': 'application/json' });
|
|
791
|
-
res.end(text);
|
|
792
|
-
return true;
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
const failedDetail = summarizeAttempts(attempted);
|
|
796
|
-
logger.warn('ZCODE-GW', '全部 {n} 次尝试失败{detail}(下一请求自动重试)', { n: attempted.length, detail: failedDetail ? ':' + failedDetail : '' });
|
|
797
|
-
res.writeHead(502, { 'Content-Type': 'application/json' });
|
|
798
|
-
res.end(JSON.stringify({ error: 'ZCode 网关:所有账号尝试均失败', attempts: attempted }));
|
|
799
|
-
return true;
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
// ── 面板状态 ──
|
|
803
|
-
|
|
804
|
-
export async function gatewayStatus() {
|
|
805
|
-
const enabled = await gatewayEnabled();
|
|
806
|
-
const hasCaptcha = Boolean(getZcodeCaptchaProvider());
|
|
807
|
-
const all = (await loadAccounts()).filter((a) => a.provider === 'zcode');
|
|
808
|
-
let withJwt = 0;
|
|
809
|
-
for (const a of all) { try { claimToken(a); withJwt++; } catch { /* 无 plan JWT */ } }
|
|
810
|
-
const now = Date.now();
|
|
811
|
-
const settings = await loadSettings();
|
|
812
|
-
return {
|
|
813
|
-
enabled,
|
|
814
|
-
hasCaptcha,
|
|
815
|
-
lan: settings.zcodeGatewayLan === true,
|
|
816
|
-
allow: Array.isArray(settings.zcodeGatewayAllow) ? settings.zcodeGatewayAllow : [],
|
|
817
|
-
suggestAllow: gatewayHostSuggestion(),
|
|
818
|
-
stats: {
|
|
819
|
-
lastCallAt: stats.lastCallAt,
|
|
820
|
-
calls: stats.calls,
|
|
821
|
-
lastAccount: stats.lastAccount,
|
|
822
|
-
// 只回窗口内服役过的号(面板徽章口径);recentWindowMs 让面板能对齐展示
|
|
823
|
-
recentAccounts: recentLabelsInWindow(recentEntries),
|
|
824
|
-
recentWindowMs: RECENT_WINDOW_MS,
|
|
825
|
-
},
|
|
826
|
-
exhausted: all
|
|
827
|
-
.filter((a) => isQuotaExhausted(a.id))
|
|
828
|
-
.map((a) => ({ id: a.id, name: a.name || a.uid || a.id, remaining: quotaCache.get(a.id)?.remaining ?? 0 })),
|
|
829
|
-
accounts: all.length,
|
|
830
|
-
accountsWithJwt: withJwt,
|
|
831
|
-
// 会话粘滞:当前有多少段会话各自钉在一个号上(面板「接口使用中」徽标据此说明)
|
|
832
|
-
stickySessions: sessionSticky.size,
|
|
833
|
-
// cooling 保持字符串数组(历史形状,测试与面板按名字读);冷却细节走 coolingDetail
|
|
834
|
-
cooling: all.filter((a) => !isDead(a) && (cooling.get(a.id) || 0) > now).map((a) => a.name || a.uid || a.id),
|
|
835
|
-
coolingDetail: all.filter((a) => !isDead(a) && (cooling.get(a.id) || 0) > now)
|
|
836
|
-
.map((a) => {
|
|
837
|
-
const remainMs = (cooling.get(a.id) || 0) - now;
|
|
838
|
-
return {
|
|
839
|
-
id: a.id, name: a.name || a.uid || a.id,
|
|
840
|
-
// 秒数为准:退避阶梯第一档只有 30s,按分钟四舍五入会显示成 1 分钟
|
|
841
|
-
remainMs, remainSeconds: Math.max(0, Math.ceil(remainMs / 1000)),
|
|
842
|
-
remainText: formatDurationMs(remainMs),
|
|
843
|
-
streak: coolingStreak.get(a.id) || 0,
|
|
844
|
-
};
|
|
845
|
-
}),
|
|
846
|
-
dead: all.filter((a) => isDead(a)).map((a) => a.name || a.uid || a.id),
|
|
847
|
-
endpoint: '/gateway/zcode/v1/messages',
|
|
848
|
-
note: hasCaptcha ? null : '需要桌面版 CreditDaddy(隐藏窗口验证码),纯 CLI / NAS 环境不可用',
|
|
849
|
-
};
|
|
850
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* ZCode 免费额度网关 — Start Plan 体验包(GLM-5.3-Flash)的本地补全代理。
|
|
3
|
+
*
|
|
4
|
+
* 数据面:POST /gateway/zcode/v1/messages(Anthropic /v1/messages 形态,10router
|
|
5
|
+
* 建一个 anthropic-compatible 自定义节点指向这里即可)。
|
|
6
|
+
*
|
|
7
|
+
* 链路:账号轮转(store 里 provider=zcode、可解析出 zcodejwttoken 的账号;
|
|
8
|
+
* 每个请求换一个队首,多任务分摊到各账号,见 rotationQueue)
|
|
9
|
+
* → 验证码(复用桌面版注册的隐藏窗口 provider,与活动领取共用同一个求解器)
|
|
10
|
+
* → POST zcode.z.ai/api/v1/zcode-plan/anthropic/v1/messages
|
|
11
|
+
* → SSE / JSON 原样流式回传。
|
|
12
|
+
*
|
|
13
|
+
* 失败分类:3007/3012(验证码)→ 作废 token 重解重试;401(JWT 失效)→ 拉黑账号;
|
|
14
|
+
* 402/额度不足 → 标记耗尽;429 → 冷却(退避阶梯 30s → 1min → 2min → 5min → 10min 封顶,成功即清零)。
|
|
15
|
+
* 全部失败返回 502 + 各账号结论。
|
|
16
|
+
*
|
|
17
|
+
* 仅限本机回路使用:daemon 只绑 127.0.0.1,网关不做鉴权(跨机场景需要先给
|
|
18
|
+
* daemon 加绑定/密钥,见 README)。NAS/纯 CLI 环境没有验证码提供者,网关开不了。
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { claimToken, fetchCaptchaConfig, fetchJsonRace, fetchZcodeQuota } from './zcodeClient.js';
|
|
22
|
+
import { readFileSync } from 'node:fs';
|
|
23
|
+
import path from 'node:path';
|
|
24
|
+
import { fileURLToPath } from 'node:url';
|
|
25
|
+
|
|
26
|
+
// ZCode 客户端 plan 请求形状(从本机客户端真实流量捕获的载荷模板:系统提示词数组 +
|
|
27
|
+
// currentDate 提醒块 + metadata 会话形状)。网关请求镜像此形状——这就是 405/3012 风控的通过票。
|
|
28
|
+
// 提示词已脱敏(去掉抓包来源的用户路径/会话 id),避免把第三方隐私随请求外发(见 issue #16)。
|
|
29
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
30
|
+
let PLAN_SHAPE = null;
|
|
31
|
+
try { PLAN_SHAPE = JSON.parse(readFileSync(path.join(__dirname, 'zcodePlanShape.json'), 'utf8')); } catch {}
|
|
32
|
+
|
|
33
|
+
import { getZcodeCaptchaProvider } from './zcodeAutoClaim.js';
|
|
34
|
+
import { gatewayHostSuggestion } from './tenrouter.js';
|
|
35
|
+
|
|
36
|
+
// 整链补全提供者(桌面版注册):隐藏窗口内「真 Chromium 求解验证码 + 同源发起补全」,
|
|
37
|
+
// 规避 Node fetch 的 TLS 指纹风控。签名 ({ captchaCfg, jwt, rawBody }) → { status, contentType, body }。
|
|
38
|
+
let completionProvider = null;
|
|
39
|
+
export function setZcodeCompletionProvider(fn) { completionProvider = typeof fn === 'function' ? fn : null; }
|
|
40
|
+
export function getZcodeCompletionProvider() { return completionProvider; }
|
|
41
|
+
import { loadAccounts, loadSettings, saveSettings, loadState, withState } from './store.js';
|
|
42
|
+
import crypto from 'node:crypto';
|
|
43
|
+
import os from 'node:os';
|
|
44
|
+
import { logger, summarizeAttempts } from './logger.js';
|
|
45
|
+
import { t } from './i18n.js';
|
|
46
|
+
import { formatDurationMs } from './formatDuration.js';
|
|
47
|
+
|
|
48
|
+
const PLAN_MESSAGES_URL = 'https://zcode.z.ai/api/v1/zcode-plan/anthropic/v1/messages';
|
|
49
|
+
const CAPTCHA_CACHE_TTL_MS = 30_000;
|
|
50
|
+
const ACCOUNT_COOLING_MS = 5 * 60_000; // 额度不足(402)等「非限流」失败的冷却
|
|
51
|
+
const MAX_ATTEMPTS = 6;
|
|
52
|
+
// 429 限流的退避阶梯:30s → 1min → 2min → 5min → 10min,之后一直停在 10min。
|
|
53
|
+
// 前四档基本翻倍(上游限流窗口多在分钟级,起步 30s 能快速恢复),
|
|
54
|
+
// 2min → 5min 那跳是陡的(×2.5):说明再往后就是真被持续限流了,给到 10min 兜底后不再涨,
|
|
55
|
+
// 避免「一直被限流的号」被永久排除在轮换之外。见 markRateLimited。
|
|
56
|
+
const RATE_LIMIT_BACKOFF_MS = [30_000, 60_000, 120_000, 300_000, 600_000];
|
|
57
|
+
// 上游补全墙钟上限(响应头到齐后 body 仍可流式跑这么久)
|
|
58
|
+
const UPSTREAM_TIMEOUT_MS = 600_000;
|
|
59
|
+
// 连接段(DNS/TCP/TLS/首字节)限时:上游黑洞挂死时几秒内换下一条路 / 代理兜底,
|
|
60
|
+
// 而不是吊满 10 分钟——这是「网关很慢 / 卡住」体感的主要来源
|
|
61
|
+
const UPSTREAM_CONNECT_MS = 15_000;
|
|
62
|
+
|
|
63
|
+
// ── 开关(持久化在 settings.zcodeGateway) ──
|
|
64
|
+
|
|
65
|
+
export async function gatewayEnabled() {
|
|
66
|
+
return (await loadSettings()).zcodeGateway === true;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function setGatewayEnabled(v) {
|
|
70
|
+
const on = v === true;
|
|
71
|
+
await saveSettings({ zcodeGateway: on });
|
|
72
|
+
// 开启网关视为「重新开始」:清掉进程内的拉黑/冷却状态,
|
|
73
|
+
// 否则重新登录导入后旧黑名单仍会把账号挡在轮换队列外(与 MiniMax 网关同款 bug)。
|
|
74
|
+
if (on) {
|
|
75
|
+
dead.clear();
|
|
76
|
+
cooling.clear();
|
|
77
|
+
coolingStreak.clear();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// ── 账号轮换状态(进程内;重启即清零) ──
|
|
82
|
+
|
|
83
|
+
let rrIndex = 0;
|
|
84
|
+
const cooling = new Map(); // accountId → 冷却截止(ms)
|
|
85
|
+
// accountId → 连续 429 次数(成功即清零):决定本次 429 走到退避阶梯的哪一档
|
|
86
|
+
const coolingStreak = new Map();
|
|
87
|
+
const dead = new Map(); // accountId → 拉黑时的凭据指纹(指纹变化 = 已重新登录导入,自动复活)
|
|
88
|
+
// 会话粘滞(用户选 A):sessionId → { accountId, at }。同一段对话的多轮固定用同一个号,
|
|
89
|
+
// TTL 到期让位给轮转,避免冷会话长期占号。声明放这里是因为 __resetForTests 要清它。
|
|
90
|
+
const sessionSticky = new Map();
|
|
91
|
+
|
|
92
|
+
function markCooling(id, ms = ACCOUNT_COOLING_MS) { cooling.set(id, Date.now() + ms); }
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* 429 限流:按连续次数走退避阶梯(30s → 1min → 2min → 5min → 10min 封顶)。
|
|
96
|
+
* 上游限流窗口通常在分钟级,从 30s 起步能快速恢复,又不会像固定 5 分钟那样
|
|
97
|
+
* 一直撞在限流窗口里(日志里清一色「冷却 5 分钟」就是这么来的)。
|
|
98
|
+
* 成功时 resetCoolingStreak 清零,所以偶发 429 不会累积。
|
|
99
|
+
*/
|
|
100
|
+
function markRateLimited(id) {
|
|
101
|
+
const streak = (coolingStreak.get(id) || 0) + 1;
|
|
102
|
+
coolingStreak.set(id, streak);
|
|
103
|
+
const ms = RATE_LIMIT_BACKOFF_MS[Math.min(streak, RATE_LIMIT_BACKOFF_MS.length) - 1];
|
|
104
|
+
cooling.set(id, Date.now() + ms);
|
|
105
|
+
return ms;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 账号补全成功:清零连续 429 计数(下次 429 重新从 30 秒起算) */
|
|
109
|
+
function resetCoolingStreak(id) { coolingStreak.delete(id); }
|
|
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
|
+
|
|
123
|
+
/**
|
|
124
|
+
* 测试专用:把某账号的冷却截止拨到指定时间戳(0 = 立即到期,用于快进冷却窗口)。
|
|
125
|
+
* 生产不走这里——冷却窗口只能自然到期。
|
|
126
|
+
*/
|
|
127
|
+
export function __setCoolingForTests(accountId, untilMs) { cooling.set(accountId, untilMs); }
|
|
128
|
+
|
|
129
|
+
/** 测试专用:清空进程内轮换/冷却/拉黑/验证码缓存/统计状态 */
|
|
130
|
+
export function __resetForTests() {
|
|
131
|
+
rrIndex = 0;
|
|
132
|
+
cooling.clear();
|
|
133
|
+
coolingStreak.clear();
|
|
134
|
+
dead.clear();
|
|
135
|
+
quotaCache.clear();
|
|
136
|
+
sessionSticky.clear();
|
|
137
|
+
marksHydrated = false;
|
|
138
|
+
captchaCache = null;
|
|
139
|
+
stats.lastCallAt = null;
|
|
140
|
+
stats.calls = 0;
|
|
141
|
+
stats.lastAccount = null;
|
|
142
|
+
recentEntries.length = 0;
|
|
143
|
+
}
|
|
144
|
+
function markDead(account) {
|
|
145
|
+
dead.set(account.id, credFingerprint(account));
|
|
146
|
+
cooling.set(account.id, Number.MAX_SAFE_INTEGER);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** 拉黑时的凭据指纹:重新登录/重新导入会整体替换 meta.credentials,指纹变化即可复活 */
|
|
150
|
+
function credFingerprint(a) {
|
|
151
|
+
return `${a.meta?.credentials?.zcodejwttoken || ''}|${a.token || ''}`;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* 账号是否仍处于拉黑状态。拉黑记的是「当时那份凭据」的指纹:
|
|
156
|
+
* 重新登录导入换了 JWT 后指纹不匹配 → 自动复活(清黑名单与冷却)。
|
|
157
|
+
*/
|
|
158
|
+
function isDead(account) {
|
|
159
|
+
const fp = dead.get(account.id);
|
|
160
|
+
if (fp === undefined) return false;
|
|
161
|
+
if (fp === credFingerprint(account)) return true;
|
|
162
|
+
dead.delete(account.id);
|
|
163
|
+
cooling.delete(account.id);
|
|
164
|
+
coolingStreak.delete(account.id);
|
|
165
|
+
logger.info('ZCODE-GW', '{label} 凭据已更新,解除拉黑', { label: account.name || account.uid || account.id });
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* 可参与轮换的账号(有可解析 plan JWT、未冷却/未拉黑),队首 = 本次主用号。
|
|
171
|
+
* @param {string|null} sessionId 调用方带来的会话标识;命中粘滞时该号优先
|
|
172
|
+
*/
|
|
173
|
+
async function rotationQueue(sessionId = null) {
|
|
174
|
+
const all = (await loadAccounts()).filter((a) => a.provider === 'zcode');
|
|
175
|
+
await hydrateMarks();
|
|
176
|
+
const now = Date.now();
|
|
177
|
+
const ready = [];
|
|
178
|
+
for (const a of all) {
|
|
179
|
+
if (isDead(a)) continue;
|
|
180
|
+
if (isQuotaExhausted(a.id)) continue; // 0 额度打标,不再轮换
|
|
181
|
+
if ((cooling.get(a.id) || 0) > now) continue;
|
|
182
|
+
try { claimToken(a); ready.push(a); } catch { /* 快照里没有 plan JWT,跳过 */ }
|
|
183
|
+
}
|
|
184
|
+
if (!ready.length) return [];
|
|
185
|
+
|
|
186
|
+
// 会话粘滞优先:同一段对话的多轮固定用同一个号(用户选 A)。
|
|
187
|
+
// 粘住的号必须仍在可用集里——被拉黑/冷却/打标后粘滞自动让位给轮转。
|
|
188
|
+
if (sessionId) {
|
|
189
|
+
const pinned = stickyFor(sessionId);
|
|
190
|
+
if (pinned) {
|
|
191
|
+
const hit = ready.find((a) => a.id === pinned);
|
|
192
|
+
if (hit) return [hit, ...ready.filter((a) => a.id !== pinned)];
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// 轮转:每个请求换一个队首,让多任务分摊到各账号(rrIndex 是「下一轮的起点」,
|
|
197
|
+
// 每轮自增 1)。老实现只把 rrIndex 归一化到 ready.length 内、从不自增,
|
|
198
|
+
// 于是队首恒为账号库里的第一个号——「多任务全走一个账号」就是这么来的。
|
|
199
|
+
const start = rrIndex % ready.length;
|
|
200
|
+
rrIndex += 1;
|
|
201
|
+
return [...ready.slice(start), ...ready.slice(0, start)];
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** 队列为空时说清原因(与 rotationQueue 同序分类)——额度耗尽不该提示「重新登录导入」 */
|
|
205
|
+
async function unavailableReason() {
|
|
206
|
+
const all = (await loadAccounts()).filter((a) => a.provider === 'zcode');
|
|
207
|
+
if (!all.length) return '没有 ZCode 账号:请在 ZCode 登录后本机导入';
|
|
208
|
+
const now = Date.now();
|
|
209
|
+
const n = { dead: 0, exhausted: 0, cooling: 0, noJwt: 0 };
|
|
210
|
+
for (const a of all) {
|
|
211
|
+
if (isDead(a)) n.dead++;
|
|
212
|
+
else if (isQuotaExhausted(a.id)) n.exhausted++;
|
|
213
|
+
else if ((cooling.get(a.id) || 0) > now) n.cooling++;
|
|
214
|
+
else n.noJwt++; // 未拉黑/未打标/未冷却却不在队列 → 快照里没有可解析的 plan JWT
|
|
215
|
+
}
|
|
216
|
+
if (n.noJwt === all.length) {
|
|
217
|
+
return '没有可用的 ZCode 账号(需要账号快照里有 zcodejwttoken:在 ZCode 重新登录后本机导入)';
|
|
218
|
+
}
|
|
219
|
+
const parts = [];
|
|
220
|
+
if (n.exhausted) parts.push(`${n.exhausted} 个额度耗尽(${Math.round(QUOTA_TTL_MS / 60_000)} 分钟内自动重探,无需重新登录)`);
|
|
221
|
+
if (n.cooling) parts.push(`${n.cooling} 个临时冷却中(稍后自动恢复)`);
|
|
222
|
+
if (n.dead) parts.push(`${n.dead} 个 JWT 已失效(需在 ZCode 重新登录后本机导入)`);
|
|
223
|
+
if (n.noJwt) parts.push(`${n.noJwt} 个缺少 zcodejwttoken(需在 ZCode 重新登录后本机导入)`);
|
|
224
|
+
return `没有可用的 ZCode 账号:${parts.join(';')}`;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// ── 验证码(与活动领取共用桌面版隐藏窗口求解器;30s 内复用同一 token) ──
|
|
228
|
+
|
|
229
|
+
let captchaCache = null; // { param, region, at }
|
|
230
|
+
|
|
231
|
+
// 调用统计(进程内):面板「10Router 已接入」活标签的数据源
|
|
232
|
+
const stats = { lastCallAt: null, calls: 0, lastAccount: null };
|
|
233
|
+
const RECENT_ACCOUNTS_MAX = 4; // 面板「接口使用中」徽标的覆盖范围:窗口内最近服役过的前 N 个号
|
|
234
|
+
// 「接口使用中」只认近 30 分钟内真正服役过的号(2026-11-07 用户反馈:无时间衰减时
|
|
235
|
+
// 调用过一次的号永远挂着徽章,四张卡全亮,看起来像只剩一个号在轮转)。
|
|
236
|
+
const RECENT_WINDOW_MS = 30 * 60_000;
|
|
237
|
+
const recentEntries = []; // { label, at } 最新在前,按 label 去重(保留最新一次)
|
|
238
|
+
function recordRecentAccount(label, at = Date.now()) {
|
|
239
|
+
if (!label) return;
|
|
240
|
+
recentEntries.unshift({ label, at });
|
|
241
|
+
const seen = new Set();
|
|
242
|
+
for (let i = recentEntries.length - 1; i >= 0; i--) {
|
|
243
|
+
if (seen.has(recentEntries[i].label)) recentEntries.splice(i, 1);
|
|
244
|
+
else seen.add(recentEntries[i].label);
|
|
245
|
+
}
|
|
246
|
+
if (recentEntries.length > 32) recentEntries.length = 32;
|
|
247
|
+
}
|
|
248
|
+
/** 窗口内的服役名单(最新在前、去重、封顶):gatewayStatus.recentAccounts 的口径。 */
|
|
249
|
+
export function recentLabelsInWindow(entries, now = Date.now(), windowMs = RECENT_WINDOW_MS, cap = RECENT_ACCOUNTS_MAX) {
|
|
250
|
+
const seen = new Set();
|
|
251
|
+
const out = [];
|
|
252
|
+
for (const e of entries) {
|
|
253
|
+
if (!e || typeof e.at !== 'number' || now - e.at > windowMs) continue;
|
|
254
|
+
if (seen.has(e.label)) continue;
|
|
255
|
+
seen.add(e.label);
|
|
256
|
+
out.push(e.label);
|
|
257
|
+
if (out.length >= cap) break;
|
|
258
|
+
}
|
|
259
|
+
return out;
|
|
260
|
+
}
|
|
261
|
+
/** 测试专用:注入指定时间的服役记录(控制窗口过滤的新旧)。 */
|
|
262
|
+
export function _recordRecentForTests(label, at) {
|
|
263
|
+
recordRecentAccount(label, at);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// 额度打标:0 额度账号不再轮换(额度缓存 10 分钟,到期自动重探;
|
|
267
|
+
// 1005/1113 失败时也会即时探测确认——剩余>0 视为瞬时错误继续用)
|
|
268
|
+
const QUOTA_TTL_MS = 10 * 60_000;
|
|
269
|
+
const quotaCache = new Map(); // accountId → { remaining, at }
|
|
270
|
+
|
|
271
|
+
let marksHydrated = false;
|
|
272
|
+
async function hydrateMarks() {
|
|
273
|
+
if (marksHydrated) return;
|
|
274
|
+
marksHydrated = true;
|
|
275
|
+
try {
|
|
276
|
+
const st = await loadState();
|
|
277
|
+
const saved = st?.zcodeGatewayExhausted || {};
|
|
278
|
+
for (const [id, e] of Object.entries(saved)) {
|
|
279
|
+
if (e && Date.now() - e.at < QUOTA_TTL_MS && !quotaCache.has(id)) quotaCache.set(id, e);
|
|
280
|
+
}
|
|
281
|
+
} catch { /* 状态读不到就从零开始 */ }
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async function persistMark(accountId, entry) {
|
|
285
|
+
try {
|
|
286
|
+
await withState((st) => {
|
|
287
|
+
st.zcodeGatewayExhausted = { ...(st.zcodeGatewayExhausted || {}), [accountId]: entry };
|
|
288
|
+
});
|
|
289
|
+
} catch { /* 持久化失败不影响内存态 */ }
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* 账号刚领到新额度(活动领取成功):清掉耗尽打标(内存 + state.json)和额度不足导致的冷却,
|
|
294
|
+
* 让它立刻回到轮换——否则要等打标 10 分钟 / 冷却 30 分钟到期。JWT 拉黑不受影响。
|
|
295
|
+
*/
|
|
296
|
+
export async function clearQuotaMark(accountId) {
|
|
297
|
+
quotaCache.delete(accountId);
|
|
298
|
+
if (!dead.has(accountId)) cooling.delete(accountId);
|
|
299
|
+
resetCoolingStreak(accountId); // 领到新额度 = 状态已恢复,429 计数重新从 30 秒起算
|
|
300
|
+
try {
|
|
301
|
+
await withState((st) => {
|
|
302
|
+
if (st?.zcodeGatewayExhausted?.[accountId]) delete st.zcodeGatewayExhausted[accountId];
|
|
303
|
+
});
|
|
304
|
+
} catch { /* 持久化失败不影响内存态 */ }
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function isQuotaExhausted(id) {
|
|
308
|
+
const q = quotaCache.get(id);
|
|
309
|
+
return Boolean(q && Date.now() - q.at < QUOTA_TTL_MS && q.remaining <= 0);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
async function probeQuota(account) {
|
|
313
|
+
const r = await fetchZcodeQuota(account).catch(() => null);
|
|
314
|
+
const remaining = Number(r?.remaining);
|
|
315
|
+
if (Number.isFinite(remaining)) {
|
|
316
|
+
quotaCache.set(account.id, { remaining, at: Date.now() });
|
|
317
|
+
return remaining;
|
|
318
|
+
}
|
|
319
|
+
return null;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async function ensureCaptcha(force = false) {
|
|
323
|
+
if (!force && captchaCache && Date.now() - captchaCache.at < CAPTCHA_CACHE_TTL_MS) return captchaCache;
|
|
324
|
+
const provider = getZcodeCaptchaProvider();
|
|
325
|
+
if (!provider) {
|
|
326
|
+
throw Object.assign(new Error('本环境没有验证码提供者(网关补全需要桌面版 CreditDaddy 运行)'), { code: 'NO_CAPTCHA_PROVIDER' });
|
|
327
|
+
}
|
|
328
|
+
const cfg = await fetchCaptchaConfig();
|
|
329
|
+
if (!cfg.enabled || !cfg.sceneId) {
|
|
330
|
+
throw Object.assign(new Error('验证码配置不可用'), { code: 'NO_CAPTCHA_CONFIG' });
|
|
331
|
+
}
|
|
332
|
+
const { captchaParam, region } = await provider(cfg);
|
|
333
|
+
captchaCache = { param: captchaParam, region, at: Date.now() };
|
|
334
|
+
return captchaCache;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function invalidateCaptcha() { captchaCache = null; }
|
|
338
|
+
|
|
339
|
+
// ── 数据面 ──
|
|
340
|
+
|
|
341
|
+
/** 友好化上游错误描述 */
|
|
342
|
+
function formatUpstreamError(status, text) {
|
|
343
|
+
const content = String(text || '').trim();
|
|
344
|
+
|
|
345
|
+
// HTML 错误页面 → 提取关键信息
|
|
346
|
+
if (content.includes('<html>') || content.includes('<h1>')) {
|
|
347
|
+
const titleMatch = content.match(/<h1[^>]*>(.*?)<\/h1>/i);
|
|
348
|
+
if (titleMatch) return `HTML 错误页:${titleMatch[1].trim()}`;
|
|
349
|
+
return 'HTML 错误页(上游服务异常)';
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// JSON 错误 → 提取业务码和消息
|
|
353
|
+
try {
|
|
354
|
+
const json = JSON.parse(content);
|
|
355
|
+
const codes = [json.code, json.status, json.error?.code];
|
|
356
|
+
const codeStr = codes.find(c => typeof c === 'number');
|
|
357
|
+
const msg = json.message || json.error?.message || '';
|
|
358
|
+
return codeStr ? (msg ? `[code:${codeStr}] ${msg}` : `[code:${codeStr}]`) : '未知错误';
|
|
359
|
+
} catch {
|
|
360
|
+
// 普通文本错误 → 截断显示
|
|
361
|
+
const preview = content.length > 60 ? `${content.slice(0, 60)}...` : content;
|
|
362
|
+
return preview || '(无响应内容)';
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function readRawBody(req, limitBytes = 20 * 1024 * 1024) {
|
|
367
|
+
return new Promise((resolve, reject) => {
|
|
368
|
+
const chunks = [];
|
|
369
|
+
let size = 0;
|
|
370
|
+
req.on('data', (c) => {
|
|
371
|
+
size += c.length;
|
|
372
|
+
if (size > limitBytes) {
|
|
373
|
+
// 只 pause 不 destroy:destroy 会把 socket 打死,调用方随后写的 413 就发不出去,
|
|
374
|
+
// 客户端只看到 ECONNRESET,分不清「自己请求体写太大」和「网络断了」。
|
|
375
|
+
// 响应写完(res 'finish')再由调用方收尾断开。
|
|
376
|
+
req.pause();
|
|
377
|
+
reject(Object.assign(new Error(`request body too large (limit ${Math.floor(limitBytes / 1024 / 1024)}MB)`), { status: 413 }));
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
chunks.push(c);
|
|
381
|
+
});
|
|
382
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
383
|
+
req.on('error', reject);
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// 业务码可能包在 HTTP 200 里(上游对部分错误回 200 + {code}),两类都要看。
|
|
388
|
+
// 裸数字必须加 \b 词边界:否则 "code":4010 会被当成 401 认证失败(→ 账号被永久拉黑),
|
|
389
|
+
// 耗时 10050ms / request-id=11137 / 30071 也会被当成额度耗尽或验证码(→ 冷却 30 分钟 / 空跑一次验证码)。
|
|
390
|
+
const isCaptchaError = (status, text) =>
|
|
391
|
+
status === 405 || /"code"\s*:\s*(3007|3012)\b|\b(3007|3012)\b|captcha|unusual activity/i.test(text);
|
|
392
|
+
|
|
393
|
+
const isAuthError = (status, text) =>
|
|
394
|
+
status === 401 || /"code"\s*:\s*401\b|\b401\b|令牌已过期|验证不正确/.test(text);
|
|
395
|
+
|
|
396
|
+
const isExhausted = (status, text) =>
|
|
397
|
+
status === 402 || /"code"\s*:\s*(1005|1113)\b|\b(1113|1005)\b|余额不足|无可用资源包|exceed quota|insufficient/i.test(text);
|
|
398
|
+
|
|
399
|
+
// 上游成功也会带 code(0 / 200),别把它们当业务错误——与 zcodeClient.businessOk 同一口径
|
|
400
|
+
const BUSINESS_OK = new Set([0, 200]);
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* 从调用方 body 的 metadata 里取会话标识。宽容解析三种形状:
|
|
404
|
+
* {"user_id": "{\"session_id\":\"ses_x\",\"account_uuid\":\"...\"}"} (上游同形,最常见)
|
|
405
|
+
* {"session_id": "ses_x"} (裸字段)
|
|
406
|
+
* {"user_id": "ses_x"} (字符串直给)
|
|
407
|
+
* @returns {{sessionId: string|null, accountUuid: string|null}}
|
|
408
|
+
*/
|
|
409
|
+
export function parseSessionMeta(metadata) {
|
|
410
|
+
const out = { sessionId: null, accountUuid: null };
|
|
411
|
+
if (!metadata || typeof metadata !== 'object') return out;
|
|
412
|
+
// 顶层直给的会话字段也算(调用方可能直接放 metadata.session_id)
|
|
413
|
+
out.sessionId = String(metadata.session_id || metadata.conversation_id || metadata.chat_id || '').slice(0, 64) || null;
|
|
414
|
+
const uid = metadata.user_id ?? metadata.userId ?? metadata.user;
|
|
415
|
+
let obj = null;
|
|
416
|
+
if (typeof uid === 'object') obj = uid;
|
|
417
|
+
else if (typeof uid === 'string') {
|
|
418
|
+
const s = uid.trim();
|
|
419
|
+
if (!s) return out;
|
|
420
|
+
if (s.startsWith('{')) {
|
|
421
|
+
try { obj = JSON.parse(s); } catch { out.sessionId = s.slice(0, 64); return out; }
|
|
422
|
+
} else out.sessionId = s.slice(0, 64);
|
|
423
|
+
}
|
|
424
|
+
if (obj && typeof obj === 'object') {
|
|
425
|
+
out.sessionId = String(obj.session_id || obj.sessionId || obj.conversation_id || obj.chat_id || out.sessionId || '').slice(0, 64) || out.sessionId;
|
|
426
|
+
out.accountUuid = String(obj.account_uuid || obj.accountUuid || '').slice(0, 64) || null;
|
|
427
|
+
}
|
|
428
|
+
return out;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// ── 会话粘滞:同一会话的多轮对话固定用同一个号 ──
|
|
432
|
+
// 用户选 A:同一段对话不跳号(跳号会让上下文承接出现割裂),新会话才轮转。
|
|
433
|
+
// 只粘「活着的」会话:TTL 到期即让位给轮转,避免某个冷会话长期占着一个号不放。
|
|
434
|
+
const SESSION_STICKY_TTL_MS = 30 * 60_000;
|
|
435
|
+
|
|
436
|
+
/** 取会话当前粘住的号(过期即失效) */
|
|
437
|
+
function stickyFor(sessionId) {
|
|
438
|
+
const e = sessionSticky.get(sessionId);
|
|
439
|
+
if (!e) return null;
|
|
440
|
+
if (Date.now() - e.at >= SESSION_STICKY_TTL_MS) {
|
|
441
|
+
sessionSticky.delete(sessionId);
|
|
442
|
+
return null;
|
|
443
|
+
}
|
|
444
|
+
return e.accountId;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** 会话粘住的号仍可用才粘;否则落到轮转队首,由调用方重新绑定 */
|
|
448
|
+
function touchSticky(sessionId, accountId) {
|
|
449
|
+
if (!sessionId) return;
|
|
450
|
+
// 每段对话一个新 session id,安静会话的条目只有等它自己再被查到才会过期——
|
|
451
|
+
// 长期运行的网关上单调增长。超阈值时整表清一遍过期项。
|
|
452
|
+
if (sessionSticky.size > 500) {
|
|
453
|
+
const now = Date.now();
|
|
454
|
+
for (const [k, v] of sessionSticky) if (now - (v?.at || 0) >= SESSION_STICKY_TTL_MS) sessionSticky.delete(k);
|
|
455
|
+
}
|
|
456
|
+
sessionSticky.set(sessionId, { accountId, at: Date.now() });
|
|
457
|
+
}
|
|
458
|
+
/** 从上游 JSON 信封里取业务码;字符串数字("3007")也认,取不到返回 null */
|
|
459
|
+
function businessCode(v) {
|
|
460
|
+
if (!v || typeof v !== 'object' || v.code === undefined || v.code === null) return null;
|
|
461
|
+
const n = Number(v.code);
|
|
462
|
+
return Number.isFinite(n) ? n : null;
|
|
463
|
+
}
|
|
464
|
+
// 组装与 ZCode 客户端真实流量一致的 plan 请求(镜像 R1 捕获,2026-09-29)
|
|
465
|
+
function buildPlanRequest(rawBody, { token, userId }) {
|
|
466
|
+
const ver = '3.14.3';
|
|
467
|
+
let bodyObj;
|
|
468
|
+
try { bodyObj = JSON.parse(rawBody); } catch { bodyObj = null; }
|
|
469
|
+
if (!bodyObj || typeof bodyObj !== 'object') bodyObj = { model: 'glm-5.3-flash', messages: [] };
|
|
470
|
+
const rawMeta = parseSessionMeta(bodyObj.metadata);
|
|
471
|
+
// 客户端形状:system = ZCode 系统提示词数组;首条 user 消息前插 currentDate 提醒块;
|
|
472
|
+
// metadata.user_id = 会话形状字符串
|
|
473
|
+
if (PLAN_SHAPE) {
|
|
474
|
+
bodyObj.system = PLAN_SHAPE.system;
|
|
475
|
+
const msgs = Array.isArray(bodyObj.messages) ? bodyObj.messages : [];
|
|
476
|
+
const reminderText = PLAN_SHAPE.reminderText
|
|
477
|
+
? PLAN_SHAPE.reminderText.replace(/Today's date is [^.]+\./, `Today's date is ${new Date().toISOString().slice(0, 10)}.`)
|
|
478
|
+
: null;
|
|
479
|
+
if (reminderText) {
|
|
480
|
+
const first = msgs[0];
|
|
481
|
+
const firstIsUser = first?.role === 'user';
|
|
482
|
+
const already = firstIsUser && typeof first.content === 'string' && first.content.includes('<system-reminder>');
|
|
483
|
+
if (!already) {
|
|
484
|
+
const block = { type: 'text', text: reminderText };
|
|
485
|
+
if (firstIsUser && Array.isArray(first.content)) first.content = [block, ...first.content];
|
|
486
|
+
else if (firstIsUser) first.content = [block, { type: 'text', text: String(first.content ?? '') }];
|
|
487
|
+
else msgs.unshift({ role: 'user', content: [block, { type: 'text', text: '.' }] });
|
|
488
|
+
}
|
|
489
|
+
bodyObj.messages = msgs;
|
|
490
|
+
}
|
|
491
|
+
// 会话标识:调用方传了就原样透传(会话粘滞的锚点),没传才随机生成。
|
|
492
|
+
// 注意上游只认这一个字段——网关此前每次都 new 一个新 session_id,
|
|
493
|
+
// 于是上游眼里每请求都是新会话,同一段对话的上下文连续性也丢了。
|
|
494
|
+
bodyObj.metadata = {
|
|
495
|
+
user_id: JSON.stringify({
|
|
496
|
+
account_uuid: rawMeta?.accountUuid || '',
|
|
497
|
+
session_id: rawMeta?.sessionId || 'ses_' + crypto.randomUUID().slice(0, 16),
|
|
498
|
+
}),
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
const headers = {
|
|
502
|
+
'Content-Type': 'application/json',
|
|
503
|
+
Accept: '*/*',
|
|
504
|
+
'accept-encoding': 'identity', // 网关不做压缩透传——转发链上有字符串化环节,gzip 字节会损坏
|
|
505
|
+
'User-Agent': `ZCode/${ver} ai-sdk/anthropic/3.0.81`,
|
|
506
|
+
'X-ZCode-App-Version': ver,
|
|
507
|
+
'X-ZCode-Agent': 'glm',
|
|
508
|
+
'X-Title': 'Z Code@cli',
|
|
509
|
+
'HTTP-Referer': 'https://zcode.z.ai',
|
|
510
|
+
'X-Client-Language': 'zh-CN',
|
|
511
|
+
'X-Client-Timezone': Intl.DateTimeFormat().resolvedOptions().timeZone || 'Asia/Shanghai',
|
|
512
|
+
'X-Platform': 'win32-x64',
|
|
513
|
+
'X-Os-Category': 'windows',
|
|
514
|
+
'X-Os-Version': os.release?.() || '10.0.19045',
|
|
515
|
+
'X-Release-Channel': 'production',
|
|
516
|
+
'x-zcode-session-type': 'main',
|
|
517
|
+
'x-zcode-trace-id': crypto.randomUUID(),
|
|
518
|
+
'x-request-id': crypto.randomUUID(),
|
|
519
|
+
'anthropic-version': '2023-06-01',
|
|
520
|
+
Authorization: `Bearer ${token}`,
|
|
521
|
+
};
|
|
522
|
+
return { headers, body: JSON.stringify(bodyObj) };
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
const LOOPBACK_RE = /^(::1|::ffff:127\.0\.0\.1|127\.0\.0\.1)$/;
|
|
526
|
+
function isLoopbackRemote(remote) {
|
|
527
|
+
return !remote || LOOPBACK_RE.test(String(remote));
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** 规范化远端地址(剥 IPv4-mapped IPv6 前缀),与白名单条目比对 */
|
|
531
|
+
export function remoteHost(remote) {
|
|
532
|
+
return String(remote || '').replace(/^::ffff:/i, '').trim();
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** 白名单匹配:精确 IP / 主机名,或 `*` 结尾的前缀通配(如 192.168.31.*) */
|
|
536
|
+
export function remoteAllowed(remote, allowList) {
|
|
537
|
+
const host = remoteHost(remote);
|
|
538
|
+
if (!host) return false;
|
|
539
|
+
return (Array.isArray(allowList) ? allowList : []).some((entry) => {
|
|
540
|
+
const e = String(entry || '').trim();
|
|
541
|
+
if (!e) return false;
|
|
542
|
+
if (e.endsWith('*')) {
|
|
543
|
+
// 通配要求带点段尾:防止 192.168.31.1* 这类把 .100-.199 整段一起放行的怪手。
|
|
544
|
+
// 要扩整段子网,把写法统一为 192.168.31.*(带尾句点)。
|
|
545
|
+
const prefix = e.slice(0, -1);
|
|
546
|
+
if (!prefix.endsWith('.')) return false;
|
|
547
|
+
return host.toLowerCase().startsWith(prefix.toLowerCase());
|
|
548
|
+
}
|
|
549
|
+
return host.toLowerCase() === e.toLowerCase();
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* 网关数据面入口。返回 true 表示响应已写出(含失败结论)。
|
|
555
|
+
*
|
|
556
|
+
* 访问控制:本机回环始终放行;开局域网后仅 IP 白名单内的机器可访问——
|
|
557
|
+
* zcode-free 本就是 10Router 侧免授权供应商,10Router 所在机器加白即可,不再保留虚拟 key 鉴权。
|
|
558
|
+
*/
|
|
559
|
+
export async function handleGateway(req, res) {
|
|
560
|
+
if (req.method !== 'POST') {
|
|
561
|
+
res.writeHead(405, { 'Content-Type': 'application/json' });
|
|
562
|
+
return res.end(JSON.stringify({ error: 'POST /gateway/zcode/v1/messages(Anthropic /v1/messages 形态)' }));
|
|
563
|
+
}
|
|
564
|
+
// settings 一次读齐:开关 + 局域网鉴权共用,省掉一次 settings.json 磁盘读(热路径每请求都走)
|
|
565
|
+
const settings = await loadSettings();
|
|
566
|
+
if (settings.zcodeGateway !== true) {
|
|
567
|
+
res.writeHead(503, { 'Content-Type': 'application/json' });
|
|
568
|
+
return res.end(JSON.stringify({ error: 'ZCode 免费额度网关未开启(面板 → ZCode → 网关开关)' }));
|
|
569
|
+
}
|
|
570
|
+
// 首发不带验证码(客户端真实流量多数直过),所以纯 daemon / NAS 也能用;
|
|
571
|
+
// 只有当上游索要验证码且本环境没有求解提供者时才失败(见 attempts 汇总)。
|
|
572
|
+
|
|
573
|
+
// 鉴权:本机回环免密;开局域网后仅白名单内 IP 免密直连(如 10Router 所在机器——zcode-free 本就是免授权供应商)
|
|
574
|
+
const remote = (req.socket && req.socket.remoteAddress) || '';
|
|
575
|
+
if (!isLoopbackRemote(remote)) {
|
|
576
|
+
if (settings.zcodeGatewayLan !== true) {
|
|
577
|
+
res.writeHead(403, { 'Content-Type': 'application/json' });
|
|
578
|
+
return res.end(JSON.stringify({ error: '网关未允许局域网访问(面板 → ZCode → 接口设置)' }));
|
|
579
|
+
}
|
|
580
|
+
if (!remoteAllowed(remote, settings.zcodeGatewayAllow)) {
|
|
581
|
+
res.writeHead(403, { 'Content-Type': 'application/json' });
|
|
582
|
+
return res.end(JSON.stringify({ error: `来源 ${remoteHost(remote) || '未知'} 不在网关 IP 白名单内(面板 → ZCode → 接口设置里添加)` }));
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
let rawBody;
|
|
587
|
+
try { rawBody = await readRawBody(req); } catch (e) {
|
|
588
|
+
res.writeHead(e.status || 400, { 'Content-Type': 'application/json' });
|
|
589
|
+
// 超限时请求体还没读完:先把 413 发出去,发完再断开,避免客户端继续往这灌数据
|
|
590
|
+
res.on('finish', () => req.destroy());
|
|
591
|
+
return res.end(JSON.stringify({ error: e.message }));
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
// 会话标识在 body 里(不在头里):客户端/10Router 若传了 metadata.user_id
|
|
595
|
+
// 就作为粘滞锚点;没传则 sessionId 为 null,纯轮转。
|
|
596
|
+
let sessionId = null;
|
|
597
|
+
try {
|
|
598
|
+
const parsed = JSON.parse(rawBody);
|
|
599
|
+
sessionId = parseSessionMeta(parsed?.metadata)?.sessionId;
|
|
600
|
+
} catch { /* 非 JSON 体走轮转 */ }
|
|
601
|
+
|
|
602
|
+
const queue = await rotationQueue(sessionId);
|
|
603
|
+
if (!queue.length) {
|
|
604
|
+
res.writeHead(503, { 'Content-Type': 'application/json' });
|
|
605
|
+
return res.end(JSON.stringify({ error: await unavailableReason() }));
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
stats.lastCallAt = new Date().toISOString();
|
|
609
|
+
stats.calls += 1;
|
|
610
|
+
|
|
611
|
+
const attempted = [];
|
|
612
|
+
// 客户端断开 → 取消当前上游请求。整个重试循环共用一个 controller/listener:
|
|
613
|
+
// 放在循环里每轮 new + req.on('close') 会在同一 req 上累积最多 MAX_ATTEMPTS 个监听器
|
|
614
|
+
// (MaxListenersExceededWarning + 泄漏)。
|
|
615
|
+
const clientAbort = new AbortController();
|
|
616
|
+
req.once('close', () => { if (!res.writableEnded) clientAbort.abort(); });
|
|
617
|
+
// 优雅断开(客户端 fetch abort 在上游响应前)只触发 res 'close',不触发 req 'close'
|
|
618
|
+
// ——少这一个钩子,Ctrl+C 后整个重试循环(含验证码求解、账号轮换)还在为已死的客户端空跑
|
|
619
|
+
res.once('close', () => { if (!res.writableEnded) clientAbort.abort(); });
|
|
620
|
+
// 首发不带验证码(客户端真实流量多数直过);上游 3007/403 时求解并在此后的
|
|
621
|
+
// 尝试上挂新 token(zcode-api 同策略)。provider 为 null(NAS/CLI)时首过路径依然可用。
|
|
622
|
+
let captcha = null;
|
|
623
|
+
for (let i = 0; i < Math.min(MAX_ATTEMPTS, queue.length * 2); i++) {
|
|
624
|
+
const account = queue[i % queue.length];
|
|
625
|
+
// 本轮已被打标/冷却/拉黑的号不再重打(第二圈只为验证码重试准备)
|
|
626
|
+
if (isDead(account) || isQuotaExhausted(account.id) || (cooling.get(account.id) || 0) > Date.now()) continue;
|
|
627
|
+
const label = account.name || account.uid || account.id;
|
|
628
|
+
let token;
|
|
629
|
+
try { token = claimToken(account); } catch (e) {
|
|
630
|
+
attempted.push({ account: label, ok: false, error: e.message });
|
|
631
|
+
markDead(account);
|
|
632
|
+
continue;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
let upstream;
|
|
636
|
+
try {
|
|
637
|
+
// 请求面完全镜像 ZCode 客户端真实流量(R1 捕获):全套 identity 头 + 客户端
|
|
638
|
+
// 系统提示词/提醒块/metadata 形状。验证码不预挂——服务端未风控时直过;
|
|
639
|
+
// 返回 3007/403 再求解挂上重试(zcode-api 同策略)。
|
|
640
|
+
const built = buildPlanRequest(rawBody, { token, userId: account.uid });
|
|
641
|
+
const headers = captcha
|
|
642
|
+
? { ...built.headers, 'X-Aliyun-Captcha-Verify-Param': captcha.param, 'X-Aliyun-Captcha-Verify-Region': captcha.region }
|
|
643
|
+
: built.headers;
|
|
644
|
+
upstream = await fetchJsonRace(PLAN_MESSAGES_URL, {
|
|
645
|
+
method: 'POST',
|
|
646
|
+
headers,
|
|
647
|
+
body: built.body,
|
|
648
|
+
timeoutMs: UPSTREAM_TIMEOUT_MS,
|
|
649
|
+
connectMs: UPSTREAM_CONNECT_MS,
|
|
650
|
+
signal: clientAbort.signal,
|
|
651
|
+
});
|
|
652
|
+
} catch (e) {
|
|
653
|
+
if (clientAbort.signal.aborted) return; // 客户端先断了
|
|
654
|
+
attempted.push({ account: label, ok: false, error: e.message });
|
|
655
|
+
continue;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
if (upstream.ok) {
|
|
659
|
+
// 上游会把业务错误包在 HTTP 200 + application/json 里(非 SSE)——先验形再转发,
|
|
660
|
+
// 否则客户端拿到「200 但不是 Message」的假成功(cc CLI 的 StreamNoEventsError 就是它)
|
|
661
|
+
const ct = (upstream.headers.get('content-type') || '').toLowerCase();
|
|
662
|
+
if (ct.includes('application/json')) {
|
|
663
|
+
const text = await upstream.text().catch(() => '');
|
|
664
|
+
let v;
|
|
665
|
+
try { v = JSON.parse(text); } catch { v = null; }
|
|
666
|
+
const code = businessCode(v);
|
|
667
|
+
// 上游成功信封也可能带 code(0 / 200),那不是业务错误;字符串数字("3007")同样要拦
|
|
668
|
+
if (code !== null && !BUSINESS_OK.has(code)) {
|
|
669
|
+
if (isCaptchaError(200, text)) {
|
|
670
|
+
invalidateCaptcha();
|
|
671
|
+
attempted.push({ account: label, ok: false, error: '验证码被拒(200 业务码)', captcha: true });
|
|
672
|
+
try { captcha = await ensureCaptcha(true); } catch { captcha = null; }
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
if (isAuthError(200, text)) {
|
|
676
|
+
markDead(account);
|
|
677
|
+
attempted.push({ account: label, ok: false, error: 'JWT 已失效,账号拉黑' });
|
|
678
|
+
logger.warn('ZCODE-GW', '{label} JWT 失效(200 业务码)', { label });
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
if (isExhausted(200, text)) {
|
|
682
|
+
const remaining = await probeQuota(account).catch(() => null);
|
|
683
|
+
if (remaining === null) {
|
|
684
|
+
// 探不到额度 ≠ 确认耗尽:不打标(否则一次查询失败就把号挡 10 分钟),只短冷却
|
|
685
|
+
markCooling(account.id, 2 * 60_000);
|
|
686
|
+
attempted.push({ account: label, ok: false, error: '额度被拒且额度查询失败,短冷却' });
|
|
687
|
+
} else if (remaining <= 0) {
|
|
688
|
+
// 确认 0 额度 → 打标(持久化到 state.json,重启不复轮换)
|
|
689
|
+
const entry = { remaining, at: Date.now() };
|
|
690
|
+
quotaCache.set(account.id, entry);
|
|
691
|
+
await persistMark(account.id, entry);
|
|
692
|
+
attempted.push({ account: label, ok: false, error: `额度耗尽(剩余 ${remaining}),已打标` });
|
|
693
|
+
} else {
|
|
694
|
+
// 还有额度却被拒 → 瞬时错误,短冷却继续用
|
|
695
|
+
markCooling(account.id, 2 * 60_000);
|
|
696
|
+
attempted.push({ account: label, ok: false, error: `额度接口瞬时拒绝(剩余 ${remaining})` });
|
|
697
|
+
}
|
|
698
|
+
continue;
|
|
699
|
+
}
|
|
700
|
+
logger.warn('ZCODE-GW', '{label} 上游 200 业务错误:{err} ({snippet})', { label, err: formatUpstreamError(200, text), snippet: text.slice(0, 80) });
|
|
701
|
+
res.writeHead(502, { 'Content-Type': 'application/json' });
|
|
702
|
+
res.end(text);
|
|
703
|
+
return true;
|
|
704
|
+
}
|
|
705
|
+
// 真 Message(非流式)——原样转发
|
|
706
|
+
logger.debug('ZCODE-GW', '{label} 补全成功 ({status})', { label, status: upstream.status });
|
|
707
|
+
stats.lastAccount = label;
|
|
708
|
+
recordRecentAccount(label);
|
|
709
|
+
cooling.delete(account.id);
|
|
710
|
+
resetCoolingStreak(account.id);
|
|
711
|
+
touchSticky(sessionId, account.id); // 会话粘住这个号,后续轮不再跳
|
|
712
|
+
res.writeHead(upstream.status, { 'Content-Type': ct || 'application/json', 'Cache-Control': 'no-cache' });
|
|
713
|
+
res.end(text);
|
|
714
|
+
return true;
|
|
715
|
+
}
|
|
716
|
+
logger.debug('ZCODE-GW', '{label} 补全成功 ({status})', { label, status: upstream.status });
|
|
717
|
+
stats.lastAccount = label;
|
|
718
|
+
recordRecentAccount(label);
|
|
719
|
+
cooling.delete(account.id);
|
|
720
|
+
resetCoolingStreak(account.id);
|
|
721
|
+
touchSticky(sessionId, account.id); // 会话粘住这个号,后续轮不再跳
|
|
722
|
+
// 注意:undici 已自动解压上游 gzip——body 是明文,绝不能再带 content-encoding 头
|
|
723
|
+
// (带着会让客户端对明文做 gunzip → 乱码)
|
|
724
|
+
const out = {
|
|
725
|
+
'Content-Type': upstream.headers.get('content-type') || 'application/json',
|
|
726
|
+
'Cache-Control': 'no-cache',
|
|
727
|
+
};
|
|
728
|
+
res.writeHead(upstream.status, out);
|
|
729
|
+
try {
|
|
730
|
+
const reader = upstream.body.getReader();
|
|
731
|
+
for (;;) {
|
|
732
|
+
const { done, value } = await reader.read();
|
|
733
|
+
if (done) break;
|
|
734
|
+
if (!res.write(Buffer.from(value))) {
|
|
735
|
+
await new Promise((r) => res.once('drain', r));
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
} catch (e) {
|
|
739
|
+
if (clientAbort.signal.aborted) {
|
|
740
|
+
// 客户端主动断开(点停止/换一句)就会在这里结束——属正常收尾,不是故障,降为 debug
|
|
741
|
+
logger.debug('ZCODE-GW', '流式转发中断:{err}', { err: e.message });
|
|
742
|
+
} else {
|
|
743
|
+
// 上游中途断了:直接 res.end() 是无 message_stop 的裸 EOF,客户端只会报
|
|
744
|
+
// 「流意外结束」——按 Anthropic 协议补一帧 error 事件,把原因带出去
|
|
745
|
+
logger.warn('ZCODE-GW', '上游流中断:{err}', { err: e.message });
|
|
746
|
+
try {
|
|
747
|
+
res.write(`event: error\ndata: ${JSON.stringify({ type: 'error', error: { type: 'api_error', message: `上游流中断:${e.message}` } })}\n\n`);
|
|
748
|
+
} catch { /* 客户端已不在 */ }
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
res.end();
|
|
752
|
+
return true;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
const text = await upstream.text().catch(() => '');
|
|
756
|
+
// 验证码类失败:作废 token 并强制重解(有提供者时下一次尝试带上新 token)
|
|
757
|
+
if (isCaptchaError(upstream.status, text)) {
|
|
758
|
+
invalidateCaptcha();
|
|
759
|
+
attempted.push({ account: label, ok: false, error: `验证码被拒(${upstream.status})`, captcha: true });
|
|
760
|
+
logger.warn('ZCODE-GW', '{label} 验证码被拒 ({err})', { label, err: formatUpstreamError(upstream.status, text) });
|
|
761
|
+
try { captcha = await ensureCaptcha(true); } catch (e) {
|
|
762
|
+
logger.warn('ZCODE-GW', '验证码重解失败:{err}', { err: e.message });
|
|
763
|
+
captcha = null;
|
|
764
|
+
}
|
|
765
|
+
continue;
|
|
766
|
+
}
|
|
767
|
+
if (isAuthError(upstream.status, text)) {
|
|
768
|
+
markDead(account);
|
|
769
|
+
attempted.push({ account: label, ok: false, error: 'JWT 已失效,账号拉黑(重新登录后再导入)' });
|
|
770
|
+
logger.debug('ZCODE-GW', '{label} JWT 失效,拉黑', { label });
|
|
771
|
+
continue;
|
|
772
|
+
}
|
|
773
|
+
if (isExhausted(upstream.status, text)) {
|
|
774
|
+
markCooling(account.id, 30 * 60_000);
|
|
775
|
+
attempted.push({ account: label, ok: false, error: '额度不足/无资源包' });
|
|
776
|
+
logger.debug('ZCODE-GW', '{label} 额度不足 ({status})', { label, status: upstream.status });
|
|
777
|
+
continue;
|
|
778
|
+
}
|
|
779
|
+
if (upstream.status === 429) {
|
|
780
|
+
const ms = markRateLimited(account.id);
|
|
781
|
+
const dur = formatDurationMs(ms);
|
|
782
|
+
const streak = coolingStreak.get(account.id);
|
|
783
|
+
attempted.push({ account: label, ok: false, error: `429 限流,冷却 ${dur}` });
|
|
784
|
+
logger.debug('ZCODE-GW', '{label} 429 限流,冷却 {dur}(连续第 {streak} 次)', { label, dur, streak });
|
|
785
|
+
continue;
|
|
786
|
+
}
|
|
787
|
+
// 其他错误:友好化展示 + 原样透传给客户端
|
|
788
|
+
const errorSummary = formatUpstreamError(upstream.status, text);
|
|
789
|
+
logger.warn('ZCODE-GW', '{label} 上游错误 {status} — {summary}', { label, status: upstream.status, summary: errorSummary });
|
|
790
|
+
res.writeHead(upstream.status, { 'Content-Type': 'application/json' });
|
|
791
|
+
res.end(text);
|
|
792
|
+
return true;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
const failedDetail = summarizeAttempts(attempted);
|
|
796
|
+
logger.warn('ZCODE-GW', '全部 {n} 次尝试失败{detail}(下一请求自动重试)', { n: attempted.length, detail: failedDetail ? ':' + failedDetail : '' });
|
|
797
|
+
res.writeHead(502, { 'Content-Type': 'application/json' });
|
|
798
|
+
res.end(JSON.stringify({ error: 'ZCode 网关:所有账号尝试均失败', attempts: attempted }));
|
|
799
|
+
return true;
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
// ── 面板状态 ──
|
|
803
|
+
|
|
804
|
+
export async function gatewayStatus() {
|
|
805
|
+
const enabled = await gatewayEnabled();
|
|
806
|
+
const hasCaptcha = Boolean(getZcodeCaptchaProvider());
|
|
807
|
+
const all = (await loadAccounts()).filter((a) => a.provider === 'zcode');
|
|
808
|
+
let withJwt = 0;
|
|
809
|
+
for (const a of all) { try { claimToken(a); withJwt++; } catch { /* 无 plan JWT */ } }
|
|
810
|
+
const now = Date.now();
|
|
811
|
+
const settings = await loadSettings();
|
|
812
|
+
return {
|
|
813
|
+
enabled,
|
|
814
|
+
hasCaptcha,
|
|
815
|
+
lan: settings.zcodeGatewayLan === true,
|
|
816
|
+
allow: Array.isArray(settings.zcodeGatewayAllow) ? settings.zcodeGatewayAllow : [],
|
|
817
|
+
suggestAllow: gatewayHostSuggestion(),
|
|
818
|
+
stats: {
|
|
819
|
+
lastCallAt: stats.lastCallAt,
|
|
820
|
+
calls: stats.calls,
|
|
821
|
+
lastAccount: stats.lastAccount,
|
|
822
|
+
// 只回窗口内服役过的号(面板徽章口径);recentWindowMs 让面板能对齐展示
|
|
823
|
+
recentAccounts: recentLabelsInWindow(recentEntries),
|
|
824
|
+
recentWindowMs: RECENT_WINDOW_MS,
|
|
825
|
+
},
|
|
826
|
+
exhausted: all
|
|
827
|
+
.filter((a) => isQuotaExhausted(a.id))
|
|
828
|
+
.map((a) => ({ id: a.id, name: a.name || a.uid || a.id, remaining: quotaCache.get(a.id)?.remaining ?? 0 })),
|
|
829
|
+
accounts: all.length,
|
|
830
|
+
accountsWithJwt: withJwt,
|
|
831
|
+
// 会话粘滞:当前有多少段会话各自钉在一个号上(面板「接口使用中」徽标据此说明)
|
|
832
|
+
stickySessions: sessionSticky.size,
|
|
833
|
+
// cooling 保持字符串数组(历史形状,测试与面板按名字读);冷却细节走 coolingDetail
|
|
834
|
+
cooling: all.filter((a) => !isDead(a) && (cooling.get(a.id) || 0) > now).map((a) => a.name || a.uid || a.id),
|
|
835
|
+
coolingDetail: all.filter((a) => !isDead(a) && (cooling.get(a.id) || 0) > now)
|
|
836
|
+
.map((a) => {
|
|
837
|
+
const remainMs = (cooling.get(a.id) || 0) - now;
|
|
838
|
+
return {
|
|
839
|
+
id: a.id, name: a.name || a.uid || a.id,
|
|
840
|
+
// 秒数为准:退避阶梯第一档只有 30s,按分钟四舍五入会显示成 1 分钟
|
|
841
|
+
remainMs, remainSeconds: Math.max(0, Math.ceil(remainMs / 1000)),
|
|
842
|
+
remainText: formatDurationMs(remainMs),
|
|
843
|
+
streak: coolingStreak.get(a.id) || 0,
|
|
844
|
+
};
|
|
845
|
+
}),
|
|
846
|
+
dead: all.filter((a) => isDead(a)).map((a) => a.name || a.uid || a.id),
|
|
847
|
+
endpoint: '/gateway/zcode/v1/messages',
|
|
848
|
+
note: hasCaptcha ? null : '需要桌面版 CreditDaddy(隐藏窗口验证码),纯 CLI / NAS 环境不可用',
|
|
849
|
+
};
|
|
850
|
+
}
|