dsh-zcode-startplan 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,414 @@
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/use/login)逐条校验参数形状。
18
+ */
19
+
20
+ import { isIP } from 'node:net'
21
+ import { startZcodeLogin, pollZcodeLogin, normalizeLoginChannel } from './upstream-api.js'
22
+ import { generateDeviceMid, ZCODE_APP_VERSION_FALLBACK } from './upstream.js'
23
+
24
+ /** 路由前缀(Client 半段用同一常量拼 URL)。 */
25
+ export const MANAGE_PREFIX = '/api/zcode-start-plan'
26
+
27
+ /** 登录流寿命(上游 `expires_at` 语义:10 分钟)。 */
28
+ const LOGIN_FLOW_TTL_MS = 10 * 60_000
29
+ /** 同时挂起的登录流上限(防 Map 无限膨胀;超限驱逐最旧)。 */
30
+ const LOGIN_FLOW_MAX = 8
31
+
32
+ /**
33
+ * 判断一个 IP 字面量是否回环地址。
34
+ * ⚠ 不用 `node:net` 的 `isLoopbackAddress`:Node 22 没有该导出,静态 import
35
+ * 加载即崩(engines 允许 `^22.19 || >=24`,必须兼容);用 `isIP` 自己判。
36
+ */
37
+ function isLoopbackAddress(value) {
38
+ const text = String(value ?? '').trim()
39
+ const kind = isIP(text)
40
+ if (kind === 4) return text.startsWith('127.')
41
+ if (kind === 6) {
42
+ const lower = text.toLowerCase()
43
+ return lower === '::1' || lower === '::ffff:127.0.0.1'
44
+ }
45
+ return false
46
+ }
47
+
48
+ /** 简化的回环判定(socket 地址 + Host 头,镜像 plugin-manager 的栅栏思路)。 */
49
+ function isLoopbackRequest(req) {
50
+ const remote = req.socket?.remoteAddress ?? ''
51
+ if (!isLoopbackAddress(remote)) return false
52
+ const hostHeader = String(req.headers?.host ?? '')
53
+ const hostname = hostHeader.startsWith('[')
54
+ ? hostHeader.slice(1, hostHeader.indexOf(']'))
55
+ : hostHeader.split(':')[0] ?? ''
56
+ if (hostname.length === 0) return true
57
+ if (hostname === 'localhost') return true
58
+ return isLoopbackAddress(hostname)
59
+ }
60
+
61
+ /** 写一个 JSON 响应。 */
62
+ function writeJson(res, status, body) {
63
+ if (res.writableEnded || res.destroyed) return
64
+ const text = JSON.stringify(body)
65
+ res.writeHead(status, {
66
+ 'content-type': 'application/json; charset=utf-8',
67
+ 'referrer-policy': 'no-referrer',
68
+ 'cache-control': 'no-store',
69
+ })
70
+ res.end(text)
71
+ }
72
+
73
+ /** 读请求体(有上限),解析为对象;失败返回 null。 */
74
+ function readJsonBody(req, maxBytes = 64 * 1024) {
75
+ return new Promise((resolve) => {
76
+ const chunks = []
77
+ let size = 0
78
+ let settled = false
79
+ const finish = (value) => {
80
+ if (settled) return
81
+ settled = true
82
+ resolve(value)
83
+ }
84
+ req.on('data', (chunk) => {
85
+ size += chunk.length
86
+ if (size > maxBytes) {
87
+ finish(null)
88
+ req.destroy()
89
+ return
90
+ }
91
+ chunks.push(chunk)
92
+ })
93
+ req.on('end', () => {
94
+ const text = Buffer.concat(chunks).toString('utf8')
95
+ if (text.length === 0) return finish(null)
96
+ try {
97
+ const parsed = JSON.parse(text)
98
+ finish(parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null)
99
+ } catch {
100
+ finish(null)
101
+ }
102
+ })
103
+ req.on('error', () => finish(null))
104
+ })
105
+ }
106
+
107
+ /** 把错误翻成字符串(不暴露堆栈给页面)。 */
108
+ const messageOf = (error) => (error instanceof Error ? error.message : String(error))
109
+
110
+ /**
111
+ * 账号的脱敏视图:绝不包含凭据字段。
112
+ */
113
+ function publicAccount(entry, index) {
114
+ return {
115
+ index: index + 1,
116
+ id: entry.id,
117
+ nickname: entry.nickname,
118
+ enabled: entry.enabled === true,
119
+ userIdTail: typeof entry.user_id === 'string' && entry.user_id.length > 0 ? entry.user_id.slice(-6) : null,
120
+ channel: entry.credential?.login_channel ?? null,
121
+ addedAt: typeof entry.added_at === 'number' ? entry.added_at : null,
122
+ modelRateLimits: entry.model_rate_limits ?? {},
123
+ lastError: entry.last_error ?? null,
124
+ }
125
+ }
126
+
127
+ /**
128
+ * 构造管理路由。
129
+ *
130
+ * @param {{ pool: import('./pool.js').AccountPool, fetchBalance?: (credential: any) => Promise<any>, log?: (message: string) => void }} deps
131
+ * @returns {Array<{ kind: 'exact', path: string, handler: (req: any, res: any) => Promise<void> }>}
132
+ */
133
+ export function makeManageRoutes(deps) {
134
+ const pool = deps.pool
135
+ const fetchBalance = deps.fetchBalance
136
+ const log = deps.log ?? (() => {})
137
+
138
+ // ── 登录流(两段式设备授权:Client 拿 URL → 浏览器授权 → Client 轮询)──
139
+ //
140
+ // ⚠ `flowSecret` 是本轮授权会话的密钥,**必须留在 Host 内存**(和 CLI 的
141
+ // `beginZcodeLogin` 一样),绝不随 /login/start 响应下发 —— 下发它等于把
142
+ // 「完成别人授权」的能力交给页面里任意脚本。
143
+ // 流程:Client 先 POST /login/start {channel} 拿 authorizeUrl(自己渲染成链接,
144
+ // 不用 window.open 以免被弹窗拦截),再隔 pollIntervalMs POST /login/poll
145
+ // {flowId} 查状态;ready 时 Host 组装凭据入池,凭据不出网关。
146
+ // 每条流 10 分钟过期,Map 上限 8 条,随手清理。
147
+
148
+ /** 进行中的登录流:flowId → { flow, channel, createdAt }。 */
149
+ const loginFlows = new Map()
150
+
151
+ /** 驱逐过期/多余的流。 */
152
+ function pruneLoginFlows() {
153
+ const now = Date.now()
154
+ for (const [key, value] of loginFlows) {
155
+ if (now - value.createdAt > LOGIN_FLOW_TTL_MS) loginFlows.delete(key)
156
+ }
157
+ while (loginFlows.size > LOGIN_FLOW_MAX) {
158
+ const oldest = [...loginFlows.entries()].sort((a, b) => a[1].createdAt - b[1].createdAt)[0]
159
+ loginFlows.delete(oldest[0])
160
+ }
161
+ }
162
+
163
+ /** 包一层 loopback 栅栏 + 异常兜底。 */
164
+ const guard = (handler) => async (req, res) => {
165
+ if (!isLoopbackRequest(req)) {
166
+ writeJson(res, 403, { ok: false, error: 'forbidden: loopback-only' })
167
+ return
168
+ }
169
+ try {
170
+ await handler(req, res)
171
+ } catch (error) {
172
+ log(`[manage] ${req.method} ${req.url} 失败:${messageOf(error)}`)
173
+ writeJson(res, 500, { ok: false, error: messageOf(error) })
174
+ }
175
+ }
176
+
177
+ /** 池子当前状态(含每账号余额,拉取失败给 null)。 */
178
+ const summaryHandler = async (_req, res) => {
179
+ const entries = pool.list({ withCredentials: true })
180
+ const accounts = []
181
+ for (let index = 0; index < entries.length; index += 1) {
182
+ const entry = entries[index]
183
+ const view = publicAccount(entry, index)
184
+ if (typeof fetchBalance === 'function' && entry.enabled) {
185
+ try {
186
+ const balance = await fetchBalance(entry.credential)
187
+ if (balance !== undefined) {
188
+ view.balance = balance.enterprise === true
189
+ ? { enterprise: true, remaining: null, total: null, planName: null }
190
+ : {
191
+ enterprise: false,
192
+ remaining: typeof balance.remaining === 'number' ? balance.remaining : null,
193
+ total: typeof balance.total === 'number' ? balance.total : null,
194
+ planName: balance.planName ?? null,
195
+ }
196
+ }
197
+ } catch {
198
+ view.balance = null
199
+ }
200
+ } else {
201
+ view.balance = null
202
+ }
203
+ accounts.push(view)
204
+ }
205
+ writeJson(res, 200, {
206
+ ok: true,
207
+ accounts,
208
+ enabledCount: accounts.filter((account) => account.enabled).length,
209
+ fetchedAt: Date.now(),
210
+ })
211
+ }
212
+
213
+ /** 单账号余额(点「刷新」时用,避免整表全拉)。 */
214
+ const balanceHandler = async (req, res) => {
215
+ const id = new URL(req.url ?? '/', 'http://localhost').searchParams.get('id')?.trim() ?? ''
216
+ const entry = id.length > 0 ? pool.list({ withCredentials: true }).find((item) => item.id === id) : undefined
217
+ if (entry === undefined) {
218
+ writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
219
+ return
220
+ }
221
+ if (typeof fetchBalance !== 'function') {
222
+ writeJson(res, 200, { ok: true, balance: null })
223
+ return
224
+ }
225
+ try {
226
+ const balance = await fetchBalance(entry.credential)
227
+ writeJson(res, 200, {
228
+ ok: true,
229
+ balance: balance === undefined
230
+ ? null
231
+ : balance.enterprise === true
232
+ ? { enterprise: true, remaining: null, total: null, planName: null }
233
+ : {
234
+ enterprise: false,
235
+ remaining: typeof balance.remaining === 'number' ? balance.remaining : null,
236
+ total: typeof balance.total === 'number' ? balance.total : null,
237
+ planName: balance.planName ?? null,
238
+ },
239
+ })
240
+ } catch (error) {
241
+ writeJson(res, 200, { ok: true, balance: null, error: messageOf(error) })
242
+ }
243
+ }
244
+
245
+ /** 启用 / 停用。 */
246
+ const setEnabledHandler = async (req, res) => {
247
+ const body = (await readJsonBody(req)) ?? {}
248
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
249
+ const enabled = body.enabled
250
+ if (id.length === 0 || typeof enabled !== 'boolean') {
251
+ writeJson(res, 400, { ok: false, error: '需要 id(字符串)与 enabled(布尔)' })
252
+ return
253
+ }
254
+ pool.setEnabled(id, enabled)
255
+ writeJson(res, 200, { ok: true, id, enabled })
256
+ }
257
+
258
+ /** 删除。 */
259
+ const removeHandler = async (req, res) => {
260
+ const body = (await readJsonBody(req)) ?? {}
261
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
262
+ if (id.length === 0) {
263
+ writeJson(res, 400, { ok: false, error: '需要 id(字符串)' })
264
+ return
265
+ }
266
+ const removed = pool.remove(id)
267
+ if (!removed) {
268
+ writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
269
+ return
270
+ }
271
+ writeJson(res, 200, { ok: true, id })
272
+ }
273
+
274
+ /** 清限流标记(当日额度误标时的自救)。 */
275
+ const resetLimitsHandler = async (req, res) => {
276
+ const body = (await readJsonBody(req)) ?? {}
277
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
278
+ const model = typeof body.model === 'string' ? body.model.trim() : ''
279
+ if (id.length === 0) {
280
+ writeJson(res, 400, { ok: false, error: '需要 id(字符串)' })
281
+ return
282
+ }
283
+ const removed = pool.clearModelRateLimits(id, model.length > 0 ? [model] : undefined)
284
+ writeJson(res, 200, { ok: true, id, removed })
285
+ }
286
+
287
+ /** 重排(顺序即选号优先级)。 */
288
+ const reorderHandler = async (req, res) => {
289
+ const body = (await readJsonBody(req)) ?? {}
290
+ const ids = Array.isArray(body.ids) ? body.ids : []
291
+ if (!ids.every((id) => typeof id === 'string' && id.trim().length > 0)) {
292
+ writeJson(res, 400, { ok: false, error: '需要 ids(非空字符串数组,且为当前集合的排列)' })
293
+ return
294
+ }
295
+ pool.reorder(ids)
296
+ writeJson(res, 200, { ok: true, ids })
297
+ }
298
+
299
+ /** 重命名备注。 */
300
+ const renameHandler = async (req, res) => {
301
+ const body = (await readJsonBody(req)) ?? {}
302
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
303
+ const nickname = typeof body.nickname === 'string' ? body.nickname.trim() : ''
304
+ if (id.length === 0 || nickname.length === 0) {
305
+ writeJson(res, 400, { ok: false, error: '需要 id 与 nickname(均非空)' })
306
+ return
307
+ }
308
+ const entry = pool.get?.(id) ?? pool.list({ withCredentials: true }).find((item) => item.id === id)
309
+ if (entry === undefined) {
310
+ writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
311
+ return
312
+ }
313
+ pool.patchAccount(id, { nickname })
314
+ writeJson(res, 200, { ok: true, id, nickname })
315
+ }
316
+
317
+ /**
318
+ * 置顶使用(「选择使用哪个账号」的落地)。
319
+ *
320
+ * 池子的既有约定:**手动顺序即选号优先级**(lib/pool.js 文件头第 1 条),
321
+ * `pick()` 永远取第一个「启用且未限流」的账号。因此「下次请求用这个号」
322
+ * = 把它排到首位。这里复用 `/reorder` 的集合校验,不另开写入口。
323
+ */
324
+ const useHandler = async (req, res) => {
325
+ const body = (await readJsonBody(req)) ?? {}
326
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
327
+ if (id.length === 0) {
328
+ writeJson(res, 400, { ok: false, error: '需要 id(字符串)' })
329
+ return
330
+ }
331
+ const entries = pool.list()
332
+ if (!entries.some((item) => item.id === id)) {
333
+ writeJson(res, 404, { ok: false, error: `账号不存在:${id}` })
334
+ return
335
+ }
336
+ const ids = [id, ...entries.map((item) => item.id).filter((existing) => existing !== id)]
337
+ pool.reorder(ids)
338
+ writeJson(res, 200, { ok: true, id, order: ids })
339
+ }
340
+
341
+ /** /login/start:向渠道申请设备授权,返回 authorizeUrl + flowId(不含 secret)。 */
342
+ const loginStartHandler = async (req, res) => {
343
+ const body = (await readJsonBody(req)) ?? {}
344
+ const channel = normalizeLoginChannel(body.channel)
345
+ const flow = await startZcodeLogin(globalThis.fetch, { channel })
346
+ pruneLoginFlows()
347
+ loginFlows.set(flow.flowId, { flow, channel, createdAt: Date.now() })
348
+ log(`[manage] 登录流已发起:${channel}(flowId=${flow.flowId.slice(0, 8)}…)`)
349
+ writeJson(res, 200, {
350
+ ok: true,
351
+ flowId: flow.flowId,
352
+ authorizeUrl: flow.authorizeUrl,
353
+ expiresAt: flow.expiresAt > 0 ? flow.expiresAt : Date.now() + LOGIN_FLOW_TTL_MS,
354
+ pollIntervalMs: Math.max(1, flow.pollIntervalSec) * 1_000,
355
+ })
356
+ }
357
+
358
+ /** /login/poll:查一次授权状态;ready 时组装凭据入池(凭据不回传)。 */
359
+ const loginPollHandler = async (req, res) => {
360
+ const body = (await readJsonBody(req)) ?? {}
361
+ const flowId = typeof body.flowId === 'string' ? body.flowId.trim() : ''
362
+ if (flowId.length === 0) {
363
+ writeJson(res, 400, { ok: false, error: '需要 flowId(字符串)' })
364
+ return
365
+ }
366
+ const record = loginFlows.get(flowId)
367
+ if (record === undefined) {
368
+ writeJson(res, 404, { ok: false, error: '登录流不存在或已过期,请重新发起' })
369
+ return
370
+ }
371
+ const outcome = await pollZcodeLogin(record.flow, globalThis.fetch, ZCODE_APP_VERSION_FALLBACK)
372
+ if (outcome.kind === 'pending') {
373
+ writeJson(res, 200, { ok: true, status: 'pending' })
374
+ return
375
+ }
376
+ loginFlows.delete(flowId)
377
+ if (outcome.kind === 'failed') {
378
+ writeJson(res, 200, { ok: true, status: 'failed', error: outcome.message })
379
+ return
380
+ }
381
+ // ready:凭据组装与 beginZcodeLogin 逐字段一致(绝不把凭据发回页面)。
382
+ const credential = {
383
+ zcode_jwt: outcome.result.zcodeJwt,
384
+ device_mid: generateDeviceMid(),
385
+ user_id: outcome.result.userId,
386
+ bigmodel_access_token: outcome.result.bigmodelAccessToken,
387
+ account_label: outcome.result.displayName,
388
+ app_version: ZCODE_APP_VERSION_FALLBACK,
389
+ login_channel: record.channel,
390
+ source: 'plugin-web',
391
+ }
392
+ const { entry, created } = pool.add(credential)
393
+ log(`[manage] 通过 Web UI ${created ? '添加' : '更新'}账号:${entry.nickname}(${record.channel})`)
394
+ writeJson(res, 200, {
395
+ ok: true,
396
+ status: 'ready',
397
+ created,
398
+ account: { id: entry.id, nickname: entry.nickname },
399
+ })
400
+ }
401
+
402
+ return [
403
+ { kind: 'exact', path: `${MANAGE_PREFIX}/summary`, handler: guard(summaryHandler) },
404
+ { kind: 'exact', path: `${MANAGE_PREFIX}/balance`, handler: guard(balanceHandler) },
405
+ { kind: 'exact', path: `${MANAGE_PREFIX}/set-enabled`, handler: guard(setEnabledHandler) },
406
+ { kind: 'exact', path: `${MANAGE_PREFIX}/remove`, handler: guard(removeHandler) },
407
+ { kind: 'exact', path: `${MANAGE_PREFIX}/reset-limits`, handler: guard(resetLimitsHandler) },
408
+ { kind: 'exact', path: `${MANAGE_PREFIX}/reorder`, handler: guard(reorderHandler) },
409
+ { kind: 'exact', path: `${MANAGE_PREFIX}/rename`, handler: guard(renameHandler) },
410
+ { kind: 'exact', path: `${MANAGE_PREFIX}/use`, handler: guard(useHandler) },
411
+ { kind: 'exact', path: `${MANAGE_PREFIX}/login/start`, handler: guard(loginStartHandler) },
412
+ { kind: 'exact', path: `${MANAGE_PREFIX}/login/poll`, handler: guard(loginPollHandler) },
413
+ ]
414
+ }