Skip to content

Commit 5a5de04

Browse files
steipetehugenshen
andcommitted
fix(qqbot): reject unsafe mention patterns
Co-authored-by: hugenshen <[email protected]>
1 parent 6c88469 commit 5a5de04

2 files changed

Lines changed: 116 additions & 9 deletions

File tree

‎extensions/qqbot/src/engine/group/mention.test.ts‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,21 @@
11
// Qqbot tests cover mention plugin behavior.
2-
import { describe, expect, it } from "vitest";
2+
import { afterEach, describe, expect, it, vi } from "vitest";
33
import {
44
detectWasMentioned,
55
hasAnyMention,
66
resolveImplicitMention,
77
stripMentionText,
88
} from "./mention.js";
99

10+
vi.mock("../utils/log.js", () => ({
11+
debugWarn: vi.fn(),
12+
}));
13+
14+
afterEach(() => {
15+
vi.clearAllMocks();
16+
vi.restoreAllMocks();
17+
});
18+
1019
describe("engine/group/mention", () => {
1120
describe("detectWasMentioned", () => {
1221
it("returns true when mentions contains is_you", () => {
@@ -39,6 +48,50 @@ describe("engine/group/mention", () => {
3948
expect(detectWasMentioned({ content: "hi", mentionPatterns: ["[", "@bot"] })).toBe(false);
4049
});
4150

51+
it("rejects ReDoS patterns via compileSafeRegexDetailed guard", () => {
52+
// "(a+)+" has nested repetition — catastrophic backtracking on long input.
53+
// The guard must reject it (return false) rather than hang.
54+
const longInput = "a".repeat(64);
55+
expect(detectWasMentioned({ content: longInput, mentionPatterns: ["(a+)+$"] })).toBe(false);
56+
});
57+
58+
it("still matches safe patterns after a rejected unsafe one", () => {
59+
// Unsafe pattern is skipped; the next safe pattern should still match.
60+
expect(
61+
detectWasMentioned({
62+
content: "hello @bot",
63+
mentionPatterns: ["(a+)+$", "@bot"],
64+
}),
65+
).toBe(true);
66+
});
67+
68+
it("emits a debugWarn with the rejection reason for each rejected pattern", async () => {
69+
const { debugWarn } = await import("../utils/log.js");
70+
detectWasMentioned({
71+
content: "hi",
72+
mentionPatterns: ["(b+)+$", "[invalid", "@safe"],
73+
});
74+
expect(debugWarn).toHaveBeenCalledTimes(2);
75+
expect(vi.mocked(debugWarn).mock.calls[0]![0]).toContain("unsafe-nested-repetition");
76+
expect(vi.mocked(debugWarn).mock.calls[0]![0]).toMatch(/\(b\+\)\+\$/);
77+
expect(vi.mocked(debugWarn).mock.calls[1]![0]).toContain("invalid-regex");
78+
expect(vi.mocked(debugWarn).mock.calls[1]![0]).toMatch(/\[invalid/);
79+
});
80+
81+
it("does not re-warn rejected mentionPatterns on every message", async () => {
82+
const { debugWarn } = await import("../utils/log.js");
83+
const input = {
84+
content: "hi",
85+
mentionPatterns: ["(c+)+$", "@safe"],
86+
};
87+
88+
detectWasMentioned(input);
89+
detectWasMentioned(input);
90+
91+
expect(debugWarn).toHaveBeenCalledTimes(1);
92+
expect(vi.mocked(debugWarn).mock.calls[0]![0]).toMatch(/\(c\+\)\+\$/);
93+
});
94+
4295
it("matches case-insensitively", () => {
4396
expect(detectWasMentioned({ content: "Hello @Bot", mentionPatterns: ["@bot"] })).toBe(true);
4497
});

‎extensions/qqbot/src/engine/group/mention.ts‎

Lines changed: 62 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
// Qqbot plugin module implements mention behavior.
2+
import {
3+
compileSafeRegexDetailed,
4+
type SafeRegexRejectReason,
5+
} from "openclaw/plugin-sdk/security-runtime";
6+
import { debugWarn } from "../utils/log.js";
27
export interface RawMention {
38
is_you?: boolean;
49
bot?: boolean;
@@ -23,6 +28,60 @@ interface HasAnyMentionInput {
2328
}
2429

2530
const MENTION_TAG_RE = /<@!?\w+>/;
31+
const MENTION_PATTERN_FLAGS = "i";
32+
const MAX_MENTION_PATTERN_CACHE_KEYS = 256;
33+
const MAX_MENTION_PATTERN_WARNING_KEYS = 256;
34+
const mentionPatternCompileCache = new Map<string, RegExp[]>();
35+
const rejectedMentionPatternWarningCache = new Set<string>();
36+
37+
type MentionPatternRejectReason = Exclude<SafeRegexRejectReason, "empty">;
38+
39+
function warnRejectedMentionPattern(pattern: string, reason: MentionPatternRejectReason): void {
40+
const key = `${MENTION_PATTERN_FLAGS}::${reason}::${pattern}`;
41+
if (rejectedMentionPatternWarningCache.has(key)) {
42+
return;
43+
}
44+
rejectedMentionPatternWarningCache.add(key);
45+
if (rejectedMentionPatternWarningCache.size > MAX_MENTION_PATTERN_WARNING_KEYS) {
46+
rejectedMentionPatternWarningCache.clear();
47+
rejectedMentionPatternWarningCache.add(key);
48+
}
49+
debugWarn(`qqbot: mentionPattern rejected (${reason}): ${pattern}`);
50+
}
51+
52+
function cacheMentionPatterns(cacheKey: string, regexes: RegExp[]): RegExp[] {
53+
mentionPatternCompileCache.set(cacheKey, regexes);
54+
if (mentionPatternCompileCache.size > MAX_MENTION_PATTERN_CACHE_KEYS) {
55+
mentionPatternCompileCache.clear();
56+
mentionPatternCompileCache.set(cacheKey, regexes);
57+
}
58+
return regexes;
59+
}
60+
61+
function compileMentionPatterns(patterns: string[]): RegExp[] {
62+
if (patterns.length === 0) {
63+
return [];
64+
}
65+
const cacheKey = patterns.join("\u001f");
66+
const cached = mentionPatternCompileCache.get(cacheKey);
67+
if (cached) {
68+
return cached;
69+
}
70+
71+
const regexes: RegExp[] = [];
72+
for (const pattern of patterns) {
73+
const result = compileSafeRegexDetailed(pattern, MENTION_PATTERN_FLAGS);
74+
if (result.reason === "empty") {
75+
continue;
76+
}
77+
if (result.regex) {
78+
regexes.push(result.regex);
79+
continue;
80+
}
81+
warnRejectedMentionPattern(result.source, result.reason);
82+
}
83+
return cacheMentionPatterns(cacheKey, regexes);
84+
}
2685

2786
export function detectWasMentioned(input: DetectWasMentionedInput): boolean {
2887
const { eventType, mentions, content, mentionPatterns } = input;
@@ -36,15 +95,10 @@ export function detectWasMentioned(input: DetectWasMentionedInput): boolean {
3695
}
3796

3897
if (mentionPatterns?.length && content) {
39-
for (const pattern of mentionPatterns) {
40-
if (!pattern) {
41-
continue;
98+
for (const regex of compileMentionPatterns(mentionPatterns)) {
99+
if (regex.test(content)) {
100+
return true;
42101
}
43-
try {
44-
if (new RegExp(pattern, "i").test(content)) {
45-
return true;
46-
}
47-
} catch {}
48102
}
49103
}
50104

0 commit comments

Comments
 (0)