[PR #882] [MERGED] feat(lorebooks): ReDoS hardening for keyword regex activation #4817

Closed
opened 2026-10-22 04:10:54 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/882
Author: @Romuromylus
Created: 5/15/2026
Status: ✅ Merged
Merged: 5/15/2026
Merged by: @Romuromylus

Base: staging ← Head: fix/lorebook-regex-redos-hardening


📝 Commits (4)

  • 2d85e3c feat(lorebooks): ReDoS hardening for keyword regex activation (#846)
  • 916fea3 chore(lorebooks): polish regex-safety walker and timeout test
  • da42107 perf(lorebooks): skip vm executor for non-useRegex matchWholeWords path
  • 36ac134 Merge branch 'staging' into fix/lorebook-regex-redos-hardening

📊 Changes

6 files changed (+391 additions, -9 deletions)

View changed files

📝 packages/server/src/services/lorebook/keyword-scanner.ts (+2 -0)
➕ packages/server/src/services/lorebook/regex-timeout.ts (+58 -0)
➕ packages/server/test/lorebook-regex-safety.test.ts (+93 -0)
📝 packages/shared/src/index.ts (+1 -0)
📝 packages/shared/src/utils/lorebook-keyword-matching.ts (+31 -9)
➕ packages/shared/src/utils/regex-safety.ts (+206 -0)

📄 Description

Linked issue

Closes #846

Why this change

Lorebook entries support author-supplied regex keys (entry.useRegex + entry.keys[]). When useRegex is on, the matcher does new RegExp(keyword, flags).test(text) against chat context — and after #845, against keyword-test sample text in the editor preview. A pathological pattern like (a+)+ against "a".repeat(N) + "!" triggers catastrophic backtracking and stalls the thread that runs it: server-side that affects every live chat on the instance, client-side that jams the editor tab.

Trust model is mostly self-contained today (you write the regex, you run it on your own chat), so it's footgun more than vulnerability — but the SillyTavern lorebook import path crosses that boundary, and the 2026-04 issue here is that the failure mode is invisible until the right input shows up. I want a guard at the activation seam that applies uniformly across server scanning, client preview, and any future caller, without changing semantics for safe patterns.

What changed

Two-layer defense, both gated at the activation boundary instead of the leaf testKeyword helper (per the #845 review thread that scoped this out of the leaf):

1. Static safety heuristic in @marinara-engine/shared (isPatternSafe) — packages/shared/src/utils/regex-safety.ts

  • Star-height check rejects nested quantifiers like (a+)+, (a*)*, (a+|b)+, ((ab)+)+
  • Pattern length cap (1000 chars)
  • {n,m} repetition cap (100, also catches unbounded {1,})
  • Walks the source once, tracks character classes / escapes / group prefixes ((?:, (?=, (?<name>) without depending on safe-regex/ret. Keeps @marinara-engine/shared at zero new deps.

Wired into testKeyword: when useRegex is on and isPatternSafe returns false, the helper falls back to literal substring matching — same posture as the existing invalid-regex catch fallback, principle of least surprise.

2. Server-side execution timeout (vmRegexExecutor) — packages/server/src/services/lorebook/regex-timeout.ts

  • Runs regex.test inside vm.runInNewContext with a 50 ms timeout. V8's interrupt checks fire during regex execution, so catastrophic backtracking aborts instead of pinning the event loop.
  • On timeout: logs a warn with the pattern source + flags + text length and returns false. Doesn't substitute literal-substring semantics on timeout — the pattern compiled and may have matched on simpler input; switching meanings mid-run would be a silent surprise.
  • Injected via the new optional regexExecutor on KeywordMatchOptions so the shared helper stays runtime-agnostic; the client preview keeps using the default executor.

Client-side has the static check only. A browser-side sync timeout would require re-architecting the helper around Web Workers (sync regex.test on the main thread has no clean interrupt seam), which is a heavier change than the symptom warrants — a frozen tab is recoverable, a frozen Node event loop isn't.

packages/shared/src/utils/regex-replacement.ts is intentionally out of scope. Same posture, different feature surface (regex scripts on display/output, separate call sites). Filing a follow-up so this one stays focused on the lorebook activation layer.

Validation

  • pnpm check passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed CONTRIBUTING.md

Manual verification notes

  • 8 new tests in packages/server/test/lorebook-regex-safety.test.ts cover both layers — isPatternSafe for safe / nested-quantifier / oversized / unbalanced patterns, testKeyword fallback semantics, and the canonical (a|aa)+ × "a".repeat(28) + "!" ReDoS pair under the vm timeout (verifies the abort actually fires within ~1 s on the runner).
  • Manually verify in browser on a real lorebook with useRegex: true: paste a pathological pattern like (a+)+ and confirm the keyword-test panel from #845 stays responsive — without this change, that combo freezes the editor tab.
  • Manually verify safe regex keys still match — e.g. \bword\b, foo|bar, (?:foo){1,5}. The static check accepts these; behavior should be unchanged.
  • Manually verify the literal-substring fallback by setting an unsafe pattern as a key and pasting text containing that pattern's source verbatim — entry should still activate (matching the existing invalid-regex fallback).
  • Manually check server logs for the new warn line on a contrived pathological pattern that survives the static check (e.g. add one via direct DB insert) — should see Lorebook regex /…/… exceeded 50ms timeout against chat context (length=…) — entry will not match this scan.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Version/release files updated (only if this PR includes a version bump)

UI evidence (if applicable)

No UI changes — purely runtime hardening behind the existing useRegex flag and the keyword-test panel from #845.

Summary by CodeRabbit

  • New Features

    • Added regex safety validation and timeout protection (50ms default) for keyword matching to prevent pattern hangs; unsafe patterns automatically fall back to literal substring matching.
  • Tests

    • Added comprehensive test suite for regex safety validation and timeout behavior.

Review Change Stack


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/882 **Author:** [@Romuromylus](https://github.com/Romuromylus) **Created:** 5/15/2026 **Status:** ✅ Merged **Merged:** 5/15/2026 **Merged by:** [@Romuromylus](https://github.com/Romuromylus) **Base:** `staging` ← **Head:** `fix/lorebook-regex-redos-hardening` --- ### 📝 Commits (4) - [`2d85e3c`](https://github.com/Pasta-Devs/Marinara-Engine/commit/2d85e3cb6c6ab871ee8306749cff8208f9adc177) feat(lorebooks): ReDoS hardening for keyword regex activation (#846) - [`916fea3`](https://github.com/Pasta-Devs/Marinara-Engine/commit/916fea35ad03e085a612ea985e7952ce4b957bc1) chore(lorebooks): polish regex-safety walker and timeout test - [`da42107`](https://github.com/Pasta-Devs/Marinara-Engine/commit/da42107722d86f3495c27c77f39054efc71257aa) perf(lorebooks): skip vm executor for non-useRegex matchWholeWords path - [`36ac134`](https://github.com/Pasta-Devs/Marinara-Engine/commit/36ac13447fd15a7f9479f2c462f5482739d65130) Merge branch 'staging' into fix/lorebook-regex-redos-hardening ### 📊 Changes **6 files changed** (+391 additions, -9 deletions) <details> <summary>View changed files</summary> 📝 `packages/server/src/services/lorebook/keyword-scanner.ts` (+2 -0) ➕ `packages/server/src/services/lorebook/regex-timeout.ts` (+58 -0) ➕ `packages/server/test/lorebook-regex-safety.test.ts` (+93 -0) 📝 `packages/shared/src/index.ts` (+1 -0) 📝 `packages/shared/src/utils/lorebook-keyword-matching.ts` (+31 -9) ➕ `packages/shared/src/utils/regex-safety.ts` (+206 -0) </details> ### 📄 Description ## Linked issue Closes #846 ## Why this change Lorebook entries support author-supplied regex keys (`entry.useRegex` + `entry.keys[]`). When `useRegex` is on, the matcher does `new RegExp(keyword, flags).test(text)` against chat context — and after #845, against keyword-test sample text in the editor preview. A pathological pattern like `(a+)+` against `"a".repeat(N) + "!"` triggers catastrophic backtracking and stalls the thread that runs it: server-side that affects every live chat on the instance, client-side that jams the editor tab. Trust model is mostly self-contained today (you write the regex, you run it on your own chat), so it's footgun more than vulnerability — but the SillyTavern lorebook import path crosses that boundary, and the 2026-04 issue here is that the failure mode is invisible until the right input shows up. I want a guard at the activation seam that applies uniformly across server scanning, client preview, and any future caller, without changing semantics for safe patterns. ## What changed Two-layer defense, both gated at the activation boundary instead of the leaf `testKeyword` helper (per the #845 review thread that scoped this out of the leaf): **1. Static safety heuristic in `@marinara-engine/shared` (`isPatternSafe`)** — `packages/shared/src/utils/regex-safety.ts` - Star-height check rejects nested quantifiers like `(a+)+`, `(a*)*`, `(a+|b)+`, `((ab)+)+` - Pattern length cap (1000 chars) - `{n,m}` repetition cap (100, also catches unbounded `{1,}`) - Walks the source once, tracks character classes / escapes / group prefixes (`(?:`, `(?=`, `(?<name>`) without depending on `safe-regex`/`ret`. Keeps `@marinara-engine/shared` at zero new deps. Wired into `testKeyword`: when `useRegex` is on and `isPatternSafe` returns false, the helper falls back to literal substring matching — same posture as the existing invalid-regex `catch` fallback, principle of least surprise. **2. Server-side execution timeout (`vmRegexExecutor`)** — `packages/server/src/services/lorebook/regex-timeout.ts` - Runs `regex.test` inside `vm.runInNewContext` with a 50 ms timeout. V8's interrupt checks fire during regex execution, so catastrophic backtracking aborts instead of pinning the event loop. - On timeout: logs a warn with the pattern source + flags + text length and returns `false`. **Doesn't** substitute literal-substring semantics on timeout — the pattern compiled and may have matched on simpler input; switching meanings mid-run would be a silent surprise. - Injected via the new optional `regexExecutor` on `KeywordMatchOptions` so the shared helper stays runtime-agnostic; the client preview keeps using the default executor. Client-side has the static check only. A browser-side sync timeout would require re-architecting the helper around Web Workers (sync `regex.test` on the main thread has no clean interrupt seam), which is a heavier change than the symptom warrants — a frozen tab is recoverable, a frozen Node event loop isn't. `packages/shared/src/utils/regex-replacement.ts` is intentionally out of scope. Same posture, different feature surface (regex scripts on display/output, separate call sites). Filing a follow-up so this one stays focused on the lorebook activation layer. ## Validation - [x] `pnpm check` passes locally - [x] Container (Docker / Podman) built and ran without issue - [x] Ran the app, clicked through the changes manually - [x] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [x] Above manual verification completed (describe below) - [x] Read and followed `CONTRIBUTING.md` ### Manual verification notes - 8 new tests in `packages/server/test/lorebook-regex-safety.test.ts` cover both layers — `isPatternSafe` for safe / nested-quantifier / oversized / unbalanced patterns, `testKeyword` fallback semantics, and the canonical `(a|aa)+` × `"a".repeat(28) + "!"` ReDoS pair under the vm timeout (verifies the abort actually fires within ~1 s on the runner). - Manually verify in browser on a real lorebook with `useRegex: true`: paste a pathological pattern like `(a+)+` and confirm the keyword-test panel from #845 stays responsive — without this change, that combo freezes the editor tab. - Manually verify safe regex keys still match — e.g. `\bword\b`, `foo|bar`, `(?:foo){1,5}`. The static check accepts these; behavior should be unchanged. - Manually verify the literal-substring fallback by setting an unsafe pattern as a key and pasting text containing that pattern's source verbatim — entry should still activate (matching the existing invalid-regex fallback). - Manually check server logs for the new warn line on a contrived pathological pattern that survives the static check (e.g. add one via direct DB insert) — should see `Lorebook regex /…/… exceeded 50ms timeout against chat context (length=…) — entry will not match this scan`. ## Docs and release impact - [x] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Version/release files updated (only if this PR includes a version bump) ## UI evidence (if applicable) No UI changes — purely runtime hardening behind the existing `useRegex` flag and the keyword-test panel from #845. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added regex safety validation and timeout protection (50ms default) for keyword matching to prevent pattern hangs; unsafe patterns automatically fall back to literal substring matching. * **Tests** * Added comprehensive test suite for regex safety validation and timeout behavior. <!-- review_stack_entry_start --> [![Review Change Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/Pasta-Devs/Marinara-Engine/pull/882) <!-- review_stack_entry_end --> <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-22 04:10:54 +07:00
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#4817
No description provided.