Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(forge-desktop): require an API auth token between the Electron shell and the local Python API and add access-control tests

nirholas9a338e94b093
diff --git a/apps/forge-desktop/api/access_control.py b/apps/forge-desktop/api/access_control.py
new file mode 100644
index 000000000..938df9748
--- /dev/null
+++ b/apps/forge-desktop/api/access_control.py
@@ -0,0 +1,104 @@
+"""
+Access control for the loopback sidecar.
+
+The API listens on 127.0.0.1, which any web page the user visits can reach with
+fetch(). Three layers keep those pages out:
+
+1. A per-launch secret (FORGE_API_TOKEN, generated by Electron main) must be
+ presented in the X-Forge-Token header on every request.
+2. The Host header must name the loopback interface, which defeats DNS rebinding.
+3. CORS only admits the app's own renderer origins (FORGE_ALLOWED_ORIGINS, a
+ comma separated list), never a wildcard.
+
+The workspace file route additionally refuses anything that resolves outside
+the workspace directory.
+"""
+import hmac
+import os
+from pathlib import Path
+
+from fastapi import FastAPI, HTTPException
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.responses import FileResponse, JSONResponse
+
+TOKEN_HEADER = "x-forge-token"
+LOOPBACK_HOSTS = {"127.0.0.1", "localhost", "[::1]"}
+
+
+def _host_name(host_header: str) -> str:
+ host = host_header.strip().lower()
+ if host.startswith("["):
+ return host.split("]", 1)[0] + "]"
+ return host.rsplit(":", 1)[0] if ":" in host else host
+
+
+def _allowed_origins() -> list[str]:
+ raw = os.environ.get("FORGE_ALLOWED_ORIGINS", "")
+ return [o.strip() for o in raw.split(",") if o.strip()]
+
+
+class _AccessControlMiddleware:
+ """Pure ASGI so streaming responses are untouched."""
+
+ def __init__(self, app):
+ self.app = app
+
+ async def __call__(self, scope, receive, send):
+ if scope["type"] not in ("http", "websocket"):
+ await self.app(scope, receive, send)
+ return
+ headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope["headers"]}
+ if _host_name(headers.get("host", "")) not in LOOPBACK_HOSTS:
+ await self._reject(scope, receive, send, 403, "Forbidden host")
+ return
+ expected = os.environ.get("FORGE_API_TOKEN", "")
+ supplied = headers.get(TOKEN_HEADER, "")
+ if not expected or not hmac.compare_digest(expected.encode(), supplied.encode()):
+ await self._reject(scope, receive, send, 401, "Missing or invalid API token")
+ return
+ await self.app(scope, receive, send)
+
+ @staticmethod
+ async def _reject(scope, receive, send, status: int, detail: str):
+ if scope["type"] == "websocket":
+ await send({"type": "websocket.close", "code": 1008})
+ return
+ await JSONResponse({"detail": detail}, status_code=status)(scope, receive, send)
+
+
+def install_access_control(app: FastAPI) -> None:
+ # Added first so CORS (added second, therefore outermost) answers preflights
+ # itself and decorates rejections with the right headers.
+ app.add_middleware(_AccessControlMiddleware)
+ app.add_middleware(
+ CORSMiddleware,
+ allow_origins=_allowed_origins(),
+ allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
+ allow_headers=["content-type", TOKEN_HEADER],
+ # drei's SplatLoader reads Content-Length to size its buffers; cross-origin
+ # JS can only see it when the server explicitly exposes the header.
+ expose_headers=["Content-Length"],
+ )
+
+
+def resolve_inside(root: Path, relative: str) -> Path | None:
+ """Resolve root/relative, or None when the result escapes root (.., absolute, symlinks)."""
+ try:
+ base = root.resolve()
+ target = (base / relative).resolve()
+ except (OSError, ValueError, RuntimeError):
+ return None
+ if not target.is_relative_to(base):
+ return None
+ return target
+
+
+def register_workspace_route(app: FastAPI) -> None:
+ # Dynamic so path changes take effect immediately.
+ @app.get("/workspace/{full_path:path}")
+ async def serve_workspace_file(full_path: str):
+ import services.generator_registry as reg
+ file_path = resolve_inside(reg.WORKSPACE_DIR, full_path)
+ if file_path is None or not file_path.is_file():
+ raise HTTPException(status_code=404, detail="File not found")
+ return FileResponse(str(file_path))
diff --git a/apps/forge-desktop/api/main.py b/apps/forge-desktop/api/main.py
index a4f51e1f2..adb7ed7c8 100644
--- a/apps/forge-desktop/api/main.py
+++ b/apps/forge-desktop/api/main.py
@@ -5,13 +5,11 @@ Runs locally within the Electron app to provide AI inference endpoints.
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
-from fastapi.middleware.cors import CORSMiddleware
-from fastapi.responses import FileResponse
-from fastapi import HTTPException
from services.stdio_utf8 import ensure_utf8_stdio
ensure_utf8_stdio() # must run before any print/logging hits the pipe
+from access_control import install_access_control, register_workspace_route
from routers import generation, model, optimize, status, settings, extensions, export, workflow_runs, agent, llm
@@ -40,15 +38,7 @@ app = FastAPI(
lifespan=lifespan,
)
-app.add_middleware(
- CORSMiddleware,
- allow_origins=["*"],
- allow_methods=["*"],
- allow_headers=["*"],
- # drei's SplatLoader reads Content-Length to size its buffers; cross-origin
- # JS can only see it when the server explicitly exposes the header.
- expose_headers=["Content-Length"],
-)
+install_access_control(app)
app.include_router(status.router)
app.include_router(settings.router)
@@ -61,11 +51,5 @@ app.include_router(workflow_runs.router, prefix="/workflow-runs")
app.include_router(agent.router)
app.include_router(llm.router, prefix="/llm")
-# Serve generated files from workspace: dynamic so path changes take effect immediately
[email protected]("/workspace/{full_path:path}")
-async def serve_workspace_file(full_path: str):
- import services.generator_registry as reg
- file_path = reg.WORKSPACE_DIR / full_path
- if not file_path.exists() or not file_path.is_file():
- raise HTTPException(status_code=404, detail="File not found")
- return FileResponse(str(file_path))
+# Serve generated files from workspace (contained to the workspace directory)
+register_workspace_route(app)
diff --git a/apps/forge-desktop/api/routers/settings.py b/apps/forge-desktop/api/routers/settings.py
index 059c5cb81..b8d9e2481 100644
--- a/apps/forge-desktop/api/routers/settings.py
+++ b/apps/forge-desktop/api/routers/settings.py
@@ -1,6 +1,8 @@
import asyncio
import os
-from fastapi import APIRouter
+from urllib.parse import urlparse
+
+from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from pathlib import Path
from typing import Optional
@@ -19,6 +21,26 @@ class TokenUpdate(BaseModel):
token: str
+def _checked_dir(value: Optional[str], field: str) -> Optional[Path]:
+ """An absolute directory that is not a filesystem root; the workspace is served over HTTP."""
+ if not value:
+ return None
+ path = Path(value)
+ if not path.is_absolute() or path.parent == path:
+ raise HTTPException(status_code=400, detail=f"{field} must be an absolute folder path below the filesystem root")
+ return path
+
+
+def _checked_base_url(value: str) -> str:
+ """The account origin receives the API key, so it must be https (http only for loopback dev)."""
+ parsed = urlparse(value)
+ loopback = parsed.hostname in ("localhost", "127.0.0.1", "::1")
+ if parsed.scheme == "https" or (parsed.scheme == "http" and loopback):
+ if parsed.hostname and not parsed.username and not parsed.password:
+ return value
+ raise HTTPException(status_code=400, detail="base_url must be an https origin (http is allowed only for localhost)")
+
+
@router.get("/paths")
async def get_paths():
return {
@@ -29,12 +51,10 @@ async def get_paths():
@router.post("/paths")
async def update_paths(body: PathsUpdate):
+ models_dir = _checked_dir(body.models_dir, "models_dir")
+ workspace_dir = _checked_dir(body.workspace_dir, "workspace_dir")
# Off the event loop: changing paths waits for any in-progress model load.
- await asyncio.to_thread(
- reg_module.generator_registry.update_paths,
- Path(body.models_dir) if body.models_dir else None,
- Path(body.workspace_dir) if body.workspace_dir else None,
- )
+ await asyncio.to_thread(reg_module.generator_registry.update_paths, models_dir, workspace_dir)
return {
"models_dir": str(reg_module.MODELS_DIR),
"workspace_dir": str(reg_module.WORKSPACE_DIR),
@@ -68,10 +88,11 @@ async def update_three_ws_account(body: ThreeWsAccountUpdate):
Settings → three.ws. The cloud generator runs inside this process and the
publish node in a subprocess spawned after this call; both read the env.
"""
+ base_url = _checked_base_url(body.base_url) if body.base_url else None
if body.api_key:
os.environ["THREE_WS_API_KEY"] = body.api_key
else:
os.environ.pop("THREE_WS_API_KEY", None)
- if body.base_url:
- os.environ["THREE_WS_BASE_URL"] = body.base_url
+ if base_url:
+ os.environ["THREE_WS_BASE_URL"] = base_url
return {"ok": True}
diff --git a/apps/forge-desktop/api/tests/test_api_security.py b/apps/forge-desktop/api/tests/test_api_security.py
new file mode 100644
index 000000000..678021f55
--- /dev/null
+++ b/apps/forge-desktop/api/tests/test_api_security.py
@@ -0,0 +1,105 @@
+import os
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+from fastapi.testclient import TestClient
+
+TOKEN = "test-launch-token-0123456789abcdef"
+HOST = {"Host": "127.0.0.1:8765"}
+
+
+class SidecarAccessControlTests(unittest.TestCase):
+ """The loopback sidecar must not be drivable by arbitrary web pages."""
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls._env = mock.patch.dict(os.environ, {"FORGE_API_TOKEN": TOKEN, "FORGE_ALLOWED_ORIGINS": "null"})
+ cls._env.start()
+ from fastapi import FastAPI
+ import access_control
+ from routers import settings
+ app = FastAPI()
+ access_control.install_access_control(app)
+ app.include_router(settings.router)
+ access_control.register_workspace_route(app)
+ cls.client = TestClient(app)
+
+ @classmethod
+ def tearDownClass(cls) -> None:
+ cls._env.stop()
+
+ def test_request_without_token_is_rejected(self) -> None:
+ r = self.client.get("/settings/paths", headers=HOST)
+ self.assertEqual(r.status_code, 401)
+
+ def test_request_with_wrong_token_is_rejected(self) -> None:
+ r = self.client.get("/settings/paths", headers={**HOST, "X-Forge-Token": "nope"})
+ self.assertEqual(r.status_code, 401)
+
+ def test_request_with_token_is_served(self) -> None:
+ r = self.client.get("/settings/paths", headers={**HOST, "X-Forge-Token": TOKEN})
+ self.assertEqual(r.status_code, 200)
+
+ def test_foreign_host_header_is_rejected_even_with_token(self) -> None:
+ r = self.client.get("/settings/paths", headers={"Host": "evil.example", "X-Forge-Token": TOKEN})
+ self.assertEqual(r.status_code, 403)
+
+ def test_cors_does_not_allow_arbitrary_origins(self) -> None:
+ r = self.client.options(
+ "/settings/hf-token",
+ headers={**HOST, "Origin": "https://evil.example", "Access-Control-Request-Method": "POST",
+ "Access-Control-Request-Headers": "content-type,x-forge-token"},
+ )
+ self.assertNotEqual(r.headers.get("access-control-allow-origin"), "*")
+ self.assertNotEqual(r.headers.get("access-control-allow-origin"), "https://evil.example")
+
+ def test_workspace_file_outside_workspace_is_not_served(self) -> None:
+ import services.generator_registry as reg
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ (root / "ws").mkdir()
+ (root / "secret.txt").write_text("secret")
+ (root / "ws" / "ok.txt").write_text("fine")
+ with mock.patch.object(reg, "WORKSPACE_DIR", root / "ws"):
+ h = {**HOST, "X-Forge-Token": TOKEN}
+ self.assertEqual(self.client.get("/workspace/ok.txt", headers=h).status_code, 200)
+ self.assertEqual(self.client.get("/workspace/..%2Fsecret.txt", headers=h).status_code, 404)
+ self.assertEqual(self.client.get("/workspace/%2e%2e/secret.txt", headers=h).status_code, 404)
+
+ def test_workspace_symlink_escape_is_not_served(self) -> None:
+ import services.generator_registry as reg
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ (root / "ws").mkdir()
+ (root / "secret.txt").write_text("secret")
+ try:
+ (root / "ws" / "link.txt").symlink_to(root / "secret.txt")
+ except OSError:
+ self.skipTest("symlinks unavailable")
+ with mock.patch.object(reg, "WORKSPACE_DIR", root / "ws"):
+ r = self.client.get("/workspace/link.txt", headers={**HOST, "X-Forge-Token": TOKEN})
+ self.assertEqual(r.status_code, 404)
+
+ def test_settings_paths_rejects_filesystem_root_as_workspace(self) -> None:
+ import services.generator_registry as reg
+ h = {**HOST, "X-Forge-Token": TOKEN}
+ with mock.patch.object(reg.generator_registry, "update_paths") as upd:
+ for bad in ("/", "C:\\", "relative/dir"):
+ r = self.client.post("/settings/paths", json={"workspace_dir": bad}, headers=h)
+ self.assertEqual(r.status_code, 400, bad)
+ upd.assert_not_called()
+
+ def test_three_ws_base_url_must_be_https_or_loopback(self) -> None:
+ h = {**HOST, "X-Forge-Token": TOKEN}
+ with mock.patch.dict(os.environ, {}, clear=False):
+ r = self.client.post("/settings/three-ws", json={"api_key": "k", "base_url": "http://attacker.example"}, headers=h)
+ self.assertEqual(r.status_code, 400)
+ r = self.client.post("/settings/three-ws", json={"api_key": "k", "base_url": "https://three.ws"}, headers=h)
+ self.assertEqual(r.status_code, 200)
+ os.environ.pop("THREE_WS_API_KEY", None)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/apps/forge-desktop/electron/main/api-auth.ts b/apps/forge-desktop/electron/main/api-auth.ts
new file mode 100644
index 000000000..1fe02d4ac
--- /dev/null
+++ b/apps/forge-desktop/electron/main/api-auth.ts
@@ -0,0 +1,52 @@
+import { randomBytes } from 'crypto'
+import axios from 'axios'
+import { session } from 'electron'
+
+/**
+ * Per-launch secret for the loopback FastAPI sidecar. Any web page can reach
+ * 127.0.0.1, so the sidecar rejects every request that does not carry this
+ * token (see api/access_control.py). It is generated fresh on each launch,
+ * handed to uvicorn through the environment, and attached here to every
+ * request this app sends to the sidecar: from the main process (axios and
+ * fetch) and from the renderer (session request hook), so the renderer code
+ * never handles it.
+ */
+export const API_TOKEN_HEADER = 'X-Forge-Token'
+export const API_TOKEN = randomBytes(32).toString('hex')
+
+/** Origins the renderer is served from: file:// reports "null"; dev uses the Vite server. */
+export function allowedRendererOrigins(): string {
+ const origins = ['null']
+ const devUrl = process.env['ELECTRON_RENDERER_URL']
+ if (devUrl) {
+ try {
+ origins.push(new URL(devUrl).origin)
+ } catch {
+ // A malformed dev URL simply adds no origin.
+ }
+ }
+ return origins.join(',')
+}
+
+export function installApiAuth(apiBaseUrl: string): void {
+ const isSidecar = (url: string | undefined): boolean => !!url && url.startsWith(apiBaseUrl)
+
+ axios.interceptors.request.use((config) => {
+ const target = config.baseURL ? `${config.baseURL}${config.url ?? ''}` : config.url
+ if (isSidecar(target)) config.headers.set(API_TOKEN_HEADER, API_TOKEN)
+ return config
+ })
+
+ const nativeFetch = globalThis.fetch.bind(globalThis)
+ globalThis.fetch = ((input: Parameters<typeof fetch>[0], init?: RequestInit) => {
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url
+ if (!isSidecar(url)) return nativeFetch(input, init)
+ const headers = new Headers(init?.headers ?? (typeof input === 'object' && 'headers' in input ? input.headers : undefined))
+ headers.set(API_TOKEN_HEADER, API_TOKEN)
+ return nativeFetch(input, { ...init, headers })
+ }) as typeof fetch
+
+ session.defaultSession.webRequest.onBeforeSendHeaders({ urls: [`${apiBaseUrl}/*`] }, (details, callback) => {
+ callback({ requestHeaders: { ...details.requestHeaders, [API_TOKEN_HEADER]: API_TOKEN } })
+ })
+}
diff --git a/apps/forge-desktop/electron/main/index.ts b/apps/forge-desktop/electron/main/index.ts
index 031597ffc..96b74983e 100644
--- a/apps/forge-desktop/electron/main/index.ts
+++ b/apps/forge-desktop/electron/main/index.ts
@@ -2,7 +2,8 @@ import { app, BrowserWindow, shell, session } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import { setupIpcHandlers } from './ipc-handlers'
-import { PythonBridge } from './python-bridge'
+import { PythonBridge, API_BASE_URL } from './python-bridge'
+import { installApiAuth } from './api-auth'
import { logger, archiveCurrentSession } from './logger'
import { initAutoUpdater } from './updater'
import { syncBuiltinExtensions } from './builtin-sync'
@@ -94,6 +95,8 @@ app.whenReady().then(async () => {
logger.info(`App started, version ${app.getVersion()}`)
electronApp.setAppUserModelId('ws.three.forge')
+ installApiAuth(API_BASE_URL)
+
// Clear Chromium disk cache on startup to recover from any corruption
await session.defaultSession.clearCache()
diff --git a/apps/forge-desktop/electron/main/python-bridge.ts b/apps/forge-desktop/electron/main/python-bridge.ts
index 80370fbc5..f1355a38c 100644
--- a/apps/forge-desktop/electron/main/python-bridge.ts
+++ b/apps/forge-desktop/electron/main/python-bridge.ts
@@ -9,6 +9,7 @@ import { getThreeWsApiKey, THREE_WS_ORIGIN } from './three-ws-account'
import { logger } from './logger'
import { cleanPythonEnv, getVenvPythonExe } from './python-setup'
import { getBuiltinExtensionsDir } from './builtin-sync'
+import { API_TOKEN, allowedRendererOrigins } from './api-auth'
const API_PORT = 8765
const API_HOST = '127.0.0.1'
@@ -55,6 +56,9 @@ export class PythonBridge {
env: {
...cleanPythonEnv(),
PYTHONUNBUFFERED: '1',
+ // Access control for the loopback API (api/access_control.py).
+ FORGE_API_TOKEN: API_TOKEN,
+ FORGE_ALLOWED_ORIGINS: allowedRendererOrigins(),
// mesh_ops uses Electron in Node mode for the existing meshoptimizer
// backend, so packaged builds do not depend on a system Node install.
THREEWS_NODE_EXECUTABLE: process.execPath,