[PR #387] [MERGED] Harden security defaults and privileged flows #4600

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

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/387
Author: @TheLonelyDevil9
Created: 5/4/2026
Status: ✅ Merged
Merged: 5/4/2026
Merged by: @SpicyMarinara

Base: main ← Head: codex/security-hardening-v1.5.7


📝 Commits (4)

  • f35f8a4 Harden security defaults and privileged flows
  • 389b756 Address security review feedback
  • d3c9430 Address CodeRabbit security review
  • e122951 Address CodeRabbit hardening follow-ups

📊 Changes

72 files changed (+2793 additions, -1119 deletions)

View changed files

📝 .env.example (+25 -6)
📝 .github/workflows/build-apk.yml (+5 -5)
📝 .github/workflows/build-container-lite.yml (+12 -12)
📝 .github/workflows/build-container.yml (+12 -12)
📝 .github/workflows/publish-github-release.yml (+4 -4)
📝 .github/workflows/pull-request-checks.yml (+6 -6)
📝 .github/workflows/pull-request-triage.yml (+2 -2)
📝 CHANGELOG.md (+12 -0)
📝 Dockerfile (+4 -1)
📝 Dockerfile.lite (+4 -1)
📝 README.md (+2 -0)
📝 android/README.md (+1 -0)
📝 android/app/src/main/AndroidManifest.xml (+2 -1)
📝 android/app/src/main/java/com/marinara/engine/MainActivity.java (+5 -2)
📝 docker-compose.yml (+2 -1)
📝 docs/CONFIGURATION.md (+39 -10)
📝 docs/FAQ.md (+10 -3)
📝 docs/TROUBLESHOOTING.md (+5 -0)
📝 docs/installation/containers.md (+7 -5)
📝 package.json (+5 -2)

...and 52 more files

📄 Description

Linked issue

No linked issue is attached yet. Per CONTRIBUTING.md § Before You Open a Pull Request, please open or link a security hardening issue before this PR is submitted for final review/merge.

Why this change

This PR implements the security remediation plan saved at D:\AIStuff\Marinara-Engine-security-remediation-plan.md for the v1.5.7 codebase.

The primary security problem is that Marinara exposes powerful local-server capabilities: model/provider calls, custom tools, backups, imports, sidecar runtime management, update application, haptics, profile export, image/audio fetching, and static file handling. Several of those capabilities are acceptable for a trusted loopback desktop app but become dangerous when reachable from a LAN, Docker bridge, Tailscale-like network, misconfigured public bind, malicious browser origin, or attacker-controlled URL/file payload.

The remediation goal is to keep local convenience for loopback users while making non-loopback and privileged behavior fail closed by default. Risky features remain available, but only with explicit configuration, auth, CSRF/origin checks, admin confirmation, path containment, and SSRF controls appropriate to the feature.

Security posture changed by this PR

Default behavior now intentionally favors safety over old convenience:

  • Loopback access remains available for normal local desktop usage.
  • Non-loopback private-network requests now require Basic Auth, IP allowlisting, or an explicit unsafe opt-in.
  • Cross-site unsafe browser requests are rejected before reaching privileged routes.
  • Privileged APIs require a configured ADMIN_SECRET instead of silently failing open when unset.
  • Update apply, sidecar runtime installs, custom script tools, and remote haptic control are disabled or loopback-gated unless explicitly enabled.
  • User-provided outbound URLs are rejected when they target loopback, private, link-local, metadata, multicast, reserved, or malformed destinations unless a feature-specific local-provider opt-in applies.
  • User-provided paths and archives are checked with drive/separator-safe containment before reads/writes/extraction.
  • Secret-bearing export and token storage paths are treated as sensitive by default.

This is expected to be a compatibility-impacting hardening change for users who intentionally expose Marinara on LAN/Tailscale/Docker/public interfaces without auth. The docs now describe the explicit escape hatches and warnings.

Threat model addressed

This PR is intended to reduce risk from:

  • A malicious website trying to POST into a locally running Marinara server from the user's browser.
  • A LAN/Tailscale/Docker/public network peer reaching a Marinara process that was previously convenient but unauthenticated.
  • SSRF payloads that attempt to use provider tests, webhook tools, translation, TTS, image generation/download, or bot-browser proxy-like features to reach local services, cloud metadata endpoints, or private networks.
  • Path traversal payloads in upload/import/archive/static-file flows.
  • Browser-rendered HTML/SVG payloads in imported or model-generated chat/game content.
  • API-triggered update/install/runtime execution paths that could otherwise run code from mutable or unverified sources.
  • Secrets leaking through seeded defaults, profile export, backups, logs, or plaintext third-party tokens.
  • Supply-chain drift in vulnerable dependencies, GitHub Actions references, Docker runtime defaults, Android WebView/backup settings, and Windows installer dependency downloads.

What changed

Security foundations:

  • Added centralized server-side security helpers for outbound URL validation, safe fetch with redirect checks, response-size limits, path containment, image magic-byte checks, and redaction utilities.
  • Added global security middleware for CSRF/origin/Sec-Fetch checks, security headers, route throttling, and privileged admin gating.
  • Added shared security constants and client-side CSRF header injection so normal first-party mutations continue to work.
  • Added focused server tests covering auth fail-closed behavior, CSRF blocking, privileged gate enforcement, rate-limit/security headers, SSRF rejection, local-provider opt-in, path containment, and image magic-byte validation.

Access control and browser request protection:

  • Non-loopback private-network access now fails closed unless Basic Auth, IP_ALLOWLIST, ALLOW_UNAUTHENTICATED_PRIVATE_NETWORK, or ALLOW_UNAUTHENTICATED_REMOTE is intentionally configured.
  • Unsafe API methods require same-origin/trusted-origin posture and a custom CSRF header from the first-party client.
  • Privileged routes now require ADMIN_SECRET and reject unset or wrong secrets with explicit 403 responses.
  • Added documentation for LAN/Tailscale/Docker access changes and the security tradeoffs of opt-in escape hatches.

Privileged feature gates:

  • Gated destructive admin endpoints.
  • Gated backup export/download/import paths.
  • Gated SillyTavern bulk import scan/run and moved arbitrary folder access behind picker/session token or IMPORT_ALLOWED_ROOTS.
  • Gated update apply and required explicit update enablement, loopback/default restrictions, and request confirmation.
  • Gated sidecar install/reinstall/download/delete/restart and disabled runtime install by default.
  • Gated haptics scan/connect/command, added loopback/default remote restrictions, command clamping/rate limits, and explicit enablement requirements.
  • Gated custom tool create/update/delete/script enablement and disabled script execution by default unless explicitly enabled.

SSRF and network hardening:

  • Added reusable URL validation that rejects local/private/link-local/reserved/metadata destinations and disallowed protocols by default.
  • Added redirect-aware safe fetch behavior so an allowed-looking public URL cannot redirect into a private destination.
  • Applied URL guards and response-size caps to provider testing/model routes, custom tool webhooks, DeepLX, TTS, image generation/image downloads, Discord webhooks, bot-browser avatar paths touched by this remediation, and sidecar/local-provider paths where appropriate.
  • Preserved explicit local-provider support behind feature-specific opt-ins rather than a global silent allow.

Filesystem and upload hardening:

  • Added Windows-aware assertInsideDir containment checks to avoid sibling-prefix bypasses and drive/separator confusion.
  • Ignored client-supplied path components for uploads that should be server-named.
  • Validated image magic bytes and blocked SVG/script masquerading as safe uploads where applicable.
  • Applied containment checks across avatar/background import/upload, backup import extraction, static asset reads, directory listing/import, and related path joins.

Secrets and data protection:

  • Removed the seeded hard-coded OpenRouter key and changed default connection seeding to avoid shipping a provider secret.
  • Encrypted Spotify tokens at rest rather than keeping raw token blobs in agent settings.
  • Redacted obvious secrets from profile export by default.
  • Added docs for the new env knobs and migration expectations.

Client/XSS hardening:

  • Hardened chat HTML sanitization so final rendered HTML is sanitized after transforms.
  • Tightened DOMPurify behavior and upgraded dompurify.
  • Added client-side admin-secret plumbing and CSRF-aware API helpers.
  • Updated settings/import UI flows to pass admin secret/folder token data where needed.

Supply-chain and platform hardening:

  • Upgraded production and build dependencies, including Fastify/static, Drizzle, DOMPurify, Vite stack, protobuf-related overrides, brace-expansion, Anthropic SDK override, and onnxruntime override alignment.
  • Hardened Dockerfiles to run as non-root and changed compose defaults to bind 127.0.0.1:${PORT:-7860}:7860.
  • Hardened Android backup/WebView settings.
  • SHA-pinned GitHub Actions references.
  • Hardened Windows installer dependency downloads with SHA-256 and Authenticode verification for Node/Git prerequisites.
  • Removed installer npx --yes style execution and pinned repo install/update behavior to v1.5.7 commit 159f5a2017ae958b737a7b618f5cd1a283603073.
  • Added release-note coverage in CHANGELOG.md so the security defaults are visible in release publication.

Compatibility and migration notes

Expected user-visible changes:

  • LAN/Tailscale/Docker users who previously accessed Marinara without auth need to configure Basic Auth, IP_ALLOWLIST, or an explicit unsafe opt-in.
  • Docker Compose now binds localhost by default. Users intentionally exposing the service must edit the bind address and configure auth.
  • Privileged APIs require ADMIN_SECRET; destructive/admin operations will fail with 403 until configured.
  • API update apply is off by default via UPDATES_APPLY_ENABLED=false behavior.
  • Custom script tools remain stored but execution is disabled unless explicitly enabled.
  • Sidecar runtime install is disabled by default for remote/server contexts.
  • Haptics remote control is disabled by default and command bounds are enforced.
  • Bulk import now requires a picker/session token or an allowed root rather than arbitrary raw server paths.
  • Existing Spotify token records need to pass through the new encrypted storage path on refresh/use.

Docs updated:

  • .env.example
  • README.md
  • docs/CONFIGURATION.md
  • docs/FAQ.md
  • docs/TROUBLESHOOTING.md
  • docs/installation/containers.md
  • android/README.md
  • CHANGELOG.md

CodeRabbit follow-up in d3c9430

The latest review pass addresses the CodeRabbit comments that remained after the first hardening commit:

  • Tightened the root Node engine to >=20.19 || >=22.12 for Vite 7 compatibility.
  • Reworked the client CSRF fetch shim so it preserves Request/init semantics and does not force multipart Content-Type headers for FormData uploads.
  • Added shared api.raw routing for sidecar downloads and kept admin/CSRF handling on that path, including surfaced status/body errors.
  • Moved rate limiting before Basic Auth so failed auth attempts are observed by the throttle.
  • Removed request Host self-whitelisting from CSRF origin checks and added explicit configured-origin coverage.
  • Dropped script-src 'unsafe-inline' from CSP while retaining inline styles for compatibility.
  • Added a hard multipart size limit for background uploads and async writes after validation.
  • Expanded profile export redaction for api_key/api-key, arrays, nested settings, and malformed legacy string settings.
  • Removed raw model-output tails from warn logs; raw snippets are debug-only and shorter.
  • Reused assertInsideDir for import root checks, including Windows cross-drive containment.
  • Rechecked folder-picker tokens against IMPORT_ALLOWED_ROOTS when roots are configured, while preserving picker behavior when no roots are configured.
  • Prevented undecryptable Spotify ciphertext from being treated as legacy plaintext and re-encrypted effective refresh tokens on refresh.
  • Added ComfyUI /history and /view timeout coverage.
  • Fixed custom script tool enabled-state handling using the effective execution type.
  • Kept remote webhook tools HTTPS-only unless WEBHOOK_LOCAL_URLS_ENABLED=true explicitly opts into local HTTP support.
  • Tightened AVIF detection to require avif/avis ftyp brands.
  • Preserved the outbound fetch streaming path while validating/pinning resolved DNS answers before connection, with regression coverage for DNS rebinding and public IPv4 validation.
  • Failed closed when a safeFetch content-type gate is configured and the response omits Content-Type.
  • Switched Windows installer PowerShell path literals from single quotes to double quotes so profile paths containing apostrophes do not break hash/signature verification.
  • Made file-backed-store cleanup failures visible while avoiding Windows libSQL handle flakiness in tests by using the node:sqlite reader for these legacy-import behavior tests.

Validation

These checkboxes are intentionally left unchecked for human contributors, per repo policy. Treat them as the manual verification checklist before final submission.

  • 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 and checks run by Codex during implementation/testing:

  • pnpm --filter @marinara-engine/server lint
  • pnpm --filter @marinara-engine/client lint
  • pnpm --filter @marinara-engine/client build
  • pnpm --filter @marinara-engine/server exec tsx --test test/security-utils.test.ts test/security-middleware.test.ts
  • pnpm --filter @marinara-engine/server exec tsx --test test/security-utils.test.ts test/security-middleware.test.ts test/file-backed-store.test.ts
  • pnpm --filter @marinara-engine/server exec tsx --test test/file-backed-store.test.ts
  • pnpm --filter @marinara-engine/server test
  • pnpm check
  • pnpm test
  • pnpm version:check
  • pnpm guard:installer-artifacts
  • pnpm audit --prod --json
  • pnpm release:notes -- 1.5.7
  • node ./scripts/check-windows-installer-layout.mjs
  • git diff --check
  • C:\\Program Files (x86)\\NSIS\\makensis.exe installer.nsi from win/installer
  • Built-app smoke via node importing ./packages/server/dist/app.js, creating a production-mode app with temp DATA_DIR, and asserting:
    • GET /api/health returns 200 with version 1.5.7
    • GET / returns 200
    • POST /api/admin/clear-all with wrong X-Admin-Secret returns 403

Observed validation results:

  • Full server test suite passed: 125/125 tests.
  • Production audit passed with 0 advisories (pnpm audit --prod --json).
  • Version files are in sync for 1.5.7.
  • Installer artifact guard reported no tracked installer binaries.
  • Windows installer layout check passed.
  • NSIS compile succeeded with NSIS v3.12 from win/installer and the generated installer artifact was removed after validation.
  • Workflow action pin check reported all workflow uses: references are SHA-pinned.
  • Server logging scan found no direct console.* usage in server source except the logger guidance comment.
  • Secret-pattern scan did not find a committed provider key; it only matched the intentional ANTHROPIC_API_KEY env override name in the Claude subscription provider code.

Automated/local checks still worth running in CI or on a reviewer machine:

  • Build and run both Docker images because Docker is not available in the current local environment:
    • docker build -t marinara-engine:security .
    • docker build -f Dockerfile.lite -t marinara-engine-lite:security .
    • Run each image and verify the process runs as non-root and listens only as configured.
  • Build the Android wrapper because Java/Gradle are not available in the current local environment:
    • Run the existing APK workflow or local Android build.
    • Confirm backup exclusion and WebView file/mixed-content settings behave on a device/emulator.
  • Exercise a real browser smoke with a fresh temp DATA_DIR:
    • First-run local loopback app load.
    • Create connection with user-provided key.
    • Create chat, send/generate a message, branch/switch chat.
    • Upload avatar/background with valid PNG/JPEG/WebP.
    • Attempt SVG/script upload and confirm rejection/non-execution.
    • Export profile and confirm provider secrets/tokens are redacted.
  • Exercise the auth matrix manually or with integration tests:
    • Loopback without auth works for normal app use.
    • LAN/Tailscale-like non-loopback without auth is denied/challenged.
    • LAN with Basic Auth succeeds.
    • IP_ALLOWLIST succeeds only for intended addresses.
    • ALLOW_UNAUTHENTICATED_PRIVATE_NETWORK restores old behavior only when explicitly configured.
  • Exercise the CSRF matrix manually or with integration tests:
    • Same-origin client mutation succeeds with automatic CSRF header.
    • Same-origin unsafe API request missing CSRF header fails.
    • Cross-site Origin/Sec-Fetch-Site POST fails.
    • Trusted dev origin configured by CSRF_TRUSTED_ORIGINS succeeds only when intended.
  • Exercise privileged-route flows:
    • Admin destructive route without ADMIN_SECRET fails.
    • Wrong ADMIN_SECRET fails.
    • Correct ADMIN_SECRET plus CSRF succeeds for intended privileged operation.
    • Backup export/import, update apply, sidecar install/delete, custom tool mutation/script enablement, haptic connect/command, and bulk import scan/run all follow the same gate.
  • Exercise SSRF cases against a controlled local test server:
    • Reject 127.0.0.1, localhost, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.169.254, IPv6 loopback/ULA, malformed protocols, and redirect-to-private.
    • Confirm public HTTPS provider URLs still work.
    • Confirm explicit local-provider opt-ins work only for intended provider paths.
  • Exercise filesystem cases on Windows and POSIX:
    • Drive-prefix sibling path attempts.
    • .. traversal in uploaded filenames, zip entries, avatar/background import, and static asset reads.
    • UNC-like path inputs.
    • Valid import/upload flows still work.
  • Exercise feature compatibility where external services are available:
    • OpenAI/OpenRouter/Anthropic provider test and generation.
    • TTS voice listing/speech generation with response-size caps.
    • Image generation and returned image download.
    • Translation/DeepLX config.
    • Discord webhook tool execution against a safe public endpoint.
    • Spotify OAuth refresh/use path to confirm encrypted token round-trip.

Manual verification notes

Codex did not perform real browser, Docker, Android device/emulator, or live external-provider manual verification in this environment.

Manual review should focus on:

  • Whether the new security defaults are acceptable for the release and clearly documented.
  • Whether the compatibility escape hatches are intentionally named and scary enough for unsafe exposure modes.
  • Whether every privileged route that can delete, execute, download, import, install, update, or control hardware is covered by the new gate.
  • Whether any remaining raw fetch call is intentionally fixed-host/public-only or should be migrated to safeFetch in a follow-up.
  • Whether release notes and troubleshooting entries are clear enough for LAN/Docker/Tailscale users.

Known residual risk and follow-ups

  • This PR keeps some fixed-host bot-browser/font/public API fetches as raw fetch calls because they target hard-coded public services rather than arbitrary user-provided URLs. Reviewers should confirm each remaining raw fetch is intentionally fixed-host or add another follow-up to migrate more of them to safeFetch.
  • The MLX/uv runtime installer path still references the upstream https://astral.sh/uv/install.sh flow, but runtime install is disabled/gated by default. A future PR should pin and verify that installer or replace it with a checksumed packaged dependency.
  • Git tag v1.5.7 is not GPG-signed. Windows installer/update hardening pins the expected commit rather than claiming signed-tag verification.
  • The new throttling is intentionally lightweight and in-memory. It reduces accidental/low-effort abuse but is not a distributed rate-limit system.
  • Secret redaction is best-effort for obvious token/key fields. Future encrypted backup support would be a stronger long-term answer.
  • CSP is conservative and header-focused here; full CSP enforcement for all extension/theme/custom HTML cases may need a separate compatibility pass.

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)

