[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

Closed
opened 2026-10-21 05:37:30 +07:00 by bsakaguchi · 1 comment
Owner

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 isPatternSafe plus 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):

  1. Create an enabled, global, prompt-only regex script: findRegex = (a|a)+$, flags = g, placement ai_output.
  2. Send/generate over a message whose text is 30 a characters followed by ! (e.g. aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!).
  3. You'll see: the backend stalls for several seconds (measured: 24 a's ≈ 0.17s, 26 ≈ 0.67s, 28 ≈ 3.2s — roughly 4× per 2 extra chars). A slightly longer message blocks for minutes; this freezes the event loop for all requests.
  4. Expected: the pattern is either rejected as unsafe, or its execution is bounded by a timeout so it cannot hang the server.

(a|a)*c is catastrophic the same way (28 a's ≈ 3.5s). (Note: the original report also listed (a|a|a)* and (a|ab)*c as 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, so isPatternSafe('(a|a)+$') returns true. The pattern is then compiled and run with no guard at packages/server/src/services/regex/regex-application.ts:118 (new RegExp) → :120 → String.replace in packages/shared/src/utils/regex-replacement.ts:138, awaited inline at the call sites in generate.routes.ts (2043/2049/6117/10957), chats.routes.ts:2137, and dry-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 only applyRegexReplacement and isPatternSafe and never uses it — the comment at regex-application.ts:112-113 even acknowledges there is no timeout. So a pattern that slips past the static check runs unbounded.

Suggested fix: Two layers. (a) Teach isPatternSafe to 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 (the consumeQuantifier body regex at :176 and the bounds checks at :181-182, plus the length gate at :38). The save path enforces it via the Zod refine at packages/shared/src/schemas/regex.schema.ts:19-20. The import path drops failing patterns at packages/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 findRegex to any of the following and Save. You'll see a 400 ... catastrophic backtracking each time; Expected: all of these save and run, because they are O(n):

  • Bounded counts above 100 — 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)
  • Open-ended counts {n,} — \s{2,}, \n{3,}, .{8,}, a{3,}. An empty upper bound becomes Infinity (:180) and is rejected (:182), even though \s{2,} is just a single-atom repeat equivalent to \s\s+. So a normal whitespace-collapse script findRegex=\s{2,} / replace=' ' cannot be saved. (Sub-bug D)
  • A literal { 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)
  • Unicode property / codepoint escapes — \p{L}+, \p{Lu}, \P{ASCII}, \u{1F600} (with the u flag). 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 because 61 happens 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)
  • Long pure-literal patterns — a findRegex longer than 1000 characters (e.g. a big boilerplate/disclaimer string to strip) is rejected by the length gate at :38 before 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:

  • Raise or remove 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.
  • Only treat { 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.
  • Properly skip \p{...}, \P{...}, \u{...} escapes so the walker doesn't land on their {.
  • Don't reject long pure-literal patterns, and when you do reject, use a message that names the real reason (length / unsupported construct) rather than "catastrophic backtracking".
  • On ST import, surface a warning when a script is dropped instead of silently discarding it.

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, so new RegExp throws "Nothing to repeat" at apply time. That error is swallowed by an empty catch, 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:170 and :184 treat a trailing + after a quantifier as a possessive marker and skip past it, so isPatternSafe returns true. new RegExp('a++') then throws (confirmed for all four forms), caught by the empty catch at regex-application.ts:125-127.

Suggested fix: Have isPatternSafe reject 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 fails isPatternSafe (confirmed: the clean-html source fails the star-height check). It is marked promptOnly: true, so:

  • On the prompt path it reaches the gate at regex-application.ts:114, isPatternSafe returns false, and it's skipped.
  • On the display path it's skipped anyway because display intentionally ignores prompt-only scripts (packages/client/src/hooks/use-apply-regex.ts:74).

Net result: a shipped, enabled default that runs in neither context.

Suggested fix: Once the isPatternSafe false-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 passes isPatternSafe.


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)*c are 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 at regex-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.

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 `isPatternSafe` plus 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):** 1. Create an enabled, global, prompt-only regex script: `findRegex` = `(a|a)+$`, `flags` = `g`, placement `ai_output`. 2. Send/generate over a message whose text is 30 `a` characters followed by `!` (e.g. `aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!`). 3. **You'll see:** the backend stalls for several seconds (measured: 24 a's ≈ 0.17s, 26 ≈ 0.67s, 28 ≈ 3.2s — roughly 4× per 2 extra chars). A slightly longer message blocks for minutes; this freezes the event loop for all requests. 4. **Expected:** the pattern is either rejected as unsafe, or its execution is bounded by a timeout so it cannot hang the server. `(a|a)*c` is catastrophic the same way (28 a's ≈ 3.5s). (Note: the original report also listed `(a|a|a)*` and `(a|ab)*c` as 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, so `isPatternSafe('(a|a)+$')` returns `true`. The pattern is then compiled and run with no guard at `packages/server/src/services/regex/regex-application.ts:118` (`new RegExp`) → `:120` → `String.replace` in `packages/shared/src/utils/regex-replacement.ts:138`, awaited inline at the call sites in `generate.routes.ts` (2043/2049/6117/10957), `chats.routes.ts:2137`, and `dry-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 only `applyRegexReplacement` and `isPatternSafe` and never uses it — the comment at `regex-application.ts:112-113` even acknowledges there is no timeout. So a pattern that slips past the static check runs unbounded. **Suggested fix:** Two layers. (a) Teach `isPatternSafe` to 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` (the `consumeQuantifier` body regex at `:176` and the bounds checks at `:181-182`, plus the length gate at `:38`). The save path enforces it via the Zod refine at `packages/shared/src/schemas/regex.schema.ts:19-20`. The import path drops failing patterns at `packages/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 `findRegex` to any of the following and Save. **You'll see** a `400 ... catastrophic backtracking` each time; **Expected:** all of these save and run, because they are O(n): - **Bounded counts above 100** — `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) - **Open-ended counts `{n,}`** — `\s{2,}`, `\n{3,}`, `.{8,}`, `a{3,}`. An empty upper bound becomes `Infinity` (`:180`) and is rejected (`:182`), even though `\s{2,}` is just a single-atom repeat equivalent to `\s\s+`. So a normal whitespace-collapse script `findRegex=\s{2,}` / `replace=' '` cannot be saved. (Sub-bug D) - **A literal `{` 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) - **Unicode property / codepoint escapes** — `\p{L}+`, `\p{Lu}`, `\P{ASCII}`, `\u{1F600}` (with the `u` flag). 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 because `61` happens 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) - **Long pure-literal patterns** — a `findRegex` longer than 1000 characters (e.g. a big boilerplate/disclaimer string to strip) is rejected by the length gate at `:38` *before* 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: - Raise or remove `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. - Only treat `{` 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. - Properly skip `\p{...}`, `\P{...}`, `\u{...}` escapes so the walker doesn't land on their `{`. - Don't reject long *pure-literal* patterns, and when you do reject, use a message that names the real reason (length / unsupported construct) rather than "catastrophic backtracking". - On ST import, surface a warning when a script is dropped instead of silently discarding it. --- ## 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, so `new RegExp` throws "Nothing to repeat" at apply time. That error is swallowed by an empty `catch`, 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:170` and `:184` treat a trailing `+` after a quantifier as a possessive marker and skip past it, so `isPatternSafe` returns `true`. `new RegExp('a++')` then throws (confirmed for all four forms), caught by the empty `catch` at `regex-application.ts:125-127`. **Suggested fix:** Have `isPatternSafe` reject 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 fails `isPatternSafe` (confirmed: the clean-html source fails the star-height check). It is marked `promptOnly: true`, so: - On the **prompt** path it reaches the gate at `regex-application.ts:114`, `isPatternSafe` returns `false`, and it's skipped. - On the **display** path it's skipped anyway because display intentionally ignores prompt-only scripts (`packages/client/src/hooks/use-apply-regex.ts:74`). Net result: a shipped, enabled default that runs in neither context. **Suggested fix:** Once the `isPatternSafe` false-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 passes `isPatternSafe`. --- **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)*c` are *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 at `regex-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.
Author
Owner

@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.

<!-- gh-comment-id:4827556679 --> @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.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#1507
No description provided.