dsh-zcode-startplan 0.4.5 → 1.0.2
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/CHANGELOG.md +1963 -405
- package/README.md +88 -405
- package/bin/cli.mjs +509 -450
- package/client.js +2459 -716
- package/cordis.patch.yml +4 -2
- package/index.js +144 -14
- package/lib/adapter.js +476 -422
- package/lib/anthropic-body.js +513 -469
- package/lib/assemble.js +808 -420
- package/lib/auto-claim.js +229 -0
- package/lib/captcha/minter.js +61 -7
- package/lib/distribution-keys.js +202 -0
- package/lib/errors.js +281 -125
- package/lib/fallback.js +120 -0
- package/lib/local-endpoint.js +367 -352
- package/lib/manage-routes.js +1245 -489
- package/lib/model-catalog.js +57 -0
- package/lib/openai-gateway.js +776 -0
- package/lib/plan-client.js +942 -532
- package/lib/pool.js +771 -478
- package/lib/sse.js +429 -317
- package/lib/upstream-api.js +948 -570
- package/lib/upstream.js +294 -134
- package/lib/version-probe.js +110 -0
- package/package.json +84 -80
- package/scripts/analyze-grant-intervals.mjs +171 -0
- package/scripts/check-compat-rc3.mjs +21 -11
- package/scripts/debug-claimable.mjs +130 -0
- package/scripts/probe-marketing.mjs +203 -0
- package/scripts/restart-dsh.ps1 +119 -76
- package/scripts/test-claimed-pending.mjs +152 -0
- package/scripts/verify_compat.mjs +75 -64
- package/scripts/watch-marketing.mjs +155 -0
- package/tests/anthropic-body.test.mjs +305 -0
- package/tests/assembler-contract.test.mjs +256 -0
- package/tests/auto-claim.test.mjs +318 -0
- package/tests/claim-routes.test.mjs +438 -0
- package/tests/client-panel.test.mjs +1141 -0
- package/tests/distribution-keys.test.mjs +123 -0
- package/tests/e2e.test.mjs +388 -0
- package/tests/fallback-scrub.test.mjs +105 -0
- package/tests/fixtures/quota-200.json +1 -0
- package/tests/launch-command.test.mjs +68 -0
- package/tests/login-channel.test.mjs +102 -0
- package/tests/openai-gateway.test.mjs +454 -0
- package/tests/pinned-models.test.mjs +505 -0
- package/tests/plan-client.test.mjs +582 -0
- package/tests/pool.test.mjs +319 -0
- package/tests/quota-blackhole.test.mjs +409 -0
- package/tests/restart-script.test.mjs +53 -0
- package/tests/routing-quota.test.mjs +251 -0
- package/tests/sse.test.mjs +86 -0
- package/tests/stream-translator.test.mjs +137 -0
- package/tests/support/hanging-stream.mjs +48 -0
- package/tests/support/resolve-profile-deps.mjs +52 -0
- package/tests/upstream-error-200.test.mjs +164 -0
- package/tests/upstream.test.mjs +330 -0
- package/tests/version-probe.test.mjs +172 -0
package/lib/manage-routes.js
CHANGED
|
@@ -1,489 +1,1245 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 账号池管理路由(供 Web UI 的 Client 半段调用)。
|
|
3
|
-
*
|
|
4
|
-
* ## 契约(照抄 @linxin666/dsh-client-ui-plugin-manager 的实证写法)
|
|
5
|
-
*
|
|
6
|
-
* - `inject: ['webServer']` → `ctx.webServer.register(route)` 逐条注册,返回 disposer;
|
|
7
|
-
* - route 形状:`{ kind: 'exact', path, handler(req, res) }`;
|
|
8
|
-
* - **loopback 防护**:仅允许本机回环地址访问(socket 与 Host 头都校验);
|
|
9
|
-
* - JSON 读写:请求体有上限,响应统一 `content-type: application/json`。
|
|
10
|
-
*
|
|
11
|
-
* ## 安全边界
|
|
12
|
-
*
|
|
13
|
-
* 这些路由能改账号池,因此:
|
|
14
|
-
* 1. 只监听回环(webServer 本身就只在本地)+ 请求级 loopback 判定;
|
|
15
|
-
* 2. **任何响应都不含凭据**(zcode_jwt / device_mid / token 一律不出网关);
|
|
16
|
-
* 设备授权流的 `flowSecret` 同样只留在 Host 内存(见 `/login/start`);
|
|
17
|
-
* 3. 写操作(enable/disable/remove/reset/reorder/
|
|
18
|
-
*/
|
|
19
|
-
|
|
20
|
-
import { isIP } from 'node:net'
|
|
21
|
-
import {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
if (
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
})
|
|
103
|
-
req.on('
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
/**
|
|
206
|
-
const
|
|
207
|
-
|
|
208
|
-
/**
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
const
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
writeJson(res,
|
|
319
|
-
return
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
const
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
1
|
+
/**
|
|
2
|
+
* 账号池管理路由(供 Web UI 的 Client 半段调用)。
|
|
3
|
+
*
|
|
4
|
+
* ## 契约(照抄 @linxin666/dsh-client-ui-plugin-manager 的实证写法)
|
|
5
|
+
*
|
|
6
|
+
* - `inject: ['webServer']` → `ctx.webServer.register(route)` 逐条注册,返回 disposer;
|
|
7
|
+
* - route 形状:`{ kind: 'exact', path, handler(req, res) }`;
|
|
8
|
+
* - **loopback 防护**:仅允许本机回环地址访问(socket 与 Host 头都校验);
|
|
9
|
+
* - JSON 读写:请求体有上限,响应统一 `content-type: application/json`。
|
|
10
|
+
*
|
|
11
|
+
* ## 安全边界
|
|
12
|
+
*
|
|
13
|
+
* 这些路由能改账号池,因此:
|
|
14
|
+
* 1. 只监听回环(webServer 本身就只在本地)+ 请求级 loopback 判定;
|
|
15
|
+
* 2. **任何响应都不含凭据**(zcode_jwt / device_mid / token 一律不出网关);
|
|
16
|
+
* 设备授权流的 `flowSecret` 同样只留在 Host 内存(见 `/login/start`);
|
|
17
|
+
* 3. 写操作(enable/disable/remove/reset/reorder/rename/login)逐条校验参数形状。
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { isIP } from 'node:net'
|
|
21
|
+
import {
|
|
22
|
+
startZcodeLogin,
|
|
23
|
+
pollZcodeLogin,
|
|
24
|
+
normalizeLoginChannel,
|
|
25
|
+
fetchClaimablePlans,
|
|
26
|
+
fetchClaimedPlans,
|
|
27
|
+
fetchClaimedPlanIds,
|
|
28
|
+
claimPlan,
|
|
29
|
+
reportActivation,
|
|
30
|
+
reportMarketingAction,
|
|
31
|
+
} from './upstream-api.js'
|
|
32
|
+
import { generateDeviceMid, ZCODE_APP_VERSION_FALLBACK } from './upstream.js'
|
|
33
|
+
|
|
34
|
+
/** 路由前缀(Client 半段用同一常量拼 URL)。 */
|
|
35
|
+
export const MANAGE_PREFIX = '/api/zcode-start-plan'
|
|
36
|
+
|
|
37
|
+
/** 登录流寿命(上游 `expires_at` 语义:10 分钟)。 */
|
|
38
|
+
const LOGIN_FLOW_TTL_MS = 10 * 60_000
|
|
39
|
+
/** 同时挂起的登录流上限(防 Map 无限膨胀;超限驱逐最旧)。 */
|
|
40
|
+
const LOGIN_FLOW_MAX = 8
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 判断一个 IP 字面量是否回环地址。
|
|
44
|
+
* ⚠ 不用 `node:net` 的 `isLoopbackAddress`:Node 22 没有该导出,静态 import
|
|
45
|
+
* 加载即崩(engines 允许 `^22.19 || >=24`,必须兼容);用 `isIP` 自己判。
|
|
46
|
+
*/
|
|
47
|
+
function isLoopbackAddress(value) {
|
|
48
|
+
const text = String(value ?? '').trim()
|
|
49
|
+
const kind = isIP(text)
|
|
50
|
+
if (kind === 4) return text.startsWith('127.')
|
|
51
|
+
if (kind === 6) {
|
|
52
|
+
const lower = text.toLowerCase()
|
|
53
|
+
return lower === '::1' || lower === '::ffff:127.0.0.1'
|
|
54
|
+
}
|
|
55
|
+
return false
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 简化的回环判定(socket 地址 + Host 头,镜像 plugin-manager 的栅栏思路)。 */
|
|
59
|
+
function isLoopbackRequest(req) {
|
|
60
|
+
const remote = req.socket?.remoteAddress ?? ''
|
|
61
|
+
if (!isLoopbackAddress(remote)) return false
|
|
62
|
+
const hostHeader = String(req.headers?.host ?? '')
|
|
63
|
+
const hostname = hostHeader.startsWith('[')
|
|
64
|
+
? hostHeader.slice(1, hostHeader.indexOf(']'))
|
|
65
|
+
: hostHeader.split(':')[0] ?? ''
|
|
66
|
+
if (hostname.length === 0) return true
|
|
67
|
+
if (hostname === 'localhost') return true
|
|
68
|
+
return isLoopbackAddress(hostname)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** 写一个 JSON 响应。 */
|
|
72
|
+
function writeJson(res, status, body) {
|
|
73
|
+
if (res.writableEnded || res.destroyed) return
|
|
74
|
+
const text = JSON.stringify(body)
|
|
75
|
+
res.writeHead(status, {
|
|
76
|
+
'content-type': 'application/json; charset=utf-8',
|
|
77
|
+
'referrer-policy': 'no-referrer',
|
|
78
|
+
'cache-control': 'no-store',
|
|
79
|
+
})
|
|
80
|
+
res.end(text)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** 读请求体(有上限),解析为对象;失败返回 null。 */
|
|
84
|
+
function readJsonBody(req, maxBytes = 64 * 1024) {
|
|
85
|
+
return new Promise((resolve) => {
|
|
86
|
+
const chunks = []
|
|
87
|
+
let size = 0
|
|
88
|
+
let settled = false
|
|
89
|
+
const finish = (value) => {
|
|
90
|
+
if (settled) return
|
|
91
|
+
settled = true
|
|
92
|
+
resolve(value)
|
|
93
|
+
}
|
|
94
|
+
req.on('data', (chunk) => {
|
|
95
|
+
size += chunk.length
|
|
96
|
+
if (size > maxBytes) {
|
|
97
|
+
finish(null)
|
|
98
|
+
req.destroy()
|
|
99
|
+
return
|
|
100
|
+
}
|
|
101
|
+
chunks.push(chunk)
|
|
102
|
+
})
|
|
103
|
+
req.on('end', () => {
|
|
104
|
+
const text = Buffer.concat(chunks).toString('utf8')
|
|
105
|
+
if (text.length === 0) return finish(null)
|
|
106
|
+
try {
|
|
107
|
+
const parsed = JSON.parse(text)
|
|
108
|
+
finish(parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null)
|
|
109
|
+
} catch {
|
|
110
|
+
finish(null)
|
|
111
|
+
}
|
|
112
|
+
})
|
|
113
|
+
req.on('error', () => finish(null))
|
|
114
|
+
})
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 把错误翻成字符串(不暴露堆栈给页面)。 */
|
|
118
|
+
const messageOf = (error) => (error instanceof Error ? error.message : String(error))
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* 账号的脱敏视图:绝不包含凭据字段。
|
|
122
|
+
*
|
|
123
|
+
* `riskBlocked`(1.0.2):该账号曾触发 3012 风控 —— 面板在**模型栏那一行**画一条
|
|
124
|
+
* 橙黄 chip(「⚠ 曾触发风控 · 点清除限流恢复」)。放在这里而不是只放 `/routing`:
|
|
125
|
+
* 账号卡片吃的是 `/summary`,`/routing` 只喂模型栏徽标,两处都要。
|
|
126
|
+
*/
|
|
127
|
+
function publicAccount(entry, index) {
|
|
128
|
+
return {
|
|
129
|
+
index: index + 1,
|
|
130
|
+
id: entry.id,
|
|
131
|
+
nickname: entry.nickname,
|
|
132
|
+
enabled: entry.enabled === true,
|
|
133
|
+
userIdTail: typeof entry.user_id === 'string' && entry.user_id.length > 0 ? entry.user_id.slice(-6) : null,
|
|
134
|
+
channel: entry.credential?.login_channel ?? null,
|
|
135
|
+
addedAt: typeof entry.added_at === 'number' ? entry.added_at : null,
|
|
136
|
+
modelRateLimits: entry.model_rate_limits ?? {},
|
|
137
|
+
lastError: entry.last_error ?? null,
|
|
138
|
+
riskBlocked: riskBlockedOfEntry(entry),
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* 风控痕迹判据(`/summary` 与 `/routing` 共用的唯一实现)。
|
|
144
|
+
*
|
|
145
|
+
* ⚠ 判据只有 `last_error` 文本:池子里没有结构化的风控时间戳字段,1.0.2 也**不加**
|
|
146
|
+
* 表结构(加列要迁移,而这条信息本来就是「历史痕迹」而非准入判据 ——
|
|
147
|
+
* `pool.pick` 明确不看 `last_error`,见 pool.js 的「不是选号判据」注释)。
|
|
148
|
+
*
|
|
149
|
+
* 为什么要留在面板上:3012 的惩罚是**账号级冷却**(30 分钟 → 24 小时 → 停用),
|
|
150
|
+
* 用户看不到任何提示就会反复重试,等于自己把冷却攒满。给出
|
|
151
|
+
* 「该账号曾触发风控」+「点清除限流恢复」就够了,不参与取号。
|
|
152
|
+
*
|
|
153
|
+
* 文案来源:`describeUpstreamError`(lib/errors.js,含 "unusual activity")或
|
|
154
|
+
* 3012 的裸响应 / 拆词后的中文文案。三个判据取或,任一命中即为真。
|
|
155
|
+
*/
|
|
156
|
+
export function riskBlockedOfEntry(entry) {
|
|
157
|
+
const text = typeof entry?.last_error === 'string' ? entry.last_error : ''
|
|
158
|
+
if (text.length === 0) return false
|
|
159
|
+
return /unusual\s+activity/i.test(text) || /3012/.test(text) || /风控/.test(text)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* 构造管理路由。
|
|
164
|
+
*
|
|
165
|
+
* @param {{
|
|
166
|
+
* pool: import('./pool.js').AccountPool,
|
|
167
|
+
* fetchBalance?: (credential: any) => Promise<any>,
|
|
168
|
+
* client?: { mintCaptcha?: () => Promise<{ param: string, region: string }> },
|
|
169
|
+
* probeCaptcha?: () => Promise<{ mode?: string, debugPort?: number, reachable: boolean, reason?: string }>,
|
|
170
|
+
* log?: (message: string) => void,
|
|
171
|
+
* onChanged?: () => void,
|
|
172
|
+
* onSetUnifiedVisible?: (visible: boolean) => void,
|
|
173
|
+
* onSetAccountVisible?: (accountId: string, visible: boolean) => void,
|
|
174
|
+
* getAutoClaimEnabled?: () => boolean,
|
|
175
|
+
* getAutoClaimStats?: () => Record<string, any>,
|
|
176
|
+
* onSetAutoClaim?: (enabled: boolean) => void,
|
|
177
|
+
* // 拨开自动领取后立即跑一轮(不 await);assemble 注入。
|
|
178
|
+
* runAutoClaim?: () => Promise<any>,
|
|
179
|
+
* settings?: { unifiedModelList?: boolean, hiddenModelLists?: string[], autoClaim?: boolean },
|
|
180
|
+
* }} deps
|
|
181
|
+
* @returns {Array<{ kind: 'exact', path: string, handler: (req: any, res: any) => Promise<void> }>}
|
|
182
|
+
*/
|
|
183
|
+
export function makeManageRoutes(deps) {
|
|
184
|
+
const pool = deps.pool
|
|
185
|
+
const fetchBalance = deps.fetchBalance
|
|
186
|
+
const log = deps.log ?? (() => {})
|
|
187
|
+
/**
|
|
188
|
+
* 额度占比缓存(1.0.1):accountId → `{ usedRatio, fetchedAt }`。
|
|
189
|
+
*
|
|
190
|
+
* `/routing` 必须**立即返回**(它是模型栏旁徽标的数据源,2s 轮询一次),
|
|
191
|
+
* 而上游余额拉取单账号可能等 30s —— 绝不能同步等。所以:
|
|
192
|
+
* 请求时只读缓存;缓存过期的账号在**后台**异步刷新,下一次轮询自然看到新值。
|
|
193
|
+
* 进程内状态,不落库(余额是上游现值,落库只会引入过期快照)。
|
|
194
|
+
*/
|
|
195
|
+
const balanceCache = new Map()
|
|
196
|
+
/** 单个账号缓存多久算新鲜(与面板手动刷新的心理预期一致)。 */
|
|
197
|
+
const BALANCE_TTL_MS = 60_000
|
|
198
|
+
/**
|
|
199
|
+
* 失败后的退避(审计修复 1.0.1):失败条目不参与「本轮是否过期」的判断,
|
|
200
|
+
* 否则失败一次会立刻过期、2s 轮询每轮又重试一次,把上游打爆。
|
|
201
|
+
*/
|
|
202
|
+
const BALANCE_FAIL_TTL_MS = 300_000
|
|
203
|
+
/** 缓存条数上限:账号被删除/频繁重登时不让 Map 无限长。 */
|
|
204
|
+
const BALANCE_CACHE_MAX = 64
|
|
205
|
+
/** 同一账号同时只允许一个后台拉取(2s 轮询会把上游打爆)。 */
|
|
206
|
+
const balanceInFlight = new Set()
|
|
207
|
+
|
|
208
|
+
/** 后台刷新某账号的额度占比;失败按退避记录(下个失败 TTL 再试)。 */
|
|
209
|
+
const refreshBalanceInBackground = (entry) => {
|
|
210
|
+
if (typeof fetchBalance !== 'function') return
|
|
211
|
+
if (balanceInFlight.has(entry.id)) return
|
|
212
|
+
balanceInFlight.add(entry.id)
|
|
213
|
+
Promise.resolve()
|
|
214
|
+
.then(() => fetchBalance(entry.credential))
|
|
215
|
+
.then((balance) => {
|
|
216
|
+
/**
|
|
217
|
+
* ⚠ 上游返回 `undefined` = **拿不到余额**(401/网络/非 JSON),不是「用光了」。
|
|
218
|
+
* 审计修复(1.0.1):此前它落进成功分支,被算成 `available:false` ——
|
|
219
|
+
* 与「已用尽」不可区分,徽标会把一个健康账号标成没额度。
|
|
220
|
+
* 必须与 `catch` 走同一条「未知 + 退避」路径。
|
|
221
|
+
*/
|
|
222
|
+
if (balance === undefined) throw new Error('balance unavailable')
|
|
223
|
+
/**
|
|
224
|
+
* 企业版 / 拉不到余额:占比未知(`null` = 不画进度,**不是** 100%)。
|
|
225
|
+
* 同时把「当前生效桶」的到期时间与可用性一并缓存 —— 这是面板
|
|
226
|
+
* 「额度开启」与对话「额度耗尽」不一致时唯一的对话依据。
|
|
227
|
+
*/
|
|
228
|
+
const remaining = typeof balance?.remaining === 'number' ? balance.remaining : null
|
|
229
|
+
const total = typeof balance?.total === 'number' ? balance.total : null
|
|
230
|
+
const usedRatio =
|
|
231
|
+
remaining !== null && total !== null && total > 0
|
|
232
|
+
? Math.min(1, Math.max(0, (total - remaining) / total))
|
|
233
|
+
: null
|
|
234
|
+
/**
|
|
235
|
+
* ⚠ 只认**还有余额**的桶(upstream-api 已把 active 桶排在前面,
|
|
236
|
+
* 且顶层 `expiresAt` 取的是第一个 active 桶)—— 0 余额的旧桶不能
|
|
237
|
+
* 让徽标看起来「还有额度」。企业版不下发数字,`available` 记 `null`
|
|
238
|
+
* (未知),不能记成 false。
|
|
239
|
+
*/
|
|
240
|
+
const enterprise = balance?.enterprise === true
|
|
241
|
+
const quotaAvailable = enterprise ? null : remaining !== null && remaining > 0
|
|
242
|
+
balanceCache.set(entry.id, {
|
|
243
|
+
usedRatio,
|
|
244
|
+
available: quotaAvailable,
|
|
245
|
+
expiresAt: Number.isFinite(balance?.expiresAt) ? balance.expiresAt : null,
|
|
246
|
+
fetchedAt: Date.now(),
|
|
247
|
+
})
|
|
248
|
+
/** 顺带回填到期缓存:统一选号「快过期先用」要靠它。 */
|
|
249
|
+
pool.noteExpiry?.(entry.id, balance?.expiresAt ?? 0)
|
|
250
|
+
trimBalanceCache()
|
|
251
|
+
})
|
|
252
|
+
.catch(() => {
|
|
253
|
+
/** 失败也记一笔(带退避 TTL),避免每 2s 反复重试把上游打爆。 */
|
|
254
|
+
balanceCache.set(entry.id, { usedRatio: null, available: null, failedAt: Date.now() })
|
|
255
|
+
trimBalanceCache()
|
|
256
|
+
})
|
|
257
|
+
.finally(() => {
|
|
258
|
+
balanceInFlight.delete(entry.id)
|
|
259
|
+
})
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** 丢弃已不在池中的账号缓存,并按访问顺序截断到上限。 */
|
|
263
|
+
const trimBalanceCache = () => {
|
|
264
|
+
const live = new Set((pool.list?.() ?? []).map((entry) => entry.id))
|
|
265
|
+
for (const id of balanceCache.keys()) {
|
|
266
|
+
if (!live.has(id)) balanceCache.delete(id)
|
|
267
|
+
}
|
|
268
|
+
while (balanceCache.size > BALANCE_CACHE_MAX) {
|
|
269
|
+
const oldest = balanceCache.keys().next().value
|
|
270
|
+
if (oldest === undefined) break
|
|
271
|
+
balanceCache.delete(oldest)
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** 命中且新鲜就直接给,否则触发后台刷新并给旧值。 */
|
|
276
|
+
const quotaCacheOf = (entry) => {
|
|
277
|
+
/** 防御:preview 可能指向一个刚被删掉的账号,拿不到 entry 就不刷新。 */
|
|
278
|
+
if (typeof entry?.id !== 'string' || entry.id.length === 0) return undefined
|
|
279
|
+
const cached = balanceCache.get(entry.id)
|
|
280
|
+
const ttl = cached?.failedAt !== undefined ? BALANCE_FAIL_TTL_MS : BALANCE_TTL_MS
|
|
281
|
+
const stale = cached === undefined || Date.now() - (cached.fetchedAt ?? cached.failedAt ?? 0) > ttl
|
|
282
|
+
if (stale) refreshBalanceInBackground(entry)
|
|
283
|
+
return cached
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** 取某账号的额度占比(0..1 已用;null = 未知)。 */
|
|
287
|
+
const quotaRatioOf = (entry) => quotaCacheOf(entry)?.usedRatio ?? null
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* 该账号是否**曾经**触发上游风控(3012 unusual activity)。
|
|
291
|
+
* 判据与实现见模块级 `riskBlockedOfEntry`(与 `/summary` 共用同一套,
|
|
292
|
+
* 避免两处口径漂移:徽标说「有」而卡片说「没有」)。
|
|
293
|
+
*/
|
|
294
|
+
const riskBlockedOf = riskBlockedOfEntry
|
|
295
|
+
/**
|
|
296
|
+
* 池子变更后的通知:账号栏位的路由集合随启用账号增删而变 —— 通知
|
|
297
|
+
* assemble 用 `handle.replace()` 原子换路由(内部自动广播
|
|
298
|
+
* `llm/adapters-updated`,模型选择器随即重拉目录)。
|
|
299
|
+
*/
|
|
300
|
+
const notifyChanged = () => {
|
|
301
|
+
try {
|
|
302
|
+
deps.onChanged?.()
|
|
303
|
+
} catch {
|
|
304
|
+
// 通知失败不影响管理操作本身。
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** 「统一选号」栏位开关(POST /unified-list)。 */
|
|
309
|
+
const unifiedListHandler = async (req, res) => {
|
|
310
|
+
const body = (await readJsonBody(req)) ?? {}
|
|
311
|
+
if (typeof body.visible !== 'boolean') {
|
|
312
|
+
writeJson(res, 400, { ok: false, error: '需要 visible(布尔)' })
|
|
313
|
+
return
|
|
314
|
+
}
|
|
315
|
+
try {
|
|
316
|
+
deps.onSetUnifiedVisible?.(body.visible)
|
|
317
|
+
} catch (error) {
|
|
318
|
+
writeJson(res, 500, { ok: false, error: messageOf(error) })
|
|
319
|
+
return
|
|
320
|
+
}
|
|
321
|
+
writeJson(res, 200, { ok: true, visible: body.visible })
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* 自动领取开关(POST /auto-claim {enabled})。
|
|
326
|
+
*
|
|
327
|
+
* **探测永远自动**(`/claimable` 是 GET、零 captcha);领取花掉活动资格 +
|
|
328
|
+
* 一次设备 captcha,所以做成显式开关。状态由 assemble 持久化到 settings.json,
|
|
329
|
+
* 重启后保持。
|
|
330
|
+
*/
|
|
331
|
+
const autoClaimHandler = async (req, res) => {
|
|
332
|
+
const body = (await readJsonBody(req)) ?? {}
|
|
333
|
+
if (typeof body.enabled !== 'boolean') {
|
|
334
|
+
writeJson(res, 400, { ok: false, error: '需要 enabled(布尔)' })
|
|
335
|
+
return
|
|
336
|
+
}
|
|
337
|
+
if (typeof deps.onSetAutoClaim !== 'function') {
|
|
338
|
+
writeJson(res, 501, { ok: false, error: '当前宿主不支持自动领取开关' })
|
|
339
|
+
return
|
|
340
|
+
}
|
|
341
|
+
try {
|
|
342
|
+
const enabled = deps.onSetAutoClaim(body.enabled) !== false
|
|
343
|
+
/**
|
|
344
|
+
* 拨开后**立即跑一轮**(不等 1 分钟心跳、更不等满间隔)。
|
|
345
|
+
*
|
|
346
|
+
* 旧实现只改标志位:`ctx.timer.interval` 的首轮要等一个完整周期(默认 6 小时),
|
|
347
|
+
* 用户拨开开关后 `lastRunAt` 一直是 0,看起来「自动领取无作用」。
|
|
348
|
+
* 这里同步触发一次(不 await,避免面板请求被 captcha 拖住);
|
|
349
|
+
* 结果通过 `/summary` 的 `autoClaim.lastRunAt` 反映出来。
|
|
350
|
+
*/
|
|
351
|
+
if (enabled === true && typeof deps.runAutoClaim === 'function') {
|
|
352
|
+
Promise.resolve()
|
|
353
|
+
.then(() => deps.runAutoClaim())
|
|
354
|
+
.catch((error) => log(`[manage] 自动领取首轮失败:${messageOf(error)}`))
|
|
355
|
+
}
|
|
356
|
+
writeJson(res, 200, { ok: true, enabled })
|
|
357
|
+
} catch (error) {
|
|
358
|
+
writeJson(res, 500, { ok: false, error: messageOf(error) })
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** 单个账号「模型栏位」开关(POST /model-list-visible,每卡片右侧的开关)。 */ const modelListVisibleHandler = async (req, res) => {
|
|
363
|
+
const body = (await readJsonBody(req)) ?? {}
|
|
364
|
+
const id = typeof body.id === 'string' ? body.id.trim() : ''
|
|
365
|
+
if (id.length === 0 || typeof body.visible !== 'boolean') {
|
|
366
|
+
writeJson(res, 400, { ok: false, error: '需要 id(字符串)与 visible(布尔)' })
|
|
367
|
+
return
|
|
368
|
+
}
|
|
369
|
+
if (!pool.list().some((entry) => entry.id === id)) {
|
|
370
|
+
writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
|
|
371
|
+
return
|
|
372
|
+
}
|
|
373
|
+
try {
|
|
374
|
+
deps.onSetAccountVisible?.(id, body.visible)
|
|
375
|
+
} catch (error) {
|
|
376
|
+
writeJson(res, 500, { ok: false, error: messageOf(error) })
|
|
377
|
+
return
|
|
378
|
+
}
|
|
379
|
+
writeJson(res, 200, { ok: true, id, visible: body.visible })
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// ── 登录流(两段式设备授权:Client 拿 URL → 浏览器授权 → Client 轮询)──
|
|
383
|
+
//
|
|
384
|
+
// ⚠ `flowSecret` 是本轮授权会话的密钥,**必须留在 Host 内存**(和 CLI 的
|
|
385
|
+
// `beginZcodeLogin` 一样),绝不随 /login/start 响应下发 —— 下发它等于把
|
|
386
|
+
// 「完成别人授权」的能力交给页面里任意脚本。
|
|
387
|
+
// 流程:Client 先 POST /login/start {channel} 拿 authorizeUrl(自己渲染成链接,
|
|
388
|
+
// 不用 window.open 以免被弹窗拦截),再隔 pollIntervalMs POST /login/poll
|
|
389
|
+
// {flowId} 查状态;ready 时 Host 组装凭据入池,凭据不出网关。
|
|
390
|
+
// 每条流 10 分钟过期,Map 上限 8 条,随手清理。
|
|
391
|
+
|
|
392
|
+
/** 进行中的登录流:flowId → { flow, channel, createdAt }。 */
|
|
393
|
+
const loginFlows = new Map()
|
|
394
|
+
|
|
395
|
+
/** 驱逐过期/多余的流。 */
|
|
396
|
+
function pruneLoginFlows() {
|
|
397
|
+
const now = Date.now()
|
|
398
|
+
for (const [key, value] of loginFlows) {
|
|
399
|
+
if (now - value.createdAt > LOGIN_FLOW_TTL_MS) loginFlows.delete(key)
|
|
400
|
+
}
|
|
401
|
+
while (loginFlows.size > LOGIN_FLOW_MAX) {
|
|
402
|
+
const oldest = [...loginFlows.entries()].sort((a, b) => a[1].createdAt - b[1].createdAt)[0]
|
|
403
|
+
loginFlows.delete(oldest[0])
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** 包一层 loopback 栅栏 + 异常兜底。 */
|
|
408
|
+
const guard = (handler) => async (req, res) => {
|
|
409
|
+
if (!isLoopbackRequest(req)) {
|
|
410
|
+
writeJson(res, 403, { ok: false, error: 'forbidden: loopback-only' })
|
|
411
|
+
return
|
|
412
|
+
}
|
|
413
|
+
try {
|
|
414
|
+
await handler(req, res)
|
|
415
|
+
} catch (error) {
|
|
416
|
+
log(`[manage] ${req.method} ${req.url} 失败:${messageOf(error)}`)
|
|
417
|
+
writeJson(res, 500, { ok: false, error: messageOf(error) })
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** 池子当前状态(**立即返回**账号列表;余额由客户端逐账号补拉)。 */
|
|
422
|
+
const summaryHandler = async (_req, res) => {
|
|
423
|
+
const entries = pool.list({ withCredentials: true })
|
|
424
|
+
const hidden = new Set(Array.isArray(deps.settings?.hiddenModelLists) ? deps.settings.hiddenModelLists : [])
|
|
425
|
+
/**
|
|
426
|
+
* ⚠ 余额**不再在 summary 里拉**(0.6.7)。
|
|
427
|
+
*
|
|
428
|
+
* 旧行为:`Promise.all` 并行拉全部账号的余额再返回 —— fetchBalance 每账号
|
|
429
|
+
* 超时 30s,上游慢/不可用时 summary 要等 30s+ 才吐,面板一直「加载中…」,
|
|
430
|
+
* 看起来就是「账号列表消失了」(数据其实在,只是被阻塞的请求挡住)。
|
|
431
|
+
*
|
|
432
|
+
* 新契约:summary 只读 SQLite(毫秒级)立即返回;`balance: null` 表示
|
|
433
|
+
* 「未拉取」,客户端对 null 的账号**逐个**打 `/balance?id=` 懒加载
|
|
434
|
+
* (单账号超时只拖慢自己那张卡,不影响列表出现)。
|
|
435
|
+
*/
|
|
436
|
+
const accounts = entries.map((entry, index) => {
|
|
437
|
+
const view = publicAccount(entry, index)
|
|
438
|
+
/** 账号「模型栏位」是否显示(面板每卡片右侧的开关状态)。 */
|
|
439
|
+
view.modelListVisible = !hidden.has(entry.id)
|
|
440
|
+
/** null = 未拉取(客户端懒加载),不是「失败」。 */
|
|
441
|
+
view.balance = null
|
|
442
|
+
return view
|
|
443
|
+
})
|
|
444
|
+
/**
|
|
445
|
+
* captcha 载体状态:面板据此决定「领取」前要不要先给一个
|
|
446
|
+
* 「以调试模式重启」按钮(而不是让用户去手抄 param)。
|
|
447
|
+
* `probeCaptcha` 现探、不缓存;探测失败只是意味着领取暂时不可用。
|
|
448
|
+
*/
|
|
449
|
+
let captcha
|
|
450
|
+
if (typeof deps.probeCaptcha === 'function') {
|
|
451
|
+
try {
|
|
452
|
+
captcha = await deps.probeCaptcha()
|
|
453
|
+
} catch (error) {
|
|
454
|
+
captcha = { reachable: false, reason: messageOf(error) }
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
writeJson(res, 200, {
|
|
458
|
+
ok: true,
|
|
459
|
+
accounts,
|
|
460
|
+
enabledCount: accounts.filter((account) => account.enabled).length,
|
|
461
|
+
unifiedModelList: deps.settings?.unifiedModelList !== false,
|
|
462
|
+
...(captcha !== undefined ? { captcha } : {}),
|
|
463
|
+
/** 自动领取开关(面板拨盘)与观测。探测永远可用;领取可开关。 */
|
|
464
|
+
autoClaim: {
|
|
465
|
+
enabled: deps.getAutoClaimEnabled?.() === true,
|
|
466
|
+
...(deps.getAutoClaimStats?.() ?? {}),
|
|
467
|
+
},
|
|
468
|
+
/** 统一选号顺序策略(0.7.0):面板据此显示「使用」按钮的实际作用。 */
|
|
469
|
+
selectionOrder: pool.selectionOrder ?? 'expiry',
|
|
470
|
+
/** OpenAI 网关状态(0.9.3):面板配置区直接渲染,不再单独请求。apiKey 不进 summary。 */
|
|
471
|
+
openAiGateway: {
|
|
472
|
+
running: deps.getOpenAiGateway?.() !== undefined,
|
|
473
|
+
enabledInSettings: deps.getOpenAiGatewayEnabled?.() === true,
|
|
474
|
+
baseUrl: deps.getOpenAiGateway?.()?.baseUrl ?? null,
|
|
475
|
+
port: deps.getOpenAiGateway?.()?.port ?? null,
|
|
476
|
+
},
|
|
477
|
+
fetchedAt: Date.now(),
|
|
478
|
+
})
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* **实时路由状态**(1.0.0):模型栏旁「当前使用账号」的数据源。
|
|
483
|
+
*
|
|
484
|
+
* 统一选号每请求自动换号,所以这里读的是 `pool.lastRouted()` ——
|
|
485
|
+
* 每次真实派发前由 plan-client 回填的进程内记录。
|
|
486
|
+
*
|
|
487
|
+
* **没有派发记录时不停留在「未知」**:`preview` 用与 `pick` **同一套筛选 +
|
|
488
|
+
* 排序**给出「下一条会用的账号」,让 UI 一上来就能显示具体是哪个号,
|
|
489
|
+
* 后续真实路由再覆盖它。钉定栏位则由客户端直接用所选账号,不看这里。
|
|
490
|
+
*
|
|
491
|
+
* 1.0.1 审计修复:
|
|
492
|
+
* - `?model=` 参与候选筛选(限流/忙是按模型判的,不带模型必然说谎);
|
|
493
|
+
* - 每个账号带 `quota`(准入判定依据),用来解释「面板有额度、对话却耗尽」;
|
|
494
|
+
* - `lastRouted.outcome` 区分「正在服务 / 已被判耗尽」,不再把失败账号
|
|
495
|
+
* 显示成健康账号。
|
|
496
|
+
*/
|
|
497
|
+
const routingHandler = async (req, res) => {
|
|
498
|
+
const model = new URL(req.url ?? '/', 'http://localhost').searchParams.get('model')?.trim() ?? ''
|
|
499
|
+
const routed = typeof pool.lastRouted === 'function' ? pool.lastRouted() : undefined
|
|
500
|
+
const entries = pool.list()
|
|
501
|
+
const preview = typeof pool.previewOrder === 'function' ? pool.previewOrder(model, 1) : []
|
|
502
|
+
/** 池里的 entry(无凭据)→ 缓存里的「生效桶」视图。 */
|
|
503
|
+
const quotaView = (entry, quotient) => {
|
|
504
|
+
const state = {
|
|
505
|
+
available: quotient?.available ?? null,
|
|
506
|
+
expiresAt: quotient?.expiresAt ?? null,
|
|
507
|
+
source: quotient === undefined ? 'pending' : quotient.failedAt !== undefined ? 'failed' : 'upstream',
|
|
508
|
+
}
|
|
509
|
+
/** 再叠加准入判定:1005 硬过滤 / 缓存桶过期都会给出否决位。 */
|
|
510
|
+
const admission = typeof pool.quotaState === 'function'
|
|
511
|
+
? pool.quotaState(entry.id, model.length > 0 ? model : routed?.modelId ?? '', {
|
|
512
|
+
/** 面板口径必须传进去:available 是 quotaState 里唯一的事实来源。 */
|
|
513
|
+
available: quotient?.available ?? null,
|
|
514
|
+
expiresAt: state.expiresAt,
|
|
515
|
+
})
|
|
516
|
+
: { available: state.available, usable: state.available, limited: false, expired: false, reason: null }
|
|
517
|
+
/**
|
|
518
|
+
* ⚠ 合并方向固定:`quotaState` 是**唯一**的合并点。
|
|
519
|
+
* `available`(面板口径)原样透传 —— `true`/`false`/`null`(未知),
|
|
520
|
+
* 准入否决**不洗掉它**:`limited=true && available=true` 就是
|
|
521
|
+
* 「面板显示有额度、对话却已耗尽」的显式冲突组合,UI 靠它出警告;
|
|
522
|
+
* 综合结论看 `usable`(准入已拒 = false;未知 = null)。
|
|
523
|
+
*/
|
|
524
|
+
return {
|
|
525
|
+
available: admission.available,
|
|
526
|
+
usable: admission.usable,
|
|
527
|
+
expiresAt: state.expiresAt,
|
|
528
|
+
source: state.source,
|
|
529
|
+
limited: admission.limited === true,
|
|
530
|
+
expired: admission.expired === true,
|
|
531
|
+
reason: admission.reason ?? null,
|
|
532
|
+
/**
|
|
533
|
+
* 风控痕迹(1.0.2):该账号曾触发 3012 unusual activity。
|
|
534
|
+
* **不是**准入判据,只供模型栏徽标画 ⚠ 与提示「点清除限流恢复」;
|
|
535
|
+
* 3012 的惩罚是账号级冷却,用户需要看见它才不会反复重试把冷却攒满。
|
|
536
|
+
*/
|
|
537
|
+
riskBlocked: riskBlockedOf(entry),
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
writeJson(res, 200, {
|
|
541
|
+
ok: true,
|
|
542
|
+
/** 最近一次**真实派发**的账号;null = 本进程还没发过请求。 */
|
|
543
|
+
lastRouted: routed ?? null,
|
|
544
|
+
/** 尚未派发时预测的下一条账号(与 pick 同筛选同排序的第一个,只读)。 */
|
|
545
|
+
preview: preview[0] === undefined
|
|
546
|
+
? null
|
|
547
|
+
: {
|
|
548
|
+
accountId: preview[0].accountId,
|
|
549
|
+
nickname: preview[0].nickname,
|
|
550
|
+
/** 同 `accounts[].usedRatio`;取整表里的 entry 才能拉额度。 */
|
|
551
|
+
usedRatio: quotaRatioOf(entries.find((item) => item.id === preview[0].accountId) ?? {}),
|
|
552
|
+
model: model.length > 0 ? model : null,
|
|
553
|
+
},
|
|
554
|
+
/**
|
|
555
|
+
* 账号 id → 昵称 + 额度占比的最小映射:钉定栏位要靠它把
|
|
556
|
+
* `zcode-start-plan-acct-<id>` 换成「账号昵称」;圆环要靠 `usedRatio`
|
|
557
|
+
* 画占用弧。**不含任何凭据**。
|
|
558
|
+
*
|
|
559
|
+
* `usedRatio`:0..1 = 已用占比(圆环顺时针占比),null = 未知/企业版。
|
|
560
|
+
* `quota.available`:面板口径(上游余额接口的**生效**桶是否还有余额)。
|
|
561
|
+
* `quota.limited`:对话口径(是否已被上游判 1005/1113 并硬过滤)。
|
|
562
|
+
* 两者同时为真 = 当前这一轮「显示有额度但实际用不了」。
|
|
563
|
+
* `quota.riskBlocked`(1.0.2):该账号曾触发 3012 风控 —— 面板据此在模型栏
|
|
564
|
+
* 徽标上加 ⚠ 并提示「点清除限流恢复」;**不参与取号**。
|
|
565
|
+
*/
|
|
566
|
+
accounts: entries.map((entry) => ({
|
|
567
|
+
accountId: entry.id,
|
|
568
|
+
nickname: entry.nickname,
|
|
569
|
+
usedRatio: quotaRatioOf(entry),
|
|
570
|
+
quota: quotaView(entry, quotaCacheOf(entry)),
|
|
571
|
+
})),
|
|
572
|
+
selectionOrder: pool.selectionOrder ?? 'expiry',
|
|
573
|
+
enabledCount: entries.filter((entry) => entry.enabled === true).length,
|
|
574
|
+
totalCount: entries.length,
|
|
575
|
+
/** 请求里带的模型:客户端未带时回落到最近一次实发模型,便于排查。 */
|
|
576
|
+
model: model.length > 0 ? model : routed?.modelId ?? null,
|
|
577
|
+
fetchedAt: Date.now(),
|
|
578
|
+
})
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/** 单账号余额(点「刷新」时用,避免整表全拉)。 */
|
|
582
|
+
const balanceHandler = async (req, res) => {
|
|
583
|
+
const id = new URL(req.url ?? '/', 'http://localhost').searchParams.get('id')?.trim() ?? ''
|
|
584
|
+
const entry = id.length > 0 ? pool.list({ withCredentials: true }).find((item) => item.id === id) : undefined
|
|
585
|
+
if (entry === undefined) {
|
|
586
|
+
writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
|
|
587
|
+
return
|
|
588
|
+
}
|
|
589
|
+
if (typeof fetchBalance !== 'function') {
|
|
590
|
+
writeJson(res, 200, { ok: true, balance: null })
|
|
591
|
+
return
|
|
592
|
+
}
|
|
593
|
+
try {
|
|
594
|
+
const balance = await fetchBalance(entry.credential)
|
|
595
|
+
/**
|
|
596
|
+
* 0.7.0:拉取成功即回填池子的到期缓存 —— 统一选号按「快过期先用」
|
|
597
|
+
* 排序时消费这个值(pool.noteExpiry)。enterprise / 全用光(无 expiresAt)
|
|
598
|
+
* 都回填 0 = 移除缓存(该账号按无穷大排后)。
|
|
599
|
+
*/
|
|
600
|
+
pool.noteExpiry?.(id, balance?.expiresAt ?? 0)
|
|
601
|
+
/**
|
|
602
|
+
* 面板手动刷新 = 用户眼里的「最新事实」,徽标缓存必须同步,
|
|
603
|
+
* 否则会出现「面板刷新后有余量、徽标还显示耗尽」的对立状态。
|
|
604
|
+
*/
|
|
605
|
+
if (balance !== undefined && balance.enterprise !== true) {
|
|
606
|
+
const remaining = typeof balance.remaining === 'number' ? balance.remaining : null
|
|
607
|
+
const total = typeof balance.total === 'number' ? balance.total : null
|
|
608
|
+
balanceCache.set(id, {
|
|
609
|
+
usedRatio:
|
|
610
|
+
remaining !== null && total !== null && total > 0
|
|
611
|
+
? Math.min(1, Math.max(0, (total - remaining) / total))
|
|
612
|
+
: null,
|
|
613
|
+
available: remaining !== null && remaining > 0,
|
|
614
|
+
expiresAt: Number.isFinite(balance.expiresAt) ? balance.expiresAt : null,
|
|
615
|
+
fetchedAt: Date.now(),
|
|
616
|
+
})
|
|
617
|
+
trimBalanceCache()
|
|
618
|
+
}
|
|
619
|
+
writeJson(res, 200, {
|
|
620
|
+
ok: true,
|
|
621
|
+
balance: balance === undefined
|
|
622
|
+
? null
|
|
623
|
+
: balance.enterprise === true
|
|
624
|
+
? { enterprise: true, remaining: null, total: null, planName: null }
|
|
625
|
+
: {
|
|
626
|
+
enterprise: false,
|
|
627
|
+
remaining: typeof balance.remaining === 'number' ? balance.remaining : null,
|
|
628
|
+
total: typeof balance.total === 'number' ? balance.total : null,
|
|
629
|
+
planName: balance.planName ?? null,
|
|
630
|
+
/** 汇总条沿用「最早到期」(兼容旧客户端)。 */
|
|
631
|
+
...(Number.isFinite(balance.expiresAt) ? { expiresAt: balance.expiresAt } : {}),
|
|
632
|
+
/**
|
|
633
|
+
* ⚠ 逐桶下发(0.6.8):每个桶带自己的 remaining/total/expiresAt,
|
|
634
|
+
* 面板按桶画条 —— 多个额度桶到期时间不同,汇总条只会显示最早的
|
|
635
|
+
* 那个,其余桶的到期时间被吞掉(用户实测反馈)。
|
|
636
|
+
*/
|
|
637
|
+
...(Array.isArray(balance.buckets) && balance.buckets.length > 0
|
|
638
|
+
? {
|
|
639
|
+
buckets: balance.buckets.map((bucket) => ({
|
|
640
|
+
planId: bucket.planId ?? null,
|
|
641
|
+
showName: bucket.showName ?? null,
|
|
642
|
+
remaining:
|
|
643
|
+
typeof bucket.availableUnits === 'number'
|
|
644
|
+
? bucket.availableUnits
|
|
645
|
+
: typeof bucket.remainingUnits === 'number'
|
|
646
|
+
? bucket.remainingUnits
|
|
647
|
+
: null,
|
|
648
|
+
total: typeof bucket.totalUnits === 'number' ? bucket.totalUnits : null,
|
|
649
|
+
...(Number.isFinite(bucket.expiresAt) && bucket.expiresAt > 0
|
|
650
|
+
? { expiresAt: bucket.expiresAt }
|
|
651
|
+
: {}),
|
|
652
|
+
})),
|
|
653
|
+
}
|
|
654
|
+
: {}),
|
|
655
|
+
/** 未生效的计划额度(如 23 点启用的领取包);无则不下发该键。 */
|
|
656
|
+
...(Array.isArray(balance.pending) && balance.pending.length > 0
|
|
657
|
+
? { pending: balance.pending }
|
|
658
|
+
: {}),
|
|
659
|
+
},
|
|
660
|
+
})
|
|
661
|
+
} catch (error) {
|
|
662
|
+
writeJson(res, 200, { ok: true, balance: null, error: messageOf(error) })
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/** 启用 / 停用。 */
|
|
667
|
+
const setEnabledHandler = async (req, res) => {
|
|
668
|
+
const body = (await readJsonBody(req)) ?? {}
|
|
669
|
+
const id = typeof body.id === 'string' ? body.id.trim() : ''
|
|
670
|
+
const enabled = body.enabled
|
|
671
|
+
if (id.length === 0 || typeof enabled !== 'boolean') {
|
|
672
|
+
writeJson(res, 400, { ok: false, error: '需要 id(字符串)与 enabled(布尔)' })
|
|
673
|
+
return
|
|
674
|
+
}
|
|
675
|
+
pool.setEnabled(id, enabled)
|
|
676
|
+
notifyChanged()
|
|
677
|
+
writeJson(res, 200, { ok: true, id, enabled })
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/** 删除。 */
|
|
681
|
+
const removeHandler = async (req, res) => {
|
|
682
|
+
const body = (await readJsonBody(req)) ?? {}
|
|
683
|
+
const id = typeof body.id === 'string' ? body.id.trim() : ''
|
|
684
|
+
if (id.length === 0) {
|
|
685
|
+
writeJson(res, 400, { ok: false, error: '需要 id(字符串)' })
|
|
686
|
+
return
|
|
687
|
+
}
|
|
688
|
+
const removed = pool.remove(id)
|
|
689
|
+
if (!removed) {
|
|
690
|
+
writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
|
|
691
|
+
return
|
|
692
|
+
}
|
|
693
|
+
/** 审计修复:账号删除后额度缓存必须同步丢弃(否则 Map 只增不减)。 */
|
|
694
|
+
balanceCache.delete(id)
|
|
695
|
+
notifyChanged()
|
|
696
|
+
writeJson(res, 200, { ok: true, id })
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/**
|
|
700
|
+
* 清限流标记(当日额度误标时的自救)。
|
|
701
|
+
*
|
|
702
|
+
* 面板只有在 `modelRateLimits` 里有未过期标记时才显示 × 按钮(client.js
|
|
703
|
+
* AccountCard),所以「清了几条、清的是哪个模型」必须回给面板 —— 旧实现只回
|
|
704
|
+
* `removed`,用户点完看不到任何具体信息,无法判断是不是点错了账号。
|
|
705
|
+
*
|
|
706
|
+
* ⚠ 同时清掉 `last_error`(1.0.2):限流/风控之后宿主会把可读错误写进
|
|
707
|
+
* `last_error`,卡片上的红字就从那里渲染。标记清了、红字还挂着 = 用户以为
|
|
708
|
+
* 「点了没生效」。所以先取出旧值回报(`lastErrorBefore`,让用户知道当初为什么
|
|
709
|
+
* 被限),再把它清空。
|
|
710
|
+
*
|
|
711
|
+
* @returns 200 `{ ok, id, removed, clearedModels, lastErrorBefore }`
|
|
712
|
+
*/
|
|
713
|
+
const resetLimitsHandler = async (req, res) => {
|
|
714
|
+
const body = (await readJsonBody(req)) ?? {}
|
|
715
|
+
const id = typeof body.id === 'string' ? body.id.trim() : ''
|
|
716
|
+
const model = typeof body.model === 'string' ? body.model.trim() : ''
|
|
717
|
+
if (id.length === 0) {
|
|
718
|
+
writeJson(res, 400, { ok: false, error: '需要 id(字符串)' })
|
|
719
|
+
return
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* 清除前的快照:`removed` 与 `clearedModels` 都从它算 ——
|
|
723
|
+
* `pool.clearModelRateLimits` 只回一个数字,回不了「清了哪些模型」。
|
|
724
|
+
*/
|
|
725
|
+
const before = pool.get?.(id) ?? pool.list().find((entry) => entry.id === id)
|
|
726
|
+
const limitsBefore = { ...(before?.model_rate_limits ?? {}) }
|
|
727
|
+
const targets = model.length > 0 ? [model] : Object.keys(limitsBefore)
|
|
728
|
+
/** 只有**真的在表里**的模型才算被清掉(切模型后再点全清不该报假数字)。 */
|
|
729
|
+
const clearedModels = targets.filter((modelId) => Object.prototype.hasOwnProperty.call(limitsBefore, modelId))
|
|
730
|
+
const lastErrorBefore = typeof before?.last_error === 'string' && before.last_error.length > 0
|
|
731
|
+
? before.last_error
|
|
732
|
+
: null
|
|
733
|
+
const removed = pool.clearModelRateLimits(id, model.length > 0 ? [model] : undefined)
|
|
734
|
+
/**
|
|
735
|
+
* 清标记同时清错误文案:否则卡片上仍显示「额度已用尽」之类的旧原因,
|
|
736
|
+
* 用户只会认为清除按钮坏了。`noteError` 缺省(老池子实例)时静默跳过。
|
|
737
|
+
*/
|
|
738
|
+
if (removed > 0 || lastErrorBefore !== null) {
|
|
739
|
+
try {
|
|
740
|
+
pool.noteError?.(id, '')
|
|
741
|
+
} catch (error) {
|
|
742
|
+
log(`[manage] 清除 last_error 失败(${id}):${messageOf(error)}`)
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
if (removed > 0) log(`[manage] 清除限流标记:${before?.nickname ?? id} × ${clearedModels.join(', ')}`)
|
|
746
|
+
notifyChanged()
|
|
747
|
+
writeJson(res, 200, {
|
|
748
|
+
ok: true,
|
|
749
|
+
id,
|
|
750
|
+
removed,
|
|
751
|
+
/** 具体清了哪些模型(面板据此提示「清了 N 条 · 哪个模型」)。 */
|
|
752
|
+
clearedModels,
|
|
753
|
+
/**
|
|
754
|
+
* 清除前的 last_error(null = 本来就没有)。给面板展示「当初为什么被限」,
|
|
755
|
+
* 用户点完 × 之后仍能看到原因,而不是信息一起被抹掉。
|
|
756
|
+
*/
|
|
757
|
+
lastErrorBefore,
|
|
758
|
+
})
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/** 重排(顺序即选号优先级)。 */
|
|
762
|
+
const reorderHandler = async (req, res) => {
|
|
763
|
+
const body = (await readJsonBody(req)) ?? {}
|
|
764
|
+
const ids = Array.isArray(body.ids) ? body.ids : []
|
|
765
|
+
if (!ids.every((id) => typeof id === 'string' && id.trim().length > 0)) {
|
|
766
|
+
writeJson(res, 400, { ok: false, error: '需要 ids(非空字符串数组,且为当前集合的排列)' })
|
|
767
|
+
return
|
|
768
|
+
}
|
|
769
|
+
pool.reorder(ids)
|
|
770
|
+
notifyChanged()
|
|
771
|
+
writeJson(res, 200, { ok: true, ids })
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/** 重命名备注。 */
|
|
775
|
+
const renameHandler = async (req, res) => {
|
|
776
|
+
const body = (await readJsonBody(req)) ?? {}
|
|
777
|
+
const id = typeof body.id === 'string' ? body.id.trim() : ''
|
|
778
|
+
const nickname = typeof body.nickname === 'string' ? body.nickname.trim() : ''
|
|
779
|
+
if (id.length === 0 || nickname.length === 0) {
|
|
780
|
+
writeJson(res, 400, { ok: false, error: '需要 id 与 nickname(均非空)' })
|
|
781
|
+
return
|
|
782
|
+
}
|
|
783
|
+
const entry = pool.get?.(id) ?? pool.list({ withCredentials: true }).find((item) => item.id === id)
|
|
784
|
+
if (entry === undefined) {
|
|
785
|
+
writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
|
|
786
|
+
return
|
|
787
|
+
}
|
|
788
|
+
pool.patchAccount(id, { nickname })
|
|
789
|
+
notifyChanged()
|
|
790
|
+
writeJson(res, 200, { ok: true, id, nickname })
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/**
|
|
794
|
+
* ⚠ 0.9.7 移除 `/use`(置顶)路由:0.7.0 起 `selectionOrder: 'expiry'` 为默认,
|
|
795
|
+
* 取号按快过期先后,置顶不再决定取号;client.js 自 0.7.0 起就没有「使用」按钮,
|
|
796
|
+
* 该路由已无任何调用方。改顺序统一走 `/reorder`。
|
|
797
|
+
*/
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* 领取赠送额度(一次性 captcha 的真正入口)。
|
|
801
|
+
*
|
|
802
|
+
* 两条路由(对应 `lib/upstream-api.js` 的两个上游调用):
|
|
803
|
+
* - `GET /claimable?id=` → 查**官方活动发现端点**(`/api/v1/marketing/touch`,
|
|
804
|
+
* 0.6.0 起;旧的 `/billing/preview` 实证恒空),返回投放按钮里的 plan_id 列表
|
|
805
|
+
* (零 captcha —— captcha 只在真正 claim 时才烧);
|
|
806
|
+
* - `POST /claim {id, planId, campaignId?}` → 直接领取;**每个 plan 重新 mint captcha**
|
|
807
|
+
* (param 一次性,复用必 3007)。`campaignId` 供领取成功后的 confirm 回执。
|
|
808
|
+
*
|
|
809
|
+
* ⚠ 为什么 captcha 走 `deps.client.mintCaptcha`(ZcodePlanClient 的串行队列):
|
|
810
|
+
* 面板点击与推理链路可能同时要 captcha,产出是**设备级**的,两条链路各自
|
|
811
|
+
* 起一份会互相踩 CDP 页面。复用同一个实例 = 同一把闸门。
|
|
812
|
+
*/
|
|
813
|
+
const claimableHandler = async (req, res) => {
|
|
814
|
+
const id = new URL(req.url ?? '/', 'http://localhost').searchParams.get('id')?.trim() ?? ''
|
|
815
|
+
const entry = id.length > 0 ? pool.list({ withCredentials: true }).find((item) => item.id === id) : undefined
|
|
816
|
+
if (entry === undefined) {
|
|
817
|
+
writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
|
|
818
|
+
return
|
|
819
|
+
}
|
|
820
|
+
if (typeof fetchClaimablePlans !== 'function') {
|
|
821
|
+
writeJson(res, 200, { ok: true, plans: [] })
|
|
822
|
+
return
|
|
823
|
+
}
|
|
824
|
+
try {
|
|
825
|
+
/** 活动发现走 marketing/touch(官方同款);补活跃上报无害且与官方启动行为一致。 */
|
|
826
|
+
await reportActivation?.(entry.credential)
|
|
827
|
+
/**
|
|
828
|
+
* ⚠ 服务端行为(2026-10-31 实测):**领取成功后 marketing/touch 不再给该账号
|
|
829
|
+
* 投放**(deliveries 变空)⇒ 只看投放,已领账号显示「无可领」、未领账号显示
|
|
830
|
+
* 「可领」——用户预期一视同仁,看到的却是参差不齐。
|
|
831
|
+
*
|
|
832
|
+
* 对策:合并 `billing/balance` 的领取记录(`data.plans[]`,含 entitlements
|
|
833
|
+
* 元数据)。无投放但记录里有的活动照样下发,标 `claimed: true` 并带上
|
|
834
|
+
* 名称/单位/额度/生效期;面板据此显示「已领取」或「已领取 · 待生效」。
|
|
835
|
+
*
|
|
836
|
+
* ⚠ 回填仍走 `^zcode-v3-start-plan-` 前缀白名单(恢复 1.0.x 语义):
|
|
837
|
+
* `data.plans[]` 还包含**订阅类 plan**(非活动),整表回填会把它们拉进
|
|
838
|
+
* 活动面板造成误读;前缀是实测的活动 id 形态(1103 / 1106-wk 两代一致)。
|
|
839
|
+
* 「待生效」由 `fetchClaimedPlans` 按 `effective_at > server_time` 判定。
|
|
840
|
+
*/
|
|
841
|
+
const [plans, claimed] = await Promise.all([
|
|
842
|
+
fetchClaimablePlans(entry.credential),
|
|
843
|
+
typeof fetchClaimedPlans === 'function'
|
|
844
|
+
? fetchClaimedPlans(entry.credential)
|
|
845
|
+
: typeof fetchClaimedPlanIds === 'function'
|
|
846
|
+
? fetchClaimedPlanIds(entry.credential).then((ids) => new Map([...ids].map((planId) => [planId, { plan_id: planId, claimed: true, pending: false }])))
|
|
847
|
+
: Promise.resolve(new Map()),
|
|
848
|
+
])
|
|
849
|
+
const merged = new Map()
|
|
850
|
+
for (const plan of plans) {
|
|
851
|
+
const record = claimed.get(plan.planId)
|
|
852
|
+
merged.set(plan.planId, {
|
|
853
|
+
...plan,
|
|
854
|
+
claimed: record !== undefined,
|
|
855
|
+
...(record?.pending === true ? { pending: true } : {}),
|
|
856
|
+
})
|
|
857
|
+
}
|
|
858
|
+
for (const [planId, record] of claimed) {
|
|
859
|
+
if (merged.has(planId)) continue
|
|
860
|
+
/** 只有活动前缀的记录才回填(plans[] 里的订阅类 plan 不是活动)。 */
|
|
861
|
+
if (!/^zcode-v3-start-plan-/.test(planId)) continue
|
|
862
|
+
merged.set(planId, {
|
|
863
|
+
planId,
|
|
864
|
+
priority: typeof record.priority === 'number' ? record.priority : 0,
|
|
865
|
+
claimed: true,
|
|
866
|
+
...(record.name !== undefined ? { name: record.name } : {}),
|
|
867
|
+
...(record.unitType !== undefined ? { unitType: record.unitType } : {}),
|
|
868
|
+
...(record.grantUnits !== undefined ? { grantUnits: record.grantUnits } : {}),
|
|
869
|
+
...(record.effectiveAt !== undefined ? { effectiveAt: record.effectiveAt } : {}),
|
|
870
|
+
...(record.expiresAt !== undefined ? { expiresAt: record.expiresAt } : {}),
|
|
871
|
+
...(record.pending === true ? { pending: true } : {}),
|
|
872
|
+
})
|
|
873
|
+
}
|
|
874
|
+
const list = [...merged.values()].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))
|
|
875
|
+
/**
|
|
876
|
+
* `sources` 给面板三种状态用(否则「探测失败」与「确实没有」不可区分):
|
|
877
|
+
* - `campaign` 投放源条数、`records` 领取记录条数(含 pending);
|
|
878
|
+
* - 两者皆 0 且 `ok:true` = 服务端此刻确实没有活动,不是故障。
|
|
879
|
+
*/
|
|
880
|
+
writeJson(res, 200, {
|
|
881
|
+
ok: true,
|
|
882
|
+
plans: list,
|
|
883
|
+
sources: { campaign: plans.length, records: claimed.size },
|
|
884
|
+
})
|
|
885
|
+
} catch (error) {
|
|
886
|
+
writeJson(res, 200, { ok: false, plans: [], error: messageOf(error) })
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
/**
|
|
891
|
+
* 领取赠送额度。
|
|
892
|
+
*
|
|
893
|
+
* ## ⚠ 设计变更(2026-10-28,来自官方客户端日志实证)
|
|
894
|
+
*
|
|
895
|
+
* 早先的实现是「先查 `preview` 拿列表 → 有才领」。日志分析证明这条路是错的:
|
|
896
|
+
*
|
|
897
|
+
* | 客户端行为 | 实测 |
|
|
898
|
+
* |---|---|
|
|
899
|
+
* | `getManualClaimPlanPreviews`(即 `/billing/preview`) | **全天 0 次调用** |
|
|
900
|
+
* | `claimManualPlan`(即 `/billing/claim`) | 点击即调,不看 preview |
|
|
901
|
+
*
|
|
902
|
+
* 官方客户端**从不预判有没有活动**:它直接发 claim,用服务端返回的
|
|
903
|
+
* `code`/`msg` 告诉用户结果。我们的 `preview` 恒空,导致面板永远显示
|
|
904
|
+
* 「暂无可领取」、按钮根本不出现 —— 而实际活动是存在的(用户已领到过)。
|
|
905
|
+
*
|
|
906
|
+
* 故改为:**`planId` 必填,直接 claim,忠实回传业务码**。
|
|
907
|
+
* 让「有没有名额」由服务端裁决(`1003` 已领过 / `1005` 领完 / `0` 成功),
|
|
908
|
+
* 而不是由我们猜。`/claimable` 路由保留(preview 语义待进一步求证),
|
|
909
|
+
* 但**不再作为领取的前置条件**。
|
|
910
|
+
*/
|
|
911
|
+
const claimHandler = async (req, res) => {
|
|
912
|
+
const body = (await readJsonBody(req)) ?? {}
|
|
913
|
+
const id = typeof body.id === 'string' ? body.id.trim() : ''
|
|
914
|
+
const planId = typeof body.planId === 'string' ? body.planId.trim() : ''
|
|
915
|
+
/** 可选:领取成功后的 marketing/touch/action confirm 回执需要它(0.9.7)。 */
|
|
916
|
+
const campaignId = typeof body.campaignId === 'string' ? body.campaignId.trim() : ''
|
|
917
|
+
if (id.length === 0) {
|
|
918
|
+
writeJson(res, 400, { ok: false, error: '需要 id(字符串)' })
|
|
919
|
+
return
|
|
920
|
+
}
|
|
921
|
+
if (planId.length === 0) {
|
|
922
|
+
writeJson(res, 400, { ok: false, error: '需要 planId(字符串):用 /claimable 探测,或从活动页抄' })
|
|
923
|
+
return
|
|
924
|
+
}
|
|
925
|
+
const entry = pool.list({ withCredentials: true }).find((item) => item.id === id)
|
|
926
|
+
if (entry === undefined) {
|
|
927
|
+
writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
|
|
928
|
+
return
|
|
929
|
+
}
|
|
930
|
+
if (typeof claimPlan !== 'function' || typeof deps.client?.mintCaptcha !== 'function') {
|
|
931
|
+
writeJson(res, 500, { ok: false, error: '领取链路未就绪(captcha 载体或上游客户端不可用)' })
|
|
932
|
+
return
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
/**
|
|
936
|
+
* captcha 产出**重试一次**。
|
|
937
|
+
*
|
|
938
|
+
* 官方客户端日志实证(2026-10-28 21:00):一次点击里
|
|
939
|
+
* `send_preflight outcome=error` → 6 秒后 `outcome=success` → 才发 claim。
|
|
940
|
+
* 失败原因是阿里云 CDN 连续 4 次 `resource.failed`(几十到两百毫秒级抖动)。
|
|
941
|
+
* 也就是说「按两次才领到」的体验在官方客户端同样存在,它靠**原地重试**消化。
|
|
942
|
+
*
|
|
943
|
+
* ⚠ 只重试一次:mint 有独立退避闸门,无限重试会烧设备信誉。
|
|
944
|
+
*/
|
|
945
|
+
let captcha
|
|
946
|
+
let attempts = 0
|
|
947
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
948
|
+
attempts += 1
|
|
949
|
+
try {
|
|
950
|
+
captcha = await deps.client.mintCaptcha()
|
|
951
|
+
break
|
|
952
|
+
} catch (error) {
|
|
953
|
+
if (attempt === 1) {
|
|
954
|
+
writeJson(res, 200, {
|
|
955
|
+
ok: false,
|
|
956
|
+
results: [{ planId, ok: false, error: `captcha 产出失败(尝试 ${attempts} 次):${messageOf(error)}` }],
|
|
957
|
+
})
|
|
958
|
+
return
|
|
959
|
+
}
|
|
960
|
+
await new Promise((resolve) => setTimeout(resolve, 800))
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
const outcome = await claimPlan(entry.credential, planId, captcha)
|
|
965
|
+
/**
|
|
966
|
+
* confirm 回执纪律(docs/upstream-protocol.md):**只在 `0`/`1003` 后发**。
|
|
967
|
+
* 成功不发 = 服务端重复投放(每轮白烧 captcha);失败发 = 叫服务端别再投了
|
|
968
|
+
* (白丢机会)。campaignId 来自面板探测结果(/claimable 下发)。
|
|
969
|
+
*/
|
|
970
|
+
if (outcome.ok === true || outcome.code === 0 || outcome.code === 1003) {
|
|
971
|
+
await reportMarketingAction(entry.credential, campaignId, 'confirm')
|
|
972
|
+
}
|
|
973
|
+
/**
|
|
974
|
+
* 忠实回传业务码,`1004` 给出**克制**的解释。
|
|
975
|
+
*
|
|
976
|
+
* ⚠ 2026-11-06/07 的对照实验未能把 `1004` 归因到「设备配额已用」:
|
|
977
|
+
* - 同账号(Ye Send)本机 claim 得 1004,但几小时后在另一环境领取成功 ——
|
|
978
|
+
* 「换设备导致」与「投放延迟到达」在时间上混杂,无法归因;
|
|
979
|
+
* - 控制变量(同账号同 Chrome 只换 device_mid)三种 device_mid 的
|
|
980
|
+
* `deliveries` 全为空,无资格差可观察;
|
|
981
|
+
* - 客户端领取成功前同样只有 `deliveries` 空的记录(按钮是后来出现的)。
|
|
982
|
+
*
|
|
983
|
+
* ⚠ 2026-11-10 版本门控消融把主因钉在了**客户端版本**上
|
|
984
|
+
* (docs/claim-forensics-2026-11.md §2.1:同账号同 device_mid 下,
|
|
985
|
+
* `3.16.3` 全部拿不到投放/拿 1004,`3.17.2` 起全部成功;门控历史上每次都随
|
|
986
|
+
* 官方发版抬高)。插件启动时会把门控版本跟到官方当前版本(version-probe,
|
|
987
|
+
* 只抬不降),所以「先确认版本」是第一条排查动作,而不是最后一条。
|
|
988
|
+
*
|
|
989
|
+
* 剩下的失败只可能是「该活动没分配到这台账号」(§4 已确认投放按账号分配),
|
|
990
|
+
* 所以文案不再写「机制未定论」。
|
|
991
|
+
*/
|
|
992
|
+
const explain = (outcome) => {
|
|
993
|
+
if (outcome.ok === true || outcome.code === 1003) return undefined
|
|
994
|
+
if (outcome.code === 1004) {
|
|
995
|
+
return (
|
|
996
|
+
'no permission(1004):服务端判定不满足领取条件。最常见原因是客户端版本' +
|
|
997
|
+
'低于官方当前版本(版本门控),插件已在启动时自动跟随官方版本;若仍失败,' +
|
|
998
|
+
'可能是该活动未分配到此账号。'
|
|
999
|
+
)
|
|
1000
|
+
}
|
|
1001
|
+
if (outcome.code === 1005) return '名额已领完(1005):该活动本批已被领满。'
|
|
1002
|
+
return outcome.message ?? `HTTP ${outcome.httpStatus ?? '?'}`
|
|
1003
|
+
}
|
|
1004
|
+
const result = {
|
|
1005
|
+
planId,
|
|
1006
|
+
ok: outcome.ok === true,
|
|
1007
|
+
...(outcome.code !== undefined ? { code: outcome.code } : {}),
|
|
1008
|
+
...(outcome.alreadyClaimed === true ? { alreadyClaimed: true } : {}),
|
|
1009
|
+
httpStatus: outcome.httpStatus,
|
|
1010
|
+
/** 服务端原文保留在 message,另给 readable 供面板展示。 */
|
|
1011
|
+
...(outcome.message !== undefined ? { message: outcome.message } : {}),
|
|
1012
|
+
...(explain(outcome) !== undefined ? { readable: explain(outcome) } : {}),
|
|
1013
|
+
...(outcome.ok === true ? {} : { error: explain(outcome) }),
|
|
1014
|
+
}
|
|
1015
|
+
log(
|
|
1016
|
+
`[manage] 领取 ${entry.nickname} × ${planId}:` +
|
|
1017
|
+
`${outcome.ok ? '成功' : `失败(${outcome.code ?? outcome.httpStatus})`},captcha 尝试 ${attempts} 次`,
|
|
1018
|
+
)
|
|
1019
|
+
writeJson(res, 200, { ok: result.ok, results: [result] })
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
/**
|
|
1023
|
+
* 重启指引(0.6.6 起**不再替用户执行重启**)。
|
|
1024
|
+
*
|
|
1025
|
+
* ## 为什么从「自动重启」改为「给命令让用户自己重启」
|
|
1026
|
+
*
|
|
1027
|
+
* 旧实现 spawn PowerShell 脚本做「杀宿主 → 等退出 → 拉起」,并叠加了
|
|
1028
|
+
* 计划任务、`-ExecutionPolicy Bypass`、隐藏窗口、临时 .cmd 等手段 ——
|
|
1029
|
+
* 这组特征与恶意软件高度重合,被火绒等 AV 拦截是**正确行为**(用户实际报毒)。
|
|
1030
|
+
* 技术上也是死路:脚本在宿主的 Job Object 内,宿主一死脚本跟着死
|
|
1031
|
+
* (实测日志停在 `forcing pid N` 之后),能逃出 job 的手段恰是 AV 最敏感的。
|
|
1032
|
+
*
|
|
1033
|
+
* 现在只做两件事:校验参数 → 返回用户可直接复制的启动命令。
|
|
1034
|
+
* 重启是用户的决定,插件不越权。
|
|
1035
|
+
*
|
|
1036
|
+
* 路由名保留 `/restart-cdp`(0.5.x 语义),面板据此展示指引;
|
|
1037
|
+
* `deps.buildRestartCommand` 由 assemble 注入(探测宿主 exe 并生成命令)。
|
|
1038
|
+
*/
|
|
1039
|
+
const restartCdpHandler = async (req, res) => {
|
|
1040
|
+
const body = (await readJsonBody(req)) ?? {}
|
|
1041
|
+
const wantsDebugPort = body.debugPort !== undefined && body.debugPort !== null
|
|
1042
|
+
const debugPort = Number.isInteger(body.debugPort) ? body.debugPort : undefined
|
|
1043
|
+
if (wantsDebugPort && !(debugPort >= 1 && debugPort <= 65_535)) {
|
|
1044
|
+
writeJson(res, 400, { ok: false, error: 'debugPort 必须是 1-65535 的整数(或省略 = 普通重启)' })
|
|
1045
|
+
return
|
|
1046
|
+
}
|
|
1047
|
+
if (typeof deps.buildRestartCommand !== 'function') {
|
|
1048
|
+
writeJson(res, 501, { ok: false, error: '重启指引不可用(缺少命令生成实现)' })
|
|
1049
|
+
return
|
|
1050
|
+
}
|
|
1051
|
+
try {
|
|
1052
|
+
const guide = deps.buildRestartCommand(debugPort !== undefined ? { debugPort } : {})
|
|
1053
|
+
log(
|
|
1054
|
+
`[manage] 生成重启指引:${guide.note} 命令:${guide.command}`,
|
|
1055
|
+
)
|
|
1056
|
+
writeJson(res, 200, {
|
|
1057
|
+
ok: true,
|
|
1058
|
+
mode: debugPort !== undefined ? 'debug' : 'plain',
|
|
1059
|
+
command: guide.command,
|
|
1060
|
+
port: guide.port,
|
|
1061
|
+
note: guide.note,
|
|
1062
|
+
})
|
|
1063
|
+
} catch (error) {
|
|
1064
|
+
writeJson(res, 500, { ok: false, error: messageOf(error) })
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
/** /login/start:向渠道申请设备授权,返回 authorizeUrl + flowId(不含 secret)。 */
|
|
1069
|
+
const loginStartHandler = async (req, res) => {
|
|
1070
|
+
const body = (await readJsonBody(req)) ?? {}
|
|
1071
|
+
const channel = normalizeLoginChannel(body.channel)
|
|
1072
|
+
const flow = await startZcodeLogin(globalThis.fetch, { channel })
|
|
1073
|
+
pruneLoginFlows()
|
|
1074
|
+
loginFlows.set(flow.flowId, { flow, channel, createdAt: Date.now() })
|
|
1075
|
+
log(`[manage] 登录流已发起:${channel}(flowId=${flow.flowId.slice(0, 8)}…)`)
|
|
1076
|
+
writeJson(res, 200, {
|
|
1077
|
+
ok: true,
|
|
1078
|
+
flowId: flow.flowId,
|
|
1079
|
+
authorizeUrl: flow.authorizeUrl,
|
|
1080
|
+
expiresAt: flow.expiresAt > 0 ? flow.expiresAt : Date.now() + LOGIN_FLOW_TTL_MS,
|
|
1081
|
+
pollIntervalMs: Math.max(1, flow.pollIntervalSec) * 1_000,
|
|
1082
|
+
})
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/** /login/poll:查一次授权状态;ready 时组装凭据入池(凭据不回传)。 */
|
|
1086
|
+
const loginPollHandler = async (req, res) => {
|
|
1087
|
+
const body = (await readJsonBody(req)) ?? {}
|
|
1088
|
+
const flowId = typeof body.flowId === 'string' ? body.flowId.trim() : ''
|
|
1089
|
+
if (flowId.length === 0) {
|
|
1090
|
+
writeJson(res, 400, { ok: false, error: '需要 flowId(字符串)' })
|
|
1091
|
+
return
|
|
1092
|
+
}
|
|
1093
|
+
const record = loginFlows.get(flowId)
|
|
1094
|
+
if (record === undefined) {
|
|
1095
|
+
writeJson(res, 404, { ok: false, error: '登录流不存在或已过期,请重新发起' })
|
|
1096
|
+
return
|
|
1097
|
+
}
|
|
1098
|
+
const outcome = await pollZcodeLogin(record.flow, globalThis.fetch, ZCODE_APP_VERSION_FALLBACK)
|
|
1099
|
+
if (outcome.kind === 'pending') {
|
|
1100
|
+
writeJson(res, 200, { ok: true, status: 'pending' })
|
|
1101
|
+
return
|
|
1102
|
+
}
|
|
1103
|
+
loginFlows.delete(flowId)
|
|
1104
|
+
if (outcome.kind === 'failed') {
|
|
1105
|
+
writeJson(res, 200, { ok: true, status: 'failed', error: outcome.message })
|
|
1106
|
+
return
|
|
1107
|
+
}
|
|
1108
|
+
// ready:凭据组装与 beginZcodeLogin 逐字段一致(绝不把凭据发回页面)。
|
|
1109
|
+
const credential = {
|
|
1110
|
+
zcode_jwt: outcome.result.zcodeJwt,
|
|
1111
|
+
device_mid: generateDeviceMid(),
|
|
1112
|
+
user_id: outcome.result.userId,
|
|
1113
|
+
bigmodel_access_token: outcome.result.bigmodelAccessToken,
|
|
1114
|
+
account_label: outcome.result.displayName,
|
|
1115
|
+
app_version: ZCODE_APP_VERSION_FALLBACK,
|
|
1116
|
+
login_channel: record.channel,
|
|
1117
|
+
source: 'plugin-web',
|
|
1118
|
+
}
|
|
1119
|
+
const { entry, created } = pool.add(credential)
|
|
1120
|
+
notifyChanged()
|
|
1121
|
+
log(`[manage] 通过 Web UI ${created ? '添加' : '更新'}账号:${entry.nickname}(${record.channel})`)
|
|
1122
|
+
writeJson(res, 200, {
|
|
1123
|
+
ok: true,
|
|
1124
|
+
status: 'ready',
|
|
1125
|
+
created,
|
|
1126
|
+
account: { id: entry.id, nickname: entry.nickname },
|
|
1127
|
+
})
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
/**
|
|
1131
|
+
* OpenAI 兼容网关:状态 + 开关(0.9.3;0.9.5 去掉主 key 的 reveal)。
|
|
1132
|
+
*
|
|
1133
|
+
* - 状态实时读 `deps.getOpenAiGateway()`(assemble 注入,运行时句柄或 undefined);
|
|
1134
|
+
* - 拨动开关写 `settings.json` 的 `openaiGatewayEnabled` —— **重启后生效**
|
|
1135
|
+
* (网关是 HTTP server,热启停会牵扯端口占用,不做运行时切换);
|
|
1136
|
+
* - 0.9.5 起鉴权**只认分发 key**(主 apiKey 已废除),apiKey 展示随之移除。
|
|
1137
|
+
*/
|
|
1138
|
+
const openAiGatewayHandler = async (req, res) => {
|
|
1139
|
+
if (req.method === 'GET') {
|
|
1140
|
+
const runtime = deps.getOpenAiGateway?.()
|
|
1141
|
+
writeJson(res, 200, {
|
|
1142
|
+
ok: true,
|
|
1143
|
+
running: runtime !== undefined,
|
|
1144
|
+
baseUrl: runtime?.baseUrl ?? null,
|
|
1145
|
+
port: runtime?.port ?? null,
|
|
1146
|
+
enabledInSettings: deps.getOpenAiGatewayEnabled?.() === true,
|
|
1147
|
+
restartRequired: (deps.getOpenAiGatewayEnabled?.() === true) !== (runtime !== undefined),
|
|
1148
|
+
})
|
|
1149
|
+
return
|
|
1150
|
+
}
|
|
1151
|
+
const body = (await readJsonBody(req)) ?? {}
|
|
1152
|
+
if (typeof body.enabled !== 'boolean') {
|
|
1153
|
+
writeJson(res, 400, { ok: false, error: '需要 enabled(布尔)' })
|
|
1154
|
+
return
|
|
1155
|
+
}
|
|
1156
|
+
deps.setOpenAiGatewayEnabled?.(body.enabled)
|
|
1157
|
+
log(`[manage] OpenAI 兼容端点已${body.enabled ? '开启' : '关闭'}(重启宿主后生效)`)
|
|
1158
|
+
writeJson(res, 200, { ok: true, enabled: body.enabled, restartRequired: true })
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
/**
|
|
1162
|
+
* 分发 key CRUD(0.9.4)。**token 只在创建响应里出现一次**——之后所有列表
|
|
1163
|
+
* 都是脱敏形态(尾 4 位);这是「服务端不保存明文可复现」之外的唯一取回机会,
|
|
1164
|
+
* 用户复制后自行保管(丢了只能删了重建)。
|
|
1165
|
+
*/
|
|
1166
|
+
const distKeysHandler = async (req, res) => {
|
|
1167
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
1168
|
+
/** GET:脱敏列表(含用量与剩余额度)。 */
|
|
1169
|
+
if (req.method === 'GET') {
|
|
1170
|
+
writeJson(res, 200, {
|
|
1171
|
+
ok: true,
|
|
1172
|
+
keys: deps.listDistributionKeys?.() ?? [],
|
|
1173
|
+
})
|
|
1174
|
+
return
|
|
1175
|
+
}
|
|
1176
|
+
const body = (await readJsonBody(req)) ?? {}
|
|
1177
|
+
if (url.searchParams.get('op') === 'create') {
|
|
1178
|
+
const created = deps.createDistributionKey?.({
|
|
1179
|
+
name: body.name,
|
|
1180
|
+
quotaTotal: body.quotaTotal,
|
|
1181
|
+
accountId: body.accountId,
|
|
1182
|
+
})
|
|
1183
|
+
if (created === undefined) {
|
|
1184
|
+
writeJson(res, 500, { ok: false, error: '分发 key 创建失败(存储不可写?)' })
|
|
1185
|
+
return
|
|
1186
|
+
}
|
|
1187
|
+
/** 唯一一次明文下发。 */
|
|
1188
|
+
writeJson(res, 200, { ok: true, key: { ...created.public, token: created.token } })
|
|
1189
|
+
return
|
|
1190
|
+
}
|
|
1191
|
+
/**
|
|
1192
|
+
* update/delete 按 **id** 定位(0.9.5):列表里只有 id(token 完全不下发)——
|
|
1193
|
+
* 旧版用掩码 token 定位,前端永远删不掉任何 key(后端按明文找不到)。
|
|
1194
|
+
*/
|
|
1195
|
+
const id = typeof body.id === 'string' ? body.id.trim() : ''
|
|
1196
|
+
if (id.length === 0) {
|
|
1197
|
+
writeJson(res, 400, { ok: false, error: '需要 id' })
|
|
1198
|
+
return
|
|
1199
|
+
}
|
|
1200
|
+
if (url.searchParams.get('op') === 'update') {
|
|
1201
|
+
const updated = deps.updateDistributionKey?.(id, {
|
|
1202
|
+
enabled: body.enabled,
|
|
1203
|
+
quotaTotal: body.quotaTotal,
|
|
1204
|
+
name: body.name,
|
|
1205
|
+
})
|
|
1206
|
+
if (updated === false) {
|
|
1207
|
+
writeJson(res, 404, { ok: false, error: '分发 key 不存在' })
|
|
1208
|
+
return
|
|
1209
|
+
}
|
|
1210
|
+
writeJson(res, 200, { ok: true })
|
|
1211
|
+
return
|
|
1212
|
+
}
|
|
1213
|
+
if (url.searchParams.get('op') === 'delete') {
|
|
1214
|
+
const removed = deps.deleteDistributionKey?.(id)
|
|
1215
|
+
if (removed === false) {
|
|
1216
|
+
writeJson(res, 404, { ok: false, error: '分发 key 不存在' })
|
|
1217
|
+
return
|
|
1218
|
+
}
|
|
1219
|
+
writeJson(res, 200, { ok: true })
|
|
1220
|
+
return
|
|
1221
|
+
}
|
|
1222
|
+
writeJson(res, 400, { ok: false, error: '未知操作(支持 ?op=create / ?op=update / ?op=delete)' })
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
return [
|
|
1226
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/summary`, handler: guard(summaryHandler) },
|
|
1227
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/routing`, handler: guard(routingHandler) },
|
|
1228
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/balance`, handler: guard(balanceHandler) },
|
|
1229
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/set-enabled`, handler: guard(setEnabledHandler) },
|
|
1230
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/remove`, handler: guard(removeHandler) },
|
|
1231
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/reset-limits`, handler: guard(resetLimitsHandler) },
|
|
1232
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/reorder`, handler: guard(reorderHandler) },
|
|
1233
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/rename`, handler: guard(renameHandler) },
|
|
1234
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/unified-list`, handler: guard(unifiedListHandler) },
|
|
1235
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/model-list-visible`, handler: guard(modelListVisibleHandler) },
|
|
1236
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/auto-claim`, handler: guard(autoClaimHandler) },
|
|
1237
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/login/start`, handler: guard(loginStartHandler) },
|
|
1238
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/login/poll`, handler: guard(loginPollHandler) },
|
|
1239
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/claimable`, handler: guard(claimableHandler) },
|
|
1240
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/claim`, handler: guard(claimHandler) },
|
|
1241
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/restart-cdp`, handler: guard(restartCdpHandler) },
|
|
1242
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/openai-gateway`, handler: guard(openAiGatewayHandler) },
|
|
1243
|
+
{ kind: 'exact', path: `${MANAGE_PREFIX}/distribution-keys`, handler: guard(distKeysHandler) },
|
|
1244
|
+
]
|
|
1245
|
+
}
|