@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.
@@ -0,0 +1,143 @@
1
+ import http from "node:http"
2
+ import https from "node:https"
3
+ import { useAgent } from "request-filtering-agent"
4
+ import type { Logger } from "./logger"
5
+
6
+ /** 允许的出站端口:只放行常见的网页端口,其余一律拒绝。 */
7
+ export const ALLOWED_PORTS: readonly number[] = [80, 443, 8080, 8443]
8
+
9
+ /** 出站请求用的 User-Agent。 */
10
+ const USER_AGENT = "opencode-qq-bot"
11
+
12
+ export interface SafeFetchOptions {
13
+ /** 响应体字节上限,超出即中断下载。 */
14
+ maxBytes: number
15
+ /** 单次请求超时(毫秒)。 */
16
+ timeoutMs: number
17
+ logger: Logger
18
+ /** 允许的端口,默认 {@link ALLOWED_PORTS}。 */
19
+ allowedPorts?: readonly number[]
20
+ /** 生成连接用的 agent,默认用 request-filtering-agent;测试可注入。 */
21
+ agentFor?: (href: string) => http.Agent | https.Agent
22
+ }
23
+
24
+ export interface SafeFetchResult {
25
+ /** HTTP 状态码。 */
26
+ status: number
27
+ /** content-type 响应头。 */
28
+ contentType?: string
29
+ /** 响应体。 */
30
+ bytes: Uint8Array
31
+ }
32
+
33
+ /** 下载远端文件的函数签名;实现可替换,便于测试。 */
34
+ export type SafeFetcher = (
35
+ url: URL,
36
+ options: SafeFetchOptions,
37
+ ) => Promise<SafeFetchResult | undefined>
38
+
39
+ /** 截断过长的地址,避免日志被超长 URL 淹没。 */
40
+ function truncateForLog(value: string, max = 120): string {
41
+ return value.length > max ? `${value.slice(0, max)}…` : value
42
+ }
43
+
44
+ /**
45
+ * 下载一个远端文件,挡住指向内网的请求。
46
+ *
47
+ * 只做字符串判断挡不住 DNS 重绑定:域名解析出来的地址随时可以变。
48
+ * 这里把判定放到连接层——先解析 DNS,解析出的每一个地址都要过一遍公网判定
49
+ * (回环、私网、CGNAT、IPv4-mapped、NAT64、6to4 之类一律不算公网地址),
50
+ * 判定通过才连过去;连的是刚判定过的那个地址,Host 与 SNI 保持原样。
51
+ *
52
+ * 另外只放行白名单里的端口,也不跟随跳转:3xx 直接算失败,
53
+ * 免得用跳转绕过判定。
54
+ */
55
+ export async function safeFetchBytes(
56
+ url: URL,
57
+ options: SafeFetchOptions,
58
+ ): Promise<SafeFetchResult | undefined> {
59
+ const { logger } = options
60
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
61
+ logger.warn(`拒绝下载不支持的协议 protocol=${url.protocol}`)
62
+ return undefined
63
+ }
64
+ const allowedPorts = options.allowedPorts ?? ALLOWED_PORTS
65
+ const port = url.port ? Number(url.port) : url.protocol === "https:" ? 443 : 80
66
+ if (!allowedPorts.includes(port)) {
67
+ logger.warn(`拒绝下载非白名单端口 port=${port} url=${truncateForLog(url.href)}`)
68
+ return undefined
69
+ }
70
+
71
+ const agent = options.agentFor?.(url.href) ?? useAgent(url.href)
72
+ const requester = url.protocol === "https:" ? https : http
73
+
74
+ return await new Promise<SafeFetchResult | undefined>((resolve) => {
75
+ let settled = false
76
+ const controller = new AbortController()
77
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs)
78
+ const finish = (result?: SafeFetchResult) => {
79
+ if (settled) return
80
+ settled = true
81
+ clearTimeout(timer)
82
+ resolve(result)
83
+ }
84
+
85
+ const request = requester.request(url, {
86
+ agent: agent as http.Agent,
87
+ headers: { "user-agent": USER_AGENT },
88
+ signal: controller.signal,
89
+ })
90
+
91
+ request.on("response", (response) => {
92
+ const status = response.statusCode ?? 0
93
+ if (status < 200 || status >= 300) {
94
+ response.resume()
95
+ logger.warn(`下载失败 status=${status} url=${truncateForLog(url.href)}`)
96
+ finish()
97
+ return
98
+ }
99
+ const declared = Number(response.headers["content-length"])
100
+ if (Number.isFinite(declared) && declared > options.maxBytes) {
101
+ response.destroy()
102
+ logger.warn(`文件过大,跳过下载 bytes=${declared} url=${truncateForLog(url.href)}`)
103
+ finish()
104
+ return
105
+ }
106
+ const chunks: Buffer[] = []
107
+ let total = 0
108
+ response.on("data", (chunk: Buffer) => {
109
+ total += chunk.length
110
+ if (total > options.maxBytes) {
111
+ request.destroy()
112
+ logger.warn(`文件过大,跳过下载 url=${truncateForLog(url.href)}`)
113
+ finish()
114
+ return
115
+ }
116
+ chunks.push(chunk)
117
+ })
118
+ response.on("end", () => {
119
+ const contentType = response.headers["content-type"]
120
+ finish({
121
+ status,
122
+ contentType: typeof contentType === "string" ? contentType : undefined,
123
+ bytes: new Uint8Array(Buffer.concat(chunks)),
124
+ })
125
+ })
126
+ response.on("error", (error) => {
127
+ if (settled) return
128
+ logger.warn(`下载中断 url=${truncateForLog(url.href)}`, error)
129
+ finish()
130
+ })
131
+ })
132
+ request.on("error", (error) => {
133
+ if (settled) return
134
+ if (controller.signal.aborted) {
135
+ logger.warn(`下载超时 url=${truncateForLog(url.href)}`)
136
+ } else {
137
+ logger.warn(`下载异常 url=${truncateForLog(url.href)}`, error)
138
+ }
139
+ finish()
140
+ })
141
+ request.end()
142
+ })
143
+ }
@@ -0,0 +1,309 @@
1
+ import { DETECTORS, redact, scan, type Detector } from "flare-redact"
2
+
3
+ /** 命中的敏感信息。 */
4
+ export interface SensitiveHit {
5
+ /** 检测器 id,例如 github_token。 */
6
+ detector: string
7
+ /** 检测器给出的原因,不含原文。 */
8
+ why: string
9
+ }
10
+
11
+ /** 出站检查的结果。 */
12
+ export interface SensitiveVerdict {
13
+ /** 是否可以发出去。 */
14
+ allowed: boolean
15
+ /** 命中的检测器,已去重。 */
16
+ hits: SensitiveHit[]
17
+ /** 回给模型的说明;放行时为空串。 */
18
+ reason: string
19
+ }
20
+
21
+ const CLEAN: SensitiveVerdict = { allowed: true, hits: [], reason: "" }
22
+
23
+ /**
24
+ * 隐私类检测器:邮箱、卡号、IBAN 在群聊里是正常内容,不拦。
25
+ *
26
+ * 出站拦截只针对凭证——把群里的「我的邮箱是 a@b.com」拦下来只会让人不敢用。
27
+ */
28
+ const PII_DETECTORS = new Set(["email", "obfuscated_email", "credit_card", "iban"])
29
+
30
+ /** 默认关闭、但确实算凭证的检测器。 */
31
+ const EXTRA_SECRET_DETECTORS = new Set(["seed_phrase"])
32
+
33
+ /**
34
+ * 出站要跑的检测器。
35
+ *
36
+ * 取 flare-redact 的默认检测器,去掉隐私类,再补上默认关闭的凭证类。
37
+ * 高熵串(UUID、哈希、base64 片段)会误伤,不开。
38
+ */
39
+ export const SECRET_DETECTORS = DETECTORS.filter(
40
+ (d) =>
41
+ !PII_DETECTORS.has(d.id) &&
42
+ d.id !== "high_entropy" &&
43
+ (d.default || d.tags?.includes("secret") || EXTRA_SECRET_DETECTORS.has(d.id)),
44
+ ).map((d) => d.id)
45
+
46
+ /** 环境变量名里出现这些词,值就按凭证看。 */
47
+ const SECRET_NAME =
48
+ /(?:^|_)(?:API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|SECRET_?KEY|CLIENT_?SECRET|KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|AUTH)(?:_|$)/i
49
+
50
+ /** 凭证至少这么长,太短的容易撞车。 */
51
+ const MIN_SECRET_LENGTH = 12
52
+
53
+ /** 已知凭证的分片长度:够长不撞车,又短到能抓住被拆开的凭证。 */
54
+ const FRAGMENT_LENGTH = 12
55
+
56
+ /** 零宽字符:插在凭证中间用来骗过正则。 */
57
+ const ZERO_WIDTH = /[\u200B-\u200F\u2060\uFEFF]/g
58
+
59
+ /** 文本里像 base64 的片段。 */
60
+ const BASE64_RUN = /[A-Za-z0-9+/_-]{20,}={0,2}/g
61
+
62
+ /** 最多解多少段 base64,防止有人拿大段数据硬撑。 */
63
+ const MAX_BASE64_RUNS = 32
64
+
65
+ /** 指向凭证文件的路径片段。 */
66
+ const SENSITIVE_PATH_PARTS = [
67
+ ".ssh",
68
+ ".aws",
69
+ ".gnupg",
70
+ ".kube",
71
+ ".docker",
72
+ ".npmrc",
73
+ ".netrc",
74
+ ".git-credentials",
75
+ ".env",
76
+ "id_rsa",
77
+ "id_ed25519",
78
+ ".pem",
79
+ ]
80
+
81
+ function escapeRegExp(value: string): string {
82
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
83
+ }
84
+
85
+ /** 归一化:全角转半角、去掉零宽字符,让「password=」这类写法也能命中。 */
86
+ function normalizeText(text: string): string {
87
+ return text.normalize("NFKC").replace(ZERO_WIDTH, "")
88
+ }
89
+
90
+ /**
91
+ * 判断一个环境变量的值像不像凭证。
92
+ *
93
+ * 名字已经筛过一轮,这里只排掉明显不是凭证的形态:太短、带空格、
94
+ * 是路径、是 URL、是 JSON。剩下的长字符串都当凭证看。
95
+ */
96
+ function looksLikeSecret(value: string): boolean {
97
+ if (value.length < MIN_SECRET_LENGTH) return false
98
+ if (/\s/.test(value)) return false
99
+ if (/^[/~]/.test(value) || /^\.\.?[/]/.test(value) || /^[A-Za-z]:[/\\]/.test(value)) return false
100
+ if (/^https?:\/\//i.test(value)) return false
101
+ if (/^[{[]/.test(value)) return false
102
+ return true
103
+ }
104
+
105
+ /**
106
+ * 从环境变量里挑出可能是凭证的值。
107
+ *
108
+ * 名字像密钥(`*_KEY` / `*_TOKEN` / `*_SECRET` …)且长得不像路径的值才算数。
109
+ */
110
+ export function collectEnvSecrets(env: Record<string, string | undefined>): string[] {
111
+ const secrets: string[] = []
112
+ for (const [name, value] of Object.entries(env)) {
113
+ if (!value || !SECRET_NAME.test(name)) continue
114
+ if (!looksLikeSecret(value)) continue
115
+ secrets.push(value)
116
+ }
117
+ return secrets
118
+ }
119
+
120
+ /** 已知凭证明文写成的检测器。 */
121
+ function knownSecretDetector(secrets: string[]): Detector | undefined {
122
+ if (secrets.length === 0) return undefined
123
+ return {
124
+ id: "known_secret",
125
+ label: "Known secret",
126
+ why: "环境里已知的凭证",
127
+ pattern: new RegExp(secrets.map(escapeRegExp).join("|")),
128
+ default: true,
129
+ }
130
+ }
131
+
132
+ /** 指向凭证文件的路径。 */
133
+ const SENSITIVE_PATH_DETECTOR: Detector = {
134
+ id: "sensitive_path",
135
+ label: "Sensitive path",
136
+ why: "指向凭证文件的路径",
137
+ pattern: new RegExp(
138
+ `(?:^|[\\s"'\`(=])[^\\s"'\`,;]*?(?:${SENSITIVE_PATH_PARTS.map(escapeRegExp).join("|")})(?:[/\\\\]|$)`,
139
+ "i",
140
+ ),
141
+ default: true,
142
+ }
143
+
144
+ /** 判断解码结果是不是像人话,解出来是二进制就丢掉。 */
145
+ function looksLikeText(text: string): boolean {
146
+ let printable = 0
147
+ for (const char of text) {
148
+ const code = char.codePointAt(0) ?? 0
149
+ const ok =
150
+ code === 9 ||
151
+ code === 10 ||
152
+ code === 13 ||
153
+ (code >= 32 && code < 127) ||
154
+ (code >= 0x4e00 && code <= 0x9fff)
155
+ if (ok) printable += 1
156
+ }
157
+ return printable / text.length >= 0.85
158
+ }
159
+
160
+ /** 解一段 base64;解不出人话就返回 undefined。 */
161
+ function decodeBase64(input: string): string | undefined {
162
+ const standard = input.replace(/-/g, "+").replace(/_/g, "/")
163
+ const padded = standard + "=".repeat((4 - (standard.length % 4)) % 4)
164
+ const decoded = Buffer.from(padded, "base64").toString("utf8")
165
+ if (decoded.length < 8) return undefined
166
+ if (decoded.includes("\uFFFD")) return undefined
167
+ if (!looksLikeText(decoded)) return undefined
168
+ return decoded
169
+ }
170
+
171
+ /** 找出文本里藏着的 base64 变体。 */
172
+ function base64Variants(text: string): string[] {
173
+ const runs = text.match(BASE64_RUN) ?? []
174
+ const variants: string[] = []
175
+ for (const run of runs.slice(0, MAX_BASE64_RUNS)) {
176
+ const decoded = decodeBase64(run)
177
+ if (decoded) variants.push(decoded)
178
+ }
179
+ return variants
180
+ }
181
+
182
+ /** 去掉分隔符,用来比对被拆开的凭证。 */
183
+ function compact(text: string): string {
184
+ return text.replace(/[\s\-_.:/\\]+/g, "")
185
+ }
186
+
187
+ /**
188
+ * 判断文本里有没有已知凭证的碎片。
189
+ *
190
+ * 凭证被空格、换行拆开时,正则匹配不上,但碎片还在。
191
+ */
192
+ function containsFragment(text: string, secrets: string[]): boolean {
193
+ if (secrets.length === 0) return false
194
+ const compactText = compact(text)
195
+ if (compactText.length < FRAGMENT_LENGTH) return false
196
+ for (const secret of secrets) {
197
+ const compactSecret = compact(secret)
198
+ if (compactSecret.length < FRAGMENT_LENGTH) continue
199
+ for (let i = 0; i + FRAGMENT_LENGTH <= compactSecret.length; i += 1) {
200
+ if (compactText.includes(compactSecret.slice(i, i + FRAGMENT_LENGTH))) return true
201
+ }
202
+ }
203
+ return false
204
+ }
205
+
206
+ export interface SensitiveCheckerOptions {
207
+ /** 已知的凭证明文:环境变量里的密钥、NapCat 访问令牌等。 */
208
+ knownSecrets?: string[]
209
+ /** 是否启用检查,默认启用。 */
210
+ enabled?: boolean
211
+ }
212
+
213
+ /**
214
+ * 出站消息的敏感信息检查。
215
+ *
216
+ * 判定交给 flare-redact:凭证格式(各家 API key、JWT、Bearer、私钥、凭证赋值)
217
+ * 都在它的检测器里;这里补三件它不管的事——环境里已知的凭证明文、
218
+ * 全角与零宽字符的归一化、base64 变体。
219
+ *
220
+ * 命中就整条拦截:出站消息要么原样发出去,要么不发。
221
+ */
222
+ export class SensitiveChecker {
223
+ private readonly enabled: boolean
224
+ private readonly knownSecrets: string[]
225
+ private readonly custom: Detector[]
226
+ private readonly only: string[]
227
+
228
+ constructor(options: SensitiveCheckerOptions = {}) {
229
+ this.enabled = options.enabled ?? true
230
+ this.knownSecrets = (options.knownSecrets ?? []).filter(
231
+ (secret) => secret.length >= MIN_SECRET_LENGTH,
232
+ )
233
+ const known = knownSecretDetector(this.knownSecrets)
234
+ this.custom = known ? [known, SENSITIVE_PATH_DETECTOR] : [SENSITIVE_PATH_DETECTOR]
235
+ this.only = [...SECRET_DETECTORS, ...this.custom.map((detector) => detector.id)]
236
+ }
237
+
238
+ /**
239
+ * 检查一段即将发出的内容。
240
+ *
241
+ * @param text 即将发出去的文本。
242
+ * @returns 放行时 `allowed` 为真;命中敏感信息时带上原因与命中的检测器。
243
+ */
244
+ check(text: string): SensitiveVerdict {
245
+ if (!this.enabled || text.trim() === "") return CLEAN
246
+ const normalized = normalizeText(text)
247
+ const variants = [normalized, ...base64Variants(normalized)]
248
+ const hits = new Map<string, SensitiveHit>()
249
+ for (const variant of variants) {
250
+ for (const finding of scan(variant, { only: this.only, custom: this.custom })) {
251
+ hits.set(finding.detector, { detector: finding.detector, why: finding.why })
252
+ }
253
+ }
254
+ if (containsFragment(variants.join("\n"), this.knownSecrets)) {
255
+ hits.set("known_secret", { detector: "known_secret", why: "环境里已知的凭证" })
256
+ }
257
+ if (hits.size === 0) return CLEAN
258
+ const detectors = [...hits.values()].map((hit) => hit.detector)
259
+ return {
260
+ allowed: false,
261
+ hits: [...hits.values()],
262
+ reason: `出站消息包含疑似敏感信息(${detectors.join("、")}),已拦截,没有发出去。请删掉这些凭证后再发一次。`,
263
+ }
264
+ }
265
+ }
266
+
267
+ /** 日志打码的选项。 */
268
+ export interface MaskOptions {
269
+ /** 已知的凭证明文:环境变量里的密钥、NapCat 访问令牌等。 */
270
+ knownSecrets?: string[]
271
+ }
272
+
273
+ /**
274
+ * 给日志打码:把凭证换成占位符,其余内容原样留下。
275
+ *
276
+ * 用的是出站拦截同一套检测器(`SECRET_DETECTORS`):邮箱、卡号、IBAN 不在内,
277
+ * 群聊里的正常内容不会被误伤。环境里已知的凭证明文用 `known_secret` 额外兜住。
278
+ *
279
+ * 日志是「打码」不是「拦截」——整行照常写下来,只是凭证本身不落到文件里。
280
+ *
281
+ * @param text 已经序列化好的一行日志。
282
+ * @param options 已知凭证明文等附加条件。
283
+ * @returns 打码后的文本;脱敏器出错时整行换成 `[REDACTED]`,宁可少写也不写漏。
284
+ */
285
+ export function maskSecrets(text: string, options: MaskOptions = {}): string {
286
+ if (text === "") return text
287
+ const knownSecrets = (options.knownSecrets ?? []).filter(
288
+ (secret) => secret.length >= MIN_SECRET_LENGTH,
289
+ )
290
+ const known = knownSecretDetector(knownSecrets)
291
+ const custom = known ? [known] : []
292
+ const only = [...SECRET_DETECTORS, ...custom.map((detector) => detector.id)]
293
+ try {
294
+ // 原文里匹配不到时,再检查归一化后的副本:全角 / 零宽混淆的凭证
295
+ // 出站拦截能识别,日志也不能原样写出去。无法安全回写位置,整行丢弃。
296
+ const normalized = normalizeText(text)
297
+ if (normalized !== text) {
298
+ const hits = scan(normalized, { only, custom })
299
+ if (hits.length > 0 || containsFragment(normalized, knownSecrets)) return "[REDACTED]"
300
+ }
301
+ return redact(text, {
302
+ only,
303
+ custom,
304
+ mask: ({ detector }) => `[REDACTED:${detector.id}]`,
305
+ })
306
+ } catch {
307
+ return "[REDACTED]"
308
+ }
309
+ }