Ryanhub - file viewer
filename: chat/sandbox.py
branch: main
back to repo
import os
import json

WORKSPACE = None
_agent_cfg = os.path.join(os.path.dirname(__file__), "agent", "config.json")
if os.path.exists(_agent_cfg):
    try:
        with open(_agent_cfg, "r", encoding="utf-8") as _f:
            _j = json.load(_f)
            WORKSPACE = _j.get("WORKSPACE")
    except Exception:
        WORKSPACE = None

def safe_path(path: str) -> str:
    """Return a safely-normalized absolute path inside `WORKSPACE`.

    Raises ValueError if the resolved path is outside the workspace.
    """

    if not isinstance(path, str):
        raise TypeError("path must be a string")

    abs_workspace = os.path.abspath(WORKSPACE)

    rel = path.lstrip("/\\")

    joined = os.path.normpath(os.path.join(abs_workspace, rel))

    try:
        common = os.path.commonpath([abs_workspace, joined])
    except Exception:
        raise ValueError("attempted path outside workspace")
    if common != abs_workspace:
        raise ValueError("attempted path outside workspace")

    return joined