[PR #7824] [MERGED] fix(security): harden regex scripts and password checks #7950

Closed
opened 2026-10-24 04:09:06 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/7824
Author: @SpicyMarinara
Created: 10/19/2026
Status: ✅ Merged
Merged: 10/19/2026
Merged by: @SpicyMarinara

Base: staging ← Head: fix/harden-server-hardening


📝 Commits (4)

  • 10e51ae fix(security): harden regex scripts and password checks
  • 6e948ed fix(security): keep signed-in browsers working during a password lock
  • a369732 fix(security): key the signed-in cookie by a server secret
  • 935f2dc fix(security): count signed-in health checks against their tries

📊 Changes

9 files changed (+605 additions, -30 deletions)

View changed files

📝 docs/REMOTE_ACCESS.md (+2 -0)
📝 docs/TROUBLESHOOTING.md (+1 -0)
📝 packages/server/src/middleware/android-local-auth.ts (+1 -1)
📝 packages/server/src/middleware/basic-auth.ts (+166 -10)
📝 packages/server/src/services/lorebook/regex-timeout.ts (+27 -14)
📝 packages/server/src/services/regex/regex-application.ts (+3 -4)
📝 packages/server/src/utils/crypto.ts (+6 -1)
➕ scripts/regressions/basic-auth-throttle-security.regression.ts (+296 -0)
➕ scripts/regressions/regex-script-timeout-security.regression.ts (+103 -0)

📄 Description

Important

Contributions target staging. Only SpicyMarinara may promote this repository's staging branch or a same-repository hotfix/* branch to main.
Outside and first-time contributors also require an approving review from SpicyMarinara.

Linked issue

No linked issue: this comes from an internal security review. @SpicyMarinara

Why this change

  • Prompt regex scripts. Regex scripts run on the server while the prompt is built, and their patterns can come from imported character cards. The timed guard that stops a pattern stuck backtracking ran only on messages of 256 characters or more. Shorter messages, which are most chat turns and greetings, ran the pattern with no time limit, so a slow pattern could hold up every other request until the script was removed.
  • Basic Auth. Wrong passwords were only limited by the general /api rate limit. Requests for the page and static files had no limit and no log line, so password guesses there were never slowed down or noticed.

What changed

  • Regex scripts: every prompt message now goes through the timed guard, whatever its length. Scripts that behave give exactly the same results. The guard now reuses one vm context instead of building a new one for each call, so a typical turn gets faster, not slower (numbers below). The lorebook regex key check uses the same reused context.
  • Basic Auth: wrong passwords are counted per client address (an IPv6 /64 counts as one) on every path, /api/health included, separately from the /api rate limits. After 10 different wrong passwords within 15 minutes, that address gets 429 with Retry-After until the window ends, even with the right password. The first wrong password from an address and reaching the limit are both logged at warn. A correct password clears the count. A browser that keeps resending one old saved password counts once, and a request without a password does not count. During the block, /api/health still answers but gives only the public reply.
  • Signed-in browsers keep working: a correct password also sets an HttpOnly, SameSite=Lax cookie (marinara_signed_in). Its value is an HMAC of the credentials keyed by a key derived from the persisted server encryption key, so it survives restarts and changes with the password, but cannot be worked out from the password alone. While an address is blocked, a browser with that cookie gets 10 more tries, so it still gets in with the correct password and other visitors' wrong passwords cannot lock the owner out of a device they already use, including behind a tunnel where every visitor shares one address. The cookie does nothing without the password, and a signed-in browser getting past a lock leaves the lock in place. It is marked Secure on HTTPS, including HTTPS reported by a local proxy. New browsers on a blocked address still wait for the window to end.
  • Loopback, IP_ALLOWLIST and trusted Tailscale/Docker peers still skip the password and are never counted. Visitors forwarded by a local reverse proxy or tunnel still have to sign in (the rules from #7816), and they share one count because they all arrive from loopback. One of them signing in does not clear that shared count.
  • Docs: docs/REMOTE_ACCESS.md and docs/TROUBLESHOOTING.md explain the wrong-password limit.
  • New regressions: scripts/regressions/regex-script-timeout-security.regression.ts and scripts/regressions/basic-auth-throttle-security.regression.ts. Both fail on staging and pass with this change. The regex one stops at its time budget, which staging exceeds by about 60 s on a 31-character message. The auth one gets 200 where 429 is expected, and (added after review) gets no signed-in cookie where one is expected.

Regex timing

applyRegexScriptsToPromptMessages, 4 prompt scripts (the built-in Clean HTML plus three common ones), median over 100 runs. The machine was under heavy load, so treat these as relative. Output was the same byte for byte in every case.

Chat staging this PR
20 messages, half under 256 characters 28.2 ms 7.3 ms
60 messages, half under 256 characters 86.2 ms 25.3 ms
200 messages, half under 256 characters 312.3 ms 71.9 ms
60 messages, all under 256 characters (worst case) 0.8 ms 22.3 ms

A single guarded call now costs about 0.07–0.14 ms, down from about 0.7 ms.

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

Commands the agent ran (results are in the PR conversation, not ticked above):

  • pnpm check: passed.
  • pnpm regression:security: 23 of 25 passed. multiplayer-control-security and encoded-api-path-security hit the runner's 30 s limit while the machine was very busy (load average 45–70). Run again on their own, encoded-api-path-security passed in 15 s and multiplayer-control-security passed in 29 s without the limit. Neither sends a wrong password.
  • The two new regressions, loopback-proxy-auth-security, docker-gateway-auth-security, docker-proxy-auth, android-local-auth, multiplayer-peer-server-security, route-rate-limits, prompt, group-prompt-regex, preset-regex-defaults and every lorebook regression (23 files): passed.
  • Both new regressions were also run against staging code: both fail there.
  • After the first review fix (signed-in cookie, 6e948eded): pnpm check passed; pnpm regression:security passed (25/25 plus the extra suites); basic-auth-throttle-security fails on the previous head and passes now; loopback-proxy-auth-security, route-rate-limits and multiplayer-peer-server-security passed.
  • After the second review fix (server-keyed cookie, its own try limit, Secure behind a local HTTPS proxy, a36973201): pnpm check passed; basic-auth-throttle-security fails on 6e948eded and passes now; loopback-proxy-auth-security, docker-gateway-auth-security, docker-proxy-auth, android-local-auth and route-rate-limits passed. The results of a full pnpm regression:security rerun are in a PR comment.
  • After the third review fix (/api/health counts a signed-in browser's passwords against its extra tries, 935f2dce8): pnpm format:check and the server lint (tsc) passed; basic-auth-throttle-security fails on a36973201 and passes now.

Manual verification notes

  • Manually verify that a chat whose prompt regex scripts edit short user messages (for example a name swap or an OOC strip) still sends the edited text: open Peek prompt and compare.
  • Manually verify that a regex script with a slow pattern on a short message is skipped within a moment and the server log names it, while the rest of the app keeps responding.
  • With BASIC_AUTH_USER and BASIC_AUTH_PASS set, open the app from another device and enter 10 different wrong passwords: manually verify that the next try shows "Too many wrong passwords" (429) and that the server log has one warn line for the first wrong password and one for the limit.
  • Manually verify that after the block ends (15 minutes, or a server restart) the correct password signs in.
  • Manually verify that a browser holding an old saved password after you change BASIC_AUTH_PASS is asked again and is not blocked.
  • Behind a reverse proxy or tunnel on the host: sign in once from your own browser, then send 10 different wrong passwords from another browser. Manually verify that your browser keeps working without a new prompt, and that the other browser gets "Too many wrong passwords" even with the correct password.
  • Manually verify that the browser's cookie list for the app shows marinara_signed_in as HttpOnly after signing in (and Secure when opened over HTTPS, for example through a tunnel), and that after changing BASIC_AUTH_PASS that browser is asked for the new password.
  • Manually verify that the first remote sign-in on a fresh data folder creates .encryption-key in the data folder if it is not there yet, and that remembered browsers keep working after a server restart.
  • Manually verify that the host computer itself (direct 127.0.0.1) stays passwordless, and that a reverse proxy or tunnel on the host still asks its visitors to sign in.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README) as needed
  • Translated docs on the docs-i18n branch updated to match, or a [docs-i18n] follow-up issue opened (see CONTRIBUTING.md § Translated documentation)
  • Version/release files updated (only if this PR includes a version bump)

English docs changed: docs/REMOTE_ACCESS.md, docs/TROUBLESHOOTING.md (the release translation sweep picks these up).

UI evidence (if applicable)

No UI changes.

Summary by CodeRabbit

  • New Features
    • Basic Auth sign-ins are temporarily rate-limited after 10 distinct incorrect passwords from the same client address within 15 minutes. Locked-out clients receive a retry time; the limit clears when the window expires or the server restarts.
    • Previously signed-in browsers can continue accessing protected pages during a lockout if they provide the correct password. Visitors sharing a proxy or tunnel share a failure count, which their successful sign-ins do not clear.
  • Bug Fixes
    • Regex replacements now receive timeout protection regardless of message length.
  • Documentation
    • Updated remote access and troubleshooting guidance with details on sign-in limits and recovery.

🔄 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/7824 **Author:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Created:** 10/19/2026 **Status:** ✅ Merged **Merged:** 10/19/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `fix/harden-server-hardening` --- ### 📝 Commits (4) - [`10e51ae`](https://github.com/Pasta-Devs/Marinara-Engine/commit/10e51ae9958dc749f9ad9a2d9f4dd43ef7bdfd6c) fix(security): harden regex scripts and password checks - [`6e948ed`](https://github.com/Pasta-Devs/Marinara-Engine/commit/6e948eded519ff96ad39ca9d8e3beafc0b89d07c) fix(security): keep signed-in browsers working during a password lock - [`a369732`](https://github.com/Pasta-Devs/Marinara-Engine/commit/a36973201f3bab80102c1aef81e390f8d563f2f1) fix(security): key the signed-in cookie by a server secret - [`935f2dc`](https://github.com/Pasta-Devs/Marinara-Engine/commit/935f2dce8a89ba24821d272fb3706f7fbdf4291e) fix(security): count signed-in health checks against their tries ### 📊 Changes **9 files changed** (+605 additions, -30 deletions) <details> <summary>View changed files</summary> 📝 `docs/REMOTE_ACCESS.md` (+2 -0) 📝 `docs/TROUBLESHOOTING.md` (+1 -0) 📝 `packages/server/src/middleware/android-local-auth.ts` (+1 -1) 📝 `packages/server/src/middleware/basic-auth.ts` (+166 -10) 📝 `packages/server/src/services/lorebook/regex-timeout.ts` (+27 -14) 📝 `packages/server/src/services/regex/regex-application.ts` (+3 -4) 📝 `packages/server/src/utils/crypto.ts` (+6 -1) ➕ `scripts/regressions/basic-auth-throttle-security.regression.ts` (+296 -0) ➕ `scripts/regressions/regex-script-timeout-security.regression.ts` (+103 -0) </details> ### 📄 Description > [!IMPORTANT] > Contributions target `staging`. Only `SpicyMarinara` may promote this repository's `staging` branch or a same-repository `hotfix/*` branch to `main`. > Outside and first-time contributors also require an approving review from `SpicyMarinara`. <!-- See CONTRIBUTING.md § Branches. --> ## Linked issue No linked issue: this comes from an internal security review. @SpicyMarinara ## Why this change - **Prompt regex scripts.** Regex scripts run on the server while the prompt is built, and their patterns can come from imported character cards. The timed guard that stops a pattern stuck backtracking ran only on messages of 256 characters or more. Shorter messages, which are most chat turns and greetings, ran the pattern with no time limit, so a slow pattern could hold up every other request until the script was removed. - **Basic Auth.** Wrong passwords were only limited by the general `/api` rate limit. Requests for the page and static files had no limit and no log line, so password guesses there were never slowed down or noticed. ## What changed - **Regex scripts:** every prompt message now goes through the timed guard, whatever its length. Scripts that behave give exactly the same results. The guard now reuses one vm context instead of building a new one for each call, so a typical turn gets faster, not slower (numbers below). The lorebook regex key check uses the same reused context. - **Basic Auth:** wrong passwords are counted per client address (an IPv6 `/64` counts as one) on every path, `/api/health` included, separately from the `/api` rate limits. After 10 different wrong passwords within 15 minutes, that address gets `429` with `Retry-After` until the window ends, even with the right password. The first wrong password from an address and reaching the limit are both logged at warn. A correct password clears the count. A browser that keeps resending one old saved password counts once, and a request without a password does not count. During the block, `/api/health` still answers but gives only the public reply. - **Signed-in browsers keep working:** a correct password also sets an HttpOnly, SameSite=Lax cookie (`marinara_signed_in`). Its value is an HMAC of the credentials keyed by a key derived from the persisted server encryption key, so it survives restarts and changes with the password, but cannot be worked out from the password alone. While an address is blocked, a browser with that cookie gets 10 more tries, so it still gets in with the correct password and other visitors' wrong passwords cannot lock the owner out of a device they already use, including behind a tunnel where every visitor shares one address. The cookie does nothing without the password, and a signed-in browser getting past a lock leaves the lock in place. It is marked `Secure` on HTTPS, including HTTPS reported by a local proxy. New browsers on a blocked address still wait for the window to end. - Loopback, `IP_ALLOWLIST` and trusted Tailscale/Docker peers still skip the password and are never counted. Visitors forwarded by a local reverse proxy or tunnel still have to sign in (the rules from #7816), and they share one count because they all arrive from loopback. One of them signing in does not clear that shared count. - Docs: `docs/REMOTE_ACCESS.md` and `docs/TROUBLESHOOTING.md` explain the wrong-password limit. - New regressions: `scripts/regressions/regex-script-timeout-security.regression.ts` and `scripts/regressions/basic-auth-throttle-security.regression.ts`. Both fail on `staging` and pass with this change. The regex one stops at its time budget, which `staging` exceeds by about 60 s on a 31-character message. The auth one gets `200` where `429` is expected, and (added after review) gets no signed-in cookie where one is expected. ### Regex timing `applyRegexScriptsToPromptMessages`, 4 prompt scripts (the built-in Clean HTML plus three common ones), median over 100 runs. The machine was under heavy load, so treat these as relative. Output was the same byte for byte in every case. | Chat | staging | this PR | | --- | --- | --- | | 20 messages, half under 256 characters | 28.2 ms | 7.3 ms | | 60 messages, half under 256 characters | 86.2 ms | 25.3 ms | | 200 messages, half under 256 characters | 312.3 ms | 71.9 ms | | 60 messages, all under 256 characters (worst case) | 0.8 ms | 22.3 ms | A single guarded call now costs about 0.07–0.14 ms, down from about 0.7 ms. ## 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` Commands the agent ran (results are in the PR conversation, not ticked above): - `pnpm check`: passed. - `pnpm regression:security`: 23 of 25 passed. `multiplayer-control-security` and `encoded-api-path-security` hit the runner's 30 s limit while the machine was very busy (load average 45–70). Run again on their own, `encoded-api-path-security` passed in 15 s and `multiplayer-control-security` passed in 29 s without the limit. Neither sends a wrong password. - The two new regressions, `loopback-proxy-auth-security`, `docker-gateway-auth-security`, `docker-proxy-auth`, `android-local-auth`, `multiplayer-peer-server-security`, `route-rate-limits`, `prompt`, `group-prompt-regex`, `preset-regex-defaults` and every `lorebook` regression (23 files): passed. - Both new regressions were also run against `staging` code: both fail there. - After the first review fix (signed-in cookie, 6e948eded): `pnpm check` passed; `pnpm regression:security` passed (25/25 plus the extra suites); `basic-auth-throttle-security` fails on the previous head and passes now; `loopback-proxy-auth-security`, `route-rate-limits` and `multiplayer-peer-server-security` passed. - After the second review fix (server-keyed cookie, its own try limit, `Secure` behind a local HTTPS proxy, a36973201): `pnpm check` passed; `basic-auth-throttle-security` fails on 6e948eded and passes now; `loopback-proxy-auth-security`, `docker-gateway-auth-security`, `docker-proxy-auth`, `android-local-auth` and `route-rate-limits` passed. The results of a full `pnpm regression:security` rerun are in a PR comment. - After the third review fix (`/api/health` counts a signed-in browser's passwords against its extra tries, 935f2dce8): `pnpm format:check` and the server lint (`tsc`) passed; `basic-auth-throttle-security` fails on a36973201 and passes now. ### Manual verification notes - Manually verify that a chat whose prompt regex scripts edit short user messages (for example a name swap or an OOC strip) still sends the edited text: open **Peek prompt** and compare. - Manually verify that a regex script with a slow pattern on a short message is skipped within a moment and the server log names it, while the rest of the app keeps responding. - With `BASIC_AUTH_USER` and `BASIC_AUTH_PASS` set, open the app from another device and enter 10 different wrong passwords: manually verify that the next try shows "Too many wrong passwords" (429) and that the server log has one warn line for the first wrong password and one for the limit. - Manually verify that after the block ends (15 minutes, or a server restart) the correct password signs in. - Manually verify that a browser holding an old saved password after you change `BASIC_AUTH_PASS` is asked again and is not blocked. - Behind a reverse proxy or tunnel on the host: sign in once from your own browser, then send 10 different wrong passwords from another browser. Manually verify that your browser keeps working without a new prompt, and that the other browser gets "Too many wrong passwords" even with the correct password. - Manually verify that the browser's cookie list for the app shows `marinara_signed_in` as HttpOnly after signing in (and Secure when opened over HTTPS, for example through a tunnel), and that after changing `BASIC_AUTH_PASS` that browser is asked for the new password. - Manually verify that the first remote sign-in on a fresh data folder creates `.encryption-key` in the data folder if it is not there yet, and that remembered browsers keep working after a server restart. - Manually verify that the host computer itself (direct `127.0.0.1`) stays passwordless, and that a reverse proxy or tunnel on the host still asks its visitors to sign in. ## Docs and release impact - [ ] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README) as needed - [ ] Translated docs on the `docs-i18n` branch updated to match, or a `[docs-i18n]` follow-up issue opened (see CONTRIBUTING.md § Translated documentation) - [ ] Version/release files updated (only if this PR includes a version bump) English docs changed: `docs/REMOTE_ACCESS.md`, `docs/TROUBLESHOOTING.md` (the release translation sweep picks these up). ## UI evidence (if applicable) No UI changes. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Basic Auth sign-ins are temporarily rate-limited after 10 distinct incorrect passwords from the same client address within 15 minutes. Locked-out clients receive a retry time; the limit clears when the window expires or the server restarts. * Previously signed-in browsers can continue accessing protected pages during a lockout if they provide the correct password. Visitors sharing a proxy or tunnel share a failure count, which their successful sign-ins do not clear. * **Bug Fixes** * Regex replacements now receive timeout protection regardless of message length. * **Documentation** * Updated remote access and troubleshooting guidance with details on sign-in limits and recovery. <!-- 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-24 04:09:06 +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#7950
No description provided.