[GH-ISSUE #3086] [Issue]: A regex script can freeze a whole generation turn — isPatternSafe misses polynomial ReDoS and the .replace path has no timeout #1647

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

Originally created by @kolacheee on GitHub (Jun 30, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3086

Originally assigned to: @SpicyMarinara on GitHub.

What's wrong

The regex-script safety gate (isPatternSafe) only rejects exponential backtracking (it checks star height — nested/quantified groups like (a+)+, (.+)+). It accepts polynomial-backtracking patterns built from adjacent independently-quantified atoms with no quantified group — e.g. .*.*.*x, .*foo.*bar.*baz, .*\*[^*]+\*.*\*[^*]+\*.*. These compile and run through a plain String.prototype.replace with no execution timeout, over every message of the chat history on every generation turn. A single short, innocuous-looking regex script can freeze the entire turn for tens of seconds.

The VM-based regex timeout (regex-timeout.ts) exists but is wired only into lorebook keyword scanning's .test path — the regex-script .replace path used for prompt/display scripts is completely unguarded.

How to reproduce (try it yourself)

  1. Add a Regex script (Agents → Regex): enabled, apply to prompt (or both), with Find = .*.*.*Q (or a realistic equivalent like .*foo.*bar.*baz), Replace = empty.
  2. Open any chat that has at least one longer assistant message (~800+ chars of narration) that does not contain the trailing literal (Q).
  3. Send a message.

You'll see: the turn hangs for tens of seconds (the UI/generation freezes) while String.replace backtracks. The pattern was not rejected by isPatternSafe, so it isn't skipped.

Measured against the real compiled code (applyRegexReplacement(input, new RegExp(".*.*.*Q","gi"), "") on uniform no-match input):

  • .*.*.*Q — 300 chars → 0.55s, 600 → 8.4s, 800 → 26.9s
  • .*.*.*.*x — 160 chars → 1.6s, 220 → 7.4s
  • degree-2 .*foo.*bar.*baz on ~19KB → did not finish in 180s

isPatternSafe returns true for all of the above.

Where it is

  • packages/server/src/services/lorebook/regex-application.ts:160-166 — the only pre-flight is if (!isPatternSafe(findRegex)) continue;, then new RegExp(findRegex, flags) and applyRegexReplacement(...) with no timeout/VM wrapper.
  • packages/shared/src/utils/regex-replacement.ts:234-257 — applyRegexReplacement is a bare text.replace(regex, ...).
  • packages/shared/src/utils/regex-safety.ts — isPatternSafe bounds star height only; polynomial chains (multiple adjacent .*/\S*/\w* with no quantified group) pass.
  • packages/server/src/services/lorebook/regex-timeout.ts:24-33 — vmRegexExecutor recompiles + runs .test under a VM timeout; wired only at keyword-scanner.ts:516,572. The .replace path is not covered.
  • Per-turn entry: packages/server/src/routes/generate.routes.ts:2064-2069 runs applyRegexScriptsToPromptMessages(mappedMessages, regexScripts, ...) at iteration 0; applyRegexScriptsToPromptMessages (regex-application.ts:178-198) loops every message. The polynomial n is per-message content length, so one long narration message is enough — message count isn't required.

What's happening

Star-height analysis catches exponential ReDoS but misses polynomial ReDoS (O(n^k) for k adjacent unbounded quantifiers). Because the .replace application path has no execution-time guard (unlike the lorebook .test path), a pattern that passes isPatternSafe runs to completion no matter how long it takes, blocking the event loop for the whole turn.

Threat model note: this is mostly self-inflicted (a user authors their own scripts), which is why it's low priority for typical installs — but regex scripts ride along in imported content (SillyTavern imports, shared character cards/presets). A malicious or careless shared asset carrying such a pattern would freeze anyone who imports and uses it, so it's worth hardening.

Suggested fix

  1. Guard the .replace path with the same timeout the .test path uses. Generalize the VM executor in regex-timeout.ts to cover replacement (run the .replace inside the VM under a time budget, or pre-flight a .test under timeout and skip the script on timeout), and apply it in regex-application.ts:160-166.
  2. Strengthen isPatternSafe to also reject low-star-height polynomial backtracking — flag patterns with ≥2 adjacent unbounded quantifiers over overlapping character classes (e.g. multiple .* / \S* / \w*) with no intervening required literal. Star height alone misses O(n^k).
  3. Defense in depth: cap the per-message input length passed to regex application, or bail when historyLength × scriptCount exceeds a budget.

Note: the two seeded default scripts (seed-regex.ts — the HTML-tag stripper and \n{3,}) are not affected; this needs an authored/imported polynomial pattern to trigger.


AI-investigated against v2.0.8 (main); cited lines read and benchmarked against the compiled packages/shared/dist. Timing measured on the real applyRegexReplacement. Please confirm before fixing.

Originally created by @kolacheee on GitHub (Jun 30, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3086 Originally assigned to: @SpicyMarinara on GitHub. **What's wrong** The regex-script safety gate (`isPatternSafe`) only rejects **exponential** backtracking (it checks *star height* — nested/quantified groups like `(a+)+`, `(.+)+`). It **accepts polynomial-backtracking** patterns built from adjacent independently-quantified atoms with no quantified group — e.g. `.*.*.*x`, `.*foo.*bar.*baz`, `.*\*[^*]+\*.*\*[^*]+\*.*`. These compile and run through a **plain `String.prototype.replace` with no execution timeout**, over **every message of the chat history on every generation turn**. A single short, innocuous-looking regex script can freeze the entire turn for tens of seconds. The VM-based regex timeout (`regex-timeout.ts`) exists but is wired **only** into lorebook keyword scanning's `.test` path — the regex-script `.replace` path used for prompt/display scripts is completely unguarded. **How to reproduce (try it yourself)** 1. Add a Regex script (Agents → Regex): enabled, apply to prompt (or both), with **Find** = `.*.*.*Q` (or a realistic equivalent like `.*foo.*bar.*baz`), Replace = empty. 2. Open any chat that has at least one longer assistant message (~800+ chars of narration) that does **not** contain the trailing literal (`Q`). 3. Send a message. You'll see: the turn hangs for tens of seconds (the UI/generation freezes) while `String.replace` backtracks. The pattern was **not** rejected by `isPatternSafe`, so it isn't skipped. Measured against the real compiled code (`applyRegexReplacement(input, new RegExp(".*.*.*Q","gi"), "")` on uniform no-match input): - `.*.*.*Q` — 300 chars → 0.55s, 600 → 8.4s, 800 → **26.9s** - `.*.*.*.*x` — 160 chars → 1.6s, 220 → **7.4s** - degree-2 `.*foo.*bar.*baz` on ~19KB → did not finish in 180s `isPatternSafe` returns `true` for all of the above. **Where it is** - `packages/server/src/services/lorebook/regex-application.ts:160-166` — the only pre-flight is `if (!isPatternSafe(findRegex)) continue;`, then `new RegExp(findRegex, flags)` and `applyRegexReplacement(...)` with **no** timeout/VM wrapper. - `packages/shared/src/utils/regex-replacement.ts:234-257` — `applyRegexReplacement` is a bare `text.replace(regex, ...)`. - `packages/shared/src/utils/regex-safety.ts` — `isPatternSafe` bounds star height only; polynomial chains (multiple adjacent `.*`/`\S*`/`\w*` with no quantified group) pass. - `packages/server/src/services/lorebook/regex-timeout.ts:24-33` — `vmRegexExecutor` recompiles + runs `.test` under a VM timeout; wired **only** at `keyword-scanner.ts:516,572`. The `.replace` path is not covered. - Per-turn entry: `packages/server/src/routes/generate.routes.ts:2064-2069` runs `applyRegexScriptsToPromptMessages(mappedMessages, regexScripts, ...)` at iteration 0; `applyRegexScriptsToPromptMessages` (`regex-application.ts:178-198`) loops every message. The polynomial `n` is **per-message content length**, so one long narration message is enough — message count isn't required. **What's happening** Star-height analysis catches exponential ReDoS but misses **polynomial** ReDoS (`O(n^k)` for `k` adjacent unbounded quantifiers). Because the `.replace` application path has no execution-time guard (unlike the lorebook `.test` path), a pattern that passes `isPatternSafe` runs to completion no matter how long it takes, blocking the event loop for the whole turn. **Threat model note:** this is mostly self-inflicted (a user authors their own scripts), which is why it's low priority for typical installs — but regex scripts ride along in **imported content** (SillyTavern imports, shared character cards/presets). A malicious or careless shared asset carrying such a pattern would freeze anyone who imports and uses it, so it's worth hardening. **Suggested fix** 1. **Guard the `.replace` path with the same timeout the `.test` path uses.** Generalize the VM executor in `regex-timeout.ts` to cover replacement (run the `.replace` inside the VM under a time budget, or pre-flight a `.test` under timeout and skip the script on timeout), and apply it in `regex-application.ts:160-166`. 2. **Strengthen `isPatternSafe` to also reject low-star-height polynomial backtracking** — flag patterns with ≥2 adjacent unbounded quantifiers over overlapping character classes (e.g. multiple `.*` / `\S*` / `\w*`) with no intervening required literal. Star height alone misses `O(n^k)`. 3. **Defense in depth:** cap the per-message input length passed to regex application, or bail when `historyLength × scriptCount` exceeds a budget. Note: the two seeded default scripts (`seed-regex.ts` — the HTML-tag stripper and `\n{3,}`) are not affected; this needs an authored/imported polynomial pattern to trigger. --- *AI-investigated against v2.0.8 (`main`); cited lines read and benchmarked against the compiled `packages/shared/dist`. Timing measured on the real `applyRegexReplacement`. Please confirm before fixing.*
Author
Owner

@SpicyMarinara commented on GitHub (Jun 30, 2026):

Fixed in the v2.0.9 prep patch. The shared regex safety gate now rejects the reported polynomial shapes such as .*.*.*Q, .*foo.*bar.*baz, and similar broad unbounded chains, and the server prompt-regex replacement path now uses a VM timeout guard for long replacement inputs before running the actual replacement.\n\nAdded prompt regression coverage for the reported patterns. Verified with pnpm regression:prompt, pnpm check, and pnpm version:check.

<!-- gh-comment-id:4844726720 --> @SpicyMarinara commented on GitHub (Jun 30, 2026): Fixed in the v2.0.9 prep patch. The shared regex safety gate now rejects the reported polynomial shapes such as `.*.*.*Q`, `.*foo.*bar.*baz`, and similar broad unbounded chains, and the server prompt-regex replacement path now uses a VM timeout guard for long replacement inputs before running the actual replacement.\n\nAdded prompt regression coverage for the reported patterns. Verified with `pnpm regression:prompt`, `pnpm check`, and `pnpm version:check`.
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#1647
No description provided.