@cmach_socket/opencode-qq-bot 0.7.0 → 0.9.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.
Files changed (51) hide show
  1. package/NOTICE +48 -15
  2. package/README.md +220 -115
  3. package/package.json +10 -1
  4. package/src/cleanup.ts +1 -0
  5. package/src/commands.ts +2 -0
  6. package/src/config/fields.ts +780 -0
  7. package/src/config/live.ts +161 -0
  8. package/src/config/registry.ts +654 -0
  9. package/src/config/store.ts +175 -0
  10. package/src/config/types.ts +253 -0
  11. package/src/config.ts +77 -1023
  12. package/src/diary/collector.ts +28 -14
  13. package/src/diary/command.ts +24 -2
  14. package/src/diary/paths.ts +27 -0
  15. package/src/diary/scheduler.ts +63 -14
  16. package/src/diary/scope.ts +27 -0
  17. package/src/diary/store.ts +48 -4
  18. package/src/diary/summary.ts +33 -5
  19. package/src/home.ts +11 -16
  20. package/src/index.ts +777 -644
  21. package/src/logger.ts +104 -1
  22. package/src/model-view.ts +3 -1
  23. package/src/naplink/client.ts +16 -0
  24. package/src/panel/api.ts +345 -0
  25. package/src/panel/auth.ts +65 -0
  26. package/src/panel/models.ts +56 -0
  27. package/src/panel/runtime.ts +51 -0
  28. package/src/panel/server.ts +185 -0
  29. package/src/panel/status.ts +201 -0
  30. package/src/rate-limit.ts +46 -0
  31. package/src/runtime/claim.ts +37 -0
  32. package/src/runtime/start.ts +55 -0
  33. package/src/sensitive.ts +6 -1
  34. package/src/session/find.ts +44 -10
  35. package/src/session/manager.ts +118 -19
  36. package/src/session/prompt.ts +1 -1
  37. package/src/text.ts +34 -0
  38. package/src/tools/policy.ts +16 -1
  39. package/src/tools/qq.ts +90 -38
  40. package/src/tools/send-guard.ts +2 -2
  41. package/src/tui-commands.ts +1 -1
  42. package/web/dist/assets/index-7eMQEM7-.css +1 -0
  43. package/web/dist/assets/index-DCkgUY7y.js +15 -0
  44. package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  45. package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  46. package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  47. package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  48. package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  49. package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  50. package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  51. package/web/dist/index.html +13 -0
package/src/logger.ts CHANGED
@@ -22,6 +22,18 @@ export interface Logger {
22
22
  error(message: string, ...meta: unknown[]): void
23
23
  }
24
24
 
25
+ /** 环形缓冲里的一条日志。 */
26
+ export interface LogEntry {
27
+ /** 时间(ISO 字符串)。 */
28
+ time: string
29
+ /** 级别。 */
30
+ level: LogLevel
31
+ /** 正文。 */
32
+ message: string
33
+ /** 附加信息。 */
34
+ meta: unknown[]
35
+ }
36
+
25
37
  /** 日志器选项。 */
