npm-shim.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. #!/usr/bin/env node
  2. 'use strict';
  3. //
  4. // npm thin-installer launcher for CodeGraph.
  5. //
  6. // The heavy artifact (a vendored Node runtime + the app) ships as a per-platform
  7. // optionalDependency: @colbymchenry/codegraph-<platform>-<arch>. npm installs
  8. // only the one matching the host, via each package's `os`/`cpu` fields (the
  9. // esbuild pattern). This shim — run by the user's OWN Node — locates that bundle
  10. // and execs its launcher, so the real work always runs on the bundled Node 24
  11. // (with node:sqlite), regardless of the user's Node version. The user's Node is
  12. // only ever a launcher; even an ancient version can run this file.
  13. //
  14. // Self-heal (issue #303): some registries — notably the npmmirror/cnpm mirrors,
  15. // and some corporate proxies — don't reliably mirror the per-platform
  16. // optionalDependencies. npm treats an unfetchable optional dep as success and
  17. // silently skips it, so the bundle goes missing and every command fails. When
  18. // the installed bundle can't be resolved, this shim falls back to downloading
  19. // the matching bundle straight from GitHub Releases — the very archive
  20. // install.sh uses — into a cache dir, then runs that. Knobs:
  21. // CODEGRAPH_NO_DOWNLOAD=1 disable the network fallback (print guidance)
  22. // CODEGRAPH_INSTALL_DIR=DIR cache location (default: ~/.codegraph)
  23. // CODEGRAPH_DOWNLOAD_BASE=URL release-download base (for mirrors/air-gapped)
  24. //
  25. // Wired up at release time as the main package's `bin`:
  26. // "bin": { "codegraph": "npm-shim.js" }
  27. // with the platform packages listed in `optionalDependencies`.
  28. var childProcess = require('child_process');
  29. var fs = require('fs');
  30. var os = require('os');
  31. var path = require('path');
  32. var target = process.platform + '-' + process.arch; // e.g. darwin-arm64, linux-x64
  33. var pkg = '@colbymchenry/codegraph-' + target;
  34. var isWindows = process.platform === 'win32';
  35. var REPO = 'colbymchenry/codegraph';
  36. main().catch(function (e) {
  37. process.stderr.write('codegraph: ' + (e && e.message ? e.message : String(e)) + '\n');
  38. process.exit(1);
  39. });
  40. async function main() {
  41. // Happy path: the npm-installed optional dependency. Fall back to a download
  42. // when the registry didn't deliver it.
  43. var resolved = resolveInstalledBundle() || (await selfHealBundle());
  44. // Thread the MCP host's pid (our parent) down to the bundled server so its
  45. // orphan watchdog can poll the host directly. Without this, the server can
  46. // only watch THIS shim — and a shim killed during the server's first ~100ms
  47. // of startup used to leave the server orphaned forever (issue #1185). An
  48. // already-set value (an outer launcher) wins.
  49. var env = Object.assign({}, process.env);
  50. if (!env.CODEGRAPH_HOST_PPID) env.CODEGRAPH_HOST_PPID = String(process.ppid);
  51. var res = childProcess.spawnSync(resolved.command, resolved.args, { stdio: 'inherit', windowsHide: true, env: env });
  52. if (res.error) {
  53. process.stderr.write('codegraph: ' + res.error.message + '\n');
  54. process.exit(1);
  55. }
  56. process.exit(res.status === null ? 1 : res.status);
  57. }
  58. // Resolve the launcher from the installed per-platform optionalDependency.
  59. // Returns {command, args} or null if the package isn't installed.
  60. function resolveInstalledBundle() {
  61. try {
  62. if (isWindows) {
  63. // Modern Node refuses to spawn the bundle's .cmd directly (EINVAL, the
  64. // CVE-2024-27980 hardening on Node 24), so invoke the bundled node.exe
  65. // against the app entry point and pass --liftoff-only here.
  66. var nodeExe = require.resolve(pkg + '/node.exe');
  67. var entry = require.resolve(pkg + '/lib/dist/bin/codegraph.js');
  68. return { command: nodeExe, args: liftoff(entry) };
  69. }
  70. return { command: require.resolve(pkg + '/bin/codegraph'), args: process.argv.slice(2) };
  71. } catch (e) {
  72. return null;
  73. }
  74. }
  75. // Locate the launcher inside an extracted GitHub bundle directory (same
  76. // node/lib/bin layout as the npm platform package). Returns {command, args} or
  77. // null when the directory doesn't hold a usable bundle yet.
  78. function launcherIn(dir) {
  79. if (isWindows) {
  80. var nodeExe = path.join(dir, 'node.exe');
  81. var entry = path.join(dir, 'lib', 'dist', 'bin', 'codegraph.js');
  82. if (fs.existsSync(nodeExe) && fs.existsSync(entry)) {
  83. return { command: nodeExe, args: liftoff(entry) };
  84. }
  85. } else {
  86. var launcher = path.join(dir, 'bin', 'codegraph');
  87. if (fs.existsSync(launcher)) return { command: launcher, args: process.argv.slice(2) };
  88. }
  89. return null;
  90. }
  91. // --liftoff-only keeps tree-sitter's WASM grammars off V8's turboshaft tier to
  92. // avoid the Zone OOM on Node >= 22 (issues #293/#298). The unix bin/codegraph
  93. // launcher already passes it; on Windows we invoke node.exe directly so add it.
  94. // --disable-warning=ExperimentalWarning mutes node:sqlite's per-thread
  95. // "experimental feature" warning, which otherwise prints once per parse worker
  96. // mid-index, shredding the progress UI. The bundled node.exe is always new
  97. // enough for both flags.
  98. function liftoff(entry) {
  99. return ['--liftoff-only', '--disable-warning=ExperimentalWarning', entry].concat(process.argv.slice(2));
  100. }
  101. // Download + cache the platform bundle from GitHub Releases. Returns
  102. // {command, args}; exits the process with guidance if it can't.
  103. async function selfHealBundle() {
  104. var version = readVersion();
  105. var bundlesDir = path.join(process.env.CODEGRAPH_INSTALL_DIR || path.join(os.homedir(), '.codegraph'), 'bundles');
  106. var dest = path.join(bundlesDir, target + '-' + version);
  107. // Already downloaded by a previous run? Use it even when downloads are
  108. // disabled — CODEGRAPH_NO_DOWNLOAD blocks fetching, not a cached bundle.
  109. var cached = launcherIn(dest);
  110. if (cached) { pruneOldBundles(bundlesDir, dest); return cached; }
  111. if (process.env.CODEGRAPH_NO_DOWNLOAD) {
  112. fail('the network fallback is disabled (CODEGRAPH_NO_DOWNLOAD is set).');
  113. }
  114. var asset = 'codegraph-' + target + (isWindows ? '.zip' : '.tar.gz');
  115. var base = process.env.CODEGRAPH_DOWNLOAD_BASE || ('https://github.com/' + REPO + '/releases/download');
  116. var url = base + '/v' + version + '/' + asset;
  117. process.stderr.write(
  118. 'codegraph: platform bundle missing (registry did not provide ' + pkg + ').\n' +
  119. 'codegraph: downloading ' + asset + ' from GitHub Releases (' + version + ')...\n'
  120. );
  121. // Stage inside bundlesDir so the final rename is on the same filesystem (atomic,
  122. // no EXDEV across tmpfs). Strip the archive's top-level codegraph-<target>/ dir.
  123. fs.mkdirSync(bundlesDir, { recursive: true });
  124. var stage = fs.mkdtempSync(path.join(bundlesDir, '.dl-'));
  125. try {
  126. var archivePath = path.join(stage, asset);
  127. await download(url, archivePath, 6);
  128. await verifyChecksum(archivePath, asset, base, version);
  129. var extracted = path.join(stage, 'bundle');
  130. fs.mkdirSync(extracted);
  131. extract(archivePath, extracted);
  132. var raced = launcherIn(dest); // another process may have finished meanwhile
  133. if (raced) { rmrf(stage); return raced; }
  134. try {
  135. fs.renameSync(extracted, dest);
  136. } catch (e) {
  137. var other = launcherIn(dest); // lost the race but theirs is valid
  138. if (other) { rmrf(stage); return other; }
  139. throw e;
  140. }
  141. } catch (e) {
  142. rmrf(stage);
  143. fail('download failed (' + e.message + ').\n URL: ' + url);
  144. }
  145. rmrf(stage);
  146. var ready = launcherIn(dest);
  147. if (!ready) fail('downloaded bundle is missing its launcher under ' + dest + '.');
  148. pruneOldBundles(bundlesDir, dest);
  149. process.stderr.write('codegraph: bundle ready.\n');
  150. return ready;
  151. }
  152. function readVersion() {
  153. try {
  154. return require(path.join(__dirname, 'package.json')).version;
  155. } catch (e) {
  156. fail('could not read this package\'s version to locate a matching release.');
  157. }
  158. }
  159. // GET with manual redirect following (GitHub release URLs redirect to a CDN).
  160. function download(url, dest, redirectsLeft) {
  161. return new Promise(function (resolve, reject) {
  162. var https = require('https');
  163. // timeout is an idle/inactivity timeout — it won't kill a slow-but-progressing
  164. // download, only a stalled connection (so a blocked mirror fails fast with
  165. // guidance instead of hanging the user's command forever).
  166. var req = https.get(url, { headers: { 'User-Agent': 'codegraph-npm-shim' }, timeout: 30000 }, function (res) {
  167. var status = res.statusCode;
  168. if (status >= 300 && status < 400 && res.headers.location) {
  169. res.resume();
  170. if (redirectsLeft <= 0) { reject(new Error('too many redirects')); return; }
  171. download(new URL(res.headers.location, url).toString(), dest, redirectsLeft - 1).then(resolve, reject);
  172. return;
  173. }
  174. if (status !== 200) { res.resume(); reject(new Error('HTTP ' + status)); return; }
  175. var file = fs.createWriteStream(dest);
  176. res.on('error', reject);
  177. res.pipe(file);
  178. file.on('error', reject);
  179. file.on('finish', function () { file.close(function () { resolve(); }); });
  180. });
  181. req.on('timeout', function () { req.destroy(new Error('connection timed out')); });
  182. req.on('error', reject);
  183. });
  184. }
  185. // Best-effort integrity check. When the release publishes a SHA256SUMS file, the
  186. // downloaded archive MUST match its listed hash or we abort. When that file is
  187. // absent (older releases) or simply unreachable, we proceed — the archive still
  188. // arrived from GitHub over TLS. So tampering/corruption is caught, while a
  189. // missing checksum never breaks an install.
  190. async function verifyChecksum(archivePath, asset, base, version) {
  191. var sumsPath = archivePath + '.SHA256SUMS';
  192. try {
  193. await download(base + '/v' + version + '/SHA256SUMS', sumsPath, 6);
  194. } catch (e) {
  195. return; // not published / unreachable → skip
  196. }
  197. var expected = null;
  198. var lines = fs.readFileSync(sumsPath, 'utf8').split('\n');
  199. for (var i = 0; i < lines.length; i++) {
  200. var m = lines[i].trim().match(/^([0-9a-fA-F]{64})\s+\*?(.+)$/);
  201. if (m && path.basename(m[2].trim()) === asset) { expected = m[1].toLowerCase(); break; }
  202. }
  203. if (!expected) return; // asset not listed → nothing to check
  204. var actual = require('crypto').createHash('sha256').update(fs.readFileSync(archivePath)).digest('hex');
  205. if (actual !== expected) {
  206. throw new Error('checksum mismatch for ' + asset +
  207. ' (expected ' + expected.slice(0, 12) + '…, got ' + actual.slice(0, 12) + '…)');
  208. }
  209. process.stderr.write('codegraph: checksum verified.\n');
  210. }
  211. // Extract via the system tar — present on macOS, Linux, and Windows 10+
  212. // (bsdtar reads .zip too). No third-party dependency in the shim.
  213. function extract(archive, destDir) {
  214. var args = isWindows
  215. ? ['-xf', archive, '-C', destDir, '--strip-components=1']
  216. : ['-xzf', archive, '-C', destDir, '--strip-components=1'];
  217. var res = childProcess.spawnSync('tar', args, { stdio: 'ignore', windowsHide: true });
  218. if (res.error) throw new Error('tar unavailable: ' + res.error.message);
  219. if (res.status !== 0) throw new Error('tar exited ' + res.status);
  220. }
  221. function rmrf(p) {
  222. try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* best effort */ }
  223. }
  224. // Drop sibling bundles for OTHER versions of this same platform target, keeping
  225. // only keepDir. The self-heal cache otherwise accumulates a full ~50 MB bundle
  226. // per version forever (issue #1074). Best-effort: a locked/busy dir (a
  227. // concurrent run still mapping an older node.exe on Windows) just stays — rmrf
  228. // already swallows its own errors, and the readdir is guarded — so cleanup can
  229. // never break a working command. Only this target's "<target>-<version>" dirs
  230. // are touched; other platforms' bundles and the ".dl-*" staging dirs are left
  231. // alone.
  232. function pruneOldBundles(bundlesDir, keepDir) {
  233. var keep = path.basename(keepDir);
  234. try {
  235. var names = fs.readdirSync(bundlesDir);
  236. for (var i = 0; i < names.length; i++) {
  237. var name = names[i];
  238. if (name === keep) continue;
  239. if (name.indexOf(target + '-') !== 0) continue;
  240. rmrf(path.join(bundlesDir, name));
  241. }
  242. } catch (e) { /* best effort — never break a working run over cleanup */ }
  243. }
  244. function fail(reason) {
  245. process.stderr.write(
  246. 'codegraph: no prebuilt bundle for ' + target + '.\n' +
  247. (reason ? 'codegraph: ' + reason + '\n' : '') +
  248. 'Expected the optional package ' + pkg + ' to be installed.\n' +
  249. 'A registry mirror (e.g. npmmirror/cnpm) that did not mirror the per-platform\n' +
  250. 'package is the usual cause. Fixes:\n' +
  251. ' - install from the official registry:\n' +
  252. ' npm i -g @colbymchenry/codegraph --registry=https://registry.npmjs.org\n' +
  253. ' - or use the standalone installer (no Node required):\n' +
  254. ' curl -fsSL https://raw.githubusercontent.com/' + REPO + '/main/install.sh | sh\n'
  255. );
  256. process.exit(1);
  257. }