|
| 1 | +""" |
| 2 | +Small FastAPI service to open a given path in the host OS (e.g., Finder on macOS). |
| 3 | +Run this outside Docker so it can launch the native file explorer. |
| 4 | +""" |
| 5 | +import logging |
| 6 | +import os |
| 7 | +import subprocess |
| 8 | +import sys |
| 9 | +import re |
| 10 | +from pathlib import Path |
| 11 | +from fastapi import FastAPI, HTTPException |
| 12 | +from pydantic import BaseModel |
| 13 | + |
| 14 | +logging.basicConfig( |
| 15 | + level=logging.INFO, |
| 16 | + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", |
| 17 | + handlers=[logging.StreamHandler()], |
| 18 | +) |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | +app = FastAPI(title="PlanExe Host Opener", version="0.1.0") |
| 22 | + |
| 23 | +RUN_BASE_ENV = os.environ.get("PLANEXE_HOST_RUN_DIR") |
| 24 | +if not RUN_BASE_ENV: |
| 25 | + raise RuntimeError("PLANEXE_HOST_RUN_DIR must be set to the host run directory.") |
| 26 | +ALLOWED_BASE = Path(RUN_BASE_ENV).expanduser().resolve() |
| 27 | + |
| 28 | +HOST = os.environ.get("PLANEXE_OPEN_DIR_SERVER_HOST", "127.0.0.1") |
| 29 | +PORT = int(os.environ.get("PLANEXE_OPEN_DIR_SERVER_PORT", "5100")) |
| 30 | + |
| 31 | + |
| 32 | +class OpenPathRequest(BaseModel): |
| 33 | + path: str |
| 34 | + |
| 35 | + |
| 36 | +class OpenPathResponse(BaseModel): |
| 37 | + status: str |
| 38 | + message: str |
| 39 | + |
| 40 | + |
| 41 | +def _is_allowed(target: Path) -> bool: |
| 42 | + try: |
| 43 | + target.resolve().relative_to(ALLOWED_BASE) |
| 44 | + return True |
| 45 | + except ValueError: |
| 46 | + return False |
| 47 | + |
| 48 | + |
| 49 | +def _command_for_platform(target: Path) -> list[str]: |
| 50 | + if sys.platform == "darwin": |
| 51 | + return ["open", str(target)] |
| 52 | + if os.name == "nt": |
| 53 | + return ["cmd", "/c", "start", "", str(target)] |
| 54 | + if sys.platform.startswith("linux"): |
| 55 | + return ["xdg-open", str(target)] |
| 56 | + raise ValueError(f"Unsupported platform: {sys.platform}") |
| 57 | + |
| 58 | + |
| 59 | +@app.post("/open", response_model=OpenPathResponse) |
| 60 | +def open_path(request: OpenPathRequest): |
| 61 | + raw_path = request.path |
| 62 | + # Only allow PlanExe-style run directory names to avoid arbitrary path access. |
| 63 | + if not re.fullmatch(r"^PlanExe_\d+_\d+$", Path(raw_path).name): |
| 64 | + raise HTTPException(status_code=400, detail="Invalid path format.") |
| 65 | + target = Path(raw_path).expanduser().resolve() |
| 66 | + |
| 67 | + if not _is_allowed(target): |
| 68 | + raise HTTPException(status_code=403, detail="Path is outside allowed base.") |
| 69 | + |
| 70 | + if not target.exists(): |
| 71 | + raise HTTPException(status_code=404, detail=f"Path does not exist: {target}") |
| 72 | + |
| 73 | + try: |
| 74 | + cmd = _command_for_platform(target) |
| 75 | + except ValueError as exc: |
| 76 | + raise HTTPException(status_code=400, detail=str(exc)) from exc |
| 77 | + |
| 78 | + try: |
| 79 | + subprocess.run(cmd, check=True) |
| 80 | + except Exception as exc: |
| 81 | + logger.warning("Failed to open %s: %s", target, exc) |
| 82 | + raise HTTPException(status_code=500, detail=f"Failed to open path: {exc}") from exc |
| 83 | + |
| 84 | + return OpenPathResponse(status="ok", message=f"Requested OS to open {target}.") |
| 85 | + |
| 86 | + |
| 87 | +@app.get("/healthz") |
| 88 | +def health() -> dict: |
| 89 | + return { |
| 90 | + "status": "ok", |
| 91 | + "allowed_base": str(ALLOWED_BASE) if ALLOWED_BASE else None, |
| 92 | + "platform": sys.platform, |
| 93 | + "host": HOST, |
| 94 | + "port": PORT, |
| 95 | + } |
| 96 | + |
| 97 | + |
| 98 | +if __name__ == "__main__": |
| 99 | + import uvicorn |
| 100 | + |
| 101 | + uvicorn.run("app:app", host=HOST, port=PORT, reload=False) |
0 commit comments