Skip to content
Merged
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
2 changes: 1 addition & 1 deletion skills/index.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
},
{
"name": "opencode-build",
"version": "0.3.2",
"version": "0.3.3",
"files": [
"ERRATA.md",
"MAINTAINING.md",
Expand Down
5 changes: 4 additions & 1 deletion skills/opencode-build/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ license: MIT
metadata:
author: Robert Stone
source: https://github.com/rjstone/opencode-dev-plugin
version: "0.3.2"
version: "0.3.3"
---

# opencode Build docs (v2)
Expand Down Expand Up @@ -56,6 +56,9 @@ When they disagree, the higher source wins.
Check that a plugin loads, without a model or your real config:
`python scripts/plugin_probe.py <plugin-dir>` (needs the v2 CLI; details in
its docstring and `references/plugins.local.md` "Load").
The plugin runs inside the probe's server, so the probe leaves secret-looking
variables (API keys, tokens) out of that server's environment and prints their
names; `--keep-env NAME` passes one the plugin needs.

`plugins-server.md` (~1800 lines) and `plugins-gui.md` (~3700 lines) are
large: list their headings first (`grep -n '^##' <file>`), then read only the
Expand Down
38 changes: 33 additions & 5 deletions skills/opencode-build/scripts/plugin_probe.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@
and MCP servers the server reports, plus plugin lines from the server log.
Optionally calls one RPC method. No model or credentials needed. Stdlib only.

The plugin runs inside that server, so it would see your environment. Variables
whose names look like secrets (KEY, TOKEN, SECRET, PASSWORD, CREDENTIAL, AUTH)
are left out of the server's environment; the probe prints their names. Pass
`--keep-env NAME` (repeatable) for one the plugin really needs. The server gets
a random password chosen here, so none is printed in its log.

python scripts/plugin_probe.py <plugin-dir>
python scripts/plugin_probe.py <plugin-dir> --rpc my-plugin/ping --input "{}"
python scripts/plugin_probe.py <plugin-dir> --opencode <path-to-opencode> --json
Expand All @@ -24,6 +30,7 @@
import json
import os
import re
import secrets
import shutil
import signal
import socket
Expand All @@ -42,6 +49,18 @@ def strip_ansi(text):
return ANSI.sub("", text)


SECRET_NAME = re.compile(r"KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH", re.I)


def child_env(environ, keep=()):
"""(env, removed): a copy of environ without variables whose names look like
secrets, except those named in keep, and the sorted names that were left out.
The plugin under test runs in the server process and would read them."""
keep = set(keep)
env = {k: v for k, v in environ.items() if k in keep or not SECRET_NAME.search(k)}
return env, sorted(set(environ) - set(env))


def find_password(log):
"""The password `opencode serve --print-logs` prints at startup, or None."""
m = re.search(r"server password (\S+)", strip_ansi(log))
Expand Down Expand Up @@ -84,11 +103,11 @@ def free_port():


class Server:
def __init__(self, opencode, plugin_dir, port):
def __init__(self, opencode, plugin_dir, port, keep_env=()):
self.tmp = tempfile.mkdtemp(prefix="plugin-probe-")
self.project = os.path.join(self.tmp, "project")
os.makedirs(self.project)
self.env = dict(os.environ)
self.env, self.env_removed = child_env(os.environ, keep_env)
for name in ("CONFIG", "DATA", "CACHE", "STATE"):
self.env[f"XDG_{name}_HOME"] = os.path.join(self.tmp, "xdg", name.lower())
conf_dir = os.path.join(self.env["XDG_CONFIG_HOME"], "opencode")
Expand All @@ -97,7 +116,9 @@ def __init__(self, opencode, plugin_dir, port):
json.dump({"plugins": [plugin_dir]}, f)
self.log_path = os.path.join(self.tmp, "serve.log")
self.base = f"http://127.0.0.1:{port}"
self.password = None
# Our own password: with OPENCODE_PASSWORD set, the server prints none.
self.password = secrets.token_hex(24)
self.env["OPENCODE_PASSWORD"] = self.password
# Local server: never route through an HTTP(S) proxy from the environment.
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
cmd = [opencode, "serve", "--hostname", "127.0.0.1", "--port", str(port),
Expand All @@ -122,7 +143,8 @@ def wait_ready(self, timeout):
while time.monotonic() < end:
if self.proc.poll() is not None:
raise RuntimeError("opencode serve exited:\n" + strip_ansi(self.log())[-2000:])
self.password = self.password or find_password(self.log())
# an opencode that ignores OPENCODE_PASSWORD prints its own: use that one
self.password = find_password(self.log()) or self.password
if self.password:
try:
self.get("/api/plugin")
Expand Down Expand Up @@ -225,6 +247,8 @@ def main(argv=None):
ap.add_argument("--input", default="null", help="JSON input for --rpc (default null)")
ap.add_argument("--json", action="store_true", help="print the result as JSON")
ap.add_argument("--keep", action="store_true", help="keep the temp folder (config, log)")
ap.add_argument("--keep-env", action="append", default=[], metavar="NAME",
help="pass this secret-looking variable to the server after all (repeatable)")
args = ap.parse_args(argv)

if not args.opencode:
Expand All @@ -236,7 +260,7 @@ def main(argv=None):
print(f"not a folder: {plugin_dir}", file=sys.stderr)
return 2
try:
server = Server(args.opencode, plugin_dir, args.port or free_port())
server = Server(args.opencode, plugin_dir, args.port or free_port(), args.keep_env)
except OSError as err:
print(f"cannot start {args.opencode}: {err}", file=sys.stderr)
return 2
Expand All @@ -248,12 +272,16 @@ def main(argv=None):
return 2
finally:
server.stop(args.keep)
result["env_removed"] = server.env_removed
if args.keep:
result["temp"] = server.tmp
if args.json:
print(json.dumps(result, indent=2))
else:
print_report(result)
if server.env_removed:
print("environment: left out", len(server.env_removed), "secret-looking variable(s):",
", ".join(server.env_removed), "(--keep-env NAME passes one)")
if args.keep:
print("temp folder:", server.tmp)
ok = result["plugin"] and (result["plugin"].get("state") or {}).get("status") == "active"
Expand Down
16 changes: 16 additions & 0 deletions tests/test_opencode_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,22 @@ def test_plugin_log_lines(self):
self.assertIn("loading plugin", lines[0])
self.assertIn("setup failed", lines[1])

def test_child_env_drops_secret_looking_variables(self):
environ = {"PATH": "/bin", "HOME": "/h", "LANG": "C", "HTTPS_PROXY": "http://p:1",
"OPENROUTER_API_KEY": "k", "GH_TOKEN": "t", "MY_SECRET": "s",
"DB_PASSWORD": "p", "AWS_SECRET_ACCESS_KEY": "a", "SSH_AUTH_SOCK": "/s",
"Npm_Config_Authtoken": "n", "GOOGLE_APPLICATION_CREDENTIALS": "/c"}
env, removed = pp.child_env(environ)
self.assertEqual(sorted(env), ["HOME", "HTTPS_PROXY", "LANG", "PATH"])
self.assertEqual(removed, sorted(set(environ) - set(env)))
self.assertEqual(environ["GH_TOKEN"], "t") # the caller's mapping is untouched

def test_child_env_keeps_named_variables(self):
env, removed = pp.child_env({"PATH": "/bin", "GH_TOKEN": "t", "X_API_KEY": "k"},
keep=["GH_TOKEN", "NOT_SET"])
self.assertEqual(env, {"PATH": "/bin", "GH_TOKEN": "t"})
self.assertEqual(removed, ["X_API_KEY"])

def test_setup_errors_exit_2_without_leaving_temp(self):
before = set(os.listdir(tempfile.gettempdir()))
with tempfile.TemporaryDirectory() as d, redirect_stderr(io.StringIO()):
Expand Down