mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[GH-ISSUE #2930] [Issue]: Regex Scripts safety check rejects many ordinary patterns (and a couple of bad ones), while the truly dangerous ones still get through #1507
Labels
No labels
android
bug
bugfix
ci
client
code freeze pause
container
dependencies
docs
documentation
duplicate
enhancement
feature
feature
feature
feature-creep
fixed-in-refactor
fixed-in-staging
good first issue
help wanted
in-pr
in-pr
needs-codeowner-decision
normal-scope
old-codebase
old-codebase
pull-request
qol
question
refactor
regression
revisit later
roadmap
scope-risk
scope-risk
server
server
shared
soup
upstream
windows
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Pasta-Devs/Marinara-Engine#1507
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Originally created by @kolacheee on GitHub (Jun 28, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2930
Originally assigned to: @SpicyMarinara on GitHub.
The Regex Scripts feature runs a "safety check" (
isPatternSafe) before it will save or apply a pattern. The check is meant to block patterns that can hang the app (catastrophic backtracking / ReDoS). In v2.0.6 it does the opposite of what you'd want in several ways: it lets some genuinely catastrophic patterns through (which can freeze the backend), and it rejects a large set of perfectly normal, fast patterns with a misleading "catastrophic backtracking" error. It also lets a couple of patterns save that then silently do nothing, and one of the two shipped default scripts never runs at all.All findings below were AI-investigated against v2.0.6 by reading the code and running a faithful port of
isPatternSafeplus direct timing of the regexes. Verify the reproduction before fixing.1. Catastrophic patterns slip through and can freeze the backend (no timeout)
What's wrong: A pattern like
(a|a)+$passes the safety check but is genuinely catastrophic. When it runs against a message of repeated characters, it backtracks exponentially and stalls the whole server while it churns — and there is no execution timeout on the regex-script path to stop it.How to reproduce (try it yourself):
findRegex=(a|a)+$,flags=g, placementai_output.acharacters followed by!(e.g.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!).(a|a)*cis catastrophic the same way (28 a's ≈ 3.5s). (Note: the original report also listed(a|a|a)*and(a|ab)*cas examples — these are NOT actually catastrophic on simple input under V8; both measured 0ms. The real trigger is an alternation that repeats an overlapping branch and has a required-fail tail, like the two above.)Where it is:
packages/shared/src/utils/regex-safety.ts:106-141— the group walker only tracks nested-quantifier "star height"; it has no concept of overlapping alternation, soisPatternSafe('(a|a)+$')returnstrue. The pattern is then compiled and run with no guard atpackages/server/src/services/regex/regex-application.ts:118(new RegExp) →:120→String.replaceinpackages/shared/src/utils/regex-replacement.ts:138, awaited inline at the call sites ingenerate.routes.ts(2043/2049/6117/10957),chats.routes.ts:2137, anddry-run-route.ts:872.Why no timeout catches it: A vm-based timeout executor exists (
packages/server/src/services/lorebook/regex-timeout.ts, 50ms cap) but it is only wired into the lorebook keyword scanner (keyword-scanner.ts:15,507,555). The regex-script apply path imports onlyapplyRegexReplacementandisPatternSafeand never uses it — the comment atregex-application.ts:112-113even acknowledges there is no timeout. So a pattern that slips past the static check runs unbounded.Suggested fix: Two layers. (a) Teach
isPatternSafeto reject quantified alternations whose branches overlap (e.g.(a|a)+, more generally repetition over an alternation with a common prefix). (b) Wrap the regex-script execution in the same vm-timeout executor already used by the keyword scanner, so anything that gets past the static check still can't hang the event loop.2. The safety check rejects many ordinary, fast patterns with a misleading error
What's wrong: A whole class of normal, linear-time regexes are rejected at save time with
400 Regex pattern is unsafe: it may cause catastrophic backtracking, even though they cannot backtrack at all. The error message blames ReDoS, which makes it impossible for a user to understand why a harmless pattern won't save. The same patterns are also silently dropped when importing a SillyTavern card.Where it is:
packages/shared/src/utils/regex-safety.ts(theconsumeQuantifierbody regex at:176and the bounds checks at:181-182, plus the length gate at:38). The save path enforces it via the Zod refine atpackages/shared/src/schemas/regex.schema.ts:19-20. The import path drops failing patterns atpackages/server/src/services/import/st-character.importer.ts:136(if (!source || !isPatternSafe(source)) continue;) with no warning.How to reproduce (try it yourself): In the Regex Scripts editor, set
findRegexto any of the following and Save. You'll see a400 ... catastrophic backtrackingeach time; Expected: all of these save and run, because they are O(n):a{0,200},[A-Za-z0-9]{0,255},.{0,140},\d{1,1000}. The cap (maxRepetition = 100,regex-safety.ts:25) is exact:a{0,100}saves,a{0,101}fails. (Sub-bug C){n,}—\s{2,},\n{3,},.{8,},a{3,}. An empty upper bound becomesInfinity(:180) and is rejected (:182), even though\s{2,}is just a single-atom repeat equivalent to\s\s+. So a normal whitespace-collapse scriptfindRegex=\s{2,}/replace=' 'cannot be saved. (Sub-bug D){that isn't a quantifier —hello {name},x{name},a{}, or a pattern containing"role": {. A{right after an atom is parsed as a{n,m}quantifier (:160-161), its body fails/^(\d+)(,(\d*))?$/(:176), and the whole pattern is rejected — even though it matches literally in JS. Workaround is to escape it as\{. (Sub-bug E)\p{L}+,\p{Lu},\P{ASCII},\u{1F600}(with theuflag). The escape branch (:70-87) only consumes the 2-char\p/\u, leaving the walker on{, which it then misreads as a quantifier and rejects. Confusing inconsistency:[\p{L}]+(same thing inside a char class) does save, because the char-class scanner swallows it; and\u{61}saves only because61happens to be a valid{61}body. (Sub-bug F){,m}form —a{,5}(a valid literal match in JS) is rejected because the body regex requires a leading digit (:176). (Sub-bug G)findRegexlonger than 1000 characters (e.g. a big boilerplate/disclaimer string to strip) is rejected by the length gate at:38before any analysis, with the same misleading "catastrophic backtracking" message — even though a literal string cannot backtrack. (Sub-bug H)Suggested fix: This is the bulk of the problem and is mostly about correctness of the parser, not safety:
maxRepetition(bounded{n,m}of any size is linear) and accept open-ended{n,}— treat it like+on the same atom rather than rejecting it.{as a quantifier when it actually forms a valid{n}/{n,}/{n,m}/{,m}body; otherwise treat it as a literal (matching JS semantics) instead of failing.\p{...},\P{...},\u{...}escapes so the walker doesn't land on their{.3. Possessive quantifiers save but then silently do nothing
What's wrong: Patterns using possessive quantifiers —
a++,a*+,a?+,a{1,2}+— pass the safety check and save successfully, but JavaScript has no possessive quantifiers, sonew RegExpthrows "Nothing to repeat" at apply time. That error is swallowed by an emptycatch, so the script just silently does nothing during generation, with no feedback to the user.How to reproduce (try it yourself): Save a script with
findRegex=a++— it saves fine. Then generate. You'll see: the script has no effect and no error appears anywhere. Expected: either reject it at save time (it's not a valid JS regex), or surface the compile error.Where it is:
regex-safety.ts:170and:184treat a trailing+after a quantifier as a possessive marker and skip past it, soisPatternSafereturnstrue.new RegExp('a++')then throws (confirmed for all four forms), caught by the emptycatchatregex-application.ts:125-127.Suggested fix: Have
isPatternSafereject a+/?that immediately follows another quantifier (JS doesn't allow it), so the bad pattern is caught at save time with a clear error rather than silently no-oping later.4. Shipped default "Clean HTML" script never runs anywhere
What's wrong: One of the two regex scripts seeded into a fresh database, "Clean HTML (Outgoing Prompt)", is dropped by the very safety check described above and so never strips HTML from anything — not on the outgoing prompt, and not on display.
How to reproduce (try it yourself): On a fresh DB, the default "Clean HTML (Outgoing Prompt)" script is enabled out of the box, but HTML tags in messages are never removed from outgoing prompts. Expected: an enabled shipped default actually does its job.
Where it is: The seed inserts the script directly via
db.insert(packages/server/src/db/seed-regex.ts:23,57), bypassing the Zod refine — so it lands in the DB even though its pattern failsisPatternSafe(confirmed: the clean-html source fails the star-height check). It is markedpromptOnly: true, so:regex-application.ts:114,isPatternSafereturnsfalse, and it's skipped.packages/client/src/hooks/use-apply-regex.ts:74).Net result: a shipped, enabled default that runs in neither context.
Suggested fix: Once the
isPatternSafefalse-positives in section 2 are fixed (the clean-html pattern is not actually dangerous — it just trips the over-eager star-height logic), this default will start working. Alternatively, rewrite the seeded pattern so it passes a corrected check, and add a seed-time assertion that every shipped default actually passesisPatternSafe.Dropped from the original report as not-reproducible / corrected: Nothing was dropped as false — all ten original sub-bugs (A–J) reproduce. Two corrections were folded in above: (1) sub-bug A's example patterns
(a|a|a)*and(a|ab)*care not catastrophic and were removed, leaving the genuinely-catastrophic(a|a)+$/(a|a)*c; and (2) the original blamed the "Collapse Excess Newlines" default (\n{3,},promptOnly:false) on the safety check too — that's incorrect. That default is skipped earlier atregex-application.ts:95(if (!isPromptOnly(...)) continue) before ever reaching the safety gate, and runs fine on display, so its safety failure has no observable effect. The "Clean HTML" default (section 4) is the real shipped-default casualty.AI-investigated against v2.0.6; verify the reproduction before fixing.
@kolacheee commented on GitHub (Jun 28, 2026):
Re-verified this against v2.0.6 (read the code + reproduced each part) and rewrote the description in plain language with concrete, try-it-yourself reproduction steps. Any original claims I could not actually reproduce were dropped (and called out at the end where relevant). Should be much easier to follow and confirm now — sorry the first version was so dense.