@cmach_socket/opencode-qq-bot 0.3.4 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/logger.ts CHANGED
@@ -1,7 +1,19 @@
1
- export type LogLevel = "debug" | "info" | "warn" | "error"
1
+ import { fsyncSync, mkdirSync } from "node:fs"
2
+ import { homedir } from "node:os"
3
+ import { isAbsolute, join } from "node:path"
4
+ import { inspect } from "node:util"
5
+ import winston from "winston"
6
+ import DailyRotateFile from "winston-daily-rotate-file"
7
+ import { maskSecrets } from "./sensitive"
2
8
 
3
- const LEVEL_ORDER: Record<LogLevel, number> = { debug: 10, info: 20, warn: 30, error: 40 }
9
+ /** 日志级别。 */
10
+ export type LogLevel = "debug" | "info" | "warn" | "error"
4
11
 
12
+ /**
13
+ * 日志器。
14
+ *
15
+ * 只有级别和消息,附加信息用 `...meta` 传,调用点与旧的 console 实现一致。
16
+ */
5
17
  export interface Logger {
6
18
  debug(message: string, ...meta: unknown[]): void
7
19
  info(message: string, ...meta: unknown[]): void
@@ -9,22 +21,266 @@ export interface Logger {
9
21
  error(message: string, ...meta: unknown[]): void
10
22
  }
11
23
 
12
- /** 创建带前缀的日志器,插件运行在 OpenCode 服务端,直接写 stdout/stderr。 */
13
- export function createLogger(prefix: string, level: LogLevel = "info"): Logger {
14
- const threshold = LEVEL_ORDER[level]
15
- const write = (lvl: LogLevel, stream: "log" | "error", message: string, meta: unknown[]) => {
16
- if (LEVEL_ORDER[lvl] < threshold) return
17
- const stamp = new Date().toISOString()
18
- const line = `[${stamp}] ${lvl.toUpperCase()} ${prefix} ${message}`
19
- const details = meta.filter((entry) => entry !== undefined)
20
- if (details.length > 0) console[stream](line, ...details)
21
- else console[stream](line)
24
+ /** 日志器选项。 */
25
+ export interface LoggerOptions {
26
+ /** 最低输出级别,默认 info。 */
27
+ level?: LogLevel
28
+ /** 是否写日志文件,默认 true。 */
29
+ file?: boolean
30
+ /** 日志目录,空表示用 XDG 状态目录。 */
31
+ dir?: string
32
+ /** 单个日志文件的大小上限,默认 5m。 */
33
+ maxSize?: string
34
+ /** 保留的历史日志份数,默认 5。 */
35
+ maxFiles?: number
36
+ /** 已知凭证明文,日志里会被额外打码。 */
37
+ knownSecrets?: string[]
38
+ }
39
+
40
+ /** winston 存放最终输出的符号键。 */
41
+ const MESSAGE = Symbol.for("message")
42
+
43
+ /** 默认的单文件大小上限。 */
44
+ const DEFAULT_MAX_SIZE = "5m"
45
+ /** 默认保留的日志份数。 */
46
+ const DEFAULT_MAX_FILES = 5
47
+ /** 日志文件名模板,%DATE% 会替换成当天日期。 */
48
+ const FILE_NAME = "qq-bot-%DATE%.log"
49
+ /** meta 最多递归几层,再深就原样留下。 */
50
+ const MAX_META_DEPTH = 4
51
+ /** 关闭日志时最多等多久(毫秒),避免卸载卡死。 */
52
+ const CLOSE_TIMEOUT_MS = 2000
53
+
54
+ /** 写文件的那一路传输。 */
55
+ interface FileTransport {
56
+ transport: DailyRotateFile
57
+ /** 当前打开的文件描述符,轮转后会更新。 */
58
+ fd?: number
59
+ }
60
+
61
+ /** 已创建的日志器,插件卸载时按实例关闭。 */
62
+ interface LoggerHandle {
63
+ api: Logger
64
+ logger: winston.Logger
65
+ files: FileTransport[]
66
+ }
67
+
68
+ const handles = new Set<LoggerHandle>()
69
+
70
+ /**
71
+ * 默认日志目录。
72
+ *
73
+ * 优先用 `$XDG_STATE_HOME/opencode-qq-bot/logs`,没设置就用
74
+ * `~/.local/state/opencode-qq-bot/logs`。
75
+ */
76
+ export function defaultLogDir(): string {
77
+ const stateHome = process.env.XDG_STATE_HOME?.trim()
78
+ const base = stateHome && isAbsolute(stateHome) ? stateHome : join(homedir(), ".local", "state")
79
+ return join(base, "opencode-qq-bot", "logs")
80
+ }
81
+
82
+ /** 判断是不是普通对象;Date、Map 之类的原样留下。 */
83
+ function isPlainObject(value: object): boolean {
84
+ const proto = Object.getPrototypeOf(value)
85
+ return proto === Object.prototype || proto === null
86
+ }
87
+
88
+ /**
89
+ * 规整 meta 里的值。
90
+ *
91
+ * Error 变成 `{name, message, stack}`,栈压成一行,避免日志文件里出现多行;
92
+ * 普通对象与数组递归处理,别的类型原样保留。
93
+ */
94
+ function normalizeValue(value: unknown, depth: number): unknown {
95
+ if (value instanceof Error) {
96
+ return {
97
+ name: value.name,
98
+ message: value.message,
99
+ stack: value.stack ? value.stack.replace(/\s*\n\s*/g, " ") : undefined,
100
+ }
22
101
  }
102
+ if (depth >= MAX_META_DEPTH) return value
103
+ if (Array.isArray(value)) return value.map((entry) => normalizeValue(entry, depth + 1))
104
+ if (value && typeof value === "object" && isPlainObject(value)) {
105
+ const result: Record<string, unknown> = {}
106
+ for (const [key, entry] of Object.entries(value)) {
107
+ result[key] = normalizeValue(entry, depth + 1)
108
+ }
109
+ return result
110
+ }
111
+ return value
112
+ }
113
+
114
+ /** 规整 meta 列表,去掉 undefined。 */
115
+ function normalizeMeta(entries: unknown[]): unknown[] {
116
+ const result: unknown[] = []
117
+ for (const entry of entries) {
118
+ if (entry === undefined) continue
119
+ result.push(normalizeValue(entry, 0))
120
+ }
121
+ return result
122
+ }
123
+
124
+ /**
125
+ * 打码格式:把最终序列化出来的那一行里的凭证换成占位符。
126
+ *
127
+ * 放在管道最后,console 与文件两条输出用的是同一套规则。
128
+ */
129
+ function maskFormat(knownSecrets: string[]): winston.Logform.Format {
130
+ return winston.format((info) => {
131
+ const line = info[MESSAGE]
132
+ if (typeof line === "string") {
133
+ info[MESSAGE] = maskSecrets(line, { knownSecrets })
134
+ }
135
+ return info
136
+ })()
137
+ }
138
+
139
+ /**
140
+ * 控制台格式:保持旧的 `[时间] 级别 前缀 消息` 样式,附加信息跟在后面。
141
+ */
142
+ function consoleFormat(prefix: string): winston.Logform.Format {
143
+ return winston.format((info) => {
144
+ const stamp = typeof info.timestamp === "string" ? info.timestamp : new Date().toISOString()
145
+ const level = String(info.level).toUpperCase()
146
+ const message = typeof info.message === "string" ? info.message : inspect(info.message)
147
+ const meta = Array.isArray(info.meta) ? info.meta : []
148
+ const details = meta.map((entry) => inspect(entry, { depth: MAX_META_DEPTH })).join(" ")
149
+ const line = `[${stamp}] ${level} ${prefix} ${message}`
150
+ info[MESSAGE] = details ? `${line} ${details}` : line
151
+ return info
152
+ })()
153
+ }
154
+
155
+ /**
156
+ * 创建一个日志器。
157
+ *
158
+ * 控制台输出保持人类可读的旧格式,同时写一份按天轮转、大小有上限的 JSON 日志文件;
159
+ * 两条输出都会逐行打码,凭证不会落盘。
160
+ *
161
+ * @param prefix 日志前缀,例如 `[qq-bot]`。
162
+ * @param options 级别、目录、轮转参数等;也可以直接传一个级别字符串。
163
+ * @returns 日志器。
164
+ */
165
+ export function createLogger(prefix: string, options: LoggerOptions | LogLevel = {}): Logger {
166
+ const resolved: LoggerOptions = typeof options === "string" ? { level: options } : options
167
+ const level = resolved.level ?? "info"
168
+ const knownSecrets = resolved.knownSecrets ?? []
169
+ const transports: winston.transport[] = []
170
+ const files: FileTransport[] = []
171
+
172
+ transports.push(
173
+ new winston.transports.Console({
174
+ format: winston.format.combine(
175
+ winston.format.errors({ stack: true }),
176
+ consoleFormat(prefix),
177
+ maskFormat(knownSecrets),
178
+ ),
179
+ stderrLevels: ["error"],
180
+ }),
181
+ )
182
+
183
+ if (resolved.file !== false) {
184
+ const dir = resolved.dir?.trim() ? resolved.dir : defaultLogDir()
185
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
186
+ const transport = new DailyRotateFile({
187
+ dirname: dir,
188
+ filename: FILE_NAME,
189
+ datePattern: "YYYY-MM-DD",
190
+ maxSize: resolved.maxSize ?? DEFAULT_MAX_SIZE,
191
+ maxFiles: resolved.maxFiles ?? DEFAULT_MAX_FILES,
192
+ format: winston.format.combine(
193
+ winston.format.errors({ stack: true }),
194
+ winston.format.json(),
195
+ maskFormat(knownSecrets),
196
+ ),
197
+ })
198
+ const entry: FileTransport = { transport }
199
+ transport.logStream.on("open", (fd: number) => {
200
+ entry.fd = fd
201
+ })
202
+ files.push(entry)
203
+ transports.push(transport)
204
+ }
205
+
206
+ const logger = winston.createLogger({
207
+ level,
208
+ format: winston.format((info) => info)(),
209
+ transports,
210
+ exitOnError: false,
211
+ })
212
+
213
+ // 传输出错时不能让进程崩掉,也不能让错误本身带着凭证进日志。
214
+ logger.on("error", (error: Error) => {
215
+ const message = error instanceof Error ? error.message : String(error)
216
+ console.error(`[${prefix}] 日志写入失败:${maskSecrets(message, { knownSecrets })}`)
217
+ })
218
+
219
+ const write = (target: LogLevel, message: string, meta: unknown[]) => {
220
+ const details = normalizeMeta(meta)
221
+ logger.log({
222
+ level: target,
223
+ message,
224
+ ...(details.length > 0 ? { meta: details } : {}),
225
+ timestamp: new Date().toISOString(),
226
+ })
227
+ }
228
+
229
+ const api: Logger = {
230
+ debug: (message, ...meta) => write("debug", message, meta),
231
+ info: (message, ...meta) => write("info", message, meta),
232
+ warn: (message, ...meta) => write("warn", message, meta),
233
+ error: (message, ...meta) => write("error", message, meta),
234
+ }
235
+ handles.add({ api, logger, files })
236
+ return api
237
+ }
238
+
239
+ /** 等传输发出 finish:这时文件流已经把数据交给了操作系统。 */
240
+ function waitFinish(transport: DailyRotateFile): Promise<void> {
241
+ return new Promise<void>((resolve) => {
242
+ const timer = setTimeout(() => resolve(), CLOSE_TIMEOUT_MS)
243
+ timer.unref?.()
244
+ transport.once("finish", () => {
245
+ clearTimeout(timer)
246
+ resolve()
247
+ })
248
+ })
249
+ }
250
+
251
+ /**
252
+ * 关闭指定日志器,等文件传输把缓冲写完;不传时关闭全部。
253
+ *
254
+ * 插件卸载时只关自己的日志器,避免接管实例时误关新实例。
255
+ */
256
+ export async function closeLogger(target?: Logger): Promise<void> {
257
+ const closing = target ? [...handles].filter((handle) => handle.api === target) : [...handles]
258
+ for (const handle of closing) handles.delete(handle)
259
+ await Promise.all(
260
+ closing.map(async (handle) => {
261
+ const waits = handle.files.map((file) => waitFinish(file.transport))
262
+ handle.logger.close()
263
+ await Promise.all(waits)
264
+ }),
265
+ )
266
+ }
23
267
 
24
- return {
25
- debug: (message, ...meta) => write("debug", "log", message, meta),
26
- info: (message, ...meta) => write("info", "log", message, meta),
27
- warn: (message, ...meta) => write("warn", "log", message, meta),
28
- error: (message, ...meta) => write("error", "error", message, meta),
268
+ /**
269
+ * 把指定日志器刷到磁盘;不传时刷新全部。
270
+ *
271
+ * 文件写入是异步的:等一个事件循环,再把内核缓冲 fsync 一次。
272
+ */
273
+ export async function flushLogger(target?: Logger): Promise<void> {
274
+ const targets = target ? [...handles].filter((handle) => handle.api === target) : [...handles]
275
+ for (const handle of targets) {
276
+ for (const file of handle.files) {
277
+ await new Promise<void>((resolve) => setImmediate(resolve))
278
+ if (file.fd === undefined) continue
279
+ try {
280
+ fsyncSync(file.fd)
281
+ } catch {
282
+ // 文件可能刚好被轮转或关闭,忽略。
283
+ }
284
+ }
29
285
  }
30
286
  }
@@ -0,0 +1,186 @@
1
+ import { lookup } from "node:dns/promises"
2
+ import { realpath, stat } from "node:fs/promises"
3
+ import { homedir } from "node:os"
4
+ import { isAbsolute, join, resolve, sep } from "node:path"
5
+ import ipaddr from "ipaddr.js"
6
+ import { ALLOWED_PORTS } from "./safe-fetch"
7
+
8
+ /**
9
+ * 媒体目录:`$XDG_STATE_HOME/opencode-qq-bot/media`。
10
+ *
11
+ * 未设置 `XDG_STATE_HOME` 时用 `~/.local/state/opencode-qq-bot/media`。
12
+ */
13
+ export function defaultMediaDir(): string {
14
+ const state = process.env.XDG_STATE_HOME?.trim()
15
+ const base = state && isAbsolute(state) ? state : join(homedir(), ".local", "state")
16
+ return join(base, "opencode-qq-bot", "media")
17
+ }
18
+
19
+ /** 出站媒体的路径策略。 */
20
+ export interface MediaPolicy {
21
+ /** 机器人工作目录:相对路径按它解析。 */
22
+ workspace: string
23
+ /** 允许发送媒体的目录(绝对路径或 `~/` 开头)。 */
24
+ allowedDirs: string[]
25
+ }
26
+
27
+ /** 媒体被策略拒绝时抛出,错误说明直接回给模型。 */
28
+ export class MediaPolicyError extends Error {}
29
+
30
+ /** 出站媒体的处理计划。 */
31
+ export type MediaPlan = { kind: "local"; path: string } | { kind: "remote"; url: URL }
32
+
33
+ /** 展开 `~` 并去掉首尾空白。 */
34
+ function expand(value: string): string {
35
+ const trimmed = value.trim()
36
+ if (trimmed === "~") return homedir()
37
+ if (trimmed.startsWith("~/")) return join(homedir(), trimmed.slice(2))
38
+ return trimmed
39
+ }
40
+
41
+ /**
42
+ * 判断路径是否位于目录之内。
43
+ *
44
+ * 按目录边界比较:`/data/qq-bot` 不会命中 `/data/qq-bot-secret`。
45
+ */
46
+ function contains(dir: string, target: string): boolean {
47
+ if (dir === target) return true
48
+ const prefix = dir.endsWith(sep) ? dir : dir + sep
49
+ return target.startsWith(prefix)
50
+ }
51
+
52
+ /**
53
+ * 判断一个 IP 是不是公网地址。
54
+ *
55
+ * 规则与 `request-filtering-agent` 一致:只有 `unicast` 段算公网,
56
+ * 回环、私网、CGNAT、链路本地、组播、IPv4-mapped、6to4 等一律不算。
57
+ */
58
+ function isPublicAddress(address: string): boolean {
59
+ try {
60
+ return ipaddr.parse(address).range() === "unicast"
61
+ } catch {
62
+ return false
63
+ }
64
+ }
65
+
66
+ /**
67
+ * 出站媒体的路径与地址把关。
68
+ *
69
+ * 本地路径只允许机器人工作目录、媒体目录和配置里显式放开的目录;
70
+ * 远端地址要求解析出的地址都是公网,再交给 NapCat 自己去拉。
71
+ */
72
+ export class OutboundMedia {
73
+ constructor(private readonly policy: MediaPolicy) {}
74
+
75
+ /**
76
+ * 检查媒体引用。
77
+ *
78
+ * 本地路径在这里就判定白名单,判定不过直接抛错,不占用发送额度。
79
+ */
80
+ async check(file: string): Promise<MediaPlan> {
81
+ const value = expand(file)
82
+ if (value.startsWith("http://") || value.startsWith("https://")) {
83
+ let url: URL
84
+ try {
85
+ url = new URL(value)
86
+ } catch {
87
+ throw new MediaPolicyError(`媒体地址无效:${file}`)
88
+ }
89
+ await this.checkRemote(url)
90
+ return { kind: "remote", url }
91
+ }
92
+ if (/^[a-z][a-z0-9+.-]*:/i.test(value)) {
93
+ throw new MediaPolicyError(`不支持的媒体地址:${file}`)
94
+ }
95
+ return { kind: "local", path: await this.resolveLocal(value) }
96
+ }
97
+
98
+ /** 按计划拿到可以交给 NapCat 的文件字段。 */
99
+ materialize(plan: MediaPlan): string {
100
+ return plan.kind === "local" ? plan.path : plan.url.href
101
+ }
102
+
103
+ /**
104
+ * 判定远端地址能不能用。
105
+ *
106
+ * 只放行常见网页端口;域名解析出来的每一个地址都必须是公网地址,
107
+ * 否则拒绝——不给 NapCat 留去拉内网地址的机会。
108
+ *
109
+ * 注意:实际下载由 NapCat 完成,它会自己再解析一次 DNS,
110
+ * 所以这里挡的是「地址本身指向内网」,挡不住 DNS 重绑定。
111
+ */
112
+ private async checkRemote(url: URL): Promise<void> {
113
+ const port = url.port ? Number(url.port) : url.protocol === "https:" ? 443 : 80
114
+ if (!ALLOWED_PORTS.includes(port)) {
115
+ throw new MediaPolicyError(`媒体地址的端口不在白名单内:${port}`)
116
+ }
117
+ const host = url.hostname.replace(/^\[|\]$/g, "")
118
+ const addresses = await resolveAddresses(host)
119
+ if (addresses.length === 0) {
120
+ throw new MediaPolicyError(`媒体地址解析不出 IP:${url.hostname}`)
121
+ }
122
+ for (const address of addresses) {
123
+ if (!isPublicAddress(address)) {
124
+ throw new MediaPolicyError(`媒体地址指向内网,不允许发送:${url.hostname}(${address})`)
125
+ }
126
+ }
127
+ }
128
+
129
+ /**
130
+ * 判定本地路径是否在允许的目录内。
131
+ *
132
+ * 展开 `~`、相对路径按工作目录解析,再取真实路径判定:
133
+ * 目录内的软链接指向目录外时同样拒绝,避免软链接绕过。
134
+ */
135
+ private async resolveLocal(file: string): Promise<string> {
136
+ const expanded = expand(file)
137
+ const lexical = isAbsolute(expanded) ? expanded : resolve(this.policy.workspace, expanded)
138
+ let real: string
139
+ try {
140
+ real = await realpath(lexical)
141
+ } catch {
142
+ throw new MediaPolicyError(`媒体文件不存在或无法读取:${file}`)
143
+ }
144
+ const info = await stat(real)
145
+ if (!info.isFile()) {
146
+ throw new MediaPolicyError(`媒体路径不是普通文件:${file}`)
147
+ }
148
+ const dirs = await this.allowedDirs()
149
+ const inLexical = dirs.some((dir) => contains(dir.lexical, lexical))
150
+ const inReal = dirs.some((dir) => contains(dir.real, real) || contains(dir.lexical, real))
151
+ if (!inLexical || !inReal) {
152
+ const allowed = dirs.map((dir) => dir.lexical).join("、")
153
+ throw new MediaPolicyError(`媒体文件不在允许的目录内:${file}(允许:${allowed || "无"})`)
154
+ }
155
+ return real
156
+ }
157
+
158
+ /** 允许的目录:词法路径与真实路径各一份,软链接目录也能命中。 */
159
+ private async allowedDirs(): Promise<{ lexical: string; real: string }[]> {
160
+ const dirs: { lexical: string; real: string }[] = []
161
+ for (const dir of this.policy.allowedDirs) {
162
+ const expanded = expand(dir)
163
+ if (!expanded) continue
164
+ const lexical = isAbsolute(expanded) ? expanded : resolve(this.policy.workspace, expanded)
165
+ let real = lexical
166
+ try {
167
+ real = await realpath(lexical)
168
+ } catch {
169
+ // 目录还不存在时先按词法路径处理。
170
+ }
171
+ dirs.push({ lexical, real })
172
+ }
173
+ return dirs
174
+ }
175
+ }
176
+
177
+ /** 解析主机名,返回全部地址;本身就是 IP 时直接返回。 */
178
+ async function resolveAddresses(host: string): Promise<string[]> {
179
+ if (ipaddr.isValid(host)) return [host]
180
+ try {
181
+ const found = await lookup(host, { all: true, verbatim: true })
182
+ return found.map((entry) => entry.address)
183
+ } catch {
184
+ return []
185
+ }
186
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * 模型视图:把群友可控的 QQ 文本整理成能直接进提示词的形式。
3
+ *
4
+ * 群里来的文本完全可控,原样拼进提示词就能伪造段落或跨行结构;
5
+ * 这里统一做结构净化,并给每条消息标上绝对时间。
6
+ *
7
+ * 净化分两层:`sanitizeUntrustedText` 负责单段文本里的换行、零宽字符与全角括号,
8
+ * `neutralizeStructureTags` 负责拼好之后整条消息里的结构标签——
9
+ * 群友把 `<quote>` 拆成两段发过来,逐段净化匹配不到,只有整体净化才拦得住。
10
+ */
11
+
12
+ /** 提示词里的结构标签;群友文本里出现同样字样时换成全角,避免伪造。 */
13
+ const STRUCTURE_TAG = /<\/?(quote|forward|history)>/gi
14
+
15
+ /** 换行类字符:换行、段分隔符、下一行、垂直制表、换页。 */
16
+ const NEWLINE_LIKE = /[\r\n\u2028\u2029\u0085\u000B\u000C]+/g
17
+ /** 零宽字符:可以用来把标签拆成看起来正常、匹配不上的形式。 */
18
+ const ZERO_WIDTH = /[\u200B-\u200F\u2060\uFEFF]/g
19
+ /** 控制字符:显示名里出现会破坏结构。 */
20
+ const CONTROL = /[\u0000-\u001F\u007F]+/g
21
+ /** 私用区字符:插件用它给结构标签占位,群友文本里的必须清掉,否则能伪造占位符。 */
22
+ const PRIVATE_USE = /[\uE000-\uF8FF]/g
23
+ /** 私用区占位符的起点。 */
24
+ const PLACEHOLDER_START = 0xe000
25
+
26
+ /**
27
+ * 把结构标签换成全角。
28
+ *
29
+ * 只对一段文本调用是不够的:`<` 与 `quote>` 分处两段时匹配不到,拼起来仍是一个标签。
30
+ * 这里对拼好的整段文本调用,跨段拼接伪造也挡得住。
31
+ */
32
+ export function neutralizeStructureTags(value: string): string {
33
+ return String(value ?? "").replace(STRUCTURE_TAG, (tag) =>
34
+ tag.replace(/</g, "<").replace(/>/g, ">"),
35
+ )
36
+ }
37
+
38
+ /**
39
+ * 净化群友可控文本。
40
+ *
41
+ * 换行类字符压成空格、零宽字符直接去掉,全角方括号换成半角,
42
+ * 提示词里的结构标签换成全角,这样群友文本再也伪造不出段落。
43
+ */
44
+ export function sanitizeUntrustedText(value: string): string {
45
+ return neutralizeStructureTags(
46
+ String(value ?? "")
47
+ .replace(/【/g, "[")
48
+ .replace(/】/g, "]")
49
+ .replace(NEWLINE_LIKE, " ")
50
+ .replace(ZERO_WIDTH, "")
51
+ .replace(PRIVATE_USE, ""),
52
+ )
53
+ }
54
+
55
+ /**
56
+ * 结构标签守卫:插件生成的结构标签在整体净化时先换成占位符。
57
+ *
58
+ * 群友文本里的 `<quote>` 之类必须中和,插件自己展开的引用块与转发块要原样保留。
59
+ * 占位符用私用区字符(单个码点,截断时不会被切成两半),
60
+ * 群友文本里的私用区字符会被净化掉,伪造不出占位符。
61
+ */
62
+ export class StructureTagGuard {
63
+ private readonly tags: string[] = []
64
+
65
+ /** 登记一个插件生成的结构标签,返回可安全拼接的占位符。 */
66
+ protect(tag: string): string {
67
+ const index = this.tags.push(tag) - 1
68
+ return String.fromCharCode(PLACEHOLDER_START + index)
69
+ }
70
+
71
+ /** 把占位符还原成原来的标签。 */
72
+ restore(text: string): string {
73
+ return text.replace(/[\uE000-\uF8FF]/g, (char) => {
74
+ const tag = this.tags[char.charCodeAt(0) - PLACEHOLDER_START]
75
+ return tag ?? ""
76
+ })
77
+ }
78
+ }
79
+
80
+ /** 净化发送者显示名:群名片可被伪造,去掉控制字符与结构符号。 */
81
+ export function sanitizeSenderName(value: string): string {
82
+ return (
83
+ String(value ?? "")
84
+ .replace(ZERO_WIDTH, "")
85
+ .replace(CONTROL, " ")
86
+ // 私用区字符是结构标签的占位符,群名片里出现会被还原成真正的标签。
87
+ .replace(PRIVATE_USE, "")
88
+ .replace(/[【】]/g, (char) => (char === "【" ? "[" : "]"))
89
+ .replace(/[<>]/g, (char) => (char === "<" ? "<" : ">"))
90
+ .replace(/\s+/g, " ")
91
+ .trim()
92
+ )
93
+ }
94
+
95
+ const TIMESTAMP_FORMAT = new Intl.DateTimeFormat("sv-SE", {
96
+ year: "2-digit",
97
+ month: "2-digit",
98
+ day: "2-digit",
99
+ hour: "2-digit",
100
+ minute: "2-digit",
101
+ hour12: false,
102
+ })
103
+
104
+ /** 绝对时间标注:本地时区的 `YY-MM-DD HH:MM`;时间无效时返回空串。 */
105
+ export function formatTimestamp(seconds: number): string {
106
+ if (!Number.isFinite(seconds) || seconds <= 0) return ""
107
+ return TIMESTAMP_FORMAT.format(new Date(seconds * 1000))
108
+ }
109
+
110
+ /** 一条消息的模型视图。 */
111
+ export interface ModelMessage {
112
+ /** 发送者显示名。 */
113
+ sender: string
114
+ /** 发送者 QQ 号。 */
115
+ userId: string
116
+ /** 消息正文。 */
117
+ text: string
118
+ /** 发送时间(Unix 秒)。 */
119
+ time: number
120
+ }
121
+
122
+ /** 拼成一行模型视图消息:`[绝对时间] 名字(QQ号): 正文`。 */
123
+ export function formatModelMessage(message: ModelMessage): string {
124
+ // QQ 号来自 QQ 服务,但仍是外部输入,按显示名净化一遍。
125
+ const userId = sanitizeSenderName(message.userId)
126
+ const name = sanitizeSenderName(message.sender) || userId || "未知用户"
127
+ const stamp = formatTimestamp(message.time)
128
+ const prefix = stamp ? `[${stamp}] ` : ""
129
+ return `${prefix}${name}(${userId}): ${message.text.trim()}`
130
+ }
@@ -75,16 +75,6 @@ export async function hydrateSegment(
75
75
  }
76
76
  }
77
77
 
78
- /** 补全一条消息里所有媒体段的远程直链。 */
79
- export async function hydrateMedia(
80
- api: OneBotApi,
81
- message: MessageSegment[],
82
- logger: Logger,
83
- ): Promise<void> {
84
- if (!Array.isArray(message)) return
85
- await Promise.all(message.map((segment) => hydrateSegment(api, segment, logger)))
86
- }
87
-
88
78
  /** NapCat 的连接与 API 门面,屏蔽 SDK 细节。 */
89
79
  export class QQClient {
90
80
  private readonly link: NapLink
@@ -120,6 +110,16 @@ export class QQClient {
120
110
  return this.link.api
121
111
  }
122
112
 
113
+ /**
114
+ * 调用 SDK 类型里没有声明的 OneBot 动作。
115
+ *
116
+ * 收藏表情相关的动作(`fetch_custom_face_detail`、`set_custom_face_desc`)
117
+ * 不在 naplink 的类型表里,只能这样透传。
118
+ */
119
+ callApi<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T> {
120
+ return this.link.callApi<T>(method, params)
121
+ }
122
+
123
123
  get connected(): boolean {
124
124
  return this.link.isConnected()
125
125
  }
@@ -179,15 +179,6 @@ export class QQClient {
179
179
  this.link.on("message.private", handler)
180
180
  }
181
181
 
182
- /** 补全消息里媒体段的直链,便于下载图片。 */
183
- async hydrate(message: MessageSegment[]): Promise<void> {
184
- try {
185
- await hydrateMedia(this.api, message, this.logger)
186
- } catch (error) {
187
- this.logger.warn("补全媒体直链失败", error)
188
- }
189
- }
190
-
191
182
  /** 机器人自己的 QQ 号,未连接时返回 undefined。 */
192
183
  get selfId(): string | undefined {
193
184
  return this.botId