Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: <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 |
Expand Down
14 changes: 4 additions & 10 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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)
Expand Down
23 changes: 21 additions & 2 deletions api/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
}

Requires Modly to be running. Its API is found through MODLY_API_URL, else the
port the app writes to <userData>/api-port, else http://127.0.0.1:8765.
port the app writes to <userData>/api-port, else http://127.0.0.1:8765. Calls
carry the X-Modly-Token the app writes to <userData>/api-token (else env
MODLY_API_TOKEN; none for a tokenless standalone backend).
"""

import asyncio
Expand Down Expand Up @@ -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 <userData>/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")


Expand Down Expand Up @@ -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:
Expand Down
5 changes: 3 additions & 2 deletions api/routers/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
37 changes: 31 additions & 6 deletions api/routers/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 ``<b64url(path)>[.<b64url(hmac)>]``. 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;
Expand All @@ -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():
Expand Down Expand Up @@ -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, ``.<signature>`` (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()
Expand All @@ -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
Expand All @@ -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
``<api origin><url_path>``. ``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:
Expand Down
169 changes: 169 additions & 0 deletions api/services/api_auth.py
Original file line number Diff line number Diff line change
@@ -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: <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``.

``<b64url(path)>.<b64url(hmac)>`` 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"))
6 changes: 6 additions & 0 deletions api/services/extension_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading
Loading