Docs and release notes were updated by this PR because auth defaults, privileged APIs, Docker binding, Android behavior, installer verification, and dependency posture changed. The version remains 1.5.7; no version bump is included in this PR.

UI evidence (if applicable)

No screenshots are attached. UI changes are limited to security/admin-secret and bulk-import controls rather than a visual redesign. A reviewer should still manually verify the settings and bulk import flows in-browser before merge.

Summary by CodeRabbit

  • New Features

    • Security-first defaults: local-first network access (non-loopback blocked unless opted in), ADMIN_SECRET for privileged actions, CSRF protections, and per-endpoint rate limiting.
    • Admin-gated bulk import with short-lived folder tokens.
    • Encrypted storage for provider credentials; improved admin access UI in settings.
  • Documentation

    • Updated README, configuration, FAQ, and troubleshooting for lockdown defaults and access controls.
  • Other

    • Docker and installers tightened (bind to localhost, run as non-root, verified downloads); Android backup disabled and WebView restricted.
  • Chores

    • Pinned CI actions and dependency updates.

🔄 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/387 **Author:** [@TheLonelyDevil9](https://github.com/TheLonelyDevil9) **Created:** 5/4/2026 **Status:** ✅ Merged **Merged:** 5/4/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `main` ← **Head:** `codex/security-hardening-v1.5.7` --- ### 📝 Commits (4) - [`f35f8a4`](https://github.com/Pasta-Devs/Marinara-Engine/commit/f35f8a475e7fd68579a27238ac23fe98ba5a25f4) Harden security defaults and privileged flows - [`389b756`](https://github.com/Pasta-Devs/Marinara-Engine/commit/389b75602a6a2d5471dbdbc24f962142170c2927) Address security review feedback - [`d3c9430`](https://github.com/Pasta-Devs/Marinara-Engine/commit/d3c9430bbe23b44f1749e32e76fd4e59f420b0f6) Address CodeRabbit security review - [`e122951`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e122951b95a95c66e22de6b57e555ce6bb70c906) Address CodeRabbit hardening follow-ups ### 📊 Changes **72 files changed** (+2793 additions, -1119 deletions) <details> <summary>View changed files</summary> 📝 `.env.example` (+25 -6) 📝 `.github/workflows/build-apk.yml` (+5 -5) 📝 `.github/workflows/build-container-lite.yml` (+12 -12) 📝 `.github/workflows/build-container.yml` (+12 -12) 📝 `.github/workflows/publish-github-release.yml` (+4 -4) 📝 `.github/workflows/pull-request-checks.yml` (+6 -6) 📝 `.github/workflows/pull-request-triage.yml` (+2 -2) 📝 `CHANGELOG.md` (+12 -0) 📝 `Dockerfile` (+4 -1) 📝 `Dockerfile.lite` (+4 -1) 📝 `README.md` (+2 -0) 📝 `android/README.md` (+1 -0) 📝 `android/app/src/main/AndroidManifest.xml` (+2 -1) 📝 `android/app/src/main/java/com/marinara/engine/MainActivity.java` (+5 -2) 📝 `docker-compose.yml` (+2 -1) 📝 `docs/CONFIGURATION.md` (+39 -10) 📝 `docs/FAQ.md` (+10 -3) 📝 `docs/TROUBLESHOOTING.md` (+5 -0) 📝 `docs/installation/containers.md` (+7 -5) 📝 `package.json` (+5 -2) _...and 52 more files_ </details> ### 📄 Description ## Linked issue No linked issue is attached yet. Per `CONTRIBUTING.md § Before You Open a Pull Request`, please open or link a security hardening issue before this PR is submitted for final review/merge. ## Why this change This PR implements the security remediation plan saved at `D:\AIStuff\Marinara-Engine-security-remediation-plan.md` for the `v1.5.7` codebase. The primary security problem is that Marinara exposes powerful local-server capabilities: model/provider calls, custom tools, backups, imports, sidecar runtime management, update application, haptics, profile export, image/audio fetching, and static file handling. Several of those capabilities are acceptable for a trusted loopback desktop app but become dangerous when reachable from a LAN, Docker bridge, Tailscale-like network, misconfigured public bind, malicious browser origin, or attacker-controlled URL/file payload. The remediation goal is to keep local convenience for loopback users while making non-loopback and privileged behavior fail closed by default. Risky features remain available, but only with explicit configuration, auth, CSRF/origin checks, admin confirmation, path containment, and SSRF controls appropriate to the feature. ## Security posture changed by this PR Default behavior now intentionally favors safety over old convenience: - Loopback access remains available for normal local desktop usage. - Non-loopback private-network requests now require Basic Auth, IP allowlisting, or an explicit unsafe opt-in. - Cross-site unsafe browser requests are rejected before reaching privileged routes. - Privileged APIs require a configured `ADMIN_SECRET` instead of silently failing open when unset. - Update apply, sidecar runtime installs, custom script tools, and remote haptic control are disabled or loopback-gated unless explicitly enabled. - User-provided outbound URLs are rejected when they target loopback, private, link-local, metadata, multicast, reserved, or malformed destinations unless a feature-specific local-provider opt-in applies. - User-provided paths and archives are checked with drive/separator-safe containment before reads/writes/extraction. - Secret-bearing export and token storage paths are treated as sensitive by default. This is expected to be a compatibility-impacting hardening change for users who intentionally expose Marinara on LAN/Tailscale/Docker/public interfaces without auth. The docs now describe the explicit escape hatches and warnings. ## Threat model addressed This PR is intended to reduce risk from: - A malicious website trying to POST into a locally running Marinara server from the user's browser. - A LAN/Tailscale/Docker/public network peer reaching a Marinara process that was previously convenient but unauthenticated. - SSRF payloads that attempt to use provider tests, webhook tools, translation, TTS, image generation/download, or bot-browser proxy-like features to reach local services, cloud metadata endpoints, or private networks. - Path traversal payloads in upload/import/archive/static-file flows. - Browser-rendered HTML/SVG payloads in imported or model-generated chat/game content. - API-triggered update/install/runtime execution paths that could otherwise run code from mutable or unverified sources. - Secrets leaking through seeded defaults, profile export, backups, logs, or plaintext third-party tokens. - Supply-chain drift in vulnerable dependencies, GitHub Actions references, Docker runtime defaults, Android WebView/backup settings, and Windows installer dependency downloads. ## What changed Security foundations: - Added centralized server-side security helpers for outbound URL validation, safe fetch with redirect checks, response-size limits, path containment, image magic-byte checks, and redaction utilities. - Added global security middleware for CSRF/origin/Sec-Fetch checks, security headers, route throttling, and privileged admin gating. - Added shared security constants and client-side CSRF header injection so normal first-party mutations continue to work. - Added focused server tests covering auth fail-closed behavior, CSRF blocking, privileged gate enforcement, rate-limit/security headers, SSRF rejection, local-provider opt-in, path containment, and image magic-byte validation. Access control and browser request protection: - Non-loopback private-network access now fails closed unless Basic Auth, `IP_ALLOWLIST`, `ALLOW_UNAUTHENTICATED_PRIVATE_NETWORK`, or `ALLOW_UNAUTHENTICATED_REMOTE` is intentionally configured. - Unsafe API methods require same-origin/trusted-origin posture and a custom CSRF header from the first-party client. - Privileged routes now require `ADMIN_SECRET` and reject unset or wrong secrets with explicit `403` responses. - Added documentation for LAN/Tailscale/Docker access changes and the security tradeoffs of opt-in escape hatches. Privileged feature gates: - Gated destructive admin endpoints. - Gated backup export/download/import paths. - Gated SillyTavern bulk import scan/run and moved arbitrary folder access behind picker/session token or `IMPORT_ALLOWED_ROOTS`. - Gated update apply and required explicit update enablement, loopback/default restrictions, and request confirmation. - Gated sidecar install/reinstall/download/delete/restart and disabled runtime install by default. - Gated haptics scan/connect/command, added loopback/default remote restrictions, command clamping/rate limits, and explicit enablement requirements. - Gated custom tool create/update/delete/script enablement and disabled script execution by default unless explicitly enabled. SSRF and network hardening: - Added reusable URL validation that rejects local/private/link-local/reserved/metadata destinations and disallowed protocols by default. - Added redirect-aware safe fetch behavior so an allowed-looking public URL cannot redirect into a private destination. - Applied URL guards and response-size caps to provider testing/model routes, custom tool webhooks, DeepLX, TTS, image generation/image downloads, Discord webhooks, bot-browser avatar paths touched by this remediation, and sidecar/local-provider paths where appropriate. - Preserved explicit local-provider support behind feature-specific opt-ins rather than a global silent allow. Filesystem and upload hardening: - Added Windows-aware `assertInsideDir` containment checks to avoid sibling-prefix bypasses and drive/separator confusion. - Ignored client-supplied path components for uploads that should be server-named. - Validated image magic bytes and blocked SVG/script masquerading as safe uploads where applicable. - Applied containment checks across avatar/background import/upload, backup import extraction, static asset reads, directory listing/import, and related path joins. Secrets and data protection: - Removed the seeded hard-coded OpenRouter key and changed default connection seeding to avoid shipping a provider secret. - Encrypted Spotify tokens at rest rather than keeping raw token blobs in agent settings. - Redacted obvious secrets from profile export by default. - Added docs for the new env knobs and migration expectations. Client/XSS hardening: - Hardened chat HTML sanitization so final rendered HTML is sanitized after transforms. - Tightened DOMPurify behavior and upgraded `dompurify`. - Added client-side admin-secret plumbing and CSRF-aware API helpers. - Updated settings/import UI flows to pass admin secret/folder token data where needed. Supply-chain and platform hardening: - Upgraded production and build dependencies, including Fastify/static, Drizzle, DOMPurify, Vite stack, protobuf-related overrides, brace-expansion, Anthropic SDK override, and onnxruntime override alignment. - Hardened Dockerfiles to run as non-root and changed compose defaults to bind `127.0.0.1:${PORT:-7860}:7860`. - Hardened Android backup/WebView settings. - SHA-pinned GitHub Actions references. - Hardened Windows installer dependency downloads with SHA-256 and Authenticode verification for Node/Git prerequisites. - Removed installer `npx --yes` style execution and pinned repo install/update behavior to `v1.5.7` commit `159f5a2017ae958b737a7b618f5cd1a283603073`. - Added release-note coverage in `CHANGELOG.md` so the security defaults are visible in release publication. ## Compatibility and migration notes Expected user-visible changes: - LAN/Tailscale/Docker users who previously accessed Marinara without auth need to configure Basic Auth, `IP_ALLOWLIST`, or an explicit unsafe opt-in. - Docker Compose now binds localhost by default. Users intentionally exposing the service must edit the bind address and configure auth. - Privileged APIs require `ADMIN_SECRET`; destructive/admin operations will fail with `403` until configured. - API update apply is off by default via `UPDATES_APPLY_ENABLED=false` behavior. - Custom script tools remain stored but execution is disabled unless explicitly enabled. - Sidecar runtime install is disabled by default for remote/server contexts. - Haptics remote control is disabled by default and command bounds are enforced. - Bulk import now requires a picker/session token or an allowed root rather than arbitrary raw server paths. - Existing Spotify token records need to pass through the new encrypted storage path on refresh/use. Docs updated: - `.env.example` - `README.md` - `docs/CONFIGURATION.md` - `docs/FAQ.md` - `docs/TROUBLESHOOTING.md` - `docs/installation/containers.md` - `android/README.md` - `CHANGELOG.md` ## CodeRabbit follow-up in `d3c9430` The latest review pass addresses the CodeRabbit comments that remained after the first hardening commit: - Tightened the root Node engine to `>=20.19 || >=22.12` for Vite 7 compatibility. - Reworked the client CSRF fetch shim so it preserves `Request`/`init` semantics and does not force multipart `Content-Type` headers for `FormData` uploads. - Added shared `api.raw` routing for sidecar downloads and kept admin/CSRF handling on that path, including surfaced status/body errors. - Moved rate limiting before Basic Auth so failed auth attempts are observed by the throttle. - Removed request `Host` self-whitelisting from CSRF origin checks and added explicit configured-origin coverage. - Dropped `script-src 'unsafe-inline'` from CSP while retaining inline styles for compatibility. - Added a hard multipart size limit for background uploads and async writes after validation. - Expanded profile export redaction for `api_key`/`api-key`, arrays, nested settings, and malformed legacy string settings. - Removed raw model-output tails from warn logs; raw snippets are debug-only and shorter. - Reused `assertInsideDir` for import root checks, including Windows cross-drive containment. - Rechecked folder-picker tokens against `IMPORT_ALLOWED_ROOTS` when roots are configured, while preserving picker behavior when no roots are configured. - Prevented undecryptable Spotify ciphertext from being treated as legacy plaintext and re-encrypted effective refresh tokens on refresh. - Added ComfyUI `/history` and `/view` timeout coverage. - Fixed custom script tool enabled-state handling using the effective execution type. - Kept remote webhook tools HTTPS-only unless `WEBHOOK_LOCAL_URLS_ENABLED=true` explicitly opts into local HTTP support. - Tightened AVIF detection to require `avif`/`avis` ftyp brands. - Preserved the outbound fetch streaming path while validating/pinning resolved DNS answers before connection, with regression coverage for DNS rebinding and public IPv4 validation. - Failed closed when a `safeFetch` content-type gate is configured and the response omits `Content-Type`. - Switched Windows installer PowerShell path literals from single quotes to double quotes so profile paths containing apostrophes do not break hash/signature verification. - Made file-backed-store cleanup failures visible while avoiding Windows libSQL handle flakiness in tests by using the node:sqlite reader for these legacy-import behavior tests. ## Validation These checkboxes are intentionally left unchecked for human contributors, per repo policy. Treat them as the manual verification checklist before final submission. - [ ] `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 and checks run by Codex during implementation/testing: - `pnpm --filter @marinara-engine/server lint` - `pnpm --filter @marinara-engine/client lint` - `pnpm --filter @marinara-engine/client build` - `pnpm --filter @marinara-engine/server exec tsx --test test/security-utils.test.ts test/security-middleware.test.ts` - `pnpm --filter @marinara-engine/server exec tsx --test test/security-utils.test.ts test/security-middleware.test.ts test/file-backed-store.test.ts` - `pnpm --filter @marinara-engine/server exec tsx --test test/file-backed-store.test.ts` - `pnpm --filter @marinara-engine/server test` - `pnpm check` - `pnpm test` - `pnpm version:check` - `pnpm guard:installer-artifacts` - `pnpm audit --prod --json` - `pnpm release:notes -- 1.5.7` - `node ./scripts/check-windows-installer-layout.mjs` - `git diff --check` - `C:\\Program Files (x86)\\NSIS\\makensis.exe installer.nsi` from `win/installer` - Built-app smoke via `node` importing `./packages/server/dist/app.js`, creating a production-mode app with temp `DATA_DIR`, and asserting: - `GET /api/health` returns `200` with version `1.5.7` - `GET /` returns `200` - `POST /api/admin/clear-all` with wrong `X-Admin-Secret` returns `403` Observed validation results: - Full server test suite passed: `125/125` tests. - Production audit passed with `0` advisories (`pnpm audit --prod --json`). - Version files are in sync for `1.5.7`. - Installer artifact guard reported no tracked installer binaries. - Windows installer layout check passed. - NSIS compile succeeded with NSIS `v3.12` from `win/installer` and the generated installer artifact was removed after validation. - Workflow action pin check reported all workflow `uses:` references are SHA-pinned. - Server logging scan found no direct `console.*` usage in server source except the logger guidance comment. - Secret-pattern scan did not find a committed provider key; it only matched the intentional `ANTHROPIC_API_KEY` env override name in the Claude subscription provider code. ## Additional stability testing recommended before merge/release Automated/local checks still worth running in CI or on a reviewer machine: - Build and run both Docker images because Docker is not available in the current local environment: - `docker build -t marinara-engine:security .` - `docker build -f Dockerfile.lite -t marinara-engine-lite:security .` - Run each image and verify the process runs as non-root and listens only as configured. - Build the Android wrapper because Java/Gradle are not available in the current local environment: - Run the existing APK workflow or local Android build. - Confirm backup exclusion and WebView file/mixed-content settings behave on a device/emulator. - Exercise a real browser smoke with a fresh temp `DATA_DIR`: - First-run local loopback app load. - Create connection with user-provided key. - Create chat, send/generate a message, branch/switch chat. - Upload avatar/background with valid PNG/JPEG/WebP. - Attempt SVG/script upload and confirm rejection/non-execution. - Export profile and confirm provider secrets/tokens are redacted. - Exercise the auth matrix manually or with integration tests: - Loopback without auth works for normal app use. - LAN/Tailscale-like non-loopback without auth is denied/challenged. - LAN with Basic Auth succeeds. - `IP_ALLOWLIST` succeeds only for intended addresses. - `ALLOW_UNAUTHENTICATED_PRIVATE_NETWORK` restores old behavior only when explicitly configured. - Exercise the CSRF matrix manually or with integration tests: - Same-origin client mutation succeeds with automatic CSRF header. - Same-origin unsafe API request missing CSRF header fails. - Cross-site `Origin`/`Sec-Fetch-Site` POST fails. - Trusted dev origin configured by `CSRF_TRUSTED_ORIGINS` succeeds only when intended. - Exercise privileged-route flows: - Admin destructive route without `ADMIN_SECRET` fails. - Wrong `ADMIN_SECRET` fails. - Correct `ADMIN_SECRET` plus CSRF succeeds for intended privileged operation. - Backup export/import, update apply, sidecar install/delete, custom tool mutation/script enablement, haptic connect/command, and bulk import scan/run all follow the same gate. - Exercise SSRF cases against a controlled local test server: - Reject `127.0.0.1`, `localhost`, `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `169.254.169.254`, IPv6 loopback/ULA, malformed protocols, and redirect-to-private. - Confirm public HTTPS provider URLs still work. - Confirm explicit local-provider opt-ins work only for intended provider paths. - Exercise filesystem cases on Windows and POSIX: - Drive-prefix sibling path attempts. - `..` traversal in uploaded filenames, zip entries, avatar/background import, and static asset reads. - UNC-like path inputs. - Valid import/upload flows still work. - Exercise feature compatibility where external services are available: - OpenAI/OpenRouter/Anthropic provider test and generation. - TTS voice listing/speech generation with response-size caps. - Image generation and returned image download. - Translation/DeepLX config. - Discord webhook tool execution against a safe public endpoint. - Spotify OAuth refresh/use path to confirm encrypted token round-trip. ## Manual verification notes Codex did not perform real browser, Docker, Android device/emulator, or live external-provider manual verification in this environment. Manual review should focus on: - Whether the new security defaults are acceptable for the release and clearly documented. - Whether the compatibility escape hatches are intentionally named and scary enough for unsafe exposure modes. - Whether every privileged route that can delete, execute, download, import, install, update, or control hardware is covered by the new gate. - Whether any remaining raw `fetch` call is intentionally fixed-host/public-only or should be migrated to `safeFetch` in a follow-up. - Whether release notes and troubleshooting entries are clear enough for LAN/Docker/Tailscale users. ## Known residual risk and follow-ups - This PR keeps some fixed-host bot-browser/font/public API fetches as raw `fetch` calls because they target hard-coded public services rather than arbitrary user-provided URLs. Reviewers should confirm each remaining raw fetch is intentionally fixed-host or add another follow-up to migrate more of them to `safeFetch`. - The MLX/uv runtime installer path still references the upstream `https://astral.sh/uv/install.sh` flow, but runtime install is disabled/gated by default. A future PR should pin and verify that installer or replace it with a checksumed packaged dependency. - Git tag `v1.5.7` is not GPG-signed. Windows installer/update hardening pins the expected commit rather than claiming signed-tag verification. - The new throttling is intentionally lightweight and in-memory. It reduces accidental/low-effort abuse but is not a distributed rate-limit system. - Secret redaction is best-effort for obvious token/key fields. Future encrypted backup support would be a stronger long-term answer. - CSP is conservative and header-focused here; full CSP enforcement for all extension/theme/custom HTML cases may need a separate compatibility pass. ## 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) Docs and release notes were updated by this PR because auth defaults, privileged APIs, Docker binding, Android behavior, installer verification, and dependency posture changed. The version remains `1.5.7`; no version bump is included in this PR. ## UI evidence (if applicable) No screenshots are attached. UI changes are limited to security/admin-secret and bulk-import controls rather than a visual redesign. A reviewer should still manually verify the settings and bulk import flows in-browser before merge. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Security-first defaults: local-first network access (non-loopback blocked unless opted in), ADMIN_SECRET for privileged actions, CSRF protections, and per-endpoint rate limiting. * Admin-gated bulk import with short-lived folder tokens. * Encrypted storage for provider credentials; improved admin access UI in settings. * **Documentation** * Updated README, configuration, FAQ, and troubleshooting for lockdown defaults and access controls. * **Other** * Docker and installers tightened (bind to localhost, run as non-root, verified downloads); Android backup disabled and WebView restricted. * **Chores** * Pinned CI actions and dependency updates. <!-- 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:03 +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#4600
No description provided.