[PR #507] [MERGED] fix(diagnostics): self-serviceable network rejection errors + CORS hot-reload + auto-create .env #4647

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

📋 Pull Request Information

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

Base: main ← Head: fix/clearer-network-rejections-and-cors-hot-reload


📝 Commits (5)

  • cf3b03e fix(diagnostics): name the env var in SSRF/CSRF rejection messages, hot-reload CORS_ORIGINS
  • 1c451c6 fix(cors): auto-allow same-origin requests regardless of CORS_ORIGINS
  • 3a0ae06 fix(cors): wrap delegator in factory function so @fastify/cors loads it correctly
  • 4fdefd7 feat(env): auto-create an empty .env on first run so users can find it
  • e40e6ae fix(diagnostics): address CodeRabbit feedback on rejection-message hints

📊 Changes

14 files changed (+274 additions, -26 deletions)

View changed files

📝 docs/CONFIGURATION.md (+1 -1)
📝 docs/REMOTE_ACCESS.md (+4 -2)
📝 packages/server/src/app.ts (+8 -3)
➕ packages/server/src/config/cors-config.ts (+98 -0)
📝 packages/server/src/config/env-watcher.ts (+7 -1)
📝 packages/server/src/config/runtime-config.ts (+31 -1)
📝 packages/server/src/middleware/csrf-protection.ts (+47 -4)
📝 packages/server/src/routes/connections.routes.ts (+5 -3)
📝 packages/server/src/routes/translate.routes.ts (+6 -1)
📝 packages/server/src/routes/tts.routes.ts (+15 -3)
📝 packages/server/src/services/image/image-generation.ts (+1 -0)
📝 packages/server/src/services/llm/base-provider.ts (+6 -1)
📝 packages/server/src/services/tools/tool-executor.ts (+1 -0)
📝 packages/server/src/utils/security.ts (+44 -6)

📄 Description

Summary

Four recurring user complaints in #︱👓-ask-prof-mari over a 15h window all reduced to the same pattern: the user hit a network gate (SSRF, CSRF, or CORS), the rejection message didn't name the env var that controls it, and they had to ask in Discord or grep the source. This PR makes those failures self-serviceable: every rejection now names the exact env var and the exact line to paste into .env, the var takes effect without a restart, and the .env file itself auto-creates on first run so users can find it.

Concretely fixes:

  • grrthemis & ly.chan #1 (SSRF on 10.0.8.10, 192.168.x.x) — the SSRF rejection now reads Refused to fetch http://10.0.8.10:1234: '10.0.8.10' (resolved to 10.0.8.10) is in a private … IP range. Set PROVIDER_LOCAL_URLS_ENABLED=true in your .env file … instead of the previous generic message. (The block itself is unchanged — same IPs blocked, same flag re-allows them.)
  • ly.chan #2 (CSRF on character import) — the 403 body now has error, origin, and hint fields with the exact CSRF_TRUSTED_ORIGINS=… line to paste. CSRF_TRUSTED_ORIGINS was already hot-reloadable (per-request read).
  • gunterlie (Bifrost behind nginx-proxy-manager) — three pain points addressed: SSRF rejection now self-explains, CORS rejection now self-explains, and CORS_ORIGINS is now hot-reloadable so they don't need to restart after pasting the suggested line. Plus same-origin auto-allow means a typical reverse-proxy setup (where Host is preserved) just works without any CORS config at all.
  • Everyone — fresh installs that never ran cp .env.example .env no longer have to wonder where their config file is. An empty .env with a header pointing at .env.example is created on first boot.

Screenshot — new SSRF error surfaced in the Connection Test UI

What changed (per change, with rationale)

1. OutboundUrlPolicy carries an optional flagName; SSRF errors include it

packages/server/src/utils/security.ts

Extended OutboundUrlPolicy with an optional flagName?: string field. The three rejection sites in validateOutboundUrl / validateResolvedAddresses now build error messages that:

  • Quote the actual URL the operator tried to reach.
  • For DNS-resolved blocks, list the resolved IP(s) that triggered the rejection ('lmstudio.local' (resolved to 10.0.8.10)).
  • Append Set ${flagName}=true in your .env file … when flagName is set.

All five outbound-fetch dispatch sites pass the right flag for their provider type:

Site Flag
services/llm/base-provider.ts (LLM provider HTTP calls) PROVIDER_LOCAL_URLS_ENABLED
services/image/image-generation.ts (image gen) IMAGE_LOCAL_URLS_ENABLED
routes/translate.routes.ts (DeepLX) DEEPLX_LOCAL_URLS_ENABLED
routes/tts.routes.ts (TTS, three sites) TTS_LOCAL_URLS_ENABLED
services/tools/tool-executor.ts (custom-tool webhooks) WEBHOOK_LOCAL_URLS_ENABLED
routes/connections.routes.ts (localUrlPolicyForProvider, used for connection tests / model lists) IMAGE_LOCAL_URLS_ENABLED for image providers, otherwise PROVIDER_LOCAL_URLS_ENABLED

No security/policy change: the same set of IPs is blocked, the same flags re-allow them. Only the user-facing error text changed.

2. CSRF rejection 403 bodies include the offending origin and a paste-able hint

packages/server/src/middleware/csrf-protection.ts

The four 403 sites (Cross-site unsafe, Origin not trusted, Referer not trusted, Missing X-Marinara-CSRF) now return JSON like:

{
  "error": "Origin 'https://marinara.gunter.lan' is not in the trusted list (CSRF_TRUSTED_ORIGINS).",
  "origin": "https://marinara.gunter.lan",
  "hint": "Add to .env (no restart needed): CSRF_TRUSTED_ORIGINS=https://marinara.gunter.lan"
}

The server also logs a one-shot [csrf] warning per unique rejected origin (throttled via a per-process Set so a misbehaving client can't flood). That gives the operator the same diagnostic in their console without having to inspect the failing request body.

The "Missing X-Marinara-CSRF" branch additionally explains who needs that header: Marinara's frontend sends it automatically; non-browser callers (curl, Postman, scripts) must set it.

No security change: the gating logic is unchanged. Only the rejection text and a logging line are new.

3. CORS_ORIGINS is now hot-reloadable

packages/server/src/config/cors-config.ts (new), packages/server/src/app.ts, packages/server/src/config/env-watcher.ts

@fastify/cors was registered once at boot with a static getCorsConfig() value, so CORS_ORIGINS was on the env-watcher's RESTART_REQUIRED_KEYS list. Switched to @fastify/cors's per-request delegator (the register(cors, () => delegateFn) pattern) so the trusted set is re-evaluated on every request. CORS_ORIGINS is no longer in RESTART_REQUIRED_KEYS.

Documented caveat: the credentials field is still bound at boot, so the rare transition between an explicit-origin list (credentials=true) and a wildcard * (credentials=false) still requires a restart for the Access-Control-Allow-Credentials header to flip. Adding/removing entries within either mode is hot-reloadable.

4. CORS auto-allows same-origin requests regardless of CORS_ORIGINS

Same files as (3). Surfaced by my own diagnostic in (3) — the previous code (and original @fastify/cors registration before this branch) only checked the configured origin list, so a request from http://localhost:7860 to a server hosted at the same address was treated identically to a cross-site request. Most browsers tolerated this for simple GETs but POST preflights silently failed. The new diagnostic exposed the latent issue immediately when testing on Tailscale (http://<tailscale-ip>:7860).

The new corsDelegate(req, callback) decision order:

  1. No Origin header → not a CORS request, allow.
  2. Origin matches the request's own Host (true same-origin) → allow regardless of CORS_ORIGINS. The browser controls both Origin and Host for in-browser requests; they match iff the page is genuinely talking to itself, which is by definition not subject to CORS.
  3. Origin matches CORS_ORIGINS (or *) → allow with the configured credentials policy.
  4. Otherwise → reject; emit a one-shot [cors] Rejected cross-origin request from '<origin>' … log line with the exact CORS_ORIGINS=… line the operator should add.

No security loosening: same-origin is by definition not subject to CORS. Net behavior is permissive for browser flows that were already legal but were being incorrectly blocked, and unchanged for genuinely cross-origin requests.

A small fix-up commit (3a0ae06) corrected the @fastify/cors registration shape — the delegator API expects register(cors, () => delegateFn), not the delegate inline. The latter was being interpreted as a Fastify plugin definition function and crashed at boot when the loader called it with no request.

5. Auto-create empty .env on first run

packages/server/src/config/runtime-config.ts

Users frequently asked "where's my .env?" because Marinara doesn't ship with one — they're expected to cp .env.example .env, but many never do. loadRuntimeEnv() now calls ensureEnvFileExists() before parsing, which creates an empty .env (with a header pointing at .env.example) at the monorepo root iff one doesn't already exist.

Header content:

# Marinara Engine - runtime configuration.
# This file is empty by design. Copy any setting you want to change from
# .env.example (same folder) and edit the value here. Most changes take
# effect within ~2 seconds without a restart.

Edge cases handled:

  • Read-only filesystem (some Docker images, locked-down installer setups) → try/catch swallows the error, logs a warn, server continues. dotenv treats missing .env and empty .env identically, so this is purely best-effort.
  • Race condition between concurrent startups → uses the wx (write-exclusive) flag, ignores EEXIST. The losing process moves on without retry.
  • Existing user .env → existsSync check first; never overwritten, even if currently empty.
  • Watcher self-trigger → the create runs at module load (very early); startEnvWatcher() attaches later in index.ts. No spurious "env changed" event from the auto-creation. On subsequent restarts the file exists, so creation is skipped entirely.

Files changed

docs/CONFIGURATION.md                              |  2 +-
docs/REMOTE_ACCESS.md                              |  6 +-
packages/server/src/app.ts                         | 11 ++-
packages/server/src/config/cors-config.ts          | 98 ++++++++++++++++++++++   (new file)
packages/server/src/config/env-watcher.ts          |  8 +-
packages/server/src/config/runtime-config.ts       | 32 ++++++-
packages/server/src/middleware/csrf-protection.ts  | 48 ++++++++++-
packages/server/src/routes/connections.routes.ts   |  8 +-
packages/server/src/routes/translate.routes.ts     |  7 +-
packages/server/src/routes/tts.routes.ts           | 18 +++-
packages/server/src/services/image/image-generation.ts  |  1 +
packages/server/src/services/llm/base-provider.ts  |  7 +-
packages/server/src/services/tools/tool-executor.ts     |  1 +
packages/server/src/utils/security.ts              | 45 ++++++++--
14 files changed, 266 insertions(+), 26 deletions(-)

Why this PR has zero security cost

  • SSRF: error text changed; the safeFetch block list is byte-identical. The flags users learn to set (PROVIDER_LOCAL_URLS_ENABLED etc.) and the IPs they unblock are the same as before.
  • CSRF: gate logic unchanged; only the 403 body and a one-shot warn line are new. Disclosing the offending origin in the error is fine — the client already saw it (it's their own request).
  • CORS:
    • Same-origin auto-allow: the browser cannot spoof Host to differ from Origin for an in-browser request, so this is the canonical definition of same-origin and not subject to CORS by spec.
    • Hot-reload: same protection as before, just available without a restart.
    • Per-rejected-origin warning: pure log line, no functional change.
  • Auto-create .env: a placeholder file with a comment header. dotenv treats missing and empty .env identically. Read-only filesystems fall back to "no .env" mode just like today.
  • Related to #492 (open) — "name.local" base URL for OAI-compatible endpoint fails with "Outbound URL is local or reserved". This PR does not change which URLs are blocked (.local suffixes are still in the SSRF reserved list), but the rejection error now reads Refused to fetch http://name.local:5001/v1: hostname 'name.local' is local or reserved. Set PROVIDER_LOCAL_URLS_ENABLED=true in your .env file (changes take effect within ~2s without a restart). — so the operator can self-serve by pasting that flag into .env. Consider whether you'd rather upgrade this to Closes #492 (treating the opt-in as the documented answer) or keep it as a partial mitigation pending a different fix that restores pre-1.5.7 unconditional .local access.
  • Addresses recurrence pattern of #394 / #396 / #398 (closed) — these three closed bugs were the same kind of "post-1.5.7 hardening blocked me, the error didn't tell me what to do" pattern: #394 was loopback-mistakenly-blocked SSRF, #396 was Request Origin Not Trusted after enabling ALLOW_UNAUTHENTICATED_PRIVATE_NETWORK, #398 was a duplicate of #396. They were each fixed individually in the past, but a future user hitting any of them again would get a clearer, self-serviceable error after this PR — the SSRF rejection names PROVIDER_LOCAL_URLS_ENABLED, the CSRF rejection names CSRF_TRUSTED_ORIGINS with the exact value to add. Linked here so this PR shows up in their search trail if the same pattern resurfaces.

Notes

  • The motivation for this PR isn't a single open issue. It's a pattern I noticed repeating in the #︱👓-ask-prof-mari Discord support channel: multiple users in the same 15-hour window couldn't find their .env file, and several others hit SSRF / CSRF / CORS rejections without knowing which env var would fix them. They eventually learned and resolved it (often after Mari pointed them at the relevant flag), but the friction was the recurring theme rather than any specific bug.
  • Rebased on top of main after PR #463 (env hot-reload) and #464 (Tailscale/Docker auth bypass) merged. Builds cleanly on the current main.

CodeRabbit review responses

CodeRabbit raised four comments on the original commits. Status:

  1. cors-config.ts — append-style hint instead of replace-style ✅ Applied. The [cors] Rejected … log line now says add '<origin>' to CORS_ORIGINS in your .env — comma-separated if you already have entries, e.g. CORS_ORIGINS=http://existing.example,<origin>.
  2. csrf-protection.ts — same fix for CSRF_TRUSTED_ORIGINS ✅ Applied. New appendOriginHint() helper used in both the server log and the 403 hint field.
  3. security.ts — flagHint only on policy-driven rejections ✅ Applied. Removed from protocol-mismatch and DNS-failure errors (setting PROVIDER_LOCAL_URLS_ENABLED=true doesn't unblock gopher:// or NXDOMAIN); kept on the two policy.allowLocal-gated rejections (local hostname / blocked resolved IP) where it's actually actionable.
  4. security.ts — redact resolved IPs from error messages ❌ Declined. Marinara is single-tenant self-hosted: the operator submitting the URL is the same person reading the error. The resolved IP is the most useful debugging info ("oh, my LAN DNS resolved my hostname to a private IP, that's why it was blocked") — for the operator-debugging case the disclosure value is high, and for the hypothetical attacker case the disclosure value is roughly zero (the attacker put the URL in; they could just nslookup it themselves or test specific IPs directly). Keeping the IP in the error message.

Test plan (manually verified)

  • Auto-create .env: starting with no .env in the test dir, server boots, .env is created with the documented header.
  • Idempotent auto-create: editing .env (e.g. adding BASIC_AUTH_USER=alice), restarting → user's edit is preserved, no overwrite.
  • Same-origin from Tailscale: visiting http://<tailscale-ip>:7830 from a phone, doing POST flows (persona create, connection edit, etc.) — works without CORS_ORIGINS config and without [cors] Rejected … warnings in the server log.
  • Same-origin from loopback: http://localhost:7830 POST flows work without warnings.
  • SSRF error names PROVIDER_LOCAL_URLS_ENABLED: connection test against an LLM connection pointing at a private IP returns the new self-explaining error (see screenshot above).
  • SSRF unblock takes effect without restart: after the failure, adding PROVIDER_LOCAL_URLS_ENABLED=true to .env, saving (no restart), and re-clicking "Test" → Marinara is no longer the one blocking.
  • SSRF for image-gen names IMAGE_LOCAL_URLS_ENABLED: same flow with an image-generation connection.
  • CSRF rejection has paste-able hint: visiting via a custom hostname and doing a POST returns the new structured 403 body and a one-shot [csrf] server warning.
  • CSRF unblock takes effect without restart: pasting the suggested CSRF_TRUSTED_ORIGINS=… line into .env, saving, retrying the POST → succeeds without restart.
  • CORS_ORIGINS hot-reloadable: editing CORS_ORIGINS in .env while the server is running shows [env-watcher] Updated: CORS_ORIGINS=… and does NOT show up in the "These variables changed but require a server restart" warning.
  • CORS rejection diagnostic: a genuine cross-origin request (origin not in CORS_ORIGINS, not same-origin) emits a one-shot [cors] Rejected … log line with the exact CORS_ORIGINS=… line to add.
  • Tailscale auth-bypass still works: [auth-bypass] BYPASS_AUTH_TAILSCALE=true … log line fires once on first request from a Tailnet IP; phone session works without Basic Auth (sanity check that PR #464 still functions).

Summary by CodeRabbit

Release Notes

  • New Features

    • CORS configuration now hot-reloads without restart for most changes (except wildcard switching).
    • Same-origin requests are automatically allowed based on Host matching.
    • .env file is auto-created on startup if missing.
  • Improvements

    • Error messages now include actionable .env configuration hints for CORS, CSRF, and network issues.
    • Enhanced troubleshooting documentation with specific remediation steps.
  • Documentation

    • Updated configuration guide with clarity on which settings require restarts.

🔄 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/507 **Author:** [@LukaTheHero](https://github.com/LukaTheHero) **Created:** 5/7/2026 **Status:** ✅ Merged **Merged:** 5/7/2026 **Merged by:** [@LukaTheHero](https://github.com/LukaTheHero) **Base:** `main` ← **Head:** `fix/clearer-network-rejections-and-cors-hot-reload` --- ### 📝 Commits (5) - [`cf3b03e`](https://github.com/Pasta-Devs/Marinara-Engine/commit/cf3b03e064120e07839a50b9db2b894601d2cad1) fix(diagnostics): name the env var in SSRF/CSRF rejection messages, hot-reload CORS_ORIGINS - [`1c451c6`](https://github.com/Pasta-Devs/Marinara-Engine/commit/1c451c64e7dfb75a082773ae54fef30f46e17896) fix(cors): auto-allow same-origin requests regardless of CORS_ORIGINS - [`3a0ae06`](https://github.com/Pasta-Devs/Marinara-Engine/commit/3a0ae06d7732af24d9c7e151e55abd408e70e444) fix(cors): wrap delegator in factory function so @fastify/cors loads it correctly - [`4fdefd7`](https://github.com/Pasta-Devs/Marinara-Engine/commit/4fdefd775cf7ce0e8f10d2a7c01518da3dbfa8a4) feat(env): auto-create an empty .env on first run so users can find it - [`e40e6ae`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e40e6ae5237c9ef2c45ce7d16c5cfe5678962f91) fix(diagnostics): address CodeRabbit feedback on rejection-message hints ### 📊 Changes **14 files changed** (+274 additions, -26 deletions) <details> <summary>View changed files</summary> 📝 `docs/CONFIGURATION.md` (+1 -1) 📝 `docs/REMOTE_ACCESS.md` (+4 -2) 📝 `packages/server/src/app.ts` (+8 -3) ➕ `packages/server/src/config/cors-config.ts` (+98 -0) 📝 `packages/server/src/config/env-watcher.ts` (+7 -1) 📝 `packages/server/src/config/runtime-config.ts` (+31 -1) 📝 `packages/server/src/middleware/csrf-protection.ts` (+47 -4) 📝 `packages/server/src/routes/connections.routes.ts` (+5 -3) 📝 `packages/server/src/routes/translate.routes.ts` (+6 -1) 📝 `packages/server/src/routes/tts.routes.ts` (+15 -3) 📝 `packages/server/src/services/image/image-generation.ts` (+1 -0) 📝 `packages/server/src/services/llm/base-provider.ts` (+6 -1) 📝 `packages/server/src/services/tools/tool-executor.ts` (+1 -0) 📝 `packages/server/src/utils/security.ts` (+44 -6) </details> ### 📄 Description ## Summary Four recurring user complaints in #︱👓-ask-prof-mari over a 15h window all reduced to the same pattern: the user hit a network gate (SSRF, CSRF, or CORS), the rejection message didn't name the env var that controls it, and they had to ask in Discord or grep the source. This PR makes those failures self-serviceable: every rejection now names the exact env var and the exact line to paste into `.env`, the var takes effect without a restart, and the `.env` file itself auto-creates on first run so users can find it. **Concretely fixes:** - **grrthemis & ly.chan #1** (SSRF on `10.0.8.10`, `192.168.x.x`) — the SSRF rejection now reads `Refused to fetch http://10.0.8.10:1234: '10.0.8.10' (resolved to 10.0.8.10) is in a private … IP range. Set PROVIDER_LOCAL_URLS_ENABLED=true in your .env file …` instead of the previous generic message. (The block itself is unchanged — same IPs blocked, same flag re-allows them.) - **ly.chan #2** (CSRF on character import) — the 403 body now has `error`, `origin`, and `hint` fields with the exact `CSRF_TRUSTED_ORIGINS=…` line to paste. `CSRF_TRUSTED_ORIGINS` was already hot-reloadable (per-request read). - **gunterlie** (Bifrost behind nginx-proxy-manager) — three pain points addressed: SSRF rejection now self-explains, CORS rejection now self-explains, and `CORS_ORIGINS` is now hot-reloadable so they don't need to restart after pasting the suggested line. Plus same-origin auto-allow means a typical reverse-proxy setup (where Host is preserved) just works without any CORS config at all. - **Everyone** — fresh installs that never ran `cp .env.example .env` no longer have to wonder where their config file is. An empty `.env` with a header pointing at `.env.example` is created on first boot. ## Screenshot — new SSRF error surfaced in the Connection Test UI <!-- DRAG THE SCREENSHOT INTO THIS LINE → it will replace this comment with the uploaded image --> ## What changed (per change, with rationale) ### 1. `OutboundUrlPolicy` carries an optional `flagName`; SSRF errors include it `packages/server/src/utils/security.ts` Extended `OutboundUrlPolicy` with an optional `flagName?: string` field. The three rejection sites in `validateOutboundUrl` / `validateResolvedAddresses` now build error messages that: - Quote the actual URL the operator tried to reach. - For DNS-resolved blocks, list the resolved IP(s) that triggered the rejection (`'lmstudio.local' (resolved to 10.0.8.10)`). - Append `Set ${flagName}=true in your .env file …` when `flagName` is set. All five outbound-fetch dispatch sites pass the right flag for their provider type: | Site | Flag | |---|---| | `services/llm/base-provider.ts` (LLM provider HTTP calls) | `PROVIDER_LOCAL_URLS_ENABLED` | | `services/image/image-generation.ts` (image gen) | `IMAGE_LOCAL_URLS_ENABLED` | | `routes/translate.routes.ts` (DeepLX) | `DEEPLX_LOCAL_URLS_ENABLED` | | `routes/tts.routes.ts` (TTS, three sites) | `TTS_LOCAL_URLS_ENABLED` | | `services/tools/tool-executor.ts` (custom-tool webhooks) | `WEBHOOK_LOCAL_URLS_ENABLED` | | `routes/connections.routes.ts` (`localUrlPolicyForProvider`, used for connection tests / model lists) | `IMAGE_LOCAL_URLS_ENABLED` for image providers, otherwise `PROVIDER_LOCAL_URLS_ENABLED` | **No security/policy change**: the same set of IPs is blocked, the same flags re-allow them. Only the user-facing error text changed. ### 2. CSRF rejection 403 bodies include the offending origin and a paste-able hint `packages/server/src/middleware/csrf-protection.ts` The four 403 sites (`Cross-site unsafe`, `Origin not trusted`, `Referer not trusted`, `Missing X-Marinara-CSRF`) now return JSON like: ```json { "error": "Origin 'https://marinara.gunter.lan' is not in the trusted list (CSRF_TRUSTED_ORIGINS).", "origin": "https://marinara.gunter.lan", "hint": "Add to .env (no restart needed): CSRF_TRUSTED_ORIGINS=https://marinara.gunter.lan" } ``` The server also logs a one-shot `[csrf]` warning per unique rejected origin (throttled via a per-process `Set` so a misbehaving client can't flood). That gives the operator the same diagnostic in their console without having to inspect the failing request body. The "Missing X-Marinara-CSRF" branch additionally explains who needs that header: Marinara's frontend sends it automatically; non-browser callers (curl, Postman, scripts) must set it. **No security change**: the gating logic is unchanged. Only the rejection text and a logging line are new. ### 3. `CORS_ORIGINS` is now hot-reloadable `packages/server/src/config/cors-config.ts` (new), `packages/server/src/app.ts`, `packages/server/src/config/env-watcher.ts` `@fastify/cors` was registered once at boot with a static `getCorsConfig()` value, so `CORS_ORIGINS` was on the env-watcher's `RESTART_REQUIRED_KEYS` list. Switched to `@fastify/cors`'s per-request delegator (the `register(cors, () => delegateFn)` pattern) so the trusted set is re-evaluated on every request. `CORS_ORIGINS` is no longer in `RESTART_REQUIRED_KEYS`. **Documented caveat**: the `credentials` field is still bound at boot, so the rare transition between an explicit-origin list (`credentials=true`) and a wildcard `*` (`credentials=false`) still requires a restart for the `Access-Control-Allow-Credentials` header to flip. Adding/removing entries within either mode is hot-reloadable. ### 4. CORS auto-allows same-origin requests regardless of `CORS_ORIGINS` Same files as (3). Surfaced by my own diagnostic in (3) — the previous code (and original `@fastify/cors` registration before this branch) only checked the configured origin list, so a request from `http://localhost:7860` to a server hosted at the same address was treated identically to a cross-site request. Most browsers tolerated this for simple GETs but POST preflights silently failed. The new diagnostic exposed the latent issue immediately when testing on Tailscale (`http://<tailscale-ip>:7860`). The new `corsDelegate(req, callback)` decision order: 1. **No `Origin` header** → not a CORS request, allow. 2. **`Origin` matches the request's own `Host`** (true same-origin) → allow regardless of `CORS_ORIGINS`. The browser controls both `Origin` and `Host` for in-browser requests; they match iff the page is genuinely talking to itself, which is by definition not subject to CORS. 3. **`Origin` matches `CORS_ORIGINS`** (or `*`) → allow with the configured credentials policy. 4. **Otherwise** → reject; emit a one-shot `[cors] Rejected cross-origin request from '<origin>' …` log line with the exact `CORS_ORIGINS=…` line the operator should add. **No security loosening**: same-origin is by definition not subject to CORS. Net behavior is permissive for browser flows that were already legal but were being incorrectly blocked, and unchanged for genuinely cross-origin requests. A small fix-up commit (`3a0ae06`) corrected the `@fastify/cors` registration shape — the delegator API expects `register(cors, () => delegateFn)`, not the delegate inline. The latter was being interpreted as a Fastify plugin definition function and crashed at boot when the loader called it with no request. ### 5. Auto-create empty `.env` on first run `packages/server/src/config/runtime-config.ts` Users frequently asked "where's my `.env`?" because Marinara doesn't ship with one — they're expected to `cp .env.example .env`, but many never do. `loadRuntimeEnv()` now calls `ensureEnvFileExists()` before parsing, which creates an empty `.env` (with a header pointing at `.env.example`) at the monorepo root iff one doesn't already exist. Header content: ``` # Marinara Engine - runtime configuration. # This file is empty by design. Copy any setting you want to change from # .env.example (same folder) and edit the value here. Most changes take # effect within ~2 seconds without a restart. ``` Edge cases handled: - **Read-only filesystem** (some Docker images, locked-down installer setups) → `try/catch` swallows the error, logs a warn, server continues. dotenv treats missing `.env` and empty `.env` identically, so this is purely best-effort. - **Race condition between concurrent startups** → uses the `wx` (write-exclusive) flag, ignores `EEXIST`. The losing process moves on without retry. - **Existing user `.env`** → `existsSync` check first; never overwritten, even if currently empty. - **Watcher self-trigger** → the create runs at module load (very early); `startEnvWatcher()` attaches later in `index.ts`. No spurious "env changed" event from the auto-creation. On subsequent restarts the file exists, so creation is skipped entirely. ## Files changed ``` docs/CONFIGURATION.md | 2 +- docs/REMOTE_ACCESS.md | 6 +- packages/server/src/app.ts | 11 ++- packages/server/src/config/cors-config.ts | 98 ++++++++++++++++++++++ (new file) packages/server/src/config/env-watcher.ts | 8 +- packages/server/src/config/runtime-config.ts | 32 ++++++- packages/server/src/middleware/csrf-protection.ts | 48 ++++++++++- packages/server/src/routes/connections.routes.ts | 8 +- packages/server/src/routes/translate.routes.ts | 7 +- packages/server/src/routes/tts.routes.ts | 18 +++- packages/server/src/services/image/image-generation.ts | 1 + packages/server/src/services/llm/base-provider.ts | 7 +- packages/server/src/services/tools/tool-executor.ts | 1 + packages/server/src/utils/security.ts | 45 ++++++++-- 14 files changed, 266 insertions(+), 26 deletions(-) ``` ## Why this PR has zero security cost - **SSRF**: error text changed; the `safeFetch` block list is byte-identical. The flags users learn to set (`PROVIDER_LOCAL_URLS_ENABLED` etc.) and the IPs they unblock are the same as before. - **CSRF**: gate logic unchanged; only the 403 body and a one-shot warn line are new. Disclosing the offending origin in the error is fine — the client already saw it (it's their own request). - **CORS**: - Same-origin auto-allow: the browser cannot spoof `Host` to differ from `Origin` for an in-browser request, so this is the canonical definition of same-origin and not subject to CORS by spec. - Hot-reload: same protection as before, just available without a restart. - Per-rejected-origin warning: pure log line, no functional change. - **Auto-create `.env`**: a placeholder file with a comment header. dotenv treats missing and empty `.env` identically. Read-only filesystems fall back to "no .env" mode just like today. ## Related issues - **Related to #492** (open) — `"name.local"` base URL for OAI-compatible endpoint fails with `"Outbound URL is local or reserved"`. This PR does not change which URLs are blocked (`.local` suffixes are still in the SSRF reserved list), but the rejection error now reads `Refused to fetch http://name.local:5001/v1: hostname 'name.local' is local or reserved. Set PROVIDER_LOCAL_URLS_ENABLED=true in your .env file (changes take effect within ~2s without a restart).` — so the operator can self-serve by pasting that flag into `.env`. Consider whether you'd rather upgrade this to `Closes #492` (treating the opt-in as the documented answer) or keep it as a partial mitigation pending a different fix that restores pre-1.5.7 unconditional `.local` access. - **Addresses recurrence pattern of #394 / #396 / #398** (closed) — these three closed bugs were the same kind of "post-1.5.7 hardening blocked me, the error didn't tell me what to do" pattern: #394 was loopback-mistakenly-blocked SSRF, #396 was `Request Origin Not Trusted` after enabling `ALLOW_UNAUTHENTICATED_PRIVATE_NETWORK`, #398 was a duplicate of #396. They were each fixed individually in the past, but a future user hitting any of them again would get a clearer, self-serviceable error after this PR — the SSRF rejection names `PROVIDER_LOCAL_URLS_ENABLED`, the CSRF rejection names `CSRF_TRUSTED_ORIGINS` with the exact value to add. Linked here so this PR shows up in their search trail if the same pattern resurfaces. ## Notes - The motivation for this PR isn't a single open issue. It's a pattern I noticed repeating in the #︱👓-ask-prof-mari Discord support channel: multiple users in the same 15-hour window couldn't find their `.env` file, and several others hit SSRF / CSRF / CORS rejections without knowing which env var would fix them. They eventually learned and resolved it (often after Mari pointed them at the relevant flag), but the friction was the recurring theme rather than any specific bug. - Rebased on top of `main` after PR #463 (env hot-reload) and #464 (Tailscale/Docker auth bypass) merged. Builds cleanly on the current `main`. ## CodeRabbit review responses CodeRabbit raised four comments on the original commits. Status: 1. **`cors-config.ts` — append-style hint instead of replace-style** ✅ Applied. The `[cors] Rejected …` log line now says `add '<origin>' to CORS_ORIGINS in your .env — comma-separated if you already have entries, e.g. CORS_ORIGINS=http://existing.example,<origin>`. 2. **`csrf-protection.ts` — same fix for `CSRF_TRUSTED_ORIGINS`** ✅ Applied. New `appendOriginHint()` helper used in both the server log and the 403 `hint` field. 3. **`security.ts` — `flagHint` only on policy-driven rejections** ✅ Applied. Removed from protocol-mismatch and DNS-failure errors (setting `PROVIDER_LOCAL_URLS_ENABLED=true` doesn't unblock `gopher://` or `NXDOMAIN`); kept on the two `policy.allowLocal`-gated rejections (local hostname / blocked resolved IP) where it's actually actionable. 4. **`security.ts` — redact resolved IPs from error messages** ❌ Declined. Marinara is single-tenant self-hosted: the operator submitting the URL is the same person reading the error. The resolved IP is the most useful debugging info ("oh, my LAN DNS resolved my hostname to a private IP, that's why it was blocked") — for the operator-debugging case the disclosure value is high, and for the hypothetical attacker case the disclosure value is roughly zero (the attacker put the URL in; they could just `nslookup` it themselves or test specific IPs directly). Keeping the IP in the error message. ## Test plan (manually verified) - [x] **Auto-create `.env`**: starting with no `.env` in the test dir, server boots, `.env` is created with the documented header. - [x] **Idempotent auto-create**: editing `.env` (e.g. adding `BASIC_AUTH_USER=alice`), restarting → user's edit is preserved, no overwrite. - [x] **Same-origin from Tailscale**: visiting `http://<tailscale-ip>:7830` from a phone, doing POST flows (persona create, connection edit, etc.) — works without `CORS_ORIGINS` config and without `[cors] Rejected …` warnings in the server log. - [x] **Same-origin from loopback**: `http://localhost:7830` POST flows work without warnings. - [x] **SSRF error names `PROVIDER_LOCAL_URLS_ENABLED`**: connection test against an LLM connection pointing at a private IP returns the new self-explaining error (see screenshot above). - [x] **SSRF unblock takes effect without restart**: after the failure, adding `PROVIDER_LOCAL_URLS_ENABLED=true` to `.env`, saving (no restart), and re-clicking "Test" → Marinara is no longer the one blocking. - [x] **SSRF for image-gen names `IMAGE_LOCAL_URLS_ENABLED`**: same flow with an image-generation connection. - [x] **CSRF rejection has paste-able hint**: visiting via a custom hostname and doing a POST returns the new structured 403 body and a one-shot `[csrf]` server warning. - [x] **CSRF unblock takes effect without restart**: pasting the suggested `CSRF_TRUSTED_ORIGINS=…` line into `.env`, saving, retrying the POST → succeeds without restart. - [x] **`CORS_ORIGINS` hot-reloadable**: editing `CORS_ORIGINS` in `.env` while the server is running shows `[env-watcher] Updated: CORS_ORIGINS=…` and does NOT show up in the "These variables changed but require a server restart" warning. - [x] **CORS rejection diagnostic**: a genuine cross-origin request (origin not in `CORS_ORIGINS`, not same-origin) emits a one-shot `[cors] Rejected …` log line with the exact `CORS_ORIGINS=…` line to add. - [x] **Tailscale auth-bypass still works**: `[auth-bypass] BYPASS_AUTH_TAILSCALE=true …` log line fires once on first request from a Tailnet IP; phone session works without Basic Auth (sanity check that PR #464 still functions). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Release Notes * **New Features** * CORS configuration now hot-reloads without restart for most changes (except wildcard switching). * Same-origin requests are automatically allowed based on Host matching. * `.env` file is auto-created on startup if missing. * **Improvements** * Error messages now include actionable `.env` configuration hints for CORS, CSRF, and network issues. * Enhanced troubleshooting documentation with specific remediation steps. * **Documentation** * Updated configuration guide with clarity on which settings require restarts. <!-- 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:09:27 +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#4647
No description provided.