@cmach_socket/opencode-qq-bot 0.6.4 → 0.6.7
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/README.md +12 -8
- package/package.json +1 -1
- package/src/access.ts +0 -5
- package/src/async.ts +25 -0
- package/src/cleanup.ts +74 -0
- package/src/commands.ts +8 -13
- package/src/config.ts +36 -83
- package/src/emoji/command.ts +0 -2
- package/src/emoji/label.ts +10 -22
- package/src/events/notice.ts +0 -19
- package/src/home.ts +8 -6
- package/src/index.ts +654 -582
- package/src/keepalive.ts +10 -24
- package/src/logger.ts +2 -1
- package/src/media-path.ts +2 -4
- package/src/model-view.ts +2 -2
- package/src/naplink/client.ts +38 -0
- package/src/naplink/media.ts +4 -8
- package/src/naplink/render.ts +41 -53
- package/src/overrides.ts +6 -17
- package/src/rate-limit.ts +2 -1
- package/src/safe-fetch.ts +1 -5
- package/src/sensitive.ts +3 -5
- package/src/session/find.ts +45 -0
- package/src/session/manager.ts +70 -93
- package/src/session/proactive.ts +8 -11
- package/src/session/soul.ts +54 -31
- package/src/text.ts +7 -0
- package/src/tools/policy.ts +6 -0
- package/src/tools/qq.ts +111 -53
- package/src/tui-commands.ts +1 -1
package/src/keepalive.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { Plugin } from "@opencode/plugin"
|
|
2
|
+
import { unrefTimer } from "./async"
|
|
2
3
|
import type { QQBotConfig } from "./config"
|
|
3
4
|
import type { Logger } from "./logger"
|
|
5
|
+
import { findSession } from "./session/find"
|
|
4
6
|
|
|
5
7
|
/** 插件存储里保存保活会话 ID 的键。 */
|
|
6
8
|
export const KEEP_ALIVE_SESSION_KEY = "keepalive-session"
|
|
@@ -9,8 +11,6 @@ export const KEEP_ALIVE_SESSION_MARKER = "qqKeepAliveSession"
|
|
|
9
11
|
/** 保活会话标题。 */
|
|
10
12
|
export const KEEP_ALIVE_TITLE = "QQ 保活"
|
|
11
13
|
|
|
12
|
-
type SessionListCursor = NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["cursor"]
|
|
13
|
-
|
|
14
14
|
/**
|
|
15
15
|
* 保活心跳:让 OpenCode 不要因为长时间没有会话活动而卸载插件。
|
|
16
16
|
*
|
|
@@ -38,8 +38,7 @@ export class KeepAlive {
|
|
|
38
38
|
this.timer = setInterval(() => {
|
|
39
39
|
void this.ping()
|
|
40
40
|
}, this.config.keepAlive.seconds * 1000)
|
|
41
|
-
|
|
42
|
-
handle.unref?.()
|
|
41
|
+
unrefTimer(this.timer)
|
|
43
42
|
}
|
|
44
43
|
|
|
45
44
|
/**
|
|
@@ -179,26 +178,13 @@ export class KeepAlive {
|
|
|
179
178
|
|
|
180
179
|
/** 查找带保活标记的历史会话。 */
|
|
181
180
|
private async findKeepAliveSession(): Promise<string | undefined> {
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
...(cursor ? { cursor } : {}),
|
|
190
|
-
})
|
|
191
|
-
const hit = result.data.find(
|
|
192
|
-
(session) => session.metadata?.[KEEP_ALIVE_SESSION_MARKER] === true,
|
|
193
|
-
)
|
|
194
|
-
if (hit) return hit.id
|
|
195
|
-
cursor = result.cursor.next ?? undefined
|
|
196
|
-
if (!cursor) break
|
|
197
|
-
}
|
|
198
|
-
} catch (error) {
|
|
199
|
-
this.logger.warn("查找保活会话失败", error)
|
|
200
|
-
}
|
|
201
|
-
return undefined
|
|
181
|
+
return await findSession(
|
|
182
|
+
this.ctx,
|
|
183
|
+
this.ctx.location.directory,
|
|
184
|
+
(session) => session.metadata?.[KEEP_ALIVE_SESSION_MARKER] === true,
|
|
185
|
+
this.logger,
|
|
186
|
+
"查找保活会话失败",
|
|
187
|
+
)
|
|
202
188
|
}
|
|
203
189
|
|
|
204
190
|
private async writeStoredSession(sessionID: string): Promise<void> {
|
package/src/logger.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { isAbsolute, join } from "node:path"
|
|
|
4
4
|
import { inspect } from "node:util"
|
|
5
5
|
import winston from "winston"
|
|
6
6
|
import DailyRotateFile from "winston-daily-rotate-file"
|
|
7
|
+
import { unrefTimer } from "./async"
|
|
7
8
|
import { maskSecrets } from "./sensitive"
|
|
8
9
|
|
|
9
10
|
/** 日志级别。 */
|
|
@@ -240,7 +241,7 @@ export function createLogger(prefix: string, options: LoggerOptions | LogLevel =
|
|
|
240
241
|
function waitFinish(transport: DailyRotateFile): Promise<void> {
|
|
241
242
|
return new Promise<void>((resolve) => {
|
|
242
243
|
const timer = setTimeout(() => resolve(), CLOSE_TIMEOUT_MS)
|
|
243
|
-
timer
|
|
244
|
+
unrefTimer(timer)
|
|
244
245
|
transport.once("finish", () => {
|
|
245
246
|
clearTimeout(timer)
|
|
246
247
|
resolve()
|
package/src/media-path.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { realpath, stat } from "node:fs/promises"
|
|
|
3
3
|
import { homedir } from "node:os"
|
|
4
4
|
import { isAbsolute, join, resolve, sep } from "node:path"
|
|
5
5
|
import ipaddr from "ipaddr.js"
|
|
6
|
+
import { expandTilde } from "./home"
|
|
6
7
|
import { ALLOWED_PORTS } from "./safe-fetch"
|
|
7
8
|
|
|
8
9
|
/**
|
|
@@ -32,10 +33,7 @@ export type MediaPlan = { kind: "local"; path: string } | { kind: "remote"; url:
|
|
|
32
33
|
|
|
33
34
|
/** 展开 `~` 并去掉首尾空白。 */
|
|
34
35
|
function expand(value: string): string {
|
|
35
|
-
|
|
36
|
-
if (trimmed === "~") return homedir()
|
|
37
|
-
if (trimmed.startsWith("~/")) return join(homedir(), trimmed.slice(2))
|
|
38
|
-
return trimmed
|
|
36
|
+
return expandTilde(value.trim())
|
|
39
37
|
}
|
|
40
38
|
|
|
41
39
|
/**
|
package/src/model-view.ts
CHANGED
|
@@ -9,13 +9,13 @@
|
|
|
9
9
|
* 群友把 `<quote>` 拆成两段发过来,逐段净化匹配不到,只有整体净化才拦得住。
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import { ZERO_WIDTH } from "./text"
|
|
13
|
+
|
|
12
14
|
/** 提示词里的结构标签;群友文本里出现同样字样时换成全角,避免伪造。 */
|
|
13
15
|
const STRUCTURE_TAG = /<\/?(quote|forward|history)>/gi
|
|
14
16
|
|
|
15
17
|
/** 换行类字符:换行、段分隔符、下一行、垂直制表、换页。 */
|
|
16
18
|
const NEWLINE_LIKE = /[\r\n\u2028\u2029\u0085\u000B\u000C]+/g
|
|
17
|
-
/** 零宽字符:可以用来把标签拆成看起来正常、匹配不上的形式。 */
|
|
18
|
-
const ZERO_WIDTH = /[\u200B-\u200F\u2060\uFEFF]/g
|
|
19
19
|
/** 控制字符:显示名里出现会破坏结构。 */
|
|
20
20
|
const CONTROL = /[\u0000-\u001F\u007F]+/g
|
|
21
21
|
/** 私用区字符:插件用它给结构标签占位,群友文本里的必须清掉,否则能伪造占位符。 */
|
package/src/naplink/client.ts
CHANGED
|
@@ -29,6 +29,17 @@ function isMediaSegmentType(type: string): type is MediaSegmentType {
|
|
|
29
29
|
return (MEDIA_SEGMENT_TYPES as readonly string[]).includes(type)
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
/** 把 SDK 事件里的关键字段摘出来,便于日志排查。 */
|
|
33
|
+
function describeEvent(event: unknown): Record<string, unknown> {
|
|
34
|
+
if (!event || typeof event !== "object") return {}
|
|
35
|
+
const record = event as Record<string, unknown>
|
|
36
|
+
const result: Record<string, unknown> = {}
|
|
37
|
+
for (const key of ["code", "reason", "attempt", "delay", "url"]) {
|
|
38
|
+
if (record[key] !== undefined) result[key] = record[key]
|
|
39
|
+
}
|
|
40
|
+
return result
|
|
41
|
+
}
|
|
42
|
+
|
|
32
43
|
/** 取第一个可下载的 http(s) 直链,忽略本地路径与 base64。 */
|
|
33
44
|
export function pickRemoteUrl(...values: unknown[]): string | undefined {
|
|
34
45
|
for (const value of values) {
|
|
@@ -110,6 +121,19 @@ export class QQClient {
|
|
|
110
121
|
)
|
|
111
122
|
})
|
|
112
123
|
})
|
|
124
|
+
// 断线与重连要能看到:发送失败往往是因为连接在那一刻正好断了。
|
|
125
|
+
this.link.on("disconnect", (event: unknown) => {
|
|
126
|
+
this.logger.warn("NapCat 连接断开", describeEvent(event))
|
|
127
|
+
})
|
|
128
|
+
this.link.on("reconnecting", (event: unknown) => {
|
|
129
|
+
this.logger.info("NapCat 正在重连", describeEvent(event))
|
|
130
|
+
})
|
|
131
|
+
this.link.on("connection:restored", (event: unknown) => {
|
|
132
|
+
this.logger.info("NapCat 连接已恢复", describeEvent(event))
|
|
133
|
+
})
|
|
134
|
+
this.link.on("connection:lost", (event: unknown) => {
|
|
135
|
+
this.logger.error("NapCat 连接丢失", describeEvent(event))
|
|
136
|
+
})
|
|
113
137
|
}
|
|
114
138
|
|
|
115
139
|
get api(): OneBotApi {
|
|
@@ -135,6 +159,20 @@ export class QQClient {
|
|
|
135
159
|
await this.refreshBotId()
|
|
136
160
|
}
|
|
137
161
|
|
|
162
|
+
/**
|
|
163
|
+
* 发送前确保连接可用。
|
|
164
|
+
*
|
|
165
|
+
* NapLink 在正常关闭(code 1000)后不会自动重连,这时发送会报
|
|
166
|
+
* 「连接未建立,请先调用 connect()」。这里补一次连接。
|
|
167
|
+
*
|
|
168
|
+
* @returns 连接是否可用。
|
|
169
|
+
*/
|
|
170
|
+
async ensureConnected(): Promise<boolean> {
|
|
171
|
+
if (this.connected) return true
|
|
172
|
+
this.logger.info("NapCat 未连接,发送前先重连")
|
|
173
|
+
return await this.connectSafe()
|
|
174
|
+
}
|
|
175
|
+
|
|
138
176
|
/** 读取机器人自己的 QQ 号,并发调用时复用同一个请求。 */
|
|
139
177
|
private refreshBotId(): Promise<void> {
|
|
140
178
|
this.botIdRequest ??= this.loadBotId().finally(() => {
|
package/src/naplink/media.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { pathToFileURL } from "node:url"
|
|
|
5
5
|
import type { Logger } from "../logger"
|
|
6
6
|
import { defaultMediaDir } from "../media-path"
|
|
7
7
|
import { type SafeFetcher, safeFetchBytes } from "../safe-fetch"
|
|
8
|
+
import { truncateForLog } from "../text"
|
|
8
9
|
|
|
9
10
|
/** 单张图片下载与落盘的字节上限。 */
|
|
10
11
|
export const MAX_IMAGE_BYTES = 5 * 1024 * 1024
|
|
@@ -84,12 +85,7 @@ function truncateCodePoints(text: string, max: number): string {
|
|
|
84
85
|
return Array.from(text).slice(0, max).join("")
|
|
85
86
|
}
|
|
86
87
|
|
|
87
|
-
|
|
88
|
-
function truncateForLog(value: string, max = 120): string {
|
|
89
|
-
return value.length > max ? `${value.slice(0, max)}…` : value
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
function decodeBase64(value: string): Uint8Array | undefined {
|
|
88
|
+
function decodeBase64Bytes(value: string): Uint8Array | undefined {
|
|
93
89
|
if (!/^[A-Za-z0-9+/]*={0,2}$/u.test(value)) return undefined
|
|
94
90
|
const bytes = Buffer.from(value, "base64")
|
|
95
91
|
return bytes.byteLength > MAX_IMAGE_BYTES ? undefined : new Uint8Array(bytes)
|
|
@@ -98,7 +94,7 @@ function decodeBase64(value: string): Uint8Array | undefined {
|
|
|
98
94
|
function parseDataUrl(uri: string, logger: Logger): ImageBytes | undefined {
|
|
99
95
|
const match = /^data:([^;,]+)?(?:;[^,]*)*;base64,(.*)$/s.exec(uri)
|
|
100
96
|
if (!match) return undefined
|
|
101
|
-
const bytes =
|
|
97
|
+
const bytes = decodeBase64Bytes(match[2] ?? "")
|
|
102
98
|
if (!bytes) return undefined
|
|
103
99
|
// 以魔数嗅探为准:URI 里声明的类型由消息发送方控制,不能直接信任。
|
|
104
100
|
const mime = mimeFromBytes(bytes)
|
|
@@ -143,7 +139,7 @@ export class MediaStore {
|
|
|
143
139
|
|
|
144
140
|
private async readImage(url: string): Promise<ImageBytes | undefined> {
|
|
145
141
|
if (url.startsWith("base64://")) {
|
|
146
|
-
const bytes =
|
|
142
|
+
const bytes = decodeBase64Bytes(url.slice("base64://".length))
|
|
147
143
|
if (!bytes) {
|
|
148
144
|
this.logger.warn("base64 图片无效或超过大小上限")
|
|
149
145
|
return undefined
|
package/src/naplink/render.ts
CHANGED
|
@@ -20,7 +20,6 @@ import {
|
|
|
20
20
|
type StoredImage,
|
|
21
21
|
} from "./media"
|
|
22
22
|
|
|
23
|
-
export { MAX_IMAGE_BYTES, inlineImageBytes }
|
|
24
23
|
export type { PromptFile } from "./media"
|
|
25
24
|
|
|
26
25
|
/** 合并转发的解析上限,避免撑爆上下文。 */
|
|
@@ -227,6 +226,36 @@ function createForwardBudget(): ForwardBudget {
|
|
|
227
226
|
return { nodes: MAX_FORWARD_TOTAL_NODES, chars: MAX_FORWARD_TOTAL_CHARS }
|
|
228
227
|
}
|
|
229
228
|
|
|
229
|
+
/**
|
|
230
|
+
* 只产出文字、不涉及媒体与上游的消息段描述。
|
|
231
|
+
*
|
|
232
|
+
* 转发内容与普通消息共用,保证两边对同一种段落的措辞一致。
|
|
233
|
+
*
|
|
234
|
+
* @returns 段落文本;需要特殊处理(@、图片、语音、引用、转发)时返回 `undefined`。
|
|
235
|
+
*/
|
|
236
|
+
function describeSegment(segment: Segment): string | undefined {
|
|
237
|
+
switch (segment.type) {
|
|
238
|
+
case "text":
|
|
239
|
+
return sanitizeUntrustedText(segment.data.text)
|
|
240
|
+
case "video":
|
|
241
|
+
return "[视频]"
|
|
242
|
+
case "audio":
|
|
243
|
+
return "[音频]"
|
|
244
|
+
case "file":
|
|
245
|
+
return `[文件]${sanitizeUntrustedText(segment.data.name || segment.data.file)}`
|
|
246
|
+
case "face":
|
|
247
|
+
return renderFace(segment.data.id)
|
|
248
|
+
case "json":
|
|
249
|
+
return "[卡片消息]"
|
|
250
|
+
case "xml":
|
|
251
|
+
return "[XML消息]"
|
|
252
|
+
case "markdown":
|
|
253
|
+
return "[Markdown消息]"
|
|
254
|
+
default:
|
|
255
|
+
return undefined
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
230
259
|
async function renderForwardSegments(
|
|
231
260
|
ctx: RenderContext,
|
|
232
261
|
message: readonly MessageSegment[],
|
|
@@ -239,10 +268,12 @@ async function renderForwardSegments(
|
|
|
239
268
|
const images: StoredImage[] = []
|
|
240
269
|
for (const segment of segments(message)) {
|
|
241
270
|
try {
|
|
271
|
+
const described = describeSegment(segment)
|
|
272
|
+
if (described !== undefined) {
|
|
273
|
+
parts.push(described)
|
|
274
|
+
continue
|
|
275
|
+
}
|
|
242
276
|
switch (segment.type) {
|
|
243
|
-
case "text":
|
|
244
|
-
parts.push(sanitizeUntrustedText(segment.data.text))
|
|
245
|
-
break
|
|
246
277
|
case "at":
|
|
247
278
|
parts.push(`@${segment.data.qq} `)
|
|
248
279
|
break
|
|
@@ -260,27 +291,6 @@ async function renderForwardSegments(
|
|
|
260
291
|
case "record":
|
|
261
292
|
parts.push("[语音]")
|
|
262
293
|
break
|
|
263
|
-
case "video":
|
|
264
|
-
parts.push("[视频]")
|
|
265
|
-
break
|
|
266
|
-
case "audio":
|
|
267
|
-
parts.push("[音频]")
|
|
268
|
-
break
|
|
269
|
-
case "file":
|
|
270
|
-
parts.push(`[文件]${sanitizeUntrustedText(segment.data.name || segment.data.file)}`)
|
|
271
|
-
break
|
|
272
|
-
case "face":
|
|
273
|
-
parts.push(renderFace(segment.data.id))
|
|
274
|
-
break
|
|
275
|
-
case "json":
|
|
276
|
-
parts.push("[卡片消息]")
|
|
277
|
-
break
|
|
278
|
-
case "xml":
|
|
279
|
-
parts.push("[XML消息]")
|
|
280
|
-
break
|
|
281
|
-
case "markdown":
|
|
282
|
-
parts.push("[Markdown消息]")
|
|
283
|
-
break
|
|
284
294
|
case "reply":
|
|
285
295
|
// 转发节点里的引用没有上下文,跳过
|
|
286
296
|
break
|
|
@@ -387,10 +397,7 @@ export async function renderForward(
|
|
|
387
397
|
}
|
|
388
398
|
|
|
389
399
|
/** 把语音消息转成文字,转写失败时返回空字符串。 */
|
|
390
|
-
|
|
391
|
-
ctx: RenderContext,
|
|
392
|
-
messageId: number | undefined,
|
|
393
|
-
): Promise<string> {
|
|
400
|
+
async function fetchVoiceText(ctx: RenderContext, messageId: number | undefined): Promise<string> {
|
|
394
401
|
if (messageId === undefined) return ""
|
|
395
402
|
try {
|
|
396
403
|
const result = await ctx.api.fetchPttText(messageId)
|
|
@@ -461,10 +468,12 @@ export async function renderMessage(
|
|
|
461
468
|
|
|
462
469
|
for (const segment of message) {
|
|
463
470
|
try {
|
|
471
|
+
const described = describeSegment(segment)
|
|
472
|
+
if (described !== undefined) {
|
|
473
|
+
textBuffer.push(described)
|
|
474
|
+
continue
|
|
475
|
+
}
|
|
464
476
|
switch (segment.type) {
|
|
465
|
-
case "text":
|
|
466
|
-
textBuffer.push(sanitizeUntrustedText(segment.data.text))
|
|
467
|
-
break
|
|
468
477
|
case "at":
|
|
469
478
|
textBuffer.push(
|
|
470
479
|
`@${sanitizeSenderName(await resolveUserName(ctx, String(segment.data.qq)))} `,
|
|
@@ -516,27 +525,6 @@ export async function renderMessage(
|
|
|
516
525
|
}
|
|
517
526
|
break
|
|
518
527
|
}
|
|
519
|
-
case "video":
|
|
520
|
-
textBuffer.push("[视频]")
|
|
521
|
-
break
|
|
522
|
-
case "audio":
|
|
523
|
-
textBuffer.push("[音频]")
|
|
524
|
-
break
|
|
525
|
-
case "file":
|
|
526
|
-
textBuffer.push(`[文件]${sanitizeUntrustedText(segment.data.name || segment.data.file)}`)
|
|
527
|
-
break
|
|
528
|
-
case "face":
|
|
529
|
-
textBuffer.push(renderFace(segment.data.id))
|
|
530
|
-
break
|
|
531
|
-
case "json":
|
|
532
|
-
textBuffer.push("[卡片消息]")
|
|
533
|
-
break
|
|
534
|
-
case "xml":
|
|
535
|
-
textBuffer.push("[XML消息]")
|
|
536
|
-
break
|
|
537
|
-
case "markdown":
|
|
538
|
-
textBuffer.push("[Markdown消息]")
|
|
539
|
-
break
|
|
540
528
|
default:
|
|
541
529
|
ctx.logger.debug(`跳过未知消息段 type=${(segment as { type: string }).type}`)
|
|
542
530
|
break
|
package/src/overrides.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { readFile, stat } from "node:fs/promises"
|
|
2
2
|
import { join } from "node:path"
|
|
3
3
|
import { type ChatTarget, targetKey } from "./chat"
|
|
4
|
-
import { parseModelRef, type ModelRef } from "./config"
|
|
4
|
+
import { DEFAULT_CONFIG, parseModelRef, type ModelRef, type WakeConfig } from "./config"
|
|
5
5
|
import type { Logger } from "./logger"
|
|
6
6
|
|
|
7
7
|
/** 唤醒方式:决定群里的消息要不要让模型必须回复。 */
|
|
@@ -27,24 +27,13 @@ export interface WakeContext {
|
|
|
27
27
|
text: string
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
/**
|
|
31
|
-
export
|
|
32
|
-
/** 全局唤醒前缀,命中即必回。 */
|
|
33
|
-
prefixes: string[]
|
|
34
|
-
/** 是否忽略 @全体成员。 */
|
|
35
|
-
ignoreAtAll: boolean
|
|
36
|
-
/** 回复机器人自己的消息是否必回。 */
|
|
37
|
-
replyToSelf: boolean
|
|
38
|
-
/** 群里第一个 @ 指向别人时是否不唤醒机器人。 */
|
|
39
|
-
ignoreAtOthers: boolean
|
|
40
|
-
}
|
|
30
|
+
/** 全局唤醒策略:与配置项 `wake` 同构。 */
|
|
31
|
+
export type WakePolicy = WakeConfig
|
|
41
32
|
|
|
42
|
-
/**
|
|
33
|
+
/** 内置的全局唤醒策略,取自配置默认值。 */
|
|
43
34
|
export const DEFAULT_WAKE_POLICY: WakePolicy = {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
replyToSelf: true,
|
|
47
|
-
ignoreAtOthers: true,
|
|
35
|
+
...DEFAULT_CONFIG.wake,
|
|
36
|
+
prefixes: [...DEFAULT_CONFIG.wake.prefixes],
|
|
48
37
|
}
|
|
49
38
|
|
|
50
39
|
/** 唤醒判定的结果。 */
|
package/src/rate-limit.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Mutex } from "async-mutex"
|
|
2
|
+
import { delay } from "./async"
|
|
2
3
|
import { type ChatTarget, targetKey } from "./chat"
|
|
3
4
|
import type { RateLimitConfig } from "./config"
|
|
4
5
|
|
|
@@ -77,7 +78,7 @@ export class SendRateLimiter {
|
|
|
77
78
|
}
|
|
78
79
|
|
|
79
80
|
private get wait(): (ms: number) => Promise<void> {
|
|
80
|
-
return this.options.sleep ??
|
|
81
|
+
return this.options.sleep ?? delay
|
|
81
82
|
}
|
|
82
83
|
|
|
83
84
|
private lock(scope: string): Mutex {
|
package/src/safe-fetch.ts
CHANGED
|
@@ -2,6 +2,7 @@ import http from "node:http"
|
|
|
2
2
|
import https from "node:https"
|
|
3
3
|
import { useAgent } from "request-filtering-agent"
|
|
4
4
|
import type { Logger } from "./logger"
|
|
5
|
+
import { truncateForLog } from "./text"
|
|
5
6
|
|
|
6
7
|
/** 允许的出站端口:只放行常见的网页端口,其余一律拒绝。 */
|
|
7
8
|
export const ALLOWED_PORTS: readonly number[] = [80, 443, 8080, 8443]
|
|
@@ -36,11 +37,6 @@ export type SafeFetcher = (
|
|
|
36
37
|
options: SafeFetchOptions,
|
|
37
38
|
) => Promise<SafeFetchResult | undefined>
|
|
38
39
|
|
|
39
|
-
/** 截断过长的地址,避免日志被超长 URL 淹没。 */
|
|
40
|
-
function truncateForLog(value: string, max = 120): string {
|
|
41
|
-
return value.length > max ? `${value.slice(0, max)}…` : value
|
|
42
|
-
}
|
|
43
|
-
|
|
44
40
|
/**
|
|
45
41
|
* 下载一个远端文件,挡住指向内网的请求。
|
|
46
42
|
*
|
package/src/sensitive.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { DETECTORS, redact, scan, type Detector } from "flare-redact"
|
|
2
|
+
import { ZERO_WIDTH } from "./text"
|
|
2
3
|
|
|
3
4
|
/** 命中的敏感信息。 */
|
|
4
5
|
export interface SensitiveHit {
|
|
@@ -58,9 +59,6 @@ const MIN_SECRET_LENGTH = 12
|
|
|
58
59
|
/** 已知凭证的分片长度:够长不撞车,又短到能抓住被拆开的凭证。 */
|
|
59
60
|
const FRAGMENT_LENGTH = 12
|
|
60
61
|
|
|
61
|
-
/** 零宽字符:插在凭证中间用来骗过正则。 */
|
|
62
|
-
const ZERO_WIDTH = /[\u200B-\u200F\u2060\uFEFF]/g
|
|
63
|
-
|
|
64
62
|
/** 文本里像 base64 的片段。 */
|
|
65
63
|
const BASE64_RUN = /[A-Za-z0-9+/_-]{20,}={0,2}/g
|
|
66
64
|
|
|
@@ -218,7 +216,7 @@ function looksLikeText(text: string): boolean {
|
|
|
218
216
|
}
|
|
219
217
|
|
|
220
218
|
/** 解一段 base64;解不出人话就返回 undefined。 */
|
|
221
|
-
function
|
|
219
|
+
function decodeBase64Text(input: string): string | undefined {
|
|
222
220
|
const standard = input.replace(/-/g, "+").replace(/_/g, "/")
|
|
223
221
|
const padded = standard + "=".repeat((4 - (standard.length % 4)) % 4)
|
|
224
222
|
const decoded = Buffer.from(padded, "base64").toString("utf8")
|
|
@@ -233,7 +231,7 @@ function base64Variants(text: string): string[] {
|
|
|
233
231
|
const runs = text.match(BASE64_RUN) ?? []
|
|
234
232
|
const variants: string[] = []
|
|
235
233
|
for (const run of runs.slice(0, MAX_BASE64_RUNS)) {
|
|
236
|
-
const decoded =
|
|
234
|
+
const decoded = decodeBase64Text(run)
|
|
237
235
|
if (decoded) variants.push(decoded)
|
|
238
236
|
}
|
|
239
237
|
return variants
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { Plugin } from "@opencode/plugin"
|
|
2
|
+
import type { Logger } from "../logger"
|
|
3
|
+
|
|
4
|
+
/** 会话列表最多翻几页。 */
|
|
5
|
+
const MAX_PAGES = 5
|
|
6
|
+
/** 每页抓多少条。 */
|
|
7
|
+
const PAGE_SIZE = 100
|
|
8
|
+
|
|
9
|
+
type ListResult = Awaited<ReturnType<Plugin.Context["session"]["list"]>>
|
|
10
|
+
/** 会话列表里的单条会话。 */
|
|
11
|
+
export type ListedSession = ListResult["data"][number]
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* 在指定目录下按谓词查找会话。
|
|
15
|
+
*
|
|
16
|
+
* 列表按创建时间倒序、翻页上限固定,避免会话很多时把整个列表拉一遍。
|
|
17
|
+
*
|
|
18
|
+
* @returns 命中的会话 ID;找不到或查询失败时返回 `undefined`。
|
|
19
|
+
*/
|
|
20
|
+
export async function findSession(
|
|
21
|
+
ctx: Plugin.Context,
|
|
22
|
+
directory: NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["directory"],
|
|
23
|
+
match: (session: ListedSession) => boolean,
|
|
24
|
+
logger: Logger,
|
|
25
|
+
failure: string,
|
|
26
|
+
): Promise<string | undefined> {
|
|
27
|
+
let cursor: ListResult["cursor"]["next"] | undefined
|
|
28
|
+
try {
|
|
29
|
+
for (let page = 0; page < MAX_PAGES; page += 1) {
|
|
30
|
+
const result = await ctx.session.list({
|
|
31
|
+
directory,
|
|
32
|
+
limit: PAGE_SIZE,
|
|
33
|
+
order: "desc",
|
|
34
|
+
...(cursor ? { cursor } : {}),
|
|
35
|
+
})
|
|
36
|
+
const hit = result.data.find(match)
|
|
37
|
+
if (hit) return hit.id
|
|
38
|
+
cursor = result.cursor.next ?? undefined
|
|
39
|
+
if (!cursor) break
|
|
40
|
+
}
|
|
41
|
+
} catch (error) {
|
|
42
|
+
logger.warn(failure, error)
|
|
43
|
+
}
|
|
44
|
+
return undefined
|
|
45
|
+
}
|