From 366376140b75412d71a1a1a128e606aad2dba5d6 Mon Sep 17 00:00:00 2001 From: Lightning Pixel Date: Mon, 16 Nov 2026 17:18:40 +0100 Subject: [PATCH 1/2] feat(security): lock the local API to the Modly app While Modly ran, any web page open in the user's browser could call the whole local API (allow_origins="*"): read workspace files, start generations, install packages, delete models. - Electron generates a token per launch and passes it to the backend (MODLY_API_TOKEN) with the renderer's origins (MODLY_ALLOWED_ORIGINS). - A webRequest hook adds X-Modly-Token to every renderer request to the API, so axios, fetch, SSE, three.js loaders and downloads need no change and the renderer never sees the token. Main-process calls go through a shared axios client that sends it. - The backend rejects any request without the token (401), except GET /health, OPTIONS and the OrcaSlicer route; CORS only allows the app's origins. - OrcaSlicer (an external app) gets a URL signed with an HMAC of the source path from GET /export/slicer-link; links expire with the launch. - The app window can no longer navigate away from its own pages (links open in the browser), so no other page can receive the token. - The token is written to api-token next to api-port (0600, removed at quit) for the MCP server and modly-cli; modly-cli only sends it to loopback hosts. The agent and extension subprocesses get it by env. - Without MODLY_API_TOKEN (standalone uvicorn, Jetson, modly-cli serve) the API stays open, with a warning at startup. Closes #458 --- api/README.md | 8 + api/main.py | 14 +- api/mcp_server.py | 23 +- api/routers/agent.py | 5 +- api/routers/export.py | 37 +++- api/services/api_auth.py | 169 +++++++++++++++ api/services/extension_process.py | 6 + api/tests/test_api_auth.py | 247 ++++++++++++++++++++++ api/tests/test_export_router.py | 88 ++++++++ api/tests/test_extension_process.py | 8 + docs/running-on-jetson.md | 4 + electron/main/api-auth.test.ts | 100 +++++++++ electron/main/api-auth.ts | 107 ++++++++++ electron/main/index.ts | 29 +++ electron/main/ipc-handlers.ts | 25 +-- electron/main/model-downloader.ts | 7 +- electron/main/model-weight-ipc.test.mjs | 13 +- electron/main/python-bridge.ts | 10 + package.json | 2 +- src/areas/generate/GeneratePage.tsx | 11 +- src/areas/generate/orcaSlicerLink.test.ts | 57 ++--- src/areas/generate/orcaSlicerLink.ts | 35 ++- tools/modly-cli/SKILL.md | 2 +- tools/modly-cli/agent.py | 36 +++- tools/modly-cli/test_agent.py | 69 ++++++ 25 files changed, 1011 insertions(+), 101 deletions(-) create mode 100644 api/services/api_auth.py create mode 100644 api/tests/test_api_auth.py create mode 100644 electron/main/api-auth.test.ts create mode 100644 electron/main/api-auth.ts diff --git a/api/README.md b/api/README.md index cdcd4d6b0..372b517d5 100644 --- a/api/README.md +++ b/api/README.md @@ -21,6 +21,14 @@ pip install -r requirements.txt uvicorn main:app --host 127.0.0.1 --port 8765 --reload ``` +Run like this, the API is **tokenless**: it accepts every request (CORS `*`) and logs +`API token disabled` once at startup. The desktop app instead starts it with +`MODLY_API_TOKEN` (per launch) and `MODLY_ALLOWED_ORIGINS`; every request must then send +`X-Modly-Token: ` or get a 401. `GET /health` and the OrcaSlicer route +`/export/slicer/...` (HMAC-signed links from `GET /export/slicer-link`) are exempt. The app +writes the token to `api-token` next to `api-port` in its user data folder for local tools +(MCP server, modly-cli); extensions get it as `MODLY_API_TOKEN`. + ## Key endpoints | Method | Path | Description | diff --git a/api/main.py b/api/main.py index 9bf352304..34406e2e4 100644 --- a/api/main.py +++ b/api/main.py @@ -5,13 +5,14 @@ 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 services import api_auth + from routers import generation, model, optimize, status, settings, extensions, export, workflow_runs, agent, llm @@ -48,15 +49,8 @@ def filter(self, record): 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"], -) +# Token check + CORS, from MODLY_API_TOKEN / MODLY_ALLOWED_ORIGINS (set by Electron). +api_auth.configure(app) app.include_router(status.router) app.include_router(settings.router) diff --git a/api/mcp_server.py b/api/mcp_server.py index 2f2f8814b..2aa60a9a3 100644 --- a/api/mcp_server.py +++ b/api/mcp_server.py @@ -16,7 +16,9 @@ } Requires Modly to be running. Its API is found through MODLY_API_URL, else the -port the app writes to /api-port, else http://127.0.0.1:8765. +port the app writes to /api-port, else http://127.0.0.1:8765. Calls +carry the X-Modly-Token the app writes to /api-token (else env +MODLY_API_TOKEN; none for a tokenless standalone backend). """ import asyncio @@ -51,6 +53,22 @@ def resolve_api_url() -> str: except (OSError, ValueError): return "http://127.0.0.1:8765" + +def resolve_api_token() -> str | None: + """The running app's token from /api-token, else MODLY_API_TOKEN.""" + try: + token = (_modly_user_data() / "api-token").read_text().strip() + if token: + return token + except OSError: + pass + return (os.environ.get("MODLY_API_TOKEN") or "").strip() or None + + +def api_headers() -> dict[str, str]: + token = resolve_api_token() + return {"X-Modly-Token": token} if token else {} + server = Server("modly") @@ -253,7 +271,8 @@ async def list_tools() -> list[Tool]: @server.call_tool() async def call_tool(name: str, arguments: dict) -> list[TextContent]: api_url = resolve_api_url() # per call: the app may restart on another port - async with httpx.AsyncClient(base_url=api_url, timeout=60.0) as client: + # Token per call too: it changes on every app launch. + async with httpx.AsyncClient(base_url=api_url, timeout=60.0, headers=api_headers()) as client: try: result = await _dispatch(client, name, arguments) except httpx.ConnectError: diff --git a/api/routers/agent.py b/api/routers/agent.py index e8b1fd8b0..f949a6248 100644 --- a/api/routers/agent.py +++ b/api/routers/agent.py @@ -13,7 +13,7 @@ from fastapi.responses import StreamingResponse from pydantic import BaseModel, Field -from services import llm_server +from services import api_auth, llm_server from services import ollama_health as ollama_health_service from services.llm_server import llama_pool from services.mesh_ops import MeshOp, MeshOpNotFoundError, MeshOpsRegistry, mesh_ops_registry @@ -589,7 +589,8 @@ async def execute_tool( action_payload carries data the frontend needs to react (e.g. new mesh URL). has_image: the user's last message carries an image (generate_from_image). """ - async with httpx.AsyncClient(timeout=timeout) as client: + # Every call here goes back into this API, which may be token-locked. + async with httpx.AsyncClient(timeout=timeout, headers=api_auth.auth_headers()) as client: try: op = _agent_op(name) if op is not None: diff --git a/api/routers/export.py b/api/routers/export.py index 854d8bf21..436a13529 100644 --- a/api/routers/export.py +++ b/api/routers/export.py @@ -8,7 +8,7 @@ from fastapi import APIRouter, HTTPException from fastapi.responses import Response, FileResponse -from services import imported_sources +from services import api_auth, imported_sources # Import the module (not the name) so WORKSPACE_DIR is read at call time: the # settings endpoint rebinds it when the user moves the workspace. import services.generator_registry as registry @@ -91,9 +91,14 @@ def _normalize_print_scale(mesh: "trimesh.Trimesh") -> bool: return True -def _resolve_slicer_source(token: str) -> tuple[Path, str]: +def _resolve_slicer_source(token: str, fmt: str) -> tuple[Path, str]: """Decode ``token`` into an existing source file and its ORIGINAL suffix. + ``token`` is ``[.]``. OrcaSlicer cannot send the + X-Modly-Token header, so when the API is locked the signature (an HMAC of + ``fmt`` + path keyed by the API token, see ``api_auth.sign_slicer_source``) + is what proves the link came from the app; a missing or wrong one is a 403. + Two kinds of source are accepted: * a workspace-relative path, confined to the workspace by ancestry; @@ -105,11 +110,14 @@ def _resolve_slicer_source(token: str) -> tuple[Path, str]: The returned suffix is the format the user actually supplied — for an import that is the pre-conversion extension, which is what decides the up-axis. """ + encoded, signature = api_auth.split_slicer_token(token) try: - padded = token + "=" * (-len(token) % 4) + padded = encoded + "=" * (-len(encoded) % 4) decoded = base64.urlsafe_b64decode(padded.encode("ascii")).decode("utf-8") except (binascii.Error, UnicodeDecodeError, ValueError): raise HTTPException(400, "Malformed source token") + if not api_auth.slicer_signature_valid(fmt, decoded, signature): + raise HTTPException(403, "Invalid slicer link signature") candidate = Path(decoded) if candidate.is_absolute(): @@ -144,8 +152,9 @@ def export_for_slicer(fmt: str, token: str, filename: str): format — from the URL's FINAL path segment, so a query string (``?path=...``) would corrupt the parsed extension and the model would silently fail to import. ``token`` is the url-safe-base64 of the source path — workspace- - relative, or absolute for a file the user imported this session (see - ``_resolve_slicer_source``); ``filename`` (e.g. ``model.stl``) is what + relative, or absolute for a file the user imported this session — plus, + when the API is locked, ``.`` (see ``_resolve_slicer_source``; + get it from ``GET /export/slicer-link``); ``filename`` (e.g. ``model.stl``) is what OrcaSlicer names the download. """ fmt = fmt.lower() @@ -154,7 +163,7 @@ def export_for_slicer(fmt: str, token: str, filename: str): if not filename.lower().endswith(f".{fmt}"): raise HTTPException(400, "Filename must end with the requested format extension") - full_path, source_suffix = _resolve_slicer_source(token) + full_path, source_suffix = _resolve_slicer_source(token, fmt) mesh = _to_single_mesh(trimesh.load(str(full_path))) # glTF/GLB is Y-up; OrcaSlicer's world is Z-up. Rotate +90° about X so the @@ -178,6 +187,22 @@ def export_for_slicer(fmt: str, token: str, filename: str): ) +@router.get("/slicer-link") +def slicer_link(path: str, fmt: str = "stl"): + """The OrcaSlicer URL path for a source mesh, signed for this launch. + + The renderer cannot sign links itself (it never sees the API token), so it + asks here — an authenticated call — and hands OrcaSlicer + ````. ``path`` is what the slicer route accepts: + workspace-relative, or the absolute path of a file imported this session. + """ + fmt = fmt.lower() + if fmt not in SLICER_FORMATS: + raise HTTPException(400, f"Unsupported slicer format: {fmt}. Supported: {', '.join(sorted(SLICER_FORMATS))}") + token = api_auth.sign_slicer_source(fmt, path) + return {"token": token, "url_path": f"/export/slicer/{fmt}/{token}/model.{fmt}"} + + @router.get("/{fmt}") def export_mesh(fmt: str, path: str): if fmt not in SUPPORTED: diff --git a/api/services/api_auth.py b/api/services/api_auth.py new file mode 100644 index 000000000..76acc42a8 --- /dev/null +++ b/api/services/api_auth.py @@ -0,0 +1,169 @@ +""" +Locks the local API to the Modly app. + +Electron starts the backend with ``MODLY_API_TOKEN`` (a per-launch secret) and +``MODLY_ALLOWED_ORIGINS`` (the renderer's origins). Every request must then +carry ``X-Modly-Token: ``, so a web page open in the user's browser can +no longer drive the API while Modly runs. + +Without ``MODLY_API_TOKEN`` (a standalone ``uvicorn main:app`` run, modly-cli +``serve``, a Jetson box) the API stays open, as before, and says so once at +startup. +""" +import base64 +import hashlib +import hmac +import json +import logging +import os + +logger = logging.getLogger("modly.api_auth") + +TOKEN_ENV = "MODLY_API_TOKEN" +ORIGINS_ENV = "MODLY_ALLOWED_ORIGINS" +TOKEN_HEADER = "X-Modly-Token" + +_UNAUTHORIZED_BODY = json.dumps({"detail": "Missing or invalid Modly API token"}).encode("utf-8") + +# Fetched by OrcaSlicer, an external app that cannot send the header: the route +# checks its own HMAC signature instead (see sign_slicer_source). +SLICER_PREFIX = "/export/slicer/" + + +def _read_token() -> str | None: + return (os.environ.get(TOKEN_ENV) or "").strip() or None + + +# Read once at startup; tests patch this attribute. +API_TOKEN: str | None = _read_token() + + +def allowed_origins(token: str | None) -> list[str]: + """CORS origins: the app's own (from env) when locked, anything when tokenless.""" + if not token: + return ["*"] + raw = os.environ.get(ORIGINS_ENV) or "" + return [origin.strip() for origin in raw.split(",") if origin.strip()] + + +def auth_headers() -> dict[str, str]: + """Headers for the backend's own calls back into the API.""" + return {TOKEN_HEADER: API_TOKEN} if API_TOKEN else {} + + +def token_matches(supplied: str | None, token: str) -> bool: + if not supplied: + return False + return hmac.compare_digest(supplied.encode("utf-8"), token.encode("utf-8")) + + +def _is_exempt(method: str, path: str) -> bool: + if method == "OPTIONS": + return True + if method in ("GET", "HEAD") and (path == "/health" or path.startswith(SLICER_PREFIX)): + return True + return False + + +class ApiTokenMiddleware: + """Pure ASGI middleware: rejects requests without the right X-Modly-Token.""" + + def __init__(self, app, token: str): + self.app = app + self.token = token + + async def __call__(self, scope, receive, send): + if scope["type"] not in ("http", "websocket"): + return await self.app(scope, receive, send) + + method = scope.get("method", "GET") + if _is_exempt(method, scope.get("path", "")): + return await self.app(scope, receive, send) + + supplied = None + for name, value in scope.get("headers") or (): + if name == b"x-modly-token": + supplied = value.decode("latin-1") + break + if token_matches(supplied, self.token): + return await self.app(scope, receive, send) + + if scope["type"] == "websocket": + await send({"type": "websocket.close", "code": 1008}) + return + await send({ + "type": "http.response.start", + "status": 401, + "headers": [ + (b"content-type", b"application/json"), + (b"content-length", str(len(_UNAUTHORIZED_BODY)).encode("ascii")), + ], + }) + await send({"type": "http.response.body", "body": _UNAUTHORIZED_BODY}) + + +def configure(app) -> None: + """Install the token check and CORS on ``app`` from the startup env.""" + from fastapi.middleware.cors import CORSMiddleware + + token = API_TOKEN + if token: + # Added first so CORS wraps it: a 401 still carries CORS headers and the + # renderer can read it. + app.add_middleware(ApiTokenMiddleware, token=token) + else: + logger.warning( + "API token disabled: %s is not set, so any local process or web page " + "can call this API. The Modly app always sets it.", TOKEN_ENV, + ) + app.add_middleware( + CORSMiddleware, + allow_origins=allowed_origins(token), + 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"], + ) + + +# --------------------------------------------------------------------------- +# OrcaSlicer links +# --------------------------------------------------------------------------- + +def _b64(data: bytes) -> str: + return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=") + + +def _slicer_signature(token: str, fmt: str, source_path: str) -> str: + message = f"{fmt.lower()}\0{source_path}".encode("utf-8") + return _b64(hmac.new(token.encode("utf-8"), message, hashlib.sha256).digest()) + + +def sign_slicer_source(fmt: str, source_path: str) -> str: + """The ``{token}`` path segment of a slicer URL for ``source_path``. + + ``.`` when the API is locked (``.`` is not in the + url-safe base64 alphabet, so the split is unambiguous); just the path part + when tokenless. + """ + encoded = _b64(source_path.encode("utf-8")) + if not API_TOKEN: + return encoded + return f"{encoded}.{_slicer_signature(API_TOKEN, fmt, source_path)}" + + +def split_slicer_token(segment: str) -> tuple[str, str | None]: + """``(b64path, signature or None)`` from a slicer ``{token}`` segment.""" + encoded, dot, signature = segment.partition(".") + return encoded, (signature if dot else None) + + +def slicer_signature_valid(fmt: str, source_path: str, signature: str | None) -> bool: + """True when tokenless, else when ``signature`` signs ``fmt`` + ``source_path``.""" + if not API_TOKEN: + return True + if not signature: + return False + expected = _slicer_signature(API_TOKEN, fmt, source_path) + return hmac.compare_digest(signature.encode("ascii", "replace"), expected.encode("ascii")) diff --git a/api/services/extension_process.py b/api/services/extension_process.py index 020fa6c83..c356c1cc0 100644 --- a/api/services/extension_process.py +++ b/api/services/extension_process.py @@ -93,6 +93,12 @@ def _build_env(self) -> dict: env["MODLY_API_DIR"] = str(Path(__file__).parent.parent) # Lets extensions call back into the Modly API (e.g. /llm/chat for the shared LLM). env.setdefault("MODLY_API_URL", "http://127.0.0.1:8765") + # The API is locked to the app: an extension calling it must send + # `X-Modly-Token: $MODLY_API_TOKEN`. Inherited already; explicit so it + # survives any future env scrubbing. Absent in tokenless mode. + from services import api_auth + if api_auth.API_TOKEN: + env[api_auth.TOKEN_ENV] = api_auth.API_TOKEN # Force the worker's Python stdio to UTF-8 so it matches the UTF-8 # pipe readers below regardless of the OS locale (cp1252/cp932). env["PYTHONUTF8"] = "1" diff --git a/api/tests/test_api_auth.py b/api/tests/test_api_auth.py new file mode 100644 index 000000000..4ba61c7b7 --- /dev/null +++ b/api/tests/test_api_auth.py @@ -0,0 +1,247 @@ +import asyncio +import os +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +import httpx +from fastapi import FastAPI + +from services import api_auth + +TOKEN = "0123456789abcdef" * 4 + + +def _app(token: str | None, origins: str = "") -> FastAPI: + """A tiny app wired exactly like main.py, with routes standing in for the real ones.""" + app = FastAPI() + with mock.patch.object(api_auth, "API_TOKEN", token), \ + mock.patch.dict(os.environ, {api_auth.ORIGINS_ENV: origins}): + api_auth.configure(app) + + @app.get("/health") + def health(): + return {"status": "ok"} + + @app.get("/model/all") + def models(): + return [] + + @app.post("/model/switch") + def switch(): + return {"ok": True} + + @app.get("/export/slicer/{fmt}/{token}/{filename}") + def slicer(fmt: str, token: str, filename: str): + return {"served": True} + + return app + + +def _request(app: FastAPI, method: str, path: str, headers: dict | None = None) -> httpx.Response: + async def go(): + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://127.0.0.1:8765") as client: + return await client.request(method, path, headers=headers or {}) + return asyncio.run(go()) + + +class TokenMiddlewareTests(unittest.TestCase): + def setUp(self) -> None: + self.app = _app(TOKEN, "http://localhost:5173,null") + + def test_missing_token_is_401_with_json_detail(self) -> None: + r = _request(self.app, "GET", "/model/all") + self.assertEqual(r.status_code, 401) + self.assertEqual(r.json(), {"detail": "Missing or invalid Modly API token"}) + + def test_wrong_token_is_401(self) -> None: + r = _request(self.app, "POST", "/model/switch", {"X-Modly-Token": "f" * 64}) + self.assertEqual(r.status_code, 401) + + def test_right_token_passes(self) -> None: + self.assertEqual(_request(self.app, "GET", "/model/all", {"X-Modly-Token": TOKEN}).status_code, 200) + self.assertEqual(_request(self.app, "POST", "/model/switch", {"x-modly-token": TOKEN}).status_code, 200) + + def test_health_is_exempt(self) -> None: + r = _request(self.app, "GET", "/health") + self.assertEqual(r.status_code, 200) + self.assertEqual(r.json(), {"status": "ok"}) + + def test_options_is_exempt(self) -> None: + r = _request(self.app, "OPTIONS", "/model/all") + self.assertNotEqual(r.status_code, 401) + + def test_slicer_route_is_left_to_its_own_signature(self) -> None: + r = _request(self.app, "GET", "/export/slicer/stl/abc.def/model.stl") + self.assertEqual(r.status_code, 200) + + def test_similar_paths_are_not_exempt(self) -> None: + self.assertEqual(_request(self.app, "GET", "/healthz").status_code, 401) + self.assertEqual(_request(self.app, "GET", "/export/slicer-link?path=a.glb").status_code, 401) + + def test_401_still_carries_cors_headers_for_the_app_origin(self) -> None: + r = _request(self.app, "GET", "/model/all", {"Origin": "http://localhost:5173"}) + self.assertEqual(r.status_code, 401) + self.assertEqual(r.headers.get("access-control-allow-origin"), "http://localhost:5173") + + +class CorsTests(unittest.TestCase): + def _preflight(self, app: FastAPI, origin: str) -> httpx.Response: + return _request(app, "OPTIONS", "/model/all", { + "Origin": origin, + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "x-modly-token,content-type", + }) + + def test_locked_mode_allows_only_the_configured_origins(self) -> None: + app = _app(TOKEN, " http://localhost:5173 , ,null,") + ok = self._preflight(app, "http://localhost:5173") + self.assertEqual(ok.status_code, 200) + self.assertEqual(ok.headers["access-control-allow-origin"], "http://localhost:5173") + self.assertIn("x-modly-token", ok.headers["access-control-allow-headers"].lower()) + self.assertEqual(self._preflight(app, "null").status_code, 200) + self.assertEqual(self._preflight(app, "https://evil.example").status_code, 400) + + def test_locked_mode_exposes_content_length(self) -> None: + r = _request(_app(TOKEN, "null"), "GET", "/model/all", {"Origin": "null", "X-Modly-Token": TOKEN}) + self.assertIn("content-length", r.headers.get("access-control-expose-headers", "").lower()) + + def test_allowed_origins_parsing(self) -> None: + with mock.patch.dict(os.environ, {api_auth.ORIGINS_ENV: "http://localhost:5173,file://,null, ,"}): + self.assertEqual(api_auth.allowed_origins(TOKEN), ["http://localhost:5173", "file://", "null"]) + self.assertEqual(api_auth.allowed_origins(None), ["*"]) + + +class TokenlessModeTests(unittest.TestCase): + def test_everything_is_allowed_and_cors_is_open(self) -> None: + app = _app(None) + self.assertEqual(_request(app, "GET", "/model/all").status_code, 200) + self.assertEqual(_request(app, "POST", "/model/switch", {"X-Modly-Token": "junk"}).status_code, 200) + r = _request(app, "GET", "/model/all", {"Origin": "https://anything.example"}) + self.assertEqual(r.headers.get("access-control-allow-origin"), "*") + + def test_warns_once_at_startup(self) -> None: + with self.assertLogs("modly.api_auth", level="WARNING") as logs: + _app(None) + self.assertEqual(len(logs.records), 1) + self.assertIn("API token disabled", logs.output[0]) + + def test_token_is_read_from_env_and_stripped(self) -> None: + with mock.patch.dict(os.environ, {api_auth.TOKEN_ENV: f" {TOKEN}\n"}): + self.assertEqual(api_auth._read_token(), TOKEN) + with mock.patch.dict(os.environ, {api_auth.TOKEN_ENV: " "}): + self.assertIsNone(api_auth._read_token()) + + def test_auth_headers(self) -> None: + with mock.patch.object(api_auth, "API_TOKEN", TOKEN): + self.assertEqual(api_auth.auth_headers(), {"X-Modly-Token": TOKEN}) + with mock.patch.object(api_auth, "API_TOKEN", None): + self.assertEqual(api_auth.auth_headers(), {}) + + +class AgentClientTests(unittest.TestCase): + def test_tool_calls_back_into_the_api_carry_the_token(self) -> None: + import routers.agent as agent + + seen: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(request) + return httpx.Response(200, json=[]) + + real = httpx.AsyncClient + + def client(*args, **kwargs): + kwargs["transport"] = httpx.MockTransport(handler) + return real(*args, **kwargs) + + with mock.patch.object(api_auth, "API_TOKEN", TOKEN), \ + mock.patch.object(agent.httpx, "AsyncClient", client): + asyncio.run(agent.execute_tool("list_models", {}, {})) + self.assertTrue(seen) + self.assertEqual(seen[0].headers.get("x-modly-token"), TOKEN) + + +def _load_mcp_server(): + """Import mcp_server with the `mcp` SDK stubbed: only its HTTP side is under + test, and the installed SDK version may not match the decorators it uses.""" + import importlib + import sys + import types + + class _Server: + def __init__(self, *_args, **_kwargs): + pass + + def __getattr__(self, _name): + return lambda *a, **k: (lambda fn: fn) + + class _TextContent: + def __init__(self, **kwargs): + self.__dict__.update(kwargs) + + stubs = { + "mcp": types.ModuleType("mcp"), + "mcp.server": types.ModuleType("mcp.server"), + "mcp.server.stdio": types.ModuleType("mcp.server.stdio"), + "mcp.types": types.ModuleType("mcp.types"), + } + stubs["mcp.server"].Server = _Server + stubs["mcp.server.stdio"].stdio_server = None + stubs["mcp.types"].Tool = dict + stubs["mcp.types"].TextContent = _TextContent + with mock.patch.dict(sys.modules, stubs): + sys.modules.pop("mcp_server", None) + module = importlib.import_module("mcp_server") + sys.modules.pop("mcp_server", None) + return module + + +try: + mcp_server = _load_mcp_server() + HAVE_MCP = True +except Exception: # noqa: BLE001 + HAVE_MCP = False + + +@unittest.skipUnless(HAVE_MCP, "mcp_server could not be imported") +class McpServerTokenTests(unittest.TestCase): + def test_reads_the_token_file_next_to_api_port(self) -> None: + with tempfile.TemporaryDirectory() as td: + (Path(td) / "api-token").write_text(TOKEN + "\n") + with mock.patch.object(mcp_server, "_modly_user_data", return_value=Path(td)), \ + mock.patch.dict(os.environ, {"MODLY_API_TOKEN": "env"}): + self.assertEqual(mcp_server.resolve_api_token(), TOKEN) + self.assertEqual(mcp_server.api_headers(), {"X-Modly-Token": TOKEN}) + + def test_falls_back_to_env_then_no_header(self) -> None: + with tempfile.TemporaryDirectory() as td, \ + mock.patch.object(mcp_server, "_modly_user_data", return_value=Path(td)): + with mock.patch.dict(os.environ, {"MODLY_API_TOKEN": "env"}): + self.assertEqual(mcp_server.resolve_api_token(), "env") + with mock.patch.dict(os.environ, {"MODLY_API_TOKEN": ""}): + self.assertEqual(mcp_server.api_headers(), {}) + + def test_tool_calls_send_the_header(self) -> None: + seen: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(request) + return httpx.Response(200, json=[]) + + real = httpx.AsyncClient + + def client(*args, **kwargs): + kwargs["transport"] = httpx.MockTransport(handler) + return real(*args, **kwargs) + + with mock.patch.object(mcp_server, "resolve_api_token", return_value=TOKEN), \ + mock.patch.object(mcp_server.httpx, "AsyncClient", client): + asyncio.run(mcp_server.call_tool("modly_list_models", {})) + self.assertEqual(seen[0].headers.get("x-modly-token"), TOKEN) + + +if __name__ == "__main__": + unittest.main() diff --git a/api/tests/test_export_router.py b/api/tests/test_export_router.py index 2bed2a687..e8a6d7ce1 100644 --- a/api/tests/test_export_router.py +++ b/api/tests/test_export_router.py @@ -204,5 +204,93 @@ def test_registered_but_deleted_file_is_404(self) -> None: self.assertEqual(ctx.exception.status_code, 404) +@unittest.skipUnless(HAVE_TRIMESH, "trimesh not installed") +class SignedSlicerLinkTests(unittest.TestCase): + """With an API token, OrcaSlicer links must carry the app's HMAC signature.""" + + def setUp(self) -> None: + from unittest import mock + from services import api_auth + + self._tmp = tempfile.TemporaryDirectory() + self.workspace = Path(self._tmp.name).resolve() + self._orig_workspace = export_router.registry.WORKSPACE_DIR + export_router.registry.WORKSPACE_DIR = self.workspace + self.rel = "Workflows/hero.glb" + (self.workspace / "Workflows").mkdir(parents=True, exist_ok=True) + trimesh.creation.box(extents=[0.3, 1.0, 0.3]).export(str(self.workspace / self.rel)) + self._patch = mock.patch.object(api_auth, "API_TOKEN", "a" * 64) + self._patch.start() + + def tearDown(self) -> None: + self._patch.stop() + export_router.registry.WORKSPACE_DIR = self._orig_workspace + self._tmp.cleanup() + + def _signed(self, fmt: str = "stl", path: str | None = None) -> str: + return export_router.slicer_link(path or self.rel, fmt)["token"] + + def test_slicer_link_returns_a_signed_path_only_url(self) -> None: + link = export_router.slicer_link(self.rel, "STL") + self.assertIn(".", link["token"]) + self.assertTrue(link["token"].startswith(_token(self.rel) + ".")) + self.assertEqual(link["url_path"], f"/export/slicer/stl/{link['token']}/model.stl") + self.assertNotIn("?", link["url_path"]) + + def test_signed_link_is_served(self) -> None: + resp = export_router.export_for_slicer("stl", self._signed(), "model.stl") + self.assertGreater(len(_load_stl(resp).faces), 0) + + def test_unsigned_link_is_refused(self) -> None: + with self.assertRaises(HTTPException) as ctx: + export_router.export_for_slicer("stl", _token(self.rel), "model.stl") + self.assertEqual(ctx.exception.status_code, 403) + + def test_tampered_signature_is_refused(self) -> None: + encoded, sig = self._signed().split(".") + bad = encoded + "." + ("A" if sig[0] != "A" else "B") + sig[1:] + with self.assertRaises(HTTPException) as ctx: + export_router.export_for_slicer("stl", bad, "model.stl") + self.assertEqual(ctx.exception.status_code, 403) + + def test_signature_does_not_transfer_to_another_path(self) -> None: + other = "Workflows/other.glb" + trimesh.creation.box().export(str(self.workspace / other)) + sig = self._signed().split(".")[1] + with self.assertRaises(HTTPException) as ctx: + export_router.export_for_slicer("stl", f"{_token(other)}.{sig}", "model.stl") + self.assertEqual(ctx.exception.status_code, 403) + + def test_signature_does_not_transfer_to_another_format(self) -> None: + with self.assertRaises(HTTPException) as ctx: + export_router.export_for_slicer("obj", self._signed("stl"), "model.obj") + self.assertEqual(ctx.exception.status_code, 403) + + def test_signature_from_another_launch_is_refused(self) -> None: + from unittest import mock + from services import api_auth + + with mock.patch.object(api_auth, "API_TOKEN", "b" * 64): + stale = self._signed() + with self.assertRaises(HTTPException) as ctx: + export_router.export_for_slicer("stl", stale, "model.stl") + self.assertEqual(ctx.exception.status_code, 403) + + def test_slicer_link_rejects_unsupported_format(self) -> None: + with self.assertRaises(HTTPException) as ctx: + export_router.slicer_link(self.rel, "glb") + self.assertEqual(ctx.exception.status_code, 400) + + def test_tokenless_link_is_the_bare_path_token(self) -> None: + from unittest import mock + from services import api_auth + + with mock.patch.object(api_auth, "API_TOKEN", None): + link = export_router.slicer_link(self.rel, "stl") + self.assertEqual(link["token"], _token(self.rel)) + resp = export_router.export_for_slicer("stl", link["token"], "model.stl") + self.assertGreater(len(_load_stl(resp).faces), 0) + + if __name__ == "__main__": unittest.main() diff --git a/api/tests/test_extension_process.py b/api/tests/test_extension_process.py index 29602cd68..9bf211d7f 100644 --- a/api/tests/test_extension_process.py +++ b/api/tests/test_extension_process.py @@ -148,6 +148,14 @@ def test_sets_explicit_node_identity_and_shared_weight_dirs(self) -> None: {"base": str(Path("/tmp/models/ext/_shared/base"))}, ) + def test_passes_the_api_token_so_extensions_can_call_the_api(self) -> None: + from unittest import mock + from services import api_auth + + with mock.patch.object(api_auth, "API_TOKEN", "f" * 64): + env = _make_proc()._build_env() + self.assertEqual(env["MODLY_API_TOKEN"], "f" * 64) + class MissingModuleExtractionTests(unittest.TestCase): def test_extracts_module_name_from_message(self) -> None: diff --git a/docs/running-on-jetson.md b/docs/running-on-jetson.md index 4d21bdcba..2cb0d8d03 100644 --- a/docs/running-on-jetson.md +++ b/docs/running-on-jetson.md @@ -242,6 +242,10 @@ WORKSPACE_DIR=$HOME/.modly/workspace \ > Optional: `export HF_TOKEN=hf_...` before launching to avoid HuggingFace rate-limits > on the one-time ~4 GB weight download. +> Started this way (no `MODLY_API_TOKEN`), the API is tokenless: no `X-Modly-Token` +> header is needed and it logs `API token disabled` once. Set `MODLY_API_TOKEN` to require +> that header on every request except `GET /health`. + Check it (from the Jetson, or from another machine using the Jetson's IP): ```bash diff --git a/electron/main/api-auth.test.ts b/electron/main/api-auth.test.ts new file mode 100644 index 000000000..8894f045d --- /dev/null +++ b/electron/main/api-auth.test.ts @@ -0,0 +1,100 @@ +import assert from 'node:assert/strict' +import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' + +async function load() { + return import(new URL('./api-auth.ts', import.meta.url).href) +} + +test('generateApiToken: 64 hex characters, different every time', async () => { + const { generateApiToken } = await load() + const a = generateApiToken() + assert.match(a, /^[0-9a-f]{64}$/) + assert.notEqual(a, generateApiToken()) +}) + +test('getApiToken: one token per launch, sent in X-Modly-Token', async () => { + const { getApiToken, apiAuthHeaders } = await load() + const token = getApiToken() + assert.match(token, /^[0-9a-f]{64}$/) + assert.equal(getApiToken(), token) + assert.deepEqual(apiAuthHeaders(), { 'X-Modly-Token': token }) +}) + +test('the token is not put on process.env', async () => { + const { getApiToken } = await load() + const token = getApiToken() + assert.ok(!Object.values(process.env).includes(token)) +}) + +test('apiClient adds the token to every request', async () => { + const { apiClient, getApiToken } = await load() + let sent: Record = {} + await apiClient.get('http://127.0.0.1:8765/model/all', { + adapter: async (config: { headers: { toJSON(): Record } }) => { + sent = config.headers.toJSON() + return { data: null, status: 200, statusText: 'OK', headers: {}, config } + }, + }) + assert.equal(sent['X-Modly-Token'], getApiToken()) +}) + +test('allowedOrigins: the dev server origin, whatever its port, plus file pages', async () => { + const { allowedOrigins } = await load() + assert.deepEqual(allowedOrigins('http://localhost:5174/'), ['http://localhost:5174', 'file://', 'null']) + assert.deepEqual(allowedOrigins('http://127.0.0.1:5173/index.html?x=1'), ['http://127.0.0.1:5173', 'file://', 'null']) + assert.deepEqual(allowedOrigins(undefined), ['file://', 'null']) + assert.deepEqual(allowedOrigins(''), ['file://', 'null']) + assert.deepEqual(allowedOrigins('not a url'), ['file://', 'null']) +}) + +test('isApiRequest: only the backend origin on its current port', async () => { + const { isApiRequest } = await load() + assert.equal(isApiRequest('http://127.0.0.1:8765/health', 8765), true) + assert.equal(isApiRequest('http://localhost:8765/generate/status/1', 8765), true) + assert.equal(isApiRequest('http://127.0.0.1:8766/model/all', 8766), true) + // The port moved: the old one no longer gets the token. + assert.equal(isApiRequest('http://127.0.0.1:8765/model/all', 8766), false) + // The Vite dev server, other hosts and schemes. + assert.equal(isApiRequest('http://localhost:5173/src/main.tsx', 8765), false) + assert.equal(isApiRequest('http://127.0.0.1/model/all', 8765), false) + assert.equal(isApiRequest('http://example.com:8765/model/all', 8765), false) + assert.equal(isApiRequest('https://127.0.0.1:8765/model/all', 8765), false) + assert.equal(isApiRequest('http://127.0.0.1.evil.test:8765/', 8765), false) + assert.equal(isApiRequest('garbage', 8765), false) +}) + +test('writeTokenFile / removeTokenFile', async () => { + const { writeTokenFile, removeTokenFile, TOKEN_FILE } = await load() + const dir = mkdtempSync(join(tmpdir(), 'modly-api-token-')) + try { + const file = join(dir, TOKEN_FILE) + assert.equal(TOKEN_FILE, 'api-token') + // A leftover from an earlier launch, readable by everyone. + writeFileSync(file, 'old', { mode: 0o644 }) + writeTokenFile(dir, 'a'.repeat(64)) + assert.equal(readFileSync(file, 'utf8'), 'a'.repeat(64)) + if (process.platform !== 'win32') assert.equal(statSync(file).mode & 0o777, 0o600) + removeTokenFile(dir) + assert.equal(existsSync(file), false) + removeTokenFile(dir) // already gone: no throw + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) + +test('isAppNavigation: the window stays on its own pages', async () => { + const { isAppNavigation } = await load() + // production: file pages only + assert.equal(isAppNavigation('file:///C:/app/out/renderer/index.html'), true) + assert.equal(isAppNavigation('https://example.test/'), false) + assert.equal(isAppNavigation('http://127.0.0.1:8765/workspace/x.glb'), false) + // dev: the Vite origin only + const dev = 'http://localhost:5174/' + assert.equal(isAppNavigation('http://localhost:5174/#/settings', dev), true) + assert.equal(isAppNavigation('http://localhost:5173/', dev), false) + assert.equal(isAppNavigation('file:///etc/passwd', dev), false) + assert.equal(isAppNavigation('not a url', dev), false) +}) diff --git a/electron/main/api-auth.ts b/electron/main/api-auth.ts new file mode 100644 index 000000000..d9bddc0da --- /dev/null +++ b/electron/main/api-auth.ts @@ -0,0 +1,107 @@ +// Locks the local FastAPI backend to the Modly app. +// +// The backend listens on 127.0.0.1, which every web page in the user's browser +// can reach too. A secret made fresh at each launch proves a request comes from +// Modly: the backend gets it through its environment, the app sends it in a +// header, and tools outside the app (MCP server, modly-cli) read it from +// /api-token next to the api-port file. +// +// The token lives in this module only. It must never be put on process.env: +// child processes (Python setup, extension runners) inherit a copy of it. + +import { randomBytes } from 'crypto' +import { chmodSync, rmSync, writeFileSync } from 'fs' +import { join } from 'path' +import axios from 'axios' + +export const API_TOKEN_HEADER = 'X-Modly-Token' +export const TOKEN_FILE = 'api-token' + +/** 32 random bytes as 64 hex characters. */ +export function generateApiToken(): string { + return randomBytes(32).toString('hex') +} + +let token: string | null = null + +/** This launch's token, made on first use. */ +export function getApiToken(): string { + token ??= generateApiToken() + return token +} + +export function apiAuthHeaders(): Record { + return { [API_TOKEN_HEADER]: getApiToken() } +} + +/** + * Axios for main-process calls to the backend: adds the token header. Use plain + * axios for anything else (GitHub, Hugging Face) so the token never leaves. + */ +export const apiClient = axios.create() +apiClient.interceptors.request.use((config) => { + config.headers.set(API_TOKEN_HEADER, getApiToken()) + return config +}) + +/** + * Origins the backend accepts in CORS. Production pages are loaded with + * loadFile, and Chromium sends either "file://" or "null" as their origin; in + * dev the renderer is served by Vite, whose port may move off 5173. + */ +export function allowedOrigins(rendererUrl?: string): string[] { + const origins: string[] = [] + if (rendererUrl) { + try { + const { origin } = new URL(rendererUrl) + if (origin && origin !== 'null') origins.push(origin) + } catch { /* not a URL: nothing to allow */ } + } + origins.push('file://', 'null') + return origins +} + +/** + * Whether the app window may navigate to `url`: only its own pages (the Vite + * dev server in dev, file:// in production). Any other page would receive the + * API token from the request hook, so it opens in the system browser instead. + */ +export function isAppNavigation(url: string, rendererUrl?: string): boolean { + try { + const target = new URL(url) + if (target.protocol === 'file:') return !rendererUrl + if (!rendererUrl) return false + return target.origin === new URL(rendererUrl).origin + } catch { + return false + } +} + +const API_HOSTS = new Set(['127.0.0.1', 'localhost']) + +/** Whether `url` targets the backend listening on `port` (and so gets the token). */ +export function isApiRequest(url: string, port: number): boolean { + try { + const u = new URL(url) + return u.protocol === 'http:' && API_HOSTS.has(u.hostname) && u.port === String(port) + } catch { + return false + } +} + +/** + * Writes /api-token, readable by the user only where the OS supports it. + * Removed first so a leftover file with wider permissions is not reused. + */ +export function writeTokenFile(dir: string, value: string): void { + const file = join(dir, TOKEN_FILE) + try { + rmSync(file, { force: true }) + writeFileSync(file, value, { mode: 0o600 }) + chmodSync(file, 0o600) + } catch { /* best effort, like the port file */ } +} + +export function removeTokenFile(dir: string): void { + try { rmSync(join(dir, TOKEN_FILE), { force: true }) } catch { /* best effort */ } +} diff --git a/electron/main/index.ts b/electron/main/index.ts index 24c686420..56f0bb40f 100644 --- a/electron/main/index.ts +++ b/electron/main/index.ts @@ -9,6 +9,7 @@ import { syncBuiltinExtensions } from './builtin-sync' import { reconcileInterruptedExtensionInstalls } from './extension-install-recovery' import { getSettings } from './settings-store' import { handleThumbnailProtocol, registerThumbnailScheme } from './asset-thumbnail-protocol' +import { API_TOKEN_HEADER, getApiToken, isApiRequest, isAppNavigation } from './api-auth' let mainWindow: BrowserWindow | null = null let pythonBridge: PythonBridge | null = null @@ -68,6 +69,17 @@ function createWindow(): void { return { action: 'deny' } }) + // The window only ever shows Modly's own pages: any other page loaded here + // would get the API token from the request hook. Links open in the browser. + const rendererUrl = is.dev ? process.env['ELECTRON_RENDERER_URL'] : undefined + const keepOnApp = (event: Electron.Event, url: string) => { + if (isAppNavigation(url, rendererUrl)) return + event.preventDefault() + if (/^https?:\/\//i.test(url)) void shell.openExternal(url) + } + mainWindow.webContents.on('will-navigate', keepOnApp) + mainWindow.webContents.on('will-redirect', keepOnApp) + if (is.dev && process.env['ELECTRON_RENDERER_URL']) { mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL']) mainWindow.webContents.openDevTools() @@ -123,6 +135,23 @@ app.whenReady().then(async () => { setupIpcHandlers(pythonBridge, () => mainWindow) initAutoUpdater(() => mainWindow) + // The backend rejects requests without this launch's token. Adding it here + // covers every request of the session (axios, fetch, SSE, three.js loaders, + // downloads) with no change in the renderer. The filter has no port, which + // matches any port; the backend's port is checked per request because it is + // only settled once the bridge starts and may change on a restart. + // A session takes a single onBeforeSendHeaders listener: this is the only one. + session.defaultSession.webRequest.onBeforeSendHeaders( + { urls: ['http://127.0.0.1/*', 'http://localhost/*'] }, + (details, callback) => { + const port = pythonBridge?.getPort() + if (port !== undefined && isApiRequest(details.url, port)) { + details.requestHeaders[API_TOKEN_HEADER] = getApiToken() + } + callback({ requestHeaders: details.requestHeaders }) + }, + ) + createWindow() app.on('activate', () => { diff --git a/electron/main/ipc-handlers.ts b/electron/main/ipc-handlers.ts index c14132b1a..8e535bbc7 100644 --- a/electron/main/ipc-handlers.ts +++ b/electron/main/ipc-handlers.ts @@ -9,6 +9,7 @@ import * as tar from 'tar' import * as os from 'os' import { promisify } from 'util' import { PythonBridge, apiBaseUrl } from './python-bridge' +import { apiClient } from './api-auth' import { isModelDownloaded, listDownloadedModels, @@ -221,7 +222,7 @@ export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGe async function unloadForRemoval(modelIds: string[]) { for (const id of modelIds) { try { - const response = await axios.post( + const response = await apiClient.post( `${apiBaseUrl()}/model/unload/${encodeURIComponent(id)}`, {}, { timeout: 40_000 }, ) if (response.data?.unloaded !== true) throw new Error('Model unload was not confirmed; weights were preserved') @@ -235,7 +236,7 @@ export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGe async function unloadExtensionForRemoval(extensionId: string) { let modelIds: string[] try { - const { data } = await axios.get<{ id: string }[]>(`${apiBaseUrl()}/model/all`, { timeout: 10_000 }) + const { data } = await apiClient.get<{ id: string }[]>(`${apiBaseUrl()}/model/all`, { timeout: 10_000 }) modelIds = data.map((model) => model.id).filter((id) => id.startsWith(`${extensionId}/`)) } catch (err) { if (backendUnreachable(err)) return @@ -428,7 +429,7 @@ export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGe ipcMain.handle('model:unloadAll', async (): Promise<{ success: boolean; error?: string }> => { try { - await axios.post(`${apiBaseUrl()}/model/unload-all`, {}, { timeout: 10_000 }) + await apiClient.post(`${apiBaseUrl()}/model/unload-all`, {}, { timeout: 10_000 }) return { success: true } } catch (err) { return { success: false, error: String(err) } @@ -781,7 +782,7 @@ export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGe const targetId = active?.currentTargetId if (!active || !targetId) return { success: false, error: 'No active download target' } active.stopRequested = 'pause' - await axios.post(`${apiBaseUrl()}/model/hf-download/pause`, null, { + await apiClient.post(`${apiBaseUrl()}/model/hf-download/pause`, null, { params: { model_id: targetId }, timeout: 5000, }) @@ -796,7 +797,7 @@ export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGe const active = activeDownloads.get(modelId) if (active) active.stopRequested = 'cancel' if (active?.currentTargetId) { - await axios.post(`${apiBaseUrl()}/model/hf-download/cancel`, null, { + await apiClient.post(`${apiBaseUrl()}/model/hf-download/cancel`, null, { params: { model_id: active.currentTargetId }, timeout: 5000, }) @@ -848,7 +849,7 @@ export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGe if (result.canceled || !result.filePath) return { success: false } try { - const response = await axios.get( + const response = await apiClient.get( `${apiBaseUrl()}/export/${format}?path=${encodeURIComponent(meshPath)}`, { responseType: 'arraybuffer' } ) @@ -964,7 +965,7 @@ export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGe // subprocesses spawned by ExtensionProcess._build_env() pick it up // without requiring a full app restart. try { - await axios.post(`${apiBaseUrl()}/settings/hf-token`, { token: hfToken }, { timeout: 3000 }) + await apiClient.post(`${apiBaseUrl()}/settings/hf-token`, { token: hfToken }, { timeout: 3000 }) } catch { /* FastAPI may not be running yet — ignore */ } } return { ...getSettings(app.getPath('userData')), hfToken: getHfToken() } @@ -1361,7 +1362,7 @@ export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGe let payload: unknown try { - const response = await axios.post( + const response = await apiClient.post( `${apiBaseUrl()}/extensions/reload`, validationCapability ? { validationCapability } : {}, { timeout: 10_000 }, @@ -1384,7 +1385,7 @@ export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGe let payload: unknown try { - const response = await axios.post( + const response = await apiClient.post( `${apiBaseUrl()}/extensions/reload`, {}, { timeout: 10_000 }, @@ -1947,7 +1948,7 @@ export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGe } // Hot-reload Python so it stops using the deleted model extension try { - await axios.post(`${apiBaseUrl()}/extensions/reload`, {}, { timeout: 10_000 }) + await apiClient.post(`${apiBaseUrl()}/extensions/reload`, {}, { timeout: 10_000 }) } catch { /* ignore if Python is not running */ } return { success: true } } catch (err) { @@ -2180,7 +2181,7 @@ export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGe ipcMain.handle('extensions:reload', async () => { terminateAllProcessRunners() try { - const res = await axios.post(`${apiBaseUrl()}/extensions/reload`, {}, { timeout: 10_000 }) + const res = await apiClient.post(`${apiBaseUrl()}/extensions/reload`, {}, { timeout: 10_000 }) return { success: true, errors: (res.data as { errors?: Record }).errors ?? {} } } catch (err) { return { success: false, error: String(err) } @@ -2251,7 +2252,7 @@ export function setupIpcHandlers(pythonBridge: PythonBridge, getWindow: WindowGe if (patch.modelsDir !== undefined && weightOperations.busy) { throw new Error('Cannot change model storage while model weights are busy') } - await axios.post(`${apiBaseUrl()}/settings/paths`, { + await apiClient.post(`${apiBaseUrl()}/settings/paths`, { models_dir: patch.modelsDir, workspace_dir: patch.workspaceDir, extensions_dir: patch.extensionsDir, diff --git a/electron/main/model-downloader.ts b/electron/main/model-downloader.ts index d48ee4139..bc45236de 100644 --- a/electron/main/model-downloader.ts +++ b/electron/main/model-downloader.ts @@ -6,6 +6,7 @@ import { existsSync, readdirSync, statSync, readFileSync } from 'fs' import { join } from 'path' import { getHfToken } from './hf-token' import { apiBaseUrl } from './python-bridge' +import { apiAuthHeaders } from './api-auth' import type { ModelSource } from './model-sources' export interface DownloadProgress { @@ -133,7 +134,9 @@ export async function downloadModelFromHF( // python-bridge pipes that into runtime.log, and `log:readAll` hands that file // to the user for bug reports. The token used to ride all the way there. const hfToken = getHfToken() // decrypted cache — settings.json holds the ciphertext - const res = await net.fetch(url, hfToken ? { headers: { 'X-HF-Token': hfToken } } : undefined) + const headers: Record = apiAuthHeaders() + if (hfToken) headers['X-HF-Token'] = hfToken + const res = await net.fetch(url, { headers }) if (!res.ok) throw new Error(`HuggingFace download failed: HTTP ${res.status}`) await consumeDownloadStream(res, onProgress) } @@ -145,7 +148,7 @@ export async function downloadModelSourcesFromHF( onProgress: ProgressCallback, ): Promise { const { net } = require('electron') - const headers: Record = { 'Content-Type': 'application/json' } + const headers: Record = { 'Content-Type': 'application/json', ...apiAuthHeaders() } const hfToken = getHfToken() if (hfToken) headers.Authorization = `Bearer ${hfToken}` const url = `${pythonApiUrl()}/model/hf-download-sources?model_id=${encodeURIComponent(modelId)}` diff --git a/electron/main/model-weight-ipc.test.mjs b/electron/main/model-weight-ipc.test.mjs index 460df7e6c..b9140083f 100644 --- a/electron/main/model-weight-ipc.test.mjs +++ b/electron/main/model-weight-ipc.test.mjs @@ -48,13 +48,16 @@ function fixture(t) { }, } const stub = new Proxy({}, { get: () => () => {} }) + const axios = { + post: (...args) => hooks.unload(...args), + get: (...args) => hooks.listModels(...args), + isAxiosError: (err) => Boolean(err?.isAxiosError), + } const deps = (name) => { if (name === 'electron') return { ipcMain: { handle: (id, fn) => handlers.set(id, fn), on: () => {} }, app: { getPath: () => root, on: () => {} } } - if (name === 'axios') return { - post: (...args) => hooks.unload(...args), - get: (...args) => hooks.listModels(...args), - isAxiosError: (err) => Boolean(err?.isAxiosError), - } + if (name === 'axios') return axios + // Backend calls go through the token-adding client. + if (name === './api-auth') return { apiClient: axios } if (name === './model-sources') return realSources if (name === './model-download-plan') return realPlan if (name === './extension-path-guard') return realGuard diff --git a/electron/main/python-bridge.ts b/electron/main/python-bridge.ts index c53055837..91eed1cfe 100644 --- a/electron/main/python-bridge.ts +++ b/electron/main/python-bridge.ts @@ -12,6 +12,7 @@ import { DEFAULT_API_PORT, findPortHolder, isModlyBackend, isPortFree, killListener, osAssignedPort, pickPort, removePortFile, writePortFile, } from './api-port' +import { allowedOrigins, getApiToken, removeTokenFile, writeTokenFile } from './api-auth' const API_HOST = '127.0.0.1' // 8765 unless another program holds it; chosen again at every start. @@ -75,6 +76,9 @@ export class PythonBridge { logger.python(msg) } + // Tools outside the app need the token as soon as the backend answers. + writeTokenFile(app.getPath('userData'), getApiToken()) + try { this.process = spawn(pythonExecutable, ['-m', 'uvicorn', 'main:app', '--host', API_HOST, '--port', String(apiPort)], { cwd: apiDir, @@ -100,6 +104,10 @@ export class PythonBridge { HF_TOKEN: this.resolveHfToken(), // The port is not fixed: the API and the extensions it runs call back here. MODLY_API_URL: apiBaseUrl(), + // Every request but /health must carry this token (see api-auth.ts), + // and CORS only lets the app's own pages in. + MODLY_API_TOKEN: getApiToken(), + MODLY_ALLOWED_ORIGINS: allowedOrigins(process.env['ELECTRON_RENDERER_URL']).join(','), }, // On Unix, put the bridge in its own process group so every subprocess // it spawns (extension runners, etc.) inherits that group. On shutdown @@ -171,6 +179,7 @@ export class PythonBridge { this.process = null this.ready = false removePortFile(app.getPath('userData')) + removeTokenFile(app.getPath('userData')) if (process.platform === 'win32') { const { execSync } = require('child_process') try { execSync(`taskkill /PID ${proc.pid} /T /F`) } catch {} @@ -216,6 +225,7 @@ export class PythonBridge { for (let i = 0; i < maxRetries; i++) { if (!this.process) throw await this.startupError() try { + // /health is open, and no token here: it may be some other program. await axios.get(`${apiBaseUrl()}/health`, { timeout: 2000 }) this.ready = true writePortFile(app.getPath('userData'), apiPort) diff --git a/package.json b/package.json index 063a2f9fd..4a6d613a8 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "prepare-resources": "node scripts/download-python-embed.js", "test": "npm run test:py && npm run test:node", "test:py": "node scripts/run-pytests.mjs", - "test:node": "node --test --experimental-strip-types --experimental-loader ./scripts/node-ts-extensionless-loader.mjs src/shared/types/assetLibrary.test.ts src/areas/generate/assetLibraryProjection.test.ts src/areas/generate/assetLibraryService.test.ts src/areas/generate/assetLibraryUi.test.ts src/areas/library/libraryView.test.ts src/areas/library/gridWindow.test.ts src/areas/generate/orcaSlicerLink.test.ts src/shared/utils/agentStream.test.ts src/shared/thumbnails/assetThumbnailQueue.test.ts src/shared/thumbnails/assetThumbnailStore.test.ts src/shared/components/agent/clientTools.test.ts src/shared/components/agent/agentContext.test.ts src/shared/utils/ollamaHealth.test.ts src/shared/utils/notification.test.ts src/shared/utils/agentConversations.test.ts electron/main/artifact-registry-service.test.ts electron/main/asset-thumbnail-cache.test.ts electron/main/extension-path-guard.test.ts electron/main/storage-directory-guard.test.ts electron/main/storage-ownership.test.ts electron/main/startup-error.test.ts electron/main/api-port.test.ts electron/main/agent-conversations.test.ts electron/main/gpu-memory.test.ts electron/preload/artifact-registry-preload.test.ts src/shared/stores/meshHistory.test.ts src/areas/generate/meshEditPanel.test.ts src/areas/generate/sculpt/SculptMesh.test.ts src/areas/generate/sculpt/SculptMesh.perf.test.ts src/areas/generate/sculpt/sculptLogic.test.ts src/shared/pages/pageRegistry.test.ts src/shared/pages/startPage.test.ts src/areas/home/recents.test.ts src/areas/workflows/workflowRunRecord.test.ts src/areas/queue/queueModel.test.ts electron/main/workspace-images.test.ts src/areas/image-studio/imageStudioStore.test.ts src/shared/utils/imageInput.test.ts && node --test electron/main/*.test.mjs src/**/*.test.mjs", + "test:node": "node --test --experimental-strip-types --experimental-loader ./scripts/node-ts-extensionless-loader.mjs src/shared/types/assetLibrary.test.ts src/areas/generate/assetLibraryProjection.test.ts src/areas/generate/assetLibraryService.test.ts src/areas/generate/assetLibraryUi.test.ts src/areas/library/libraryView.test.ts src/areas/library/gridWindow.test.ts src/areas/generate/orcaSlicerLink.test.ts src/shared/utils/agentStream.test.ts src/shared/thumbnails/assetThumbnailQueue.test.ts src/shared/thumbnails/assetThumbnailStore.test.ts src/shared/components/agent/clientTools.test.ts src/shared/components/agent/agentContext.test.ts src/shared/utils/ollamaHealth.test.ts src/shared/utils/notification.test.ts src/shared/utils/agentConversations.test.ts electron/main/artifact-registry-service.test.ts electron/main/asset-thumbnail-cache.test.ts electron/main/extension-path-guard.test.ts electron/main/storage-directory-guard.test.ts electron/main/storage-ownership.test.ts electron/main/startup-error.test.ts electron/main/api-port.test.ts electron/main/api-auth.test.ts electron/main/agent-conversations.test.ts electron/main/gpu-memory.test.ts electron/preload/artifact-registry-preload.test.ts src/shared/stores/meshHistory.test.ts src/areas/generate/meshEditPanel.test.ts src/areas/generate/sculpt/SculptMesh.test.ts src/areas/generate/sculpt/SculptMesh.perf.test.ts src/areas/generate/sculpt/sculptLogic.test.ts src/shared/pages/pageRegistry.test.ts src/shared/pages/startPage.test.ts src/areas/home/recents.test.ts src/areas/workflows/workflowRunRecord.test.ts src/areas/queue/queueModel.test.ts electron/main/workspace-images.test.ts src/areas/image-studio/imageStudioStore.test.ts src/shared/utils/imageInput.test.ts && node --test electron/main/*.test.mjs src/**/*.test.mjs", "package": "cross-env CSC_IDENTITY_AUTO_DISCOVERY=false npm run build && npm run prepare-resources && electron-builder", "package:mac": "cross-env CSC_IDENTITY_AUTO_DISCOVERY=false npm run build && npm run prepare-resources && electron-builder --mac --arm64", "lint": "eslint ." diff --git a/src/areas/generate/GeneratePage.tsx b/src/areas/generate/GeneratePage.tsx index b546ef3a2..f7fd971b2 100644 --- a/src/areas/generate/GeneratePage.tsx +++ b/src/areas/generate/GeneratePage.tsx @@ -1,3 +1,4 @@ +import axios from 'axios' import { useState, useRef, useCallback, useEffect, useMemo } from 'react' import type { ReactNode } from 'react' import { useAppStore, DEFAULT_LIGHT_SETTINGS } from '@shared/stores/appStore' @@ -15,7 +16,7 @@ import { commitSculpt, useSculptStore } from './sculpt/sculptStore' import { sculptKeyAction } from './sculpt/sculptLogic' import { getDefaultAssetLibraryService } from './assetLibraryService' import { requestLibraryThumbnails } from '@shared/thumbnails/assetThumbnailService' -import { buildOrcaSlicerDeepLink, canOpenInOrcaSlicer } from './orcaSlicerLink' +import { SLICER_FORMAT, canOpenInOrcaSlicer, orcaSlicerDeepLink, orcaSlicerSourcePath } from './orcaSlicerLink' import type { ProjectedAssetLibraryEntry } from './assetLibraryProjection' import { useNavStore } from '@shared/stores/navStore' import { @@ -852,7 +853,13 @@ export default function GeneratePage(): JSX.Element { const outputUrl = await committedMeshUrl() if (!outputUrl) return try { - const link = buildOrcaSlicerDeepLink(apiUrl, outputUrl) + const sourcePath = orcaSlicerSourcePath(outputUrl) + if (!sourcePath) throw new Error('This model cannot be opened in OrcaSlicer.') + // OrcaSlicer fetches the mesh without the API token: the backend signs the URL. + const { data } = await axios.get<{ url_path: string }>(`${apiUrl}/export/slicer-link`, { + params: { fmt: SLICER_FORMAT, path: sourcePath }, + }) + const link = orcaSlicerDeepLink(apiUrl, data.url_path) const result = await window.electron.slicer.open(link) if (!result.success) { // Deliberately not "make sure it is installed": the main process cannot diff --git a/src/areas/generate/orcaSlicerLink.test.ts b/src/areas/generate/orcaSlicerLink.test.ts index 514618eb2..98594a959 100644 --- a/src/areas/generate/orcaSlicerLink.test.ts +++ b/src/areas/generate/orcaSlicerLink.test.ts @@ -3,39 +3,41 @@ import test from 'node:test' import { SLICER_FORMAT, - buildOrcaSlicerDeepLink, canOpenInOrcaSlicer, - encodeWorkspacePathToken, + orcaSlicerDeepLink, + orcaSlicerSourcePath, } from './orcaSlicerLink.ts' +// A url_path as returned by GET /export/slicer-link (token = signed source path). +const URL_PATH = '/export/slicer/stl/V29ya2Zsb3dzL2hlcm8uZ2xi.c2lnbmF0dXJl/model.stl' + test('builds an orcaslicer://open deeplink whose file= is a percent-encoded, query-less URL ending in model.stl', () => { - const link = buildOrcaSlicerDeepLink('http://localhost:8765', '/workspace/Workflows/checkpoints/hero.glb') + const link = orcaSlicerDeepLink('http://localhost:8765', URL_PATH) assert.ok(link.startsWith('orcaslicer://open?file=')) const modelUrl = decodeURIComponent(link.slice('orcaslicer://open?file='.length)) // OrcaSlicer derives the import format from the URL's final path segment, so // it must end in the real extension and carry no query string. assert.ok(!modelUrl.includes('?'), 'model URL must not contain a query string') assert.ok(modelUrl.endsWith('/model.stl'), 'model URL must end in model.stl') - assert.equal( - modelUrl, - `http://localhost:8765/export/slicer/stl/${encodeWorkspacePathToken('Workflows/checkpoints/hero.glb')}/model.stl`, - ) + assert.equal(modelUrl, `http://localhost:8765${URL_PATH}`) }) -test('token round-trips a workspace path through url-safe base64 (matches the API decode)', () => { - const path = 'Workflows/checkpoints/hero model (v2).glb' - const token = encodeWorkspacePathToken(path) - assert.ok(!/[+/=]/.test(token), 'token must be url-safe with no padding') - // Decode the way the Python API does: restore padding, then urlsafe-decode. - const padded = token + '='.repeat((4 - (token.length % 4)) % 4) - const decoded = Buffer.from(padded.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf-8') - assert.equal(decoded, path) +test('strips a trailing slash from the api origin and tolerates a path without a leading slash', () => { + const a = decodeURIComponent(orcaSlicerDeepLink('http://localhost:8765/', URL_PATH).slice('orcaslicer://open?file='.length)) + const b = decodeURIComponent(orcaSlicerDeepLink('http://localhost:8765', URL_PATH.slice(1)).slice('orcaslicer://open?file='.length)) + assert.equal(a, `http://localhost:8765${URL_PATH}`) + assert.equal(b, `http://localhost:8765${URL_PATH}`) }) -test('strips a trailing slash from the api origin', () => { - const link = buildOrcaSlicerDeepLink('http://localhost:8765/', '/workspace/a.glb') - const modelUrl = decodeURIComponent(link.slice('orcaslicer://open?file='.length)) - assert.equal(modelUrl, `http://localhost:8765/export/slicer/stl/${encodeWorkspacePathToken('a.glb')}/model.stl`) +test('orcaSlicerSourcePath: workspace meshes give their workspace-relative path', () => { + assert.equal(orcaSlicerSourcePath('/workspace/Workflows/checkpoints/hero.glb'), 'Workflows/checkpoints/hero.glb') + assert.equal(orcaSlicerSourcePath('/workspace/Foo/scan.splat'), undefined) + assert.equal(orcaSlicerSourcePath(undefined), undefined) +}) + +test('orcaSlicerSourcePath: an imported mesh gives its decoded absolute path', () => { + const absolute = String.raw`C:\Users\Me\Downloads\mage_v2.glb` + assert.equal(orcaSlicerSourcePath(`/optimize/serve-file?path=${encodeURIComponent(absolute)}`), absolute) }) test('canOpenInOrcaSlicer accepts sliceable workspace meshes and rejects splats and empty', () => { @@ -60,23 +62,6 @@ test('canOpenInOrcaSlicer accepts an imported mesh served from outside the works assert.equal(canOpenInOrcaSlicer('/optimize/serve-file?path=%2Ftmp%2Fscan.splat'), false) }) -test('deeplink for an imported mesh tokenises the decoded absolute path', () => { - const absolute = String.raw`C:\Users\Me\Downloads\mage_v2.glb` - const outputUrl = `/optimize/serve-file?path=${encodeURIComponent(absolute)}` - const modelUrl = decodeURIComponent( - buildOrcaSlicerDeepLink('http://localhost:8765', outputUrl).slice('orcaslicer://open?file='.length), - ) - assert.equal( - modelUrl, - `http://localhost:8765/export/slicer/stl/${encodeWorkspacePathToken(absolute)}/model.stl`, - ) - assert.ok(!modelUrl.includes('?'), 'model URL must not contain a query string') -}) - -test('buildOrcaSlicerDeepLink refuses an output it cannot slice', () => { - assert.throws(() => buildOrcaSlicerDeepLink('http://localhost:8765', '/workspace/Foo/scan.splat')) -}) - test('SLICER_FORMAT is a format OrcaSlicer can import', () => { assert.equal(SLICER_FORMAT, 'stl') }) diff --git a/src/areas/generate/orcaSlicerLink.ts b/src/areas/generate/orcaSlicerLink.ts index d5a76c9b1..d4777e86b 100644 --- a/src/areas/generate/orcaSlicerLink.ts +++ b/src/areas/generate/orcaSlicerLink.ts @@ -7,6 +7,12 @@ // query string, and the whole thing must be percent-encoded. OrcaSlicer cannot // import GLB, so we point at the backend's slicer-export route which converts to // STL on the fly. +// +// OrcaSlicer is an external app: it fetches that URL without the API token, so +// the URL carries a signature of the source path instead. Only the backend can +// sign (the renderer never sees the token): ask `GET /export/slicer-link` for +// the `url_path` of `orcaSlicerSourcePath(outputUrl)`, then build the deeplink +// with `orcaSlicerDeepLink`. Links stop working when Modly restarts. /** Format handed to OrcaSlicer. STL is universal and OrcaSlicer auto-repairs it. */ export const SLICER_FORMAT = 'stl' @@ -20,14 +26,6 @@ const SERVE_FILE_PREFIX = '/optimize/serve-file?path=' */ const SLICEABLE_SOURCE = /\.(glb|gltf|obj|stl)$/i -/** URL-safe base64 (no padding) of a UTF-8 string — matches the API's token decode. */ -export function encodeWorkspacePathToken(workspacePath: string): string { - const bytes = new TextEncoder().encode(workspacePath) - let binary = '' - for (const b of bytes) binary += String.fromCharCode(b) - return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') -} - /** * The source path the slicer route should convert, or `undefined` when the * output cannot be sliced. @@ -37,7 +35,7 @@ export function encodeWorkspacePathToken(workspacePath: string): string { * from elsewhere on disk). Both are sliceable — the API accepts the absolute * path of an import because it recorded that the user picked it themselves. */ -function sliceableSourcePath(outputUrl: string | undefined): string | undefined { +export function orcaSlicerSourcePath(outputUrl: string | undefined): string | undefined { if (!outputUrl) return undefined if (outputUrl.startsWith('/workspace/')) { @@ -59,21 +57,18 @@ function sliceableSourcePath(outputUrl: string | undefined): string | undefined * user-selected import. */ export function canOpenInOrcaSlicer(outputUrl: string | undefined): boolean { - return sliceableSourcePath(outputUrl) !== undefined + return orcaSlicerSourcePath(outputUrl) !== undefined } /** - * Build the `orcaslicer://open?file=...` deeplink for a generated mesh. + * The `orcaslicer://open?file=...` deeplink for a signed slicer URL. * - * @param apiUrl Modly backend origin, e.g. `http://localhost:8765` - * @param outputUrl workspace or serve-file URL of the mesh - * @throws if `outputUrl` is not sliceable — guard with {@link canOpenInOrcaSlicer} + * @param apiUrl Modly backend origin, e.g. `http://localhost:8765` + * @param urlPath `url_path` returned by `GET /export/slicer-link` + * (`/export/slicer/stl//model.stl`) */ -export function buildOrcaSlicerDeepLink(apiUrl: string, outputUrl: string): string { - const sourcePath = sliceableSourcePath(outputUrl) - if (!sourcePath) throw new Error(`Not sliceable: ${outputUrl}`) - const token = encodeWorkspacePathToken(sourcePath) +export function orcaSlicerDeepLink(apiUrl: string, urlPath: string): string { const base = apiUrl.replace(/\/+$/, '') - const modelUrl = `${base}/export/slicer/${SLICER_FORMAT}/${token}/model.${SLICER_FORMAT}` - return `orcaslicer://open?file=${encodeURIComponent(modelUrl)}` + const path = urlPath.startsWith('/') ? urlPath : `/${urlPath}` + return `orcaslicer://open?file=${encodeURIComponent(`${base}${path}`)}` } diff --git a/tools/modly-cli/SKILL.md b/tools/modly-cli/SKILL.md index f287b7a17..d02e2b9fe 100644 --- a/tools/modly-cli/SKILL.md +++ b/tools/modly-cli/SKILL.md @@ -14,7 +14,7 @@ metadata: ## Overview -Modly exposes a local API at `http://127.0.0.1:8765` while the official desktop app is running. If another program holds that port, the app uses the next free one and writes it to `api-port` in its user data folder (`%APPDATA%/Modly`, `~/Library/Application Support/Modly`, `~/.config/Modly`); the CLI reads it, and `MODLY_API_URL` overrides both. The stdlib-only CLI at `tools/modly-cli/agent.py` is an agent helper over the canonical automation contract: +Modly exposes a local API at `http://127.0.0.1:8765` while the official desktop app is running. If another program holds that port, the app uses the next free one and writes it to `api-port` in its user data folder (`%APPDATA%/Modly`, `~/Library/Application Support/Modly`, `~/.config/Modly`); the CLI reads it, and `MODLY_API_URL` overrides both. The app also locks its API with a per-launch token, written to `api-token` in the same folder; the CLI sends it as `X-Modly-Token` on every request (falling back to `MODLY_API_TOKEN`), so raw `curl` calls to the app's API need that header too. A backend started with `dev serve-api`/`dev ensure-server --start` is tokenless. The stdlib-only CLI at `tools/modly-cli/agent.py` is an agent helper over the canonical automation contract: - `health` - `model` diff --git a/tools/modly-cli/agent.py b/tools/modly-cli/agent.py index 8c329a3cd..61d17305d 100644 --- a/tools/modly-cli/agent.py +++ b/tools/modly-cli/agent.py @@ -61,6 +61,33 @@ def resolve_base_url() -> str: return "http://127.0.0.1:8765" +def resolve_api_token() -> str | None: + """The running app's API token from api-token (next to api-port), else + MODLY_API_TOKEN. None for a tokenless backend (e.g. `dev serve`). + + Read per request: the app writes a fresh token on every launch. + """ + try: + token = (_modly_user_data() / "api-token").read_text().strip() + if token: + return token + except OSError: + pass + return (os.environ.get("MODLY_API_TOKEN") or "").strip() or None + + +_LOOPBACK_HOSTS = {"127.0.0.1", "localhost", "::1"} + + +def _auth_headers(url: str) -> dict[str, str]: + """X-Modly-Token for the local app only: the token is never sent to a + remote --base-url (it would hand that host the user's local API).""" + if (urllib.parse.urlsplit(url).hostname or "").lower() not in _LOOPBACK_HOSTS: + return {} + token = resolve_api_token() + return {"X-Modly-Token": token} if token else {} + + DEFAULT_BASE_URL = resolve_base_url() DEFAULT_TIMEOUT_SECONDS = _int_env("MODLY_CLI_TIMEOUT", "MODLY_AGENT_TIMEOUT", 1800) DEFAULT_POLL_SECONDS = _float_env("MODLY_CLI_POLL_SECONDS", "MODLY_AGENT_POLL_SECONDS", 2.0) @@ -94,7 +121,7 @@ def _request_json( data: bytes | None = None, headers: dict[str, str] | None = None, ) -> Any: - req = urllib.request.Request(url, data=data, method=method, headers=headers or {}) + req = urllib.request.Request(url, data=data, method=method, headers={**_auth_headers(url), **(headers or {})}) try: with urllib.request.urlopen(req, timeout=timeout) as resp: raw = resp.read().decode("utf-8") @@ -112,7 +139,8 @@ def _request_json( def _download(url: str, dest: Path, *, timeout: float) -> int: dest.parent.mkdir(parents=True, exist_ok=True) try: - with urllib.request.urlopen(url, timeout=timeout) as resp, dest.open("wb") as fh: + req = urllib.request.Request(url, headers=_auth_headers(url)) + with urllib.request.urlopen(req, timeout=timeout) as resp, dest.open("wb") as fh: total = 0 while True: chunk = resp.read(1024 * 1024) @@ -361,6 +389,10 @@ def _resolve_serve_config(args: argparse.Namespace) -> tuple[Path, Path, dict[st # Like Electron's cleanPythonEnv(): variables from the caller's own Python setup (a conda env, # an activated venv) would point Modly's venv interpreter at foreign site-packages. env = {k: v for k, v in os.environ.items() if k not in _FOREIGN_PYTHON_ENV} + # A dev backend is tokenless (open API, no X-Modly-Token): never inherit the + # app's lock from a shell that runs inside a Modly extension. + env.pop("MODLY_API_TOKEN", None) + env.pop("MODLY_ALLOWED_ORIGINS", None) hf_token =getattr(args, "hf_token", None) or settings.get("hfToken") or os.environ.get("HF_TOKEN", "") env.update({ "PYTHONUNBUFFERED": "1", diff --git a/tools/modly-cli/test_agent.py b/tools/modly-cli/test_agent.py index 990bfbb0b..62a405e50 100644 --- a/tools/modly-cli/test_agent.py +++ b/tools/modly-cli/test_agent.py @@ -569,6 +569,75 @@ def test_resolve_serve_config_explicit_paths(self) -> None: self.assertTrue(cmd[0].endswith("python.exe")) self.assertIn("PYTHONUNBUFFERED", env) + def test_resolve_serve_config_starts_a_tokenless_backend(self) -> None: + with tempfile.TemporaryDirectory() as td: + api_dir = Path(td) / "api" + api_dir.mkdir() + (api_dir / "main.py").write_text("# api") + python = Path(td) / "python.exe" + python.write_text("# python") + args = SimpleNamespace(api_dir=str(api_dir), python=str(python), host="127.0.0.1", port=8765, + models_dir=None, workspace_dir=None, extensions_dir=None, model=None, hf_token=None) + locked = {"MODLY_API_TOKEN": "a" * 64, "MODLY_ALLOWED_ORIGINS": "null"} + with patch.dict(os.environ, locked), \ + patch.object(agent, "_load_modly_settings", return_value={}): + _api_dir, _python, env, _cmd, _url = agent._resolve_serve_config(args) + self.assertNotIn("MODLY_API_TOKEN", env) + self.assertNotIn("MODLY_ALLOWED_ORIGINS", env) + + +class ApiTokenTests(unittest.TestCase): + def _user_data(self, td: str, token: str | None) -> Path: + folder = Path(td) + if token is not None: + (folder / "api-token").write_text(token) + return folder + + def test_reads_the_token_the_app_wrote_next_to_api_port(self) -> None: + with tempfile.TemporaryDirectory() as td, \ + patch.object(agent, "_modly_user_data", return_value=self._user_data(td, "abc123\n")), \ + patch.dict(os.environ, {"MODLY_API_TOKEN": "from-env"}): + self.assertEqual(agent.resolve_api_token(), "abc123") + + def test_falls_back_to_env_then_none(self) -> None: + with tempfile.TemporaryDirectory() as td, \ + patch.object(agent, "_modly_user_data", return_value=self._user_data(td, None)): + with patch.dict(os.environ, {"MODLY_API_TOKEN": "from-env"}): + self.assertEqual(agent.resolve_api_token(), "from-env") + with patch.dict(os.environ, {}, clear=True): + self.assertIsNone(agent.resolve_api_token()) + self.assertEqual(agent._auth_headers("http://127.0.0.1:8765/health"), {}) + + def test_token_is_only_sent_to_the_local_app(self) -> None: + with patch.object(agent, "resolve_api_token", return_value="secret"): + self.assertEqual(agent._auth_headers("http://127.0.0.1:8765/x"), {"X-Modly-Token": "secret"}) + self.assertEqual(agent._auth_headers("http://localhost:8765/x"), {"X-Modly-Token": "secret"}) + self.assertEqual(agent._auth_headers("http://[::1]:8765/x"), {"X-Modly-Token": "secret"}) + self.assertEqual(agent._auth_headers("http://192.168.1.20:8765/x"), {}) + self.assertEqual(agent._auth_headers("https://modly.example.test/x"), {}) + + def test_requests_and_downloads_send_the_token_header(self) -> None: + seen: list[object] = [] + + class _Resp(io.BytesIO): + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def fake_urlopen(req, timeout): + seen.append(req) + return _Resp(b"{}") + + with tempfile.TemporaryDirectory() as td, \ + patch.object(agent, "_modly_user_data", return_value=self._user_data(td, "tok")), \ + patch.object(agent.urllib.request, "urlopen", fake_urlopen): + agent._request_json("GET", "http://127.0.0.1:8765/model/all", timeout=1, headers={"Accept": "x"}) + agent._download("http://127.0.0.1:8765/workspace/a.glb", Path(td) / "out" / "a.glb", timeout=1) + self.assertEqual([r.get_header("X-modly-token") for r in seen], ["tok", "tok"]) + self.assertEqual(seen[0].get_header("Accept"), "x") + class ParserTests(unittest.TestCase): def test_canonical_dev_experimental_and_legacy_subcommands_parse(self) -> None: From b96a893ccf5ff8196b7313b05cdc9d329b45b319 Mon Sep 17 00:00:00 2001 From: Lightning Pixel Date: Mon, 16 Nov 2026 17:22:25 +0100 Subject: [PATCH 2/2] fix(security): only add the API token to the app window's own requests The webRequest hook keyed on the destination alone; it now also requires the request to come from the main window's webContents. --- electron/main/index.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/electron/main/index.ts b/electron/main/index.ts index 56f0bb40f..fb1c4f14b 100644 --- a/electron/main/index.ts +++ b/electron/main/index.ts @@ -145,7 +145,10 @@ app.whenReady().then(async () => { { urls: ['http://127.0.0.1/*', 'http://localhost/*'] }, (details, callback) => { const port = pythonBridge?.getPort() - if (port !== undefined && isApiRequest(details.url, port)) { + // Only the app window's own requests get the token, whatever their + // destination: never another window or webContents in this session. + const fromAppWindow = mainWindow !== null && details.webContentsId === mainWindow.webContents.id + if (fromAppWindow && port !== undefined && isApiRequest(details.url, port)) { details.requestHeaders[API_TOKEN_HEADER] = getApiToken() } callback({ requestHeaders: details.requestHeaders })