omp-opencode-bridge 0.0.0-stage → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/install.sh ADDED
@@ -0,0 +1,708 @@
1
+ #!/usr/bin/env bash
2
+ # opencode-free-bridge installer.
3
+ #
4
+ # curl -fsSL https://raw.githubusercontent.com/azrinaldi/opencode-free-bridge/main/install.sh | bash
5
+ #
6
+ # What it does:
7
+ # 1. finds Bun, or installs it. The CLI ships as a Bun binary and the
8
+ # free-tier gate checks the transport fingerprint: measured 200 on Bun,
9
+ # 403 on Node and curl.
10
+ # 2. downloads the bridge into a staging directory and validates it before
11
+ # touching anything that is already running
12
+ # 3. retires a pre-2.0 `opencode-bridge.service` that would fight for the port
13
+ # 4. copies the bridge and its tools into an install dir (server.ts,
14
+ # identity.ts, token-budget.ts, verify.ts, gate-drill.ts and the
15
+ # transport-fingerprint files), backing up any existing install first
16
+ # 5. registers a service so the bridge starts on boot and restarts on crash
17
+ # (systemd on Linux, launchd on macOS). Windows is not supported.
18
+ # 6. waits for /health, then runs the self-check and the TLS fingerprint check
19
+ #
20
+ # It exits non-zero if the bridge does not come up. "Done" is only printed for
21
+ # a bridge that answered.
22
+ #
23
+ # Env overrides:
24
+ # PORT listen port (default 20129)
25
+ # HOST bind address (default 127.0.0.1)
26
+ # BINDIR where the files go (default ~/.opencode-free-bridge)
27
+ # NO_SERVICE skip service install (default: install the service)
28
+ # REPO source repo (default azrinaldi/opencode-free-bridge)
29
+ # SOURCE auto | local | remote (default auto: local when run from a clone)
30
+ set -euo pipefail
31
+
32
+ PORT="${PORT:-20129}"
33
+ HOST="${HOST:-127.0.0.1}"
34
+ BINDIR="${BINDIR:-$HOME/.opencode-free-bridge}"
35
+ REPO="${REPO:-azrinaldi/opencode-free-bridge}"
36
+ BRANCH="${BRANCH:-main}"
37
+ # Directory of this script when it exists on disk. The `curl | bash` route has no
38
+ # file at all, so the local path is only taken when BASH_SOURCE names a real
39
+ # install.sh; otherwise `SOURCE=auto` falls through to the remote download.
40
+ SOURCE_PATH="${BASH_SOURCE[0]:-}"
41
+ SCRIPT_DIR=""
42
+ if [ -n "$SOURCE_PATH" ] && [ -f "$SOURCE_PATH" ]; then
43
+ SCRIPT_DIR="$(cd "$(dirname "$SOURCE_PATH")" && pwd)"
44
+ fi
45
+
46
+ say() { printf '\033[1;32m[opencode-free-bridge]\033[0m %s\n' "$*"; }
47
+ warn() { printf '\033[1;33m[opencode-free-bridge]\033[0m %s\n' "$*" >&2; }
48
+ die() { printf '\033[1;31m[opencode-free-bridge]\033[0m %s\n' "$*" >&2; exit 1; }
49
+
50
+ [[ "$PORT" =~ ^[0-9]+$ ]] && [ "$PORT" -ge 1 ] && [ "$PORT" -le 65535 ] || die "Invalid PORT: $PORT"
51
+ [[ "$HOST" =~ ^[A-Za-z0-9.:_-]+$ ]] || die "Invalid HOST: $HOST"
52
+ case "$BINDIR" in
53
+ *$'\n'*|*$'\r'*) die "Invalid BINDIR: newline not allowed" ;;
54
+ esac
55
+
56
+ # ---------------------------------------------------------------- Node.js ---
57
+ # Bun is required, not preferred. Measured from one IP in one minute with
58
+ # identical headers and body: the real CLI and the bridge on Bun both get 200,
59
+ # while Node and curl get 403. The CLI ships as a Bun binary, and the free-tier
60
+ # gate inspects the transport fingerprint, so only Bun reproduces it.
61
+ #
62
+ # `curl https://bun.sh/install | bash` puts bun in `$HOME/.bun/bin` and adds it
63
+ # to an *interactive* shell's PATH only. A non-interactive SSH session, a cron
64
+ # job, or this installer running under `sh -c` therefore sees no `bun` even
65
+ # though the binary is present. Look in the standard locations before
66
+ # concluding it is missing.
67
+ find_bun() {
68
+ if command -v bun >/dev/null 2>&1; then
69
+ command -v bun
70
+ return 0
71
+ fi
72
+ local candidate
73
+ for candidate in "${BUN_INSTALL:-}/bin/bun" "$HOME/.bun/bin/bun" "$HOME/.local/bin/bun" /usr/local/bin/bun /opt/bun/bin/bun; do
74
+ if [ -n "$candidate" ] && [ -x "$candidate" ]; then
75
+ printf '%s\n' "$candidate"
76
+ return 0
77
+ fi
78
+ done
79
+ return 1
80
+ }
81
+
82
+ if BUN_BIN="$(find_bun)"; then
83
+ RUNTIME="$BUN_BIN"
84
+ say "runtime: bun ($("$RUNTIME" --version)) — matches the CLI's transport"
85
+ case ":$PATH:" in
86
+ *":$(dirname "$RUNTIME"):"*) ;;
87
+ *) warn "bun is not on PATH; using $RUNTIME. Add $(dirname "$RUNTIME") to PATH for manual runs." ;;
88
+ esac
89
+ elif [ -n "${ALLOW_NODE:-}" ] && command -v node >/dev/null 2>&1; then
90
+ RUNTIME="$(command -v node)"
91
+ warn "runtime: node — NOT supported for live use. The free-tier gate refuses Node's"
92
+ warn "transport fingerprint with 403. Proceeding because ALLOW_NODE is set."
93
+ else
94
+ # The one-line installer exists so a new user does not have to read a manual.
95
+ # Telling them "install Bun first" and exiting defeats that, so install it.
96
+ say "Bun is not installed; installing it now (required for the transport fingerprint)"
97
+ if ! command -v unzip >/dev/null 2>&1 && ! command -v 7z >/dev/null 2>&1; then
98
+ if [ "$(id -u)" = "0" ] || (command -v sudo >/dev/null 2>&1 && sudo -n true >/dev/null 2>&1); then
99
+ SUDO_CMD=""
100
+ [ "$(id -u)" != "0" ] && SUDO_CMD="sudo -n"
101
+ say "Installing unzip (required by the Bun installer)..."
102
+ if command -v apt-get >/dev/null 2>&1; then
103
+ $SUDO_CMD apt-get update -qq >/dev/null 2>&1 && $SUDO_CMD apt-get install -y -qq unzip >/dev/null 2>&1 || true
104
+ elif command -v dnf >/dev/null 2>&1; then
105
+ $SUDO_CMD dnf install -y -q unzip >/dev/null 2>&1 || true
106
+ elif command -v yum >/dev/null 2>&1; then
107
+ $SUDO_CMD yum install -y -q unzip >/dev/null 2>&1 || true
108
+ elif command -v apk >/dev/null 2>&1; then
109
+ $SUDO_CMD apk add --no-cache -q unzip >/dev/null 2>&1 || true
110
+ elif command -v pacman >/dev/null 2>&1; then
111
+ $SUDO_CMD pacman -Sy --noconfirm unzip >/dev/null 2>&1 || true
112
+ fi
113
+ fi
114
+ fi
115
+ if command -v curl >/dev/null 2>&1; then
116
+ if ! curl -fsSL https://bun.sh/install | bash >/tmp/ofb-bun-install.log 2>&1; then
117
+ warn "Bun installation failed. Log:"
118
+ tail -5 /tmp/ofb-bun-install.log >&2 2>/dev/null || true
119
+ die "install Bun manually: https://bun.sh"
120
+ fi
121
+ elif command -v wget >/dev/null 2>&1; then
122
+ if ! wget -qO- https://bun.sh/install | bash >/tmp/ofb-bun-install.log 2>&1; then
123
+ warn "Bun installation failed. Log:"
124
+ tail -5 /tmp/ofb-bun-install.log >&2 2>/dev/null || true
125
+ die "install Bun manually: https://bun.sh"
126
+ fi
127
+ else
128
+ die "neither curl nor wget is available, so Bun cannot be installed. Install Bun manually: https://bun.sh"
129
+ fi
130
+ rm -f /tmp/ofb-bun-install.log
131
+ if ! BUN_BIN="$(find_bun)"; then
132
+ die "Bun was installed but cannot be found in ~/.bun/bin. Open a new shell and re-run this installer."
133
+ fi
134
+ RUNTIME="$BUN_BIN"
135
+ say "runtime: bun ($("$RUNTIME" --version)) — installed by this script"
136
+ fi
137
+ # Bun has no version gate here: the bridge uses only long-stable APIs, and Bun
138
+ # 1.4.2 (the CLI's own bundled version) and 1.4.3 were both verified. Node does.
139
+ if [ "$(basename "$RUNTIME")" = "node" ]; then
140
+ NODE_MAJOR="$(node -p 'process.versions.node.split(".")[0]')"
141
+ [ "$NODE_MAJOR" -ge 18 ] || die "Node.js >= 18 required (found $(node -v))"
142
+ fi
143
+
144
+ # -------------------------------------------------------------- migration ---
145
+ # Upgrading from 1.x or early 2.x means three things change underneath:
146
+ #
147
+ # * the runtime (node -> bun), so any service unit still says `node`
148
+ # * the file set (identity.ts and the transport tools are new), so a partial
149
+ # copy from an older installer leaves a bridge that cannot start
150
+ # * the transport itself, so an old install that "worked" now needs Bun to
151
+ # get anything but 403
152
+ #
153
+ # The old files are moved aside rather than deleted, so a failed upgrade can be
154
+ # undone by hand.
155
+ PREV_VERSION=""
156
+ if [ -f "$BINDIR/package.json" ]; then
157
+ PREV_VERSION="$("$RUNTIME" -e 'try{process.stdout.write(require(process.argv[1]).version||"")}catch{}' "$BINDIR/package.json" 2>/dev/null || true)"
158
+ fi
159
+ if [ -n "$PREV_VERSION" ]; then
160
+ say "Found existing install: v$PREV_VERSION in $BINDIR"
161
+ BACKUP="$BINDIR/.backup-v$PREV_VERSION-$(date +%Y%m%d%H%M%S)"
162
+ mkdir -p "$BACKUP"
163
+ for f in server.ts identity.ts token-budget.ts verify.ts gate-drill.ts transport-fingerprint.ts transport-baseline.json package.json tunnel-doctor.sh proxy.ts panel.ts egress-proxy.ts anthropic.ts THIRD_PARTY_NOTICES.md; do
164
+ [ -f "$BINDIR/$f" ] && cp -p "$BINDIR/$f" "$BACKUP/$f" 2>/dev/null || true
165
+ done
166
+ say "Backed up to $BACKUP"
167
+ if [ -f "$BINDIR/server.ts" ] && ! grep -q '#!/usr/bin/env bun' "$BINDIR/server.ts" 2>/dev/null; then
168
+ say "Old install ran on Node; this version requires Bun for the live gate"
169
+ fi
170
+ fi
171
+
172
+ # A service unit written by an older installer still points at `node`, which
173
+ # would silently keep failing after the upgrade. Rewrite it if we can.
174
+ migrate_service_runtime() {
175
+ local unit esc_runtime esc_bindir
176
+ esc_runtime="$(printf '%s' "$RUNTIME" | sed 's/[\\&|]/\\&/g')"
177
+ esc_bindir="$(printf '%s' "$BINDIR" | sed 's/[\\&|]/\\&/g')"
178
+ for unit in "/etc/systemd/system/opencode-free-bridge.service" \
179
+ "$HOME/.config/systemd/user/opencode-free-bridge.service"; do
180
+ [ -f "$unit" ] || continue
181
+ if grep -q 'ExecStart=.*node' "$unit" 2>/dev/null; then
182
+ sed -i.bak -E "s|^ExecStart=.*|ExecStart=\"$esc_runtime\" \"$esc_bindir/server.ts\"|" "$unit" 2>/dev/null || {
183
+ warn "could not rewrite $unit — update ExecStart to: \"$RUNTIME\" \"$BINDIR/server.ts\""
184
+ continue
185
+ }
186
+ say "Service unit updated to run under $(basename "$RUNTIME"): $unit"
187
+ if [ "${unit#/etc}" != "$unit" ]; then
188
+ systemctl daemon-reload 2>/dev/null || true
189
+ else
190
+ systemctl --user daemon-reload 2>/dev/null || true
191
+ fi
192
+ fi
193
+ done
194
+ local plist="$HOME/Library/LaunchAgents/com.opencode-free-bridge.plist"
195
+ if [ -f "$plist" ] && grep -q '<string>.*node</string>' "$plist" 2>/dev/null; then
196
+ sed -i.bak -E "s|<string>[^<]*node</string>|<string>$esc_runtime</string>|" "$plist" 2>/dev/null || true
197
+ say "launchd agent updated to run under $(basename "$RUNTIME")"
198
+ fi
199
+ }
200
+ migrate_service_runtime
201
+
202
+ # ------------------------------------------------------- legacy retirement ---
203
+ # Releases before v2.0 registered `opencode-bridge.service`, not
204
+ # `opencode-free-bridge.service`. Both bind the same port, so leaving the old
205
+ # unit enabled makes the new service fail with EADDRINUSE and restart-loop
206
+ # forever. A user who finds this repo and re-runs the installer on a machine
207
+ # that still has the old bridge should get an upgrade, not a port fight.
208
+ port_holder() {
209
+ if command -v ss >/dev/null 2>&1; then
210
+ ss -tlnp 2>/dev/null | awk -v p=":$PORT$" '$4 ~ p {print; exit}'
211
+ return 0
212
+ fi
213
+ if command -v lsof >/dev/null 2>&1; then
214
+ lsof -nP -iTCP:"$PORT" -sTCP:LISTEN 2>/dev/null | awk 'NR==2 {print; exit}'
215
+ return 0
216
+ fi
217
+ return 0
218
+ }
219
+
220
+ legacy_unit_active() {
221
+ systemctl is-active --quiet opencode-bridge 2>/dev/null && return 0
222
+ systemctl --user is-active --quiet opencode-bridge 2>/dev/null && return 0
223
+ return 1
224
+ }
225
+
226
+ # Is the port held by the bridge this installer is about to replace? Re-running
227
+ # the installer on an existing install must work, so the bridge's own process
228
+ # is not a conflict. Anything else is.
229
+ #
230
+ # Note the `|| true`: the installer runs under `set -euo pipefail`, and a
231
+ # pipeline whose `grep` finds nothing exits 1, which would abort the whole
232
+ # install with no message. Every probe here must be allowed to come up empty.
233
+ pid_on_port() {
234
+ local pid
235
+ pid="$(port_holder | grep -oP 'pid=\K[0-9]+' | head -1 || true)"
236
+ if [ -z "$pid" ]; then
237
+ pid="$(port_holder | sed -n 's/.*pid=\([0-9][0-9]*\).*/\1/p' | head -1 || true)"
238
+ fi
239
+ if [ -z "$pid" ] && command -v lsof >/dev/null 2>&1; then
240
+ pid="$(lsof -nP -t -iTCP:"$PORT" -sTCP:LISTEN 2>/dev/null | head -1 || true)"
241
+ fi
242
+ printf '%s\n' "$pid"
243
+ }
244
+
245
+ port_held_by_own_bridge() {
246
+ local pid cwd target
247
+ pid="$(pid_on_port)"
248
+ [ -n "$pid" ] || return 1
249
+
250
+ # The detached bridge is started with `bun server.ts` after a pushd, so its
251
+ # cmdline is relative and only the cwd identifies it. readlink appends
252
+ # " (deleted)" once the install directory has been replaced, which must not
253
+ # defeat the match.
254
+ cwd="$(readlink -f "/proc/$pid/cwd" 2>/dev/null | sed 's/ (deleted)$//' || true)"
255
+ target="$(readlink -f "$BINDIR" 2>/dev/null || printf '%s' "$BINDIR")"
256
+ [ -n "$cwd" ] && [ -n "$target" ] && [ "$cwd" = "$target" ] && return 0
257
+
258
+ tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null | grep -qF "$BINDIR/server.ts" && return 0
259
+ ps -p "$pid" -o command= 2>/dev/null | grep -qF "$BINDIR/server.ts" && return 0
260
+ command -v lsof >/dev/null 2>&1 && lsof -a -p "$pid" -d cwd -Fn 2>/dev/null | grep -qF "n$target" && return 0
261
+ return 1
262
+ }
263
+
264
+ stop_own_bridge() {
265
+ local pid
266
+ pid="$(pid_on_port)"
267
+ [ -n "$pid" ] || return 0
268
+
269
+ # If systemd supervises this bridge, stop it through systemd. Killing the pid
270
+ # directly would be undone immediately by Restart=always.
271
+ if systemctl is-active --quiet opencode-free-bridge 2>/dev/null; then
272
+ say "Stopping the running bridge service to replace it"
273
+ systemctl stop opencode-free-bridge 2>/dev/null || true
274
+ return 0
275
+ fi
276
+ if systemctl --user is-active --quiet opencode-free-bridge 2>/dev/null; then
277
+ say "Stopping the running bridge service to replace it"
278
+ systemctl --user stop opencode-free-bridge 2>/dev/null || true
279
+ return 0
280
+ fi
281
+
282
+ say "Stopping the running bridge (pid $pid) to replace it"
283
+ kill "$pid" 2>/dev/null || true
284
+ for _ in $(seq 1 20); do
285
+ kill -0 "$pid" 2>/dev/null || return 0
286
+ sleep 0.25
287
+ done
288
+ kill -9 "$pid" 2>/dev/null || true
289
+ }
290
+
291
+ # Decide before touching anything. If a stranger owns the port, stopping the
292
+ # user's working bridge first would leave them with nothing at all.
293
+ if [ -n "$(port_holder)" ] && ! legacy_unit_active && ! port_held_by_own_bridge; then
294
+ warn "port $PORT is already in use:"
295
+ warn " $(port_holder)"
296
+ warn "Nothing was changed. Either stop that process, or install on another port:"
297
+ warn " PORT=20130 bash install.sh"
298
+ die "port $PORT is occupied by another process"
299
+ fi
300
+
301
+ retire_legacy_service() {
302
+ local name="opencode-bridge.service"
303
+ local stamp retired=0
304
+ stamp="$(date +%Y%m%d%H%M%S)"
305
+
306
+ if [ -f "/etc/systemd/system/$name" ] || systemctl cat "$name" >/dev/null 2>&1; then
307
+ if systemctl is-active --quiet "$name" 2>/dev/null; then
308
+ systemctl stop "$name" 2>/dev/null && retired=1
309
+ fi
310
+ systemctl disable "$name" >/dev/null 2>&1 || true
311
+ if [ -f "/etc/systemd/system/$name" ]; then
312
+ mv -f "/etc/systemd/system/$name" "/etc/systemd/system/$name.retired-$stamp" 2>/dev/null || true
313
+ fi
314
+ rm -f "/etc/systemd/system/multi-user.target.wants/$name" 2>/dev/null || true
315
+ systemctl daemon-reload 2>/dev/null || true
316
+ say "Retired legacy unit $name (it held the old bridge on port $PORT)"
317
+ fi
318
+
319
+ if [ -f "$HOME/.config/systemd/user/$name" ]; then
320
+ systemctl --user stop "$name" 2>/dev/null || true
321
+ systemctl --user disable "$name" >/dev/null 2>&1 || true
322
+ mv -f "$HOME/.config/systemd/user/$name" "$HOME/.config/systemd/user/$name.retired-$stamp" 2>/dev/null || true
323
+ rm -f "$HOME/.config/systemd/user/default.target.wants/$name" 2>/dev/null || true
324
+ systemctl --user daemon-reload 2>/dev/null || true
325
+ say "Retired legacy user unit $name"
326
+ fi
327
+
328
+ # Let the old process release the listening socket before the new service
329
+ # tries to bind it.
330
+ if [ "$retired" = "1" ]; then sleep 1; fi
331
+ }
332
+
333
+ # ------------------------------------------------------------------ fetch ---
334
+ # Everything is staged and syntax-checked *before* the running bridge is
335
+ # touched. A network failure halfway through an upgrade therefore leaves the old
336
+ # bridge serving traffic instead of leaving the user with a stopped service and
337
+ # a half-written install.
338
+ #
339
+ # Source selection: a clone of this repo installs its own working tree. That is
340
+ # what `bash install.sh` inside a checkout means, and it is the only way to
341
+ # install a commit that has not been pushed yet (the curl route fetched from
342
+ # GitHub and 404'd on files that existed only locally). Set SOURCE=remote to
343
+ # force the download path from inside a clone.
344
+ RAW="https://raw.githubusercontent.com/${REPO}/${BRANCH}"
345
+ SOURCE="${SOURCE:-auto}"
346
+ SRC_DIR=""
347
+ if [ "$SOURCE" = "auto" ]; then
348
+ if [ -f "$SCRIPT_DIR/server.ts" ] && [ -f "$SCRIPT_DIR/package.json" ]; then
349
+ SOURCE="local"
350
+ else
351
+ SOURCE="remote"
352
+ fi
353
+ fi
354
+ if [ "$SOURCE" = "local" ]; then
355
+ SRC_DIR="$SCRIPT_DIR"
356
+ say "Source: local checkout ($SRC_DIR)"
357
+ elif [ "$SOURCE" = "remote" ]; then
358
+ say "Source: ${RAW}"
359
+ else
360
+ die "Invalid SOURCE: $SOURCE (expected auto, local, or remote)"
361
+ fi
362
+
363
+ mkdir -p "$BINDIR"
364
+ STAGE="$(mktemp -d "${TMPDIR:-/tmp}/ofb-stage.XXXXXX")"
365
+ cleanup_stage() { rm -rf "$STAGE" 2>/dev/null || true; }
366
+ trap cleanup_stage EXIT
367
+ say "Installing into $BINDIR"
368
+
369
+ fetch() {
370
+ local file="$1"
371
+ local tmp="$STAGE/$file"
372
+ if [ "$SOURCE" = "local" ]; then
373
+ [ -f "$SRC_DIR/$file" ] || die "$file is missing from the local checkout ($SRC_DIR)"
374
+ cp -p "$SRC_DIR/$file" "$tmp"
375
+ return 0
376
+ fi
377
+ # raw.githubusercontent.com sits behind a CDN that can serve the previous
378
+ # commit for a while after a push. A stale install.sh is harmless (it already
379
+ # ran) but a stale server.ts next to a fresh identity.ts is not. The query
380
+ # string is ignored by the server and defeats the cache.
381
+ local url="$RAW/$file?cb=$(date +%s)"
382
+ if command -v curl >/dev/null 2>&1; then
383
+ # A bare `curl: (22)` names neither the file nor the reason. Say which one,
384
+ # because the usual cause is a release that lists a file it never pushed.
385
+ curl -fsSL --retry 3 -H 'Cache-Control: no-cache' -o "$tmp" "$url" \
386
+ || die "could not download $file from $RAW (HTTP error above). The release may be missing this file; retry with SOURCE=local from a checkout."
387
+ elif command -v wget >/dev/null 2>&1; then
388
+ wget -qO "$tmp" "$url" \
389
+ || die "could not download $file from $RAW. The release may be missing this file; retry with SOURCE=local from a checkout."
390
+ else
391
+ die "neither curl nor wget is available"
392
+ fi
393
+ [ -s "$tmp" ] || die "downloaded $file is empty"
394
+ }
395
+
396
+
397
+ fetch package.json
398
+ fetch server.ts
399
+ fetch identity.ts
400
+ fetch token-budget.ts
401
+ fetch verify.ts
402
+ fetch gate-drill.ts
403
+ fetch transport-fingerprint.ts
404
+ fetch transport-baseline.json
405
+ fetch tunnel-doctor.sh
406
+ fetch proxy.ts
407
+ fetch panel.ts
408
+ fetch egress-proxy.ts
409
+ fetch anthropic.ts
410
+
411
+ # A syntactically broken release must never replace a working install.
412
+ #
413
+ # `bun --check` does NOT mean "parse only": Bun has no --check flag, so it
414
+ # treats the file as the entrypoint and *runs* it. That started a second server
415
+ # during an install and, worse, made every upgrade abort with "failed a syntax
416
+ # check". Parse the source instead: Bun.Transpiler compiles TypeScript without
417
+ # executing it, and `new Function` remains the fallback on a Node runtime.
418
+ syntax_check() {
419
+ "$RUNTIME" -e '
420
+ const fs = require("fs");
421
+ const src = fs.readFileSync(process.argv[1], "utf8").replace(/^#!.*\n/, "");
422
+ try {
423
+ if (typeof Bun !== "undefined" && Bun.Transpiler) new Bun.Transpiler({ loader: "ts" }).transformSync(src);
424
+ else new Function(src);
425
+ } catch (err) { console.error(err.message); process.exit(1); }
426
+ ' "$1"
427
+ }
428
+
429
+ for ts in server.ts identity.ts token-budget.ts verify.ts gate-drill.ts transport-fingerprint.ts proxy.ts panel.ts egress-proxy.ts anthropic.ts; do
430
+ syntax_check "$STAGE/$ts" >/dev/null 2>&1 || die "$ts failed a syntax check; the running bridge was left untouched"
431
+ done
432
+ for json in package.json transport-baseline.json; do
433
+ "$RUNTIME" -e 'JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"))' "$STAGE/$json" \
434
+ || die "$json is not valid JSON; the running bridge was left untouched"
435
+ done
436
+ # tunnel-doctor.sh is bash, not JS, so `new Function` cannot check it. `bash -n`
437
+ # parses without executing, which is exactly the guarantee we need here.
438
+ if [ -f "$STAGE/tunnel-doctor.sh" ]; then
439
+ if command -v bash >/dev/null 2>&1; then
440
+ bash -n "$STAGE/tunnel-doctor.sh" || die "tunnel-doctor.sh failed a syntax check; the running bridge was left untouched"
441
+ fi
442
+ fi
443
+
444
+ # Staged and validated. Only now is it safe to stop the old bridge.
445
+ retire_legacy_service
446
+ stop_own_bridge
447
+
448
+ # The old process releases the socket asynchronously after SIGTERM. Wait for it
449
+ # instead of racing the bind, and report clearly if it never happens.
450
+ for _ in $(seq 1 10); do
451
+ [ -z "$(port_holder)" ] && break
452
+ sleep 0.5
453
+ done
454
+ if [ -n "$(port_holder)" ]; then
455
+ warn "port $PORT is still held after stopping the old bridge:"
456
+ warn " $(port_holder)"
457
+ die "cannot bind port $PORT"
458
+ fi
459
+
460
+ for file in package.json server.ts identity.ts token-budget.ts verify.ts gate-drill.ts transport-fingerprint.ts transport-baseline.json tunnel-doctor.sh proxy.ts panel.ts egress-proxy.ts anthropic.ts THIRD_PARTY_NOTICES.md; do
461
+ [ -f "$STAGE/$file" ] && mv -f "$STAGE/$file" "$BINDIR/$file"
462
+ done
463
+ chmod +x "$BINDIR/server.ts" "$BINDIR/identity.ts" "$BINDIR/verify.ts" "$BINDIR/gate-drill.ts" "$BINDIR/transport-fingerprint.ts" "$BINDIR/tunnel-doctor.sh" "$BINDIR/egress-proxy.ts" 2>/dev/null || true
464
+ say "Files installed (v$("$RUNTIME" -e 'try{process.stdout.write(require(process.argv[1]).version||"latest")}catch{process.stdout.write("latest")}' "$BINDIR/package.json" 2>/dev/null || echo 'latest'))"
465
+
466
+ # ---------------------------------------------------------------- service ---
467
+ SERVICE_SCOPE="none"
468
+ install_service() {
469
+ local os
470
+ os="$(uname -s | tr '[:upper:]' '[:lower:]')"
471
+
472
+ if [ "$os" = "linux" ] && command -v systemctl >/dev/null 2>&1; then
473
+ local unit_dir="/etc/systemd/system"
474
+ local unit="$unit_dir/opencode-free-bridge.service"
475
+ if [ -w "$unit_dir" ]; then
476
+ cat > "$unit" <<UNIT
477
+ [Unit]
478
+ Description=OpenCode Free Bridge (OpenAI/Anthropic-compatible, free-tier models)
479
+ After=network-online.target
480
+ Wants=network-online.target
481
+
482
+ [Service]
483
+ Type=simple
484
+ User=$(id -un)
485
+ WorkingDirectory=$BINDIR
486
+ Environment=PORT=$PORT
487
+ Environment=HOST=$HOST
488
+ ExecStart="$RUNTIME" "$BINDIR/server.ts"
489
+ Restart=always
490
+ RestartSec=3
491
+ MemoryMax=512M
492
+
493
+ [Install]
494
+ WantedBy=multi-user.target
495
+ UNIT
496
+ systemctl daemon-reload
497
+ systemctl enable opencode-free-bridge >/dev/null 2>&1 || true
498
+ if ! systemctl restart opencode-free-bridge; then
499
+ warn "systemd refused to start opencode-free-bridge — inspect: systemctl status opencode-free-bridge"
500
+ return 1
501
+ fi
502
+ SERVICE_SCOPE="system"
503
+ say "systemd service installed and restarted"
504
+ return 0
505
+ elif systemctl --user status >/dev/null 2>&1; then
506
+ local user_unit_dir="$HOME/.config/systemd/user"
507
+ local user_unit="$user_unit_dir/opencode-free-bridge.service"
508
+ mkdir -p "$user_unit_dir"
509
+ cat > "$user_unit" <<UNIT
510
+ [Unit]
511
+ Description=OpenCode Free Bridge (OpenAI/Anthropic-compatible, free-tier models)
512
+ After=network-online.target
513
+
514
+ [Service]
515
+ Type=simple
516
+ WorkingDirectory=$BINDIR
517
+ Environment=PORT=$PORT
518
+ Environment=HOST=$HOST
519
+ ExecStart="$RUNTIME" "$BINDIR/server.ts"
520
+ Restart=always
521
+ RestartSec=3
522
+ MemoryMax=512M
523
+ [Install]
524
+ WantedBy=default.target
525
+ UNIT
526
+ systemctl --user daemon-reload
527
+ systemctl --user enable opencode-free-bridge >/dev/null 2>&1 || true
528
+ if ! systemctl --user restart opencode-free-bridge; then
529
+ warn "systemd --user refused to start opencode-free-bridge — inspect: systemctl --user status opencode-free-bridge"
530
+ return 1
531
+ fi
532
+ SERVICE_SCOPE="user"
533
+ command -v loginctl >/dev/null 2>&1 && loginctl enable-linger "$(id -un)" >/dev/null 2>&1 || true
534
+ say "systemd --user service installed and restarted"
535
+ return 0
536
+ else
537
+ warn "no write access to $unit_dir — skipping service install (run with sudo to enable it)"
538
+ return 1
539
+ fi
540
+ fi
541
+
542
+ if [ "$os" = "darwin" ]; then
543
+ local plist="$HOME/Library/LaunchAgents/com.opencode-free-bridge.plist"
544
+ mkdir -p "$(dirname "$plist")"
545
+ cat > "$plist" <<PLIST
546
+ <?xml version="1.0" encoding="UTF-8"?>
547
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
548
+ <plist version="1.0">
549
+ <dict>
550
+ <key>Label</key><string>com.opencode-free-bridge</string>
551
+ <key>ProgramArguments</key>
552
+ <array><string>$RUNTIME</string><string>$BINDIR/server.ts</string></array>
553
+ <key>WorkingDirectory</key><string>$BINDIR</string>
554
+ <key>EnvironmentVariables</key>
555
+ <dict><key>PORT</key><string>$PORT</string><key>HOST</key><string>$HOST</string></dict>
556
+ <key>StandardOutPath</key><string>$HOME/Library/Logs/opencode-free-bridge.log</string>
557
+ <key>StandardErrorPath</key><string>$HOME/Library/Logs/opencode-free-bridge.log</string>
558
+ <key>RunAtLoad</key><true/>
559
+ <key>KeepAlive</key><true/>
560
+ </dict>
561
+ </plist>
562
+ PLIST
563
+ mkdir -p "$HOME/Library/Logs"
564
+ launchctl unload "$plist" >/dev/null 2>&1 || true
565
+ launchctl load "$plist"
566
+ SERVICE_SCOPE="launchd"
567
+ say "launchd agent installed and restarted"
568
+ return 0
569
+ fi
570
+
571
+ warn "no supported service manager found — start it manually: PORT=$PORT $RUNTIME $BINDIR/server.ts"
572
+ return 1
573
+ }
574
+
575
+ SERVICE_OK=1
576
+ if [ "${NO_SERVICE:-0}" != "1" ]; then
577
+ install_service || SERVICE_OK=0
578
+ else
579
+ SERVICE_OK=0
580
+ fi
581
+
582
+ # ------------------------------------------------------------ start check ---
583
+ if [ "$SERVICE_OK" != "1" ]; then
584
+ say "Starting in the background (no service manager)"
585
+ pkill -f -- "$BINDIR/server.ts" 2>/dev/null || true
586
+ sleep 0.5
587
+ # Two things matter here, and both were measured:
588
+ #
589
+ # * No subshell. `( ... & )` leaves bash waiting on the child, so a piped
590
+ # installer blocks until the bridge exits — 70s in a minimal repro, and a
591
+ # real install that never returned.
592
+ # * setsid + stdin from /dev/null, so the child owns no descriptor of the
593
+ # caller's terminal or pipe.
594
+ #
595
+ # pushd/popd changes directory without forking. Measured: 0.004s.
596
+ pushd "$BINDIR" >/dev/null
597
+ if command -v setsid >/dev/null 2>&1; then
598
+ setsid env PORT="$PORT" HOST="$HOST" "$RUNTIME" server.ts </dev/null >"$BINDIR/bridge.log" 2>&1 &
599
+ else
600
+ env PORT="$PORT" HOST="$HOST" nohup "$RUNTIME" server.ts </dev/null >"$BINDIR/bridge.log" 2>&1 &
601
+ fi
602
+ disown 2>/dev/null || true
603
+ popd >/dev/null
604
+ fi
605
+
606
+ PROBE_HOST="$HOST"
607
+ if [ "$PROBE_HOST" = "0.0.0.0" ] || [ "$PROBE_HOST" = "::" ]; then
608
+ PROBE_HOST="127.0.0.1"
609
+ fi
610
+
611
+ probe_health() {
612
+ if command -v curl >/dev/null 2>&1; then
613
+ curl -fsS -m 2 "http://$PROBE_HOST:$PORT/health" >/dev/null 2>&1
614
+ else
615
+ "$RUNTIME" -e 'fetch(process.argv[1],{signal:AbortSignal.timeout(2000)}).then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))' "http://$PROBE_HOST:$PORT/health" >/dev/null 2>&1
616
+ fi
617
+ }
618
+
619
+ say "Waiting for the bridge to come up..."
620
+ BRIDGE_UP=0
621
+ for _ in $(seq 1 20); do
622
+ # -m matters: a HOST that is not routable makes curl hang for minutes, and
623
+ # the installer used to sit there until the user killed it.
624
+ if probe_health; then BRIDGE_UP=1; break; fi
625
+ sleep 1
626
+ done
627
+
628
+ if [ "$BRIDGE_UP" != "1" ]; then
629
+ warn "the bridge did not answer on http://$PROBE_HOST:$PORT/health after 20s"
630
+ if [ "$SERVICE_OK" = "1" ]; then
631
+ if [ "$SERVICE_SCOPE" = "user" ]; then
632
+ warn "inspect: systemctl --user status opencode-free-bridge ; journalctl --user -u opencode-free-bridge -n 30"
633
+ else
634
+ warn "inspect: systemctl status opencode-free-bridge ; journalctl -u opencode-free-bridge -n 30"
635
+ fi
636
+ else
637
+ warn "inspect: $BINDIR/bridge.log"
638
+ fi
639
+ die "install finished but the service is not running"
640
+ fi
641
+ say "Bridge is answering on http://$PROBE_HOST:$PORT"
642
+
643
+ echo
644
+ say "Running self-check (quick — full check: $RUNTIME $BINDIR/verify.ts)"
645
+ echo
646
+ # Bounded on purpose: the self-check talks to a live upstream that can throttle.
647
+ # Without a hard cap, a slow upstream makes the installer look hung, and the user
648
+ # kills it before the service is registered.
649
+ if command -v timeout >/dev/null 2>&1; then
650
+ set +e
651
+ PORT="$PORT" HOST="$HOST" timeout 120 "$RUNTIME" "$BINDIR/verify.ts" --quick
652
+ CHECK_RC=$?
653
+ set -e
654
+ else
655
+ set +e
656
+ PORT="$PORT" HOST="$HOST" "$RUNTIME" "$BINDIR/verify.ts" --quick
657
+ CHECK_RC=$?
658
+ set -e
659
+ fi
660
+ case "$CHECK_RC" in
661
+ 0) ;;
662
+ 2) warn "the bridge is installed and healthy, but upstream refused this IP (free-tier allowance or an abuse block)"
663
+ warn "the official OpenCode CLI gets the same refusal from this network; the self-check above says which one"
664
+ warn "re-check later with the command below" ;;
665
+ 124) warn "self-check hit the 120s cap; the bridge is installed, run the check again when upstream is responsive" ;;
666
+ *) warn "self-check reported a problem; inspect the log with the command below" ;;
667
+ esac
668
+
669
+ # The TLS fingerprint is the gate. An outdated Bun installs and starts happily
670
+ # and then earns a 403 that looks exactly like an exhausted IP allowance, so
671
+ # check it here rather than letting the user debug the wrong thing.
672
+ if [ -f "$BINDIR/transport-fingerprint.ts" ] && [ -f "$BINDIR/transport-baseline.json" ]; then
673
+ set +e
674
+ ( cd "$BINDIR" && "$RUNTIME" transport-fingerprint.ts --check >/dev/null 2>&1 )
675
+ TLS_RC=$?
676
+ set -e
677
+ if [ "$TLS_RC" != "0" ]; then
678
+ warn "this Bun build's TLS ClientHello does not match the recorded OpenCode CLI baseline"
679
+ warn "upstream inspects that fingerprint; expect 403 until it matches."
680
+ warn "inspect: cd $BINDIR && $RUNTIME transport-fingerprint.ts --check"
681
+ fi
682
+ fi
683
+
684
+ echo
685
+ say "Done."
686
+ cat <<NEXT
687
+
688
+ Endpoint : http://$PROBE_HOST:$PORT/v1
689
+ API key : public (any value is accepted)
690
+ Models : curl http://$PROBE_HOST:$PORT/v1/models
691
+
692
+ Add it to 9Router, Cursor, Continue, or any OpenAI-compatible client as a
693
+ custom provider. Re-run the self-check any time with:
694
+
695
+ "$RUNTIME" $BINDIR/verify.ts
696
+
697
+ NEXT
698
+
699
+ if [ "$SERVICE_OK" = "1" ]; then
700
+ if [ "$SERVICE_SCOPE" = "user" ]; then
701
+ echo " Logs : journalctl --user -u opencode-free-bridge -f"
702
+ elif [ "$SERVICE_SCOPE" = "system" ]; then
703
+ echo " Logs : journalctl -u opencode-free-bridge -f"
704
+ else
705
+ echo " Logs : tail -f ~/Library/Logs/opencode-free-bridge.log"
706
+ fi
707
+ fi
708
+ echo