26
38
  export interface LoggerOptions {
27
39
  /** 最低输出级别,默认 info。 */
@@ -51,6 +63,77 @@ const FILE_NAME = "qq-bot-%DATE%.log"
51
63
  const MAX_META_DEPTH = 4
52
64
  /** 关闭日志时最多等多久(毫秒),避免卸载卡死。 */
53
65
  const CLOSE_TIMEOUT_MS = 2000
66
+ /** 进程内日志环形缓冲的容量。 */
67
+ const LOG_BUFFER_SIZE = 500
68
+ /** 日志级别的大小顺序。 */
69
+ const LEVEL_ORDER: readonly LogLevel[] = ["debug", "info", "warn", "error"]
70
+
71
+ /** 进程内的日志环形缓冲:面板直接看日志,不必去翻文件。 */
72
+ const logBuffer: LogEntry[] = []
73
+ /** 日志订阅者:面板的 SSE 增量推送用。 */
74
+ const logSubscribers = new Set<(entry: LogEntry) => void>()
75
+
76
+ /**
77
+ * 读取最近的日志。
78
+ *
79
+ * @param options `limit` 取多少条,`level` 只看某个级别。
80
+ */
81
+ export function readLogTail(options: { limit?: number; level?: LogLevel } = {}): LogEntry[] {
82
+ const limit = Math.max(1, Math.min(options.limit ?? 200, LOG_BUFFER_SIZE))
83
+ const level = options.level
84
+ const filtered = level ? logBuffer.filter((entry) => entry.level === level) : logBuffer
85
+ return filtered.slice(-limit)
86
+ }
87
+
88
+ /**
89
+ * 订阅新写入的日志。
90
+ *
91
+ * @param listener 每条新日志调用一次。
92
+ * @returns 取消订阅的函数。
93
+ */
94
+ export function subscribeLogs(listener: (entry: LogEntry) => void): () => void {
95
+ logSubscribers.add(listener)
96
+ return () => {
97
+ logSubscribers.delete(listener)
98
+ }
99
+ }
100
+
101
+ /** 给缓冲里的副本打码:文件里打码了,面板里也必须打码。 */
102
+ function maskEntry(value: unknown, knownSecrets: string[]): unknown {
103
+ if (typeof value === "string") return maskSecrets(value, { knownSecrets })
104
+ if (!value || typeof value !== "object") return value
105
+ try {
106
+ const text = JSON.stringify(value)
107
+ const masked = maskSecrets(text, { knownSecrets })
108
+ return masked === text ? value : (JSON.parse(masked) as unknown)
109
+ } catch {
110
+ return value
111
+ }
112
+ }
113
+
114
+ /** 把一条日志压进环形缓冲并通知订阅者。 */
115
+ function pushBuffer(
116
+ level: LogLevel,
117
+ message: string,
118
+ meta: unknown[],
119
+ knownSecrets: string[],
120
+ ): void {
121
+ const entry: LogEntry = {
122
+ time: new Date().toISOString(),
123
+ level,
124
+ message: maskSecrets(message, { knownSecrets }),
125
+ meta: meta.map((item) => maskEntry(item, knownSecrets)),
126
+ }
127
+ logBuffer.push(entry)
128
+ while (logBuffer.length > LOG_BUFFER_SIZE) logBuffer.shift()
129
+ for (const listener of logSubscribers) {
130
+ try {
131
+ listener(entry)
132
+ } catch {
133
+ // 订阅者出错不影响日志本身。
134
+ }
135
+ }
136
+ }
54
137
 
55
138
  /** 写文件的那一路传输。 */
56
139
  interface FileTransport {
@@ -64,6 +147,8 @@ interface LoggerHandle {
64
147
  api: Logger
65
148
  logger: winston.Logger
66
149
  files: FileTransport[]
150
+ /** 当前最低级别:热更新时跟着变。 */
151
+ level: LogLevel
67
152
  }
68
153
 
69
154
  const handles = new Set<LoggerHandle>()
@@ -210,6 +295,8 @@ export function createLogger(prefix: string, options: LoggerOptions | LogLevel =
210
295
  transports,
211
296
  exitOnError: false,
212
297
  })
298
+ /** 当前级别:热更新时跟着变,缓冲的过滤要与输出一致。 */
299
+ const handle: LoggerHandle = { api: undefined as unknown as Logger, logger, files, level }
213
300
 
214
301
  // 传输出错时不能让进程崩掉,也不能让错误本身带着凭证进日志。
215
302
  logger.on("error", (error: Error) => {
@@ -218,7 +305,10 @@ export function createLogger(prefix: string, options: LoggerOptions | LogLevel =
218
305
  })
219
306
 
220
307
  const write = (target: LogLevel, message: string, meta: unknown[]) => {
308
+ // 低于当前级别的日志不进缓冲:面板看到的级别过滤和文件里一致。
309
+ if (LEVEL_ORDER.indexOf(target) < LEVEL_ORDER.indexOf(handle.level)) return
221
310
  const details = normalizeMeta(meta)
311
+ pushBuffer(target, message, details, knownSecrets)
222
312
  logger.log({
223
313
  level: target,
224
314
  message,
@@ -233,10 +323,23 @@ export function createLogger(prefix: string, options: LoggerOptions | LogLevel =
233
323
  warn: (message, ...meta) => write("warn", message, meta),
234
324
  error: (message, ...meta) => write("error", message, meta),
235
325
  }
236
- handles.add({ api, logger, files })
326
+ handle.api = api
327
+ handles.add(handle)
237
328
  return api
238
329
  }
239
330
 
331
+ /**
332
+ * 改日志器的最低级别。
333
+ *
334
+ * 日志级别是热字段:面板改完立即生效,不用重启。
335
+ */
336
+ export function setLogLevel(target: Logger, level: LogLevel): void {
337
+ const handle = [...handles].find((entry) => entry.api === target)
338
+ if (!handle) return
339
+ handle.level = level
340
+ handle.logger.level = level
341
+ }
342
+
240
343
  /** 等传输发出 finish:这时文件流已经把数据交给了操作系统。 */
241
344
  function waitFinish(transport: DailyRotateFile): Promise<void> {
242
345
  return new Promise<void>((resolve) => {
package/src/model-view.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  import { ZERO_WIDTH } from "./text"
13
13
 
14
14
  /** 提示词里的结构标签;群友文本里出现同样字样时换成全角,避免伪造。 */
15
- const STRUCTURE_TAG = /<\/?(quote|forward|history)>/gi
15
+ const STRUCTURE_TAG = /<\/?(quote|forward|history|chat)>/gi
16
16
 
17
17
  /** 换行类字符:换行、段分隔符、下一行、垂直制表、换页。 */
18
18
  const NEWLINE_LIKE = /[\r\n\u2028\u2029\u0085\u000B\u000C]+/g
@@ -87,6 +87,8 @@ export function sanitizeSenderName(value: string): string {
87
87
  .replace(PRIVATE_USE, "")
88
88
  .replace(/[【】]/g, (char) => (char === "【" ? "[" : "]"))
89
89
  .replace(/[<>]/g, (char) => (char === "<" ? "<" : ">"))
90
+ // 括号是角色标记的写法:群名片里带着括号就能伪造出 `(owner)`。
91
+ .replace(/[()()]/g, "")
90
92
  .replace(/\s+/g, " ")
91
93
  .trim()
92
94
  )
@@ -93,6 +93,10 @@ export class QQClient {
93
93
  private readonly link: NapLink
94
94
  private botId: string | undefined
95
95
  private botIdRequest: Promise<void> | undefined
96
+ /** 重连次数。 */
97
+ private reconnectCount = 0
98
+ /** 最后一次重连的时间(毫秒)。 */
99
+ private lastReconnect: number | undefined
96
100
 
97
101
  constructor(
98
102
  private readonly config: NapcatConfig,
@@ -126,6 +130,8 @@ export class QQClient {
126
130
  this.logger.warn("NapCat 连接断开", describeEvent(event))
127
131
  })
128
132
  this.link.on("reconnecting", (event: unknown) => {
133
+ this.reconnectCount += 1
134
+ this.lastReconnect = Date.now()
129
135
  this.logger.info("NapCat 正在重连", describeEvent(event))
130
136
  })
131
137
  this.link.on("connection:restored", (event: unknown) => {
@@ -154,6 +160,16 @@ export class QQClient {
154
160
  return this.link.isConnected()
155
161
  }
156
162
 
163
+ /** 重连次数。 */
164
+ get reconnects(): number {
165
+ return this.reconnectCount
166
+ }
167
+
168
+ /** 最后一次重连的时间(毫秒)。 */
169
+ get lastReconnectAt(): number | undefined {
170
+ return this.lastReconnect
171
+ }
172
+
157
173
  async connect(): Promise<void> {
158
174
  await this.link.connect()
159
175
  await this.refreshBotId()
@@ -0,0 +1,345 @@
1
+ import { readFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { serveStatic } from "@hono/node-server/serve-static"
4
+ import { Hono } from "hono"
5
+ import { getCookie, setCookie } from "hono/cookie"
6
+ import { csrf } from "hono/csrf"
7
+ import { secureHeaders } from "hono/secure-headers"
8
+ import { streamSSE } from "hono/streaming"
9
+ import type { ConfigController } from "../config/live"
10
+ import { CONFIG_FIELDS, CONFIG_GROUPS } from "../config/fields"
11
+ import {
12
+ configJsonSchema,
13
+ createStrictFieldSchema,
14
+ getConfigValue,
15
+ requiredFieldProblem,
16
+ } from "../config/registry"
17
+ import { readLogTail, subscribeLogs, type LogEntry } from "../logger"
18
+ import { PanelAuth, SESSION_COOKIE } from "./auth"
19
+ import type { ModelProvider } from "./models"
20
+ import { collectStatus } from "./status"
21
+ import type { PanelRuntime } from "./runtime"
22
+
23
+ /**
24
+ * 面板的 HTTP 接口。
25
+ *
26
+ * 鉴权两条路:`Authorization: Bearer <token>` 供命令行与 curl 用,
27
+ * 浏览器先 `POST /api/login` 换会话 Cookie,之后自动带上。
28
+ */
29
+
30
+ /** 安全的方法:不需要 CSRF 校验。 */
31
+ const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"])
32
+
33
+ /** 面板应用的依赖。 */
34
+ export interface PanelAppOptions {
35
+ /** 令牌与会话管理。 */
36
+ auth: PanelAuth
37
+ /** 配置控制器:读写与热更新都走它。 */
38
+ controller: ConfigController
39
+ /** 运行时句柄。 */
40
+ runtime: PanelRuntime
41
+ /** 可用模型列表。 */
42
+ models: ModelProvider
43
+ /** 前端构建产物目录;没有就不托管静态资源。 */
44
+ staticDir?: string
45
+ }
46
+
47
+ /** 状态推送的间隔(毫秒)。 */
48
+ const STATUS_INTERVAL_MS = 2000
49
+
50
+ /** 单个配置项在接口里的样子。 */
51
+ interface ConfigFieldView {
52
+ /** 配置路径。 */
53
+ path: string
54
+ /** 生效值;敏感字段没有这一项。 */
55
+ value?: unknown
56
+ /** 文件里写的值;敏感字段没有这一项。 */
57
+ fileValue?: unknown
58
+ /** 值来自哪里:`file` 或 `default`。 */
59
+ source: "file" | "default"
60
+ /** 是否敏感字段。 */
61
+ secret: boolean
62
+ /** 是否热更新。 */
63
+ hot: boolean
64
+ /** 敏感字段只给这个:有没有值。 */
65
+ hasValue?: boolean
66
+ }
67
+
68
+ /** 构造面板应用。 */
69
+ export function createPanelApp(options: PanelAppOptions): Hono {
70
+ const app = new Hono()
71
+ const { auth, controller, runtime } = options
72
+
73
+ // 静态资源带安全响应头:面板是本地工具,但浏览器照样要按 CSP 走。
74
+ app.use(
75
+ "*",
76
+ secureHeaders({
77
+ contentSecurityPolicy: {
78
+ defaultSrc: ["'self'"],
79
+ scriptSrc: ["'self'"],
80
+ styleSrc: ["'self'", "'unsafe-inline'"],
81
+ imgSrc: ["'self'", "data:"],
82
+ fontSrc: ["'self'", "data:"],
83
+ connectSrc: ["'self'"],
84
+ objectSrc: ["'none'"],
85
+ baseUri: ["'self'"],
86
+ frameAncestors: ["'none'"],
87
+ },
88
+ // 面板走本机 http,HSTS 没有意义。
89
+ strictTransportSecurity: false,
90
+ }),
91
+ )
92
+
93
+ // 写接口校验 Origin:带 Origin 的请求必须同源,不带的(curl)放行。
94
+ app.use("/api/*", async (c, next) => {
95
+ if (SAFE_METHODS.has(c.req.method)) return await next()
96
+ const origin = c.req.header("Origin")
97
+ if (origin) {
98
+ let expected = ""
99
+ try {
100
+ expected = new URL(c.req.url).origin
101
+ } catch {
102
+ expected = ""
103
+ }
104
+ if (origin !== expected) {
105
+ return c.json({ error: "forbidden", message: "跨站请求已被拒绝" }, 403)
106
+ }
107
+ }
108
+ return await next()
109
+ })
110
+ // 表单类内容类型再过一遍 hono 自带的 CSRF 校验。
111
+ app.use("/api/*", csrf({ origin: (origin, c) => origin === new URL(c.req.url).origin }))
112
+
113
+ // 鉴权:Bearer 令牌或会话 Cookie。
114
+ app.use("/api/*", async (c, next) => {
115
+ if (c.req.path === "/api/login") return await next()
116
+ const header = c.req.header("Authorization")
117
+ if (header?.startsWith("Bearer ")) {
118
+ if (auth.matches(header.slice("Bearer ".length).trim())) return await next()
119
+ return c.json({ error: "unauthorized", message: "令牌不正确" }, 401)
120
+ }
121
+ if (auth.valid(getCookie(c, SESSION_COOKIE))) return await next()
122
+ return c.json({ error: "unauthorized", message: "未授权:请先登录" }, 401)
123
+ })
124
+
125
+ // 用令牌换会话 Cookie。
126
+ app.post("/api/login", async (c) => {
127
+ const body = await readJson(c.req.raw)
128
+ const token =
129
+ body && typeof body === "object" && !Array.isArray(body)
130
+ ? (body as Record<string, unknown>).token
131
+ : undefined
132
+ if (typeof token !== "string" || !auth.matches(token)) {
133
+ return c.json({ error: "invalid_token", message: "令牌不正确" }, 401)
134
+ }
135
+ setCookie(c, SESSION_COOKIE, auth.issue(), {
136
+ httpOnly: true,
137
+ sameSite: "Strict",
138
+ path: "/",
139
+ maxAge: 60 * 60 * 24 * 30,
140
+ })
141
+ return c.json({ ok: true })
142
+ })
143
+
144
+ // 字段元数据与 JSON Schema:前端据此渲染表单。
145
+ app.get("/api/config/schema", (c) => {
146
+ return c.json({
147
+ version: 1,
148
+ groups: CONFIG_GROUPS,
149
+ fields: CONFIG_FIELDS,
150
+ jsonSchema: configJsonSchema(),
151
+ })
152
+ })
153
+
154
+ // 生效值、文件值与每字段来源。
155
+ app.get("/api/config", (c) => {
156
+ return c.json({ fields: configView(controller) })
157
+ })
158
+
159
+ // 提交变更:后端用同一份规则校验后落盘。
160
+ app.put("/api/config", async (c) => {
161
+ const contentType = c.req.header("Content-Type") ?? ""
162
+ if (!contentType.toLowerCase().includes("application/json")) {
163
+ return c.json({ error: "unsupported_media_type", message: "只接受 JSON 请求体" }, 415)
164
+ }
165
+ const body = await readJson(c.req.raw)
166
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
167
+ return c.json({ error: "invalid_body", message: "请求体必须是一个 JSON 对象" }, 400)
168
+ }
169
+ const patch = body as Record<string, unknown>
170
+ const problems = validatePatch(patch)
171
+ if (problems.length > 0) {
172
+ return c.json(
173
+ { error: "validation_failed", message: "配置校验不通过", fields: problems },
174
+ 400,
175
+ )
176
+ }
177
+ try {
178
+ const result = await controller.applyPatch(patch)
179
+ return c.json({
180
+ ok: true,
181
+ restartRequired: result.restartRequired,
182
+ fields: configView(controller),
183
+ })
184
+ } catch (error) {
185
+ return c.json(
186
+ {
187
+ error: "write_failed",
188
+ message: error instanceof Error ? error.message : String(error),
189
+ },
190
+ 500,
191
+ )
192
+ }
193
+ })
194
+
195
+ // 可用模型列表。
196
+ app.get("/api/models", async (c) => {
197
+ try {
198
+ return c.json({ models: await options.models.list() })
199
+ } catch (error) {
200
+ return c.json(
201
+ { error: "models_failed", message: error instanceof Error ? error.message : String(error) },
202
+ 502,
203
+ )
204
+ }
205
+ })
206
+
207
+ // 运行状态快照。
208
+ app.get("/api/status", async (c) => {
209
+ return c.json(await collectStatus(runtime))
210
+ })
211
+
212
+ // 日志尾部。
213
+ app.get("/api/logs", (c) => {
214
+ const limit = Number(c.req.query("limit") ?? "200")
215
+ const level = c.req.query("level")
216
+ const entries = readLogTail({
217
+ ...(Number.isFinite(limit) ? { limit } : {}),
218
+ ...(level === "debug" || level === "info" || level === "warn" || level === "error"
219
+ ? { level }
220
+ : {}),
221
+ })
222
+ return c.json({ entries })
223
+ })
224
+
225
+ // SSE:状态、配置变更与日志推送。
226
+ app.get("/api/stream", (c) => {
227
+ return streamSSE(c, async (stream) => {
228
+ let alive = true
229
+ const write = async (event: string, data: unknown) => {
230
+ if (!alive) return
231
+ try {
232
+ await stream.writeSSE({ event, data: JSON.stringify(data) })
233
+ } catch {
234
+ alive = false
235
+ }
236
+ }
237
+ const unsubscribeLogs = subscribeLogs((entry: LogEntry) => {
238
+ void write("log", entry)
239
+ })
240
+ const unsubscribeConfig = controller.onChange(() => {
241
+ void write("config", { fields: configView(controller) })
242
+ })
243
+ const timer = setInterval(() => {
244
+ void collectStatus(runtime)
245
+ .then((status) => write("status", status))
246
+ .catch(() => undefined)
247
+ }, STATUS_INTERVAL_MS)
248
+ timer.unref?.()
249
+ const close = () => {
250
+ alive = false
251
+ clearInterval(timer)
252
+ unsubscribeLogs()
253
+ unsubscribeConfig()
254
+ }
255
+ stream.onAbort(close)
256
+ await write("status", await collectStatus(runtime))
257
+ // 保持连接,直到客户端断开;`onAbort` 负责清理计时器与订阅。
258
+ while (alive) await stream.sleep(1000)
259
+ close()
260
+ })
261
+ })
262
+
263
+ // 静态资源与单页应用。
264
+ if (options.staticDir) {
265
+ const root = options.staticDir
266
+ app.use("/*", serveStatic({ root, rewriteRequestPath: (path) => path }))
267
+ app.notFound(async (c) => {
268
+ if (c.req.path.startsWith("/api/")) {
269
+ return c.json({ error: "not_found", message: "接口不存在" }, 404)
270
+ }
271
+ const index = join(root, "index.html")
272
+ try {
273
+ const html = await readFile(index, "utf8")
274
+ return c.html(html)
275
+ } catch {
276
+ return c.text("前端构建产物不存在:请先执行 bun run web:build", 404)
277
+ }
278
+ })
279
+ }
280
+
281
+ return app
282
+ }
283
+
284
+ /** 读取 JSON 请求体;解析失败返回 undefined。 */
285
+ async function readJson(request: Request): Promise<unknown> {
286
+ try {
287
+ return await request.json()
288
+ } catch {
289
+ return undefined
290
+ }
291
+ }
292
+
293
+ /** 逐字段的生效值视图。 */
294
+ function configView(controller: ConfigController): ConfigFieldView[] {
295
+ const config = controller.current
296
+ const raw = controller.file
297
+ return CONFIG_FIELDS.map((field) => {
298
+ const value = config ? getConfigValue(config, field.path) : undefined
299
+ const fileValue = getConfigValue(raw, field.path)
300
+ const fromFile = fileValue !== undefined
301
+ const base = {
302
+ path: field.path,
303
+ source: fromFile ? ("file" as const) : ("default" as const),
304
+ secret: field.secret === true,
305
+ hot: field.hot === true,
306
+ }
307
+ if (field.secret) {
308
+ const hasValue =
309
+ typeof value === "string" ? value.length > 0 : value !== undefined && value !== null
310
+ return { ...base, hasValue }
311
+ }
312
+ return {
313
+ ...base,
314
+ value,
315
+ ...(fromFile ? { fileValue } : {}),
316
+ }
317
+ })
318
+ }
319
+
320
+ /** 校验稀疏补丁:字段必须存在,值必须合法。 */
321
+ function validatePatch(patch: Record<string, unknown>): Array<{ path: string; message: string }> {
322
+ const problems: Array<{ path: string; message: string }> = []
323
+ for (const [path, value] of Object.entries(patch)) {
324
+ const field = CONFIG_FIELDS.find((entry) => entry.path === path)
325
+ if (!field) {
326
+ problems.push({ path, message: "未知配置项" })
327
+ continue
328
+ }
329
+ if (value === null) {
330
+ const problem = requiredFieldProblem(path, value)
331
+ if (problem) problems.push({ path, message: problem })
332
+ continue
333
+ }
334
+ const schema = createStrictFieldSchema(field)
335
+ const result = schema.safeParse(value)
336
+ if (!result.success) {
337
+ const message = result.error.issues
338
+ .map((issue) => issue.message)
339
+ .filter((text) => text.length > 0)
340
+ .join(";")
341
+ problems.push({ path, message: message.length > 0 ? message : "取值不合法" })
342
+ }
343
+ }
344
+ return problems
345
+ }
@@ -0,0 +1,65 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto"
2
+
3
+ /**
4
+ * 面板鉴权:单令牌 + 会话 Cookie。
5
+ *
6
+ * 面板是单用户本地工具:一个令牌换一张会话 Cookie 就够了。
7
+ */
8
+
9
+ /** 会话 Cookie 的名字。 */
10
+ export const SESSION_COOKIE = "qqbot_session"
11
+
12
+ /** 令牌哈希。 */
13
+ function digest(value: string): Buffer {
14
+ return createHash("sha256").update(value, "utf8").digest()
15
+ }
16
+
17
+ /** 令牌与会话管理。 */
18
+ export class PanelAuth {
19
+ /** 令牌哈希:内存里不留明文。 */
20
+ private tokenHash: Buffer
21
+ /** 已签发的会话 id。 */
22
+ private readonly sessions = new Set<string>()
23
+
24
+ constructor(token: string) {
25
+ this.tokenHash = digest(token)
26
+ }
27
+
28
+ /**
29
+ * 令牌是否正确。
30
+ *
31
+ * 比较等长的 sha256 哈希,恒定时间,不泄露长度以外的信息。
32
+ */
33
+ matches(candidate: string): boolean {
34
+ if (typeof candidate !== "string" || candidate.length === 0) return false
35
+ return timingSafeEqual(this.tokenHash, digest(candidate))
36
+ }
37
+
38
+ /** 签发一个会话 id。 */
39
+ issue(): string {
40
+ const id = randomBytes(24).toString("hex")
41
+ this.sessions.add(id)
42
+ return id
43
+ }
44
+
45
+ /** 会话是否有效。 */
46
+ valid(session: string | undefined): boolean {
47
+ if (typeof session !== "string" || session.length === 0) return false
48
+ return this.sessions.has(session)
49
+ }
50
+
51
+ /**
52
+ * 更换令牌。
53
+ *
54
+ * 旧令牌与所有已签发的会话立刻作废。
55
+ */
56
+ rotate(token: string): void {
57
+ this.tokenHash = digest(token)
58
+ this.sessions.clear()
59
+ }
60
+
61
+ /** 作废全部会话。 */
62
+ clear(): void {
63
+ this.sessions.clear()
64
+ }
65
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * 可用模型列表。
3
+ *
4
+ * 候选模型来自 OpenCode 的 provider 配置与模型目录,不在插件的配置里;
5
+ * 插件只是借 `ctx.model` 转述,模型列表变了要重载插件才会同步。
6
+ */
7
+
8
+ /** 面板展示的模型。 */
9
+ export interface ModelInfo {
10
+ /** provider id。 */
11
+ providerID: string
12
+ /** 模型 id。 */
13
+ id: string
14
+ /** 展示名。 */
15
+ name: string
16
+ /** 是否是 OpenCode 当前的默认模型。 */
17
+ default: boolean
18
+ }
19
+
20
+ /** 模型列表的来源。 */
21
+ export interface ModelProvider {
22
+ /** 取当前可用的模型。 */
23
+ list(): Promise<ModelInfo[]>
24
+ }
25
+
26
+ /** OpenCode 的模型接口:只用 list 与 default 两个方法。 */
27
+ interface ModelApiLike {
28
+ list(): Promise<{ data?: Array<{ providerID?: string; id?: string; name?: string }> }>
29
+ default(): Promise<{ data?: { providerID?: string; id?: string } | null }>
30
+ }
31
+
32
+ /**
33
+ * 把 OpenCode 的模型接口包成面板要的形状。
34
+ *
35
+ * @param api `ctx.model`。
36
+ */
37
+ export function createModelProvider(api: ModelApiLike): ModelProvider {
38
+ return {
39
+ async list(): Promise<ModelInfo[]> {
40
+ const listed = await api.list()
41
+ const fallback = await api.default().catch(() => ({ data: null }))
42
+ const current = fallback.data
43
+ const models = listed.data ?? []
44
+ return models.map((model) => ({
45
+ providerID: model.providerID ?? "",
46
+ id: model.id ?? "",
47
+ name: model.name ?? `${model.providerID ?? ""}/${model.id ?? ""}`,
48
+ default:
49
+ current !== undefined &&
50
+ current !== null &&
51
+ current.providerID === model.providerID &&
52
+ current.id === model.id,
53
+ }))
54
+ },
55
+ }
56
+ }