From 391c3265f406dcb64aec39c2ddf64a3bf13c0f34 Mon Sep 17 00:00:00 2001 From: kawaiipunk Date: Mon, 9 Nov 2026 15:33:48 +0000 Subject: [PATCH] Fix sandbox launch with OpenCode v2 background service OpenCode v2.2 starts a background service on 127.0.0.1:49374, which nono blocks unless a localhost port is granted. Give the sandbox its own service on 49376 with isolated config/state, and clean up its lifecycle. - Grant localhost ports 49376 (sandboxed service) and 3301 (Tinfoil proxy) - Add sandbox config/state dirs and XDG_STATE_HOME/OPENCODE_CONFIG_DIR - Wrapper mirrors real config, pins the sandbox service port, and stops stale/orphaned services so they never outlive the nono proxy - Remove deprecated commands.allow/deny and the redundant SSH key glob deny - Update installer, uninstall cleanup, and README --- Makefile | 2 + README.md | 211 +++++++++++++++++++++++++------- bin/opencode | 168 +++++++++++++++++++++++-- profiles/opencode-tinfoil.jsonc | 60 +++------ scripts/install.sh | 24 +++- 5 files changed, 368 insertions(+), 97 deletions(-) diff --git a/Makefile b/Makefile index 383f46b..6ff258d 100644 --- a/Makefile +++ b/Makefile @@ -10,6 +10,8 @@ install: uninstall: rm -f $(PROFILE_DIR)/opencode-tinfoil.json rm -f $(BIN_DIR)/opencode + rm -rf $(HOME)/.config/opencode-sandbox + rm -rf $(HOME)/.local/state/opencode-sandbox @echo "Uninstalled." validate: diff --git a/README.md b/README.md index 053f284..d5d181e 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ # nono-opencode-tinfoil - + A [`nono`](https://github.com/guybedford/nono) sandbox profile for running [OpenCode](https://opencode.ai) with access to [Tinfoil](https://tinfoil.sh) enclaves and other LLM providers. - + ## Quick Start - + ```bash git clone https://github.com/autonomic/nono-opencode-tinfoil.git cd nono-opencode-tinfoil @@ -13,9 +13,8 @@ make install # Ensure ~/.local/bin is in your PATH opencode ``` - -## Install +## Install ### macOS / Linux @@ -29,15 +28,21 @@ This installs: - The sandbox profile to `~/.config/nono/profiles/opencode-tinfoil.json` - A wrapper script to `~/.local/bin/opencode` +- Sandbox-local OpenCode config/state directories: + - `~/.config/opencode-sandbox/opencode` + - `~/.local/state/opencode-sandbox/opencode` ### Requirements -- [nono](https://github.com/guybedford/nono) installed e.g. `brew install nono` -- `opencode` installed globally. If not already installed, you can use any of: +- [nono](https://github.com/guybedford/nono) **0.81+**, e.g. `brew install nono` +- OpenCode **v2.2+**, installed globally. If not already installed, you can use any of: - **Homebrew**: `brew install opencode` - **npm**: `npm i -g opencode-ai` - **Other**: Any Node version manager (Volta, fnm, etc.) +OpenCode v2 runs a background service, which is why this profile grants a +localhost port and creates sandbox-local config/state directories. + ## How it works ``` @@ -48,9 +53,19 @@ you type: opencode scans PATH for the real opencode binary (skips itself — finds brew, npm, volta, etc.) ↓ - exec nono run --profile opencode-tinfoil --allow-cwd -- + creates ~/.config/opencode-sandbox/opencode + ~/.local/state/opencode-sandbox/opencode + symlinks your real ~/.config/opencode/* into the sandbox + (except service.json) + writes {"port": 49376} to the sandbox service.json if missing ↓ - opencode runs inside the sandbox + runs nono run --profile opencode-tinfoil --allow-cwd -- + ↓ + opencode runs inside the sandbox and starts its own + background service on 127.0.0.1:49376 + ↓ + when the sandbox exits, the wrapper stops the service + so it never outlives the nono proxy ``` The wrapper resolves the real `opencode` binary at runtime by scanning every @@ -58,10 +73,47 @@ directory in your `PATH`. It skips itself, so it works regardless of: - Where opencode is installed (Homebrew on macOS/Linux, npm global, Volta, etc.) - PATH ordering between the wrapper and the real binary +- PATH entries containing spaces - opencode version bumps You just type `opencode` from any project directory and it runs sandboxed. +### Sandbox-local service + +OpenCode v2 starts a background service on localhost. If the sandbox reused the +host service (default `127.0.0.1:49374`), the agent would run outside the +sandbox. To prevent that, the profile: + +- points `OPENCODE_CONFIG_DIR` at `~/.config/opencode-sandbox/opencode` +- points `XDG_STATE_HOME` at `~/.local/state/opencode-sandbox` +- grants localhost port `49376` for the sandboxed service + +The wrapper mirrors your normal OpenCode config into the sandbox config +directory as symlinks, so your models, plugins, and `opencode.jsonc` still apply. +`service.json` is deliberately **not** mirrored; the sandbox keeps its own copy +pinning port `49376`. + +Your host OpenCode service on `49374` is left untouched. The sandboxed CLI only +sees its own service registration in `~/.local/state/opencode-sandbox`. + +OpenCode spawns the service detached, so it would normally outlive the sandbox. +That matters because the service sends model requests through the nono proxy, +and the proxy exits with the sandbox. The wrapper therefore: + +- stops the sandboxed service when the last sandboxed instance exits +- stops any stale service left behind by an abruptly killed session before the + next launch +- leaves a live service alone while another sandboxed instance is still running + +If you run multiple sandboxed instances at once, they share the service on +`49376`, and it is stopped when the last instance exits. If the instance that +started the service exits first, stop the service explicitly so the remaining +instance starts a fresh one in its own sandbox: + +```bash +~/.local/bin/opencode service stop +``` + ### PATH ordering If a non-sandboxed `opencode` appears *earlier* on your `PATH` than the @@ -79,79 +131,146 @@ alias opencode="$HOME/.local/bin/opencode" ``` ## Usage - + From any project directory: - + ```bash opencode ``` - -Or use the profile directly with any opencode binary: - -```bash -nono run --profile opencode-tinfoil --allow-cwd -- opencode -``` - -You can also point it at a specific binary: - + +Or use the profile directly with a specific opencode binary. Note that the +sandbox config/state directories and `service.json` must exist first; `make +install` creates them, or you can launch the wrapper once: + ```bash # Homebrew (macOS) nono run --profile opencode-tinfoil --allow-cwd -- /opt/homebrew/bin/opencode - + # Homebrew (Linux) nono run --profile opencode-tinfoil --allow-cwd -- /home/linuxbrew/.linuxbrew/bin/opencode - + # npm global nono run --profile opencode-tinfoil --allow-cwd -- $(npm root -g)/opencode/bin/opencode ``` - + +### Changing the sandbox service port + +Port `49376` is chosen to avoid OpenCode's default `49374` (host service) and +`49375` (local channel). If `49376` is already in use, change it in **both** +places: + +1. `network.open_port` in `profiles/opencode-tinfoil.jsonc` +2. `SANDBOX_SERVICE_PORT` in `bin/opencode` (and the existing + `~/.config/opencode-sandbox/opencode/service.json`) + +Then re-run `make install`. + ## Tinfoil integration - - + The profile allows network access to: - + - `*.tinfoil.sh` - `inference.tinfoil.sh` - `containers.tinfoil.sh` -- `127.0.0.1` (supports Tinfoil local proxy at `http://127.0.0.1:3301/v1`) +- `127.0.0.1` (Tinfoil local proxy at `http://127.0.0.1:3301/v1`) - `ghcr.io` - + It also grants read/write access to `~/.tinfoil` for Tinfoil credentials. - -Other LLM provider network options (Anthropic, GLM, Kimi, etc.) are provided as commented-out entries in the profile for easy activation. - + +The profile grants localhost ports: + +- `49376` — sandboxed OpenCode background service +- `3301` — Tinfoil local proxy + +Other LLM provider network options (Anthropic, GLM, Kimi, etc.) are provided as +commented-out entries in the profile for easy activation. + ## Security model - + - Current working directory: read/write -- OpenCode config: read/write +- OpenCode config and sandbox config/state: read/write - Tinfoil config: read/write - SSH private keys, AWS/GCP/Azure credentials, kubeconfig: denied -- `sudo`, `su`, `doas`, `passwd`, disk tools: denied - +- The OpenCode background service runs **inside** the sandbox; the host service + on `127.0.0.1:49374` is not reused +- The profile no longer uses `commands.allow` / `commands.deny`. Those fields + are deprecated in nono and only applied at startup, so they were not enforced + for child processes. Access is constrained by filesystem, network, and + environment policy instead. + +### Linux Landlock caveat + +On Linux, nono uses Landlock, which has no deny semantics. `filesystem.deny` +globs are only enforced against paths that exist at sandbox start. Files created +afterward that match a deny glob are **not** denied. This profile therefore +avoids glob-based denies and relies on narrow allow grants plus the +`deny_credentials` group. If you add your own glob denies, keep this limitation +in mind or enable capability elevation in nono for runtime enforcement. + ### Environment Variables - + | Status | Variables / Patterns | |--------|----------------------| | Allowed | `PATH`, `HOME`, `USER`, `SHELL`, `TERM` | -| Denied | `AWS_*`, `GOOGLE_*`, `AZURE_*`, `KUBECONFIG`, `SSH_AUTH_SOCK` | - +| Denied | `AWS_*`, `GOOGLE_*`, `AZURE_*`, `GCP_*`, `KUBECONFIG`, `SSH_AUTH_SOCK` | + ## Uninstall - - + ```bash make uninstall ``` - -## License - -GPL-3.0 +This removes the profile, the wrapper, and the sandbox config/state +directories. Your real `~/.config/opencode` and `~/.local/state/opencode` are +not touched. ## Troubleshooting - + **"command not found: opencode"** Ensure `~/.local/bin` is in your `PATH`. Add `export PATH="$HOME/.local/bin:$PATH"` to your `.bashrc` or `.zshrc` and restart your terminal. - + **Sandbox is being bypassed** If you have another version of `opencode` installed (e.g. via Homebrew) that appears earlier in your `PATH` than the wrapper, the sandbox will be bypassed. Check this using `which -a opencode`. The wrapper at `~/.local/bin/opencode` must come first. +**`permission denied 127.0.0.1:49374` / `Server process exited with code 1`** +This means the sandboxed OpenCode is still trying to use the host service port. +The sandbox `service.json` is missing or stale, or the wrapper was bypassed. +Re-run `make install`, then remove the sandbox config and relaunch: + +```bash +rm -rf ~/.config/opencode-sandbox ~/.local/state/opencode-sandbox +opencode +``` + +Confirm the sandboxed service is on `49376`: + +```bash +~/.local/bin/opencode service status # sandbox, should be 49376 +/path/to/host/opencode service status # host, should still be 49374 +``` + +Use the real binary path for the host check (for example +`/home/linuxbrew/.linuxbrew/bin/opencode`). If `~/.local/bin` comes first in +your `PATH`, plain `opencode` invokes the sandbox wrapper. + +**`Failed to start server. Is port 49376 in use?`** +The wrapper stops stale sandboxed services on startup, so this usually means an +unrelated process is using the port. Pick a different port as described in +[Changing the sandbox service port](#changing-the-sandbox-service-port). If you +want to clear it manually, stop the sandboxed service from inside the sandbox: + +```bash +~/.local/bin/opencode service stop +``` + +**`Unrecognized flag: --standalone`** +`--standalone` is a top-level OpenCode flag, not a `serve` or `service` +subcommand flag. Use `opencode --standalone ...` rather than +`opencode serve --standalone`. + +**Landlock glob-deny warning** +See [Linux Landlock caveat](#linux-landlock-caveat). + +## License + +GPL-3.0 diff --git a/bin/opencode b/bin/opencode index 2e6b92e..7ecc6b6 100755 --- a/bin/opencode +++ b/bin/opencode @@ -1,11 +1,41 @@ #!/usr/bin/env bash set -euo pipefail +PROFILE_NAME="opencode-tinfoil" +SANDBOX_CONFIG_DIR="${HOME}/.config/opencode-sandbox/opencode" +SANDBOX_STATE_HOME="${HOME}/.local/state/opencode-sandbox" +SANDBOX_STATE_DIR="${SANDBOX_STATE_HOME}/opencode" +ACTIVE_DIR="${SANDBOX_STATE_HOME}/active" +SERVICE_STATE="${SANDBOX_STATE_DIR}/service.json" +REAL_CONFIG_DIR="${HOME}/.config/opencode" +SANDBOX_SERVICE_PORT=49376 + +# Resolve this script's own path, following symlinks so we can skip ourselves +# when scanning PATH for the real OpenCode binary. +self_path() { + local src="${BASH_SOURCE[0]}" dir + while [ -L "$src" ]; do + dir="$(cd -P "$(dirname "$src")" >/dev/null 2>&1 && pwd)" + src="$(readlink "$src")" + case "$src" in + /*) ;; + *) src="${dir}/${src}" ;; + esac + done + printf '%s/%s\n' "$(cd -P "$(dirname "$src")" >/dev/null 2>&1 && pwd)" "$(basename "$src")" +} + +SELF="$(self_path)" + find_real_opencode() { - local d c - for d in $(printf '%s' "$PATH" | tr ':' ' '); do + local d c resolved + local IFS=: + for d in $PATH; do + [ -n "$d" ] || continue for c in "$d/opencode" "$d/opencode.exe"; do - if [ -x "$c" ] && [ "$c" != "$HOME/.local/bin/opencode" ]; then + [ -f "$c" ] && [ -x "$c" ] || continue + resolved="$(cd -P "$(dirname "$c")" >/dev/null 2>&1 && pwd)/$(basename "$c")" + if [ "$resolved" != "$SELF" ]; then printf '%s\n' "$c" return 0 fi @@ -14,10 +44,134 @@ find_real_opencode() { return 1 } -REAL_OPENCODE="$(find_real_opencode || true)" -if [ -z "$REAL_OPENCODE" ]; then - echo "Error: real opencode binary not found in PATH" >&2 +# Read the PID of the sandboxed background service from its state file. +sandbox_service_pid() { + [ -f "${SERVICE_STATE}" ] || return 1 + sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "${SERVICE_STATE}" | head -n 1 +} + +# Stop the sandboxed background service. OpenCode spawns it detached, so it +# would otherwise outlive the nono supervisor (and lose the nono proxy). +stop_sandbox_service() { + local pid cmd i + pid="$(sandbox_service_pid || true)" + if [ -z "${pid}" ] || ! kill -0 "${pid}" 2>/dev/null; then + rm -f "${SERVICE_STATE}" + return 0 + fi + + cmd="$(ps -p "${pid}" -o command= 2>/dev/null || true)" + case "${cmd}" in + *opencode*serve*--service*) ;; + *) rm -f "${SERVICE_STATE}"; return 0 ;; + esac + + # On Linux, make sure this is our sandbox service and not an unrelated + # OpenCode service whose PID happened to be reused. + if [ -r "/proc/${pid}/environ" ]; then + if ! tr '\0' '\n' < "/proc/${pid}/environ" 2>/dev/null | grep -qF "OPENCODE_CONFIG_DIR=${SANDBOX_CONFIG_DIR}"; then + if ! tr '\0' '\n' < "/proc/${pid}/environ" 2>/dev/null | grep -qF "XDG_STATE_HOME=${SANDBOX_STATE_HOME}"; then + rm -f "${SERVICE_STATE}" + return 0 + fi + fi + fi + + kill -TERM "${pid}" 2>/dev/null || true + i=0 + while [ "${i}" -lt 10 ] && kill -0 "${pid}" 2>/dev/null; do + sleep 0.2 + i=$((i + 1)) + done + kill -KILL "${pid}" 2>/dev/null || true + rm -f "${SERVICE_STATE}" +} + +prune_active() { + local f pid + [ -d "${ACTIVE_DIR}" ] || return 0 + for f in "${ACTIVE_DIR}"/*; do + [ -e "${f}" ] || continue + pid="$(basename "${f}")" + if ! kill -0 "${pid}" 2>/dev/null; then + rm -f "${f}" + fi + done +} + +active_count() { + local f n=0 + [ -d "${ACTIVE_DIR}" ] || { echo 0; return; } + for f in "${ACTIVE_DIR}"/*; do + [ -e "${f}" ] || continue + n=$((n + 1)) + done + echo "${n}" +} + +CLEANED=0 +cleanup() { + [ "${CLEANED}" -eq 1 ] && return 0 + CLEANED=1 + rm -f "${ACTIVE_DIR}/$$" + prune_active + # Stop the service once the last sandboxed instance exits. Its nono proxy + # belongs to that instance's supervisor, so leaving it behind would leave a + # service that can no longer reach the network. + if [ "$(active_count)" -eq 0 ]; then + stop_sandbox_service + fi +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM +trap 'exit 129' HUP + +if ! command -v nono >/dev/null 2>&1; then + echo "Error: nono not found in PATH. Install it first, e.g. 'brew install nono'." >&2 exit 1 fi -exec nono run --profile opencode-tinfoil --allow-cwd -- "$REAL_OPENCODE" "$@" +REAL_OPENCODE="$(find_real_opencode || true)" +if [ -z "${REAL_OPENCODE}" ]; then + echo "Error: real opencode binary not found in PATH (excluding this wrapper)." >&2 + exit 1 +fi + +# OpenCode v2 runs a background service. Give the sandbox its own config and +# state directories so it starts a dedicated service instead of discovering a +# host service running outside the sandbox. +mkdir -p "${SANDBOX_CONFIG_DIR}" "${SANDBOX_STATE_DIR}" "${ACTIVE_DIR}" + +# Mirror the user's real config into the sandbox config dir, but never copy +# service.json: that file pins the sandbox service port. +if [ -d "${REAL_CONFIG_DIR}" ]; then + shopt -s dotglob nullglob + for entry in "${REAL_CONFIG_DIR}"/*; do + name="$(basename "${entry}")" + [ "${name}" = "service.json" ] && continue + dest="${SANDBOX_CONFIG_DIR}/${name}" + if [ -L "${dest}" ]; then + rm -f "${dest}" + fi + if [ ! -e "${dest}" ]; then + ln -s "${entry}" "${dest}" + fi + done + shopt -u dotglob nullglob +fi + +if [ ! -f "${SANDBOX_CONFIG_DIR}/service.json" ]; then + printf '{\n "port": %s\n}\n' "${SANDBOX_SERVICE_PORT}" > "${SANDBOX_CONFIG_DIR}/service.json" + chmod 600 "${SANDBOX_CONFIG_DIR}/service.json" +fi + +# If no other sandboxed OpenCode is running, clear out a service left behind by +# a previous session (for example after a SIGKILL) before starting a new one. +prune_active +if [ "$(active_count)" -eq 0 ]; then + stop_sandbox_service +fi +: > "${ACTIVE_DIR}/$$" + +nono run --profile "${PROFILE_NAME}" --allow-cwd -- "${REAL_OPENCODE}" "$@" diff --git a/profiles/opencode-tinfoil.jsonc b/profiles/opencode-tinfoil.jsonc index 16d49bb..8b3eb28 100644 --- a/profiles/opencode-tinfoil.jsonc +++ b/profiles/opencode-tinfoil.jsonc @@ -6,39 +6,6 @@ "groups": { "include": ["deny_credentials"] }, - "commands": { - "allow": [ - "git", - "node", - "npm", - "npx", - "bun", - "python3", - "python", - "pip", - "pip3", - "cargo", - "rustc", - "go", - "tinfoil" - ], - "deny": [ - "sudo", - "su", - "doas", - "pkexec", - "passwd", - "chsh", - "usermod", - "useradd", - "deluser", - "rm -rf /", - "mkfs", - "dd", - "fdisk", - "parted" - ] - }, "workdir": { "access": "readwrite" }, @@ -48,7 +15,10 @@ ], "read": [ "$HOME/.config/opencode", + "$HOME/.config/opencode-sandbox", "$HOME/.local/share/opencode", + "$HOME/.local/state/opencode-sandbox", + "$HOME/.cache/opencode", "$HOME/.opencode", "$HOME/.claude", "$HOME/.gitconfig", @@ -62,13 +32,15 @@ ], "write": [ "$HOME/.config/opencode", + "$HOME/.config/opencode-sandbox", "$HOME/.local/share/opencode", + "$HOME/.local/state/opencode-sandbox", + "$HOME/.cache/opencode", "$HOME/.opencode", "$HOME/.claude", "/tmp" ], "deny": [ - "$HOME/.ssh/id_*", "$HOME/.gnupg", "$HOME/.aws", "$HOME/.azure", @@ -84,6 +56,10 @@ }, "network": { "block": false, + "open_port": [ + 49376, // OpenCode background service, kept separate from the host service on 49374 + 3301 // Tinfoil local proxy http://127.0.0.1:3301/v1 + ], "allow_domain": [ "api.openai.com", "api.anthropic.com", @@ -142,15 +118,17 @@ }, "environment": { "set_vars": { - "OPENCODE_CONFIG_DIR": "$HOME/.config/opencode", + "XDG_STATE_HOME": "$HOME/.local/state/opencode-sandbox", + "OPENCODE_CONFIG_DIR": "$HOME/.config/opencode-sandbox/opencode", "TINFOIL_CONFIG_DIR": "$HOME/.tinfoil" }, "deny_vars": [ - "AWS_SECRET_ACCESS_KEY", - "AWS_ACCESS_KEY_ID", - "AZURE_CLIENT_SECRET", - "GCP_PRIVATE_KEY", - "KUBECONFIG" + "AWS_*", + "GOOGLE_*", + "AZURE_*", + "GCP_*", + "KUBECONFIG", + "SSH_AUTH_SOCK" ] } -} \ No newline at end of file +} diff --git a/scripts/install.sh b/scripts/install.sh index 2f0cfcb..31572c6 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -7,6 +7,10 @@ PROFILE_DIR="${HOME}/.config/nono/profiles" BIN_DIR="${HOME}/.local/bin" WRAPPER_SRC="bin/opencode" +SANDBOX_CONFIG_DIR="${HOME}/.config/opencode-sandbox/opencode" +SANDBOX_STATE_DIR="${HOME}/.local/state/opencode-sandbox/opencode" +SANDBOX_SERVICE_PORT=49376 + if ! command -v nono &>/dev/null; then echo "Error: nono is not installed. Install it first:" echo " brew install nono" @@ -27,17 +31,31 @@ chmod 644 "${PROFILE_DIR}/${PROFILE_NAME}.json" cp "${WRAPPER_SRC}" "${BIN_DIR}/opencode" chmod 755 "${BIN_DIR}/opencode" +# Create the sandbox-local OpenCode config/state directories. The wrapper also +# does this at launch time, but doing it here makes the layout explicit and +# lets the smoke test start from a clean setup. +mkdir -p "${SANDBOX_CONFIG_DIR}" "${SANDBOX_STATE_DIR}" +if [[ ! -f "${SANDBOX_CONFIG_DIR}/service.json" ]]; then + printf '{\n "port": %s\n}\n' "${SANDBOX_SERVICE_PORT}" > "${SANDBOX_CONFIG_DIR}/service.json" + chmod 600 "${SANDBOX_CONFIG_DIR}/service.json" +fi + nono profile validate "${PROFILE_NAME}" echo "Installed:" echo " Profile: ${PROFILE_DIR}/${PROFILE_NAME}.json" echo " Wrapper: ${BIN_DIR}/opencode" +echo " Sandbox config: ${SANDBOX_CONFIG_DIR}" +echo " Sandbox state: ${SANDBOX_STATE_DIR}" +echo " Sandbox service port: ${SANDBOX_SERVICE_PORT}" find_first_opencode() { local d c - for d in $(printf '%s' "$PATH" | tr ':' ' '); do + local IFS=: + for d in $PATH; do + [ -n "$d" ] || continue for c in "$d/opencode" "$d/opencode.exe"; do - if [ -x "$c" ]; then + if [ -f "$c" ] && [ -x "$c" ]; then printf '%s\n' "$c" return 0 fi @@ -74,4 +92,4 @@ if "${BIN_DIR}/opencode" --version; then else echo "Error: sandboxed wrapper failed to launch." >&2 exit 1 -fi \ No newline at end of file +fi