@cmach_socket/opencode-qq-bot 0.3.4 → 0.6.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.
- package/NOTICE +69 -0
- package/README.md +370 -44
- package/package.json +21 -2
- package/src/access.ts +79 -0
- package/src/bot-lock.ts +17 -26
- package/src/chat.ts +0 -20
- package/src/commands.ts +267 -0
- package/src/config.ts +602 -48
- package/src/emoji/command.ts +184 -0
- package/src/emoji/faces.ts +136 -0
- package/src/emoji/favorite-index.ts +150 -0
- package/src/emoji/favorites.ts +161 -0
- package/src/emoji/label.ts +318 -0
- package/src/events/notice.ts +139 -0
- package/src/events/store.ts +53 -0
- package/src/home.ts +45 -0
- package/src/index.ts +437 -63
- package/src/instance.ts +30 -17
- package/src/keepalive.ts +222 -0
- package/src/logger.ts +273 -17
- package/src/media-path.ts +186 -0
- package/src/model-view.ts +136 -0
- package/src/naplink/client.ts +14 -17
- package/src/naplink/history.ts +263 -0
- package/src/naplink/media.ts +34 -103
- package/src/naplink/render.ts +142 -33
- package/src/outbound.ts +174 -0
- package/src/overrides.ts +312 -0
- package/src/rate-limit.ts +228 -0
- package/src/safe-fetch.ts +143 -0
- package/src/sensitive.ts +309 -0
- package/src/session/manager.ts +488 -31
- package/src/session/proactive.ts +21 -0
- package/src/session/prompt.ts +4 -1
- package/src/session/soul.ts +46 -0
- package/src/tools/ask-guard.ts +5 -5
- package/src/tools/policy-guard.ts +45 -0
- package/src/tools/policy.ts +205 -0
- package/src/tools/qq.ts +353 -41
- package/src/tools/send-guard.ts +73 -0
- package/src/trace.ts +209 -0
- package/src/tui-commands.ts +70 -0
- package/src/version.ts +12 -0
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { Mutex } from "async-mutex"
|
|
2
|
+
import { type ChatTarget, targetKey } from "./chat"
|
|
3
|
+
import type { RateLimitConfig } from "./config"
|
|
4
|
+
|
|
5
|
+
/** 一分钟的毫秒数。 */
|
|
6
|
+
const MINUTE_MS = 60_000
|
|
7
|
+
/** 一小时的毫秒数。 */
|
|
8
|
+
const HOUR_MS = 60 * MINUTE_MS
|
|
9
|
+
/** 等待窗口结束时最多重算几次,兜底防止时钟不前进时死循环。 */
|
|
10
|
+
const MAX_STALL_ATTEMPTS = 5
|
|
11
|
+
|
|
12
|
+
/** 限流判定结果。 */
|
|
13
|
+
export interface RateLimitVerdict {
|
|
14
|
+
/** 是否放行这次发送。 */
|
|
15
|
+
allowed: boolean
|
|
16
|
+
/** 拒绝原因,直接写给模型看;放行时为空串。 */
|
|
17
|
+
reason: string
|
|
18
|
+
/** 为了放行这次发送实际等待的毫秒数。 */
|
|
19
|
+
waitedMs: number
|
|
20
|
+
/** 这次放行是否靠等待窗口结束换来的。 */
|
|
21
|
+
stalled: boolean
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** 一次出站发送的记录。 */
|
|
25
|
+
interface SendRecord {
|
|
26
|
+
/** 发送时间(毫秒)。 */
|
|
27
|
+
at: number
|
|
28
|
+
/** 所属发送操作;同一次工具调用拆出的多段共用一个 id。 */
|
|
29
|
+
operation?: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface SendRateLimiterOptions {
|
|
33
|
+
/** 取当前时间(毫秒),测试时可注入。 */
|
|
34
|
+
now?: () => number
|
|
35
|
+
/** 等待一段时间,测试时可注入。 */
|
|
36
|
+
sleep?: (ms: number) => Promise<void>
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 模型驱动的出站消息按目标计数:同一个群共用一份额度。 */
|
|
40
|
+
export function modelSendScope(target: ChatTarget): string {
|
|
41
|
+
return targetKey(target)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 插件自己生成的出站消息单独计数。
|
|
46
|
+
*
|
|
47
|
+
* 命令结果、任务进度不是模型刷屏,不该占用模型回复的额度,
|
|
48
|
+
* 但同样要和其它出站消息隔开一点时间。
|
|
49
|
+
*/
|
|
50
|
+
export function pluginSendScope(target: ChatTarget): string {
|
|
51
|
+
return `${targetKey(target)}#plugin`
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 出站消息的速率限制。
|
|
56
|
+
*
|
|
57
|
+
* 每个目标单独计数。硬上限(每分钟 / 每小时)超出时直接拒绝这次发送,
|
|
58
|
+
* 让模型立刻停下而不是把群刷爆;相邻两次发送间隔不足时先等一等,
|
|
59
|
+
* 攒成一阵发出去也不会连成一片。
|
|
60
|
+
*
|
|
61
|
+
* 计数与限流状态只存在内存里:插件重启后重新开始计数,
|
|
62
|
+
* 短窗口的计数本来也不该跨重启保留。
|
|
63
|
+
*/
|
|
64
|
+
export class SendRateLimiter {
|
|
65
|
+
/** 每个目标最近的发送记录。 */
|
|
66
|
+
private readonly records = new Map<string, SendRecord[]>()
|
|
67
|
+
/** 每个目标的互斥锁,同一目标的并发发送串行判定。 */
|
|
68
|
+
private readonly locks = new Map<string, Mutex>()
|
|
69
|
+
|
|
70
|
+
constructor(
|
|
71
|
+
private readonly config: RateLimitConfig,
|
|
72
|
+
private readonly options: SendRateLimiterOptions = {},
|
|
73
|
+
) {}
|
|
74
|
+
|
|
75
|
+
private get currentTime(): number {
|
|
76
|
+
return (this.options.now ?? Date.now)()
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
private get wait(): (ms: number) => Promise<void> {
|
|
80
|
+
return this.options.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)))
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
private lock(scope: string): Mutex {
|
|
84
|
+
let lock = this.locks.get(scope)
|
|
85
|
+
if (!lock) {
|
|
86
|
+
lock = new Mutex()
|
|
87
|
+
this.locks.set(scope, lock)
|
|
88
|
+
}
|
|
89
|
+
return lock
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** 取目标最近一小时的发送记录,顺手丢掉过期的那几条。 */
|
|
93
|
+
private recent(scope: string, now: number): SendRecord[] {
|
|
94
|
+
const records = this.records.get(scope) ?? []
|
|
95
|
+
const kept = records.filter((record) => now - record.at < HOUR_MS)
|
|
96
|
+
if (kept.length !== records.length) this.records.set(scope, kept)
|
|
97
|
+
return kept
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 申请一次发送许可。
|
|
102
|
+
*
|
|
103
|
+
* @param scope 计数维度,通常是目标键(`group:123`)。
|
|
104
|
+
* @param operation 同一次工具调用拆出的多段共用一个 id:段与段之间不再额外等待。
|
|
105
|
+
* @returns 放行时 `allowed` 为真;被硬上限拦下时带上原因与等待建议。
|
|
106
|
+
*/
|
|
107
|
+
async acquire(scope: string, operation?: string): Promise<RateLimitVerdict> {
|
|
108
|
+
return await this.lock(scope).runExclusive(() => this.admit(scope, operation, true))
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* 只做节奏控制,永不拒绝。
|
|
113
|
+
*
|
|
114
|
+
* 插件自己生成的消息(命令结果、任务进度)走这里:
|
|
115
|
+
* 它们不是模型刷屏,但同样不该连成一片发出去。
|
|
116
|
+
*/
|
|
117
|
+
async pace(scope: string, operation?: string): Promise<void> {
|
|
118
|
+
await this.lock(scope).runExclusive(() => this.admit(scope, operation, false))
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* 当前窗口内还剩多少条发送额度。
|
|
123
|
+
*
|
|
124
|
+
* 返回分钟与小时上限中较小的剩余数;对应上限为 0(不限)时按 `Infinity` 计。
|
|
125
|
+
*/
|
|
126
|
+
remaining(scope: string): number {
|
|
127
|
+
const now = this.currentTime
|
|
128
|
+
const records = this.recent(scope, now)
|
|
129
|
+
const minute = records.filter((record) => now - record.at < MINUTE_MS).length
|
|
130
|
+
const minuteLeft =
|
|
131
|
+
this.config.maxPerMinute > 0 ? Math.max(0, this.config.maxPerMinute - minute) : Infinity
|
|
132
|
+
const hourLeft =
|
|
133
|
+
this.config.maxPerHour > 0 ? Math.max(0, this.config.maxPerHour - records.length) : Infinity
|
|
134
|
+
return Math.min(minuteLeft, hourLeft)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** 判定并记账一次发送。 */
|
|
138
|
+
private async admit(
|
|
139
|
+
scope: string,
|
|
140
|
+
operation: string | undefined,
|
|
141
|
+
enforce: boolean,
|
|
142
|
+
): Promise<RateLimitVerdict> {
|
|
143
|
+
let waitedMs = 0
|
|
144
|
+
let stalled = false
|
|
145
|
+
if (enforce) {
|
|
146
|
+
const slot = await this.waitForSlot(scope)
|
|
147
|
+
if (!slot.allowed) return slot
|
|
148
|
+
waitedMs = slot.waitedMs
|
|
149
|
+
stalled = slot.stalled
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const now = this.currentTime
|
|
153
|
+
const records = this.recent(scope, now)
|
|
154
|
+
const gap = this.gapDelay(records, now, operation)
|
|
155
|
+
if (gap > 0) await this.wait(gap)
|
|
156
|
+
this.records.set(scope, [
|
|
157
|
+
...records,
|
|
158
|
+
{ at: this.currentTime, ...(operation ? { operation } : {}) },
|
|
159
|
+
])
|
|
160
|
+
return { allowed: true, reason: "", waitedMs: waitedMs + gap, stalled }
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 等一个发送名额出来。
|
|
165
|
+
*
|
|
166
|
+
* 每分钟上限可以配成“等窗口结束再发”:只等到最早的记录滑出短窗口,
|
|
167
|
+
* 等待总时长受 `stallMaxWaitMs` 限制;每小时上限始终直接拒绝,
|
|
168
|
+
* 不真的睡一小时。长窗口满了就没什么可等的。
|
|
169
|
+
*/
|
|
170
|
+
private async waitForSlot(scope: string): Promise<RateLimitVerdict> {
|
|
171
|
+
let waitedMs = 0
|
|
172
|
+
for (let attempt = 0; attempt < MAX_STALL_ATTEMPTS; attempt += 1) {
|
|
173
|
+
const now = this.currentTime
|
|
174
|
+
const records = this.recent(scope, now)
|
|
175
|
+
if (this.config.maxPerHour > 0 && records.length >= this.config.maxPerHour) {
|
|
176
|
+
return {
|
|
177
|
+
allowed: false,
|
|
178
|
+
reason: `发送频率超限:本小时已发出 ${records.length} 条,最多为每小时 ${this.config.maxPerHour} 条。请停止发送并结束本轮。`,
|
|
179
|
+
waitedMs,
|
|
180
|
+
stalled: waitedMs > 0,
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const minute = records.filter((record) => now - record.at < MINUTE_MS)
|
|
184
|
+
if (this.config.maxPerMinute <= 0 || minute.length < this.config.maxPerMinute) {
|
|
185
|
+
return { allowed: true, reason: "", waitedMs, stalled: waitedMs > 0 }
|
|
186
|
+
}
|
|
187
|
+
if (!this.config.stall) {
|
|
188
|
+
return {
|
|
189
|
+
allowed: false,
|
|
190
|
+
reason: `发送频率超限:本分钟已发出 ${minute.length} 条,最多为每分钟 ${this.config.maxPerMinute} 条。请停止发送并结束本轮。`,
|
|
191
|
+
waitedMs,
|
|
192
|
+
stalled: false,
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
// 需要滑出窗口的记录数:腾出一个名额就够了。
|
|
196
|
+
const needed = minute.length - (this.config.maxPerMinute - 1)
|
|
197
|
+
const candidate = [...minute].sort((left, right) => left.at - right.at)[needed - 1]
|
|
198
|
+
if (!candidate) break
|
|
199
|
+
const waitMs = MINUTE_MS - (now - candidate.at)
|
|
200
|
+
if (waitedMs + waitMs > this.config.stallMaxWaitMs) {
|
|
201
|
+
return {
|
|
202
|
+
allowed: false,
|
|
203
|
+
reason: `发送频率超限:本分钟已发出 ${minute.length} 条,最多为每分钟 ${this.config.maxPerMinute} 条;等窗口结束需要 ${waitMs} 毫秒,超过允许的 ${this.config.stallMaxWaitMs} 毫秒。请停止发送并结束本轮。`,
|
|
204
|
+
waitedMs,
|
|
205
|
+
stalled: waitedMs > 0,
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
await this.wait(waitMs)
|
|
209
|
+
waitedMs += waitMs
|
|
210
|
+
}
|
|
211
|
+
return {
|
|
212
|
+
allowed: false,
|
|
213
|
+
reason: "发送频率超限:等待窗口结束后仍未拿到发送名额。请停止发送并结束本轮。",
|
|
214
|
+
waitedMs,
|
|
215
|
+
stalled: waitedMs > 0,
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** 距离上一次发送还差多久;同一次操作的多段之间不再等待。 */
|
|
220
|
+
private gapDelay(records: SendRecord[], now: number, operation?: string): number {
|
|
221
|
+
const gap = this.config.minGapMs
|
|
222
|
+
if (gap <= 0) return 0
|
|
223
|
+
const last = records[records.length - 1]
|
|
224
|
+
if (!last) return 0
|
|
225
|
+
if (operation !== undefined && last.operation === operation) return 0
|
|
226
|
+
return Math.max(0, gap - (now - last.at))
|
|
227
|
+
}
|
|
228
|
+
}
|
|
@@ -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
|
+
}
|
package/src/sensitive.ts
ADDED
|
@@ -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
|
+
}
|