#!/bin/sh # Per-user pinned-Node runtime installer for Wingman (macOS and Linux). # Installs an official pinned Node.js LTS runtime and Wingman JS into # ~/.wingman/runtime/ with SHA-256 verification (fail closed), atomic swap, # rollback, a stable ~/.wingman/bin/wingman launcher, and uninstall support. # # Boundaries: # - Requires no administrator/root privileges. # - Never edits AI client MCP configs, shell profiles, or login autostart. # - Run ~/.wingman/bin/wingman setup explicitly afterwards to configure clients. set -eu umask 077 PINNED_NODE_VERSION="v24.22.3" PINNED_WINGMAN_VERSION="3.0.0" WINGMAN_PACKAGE="@scylax.ai/wingman" DEFAULT_NODE_BASE_URL="https://nodejs.org/dist" # Official SHA-256 checksums from https://nodejs.org/dist/v24.22.3/SHASUMS256.txt # Kept in sync with packaging/runtime/node-runtime.json. SHA256_DARWIN_ARM64="ff6e17d4874b76d272212b908cc020d6e815fba5a6c7eaaa06add725840307fd" SHA256_DARWIN_X64="977614af0504c81045e7fd85596dbca0e5f951b96681516dadafedcca8c447f7" SHA256_LINUX_ARM64="261af2af250dfd7e9f25cf151d1b2713a0adf8f10a9ad116c4947f68627affe8" SHA256_LINUX_X64="061ec3e3062115705b56b51fa9cc330ab50d34b6969387d4e4b1a50c6809acc2" ACTION="install" NODE_VERSION="$PINNED_NODE_VERSION" WINGMAN_VERSION="$PINNED_WINGMAN_VERSION" NODE_BASE_URL="$DEFAULT_NODE_BASE_URL" NODE_SHA256="" CHECKSUMS_FILE="" WINGMAN_URL="" WINGMAN_SHA256="" NPM_REGISTRY="" RUNTIME_ID="" WINGMAN_HOME="${WINGMAN_HOME:-}" ALLOW_LOOPBACK_HTTP=0 STAGE_DIR="" TMP_LINK="" TMP_LAUNCHER="" LOCK_DIR="" LOCK_OWNED=0 LOCK_TOKEN="$$-$(date +%s 2>/dev/null || echo 0)" DOWNLOAD_PID="" VERIFY_PID="" # Swap rollback state: if an error or signal interrupts between promoting/swapping # `current` and completing post-swap verification, cleanup() rolls back cleanly. SWAP_PENDING=0 SWAP_OLD_CURR="" SWAP_NEW_DIR="" ROLLBACK_PENDING=0 ROLLBACK_OLD_CURR="" usage() { cat <<'EOF' Usage: install.sh [options] Installs Wingman with a per-user pinned Node.js LTS runtime under ~/.wingman/runtime/ and creates a stable ~/.wingman/bin/wingman launcher. No admin access required. Never edits client configs, shell rc files, or autostart. Actions: (default) Install or upgrade the pinned runtime atomically --rollback Atomically switch ~/.wingman/runtime/current back to previous --uninstall Remove ~/.wingman/bin/wingman and ~/.wingman/runtime --help, -h Show this help Options: --wingman-home Override ~/.wingman (default: $HOME/.wingman) --node-version Node.js version to install (default: v24.22.3) --node-base-url Node.js dist base URL (HTTPS required except loopback) --node-sha256 Expected SHA-256 for the Node.js archive --checksums-file Local SHA-256 checksums file ( ) --wingman-version Wingman version to install (default: 3.0.0) --wingman-url Direct Wingman JS .tar.gz/.tgz archive URL (requires SHA-256) --wingman-sha256 Expected SHA-256 for --wingman-url --npm-registry Custom npm registry URL when installing via npm --runtime-id Custom version directory under ~/.wingman/runtime/ --allow-loopback-http Test-only: allow plain HTTP strictly to 127.0.0.1/localhost/[::1] EOF } fail() { printf '[Wingman installer] ERROR: %s\n' "$1" >&2 exit 1 } info() { printf '[Wingman installer] %s\n' "$1" } restore_current_pointer() { old_target="$1" curr_link="$RUNTIME_ROOT/current" if [ -n "$old_target" ]; then restore_node="$RUNTIME_ROOT/$old_target/node/bin/node" atomic_swap_symlink "$restore_node" "$old_target" "$curr_link" 2>/dev/null || true else rm -f "$curr_link" 2>/dev/null || true fi } release_lock() { if [ "$LOCK_OWNED" = "1" ] && [ -n "$LOCK_DIR" ] && [ -d "$LOCK_DIR" ]; then owner_file="$LOCK_DIR/owner" if [ -f "$owner_file" ] && [ ! -L "$owner_file" ]; then recorded=$(cat "$owner_file" 2>/dev/null || true) if [ "$recorded" = "$LOCK_TOKEN" ]; then rm -f "$owner_file" 2>/dev/null || true rmdir "$LOCK_DIR" 2>/dev/null || true fi fi fi LOCK_OWNED=0 } cleanup() { rc="${1:-$?}" trap - EXIT INT TERM HUP if [ -n "$DOWNLOAD_PID" ]; then kill "$DOWNLOAD_PID" 2>/dev/null || true wait "$DOWNLOAD_PID" 2>/dev/null || true DOWNLOAD_PID="" fi if [ -n "$VERIFY_PID" ]; then kill "$VERIFY_PID" 2>/dev/null || true wait "$VERIFY_PID" 2>/dev/null || true VERIFY_PID="" fi if [ "$SWAP_PENDING" = "1" ]; then printf '[Wingman installer] Interrupted or failed during swap; rolling back...\n' >&2 rm -f "$RUNTIME_ROOT/.link-tmp-"* "$BIN_DIR/.wingman.tmp."* 2>/dev/null || true restore_current_pointer "$SWAP_OLD_CURR" if [ -n "$SWAP_NEW_DIR" ] && [ -d "$SWAP_NEW_DIR" ] && [ ! -L "$SWAP_NEW_DIR" ]; then rm -rf "$SWAP_NEW_DIR" 2>/dev/null || true fi SWAP_PENDING=0 fi if [ "$ROLLBACK_PENDING" = "1" ]; then printf '[Wingman installer] Interrupted or failed during rollback; restoring prior runtime...\n' >&2 rm -f "$RUNTIME_ROOT/.link-tmp-"* "$BIN_DIR/.wingman.tmp."* 2>/dev/null || true restore_current_pointer "$ROLLBACK_OLD_CURR" ROLLBACK_PENDING=0 fi if [ -n "$TMP_LINK" ] && [ -L "$TMP_LINK" -o -e "$TMP_LINK" ]; then rm -f "$TMP_LINK" 2>/dev/null || true fi if [ -n "$TMP_LAUNCHER" ] && [ -e "$TMP_LAUNCHER" ]; then rm -f "$TMP_LAUNCHER" 2>/dev/null || true fi if [ -n "$STAGE_DIR" ] && [ -d "$STAGE_DIR" ]; then rm -rf "$STAGE_DIR" 2>/dev/null || true fi release_lock exit "$rc" } trap cleanup EXIT trap 'cleanup 130' INT trap 'cleanup 143' TERM trap 'cleanup 129' HUP require_arg() { if [ "$#" -lt 2 ] || [ -z "$2" ]; then fail "Option $1 requires a non-empty value." fi } validate_safe_id() { label="$1" val="$2" if [ -z "$val" ] || [ "$val" = "." ] || [ "$val" = ".." ] || [ "$val" = "current" ] || [ "$val" = "previous" ]; then fail "Invalid $label: '$val'" fi case "$val" in .*|*[!A-Za-z0-9._-]*) fail "Invalid $label (must match [A-Za-z0-9][A-Za-z0-9._-]*): '$val'" ;; esac } validate_sha256_hex() { label="$1" val="$2" if [ "${#val}" -ne 64 ]; then fail "Invalid $label SHA-256 (must be 64 hex characters)." fi case "$val" in *[!0-9a-fA-F]*) fail "Invalid $label SHA-256 (contains non-hex characters)." ;; esac } # Parse and strictly validate a URL's scheme, authority, host, and optional port # before any network call. Rejects any userinfo (@), backslashes, whitespace, # malformed ports, or spoofed hostnames (e.g. localhost:80@evil, 127.0.0.1.evil). # Prints " " on stdout or returns non-zero. parse_url_meta() { _pum_url="$1" printf '%s\n' "$_pum_url" | awk ' NR > 1 { exit 1 } /[[:space:]\\]/ { exit 1 } { u = $0 if (u ~ /^https:\/\//) { scheme = "https" rest = substr(u, 9) } else if (u ~ /^http:\/\//) { scheme = "http" rest = substr(u, 8) } else { exit 1 } # Split authority from path/query/fragment auth = rest idx = match(rest, /[\/?#]/) if (idx > 0) { auth = substr(rest, 1, idx - 1) } if (auth == "") exit 1 # Strictly reject ANY userinfo (@) in authority if (index(auth, "@") > 0) exit 1 host = "" port = "" is_loopback = 0 if (substr(auth, 1, 1) == "[") { # Bracketed IPv6 literal: [addr] or [addr]:port rb = index(auth, "]") if (rb <= 2) exit 1 host = tolower(substr(auth, 2, rb - 2)) tail = substr(auth, rb + 1) # Reject dots (IPv4-mapped like ::ffff:127.0.0.1), zone IDs, or non-hex if (host !~ /^[0-9a-f:]+$/) exit 1 if (tail != "") { if (substr(tail, 1, 1) != ":") exit 1 port = substr(tail, 2) } if (host == "::1") is_loopback = 1 } else { # Hostname or IPv4: no brackets, at most one colon (for numeric port) if (index(auth, "[") > 0 || index(auth, "]") > 0) exit 1 col = index(auth, ":") if (col > 0) { host = tolower(substr(auth, 1, col - 1)) port = substr(auth, col + 1) if (port == "" || index(port, ":") > 0) exit 1 } else { host = tolower(auth) } if (host == "" || host !~ /^[a-z0-9.-]+$/) exit 1 if (substr(host, 1, 1) == "." || substr(host, length(host), 1) == ".") exit 1 if (index(host, "..") > 0) exit 1 if (host == "127.0.0.1" || host == "localhost") is_loopback = 1 } if (port != "") { if (port !~ /^[0-9]+$/ || length(port) > 5) exit 1 pnum = port + 0 if (pnum < 1 || pnum > 65535) exit 1 } printf "%s %d\n", scheme, is_loopback exit 0 } ' } is_loopback_http_url() { _ilh_meta=$(parse_url_meta "$1") || return 1 [ "$_ilh_meta" = "http 1" ] } validate_url() { _vu_label="$1" _vu_url="$2" _vu_meta=$(parse_url_meta "$_vu_url") \ || fail "$_vu_label is invalid or contains forbidden userinfo/host/port: $_vu_url" case "$_vu_meta" in "https "*) return 0 ;; "http 1") if [ "$ALLOW_LOOPBACK_HTTP" = "1" ]; then return 0 fi fail "$_vu_label must use https:// (pass --allow-loopback-http for local loopback fixture testing): $_vu_url" ;; *) fail "$_vu_label must use https:// (plain http:// is rejected): $_vu_url" ;; esac } validate_redirect_url() { _vru_next="$1" _vru_require_https="$2" _vru_meta=$(parse_url_meta "$_vru_next") \ || fail "Refusing malformed or userinfo redirect target: $_vru_next" case "$_vru_meta" in "https "*) return 0 ;; "http 1") if [ "$_vru_require_https" = "0" ] && [ "$ALLOW_LOOPBACK_HTTP" = "1" ]; then return 0 fi fail "Refusing non-HTTPS redirect target: $_vru_next" ;; *) fail "Refusing non-HTTPS redirect target: $_vru_next" ;; esac } url_origin() { printf '%s' "$1" | awk '{ if (match($0, /^https?:\/\/[^\/?#]+/)) { print substr($0, RSTART, RLENGTH) } }' } assert_not_symlink() { _sym_target="$1" if [ -L "$_sym_target" ]; then fail "Refusing to operate on symlink path: $_sym_target" fi } canonical_dir() { _cd_dir="$1" [ -d "$_cd_dir" ] || fail "Expected directory does not exist: $_cd_dir" assert_not_symlink "$_cd_dir" (CDPATH= cd -- "$_cd_dir" && pwd -P) } assert_confined_path() { _cp_base="$1" _cp_target="$2" _cp_real_base=$(canonical_dir "$_cp_base") assert_not_symlink "$_cp_target" _cp_parent=$(dirname "$_cp_target") assert_not_symlink "$_cp_parent" _cp_real_parent=$(canonical_dir "$_cp_parent") case "$_cp_real_parent" in "$_cp_real_base"|"$_cp_real_base"/*) ;; *) fail "Refusing path outside $_cp_real_base: $_cp_target" ;; esac if [ -d "$_cp_target" ]; then _cp_real_target=$(canonical_dir "$_cp_target") case "$_cp_real_target" in "$_cp_real_base"/*) ;; *) fail "Refusing directory outside $_cp_real_base: $_cp_target" ;; esac fi } ensure_private_dir() { dir="$1" assert_not_symlink "$dir" if [ ! -d "$dir" ]; then mkdir -p "$dir" fi chmod 0700 "$dir" } sha256_file() { file="$1" if command -v sha256sum >/dev/null 2>&1; then sha256sum "$file" | awk '{print tolower($1)}' elif command -v shasum >/dev/null 2>&1; then shasum -a 256 "$file" | awk '{print tolower($1)}' elif command -v openssl >/dev/null 2>&1; then openssl dgst -sha256 "$file" | awk '{print tolower($NF)}' else fail "No SHA-256 verification tool available (need sha256sum, shasum, or openssl); failing closed." fi } verify_sha256() { file="$1" expected_raw="$2" label="$3" validate_sha256_hex "$label" "$expected_raw" expected=$(printf '%s' "$expected_raw" | tr 'A-F' 'a-f') actual=$(sha256_file "$file") if [ "$actual" != "$expected" ]; then fail "SHA-256 mismatch for $label: expected $expected, got $actual" fi } lookup_checksum_file() { file="$1" filename="$2" [ -r "$file" ] || fail "Checksums file is not readable: $file" awk -v target="$filename" ' /^[[:space:]]*#/ || /^[[:space:]]*$/ { next } { name = $2 sub(/^\*/, "", name) if (name == target) { print $1 found = 1 exit 0 } } END { if (!found) exit 1 } ' "$file" 2>/dev/null || return 1 } download_file() { url="$1" dest="$2" validate_url "Download URL" "$url" require_https=1 if is_loopback_http_url "$url"; then require_https=0 fi current_url="$url" hops=0 headers_file="${dest}.headers" while :; do rm -f "$headers_file" "$dest" if [ "$require_https" = "1" ]; then curl_proto="=https" else curl_proto="=https,http" fi if command -v curl >/dev/null 2>&1; then # Enforce HTTPS-only redirects at both curl (--proto-redir '=https') and # manual hop-validation layers (no automatic redirects with --max-redirs 0). curl -fsS --connect-timeout 20 --max-time 300 \ --proto "$curl_proto" --proto-redir '=https' --max-redirs 0 \ -D "$headers_file" -o "$dest" "$current_url" & DOWNLOAD_PID=$! wait "$DOWNLOAD_PID" || { DOWNLOAD_PID=""; rm -f "$headers_file"; fail "Download failed: $current_url"; } DOWNLOAD_PID="" elif command -v wget >/dev/null 2>&1; then wget -q --server-response --max-redirect=0 --timeout=20 -O "$dest" "$current_url" 2>"$headers_file" & DOWNLOAD_PID=$! wget_rc=0 wait "$DOWNLOAD_PID" || wget_rc=$? DOWNLOAD_PID="" status_check=$(awk 'toupper($1) ~ /^HTTP\// { code=$2 } END { print code }' "$headers_file") case "$status_check" in 301|302|303|307|308) ;; *) if [ "$wget_rc" -ne 0 ]; then rm -f "$headers_file" fail "Download failed: $current_url" fi ;; esac else fail "Neither curl nor wget is installed; cannot download $current_url" fi http_status=$(awk 'toupper($1) ~ /^HTTP\// { code=$2 } END { print code }' "$headers_file") case "$http_status" in 301|302|303|307|308) hops=$((hops + 1)) if [ "$hops" -gt 5 ]; then rm -f "$headers_file" fail "Too many redirects while downloading: $url" fi location=$(awk '{ line = $0 sub(/\r$/, "", line) low = tolower(line) if (index(low, "location:") == 1) { val = substr(line, 10) sub(/^[[:space:]]+/, "", val) loc = val } } END { print loc }' "$headers_file") rm -f "$headers_file" [ -n "$location" ] || fail "Redirect missing Location header: $current_url" case "$location" in //*) fail "Refusing protocol-relative redirect Location: $location" ;; /*) origin=$(url_origin "$current_url") [ -n "$origin" ] || fail "Cannot resolve relative redirect from $current_url" next_url="${origin}${location}" ;; http://*|https://*) next_url="$location" ;; *) fail "Refusing unsupported redirect Location: $location" ;; esac validate_redirect_url "$next_url" "$require_https" current_url="$next_url" ;; 200|"") rm -f "$headers_file" break ;; *) rm -f "$headers_file" fail "Unexpected HTTP status $http_status downloading $current_url" ;; esac done [ -s "$dest" ] || fail "Downloaded file is empty: $url" } check_tar_safe() { archive="$1" strip_depth="${2:-0}" # 1. Refuse absolute paths or parent traversal components in entry names. bad_names=$(tar -tzf "$archive" | awk ' /^\// || /(^|\/)\.\.(\/|$)/ { print; exit 0 } ') if [ -n "$bad_names" ]; then fail "Refusing unsafe archive entry in $archive: $bad_names" fi # 2. Inspect entry types and symlink/hardlink targets before extraction. # Refuse hardlinks, device nodes, FIFOs, absolute symlinks, and any relative # symlink whose target climbs outside the extraction root. bad_links=$(tar -tvzf "$archive" | awk -v strip="$strip_depth" ' function check_rel_target(entry_name, link_target, parts, n, i, seg, depth, tparts, tn) { if (link_target ~ /^\//) return 0 # Normalize entry path, stripping leading ./ and optional strip_depth components sub(/^\.\//, "", entry_name) n = split(entry_name, parts, "/") depth = 0 # Walk parent directory components of entry_name (excluding the filename itself) for (i = 1 + strip; i < n; i++) { seg = parts[i] if (seg == "" || seg == ".") continue if (seg == "..") { depth-- if (depth < 0) return 0 } else { depth++ } } # Now walk link_target components from that parent depth tn = split(link_target, tparts, "/") for (i = 1; i <= tn; i++) { seg = tparts[i] if (seg == "" || seg == ".") continue if (seg == "..") { depth-- if (depth < 0) return 0 } else { depth++ } } return 1 } /^[bcp]/ { print "special-file: " $0; exit 0 } /^h/ { print "hardlink: " $0; exit 0 } / link to / { print "hardlink: " $0; exit 0 } /^l/ { idx = index($0, " -> ") if (idx == 0) { print "unparseable-symlink: " $0; exit 0 } left = substr($0, 1, idx - 1) target = substr($0, idx + 4) # Entry name is the last whitespace-delimited field before " -> " nf = split(left, fields, /[[:space:]]+/) name = fields[nf] if (!check_rel_target(name, target)) { print "escaping-symlink: " name " -> " target exit 0 } } ') if [ -n "$bad_links" ]; then fail "Refusing unsafe archive link in $archive: $bad_links" fi } verify_extracted_tree_links() { root_dir="$1" real_root=$(canonical_dir "$root_dir") # Walk every symlink inside the extracted directory and confirm its resolved # target stays strictly inside $real_root (defense-in-depth against chained # symlinks or tar parser differences). find "$real_root" -type l | while IFS= read -r link_path; do link_target=$(readlink "$link_path") case "$link_target" in /*) fail "Refusing absolute symlink inside extracted archive: $link_path -> $link_target" ;; esac link_parent=$(dirname "$link_path") if [ -d "$link_path" ]; then resolved=$(CDPATH= cd -- "$link_path" 2>/dev/null && pwd -P) || fail "Broken or escaping directory symlink: $link_path" else target_dir=$(dirname "$link_target") target_base=$(basename "$link_target") resolved_dir=$(CDPATH= cd -- "$link_parent/$target_dir" 2>/dev/null && pwd -P) || fail "Broken or escaping symlink in archive: $link_path -> $link_target" resolved="${resolved_dir}/${target_base}" fi case "$resolved" in "$real_root"|"$real_root"/*) ;; *) fail "Refusing symlink escaping staging root ($real_root): $link_path -> $resolved" ;; esac done } atomic_swap_symlink() { node_helper="$1" target_rel="$2" link_path="$3" parent_dir=$(dirname "$link_path") TMP_LINK="$parent_dir/.link-tmp-$$" rm -f "$TMP_LINK" ln -s "$target_rel" "$TMP_LINK" # Use POSIX rename(2) via the verified Node binary so replacing an existing # symlink-to-directory is atomic on both Linux and macOS (avoiding GNU mv -T # vs BSD mv incompatibilities). if [ -x "$node_helper" ]; then "$node_helper" -e 'require("fs").renameSync(process.argv[1], process.argv[2])' "$TMP_LINK" "$link_path" else ln -sfn "$target_rel" "$link_path" rm -f "$TMP_LINK" fi TMP_LINK="" } write_launcher() { bin_dir="$1" ensure_private_dir "$bin_dir" assert_confined_path "$WINGMAN_HOME" "$bin_dir" launcher_path="$bin_dir/wingman" assert_not_symlink "$launcher_path" TMP_LAUNCHER="$bin_dir/.wingman.tmp.$$" cat >"$TMP_LAUNCHER" <<'EOF' #!/bin/sh set -eu SELF_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) WINGMAN_HOME=$(CDPATH= cd -- "$SELF_DIR/.." && pwd) CURRENT="$WINGMAN_HOME/runtime/current" NODE_BIN="$CURRENT/node/bin/node" if [ ! -x "$NODE_BIN" ]; then printf '[Wingman] Pinned runtime is missing or incomplete at %s. Re-run the installer.\n' "$CURRENT" >&2 exit 1 fi if [ -f "$CURRENT/app/bin/wingman.js" ]; then ENTRY="$CURRENT/app/bin/wingman.js" elif [ -f "$CURRENT/app/node_modules/@scylax.ai/wingman/bin/wingman.js" ]; then ENTRY="$CURRENT/app/node_modules/@scylax.ai/wingman/bin/wingman.js" else printf '[Wingman] Wingman entrypoint is missing under %s/app. Re-run the installer.\n' "$CURRENT" >&2 exit 1 fi exec "$NODE_BIN" "$ENTRY" "$@" EOF chmod 0700 "$TMP_LAUNCHER" mv -f "$TMP_LAUNCHER" "$launcher_path" TMP_LAUNCHER="" } detect_platform_arch() { raw_os=$(uname -s) case "$raw_os" in Darwin) PLATFORM="darwin" ;; Linux) PLATFORM="linux" ;; *) fail "Unsupported OS: $raw_os (this script supports macOS and Linux; use install.ps1 on Windows)." ;; esac raw_arch=$(uname -m) case "$raw_arch" in x86_64|amd64) ARCH="x64" ;; arm64|aarch64) ARCH="arm64" ;; *) fail "Unsupported CPU architecture: $raw_arch (supported: x64, arm64)." ;; esac } pinned_node_sha256() { if [ "$NODE_VERSION" != "$PINNED_NODE_VERSION" ]; then return 1 fi case "${PLATFORM}-${ARCH}" in darwin-arm64) printf '%s' "$SHA256_DARWIN_ARM64" ;; darwin-x64) printf '%s' "$SHA256_DARWIN_X64" ;; linux-arm64) printf '%s' "$SHA256_LINUX_ARM64" ;; linux-x64) printf '%s' "$SHA256_LINUX_X64" ;; *) return 1 ;; esac } find_entrypoint_rel() { dir="$1" if [ -f "$dir/app/bin/wingman.js" ]; then printf '%s' "app/bin/wingman.js" elif [ -f "$dir/app/node_modules/@scylax.ai/wingman/bin/wingman.js" ]; then printf '%s' "app/node_modules/@scylax.ai/wingman/bin/wingman.js" else return 1 fi } acquire_lock() { ensure_private_dir "$WINGMAN_HOME" LOCK_DIR="$WINGMAN_HOME/.runtime.lock" assert_not_symlink "$LOCK_DIR" if ! mkdir "$LOCK_DIR" 2>/dev/null; then # Do NOT set LOCK_OWNED=1: cleanup() must never remove another process's lock. fail "Another Wingman runtime operation is in progress ($LOCK_DIR). Retry after it finishes." fi LOCK_OWNED=1 printf '%s\n' "$LOCK_TOKEN" >"$LOCK_DIR/owner" ensure_private_dir "$RUNTIME_ROOT" } allocate_install_slot() { base_id="$1" if [ ! -e "$RUNTIME_ROOT/$base_id" ] && [ ! -L "$RUNTIME_ROOT/$base_id" ]; then printf '%s' "$base_id" return 0 fi rev=1 while :; do candidate="${base_id}.r${rev}" if [ ! -e "$RUNTIME_ROOT/$candidate" ] && [ ! -L "$RUNTIME_ROOT/$candidate" ]; then printf '%s' "$candidate" return 0 fi rev=$((rev + 1)) done } do_uninstall() { if [ ! -e "$WINGMAN_HOME" ] && [ ! -L "$WINGMAN_HOME" ]; then info "Nothing to uninstall ($WINGMAN_HOME does not exist)." return 0 fi assert_not_symlink "$WINGMAN_HOME" [ -d "$WINGMAN_HOME" ] || fail "Wingman home is not a directory: $WINGMAN_HOME" # Refuse symlinks on BIN_DIR, launcher, and RUNTIME_ROOT before touching anything. if [ -e "$BIN_DIR" ] || [ -L "$BIN_DIR" ]; then assert_confined_path "$WINGMAN_HOME" "$BIN_DIR" fi launcher="$BIN_DIR/wingman" if [ -e "$launcher" ] || [ -L "$launcher" ]; then assert_confined_path "$WINGMAN_HOME" "$launcher" fi if [ -e "$RUNTIME_ROOT" ] || [ -L "$RUNTIME_ROOT" ]; then assert_confined_path "$WINGMAN_HOME" "$RUNTIME_ROOT" fi # Acquire ownership-checked lock inside $WINGMAN_HOME before modifying state. LOCK_DIR="$WINGMAN_HOME/.runtime.lock" assert_not_symlink "$LOCK_DIR" if ! mkdir "$LOCK_DIR" 2>/dev/null; then fail "Another Wingman runtime operation is in progress ($LOCK_DIR). Retry after it finishes." fi LOCK_OWNED=1 printf '%s\n' "$LOCK_TOKEN" >"$LOCK_DIR/owner" if [ -e "$launcher" ] || [ -L "$launcher" ]; then assert_confined_path "$WINGMAN_HOME" "$launcher" rm -f "$launcher" info "Removed launcher: $launcher" fi if [ -d "$BIN_DIR" ]; then assert_confined_path "$WINGMAN_HOME" "$BIN_DIR" rmdir "$BIN_DIR" 2>/dev/null || true fi if [ -d "$RUNTIME_ROOT" ]; then assert_confined_path "$WINGMAN_HOME" "$RUNTIME_ROOT" rm -rf "$RUNTIME_ROOT" info "Removed pinned runtime directory: $RUNTIME_ROOT" fi release_lock info "Uninstall complete. Client MCP configs, tokens, profiles, and autostart (if any) were NOT modified." } do_rollback() { acquire_lock prev_link="$RUNTIME_ROOT/previous" curr_link="$RUNTIME_ROOT/current" [ -L "$prev_link" ] || fail "No previous runtime available for rollback ($prev_link not found)." prev_target=$(readlink "$prev_link") validate_safe_id "previous runtime target" "$prev_target" prev_dir="$RUNTIME_ROOT/$prev_target" assert_confined_path "$RUNTIME_ROOT" "$prev_dir" [ -d "$prev_dir" ] || fail "Previous runtime directory is missing: $prev_dir" prev_node="$prev_dir/node/bin/node" [ -x "$prev_node" ] || fail "Previous runtime Node binary is missing or not executable: $prev_node" prev_entry_rel=$(find_entrypoint_rel "$prev_dir") || fail "Previous runtime Wingman entrypoint is missing under $prev_dir" "$prev_node" "$prev_dir/$prev_entry_rel" --help >/dev/null 2>&1 \ || fail "Previous runtime failed smoke verification; refusing rollback." old_curr="" if [ -L "$curr_link" ]; then old_curr=$(readlink "$curr_link") fi ROLLBACK_OLD_CURR="$old_curr" ROLLBACK_PENDING=1 atomic_swap_symlink "$prev_node" "$prev_target" "$curr_link" write_launcher "$BIN_DIR" "$BIN_DIR/wingman" --help >/dev/null 2>&1 & VERIFY_PID=$! wait "$VERIFY_PID" || { VERIFY_PID=""; fail "Rollback launcher verification failed."; } VERIFY_PID="" ROLLBACK_PENDING=0 if [ -n "$old_curr" ] && [ "$old_curr" != "$prev_target" ]; then validate_safe_id "current runtime target" "$old_curr" atomic_swap_symlink "$prev_node" "$old_curr" "$prev_link" fi info "Rolled back active runtime to: $prev_target" info "Stable launcher: $BIN_DIR/wingman" } do_install() { detect_platform_arch validate_safe_id "node version" "$NODE_VERSION" validate_safe_id "wingman version" "$WINGMAN_VERSION" if [ -z "$RUNTIME_ID" ]; then RUNTIME_ID="${WINGMAN_VERSION}-node-${NODE_VERSION}" fi validate_safe_id "runtime id" "$RUNTIME_ID" validate_url "Node base URL" "$NODE_BASE_URL" if [ -n "$NPM_REGISTRY" ]; then validate_url "npm registry URL" "$NPM_REGISTRY" fi node_archive="node-${NODE_VERSION}-${PLATFORM}-${ARCH}.tar.gz" node_url="${NODE_BASE_URL%/}/${NODE_VERSION}/${node_archive}" if [ -z "$NODE_SHA256" ]; then if [ -n "$CHECKSUMS_FILE" ]; then NODE_SHA256=$(lookup_checksum_file "$CHECKSUMS_FILE" "$node_archive") \ || fail "No SHA-256 entry for $node_archive in $CHECKSUMS_FILE; failing closed." else NODE_SHA256=$(pinned_node_sha256) \ || fail "No pinned SHA-256 for $node_archive. Provide --node-sha256 or --checksums-file; failing closed." fi fi validate_sha256_hex "Node archive ($node_archive)" "$NODE_SHA256" if [ -n "$WINGMAN_URL" ]; then validate_url "Wingman bundle URL" "$WINGMAN_URL" if [ -z "$WINGMAN_SHA256" ] && [ -n "$CHECKSUMS_FILE" ]; then wingman_url_clean="${WINGMAN_URL%%\?*}" wingman_file_name=$(basename "$wingman_url_clean") WINGMAN_SHA256=$(lookup_checksum_file "$CHECKSUMS_FILE" "$wingman_file_name") || true fi if [ -z "$WINGMAN_SHA256" ]; then fail "--wingman-url requires --wingman-sha256 (or matching entry in --checksums-file); failing closed." fi validate_sha256_hex "Wingman archive" "$WINGMAN_SHA256" fi acquire_lock STAGE_DIR="$RUNTIME_ROOT/.staging-${RUNTIME_ID}-$$" rm -rf "$STAGE_DIR" mkdir -p "$STAGE_DIR/downloads" "$STAGE_DIR/node" "$STAGE_DIR/app" info "Downloading Node.js $NODE_VERSION ($PLATFORM-$ARCH)..." node_tgz="$STAGE_DIR/downloads/$node_archive" download_file "$node_url" "$node_tgz" verify_sha256 "$node_tgz" "$NODE_SHA256" "$node_archive" info "Verified SHA-256 for $node_archive." check_tar_safe "$node_tgz" 1 tar -xzf "$node_tgz" --strip-components=1 -C "$STAGE_DIR/node" \ || fail "Failed to extract $node_archive" verify_extracted_tree_links "$STAGE_DIR/node" stage_node="$STAGE_DIR/node/bin/node" [ -x "$stage_node" ] || fail "Extracted Node binary is missing or not executable: $stage_node" installed_node_ver=$("$stage_node" -v 2>/dev/null || true) [ -n "$installed_node_ver" ] || fail "Extracted Node binary failed to execute ($stage_node)." info "Verified pinned Node binary: $installed_node_ver" if [ -n "$WINGMAN_URL" ]; then wingman_tgz="$STAGE_DIR/downloads/wingman.tar.gz" info "Downloading Wingman JS archive..." download_file "$WINGMAN_URL" "$wingman_tgz" verify_sha256 "$wingman_tgz" "$WINGMAN_SHA256" "Wingman archive" info "Verified SHA-256 for Wingman archive." check_tar_safe "$wingman_tgz" 0 mkdir -p "$STAGE_DIR/unpack" tar -xzf "$wingman_tgz" -C "$STAGE_DIR/unpack" \ || fail "Failed to extract Wingman archive" verify_extracted_tree_links "$STAGE_DIR/unpack" if [ -f "$STAGE_DIR/unpack/bin/wingman.js" ] && [ ! -L "$STAGE_DIR/unpack/bin/wingman.js" ]; then cp -RP "$STAGE_DIR/unpack/." "$STAGE_DIR/app/" elif [ -f "$STAGE_DIR/unpack/package/bin/wingman.js" ] && [ ! -L "$STAGE_DIR/unpack/package/bin/wingman.js" ]; then cp -RP "$STAGE_DIR/unpack/package/." "$STAGE_DIR/app/" else found_root="" for candidate in "$STAGE_DIR/unpack"/*; do if [ -d "$candidate" ] && [ ! -L "$candidate" ] && [ -f "$candidate/bin/wingman.js" ]; then found_root="$candidate" break fi done [ -n "$found_root" ] || fail "Wingman archive does not contain bin/wingman.js" cp -RP "$found_root/." "$STAGE_DIR/app/" fi rm -rf "$STAGE_DIR/unpack" # Re-verify every symlink stays inside $STAGE_DIR/app after unwrapping package/ verify_extracted_tree_links "$STAGE_DIR/app" else stage_npm="$STAGE_DIR/node/bin/npm" [ -x "$stage_npm" ] || fail "Bundled npm is missing under $STAGE_DIR/node/bin/npm" info "Installing ${WINGMAN_PACKAGE}@${WINGMAN_VERSION} into pinned runtime..." if [ -n "$NPM_REGISTRY" ]; then PATH="$STAGE_DIR/node/bin:$PATH" "$stage_npm" install \ --prefix "$STAGE_DIR/app" \ --omit=dev --ignore-scripts --no-audit --no-fund --no-update-notifier \ --registry "$NPM_REGISTRY" \ "${WINGMAN_PACKAGE}@${WINGMAN_VERSION}" \ || fail "Installing ${WINGMAN_PACKAGE}@${WINGMAN_VERSION} with npm failed" else PATH="$STAGE_DIR/node/bin:$PATH" "$stage_npm" install \ --prefix "$STAGE_DIR/app" \ --omit=dev --ignore-scripts --no-audit --no-fund --no-update-notifier \ "${WINGMAN_PACKAGE}@${WINGMAN_VERSION}" \ || fail "Installing ${WINGMAN_PACKAGE}@${WINGMAN_VERSION} with npm failed" fi verify_extracted_tree_links "$STAGE_DIR/app" fi rm -rf "$STAGE_DIR/downloads" rel_entry=$(find_entrypoint_rel "$STAGE_DIR") \ || fail "Installed Wingman JS is missing bin/wingman.js" assert_confined_path "$STAGE_DIR" "$STAGE_DIR/$rel_entry" # Smoke-verify the staged runtime BEFORE touching the active runtime. "$stage_node" "$STAGE_DIR/$rel_entry" --help >/dev/null 2>&1 \ || fail "Staged Wingman runtime failed --help smoke verification; aborting before swap." install_slot=$(allocate_install_slot "$RUNTIME_ID") validate_safe_id "install slot" "$install_slot" "$stage_node" -e ' const fs = require("fs"); const [dest, runtimeId, wingmanVersion, nodeVersion, platform, arch, entrypoint] = process.argv.slice(1); const doc = { schemaVersion: 1, runtimeId, wingmanVersion, nodeVersion, platform, arch, entrypoint, installedAt: new Date().toISOString(), }; fs.writeFileSync(dest, JSON.stringify(doc, null, 2) + "\n", { mode: 0o600 }); ' "$STAGE_DIR/manifest.json" "$install_slot" "$WINGMAN_VERSION" "$NODE_VERSION" "$PLATFORM" "$ARCH" "$rel_entry" curr_link="$RUNTIME_ROOT/current" prev_link="$RUNTIME_ROOT/previous" old_curr="" if [ -L "$curr_link" ]; then old_curr=$(readlink "$curr_link") fi # Promote into a fresh immutable slot (never moving a live directory out from # under `current`), and arm trap-backed rollback before flipping `current`. target_dir="$RUNTIME_ROOT/$install_slot" SWAP_OLD_CURR="$old_curr" SWAP_NEW_DIR="$target_dir" SWAP_PENDING=1 mv "$STAGE_DIR" "$target_dir" STAGE_DIR="" swap_ok=0 if atomic_swap_symlink "$target_dir/node/bin/node" "$install_slot" "$curr_link" \ && write_launcher "$BIN_DIR"; then "$BIN_DIR/wingman" --help >/dev/null 2>&1 & VERIFY_PID=$! if wait "$VERIFY_PID"; then swap_ok=1 fi VERIFY_PID="" fi if [ "$swap_ok" -ne 1 ]; then # cleanup() also performs rollback via SWAP_PENDING=1 if a signal or error # interrupts any step above; doing it here provides an explicit error line. printf '[Wingman installer] Post-swap verification failed; rolling back...\n' >&2 rm -f "$RUNTIME_ROOT/.link-tmp-"* "$BIN_DIR/.wingman.tmp."* 2>/dev/null || true restore_current_pointer "$old_curr" rm -rf "$target_dir" 2>/dev/null || true SWAP_PENDING=0 fail "Install rolled back after post-swap verification failed." fi SWAP_PENDING=0 if [ -n "$old_curr" ] && [ "$old_curr" != "$install_slot" ]; then validate_safe_id "previous runtime id" "$old_curr" atomic_swap_symlink "$target_dir/node/bin/node" "$old_curr" "$prev_link" fi info "Installed Wingman pinned runtime: $target_dir" info "Active runtime: $curr_link -> $install_slot" info "Stable launcher: $BIN_DIR/wingman" info "No AI client configs, shell profiles, or login autostart were modified." info "Next steps:" info " 1. Optionally add $BIN_DIR to your PATH." info " 2. Run: $BIN_DIR/wingman setup" info " 3. To roll back an upgrade: $0 --rollback" info " 4. To remove the pinned runtime: $0 --uninstall" } while [ "$#" -gt 0 ]; do case "$1" in --help|-h) usage exit 0 ;; --uninstall) ACTION="uninstall" shift ;; --rollback) ACTION="rollback" shift ;; --wingman-home) require_arg "$@" WINGMAN_HOME="$2" shift 2 ;; --node-version) require_arg "$@" NODE_VERSION="$2" shift 2 ;; --node-base-url) require_arg "$@" NODE_BASE_URL="$2" shift 2 ;; --node-sha256) require_arg "$@" NODE_SHA256="$2" shift 2 ;; --checksums-file) require_arg "$@" CHECKSUMS_FILE="$2" shift 2 ;; --wingman-version) require_arg "$@" WINGMAN_VERSION="$2" shift 2 ;; --wingman-url) require_arg "$@" WINGMAN_URL="$2" shift 2 ;; --wingman-sha256) require_arg "$@" WINGMAN_SHA256="$2" shift 2 ;; --npm-registry) require_arg "$@" NPM_REGISTRY="$2" shift 2 ;; --runtime-id) require_arg "$@" RUNTIME_ID="$2" shift 2 ;; --allow-loopback-http) ALLOW_LOOPBACK_HTTP=1 shift ;; *) fail "Unknown argument: $1 (use --help for usage)" ;; esac done if [ -z "$WINGMAN_HOME" ]; then [ -n "${HOME:-}" ] || fail "HOME is not set; pass --wingman-home ." WINGMAN_HOME="$HOME/.wingman" fi RUNTIME_ROOT="$WINGMAN_HOME/runtime" BIN_DIR="$WINGMAN_HOME/bin" case "$ACTION" in install) do_install ;; rollback) do_rollback ;; uninstall) do_uninstall ;; *) fail "Unsupported action: $ACTION" ;; esac