[GH-ISSUE #846] [Feature]: ReDoS hardening for the lorebook activation/regex layer #407

Closed
opened 2026-10-20 17:28:30 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @Romuromylus on GitHub (May 14, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/846

Originally assigned to: @Romuromylus on GitHub.

What problem does this solve?

Lorebook entries support author-supplied regex keywords (entry.useRegex + entry.keys[]). When useRegex is on, the matcher constructs new RegExp(keyword, flags) and runs .test(text) against chat context (or, after #845, against keyword-test sample text in the editor). A pathological pattern like (a+)+$ against "a".repeat(N) + "!" triggers catastrophic backtracking and stalls the thread that runs it.

The trust model is self-contained today: the author writes the regex, the author runs it against their own chat in their own browser/server. So this is fundamentally a self-inflicted-DoS / footgun rather than a security vulnerability — but it's still worth tracking, because:

  1. The footgun is invisible until activation time. The keyword-test panel added in #845 (and #816) makes the failure mode surface earlier, but only if the user happens to trigger the pattern. A near-bad pattern can stay in a lorebook for months and only stall the chat under the right input.
  2. Importing lorebooks from third parties — SillyTavern World Info, shared lorebook bundles — does cross the trust boundary. An imported entry whose author isn't the current user can carry a malicious regex, and the importing user has no easy way to spot it.
  3. The flagged code path runs in both the server (packages/server/src/services/lorebook/keyword-scanner.ts) and now the client (packages/client/src/components/lorebooks/LorebookEditor.tsx preview, via the shared helper at packages/shared/src/utils/lorebook-keyword-matching.ts). A server-side stall affects all live chats on that instance; a client-side stall jams the editor tab.

Proposed solution

Add a regex-safety layer at the activation boundary — not at the leaf testKeyword helper — so it applies uniformly across server scanning, client preview, and any future caller. Options (in roughly increasing weight):

  1. Pre-validate with a complexity heuristic (e.g. safe-regex or a hand-rolled depth check). Reject or fall back to literal substring matching for patterns that fail the check. Cheap to add, false-positives possible.
  2. Per-call execution timeout wrapper around regex.test. Implementable in the browser via setTimeout + a worker; on the server via worker_threads with a timer. Catches patterns that pass static checks but explode on specific inputs.
  3. Non-backtracking engine. RE2 via re2-wasm on both client and server. Strongest, but adds ~300KB WASM to the client bundle and changes semantics (no backreferences, no lookaround). Probably too aggressive for this codebase's user expectations.

A combination of #1 (cheap pre-filter) + #2 (timeout safety net) is probably the right place to land — keeps the JS regex semantics users already know, but breaks the worst-case stall.

Alternatives considered

  • Do nothing. Match the existing posture of packages/shared/src/utils/regex-replacement.ts, which has the same "author runs their own regex" trust model and no hardening today. Defensible given the trust model, but leaves the import-from-third-party case unaddressed.
  • Add hardening at the leaf testKeyword helper. Rejected during the #845 review — the leaf doesn't know the call context, and applying it there would force every caller to absorb the cost / behavior change. The activation layer (scanForActivatedEntries and the editor preview's previewMatches memo) is the better seam.
  • Warn on suspicious patterns in the editor instead of enforcing. Would address #1 (early warning) without changing matcher semantics. Could ship alongside enforcement — they're not exclusive.

Additional context

  • Surfaced during CodeRabbit's review of #845 (thread). The leaf-helper hardening was declined for that PR; the discussion concluded a dedicated activation-layer effort was the right scope.
  • Existing call sites today: packages/server/src/services/lorebook/keyword-scanner.ts:testPrimaryKeys (via the shared helper after #845 merges), and packages/client/src/components/lorebooks/LorebookEditor.tsx's previewMatches memo.
  • Worth checking whether packages/shared/src/utils/regex-replacement.ts should be folded into the same hardening pass — same posture, separate code path.
  • Not urgent. Filing as a low-priority hardening item.

Template check

  • I DID NOT read this template and provide the requested details.
Originally created by @Romuromylus on GitHub (May 14, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/846 Originally assigned to: @Romuromylus on GitHub. ## What problem does this solve? Lorebook entries support author-supplied regex keywords (`entry.useRegex` + `entry.keys[]`). When `useRegex` is on, the matcher constructs `new RegExp(keyword, flags)` and runs `.test(text)` against chat context (or, after #845, against keyword-test sample text in the editor). A pathological pattern like `(a+)+$` against `"a".repeat(N) + "!"` triggers catastrophic backtracking and stalls the thread that runs it. The trust model is self-contained today: the author writes the regex, the author runs it against their own chat in their own browser/server. So this is fundamentally a self-inflicted-DoS / footgun rather than a security vulnerability — but it's still worth tracking, because: 1. The footgun is invisible until activation time. The keyword-test panel added in #845 (and #816) makes the failure mode surface earlier, but only if the user happens to trigger the pattern. A near-bad pattern can stay in a lorebook for months and only stall the chat under the right input. 2. Importing lorebooks from third parties — SillyTavern World Info, shared lorebook bundles — does cross the trust boundary. An imported entry whose author isn't the current user can carry a malicious regex, and the importing user has no easy way to spot it. 3. The flagged code path runs in both the server (`packages/server/src/services/lorebook/keyword-scanner.ts`) and now the client (`packages/client/src/components/lorebooks/LorebookEditor.tsx` preview, via the shared helper at `packages/shared/src/utils/lorebook-keyword-matching.ts`). A server-side stall affects all live chats on that instance; a client-side stall jams the editor tab. ## Proposed solution Add a regex-safety layer at the activation boundary — not at the leaf `testKeyword` helper — so it applies uniformly across server scanning, client preview, and any future caller. Options (in roughly increasing weight): 1. **Pre-validate with a complexity heuristic** (e.g. `safe-regex` or a hand-rolled depth check). Reject or fall back to literal substring matching for patterns that fail the check. Cheap to add, false-positives possible. 2. **Per-call execution timeout** wrapper around `regex.test`. Implementable in the browser via `setTimeout` + a worker; on the server via `worker_threads` with a timer. Catches patterns that pass static checks but explode on specific inputs. 3. **Non-backtracking engine.** RE2 via `re2-wasm` on both client and server. Strongest, but adds ~300KB WASM to the client bundle and changes semantics (no backreferences, no lookaround). Probably too aggressive for this codebase's user expectations. A combination of #1 (cheap pre-filter) + #2 (timeout safety net) is probably the right place to land — keeps the JS regex semantics users already know, but breaks the worst-case stall. ## Alternatives considered - **Do nothing.** Match the existing posture of `packages/shared/src/utils/regex-replacement.ts`, which has the same "author runs their own regex" trust model and no hardening today. Defensible given the trust model, but leaves the import-from-third-party case unaddressed. - **Add hardening at the leaf `testKeyword` helper.** Rejected during the #845 review — the leaf doesn't know the call context, and applying it there would force every caller to absorb the cost / behavior change. The activation layer (`scanForActivatedEntries` and the editor preview's `previewMatches` memo) is the better seam. - **Warn on suspicious patterns in the editor instead of enforcing.** Would address #1 (early warning) without changing matcher semantics. Could ship alongside enforcement — they're not exclusive. ## Additional context - Surfaced during CodeRabbit's review of #845 ([thread](https://github.com/Pasta-Devs/Marinara-Engine/pull/845#discussion_r3244734888)). The leaf-helper hardening was declined for that PR; the discussion concluded a dedicated activation-layer effort was the right scope. - Existing call sites today: `packages/server/src/services/lorebook/keyword-scanner.ts:testPrimaryKeys` (via the shared helper after #845 merges), and `packages/client/src/components/lorebooks/LorebookEditor.tsx`'s `previewMatches` memo. - Worth checking whether `packages/shared/src/utils/regex-replacement.ts` should be folded into the same hardening pass — same posture, separate code path. - Not urgent. Filing as a low-priority hardening item. ## Template check - [ ] I DID NOT read this template and provide the requested details.
Author
Owner

@Romuromylus commented on GitHub (May 15, 2026):

Picking this up. Plan: hand-rolled isPatternSafe heuristic in shared (star-height + length cap + dangerous {n,} repetition) wired into the existing testKeyword helper, plus a server-side vm.runInNewContext timeout executor injected through an optional regexExecutor in KeywordMatchOptions. Client preview picks up the static check automatically; no browser-side timeout (sync regex on the main thread has no clean interrupt seam without workers, which would re-architect the whole sync API for limited benefit on a single tab).

Keeping packages/shared/src/utils/regex-replacement.ts out of this PR — same posture but different feature surface; will file a follow-up so this one stays focused on the lorebook activation layer.

<!-- gh-comment-id:4457609311 --> @Romuromylus commented on GitHub (May 15, 2026): Picking this up. Plan: hand-rolled `isPatternSafe` heuristic in shared (star-height + length cap + dangerous `{n,}` repetition) wired into the existing `testKeyword` helper, plus a server-side `vm.runInNewContext` timeout executor injected through an optional `regexExecutor` in `KeywordMatchOptions`. Client preview picks up the static check automatically; no browser-side timeout (sync regex on the main thread has no clean interrupt seam without workers, which would re-architect the whole sync API for limited benefit on a single tab). Keeping `packages/shared/src/utils/regex-replacement.ts` out of this PR — same posture but different feature surface; will file a follow-up so this one stays focused on the lorebook activation layer.
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#407
No description provided.