@cmach_socket/opencode-qq-bot 0.5.1 → 0.6.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/rate-limit.ts CHANGED
@@ -6,6 +6,8 @@ import type { RateLimitConfig } from "./config"
6
6
  const MINUTE_MS = 60_000
7
7
  /** 一小时的毫秒数。 */
8
8
  const HOUR_MS = 60 * MINUTE_MS
9
+ /** 等待窗口结束时最多重算几次,兜底防止时钟不前进时死循环。 */
10
+ const MAX_STALL_ATTEMPTS = 5
9
11
 
10
12
  /** 限流判定结果。 */
11
13
  export interface RateLimitVerdict {
@@ -15,6 +17,8 @@ export interface RateLimitVerdict {
15
17
  reason: string
16
18
  /** 为了放行这次发送实际等待的毫秒数。 */
17
19
  waitedMs: number
20
+ /** 这次放行是否靠等待窗口结束换来的。 */
21
+ stalled: boolean
18
22
  }
19
23
 
20
24
  /** 一次出站发送的记录。 */
@@ -114,39 +118,102 @@ export class SendRateLimiter {
114
118
  await this.lock(scope).runExclusive(() => this.admit(scope, operation, false))
115
119
  }
116
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
+
117
137
  /** 判定并记账一次发送。 */
118
138
  private async admit(
119
139
  scope: string,
120
140
  operation: string | undefined,
121
141
  enforce: boolean,
122
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
+
123
152
  const now = this.currentTime
124
153
  const records = this.recent(scope, now)
125
- if (enforce) {
126
- const minute = records.filter((record) => now - record.at < MINUTE_MS).length
127
- if (this.config.maxPerMinute > 0 && minute >= this.config.maxPerMinute) {
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) {
128
176
  return {
129
177
  allowed: false,
130
- reason: `发送频率超限:本分钟已发出 ${minute} 条,最多为每分钟 ${this.config.maxPerMinute} 条。请停止发送并结束本轮。`,
131
- waitedMs: 0,
178
+ reason: `发送频率超限:本小时已发出 ${records.length} 条,最多为每小时 ${this.config.maxPerHour} 条。请停止发送并结束本轮。`,
179
+ waitedMs,
180
+ stalled: waitedMs > 0,
132
181
  }
133
182
  }
134
- if (this.config.maxPerHour > 0 && records.length >= this.config.maxPerHour) {
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) {
135
188
  return {
136
189
  allowed: false,
137
- reason: `发送频率超限:本小时已发出 ${records.length} 条,最多为每小时 ${this.config.maxPerHour} 条。请停止发送并结束本轮。`,
138
- waitedMs: 0,
190
+ reason: `发送频率超限:本分钟已发出 ${minute.length} 条,最多为每分钟 ${this.config.maxPerMinute} 条。请停止发送并结束本轮。`,
191
+ waitedMs,
192
+ stalled: false,
139
193
  }
140
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,
141
216
  }
142
-
143
- const waitedMs = this.gapDelay(records, now, operation)
144
- if (waitedMs > 0) await this.wait(waitedMs)
145
- this.records.set(scope, [
146
- ...records,
147
- { at: this.currentTime, ...(operation ? { operation } : {}) },
148
- ])
149
- return { allowed: true, reason: "", waitedMs }
150
217
  }
151
218
 
152
219
  /** 距离上一次发送还差多久;同一次操作的多段之间不再等待。 */
package/src/sensitive.ts CHANGED
@@ -27,8 +27,13 @@ const CLEAN: SensitiveVerdict = { allowed: true, hits: [], reason: "" }
27
27
  */
28
28
  const PII_DETECTORS = new Set(["email", "obfuscated_email", "credit_card", "iban"])
29
29
 
30
- /** 默认关闭、但确实算凭证的检测器。 */
31
- const EXTRA_SECRET_DETECTORS = new Set(["seed_phrase"])
30
+ /**
31
+ * 默认关闭、但确实算凭证的检测器。
32
+ *
33
+ * `internal_url` 会命中 localhost 与内网地址:本插件的威胁模型里,
34
+ * 内网地址泄漏到日志或出站消息同样算问题,所以显式打开。
35
+ */
36
+ const EXTRA_SECRET_DETECTORS = new Set(["seed_phrase", "internal_url"])
32
37
 
33
38
  /**
34
39
  * 出站要跑的检测器。
@@ -75,7 +80,17 @@ const SENSITIVE_PATH_PARTS = [
75
80
  ".env",
76
81
  "id_rsa",
77
82
  "id_ed25519",
83
+ "id_ecdsa",
84
+ "id_dsa",
78
85
  ".pem",
86
+ ".p12",
87
+ ".pfx",
88
+ ".jks",
89
+ ".keystore",
90
+ ".pgpass",
91
+ ".my.cnf",
92
+ ".htpasswd",
93
+ "credentials.db",
79
94
  ]
80
95
 
81
96
  function escapeRegExp(value: string): string {
@@ -117,6 +132,51 @@ export function collectEnvSecrets(env: Record<string, string | undefined>): stri
117
132
  return secrets
118
133
  }
119
134
 
135
+ /** URL 里可能带凭证的查询参数名。 */
136
+ const SECRET_QUERY_KEYS =
137
+ /^(?:token|access[_-]?token|refresh[_-]?token|auth|authorization|secret|secret[_-]?key|key|api[_-]?key|pass(?:word)?|signature|sig|credential)s?$/i
138
+
139
+ /**
140
+ * 把 URL 里的凭证抹掉,只留下能定位服务的部分。
141
+ *
142
+ * 日志里打印 NapCat 地址时用:token 常常就挂在查询串或 userinfo 上。
143
+ */
144
+ export function redactUrl(url: string): string {
145
+ try {
146
+ const parsed = new URL(url)
147
+ parsed.username = ""
148
+ parsed.password = ""
149
+ parsed.search = ""
150
+ parsed.hash = ""
151
+ return parsed.toString()
152
+ } catch {
153
+ return "[无法解析的地址]"
154
+ }
155
+ }
156
+
157
+ /**
158
+ * 取出 URL 里可能带凭证的值。
159
+ *
160
+ * 这些值要加进已知凭证,日志里的同一段内容才会被逐行打码。
161
+ */
162
+ export function secretsFromUrl(url: string): string[] {
163
+ const secrets: string[] = []
164
+ try {
165
+ const parsed = new URL(url)
166
+ for (const [name, value] of parsed.searchParams) {
167
+ if (!SECRET_QUERY_KEYS.test(name)) continue
168
+ if (!value || value.length < MIN_SECRET_LENGTH) continue
169
+ secrets.push(value)
170
+ }
171
+ for (const part of [parsed.username, parsed.password]) {
172
+ if (part && part.length >= MIN_SECRET_LENGTH) secrets.push(part)
173
+ }
174
+ } catch {
175
+ // 地址解析不了就没有凭证可取。
176
+ }
177
+ return secrets
178
+ }
179
+
120
180
  /** 已知凭证明文写成的检测器。 */
121
181
  function knownSecretDetector(secrets: string[]): Detector | undefined {
122
182
  if (secrets.length === 0) return undefined
@@ -135,7 +195,7 @@ const SENSITIVE_PATH_DETECTOR: Detector = {
135
195
  label: "Sensitive path",
136
196
  why: "指向凭证文件的路径",
137
197
  pattern: new RegExp(
138
- `(?:^|[\\s"'\`(=])[^\\s"'\`,;]*?(?:${SENSITIVE_PATH_PARTS.map(escapeRegExp).join("|")})(?:[/\\\\]|$)`,
198
+ `(?:^|[\\s"'\`(=])[^\\s"'\`,;]*?(?:${SENSITIVE_PATH_PARTS.map(escapeRegExp).join("|")})(?:[/\\\\]|\\b|$)`,
139
199
  "i",
140
200
  ),
141
201
  default: true,