Skip to content

Commit 4322e97

Browse files
committed
fix(upstream): let an explicit OPENROUTER_API_KEY override stored opencode auth
The wrapper only seeded auth.json when no openrouter credential existed. Anyone who had previously run 'opencode /connect' would have their port.env key silently ignored and the run billed to the old key — close to undebuggable. An explicitly provided key now always wins. Other providers in auth.json are preserved rather than clobbered, and a corrupt auth.json recovers instead of failing the run.
1 parent 0ca906a commit 4322e97

1 file changed

Lines changed: 26 additions & 3 deletions

File tree

‎scripts/upstream‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,35 @@ model_args=()
7272

7373
# opencode reads credentials from auth.json. Seed it from OPENROUTER_API_KEY so
7474
# headless CI and local runs work without the interactive /connect flow.
75+
#
76+
# An explicitly-provided key always wins: if you put a key in port.env, that is
77+
# the key that gets used, even when an openrouter credential already exists from
78+
# a previous `opencode /connect`. Silently preferring the stored one makes
79+
# "why is it still using the old key" nearly impossible to debug.
80+
#
81+
# Other providers in auth.json are preserved — only the openrouter entry is
82+
# replaced.
7583
if [ -n "${OPENROUTER_API_KEY:-}" ]; then
7684
auth_dir="${XDG_DATA_HOME:-$HOME/.local/share}/opencode"
85+
auth_file="$auth_dir/auth.json"
7786
mkdir -p "$auth_dir"
78-
if [ ! -f "$auth_dir/auth.json" ] || ! grep -q '"openrouter"' "$auth_dir/auth.json" 2>/dev/null; then
79-
printf '{"openrouter":{"type":"api","key":"%s"}}\n' "$OPENROUTER_API_KEY" > "$auth_dir/auth.json"
80-
chmod 600 "$auth_dir/auth.json"
87+
if OPENROUTER_API_KEY="$OPENROUTER_API_KEY" AUTH_FILE="$auth_file" python3 - <<'PYAUTH'
88+
import json, os, pathlib
89+
path = pathlib.Path(os.environ["AUTH_FILE"])
90+
try:
91+
data = json.loads(path.read_text())
92+
if not isinstance(data, dict):
93+
data = {}
94+
except Exception:
95+
data = {}
96+
data["openrouter"] = {"type": "api", "key": os.environ["OPENROUTER_API_KEY"]}
97+
path.write_text(json.dumps(data, indent=2) + "\n")
98+
path.chmod(0o600)
99+
PYAUTH
100+
then
101+
echo "auth: openrouter credential set from OPENROUTER_API_KEY" >&2
102+
else
103+
echo "WARNING: could not write $auth_file; falling back to whatever opencode has stored" >&2
81104
fi
82105
fi
83106

0 commit comments

Comments
 (0)