Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
"""
Access control for the loopback sidecar.
The API listens on 127.0.0.1, which any web page the user visits can reach with
fetch(). Three layers keep those pages out:
1. A per-launch secret (FORGE_API_TOKEN, generated by Electron main) must be
presented in the X-Forge-Token header on every request.
2. The Host header must name the loopback interface, which defeats DNS rebinding.
3. CORS only admits the app's own renderer origins (FORGE_ALLOWED_ORIGINS, a
comma separated list), never a wildcard.
The workspace file route additionally refuses anything that resolves outside
the workspace directory.
"""
import hmac
import os
from pathlib import Path
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
TOKEN_HEADER = "x-forge-token"
LOOPBACK_HOSTS = {"127.0.0.1", "localhost", "[::1]"}
def _host_name(host_header: str) -> str:
host = host_header.strip().lower()
if host.startswith("["):
return host.split("]", 1)[0] + "]"
return host.rsplit(":", 1)[0] if ":" in host else host
def _allowed_origins() -> list[str]:
raw = os.environ.get("FORGE_ALLOWED_ORIGINS", "")
return [o.strip() for o in raw.split(",") if o.strip()]
class _AccessControlMiddleware:
"""Pure ASGI so streaming responses are untouched."""
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] not in ("http", "websocket"):
await self.app(scope, receive, send)
return
headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope["headers"]}
if _host_name(headers.get("host", "")) not in LOOPBACK_HOSTS:
await self._reject(scope, receive, send, 403, "Forbidden host")
return
expected = os.environ.get("FORGE_API_TOKEN", "")
supplied = headers.get(TOKEN_HEADER, "")
if not expected or not hmac.compare_digest(expected.encode(), supplied.encode()):
await self._reject(scope, receive, send, 401, "Missing or invalid API token")
return
await self.app(scope, receive, send)
@staticmethod
async def _reject(scope, receive, send, status: int, detail: str):
if scope["type"] == "websocket":
await send({"type": "websocket.close", "code": 1008})
return
await JSONResponse({"detail": detail}, status_code=status)(scope, receive, send)
def install_access_control(app: FastAPI) -> None:
# Added first so CORS (added second, therefore outermost) answers preflights
# itself and decorates rejections with the right headers.
app.add_middleware(_AccessControlMiddleware)
app.add_middleware(
CORSMiddleware,
allow_origins=_allowed_origins(),
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
allow_headers=["content-type", TOKEN_HEADER],
# drei's SplatLoader reads Content-Length to size its buffers; cross-origin
# JS can only see it when the server explicitly exposes the header.
expose_headers=["Content-Length"],
)
def resolve_inside(root: Path, relative: str) -> Path | None:
"""Resolve root/relative, or None when the result escapes root (.., absolute, symlinks)."""
try:
base = root.resolve()
target = (base / relative).resolve()
except (OSError, ValueError, RuntimeError):
return None
if not target.is_relative_to(base):
return None
return target
def register_workspace_route(app: FastAPI) -> None:
# Dynamic so path changes take effect immediately.
@app.get("/workspace/{full_path:path}")
async def serve_workspace_file(full_path: str):
import services.generator_registry as reg
file_path = resolve_inside(reg.WORKSPACE_DIR, full_path)
if file_path is None or not file_path.is_file():
raise HTTPException(status_code=404, detail="File not found")
return FileResponse(str(file_path))