[PR #725] [MERGED] fix(csrf): surface untrusted-origin saves in the UI instead of failing silently #4746

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

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/725
Author: @LukaTheHero
Created: 5/12/2026
Status: ✅ Merged
Merged: 5/12/2026
Merged by: @LukaTheHero

Base: main ← Head: fix/csrf-origin-trust-banner


📝 Commits (2)

  • d76dfaf fix(csrf): surface untrusted-origin saves in the UI instead of failing silently
  • f2bc9e5 fix(csrf): extract env line correctly when the hinted origin contains dots

📊 Changes

12 files changed (+598 additions, -9 deletions)

View changed files

📝 .env.example (+18 -4)
📝 CHANGELOG.md (+1 -0)
📝 docs/REMOTE_ACCESS.md (+1 -1)
📝 docs/TROUBLESHOOTING.md (+1 -1)
📝 packages/client/src/App.tsx (+2 -0)
➕ packages/client/src/components/diagnostics/CsrfOriginWarningBanner.tsx (+209 -0)
📝 packages/client/src/lib/csrf-fetch.ts (+70 -3)
📝 packages/server/src/index.ts (+2 -0)
📝 packages/server/src/middleware/csrf-protection.ts (+108 -0)
➕ packages/server/src/routes/csrf-diagnostics.routes.ts (+23 -0)
📝 packages/server/src/routes/index.ts (+2 -0)
📝 packages/server/test/security-middleware.test.ts (+161 -0)

📄 Description

Summary

Closes #722.

A self-hosted Marinara instance reached through a public IP, reverse-proxy domain, or Tailscale MagicDNS hostname is not auto-trusted by the CSRF hook, so any unsafe API request gets a 403. The rejection was invisible to the user — chats stayed promptPresetId: null, settings reverted on reload, and the failure mode looked like a model-quality regression instead of a config issue.

Why this matters

The reporter spent significant time chasing what looked like a prompt-quality bug in SillyTavern-style roleplay, because Marinara's UI accepted a preset selection that the server then silently refused to persist. They ended up reaching out on Discord to debug it. Other self-hosters on public IPs / reverse proxies / Tailscale MagicDNS are hitting the same wall and probably quitting rather than diagnosing it.

What changed

Three layers cover the silent-failure case:

  1. Sticky red top banner on page load when the current origin would be rejected. Driven by a new read-only GET /api/csrf/origin-status endpoint that reports the trust verdict without triggering the CSRF-hook reject-log cache. The banner shows the offending origin, the exact .env line, a one-click Copy button, and a dismiss-for-session button.
  2. Sonner toast on any 403 from a same-origin unsafe API request. The fetch shim inspects every 403, detects the CSRF shape, and surfaces it as Save blocked: origin not trusted / : cross-site request rejected / : missing CSRF header with the .env hint as the description. Debounced per origin (10s) so parallel mutations don't stack identical toasts.
  3. Stable code field on every CSRF 403: CSRF_ORIGIN_NOT_TRUSTED, CSRF_REFERER_NOT_TRUSTED, CSRF_CROSS_SITE, CSRF_MISSING_HEADER. The client detects via code (with a fallback regex for older servers paired with newer clients).

Plus a startup diagnostic — the server logs the active CSRF auto-trust scope on boot:

  • [csrf] Auto-trusted (loopback): http://127.0.0.1:<PORT>, http://localhost:<PORT>
  • [csrf] Auto-trusted (HOST): <protocol>://<host>:<PORT> (when HOST is bound to a specific address)
  • [csrf] Auto-trusted (pattern): any RFC 1918 / CGNAT (Tailscale) / Docker / link-local IP literal where Origin matches Host
  • [csrf] CSRF_TRUSTED_ORIGINS: <comma-separated list>
  • a WARN when CSRF_TRUSTED_ORIGINS contains *

Auto-trust scope (unchanged)

These never had the bug and don't need to be added to CSRF_TRUSTED_ORIGINS:

  • Loopback (127.0.0.1:<PORT>, localhost:<PORT>)
  • LAN IP literals (RFC 1918: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)
  • Tailscale CGNAT IP literals (100.64.0.0/10)
  • Docker bridge IP literals (172.16.0.0/12)
  • IPv6 link-local / ULA literals

What still needs an explicit entry (and now surfaces the banner instead of failing silently):

  • Public IPs (e.g. http://203.0.113.10:7831)
  • Reverse-proxy domains (e.g. https://chat.example.com)
  • Tailscale MagicDNS hostnames (e.g. http://my-box.tailnet.ts.net:7860)
  • Custom hostname aliases

Multiple origins are comma-separated — parsing was always supported; .env.example and docs now show the syntax.

Files changed

Server

  • packages/server/src/middleware/csrf-protection.ts — added code field to all 4 reject bodies; new exported evaluateRequestOriginTrust() pure predicate; new getCsrfTrustSummary() / logCsrfTrustSummary() helpers.
  • packages/server/src/routes/csrf-diagnostics.routes.ts (new) — GET /api/csrf/origin-status.
  • packages/server/src/routes/index.ts — register the new route.
  • packages/server/src/index.ts — log auto-trust scope after listen.
  • packages/server/test/security-middleware.test.ts — assertions for the new code field, a comma-separated multi-origin test, and three new tests for the diagnostic endpoint.

Client

  • packages/client/src/lib/csrf-fetch.ts — fetch shim now inspects 403 bodies and pops a sonner toast on CSRF rejection.
  • packages/client/src/components/diagnostics/CsrfOriginWarningBanner.tsx (new) — sticky top banner mounted in App.tsx alongside <Toaster>. Uses var(--destructive) so it picks up the active theme.
  • packages/client/src/App.tsx — mount the banner.

Docs / config

  • .env.example — full rewrite of the CSRF_TRUSTED_ORIGINS comment with auto-trust list, when-to-add guidance, multi-origin example, and the * warning.
  • docs/TROUBLESHOOTING.md and docs/REMOTE_ACCESS.md — describe the new banner, toast, code field, and multi-origin syntax.
  • CHANGELOG.md — Unreleased > Fixed entry.

What's deliberately out of scope

  • Auto-trusting public IPs or DNS hostnames would open DNS-rebinding holes. Not done.
  • A Settings UI to edit CSRF_TRUSTED_ORIGINS from the browser — the banner has a copy-paste flow today; a Settings editor is a separate UX call worth its own PR.
  • Making the banner non-dismissible — the dismiss is session-scoped (sessionStorage), so it reappears on every reload until the operator fixes .env.

Reporter context

Originally surfaced by chai on Discord, where a user thought their roleplay output had regressed because Marinara's universal preset wasn't being applied. The actual cause was the public-IP origin rejection silently nulling out promptPresetId. Issue #722 was filed with the full repro.

Summary by CodeRabbit

  • New Features

    • Added a sticky CSRF origin warning banner in the UI that alerts users when their origin isn't trusted, with a one-click copy button to simplify configuration of CSRF_TRUSTED_ORIGINS.
    • Added diagnostics endpoint to check current origin's CSRF trust status.
  • Bug Fixes

    • CSRF rejections now surface visibly in the UI and logs with clear, stable error codes.
    • Toast notifications now appear for CSRF-related save failures.
  • Documentation

    • Expanded troubleshooting guides for remote access and CSRF configuration.
    • Updated .env.example with detailed guidance on auto-trusted origins and manual configuration.

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/725 **Author:** [@LukaTheHero](https://github.com/LukaTheHero) **Created:** 5/12/2026 **Status:** ✅ Merged **Merged:** 5/12/2026 **Merged by:** [@LukaTheHero](https://github.com/LukaTheHero) **Base:** `main` ← **Head:** `fix/csrf-origin-trust-banner` --- ### 📝 Commits (2) - [`d76dfaf`](https://github.com/Pasta-Devs/Marinara-Engine/commit/d76dfaf2faca84a2a12e2511693b3688b4a228a1) fix(csrf): surface untrusted-origin saves in the UI instead of failing silently - [`f2bc9e5`](https://github.com/Pasta-Devs/Marinara-Engine/commit/f2bc9e52b87c9f5c73ca416485271e564d33f680) fix(csrf): extract env line correctly when the hinted origin contains dots ### 📊 Changes **12 files changed** (+598 additions, -9 deletions) <details> <summary>View changed files</summary> 📝 `.env.example` (+18 -4) 📝 `CHANGELOG.md` (+1 -0) 📝 `docs/REMOTE_ACCESS.md` (+1 -1) 📝 `docs/TROUBLESHOOTING.md` (+1 -1) 📝 `packages/client/src/App.tsx` (+2 -0) ➕ `packages/client/src/components/diagnostics/CsrfOriginWarningBanner.tsx` (+209 -0) 📝 `packages/client/src/lib/csrf-fetch.ts` (+70 -3) 📝 `packages/server/src/index.ts` (+2 -0) 📝 `packages/server/src/middleware/csrf-protection.ts` (+108 -0) ➕ `packages/server/src/routes/csrf-diagnostics.routes.ts` (+23 -0) 📝 `packages/server/src/routes/index.ts` (+2 -0) 📝 `packages/server/test/security-middleware.test.ts` (+161 -0) </details> ### 📄 Description ## Summary Closes #722. A self-hosted Marinara instance reached through a public IP, reverse-proxy domain, or Tailscale MagicDNS hostname is not auto-trusted by the CSRF hook, so any unsafe API request gets a 403. The rejection was invisible to the user — chats stayed `promptPresetId: null`, settings reverted on reload, and the failure mode looked like a model-quality regression instead of a config issue. ## Why this matters The reporter spent significant time chasing what looked like a prompt-quality bug in SillyTavern-style roleplay, because Marinara's UI accepted a preset selection that the server then silently refused to persist. They ended up reaching out on Discord to debug it. Other self-hosters on public IPs / reverse proxies / Tailscale MagicDNS are hitting the same wall and probably quitting rather than diagnosing it. ## What changed Three layers cover the silent-failure case: 1. **Sticky red top banner on page load** when the current origin would be rejected. Driven by a new read-only `GET /api/csrf/origin-status` endpoint that reports the trust verdict without triggering the CSRF-hook reject-log cache. The banner shows the offending origin, the exact `.env` line, a one-click **Copy** button, and a dismiss-for-session button. 2. **Sonner toast on any 403** from a same-origin unsafe API request. The fetch shim inspects every 403, detects the CSRF shape, and surfaces it as ``Save blocked: origin not trusted`` / ``: cross-site request rejected`` / ``: missing CSRF header`` with the `.env` hint as the description. Debounced per origin (10s) so parallel mutations don't stack identical toasts. 3. **Stable `code` field on every CSRF 403**: `CSRF_ORIGIN_NOT_TRUSTED`, `CSRF_REFERER_NOT_TRUSTED`, `CSRF_CROSS_SITE`, `CSRF_MISSING_HEADER`. The client detects via `code` (with a fallback regex for older servers paired with newer clients). Plus a **startup diagnostic** — the server logs the active CSRF auto-trust scope on boot: - ``[csrf] Auto-trusted (loopback): http://127.0.0.1:<PORT>, http://localhost:<PORT>`` - ``[csrf] Auto-trusted (HOST): <protocol>://<host>:<PORT>`` (when HOST is bound to a specific address) - ``[csrf] Auto-trusted (pattern): any RFC 1918 / CGNAT (Tailscale) / Docker / link-local IP literal where Origin matches Host`` - ``[csrf] CSRF_TRUSTED_ORIGINS: <comma-separated list>`` - a ``WARN`` when CSRF_TRUSTED_ORIGINS contains ``*`` ## Auto-trust scope (unchanged) These never had the bug and don't need to be added to ``CSRF_TRUSTED_ORIGINS``: - Loopback (``127.0.0.1:<PORT>``, ``localhost:<PORT>``) - LAN IP literals (RFC 1918: ``10.0.0.0/8``, ``172.16.0.0/12``, ``192.168.0.0/16``) - Tailscale CGNAT IP literals (``100.64.0.0/10``) - Docker bridge IP literals (``172.16.0.0/12``) - IPv6 link-local / ULA literals What still needs an explicit entry (and now surfaces the banner instead of failing silently): - Public IPs (e.g. ``http://203.0.113.10:7831``) - Reverse-proxy domains (e.g. ``https://chat.example.com``) - Tailscale MagicDNS hostnames (e.g. ``http://my-box.tailnet.ts.net:7860``) - Custom hostname aliases Multiple origins are comma-separated — parsing was always supported; ``.env.example`` and docs now show the syntax. ## Files changed **Server** - ``packages/server/src/middleware/csrf-protection.ts`` — added ``code`` field to all 4 reject bodies; new exported ``evaluateRequestOriginTrust()`` pure predicate; new ``getCsrfTrustSummary()`` / ``logCsrfTrustSummary()`` helpers. - ``packages/server/src/routes/csrf-diagnostics.routes.ts`` (new) — ``GET /api/csrf/origin-status``. - ``packages/server/src/routes/index.ts`` — register the new route. - ``packages/server/src/index.ts`` — log auto-trust scope after listen. - ``packages/server/test/security-middleware.test.ts`` — assertions for the new ``code`` field, a comma-separated multi-origin test, and three new tests for the diagnostic endpoint. **Client** - ``packages/client/src/lib/csrf-fetch.ts`` — fetch shim now inspects 403 bodies and pops a sonner toast on CSRF rejection. - ``packages/client/src/components/diagnostics/CsrfOriginWarningBanner.tsx`` (new) — sticky top banner mounted in ``App.tsx`` alongside ``<Toaster>``. Uses ``var(--destructive)`` so it picks up the active theme. - ``packages/client/src/App.tsx`` — mount the banner. **Docs / config** - ``.env.example`` — full rewrite of the ``CSRF_TRUSTED_ORIGINS`` comment with auto-trust list, when-to-add guidance, multi-origin example, and the ``*`` warning. - ``docs/TROUBLESHOOTING.md`` and ``docs/REMOTE_ACCESS.md`` — describe the new banner, toast, ``code`` field, and multi-origin syntax. - ``CHANGELOG.md`` — Unreleased > Fixed entry. ## What's deliberately out of scope - **Auto-trusting public IPs or DNS hostnames** would open DNS-rebinding holes. Not done. - **A Settings UI to edit ``CSRF_TRUSTED_ORIGINS`` from the browser** — the banner has a copy-paste flow today; a Settings editor is a separate UX call worth its own PR. - **Making the banner non-dismissible** — the dismiss is session-scoped (sessionStorage), so it reappears on every reload until the operator fixes ``.env``. ## Reporter context Originally surfaced by chai on Discord, where a user thought their roleplay output had regressed because Marinara's universal preset wasn't being applied. The actual cause was the public-IP origin rejection silently nulling out ``promptPresetId``. Issue #722 was filed with the full repro. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added a sticky CSRF origin warning banner in the UI that alerts users when their origin isn't trusted, with a one-click copy button to simplify configuration of `CSRF_TRUSTED_ORIGINS`. * Added diagnostics endpoint to check current origin's CSRF trust status. * **Bug Fixes** * CSRF rejections now surface visibly in the UI and logs with clear, stable error codes. * Toast notifications now appear for CSRF-related save failures. * **Documentation** * Expanded troubleshooting guides for remote access and CSRF configuration. * Updated `.env.example` with detailed guidance on auto-trusted origins and manual configuration. [![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/725) <!-- 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:19 +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#4746
No description provided.