npm-shim.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. function liftoff(entry) {
  95. return ['--liftoff-only', entry].concat(process.argv.slice(2));
  96. }
  97. // Download + cache the platform bundle from GitHub Releases. Returns
  98. // {command, args}; exits the process with guidance if it can't.
  99. async function selfHealBundle() {
  100. var version = readVersion();
  101. var bundlesDir = path.join(process.env.CODEGRAPH_INSTALL_DIR || path.join(os.homedir(), '.codegraph'), 'bundles');
  102. var dest = path.join(bundlesDir, target + '-' + version);
  103. // Already downloaded by a previous run? Use it even when downloads are
  104. // disabled — CODEGRAPH_NO_DOWNLOAD blocks fetching, not a cached bundle.
  105. var cached = launcherIn(dest);
  106. if (cached) { pruneOldBundles(bundlesDir, dest); return cached; }
  107. if (process.env.CODEGRAPH_NO_DOWNLOAD) {
  108. fail('the network fallback is disabled (CODEGRAPH_NO_DOWNLOAD is set).');
  109. }
  110. var asset = 'codegraph-' + target + (isWindows ? '.zip' : '.tar.gz');
  111. var base = process.env.CODEGRAPH_DOWNLOAD_BASE || ('https://github.com/' + REPO + '/releases/download');
  112. var url = base + '/v' + version + '/' + asset;
  113. process.stderr.write(
  114. 'codegraph: platform bundle missing (registry did not provide ' + pkg + ').\n' +
  115. 'codegraph: downloading ' + asset + ' from GitHub Releases (' + version + ')...\n'
  116. );
  117. // Stage inside bundlesDir so the final rename is on the same filesystem (atomic,
  118. // no EXDEV across tmpfs). Strip the archive's top-level codegraph-<target>/ dir.
  119. fs.mkdirSync(bundlesDir, { recursive: true });
  120. var stage = fs.mkdtempSync(path.join(bundlesDir, '.dl-'));
  121. try {
  122. var archivePath = path.join(stage, asset);
  123. await download(url, archivePath, 6);
  124. await verifyChecksum(archivePath, asset, base, version);
  125. var extracted = path.join(stage, 'bundle');
  126. fs.mkdirSync(extracted);
  127. extract(archivePath, extracted);
  128. var raced = launcherIn(dest); // another process may have finished meanwhile
  129. if (raced) { rmrf(stage); return raced; }
  130. try {
  131. fs.renameSync(extracted, dest);
  132. } catch (e) {
  133. var other = launcherIn(dest); // lost the race but theirs is valid
  134. if (other) { rmrf(stage); return other; }
  135. throw e;
  136. }
  137. } catch (e) {
  138. rmrf(stage);
  139. fail('download failed (' + e.message + ').\n URL: ' + url);
  140. }
  141. rmrf(stage);
  142. var ready = launcherIn(dest);
  143. if (!ready) fail('downloaded bundle is missing its launcher under ' + dest + '.');
  144. pruneOldBundles(bundlesDir, dest);
  145. process.stderr.write('codegraph: bundle ready.\n');
  146. return ready;
  147. }
  148. function readVersion() {
  149. try {
  150. return require(path.join(__dirname, 'package.json')).version;
  151. } catch (e) {
  152. fail('could not read this package\'s version to locate a matching release.');
  153. }
  154. }
  155. // GET with manual redirect following (GitHub release URLs redirect to a CDN).
  156. function download(url, dest, redirectsLeft) {
  157. return new Promise(function (resolve, reject) {
  158. var https = require('https');
  159. // timeout is an idle/inactivity timeout — it won't kill a slow-but-progressing
  160. // download, only a stalled connection (so a blocked mirror fails fast with
  161. // guidance instead of hanging the user's command forever).
  162. var req = https.get(url, { headers: { 'User-Agent': 'codegraph-npm-shim' }, timeout: 30000 }, function (res) {
  163. var status = res.statusCode;
  164. if (status >= 300 && status < 400 && res.headers.location) {
  165. res.resume();
  166. if (redirectsLeft <= 0) { reject(new Error('too many redirects')); return; }
  167. download(new URL(res.headers.location, url).toString(), dest, redirectsLeft - 1).then(resolve, reject);
  168. return;
  169. }
  170. if (status !== 200) { res.resume(); reject(new Error('HTTP ' + status)); return; }
  171. var file = fs.createWriteStream(dest);
  172. res.on('error', reject);
  173. res.pipe(file);
  174. file.on('error', reject);
  175. file.on('finish', function () { file.close(function () { resolve(); }); });
  176. });
  177. req.on('timeout', function () { req.destroy(new Error('connection timed out')); });
  178. req.on('error', reject);
  179. });
  180. }
  181. // Best-effort integrity check. When the release publishes a SHA256SUMS file, the
  182. // downloaded archive MUST match its listed hash or we abort. When that file is
  183. // absent (older releases) or simply unreachable, we proceed — the archive still
  184. // arrived from GitHub over TLS. So tampering/corruption is caught, while a
  185. // missing checksum never breaks an install.
  186. async function verifyChecksum(archivePath, asset, base, version) {
  187. var sumsPath = archivePath + '.SHA256SUMS';
  188. try {
  189. await download(base + '/v' + version + '/SHA256SUMS', sumsPath, 6);
  190. } catch (e) {
  191. return; // not published / unreachable → skip
  192. }
  193. var expected = null;
  194. var lines = fs.readFileSync(sumsPath, 'utf8').split('\n');
  195. for (var i = 0; i < lines.length; i++) {
  196. var m = lines[i].trim().match(/^([0-9a-fA-F]{64})\s+\*?(.+)$/);
  197. if (m && path.basename(m[2].trim()) === asset) { expected = m[1].toLowerCase(); break; }
  198. }
  199. if (!expected) return; // asset not listed → nothing to check
  200. var actual = require('crypto').createHash('sha256').update(fs.readFileSync(archivePath)).digest('hex');
  201. if (actual !== expected) {
  202. throw new Error('checksum mismatch for ' + asset +
  203. ' (expected ' + expected.slice(0, 12) + '…, got ' + actual.slice(0, 12) + '…)');
  204. }
  205. process.stderr.write('codegraph: checksum verified.\n');
  206. }
  207. // Extract via the system tar — present on macOS, Linux, and Windows 10+
  208. // (bsdtar reads .zip too). No third-party dependency in the shim.
  209. function extract(archive, destDir) {
  210. var args = isWindows
  211. ? ['-xf', archive, '-C', destDir, '--strip-components=1']
  212. : ['-xzf', archive, '-C', destDir, '--strip-components=1'];
  213. var res = childProcess.spawnSync('tar', args, { stdio: 'ignore', windowsHide: true });
  214. if (res.error) throw new Error('tar unavailable: ' + res.error.message);
  215. if (res.status !== 0) throw new Error('tar exited ' + res.status);
  216. }
  217. function rmrf(p) {
  218. try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* best effort */ }
  219. }
  220. // Drop sibling bundles for OTHER versions of this same platform target, keeping
  221. // only keepDir. The self-heal cache otherwise accumulates a full ~50 MB bundle
  222. // per version forever (issue #1074). Best-effort: a locked/busy dir (a
  223. // concurrent run still mapping an older node.exe on Windows) just stays — rmrf
  224. // already swallows its own errors, and the readdir is guarded — so cleanup can
  225. // never break a working command. Only this target's "<target>-<version>" dirs
  226. // are touched; other platforms' bundles and the ".dl-*" staging dirs are left
  227. // alone.
  228. function pruneOldBundles(bundlesDir, keepDir) {
  229. var keep = path.basename(keepDir);
  230. try {
  231. var names = fs.readdirSync(bundlesDir);
  232. for (var i = 0; i < names.length; i++) {
  233. var name = names[i];
  234. if (name === keep) continue;
  235. if (name.indexOf(target + '-') !== 0) continue;
  236. rmrf(path.join(bundlesDir, name));
  237. }
  238. } catch (e) { /* best effort — never break a working run over cleanup */ }
  239. }
  240. function fail(reason) {
  241. process.stderr.write(
  242. 'codegraph: no prebuilt bundle for ' + target + '.\n' +
  243. (reason ? 'codegraph: ' + reason + '\n' : '') +
  244. 'Expected the optional package ' + pkg + ' to be installed.\n' +
  245. 'A registry mirror (e.g. npmmirror/cnpm) that did not mirror the per-platform\n' +
  246. 'package is the usual cause. Fixes:\n' +
  247. ' - install from the official registry:\n' +
  248. ' npm i -g @colbymchenry/codegraph --registry=https://registry.npmjs.org\n' +
  249. ' - or use the standalone installer (no Node required):\n' +
  250. ' curl -fsSL https://raw.githubusercontent.com/' + REPO + '/main/install.sh | sh\n'
  251. );
  252. process.exit(1);
  253. }