Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix: resolve managed binary path from package root instead of $HOME

Luigi Agosti2d8ccdb6264a
diff --git a/dev b/dev
index b16d0607..2b775059 100755
--- a/dev
+++ b/dev
@@ -23,7 +23,7 @@ COMMANDS=(
"run:πŸƒ:Run the application"
"check:πŸ§ͺ:All checks"
"all:βœ…:check + test + e2e"
- "full:βœ…:check + test + e2e-browsers + smoke-browsers"
+ "full:βœ…:check + npm + test + e2e-browsers + smoke-browsers"
"e2e-browsers:🐳:e2e extended across all 3 browsers"
"smoke-browsers:πŸ’¨:e2e smoke across all 3 browsers (browser-sensitive only for cloak/ghost-chrome)"
"test unit:πŸ”¬:Go unit tests"
@@ -431,11 +431,12 @@ run_command() {
|| exit 1
;;
"full")
- echo " ${ACCENT}${BOLD}βœ… full: check + test + e2e-browsers + smoke-browsers${NC}"
+ echo " ${ACCENT}${BOLD}βœ… full: check + npm + test + e2e-browsers + smoke-browsers${NC}"
echo ""
bash scripts/check.sh || exit 1
bash scripts/check-dashboard.sh || exit 1
bash scripts/check-plugin.sh || exit 1
+ bash scripts/check-npm.sh || exit 1
bash scripts/test.sh all || exit 1
run_e2e_matrix "E2E-browsers summary" \
"extended / chrome|extended|chrome" \
diff --git a/npm/scripts/fake-release-server.js b/npm/scripts/fake-release-server.js
new file mode 100755
index 00000000..41d1e9c4
--- /dev/null
+++ b/npm/scripts/fake-release-server.js
@@ -0,0 +1,71 @@
+#!/usr/bin/env node
+'use strict';
+
+// fake-release-server serves a single release asset (the platform binary) and a
+// matching checksums.txt over plain http, mirroring the GitHub release layout
+// that download.ts expects: <base>/v<version>/<asset>. It exists so the install
+// smoke test can drive the real postinstall download path β€” checksum verify,
+// atomic rename, chmod, HOME-based install dir β€” without the network or a
+// published release. The checksum it serves is computed from the served bytes,
+// so the real verifySHA256 check passes.
+//
+// Driven entirely by env so the shell harness stays declarative:
+// FAKE_RELEASE_PORT port to listen on (default 0 β†’ OS-assigned)
+// FAKE_RELEASE_VERSION version segment, e.g. 0.15.1
+// FAKE_RELEASE_BINARY_NAME asset name, e.g. pinchtab-linux-amd64
+// FAKE_RELEASE_BINARY_PATH path to the file served as that asset
+// On listen it prints "listening <port>" so the caller can learn an OS-assigned
+// port and wait for readiness.
+
+const http = require('http');
+const fs = require('fs');
+const crypto = require('crypto');
+
+const version = process.env.FAKE_RELEASE_VERSION;
+const binaryName = process.env.FAKE_RELEASE_BINARY_NAME;
+const binaryPath = process.env.FAKE_RELEASE_BINARY_PATH;
+const port = Number(process.env.FAKE_RELEASE_PORT || 0);
+
+for (const [name, value] of [
+ ['FAKE_RELEASE_VERSION', version],
+ ['FAKE_RELEASE_BINARY_NAME', binaryName],
+ ['FAKE_RELEASE_BINARY_PATH', binaryPath],
+]) {
+ if (!value) {
+ console.error(`fake-release-server: missing ${name}`);
+ process.exit(1);
+ }
+}
+
+const binaryBytes = fs.readFileSync(binaryPath);
+const sha256 = crypto.createHash('sha256').update(binaryBytes).digest('hex');
+const checksums = `${sha256} ${binaryName}\n`;
+
+const prefix = `/v${version}/`;
+
+const server = http.createServer((req, res) => {
+ if (!req.url || !req.url.startsWith(prefix)) {
+ res.writeHead(404).end('not found');
+ return;
+ }
+ const asset = req.url.slice(prefix.length);
+ if (asset === 'checksums.txt') {
+ res.writeHead(200, { 'content-type': 'text/plain' }).end(checksums);
+ return;
+ }
+ if (asset === binaryName) {
+ res.writeHead(200, { 'content-type': 'application/octet-stream' }).end(binaryBytes);
+ return;
+ }
+ res.writeHead(404).end('not found');
+});
+
+server.listen(port, '127.0.0.1', () => {
+ const actualPort = server.address().port;
+ // Single stable line the harness greps for.
+ console.log(`listening ${actualPort}`);
+});
+
+for (const sig of ['SIGINT', 'SIGTERM']) {
+ process.on(sig, () => server.close(() => process.exit(0)));
+}
diff --git a/npm/scripts/npm-install-home-divergence.sh b/npm/scripts/npm-install-home-divergence.sh
new file mode 100755
index 00000000..35df2f0d
--- /dev/null
+++ b/npm/scripts/npm-install-home-divergence.sh
@@ -0,0 +1,157 @@
+#!/usr/bin/env bash
+#
+# Hermetic install smoke test for the "global install downloads to the wrong
+# HOME" bug (issue #628). It reproduces the mechanism WITHOUT Docker, sudo, or
+# the network: the only thing that bug needs is postinstall running under a
+# different HOME than the CLI wrapper.
+#
+# 1. Serve a fake release (real binary bytes + matching checksums.txt) from a
+# local http server, pointed at via PINCHTAB_DOWNLOAD_BASE_URL.
+# 2. `npm install -g` with HOME=$INSTALL_HOME -> postinstall downloads the
+# binary into $INSTALL_HOME/.pinchtab/bin/... (the "root" side of the bug).
+# 3. Run the CLI with HOME=$RUN_HOME (a different HOME) -> the wrapper must
+# still find the binary and run.
+#
+# On unfixed code the CLI exits non-zero with "binary not found" -- this script
+# fails and prints exactly where the binary landed vs. where the wrapper looked.
+# After the package-relative fix, step 3 passes regardless of HOME.
+#
+# Usage: npm-install-home-divergence.sh [npm-install-target]
+# npm-install-target defaults to a freshly packed tarball of this package.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+NPM_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
+
+TMP_ROOT="$(mktemp -d)"
+INSTALL_HOME="$TMP_ROOT/install-home" # HOME during 'npm install' (~ root under sudo)
+RUN_HOME="$TMP_ROOT/run-home" # HOME when running the CLI (the real user)
+PREFIX_DIR="$TMP_ROOT/prefix" # global npm prefix, OUTSIDE the repo tree
+SERVER_LOG="$TMP_ROOT/server.log"
+SERVER_PID=""
+
+cleanup() {
+ if [ -n "$SERVER_PID" ] && kill -0 "$SERVER_PID" 2>/dev/null; then
+ kill "$SERVER_PID" >/dev/null 2>&1 || true
+ wait "$SERVER_PID" >/dev/null 2>&1 || true
+ fi
+ rm -rf "$TMP_ROOT"
+}
+trap cleanup EXIT
+
+mkdir -p "$INSTALL_HOME" "$RUN_HOME" "$PREFIX_DIR"
+
+# Ensure the package is built (we need dist/ for the platform helper and pack).
+if [ ! -f "$NPM_DIR/dist/src/platform.js" ]; then
+ echo "Building npm package (dist/ missing)..."
+ (cd "$NPM_DIR" && npm run build >/dev/null)
+fi
+
+VERSION="$(node -p "require('$NPM_DIR/package.json').version")"
+BINARY_NAME="$(node -e "const p=require('$NPM_DIR/dist/src/platform');process.stdout.write(p.getBinaryName(p.detectPlatform()))")"
+echo "Platform binary: $BINARY_NAME version: $VERSION"
+
+# Resolve the install target (packed tarball by default -> hermetic, no registry).
+if [ "$#" -ge 1 ]; then
+ INSTALL_TARGET="$1"
+else
+ # Discard pack output entirely: prepack/prepare lifecycle scripts print to
+ # stdout, so parsing the tarball name from it is unreliable. The name is
+ # deterministic for this unscoped package: <name>-<version>.tgz.
+ echo "Packing tarball from ${NPM_DIR} ..."
+ (cd "$NPM_DIR" && npm pack --pack-destination "$TMP_ROOT" >/dev/null 2>&1)
+ INSTALL_TARGET="$TMP_ROOT/pinchtab-$VERSION.tgz"
+ if [ ! -f "$INSTALL_TARGET" ]; then
+ echo "smoke failed: npm pack did not produce $INSTALL_TARGET" >&2
+ exit 1
+ fi
+fi
+echo "Install target: $INSTALL_TARGET"
+
+# Fake release binary: a tiny executable stub that prints a recognizable marker.
+MARKER="pinchtab-home-divergence-smoke $VERSION"
+FAKE_BINARY="$TMP_ROOT/$BINARY_NAME"
+printf '#!/bin/sh\necho "%s"\nexit 0\n' "$MARKER" >"$FAKE_BINARY"
+chmod +x "$FAKE_BINARY"
+
+# Start the local fake-release server on an OS-assigned port.
+FAKE_RELEASE_VERSION="$VERSION" \
+FAKE_RELEASE_BINARY_NAME="$BINARY_NAME" \
+FAKE_RELEASE_BINARY_PATH="$FAKE_BINARY" \
+FAKE_RELEASE_PORT=0 \
+ node "$SCRIPT_DIR/fake-release-server.js" >"$SERVER_LOG" 2>&1 &
+SERVER_PID="$!"
+
+PORT=""
+for _ in $(seq 1 50); do
+ PORT="$(sed -n 's/^listening \([0-9]*\)$/\1/p' "$SERVER_LOG" 2>/dev/null | head -1)"
+ [ -n "$PORT" ] && break
+ sleep 0.1
+done
+if [ -z "$PORT" ]; then
+ echo "smoke failed: fake release server never reported a port" >&2
+ cat "$SERVER_LOG" >&2
+ exit 1
+fi
+BASE_URL="http://127.0.0.1:$PORT"
+echo "Fake release server: $BASE_URL"
+
+# -- Install side: postinstall runs with HOME=$INSTALL_HOME -------------------
+echo
+echo "Installing (HOME=$INSTALL_HOME) ..."
+HOME="$INSTALL_HOME" \
+PINCHTAB_DOWNLOAD_BASE_URL="$BASE_URL" \
+ npm install -g --prefix "$PREFIX_DIR" "$INSTALL_TARGET" >"$TMP_ROOT/install.log" 2>&1 || {
+ echo "smoke failed: npm install errored" >&2
+ cat "$TMP_ROOT/install.log" >&2
+ exit 1
+}
+
+# postinstall must have downloaded the binary somewhere. After the fix it lands
+# in the package-relative managed dir; before the fix it lands under
+# $INSTALL_HOME/.pinchtab. Accept either here -- the run-side check below is what
+# actually gates on the bug -- but fail clearly if NEITHER exists, which means
+# postinstall never ran (a broken test env, not issue #628).
+PKG_BINARY="$PREFIX_DIR/lib/node_modules/pinchtab/.managed-bin/$VERSION/$BINARY_NAME"
+LEGACY_BINARY="$INSTALL_HOME/.pinchtab/bin/$VERSION/$BINARY_NAME"
+if [ -f "$PKG_BINARY" ]; then
+ DOWNLOADED_TO="$PKG_BINARY"
+ echo "postinstall downloaded binary -> $DOWNLOADED_TO (package-relative)"
+elif [ -f "$LEGACY_BINARY" ]; then
+ DOWNLOADED_TO="$LEGACY_BINARY"
+ echo "postinstall downloaded binary -> $DOWNLOADED_TO (legacy \$HOME location)"
+else
+ echo "smoke inconclusive: postinstall did not download a binary to either" >&2
+ echo " $PKG_BINARY" >&2
+ echo " $LEGACY_BINARY" >&2
+ echo "install log:" >&2; cat "$TMP_ROOT/install.log" >&2
+ exit 1
+fi
+
+# -- Run side: the CLI runs with a DIFFERENT HOME=$RUN_HOME -------------------
+CLI="$PREFIX_DIR/bin/pinchtab"
+echo
+echo "Running CLI (HOME=$RUN_HOME) : $CLI --version"
+set +e
+CLI_OUT="$(HOME="$RUN_HOME" "$CLI" --version 2>&1)"
+CLI_RC=$?
+set -e
+
+echo "-- CLI output --"
+echo "$CLI_OUT"
+echo "-- exit code: $CLI_RC --"
+
+if [ "$CLI_RC" -eq 0 ] && printf '%s' "$CLI_OUT" | grep -qF "$MARKER"; then
+ echo
+ echo "[PASS] CLI resolved the binary across the install/run HOME boundary."
+ exit 0
+fi
+
+echo
+echo "[FAIL] CLI could not find the binary when run under a different HOME." >&2
+echo " installed at : $DOWNLOADED_TO" >&2
+echo " wrapper HOME : $RUN_HOME (looked under \$HOME/.pinchtab/bin/...)" >&2
+echo "This is issue #628: the managed binary dir is derived from HOME, so an" >&2
+echo "install as one user/HOME and a run as another can never agree." >&2
+exit 1
diff --git a/npm/src/download.ts b/npm/src/download.ts
index 5102e99d..f1e37115 100644
--- a/npm/src/download.ts
+++ b/npm/src/download.ts
@@ -3,7 +3,12 @@ import * as path from 'path';
import * as http from 'http';
import * as https from 'https';
import * as crypto from 'crypto';
-import { detectPlatform, getBinaryName, getBinaryPath, readPackageVersion } from './platform';
+import {
+ detectPlatform,
+ getBinaryName,
+ getManagedBinaryPath,
+ readPackageVersion,
+} from './platform';
const GITHUB_REPO = 'pinchtab/pinchtab';
@@ -12,6 +17,33 @@ function getVersion(): string {
return readPackageVersion(__dirname);
}
+// releaseAssetUrl builds the download URL for a release asset. It defaults to
+// the GitHub release for GITHUB_REPO, but honors PINCHTAB_DOWNLOAD_BASE_URL so
+// installs can point at a private mirror or air-gapped cache β€” and so the
+// hermetic install smoke test can serve fixtures from a local http server
+// instead of the network. The asset layout under the base mirrors GitHub's:
+// <base>/v<version>/<asset>.
+function releaseAssetUrl(version: string, asset: string): string {
+ const base = process.env.PINCHTAB_DOWNLOAD_BASE_URL?.trim();
+ if (base) {
+ return `${base.replace(/\/+$/, '')}/v${version}/${asset}`;
+ }
+ return `https://github.com/${GITHUB_REPO}/releases/download/v${version}/${asset}`;
+}
+
+// defaultGet dispatches to http.get or https.get by URL scheme so a plain-http
+// PINCHTAB_DOWNLOAD_BASE_URL (a mirror or the local test server) works: https.get
+// cannot fetch an http:// URL. Redirects are followed with this same dispatcher,
+// so a hop that changes scheme is still handled.
+function defaultGet(
+ url: string,
+ options: http.RequestOptions,
+ callback: (res: http.IncomingMessage) => void
+): http.ClientRequest {
+ const getter = new URL(url).protocol === 'http:' ? http.get : https.get;
+ return getter(url, options, callback);
+}
+
// NOTE: HTTPS_PROXY / HTTP_PROXY are NOT honored β€” downloads go direct. A prior
// buildProxyAgent() built an https.Agent({host,port}) that https.get(url, …)
// silently overrode (the Agent's host/port were never used for tunneling), so
@@ -33,7 +65,7 @@ export function httpGetFollowingRedirects(
url: string,
options: http.RequestOptions,
callback: (res: http.IncomingMessage) => void
- ) => http.ClientRequest = https.get
+ ) => http.ClientRequest = defaultGet
): void {
const attempt = (currentUrl: string, redirectsRemaining: number) => {
const request = requestFn(currentUrl, {}, (response) => {
@@ -100,7 +132,7 @@ function fetchUrl(url: string, maxRedirects = 5): Promise<Buffer> {
}
async function downloadChecksums(version: string): Promise<Map<string, string>> {
- const url = `https://github.com/${GITHUB_REPO}/releases/download/v${version}/checksums.txt`;
+ const url = releaseAssetUrl(version, 'checksums.txt');
try {
const data = await fetchUrl(url);
@@ -145,7 +177,7 @@ async function downloadBinary(
version: string
): Promise<void> {
const binaryName = getBinaryName(platform);
- const binaryPath = getBinaryPath(binaryName, version);
+ const binaryPath = getManagedBinaryPath(__dirname, binaryName, version);
// Fetch the checksum map once and reuse it for both the existing-binary
// verification and the post-download check (it was previously downloaded
@@ -175,7 +207,7 @@ async function downloadBinary(
}
console.log(`Downloading Pinchtab ${version} for ${platform.os}-${platform.arch}...`);
- const downloadUrl = `https://github.com/${GITHUB_REPO}/releases/download/v${version}/${binaryName}`;
+ const downloadUrl = releaseAssetUrl(version, binaryName);
// Ensure the managed install directory exists
const binDir = path.dirname(binaryPath);
@@ -258,5 +290,5 @@ export async function ensureBinary(): Promise<string> {
await downloadBinary(platform, version);
const binaryName = getBinaryName(platform);
- return getBinaryPath(binaryName, version);
+ return getManagedBinaryPath(__dirname, binaryName, version);
}
diff --git a/npm/src/index.ts b/npm/src/index.ts
index 118b8bdb..11b430f9 100644
--- a/npm/src/index.ts
+++ b/npm/src/index.ts
@@ -3,13 +3,7 @@ import { randomBytes } from 'crypto';
import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
-import {
- detectPlatform,
- getBinaryName,
- getBinaryPath,
- getCheckoutBinaryPath,
- readPackageVersion,
-} from './platform';
+import { getCheckoutBinaryPath, resolveManagedBinaryPath } from './platform';
import { withAuthedFetch } from './http';
import {
SnapshotParams,
@@ -251,20 +245,10 @@ export class Pinchtab {
return checkoutBinaryPath;
}
- const platform = detectPlatform();
- const binaryName = getBinaryName(platform);
-
- // Try version-specific path first
- let version: string | undefined;
- try {
- version = readPackageVersion(__dirname);
- } catch (err) {
- console.warn(
- `Could not read version from package.json, falling back to unversioned binary. (${(err as Error).message})`
- );
- }
-
- const binaryPath = getBinaryPath(binaryName, version);
+ // Shared resolver: package-relative managed location first, then the legacy
+ // $HOME fallback (issue #628). Keeps the SDK, the CLI wrapper, and the
+ // installer agreeing on one binary location.
+ const binaryPath = resolveManagedBinaryPath(__dirname);
if (!fs.existsSync(binaryPath)) {
throw new Error(
`Pinchtab binary not found at ${binaryPath}.\n` +
diff --git a/npm/src/platform.ts b/npm/src/platform.ts
index f2727de9..9f4f963a 100644
--- a/npm/src/platform.ts
+++ b/npm/src/platform.ts
@@ -49,6 +49,11 @@ export function getBinaryName(platform: Platform): string {
return `pinchtab-${os}-${archName}`;
}
+// getBinDir returns the LEGACY $HOME-based managed binary directory
+// (~/.pinchtab/bin). New installs use the package-relative getManagedBinDir;
+// this remains only so resolveManagedBinaryPath can still find binaries placed
+// by older versions. Deriving the location from $HOME is exactly what caused
+// issue #628 (install as root under sudo, run as the user β†’ different $HOME).
export function getBinDir(): string {
return path.join(process.env.HOME || process.env.USERPROFILE || '', '.pinchtab', 'bin');
}
@@ -82,6 +87,9 @@ export function getCheckoutBinaryPath(fromDir: string): string | null {
return path.join(repoRoot, 'pinchtab-dev');
}
+// getBinaryPath returns the LEGACY $HOME-based binary path. Retained for
+// backwards-compatible lookups (see resolveManagedBinaryPath); new installs
+// write to the package-relative getManagedBinaryPath instead.
export function getBinaryPath(binaryName: string, version?: string): string {
// Version-specific path: ~/.pinchtab/bin/0.7.0/pinchtab-darwin-arm64
// This allows multiple versions to coexist and prevents silent overwrites
@@ -93,6 +101,59 @@ export function getBinaryPath(binaryName: string, version?: string): string {
return path.join(getBinDir(), binaryName);
}
+// findPackageRoot walks up from fromDir to the nearest directory containing a
+// package.json and returns it (or null if none is found). This is the installed
+// npm package's own directory, which β€” unlike $HOME β€” is identical whether
+// postinstall runs as root/sudo or the CLI runs as the invoking user. It is the
+// anchor for the managed binary location so the two can never diverge (#628).
+export function findPackageRoot(fromDir: string): string | null {
+ let dir = path.resolve(fromDir);
+
+ while (dir) {
+ if (fs.existsSync(path.join(dir, 'package.json'))) {
+ return dir;
+ }
+
+ const parent = path.dirname(dir);
+ if (parent === dir) {
+ break;
+ }
+ dir = parent;
+ }
+
+ return null;
+}
+
+// MANAGED_BIN_DIRNAME is the directory, inside the installed package, that holds
+// the downloaded Go binary. A dot-prefixed name keeps it out of the way; it is
+// created at install time (not shipped in the package tarball).
+const MANAGED_BIN_DIRNAME = '.managed-bin';
+
+// getManagedBinDir returns the package-relative managed binary directory for the
+// package containing fromDir. It falls back to the legacy $HOME location only
+// when no package root can be found, which should not happen for an installed
+// package but keeps resolution defined in odd layouts.
+export function getManagedBinDir(fromDir: string): string {
+ const root = findPackageRoot(fromDir);
+ if (!root) {
+ return getBinDir();
+ }
+ return path.join(root, MANAGED_BIN_DIRNAME);
+}
+
+// getManagedBinaryPath returns the versioned managed binary path (version-less
+// when version is omitted). Both the installer (download.ts, write) and the
+// resolver (resolveManagedBinaryPath, read) go through this single function so
+// the install-time and run-time locations cannot drift apart.
+export function getManagedBinaryPath(
+ fromDir: string,
+ binaryName: string,
+ version?: string
+): string {
+ const dir = getManagedBinDir(fromDir);
+ return version ? path.join(dir, version, binaryName) : path.join(dir, binaryName);
+}
+
// readPackageVersion walks up from fromDir to the nearest package.json and
// returns its version. Shared so the wrapper, SDK, and installer agree on which
// versioned binary directory to look in.
@@ -119,9 +180,12 @@ export function readPackageVersion(fromDir: string): string {
}
// resolveManagedBinaryPath returns the path of the downloaded binary for the
-// current platform: the version-specific path when it exists, otherwise the
-// version-less path for backwards compatibility. It does NOT assert existence β€”
-// callers decide how to report a missing binary.
+// current platform. It prefers the package-relative managed location (stable
+// across $HOME and user β€” issue #628), then falls back to binaries left by
+// older versions under the legacy $HOME/.pinchtab/bin so existing installs keep
+// working. It does NOT assert existence for the value it returns when nothing is
+// found β€” callers decide how to report a missing binary; that value is the
+// canonical (package-relative) path.
export function resolveManagedBinaryPath(fromDir: string): string {
const binaryName = getBinaryName(detectPlatform());
@@ -132,14 +196,24 @@ export function resolveManagedBinaryPath(fromDir: string): string {
// Fall back to the version-less path when no package.json version is found.
}
- if (version) {
- const versioned = getBinaryPath(binaryName, version);
- if (fs.existsSync(versioned)) {
- return versioned;
+ // Preferred: package-relative, independent of $HOME.
+ const preferred = getManagedBinaryPath(fromDir, binaryName, version);
+ if (fs.existsSync(preferred)) {
+ return preferred;
+ }
+
+ // Backwards compatibility: honor binaries installed by older versions under
+ // the legacy $HOME/.pinchtab/bin location (versioned first, then version-less).
+ const legacyCandidates = version
+ ? [getBinaryPath(binaryName, version), getBinaryPath(binaryName)]
+ : [getBinaryPath(binaryName)];
+ for (const candidate of legacyCandidates) {
+ if (fs.existsSync(candidate)) {
+ return candidate;
}
}
- return getBinaryPath(binaryName);
+ return preferred;
}
// firstSubcommand returns the first non-flag argument, skipping the global
diff --git a/npm/tests/managed-binary-path.test.ts b/npm/tests/managed-binary-path.test.ts
new file mode 100644
index 00000000..324d6e8b
--- /dev/null
+++ b/npm/tests/managed-binary-path.test.ts
@@ -0,0 +1,125 @@
+/**
+ * Managed binary path resolution (issue #628)
+ *
+ * The bug: the managed binary directory was derived from $HOME, so a global
+ * install whose postinstall ran under one HOME (e.g. root, via `sudo npm i -g`)
+ * placed the binary somewhere the CLI wrapper β€” running under the invoking
+ * user's HOME β€” never looked. Install-time and run-time locations diverged.
+ *
+ * These tests pin the fix: the managed binary location is package-relative and
+ * therefore independent of $HOME, while binaries left by older versions under
+ * ~/.pinchtab/bin are still honored for backwards compatibility.
+ */
+
+import { test, describe, afterEach } from 'node:test';
+import * as assert from 'node:assert';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {
+ detectPlatform,
+ getBinaryName,
+ getManagedBinaryPath,
+ resolveManagedBinaryPath,
+} from '../src/platform';
+
+const BINARY_NAME = getBinaryName(detectPlatform());
+const VERSION = '1.2.3';
+
+describe('managed binary path (issue #628)', () => {
+ const originalHome = process.env.HOME;
+ const originalUserProfile = process.env.USERPROFILE;
+ const tmpDirs: string[] = [];
+
+ function restoreEnv(name: 'HOME' | 'USERPROFILE', value: string | undefined): void {
+ if (value === undefined) {
+ delete process.env[name];
+ } else {
+ process.env[name] = value;
+ }
+ }
+
+ afterEach(() => {
+ restoreEnv('HOME', originalHome);
+ restoreEnv('USERPROFILE', originalUserProfile);
+ for (const dir of tmpDirs.splice(0)) {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ // Build a throwaway installed-package layout: <root>/node_modules/pinchtab
+ // with a package.json, and return the compiled-code dir the runtime resolves
+ // from (dist/src, mirroring where platform.js lives when published).
+ function makeInstalledPackage(version: string): { pkgDir: string; fromDir: string } {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pinchtab-pkg-'));
+ tmpDirs.push(dir);
+ const pkgDir = path.join(dir, 'node_modules', 'pinchtab');
+ const fromDir = path.join(pkgDir, 'dist', 'src');
+ fs.mkdirSync(fromDir, { recursive: true });
+ fs.writeFileSync(
+ path.join(pkgDir, 'package.json'),
+ JSON.stringify({ name: 'pinchtab', version })
+ );
+ return { pkgDir, fromDir };
+ }
+
+ test('install target does not change with $HOME', () => {
+ const { pkgDir, fromDir } = makeInstalledPackage(VERSION);
+
+ process.env.HOME = '/root'; // postinstall as root under sudo
+ const installPath = getManagedBinaryPath(fromDir, BINARY_NAME, VERSION);
+
+ process.env.HOME = '/home/user1'; // CLI as the invoking user
+ const runPath = getManagedBinaryPath(fromDir, BINARY_NAME, VERSION);
+
+ assert.strictEqual(installPath, runPath, 'binary path must be independent of $HOME');
+ assert.ok(
+ installPath.startsWith(pkgDir + path.sep),
+ `binary must live under the package root, got ${installPath}`
+ );
+ assert.ok(
+ !installPath.includes(`${path.sep}.pinchtab${path.sep}`),
+ `binary must not resolve under a $HOME-based ~/.pinchtab dir, got ${installPath}`
+ );
+ });
+
+ test('resolve finds the package-relative binary under a different $HOME', () => {
+ const { fromDir } = makeInstalledPackage(VERSION);
+
+ // Simulate postinstall (root HOME) writing the downloaded binary.
+ process.env.HOME = '/root';
+ const installPath = getManagedBinaryPath(fromDir, BINARY_NAME, VERSION);
+ fs.mkdirSync(path.dirname(installPath), { recursive: true });
+ fs.writeFileSync(installPath, 'binary');
+
+ // Resolve as a different user β€” must still find it.
+ process.env.HOME = '/home/user1';
+ assert.strictEqual(resolveManagedBinaryPath(fromDir), installPath);
+ });
+
+ test('falls back to a legacy ~/.pinchtab binary for already-installed users', () => {
+ const { fromDir } = makeInstalledPackage(VERSION);
+
+ const fakeHome = fs.mkdtempSync(path.join(os.tmpdir(), 'pinchtab-home-'));
+ tmpDirs.push(fakeHome);
+ process.env.HOME = fakeHome;
+ delete process.env.USERPROFILE;
+
+ // A binary only in the legacy versioned location under $HOME.
+ const legacy = path.join(fakeHome, '.pinchtab', 'bin', VERSION, BINARY_NAME);
+ fs.mkdirSync(path.dirname(legacy), { recursive: true });
+ fs.writeFileSync(legacy, 'binary');
+
+ // Package-relative path does not exist β†’ resolver must fall back to legacy.
+ assert.strictEqual(resolveManagedBinaryPath(fromDir), legacy);
+ });
+
+ test('reports the package-relative path when nothing is installed yet', () => {
+ const { fromDir } = makeInstalledPackage(VERSION);
+ process.env.HOME = '/home/user1';
+
+ const resolved = resolveManagedBinaryPath(fromDir);
+ assert.strictEqual(resolved, getManagedBinaryPath(fromDir, BINARY_NAME, VERSION));
+ assert.ok(!resolved.includes(`${path.sep}.pinchtab${path.sep}`));
+ });
+});
diff --git a/scripts/check-npm.sh b/scripts/check-npm.sh
index 49e57571..f43c57c3 100644
--- a/scripts/check-npm.sh
+++ b/scripts/check-npm.sh
@@ -95,4 +95,9 @@ node -e "
npm audit --audit-level=moderate || true
+# Hermetic install smoke: install under one $HOME, run the CLI under another, and
+# assert it still finds the binary (issue #628). Reuses the tarball packed above.
+echo "Running install HOME-divergence smoke (issue #628)..."
+bash scripts/npm-install-home-divergence.sh "$PWD/$TARBALL"
+
echo "npm package verification passed."