mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[PR #507] [MERGED] fix(diagnostics): self-serviceable network rejection errors + CORS hot-reload + auto-create .env #4647
Labels
No labels
android
bug
bugfix
ci
client
code freeze pause
container
dependencies
docs
documentation
duplicate
enhancement
feature
feature
feature
feature-creep
fixed-in-refactor
fixed-in-staging
good first issue
help wanted
in-pr
in-pr
needs-codeowner-decision
normal-scope
old-codebase
old-codebase
pull-request
qol
question
refactor
regression
revisit later
roadmap
scope-risk
scope-risk
server
server
shared
soup
upstream
windows
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Pasta-Devs/Marinara-Engine#4647
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 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)
cf3b03efix(diagnostics): name the env var in SSRF/CSRF rejection messages, hot-reload CORS_ORIGINS1c451c6fix(cors): auto-allow same-origin requests regardless of CORS_ORIGINS3a0ae06fix(cors): wrap delegator in factory function so @fastify/cors loads it correctly4fdefd7feat(env): auto-create an empty .env on first run so users can find ite40e6aefix(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.envfile itself auto-creates on first run so users can find it.Concretely fixes:
10.0.8.10,192.168.x.x) — the SSRF rejection now readsRefused 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.)error,origin, andhintfields with the exactCSRF_TRUSTED_ORIGINS=…line to paste.CSRF_TRUSTED_ORIGINSwas already hot-reloadable (per-request read).CORS_ORIGINSis 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.cp .env.example .envno longer have to wonder where their config file is. An empty.envwith a header pointing at.env.exampleis created on first boot.Screenshot — new SSRF error surfaced in the Connection Test UI
What changed (per change, with rationale)
1.
OutboundUrlPolicycarries an optionalflagName; SSRF errors include itpackages/server/src/utils/security.tsExtended
OutboundUrlPolicywith an optionalflagName?: stringfield. The three rejection sites invalidateOutboundUrl/validateResolvedAddressesnow build error messages that:'lmstudio.local' (resolved to 10.0.8.10)).Set ${flagName}=true in your .env file …whenflagNameis set.All five outbound-fetch dispatch sites pass the right flag for their provider type:
services/llm/base-provider.ts(LLM provider HTTP calls)PROVIDER_LOCAL_URLS_ENABLEDservices/image/image-generation.ts(image gen)IMAGE_LOCAL_URLS_ENABLEDroutes/translate.routes.ts(DeepLX)DEEPLX_LOCAL_URLS_ENABLEDroutes/tts.routes.ts(TTS, three sites)TTS_LOCAL_URLS_ENABLEDservices/tools/tool-executor.ts(custom-tool webhooks)WEBHOOK_LOCAL_URLS_ENABLEDroutes/connections.routes.ts(localUrlPolicyForProvider, used for connection tests / model lists)IMAGE_LOCAL_URLS_ENABLEDfor image providers, otherwisePROVIDER_LOCAL_URLS_ENABLEDNo 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.tsThe four 403 sites (
Cross-site unsafe,Origin not trusted,Referer not trusted,Missing X-Marinara-CSRF) now return JSON like:The server also logs a one-shot
[csrf]warning per unique rejected origin (throttled via a per-processSetso 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_ORIGINSis now hot-reloadablepackages/server/src/config/cors-config.ts(new),packages/server/src/app.ts,packages/server/src/config/env-watcher.ts@fastify/corswas registered once at boot with a staticgetCorsConfig()value, soCORS_ORIGINSwas on the env-watcher'sRESTART_REQUIRED_KEYSlist. Switched to@fastify/cors's per-request delegator (theregister(cors, () => delegateFn)pattern) so the trusted set is re-evaluated on every request.CORS_ORIGINSis no longer inRESTART_REQUIRED_KEYS.Documented caveat: the
credentialsfield 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 theAccess-Control-Allow-Credentialsheader to flip. Adding/removing entries within either mode is hot-reloadable.4. CORS auto-allows same-origin requests regardless of
CORS_ORIGINSSame files as (3). Surfaced by my own diagnostic in (3) — the previous code (and original
@fastify/corsregistration before this branch) only checked the configured origin list, so a request fromhttp://localhost:7860to 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:Originheader → not a CORS request, allow.Originmatches the request's ownHost(true same-origin) → allow regardless ofCORS_ORIGINS. The browser controls bothOriginandHostfor in-browser requests; they match iff the page is genuinely talking to itself, which is by definition not subject to CORS.OriginmatchesCORS_ORIGINS(or*) → allow with the configured credentials policy.[cors] Rejected cross-origin request from '<origin>' …log line with the exactCORS_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/corsregistration shape — the delegator API expectsregister(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
.envon first runpackages/server/src/config/runtime-config.tsUsers frequently asked "where's my
.env?" because Marinara doesn't ship with one — they're expected tocp .env.example .env, but many never do.loadRuntimeEnv()now callsensureEnvFileExists()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:
Edge cases handled:
try/catchswallows the error, logs a warn, server continues. dotenv treats missing.envand empty.envidentically, so this is purely best-effort.wx(write-exclusive) flag, ignoresEEXIST. The losing process moves on without retry..env→existsSynccheck first; never overwritten, even if currently empty.startEnvWatcher()attaches later inindex.ts. No spurious "env changed" event from the auto-creation. On subsequent restarts the file exists, so creation is skipped entirely.Files changed
Why this PR has zero security cost
safeFetchblock list is byte-identical. The flags users learn to set (PROVIDER_LOCAL_URLS_ENABLEDetc.) and the IPs they unblock are the same as before.Hostto differ fromOriginfor an in-browser request, so this is the canonical definition of same-origin and not subject to CORS by spec..env: a placeholder file with a comment header. dotenv treats missing and empty.envidentically. Read-only filesystems fall back to "no .env" mode just like today.Related issues
"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 (.localsuffixes are still in the SSRF reserved list), but the rejection error now readsRefused 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 toCloses #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.localaccess.Request Origin Not Trustedafter enablingALLOW_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 namesPROVIDER_LOCAL_URLS_ENABLED, the CSRF rejection namesCSRF_TRUSTED_ORIGINSwith the exact value to add. Linked here so this PR shows up in their search trail if the same pattern resurfaces.Notes
.envfile, 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.mainafter PR #463 (env hot-reload) and #464 (Tailscale/Docker auth bypass) merged. Builds cleanly on the currentmain.CodeRabbit review responses
CodeRabbit raised four comments on the original commits. Status:
cors-config.ts— append-style hint instead of replace-style ✅ Applied. The[cors] Rejected …log line now saysadd '<origin>' to CORS_ORIGINS in your .env — comma-separated if you already have entries, e.g. CORS_ORIGINS=http://existing.example,<origin>.csrf-protection.ts— same fix forCSRF_TRUSTED_ORIGINS✅ Applied. NewappendOriginHint()helper used in both the server log and the 403hintfield.security.ts—flagHintonly on policy-driven rejections ✅ Applied. Removed from protocol-mismatch and DNS-failure errors (settingPROVIDER_LOCAL_URLS_ENABLED=truedoesn't unblockgopher://orNXDOMAIN); kept on the twopolicy.allowLocal-gated rejections (local hostname / blocked resolved IP) where it's actually actionable.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 justnslookupit themselves or test specific IPs directly). Keeping the IP in the error message.Test plan (manually verified)
.env: starting with no.envin the test dir, server boots,.envis created with the documented header..env(e.g. addingBASIC_AUTH_USER=alice), restarting → user's edit is preserved, no overwrite.http://<tailscale-ip>:7830from a phone, doing POST flows (persona create, connection edit, etc.) — works withoutCORS_ORIGINSconfig and without[cors] Rejected …warnings in the server log.http://localhost:7830POST flows work without warnings.PROVIDER_LOCAL_URLS_ENABLED: connection test against an LLM connection pointing at a private IP returns the new self-explaining error (see screenshot above).PROVIDER_LOCAL_URLS_ENABLED=trueto.env, saving (no restart), and re-clicking "Test" → Marinara is no longer the one blocking.IMAGE_LOCAL_URLS_ENABLED: same flow with an image-generation connection.[csrf]server warning.CSRF_TRUSTED_ORIGINS=…line into.env, saving, retrying the POST → succeeds without restart.CORS_ORIGINShot-reloadable: editingCORS_ORIGINSin.envwhile 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_ORIGINS, not same-origin) emits a one-shot[cors] Rejected …log line with the exactCORS_ORIGINS=…line to add.[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
.envfile is auto-created on startup if missing.Improvements
.envconfiguration hints for CORS, CSRF, and network issues.Documentation
🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.