1
0

npm-shim.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /**
  2. * npm thin-installer launcher (`scripts/npm-shim.js`) tests.
  3. *
  4. * The shim runs on the user's own Node, locates the per-platform optionalDependency
  5. * bundle, and — when a registry mirror failed to deliver it (issue #303) — falls
  6. * back to downloading the bundle from GitHub Releases. These tests exercise that
  7. * shim as a real subprocess from a temp "main package" dir (its own package.json
  8. * + node_modules), so resolution and version lookup behave hermetically.
  9. *
  10. * The download/checksum paths run against a local self-signed HTTPS server via
  11. * CODEGRAPH_DOWNLOAD_BASE — no real network, no published release needed. The
  12. * shim is launched with async `spawn` (not spawnSync), so the test's event loop
  13. * stays free to serve those requests.
  14. *
  15. * POSIX only: the fake bundle launcher is a shell script and extraction uses the
  16. * system `tar`. Skipped on Windows (where the shim's exec path differs anyway).
  17. */
  18. import { describe, it, expect, beforeAll, afterAll } from 'vitest';
  19. import { spawn, execSync } from 'child_process';
  20. import * as https from 'https';
  21. import * as fs from 'fs';
  22. import * as os from 'os';
  23. import * as path from 'path';
  24. import * as crypto from 'crypto';
  25. import type { AddressInfo } from 'net';
  26. const SHIM_SRC = path.join(__dirname, '..', 'scripts', 'npm-shim.js');
  27. const target = `${process.platform}-${process.arch}`;
  28. const asset = `codegraph-${target}.tar.gz`;
  29. const isWindows = process.platform === 'win32';
  30. function hasOpenssl(): boolean {
  31. try { execSync('openssl version', { stdio: 'ignore' }); return true; } catch { return false; }
  32. }
  33. const CAN_NET = !isWindows && hasOpenssl();
  34. function mkTmp(label: string): string {
  35. return fs.mkdtempSync(path.join(os.tmpdir(), `cg-shim-${label}-`));
  36. }
  37. // A temp dir standing in for the installed @colbymchenry/codegraph main package.
  38. function makePkg(version = '9.9.9-test'): string {
  39. const dir = mkTmp('pkg');
  40. fs.copyFileSync(SHIM_SRC, path.join(dir, 'npm-shim.js'));
  41. fs.writeFileSync(path.join(dir, 'package.json'),
  42. JSON.stringify({ name: '@colbymchenry/codegraph', version }) + '\n');
  43. return dir;
  44. }
  45. // A fake bundle launcher that prints a marker + its args, so we can prove the
  46. // shim found and exec'd it (and passed args through).
  47. function writeLauncher(binDir: string): void {
  48. fs.mkdirSync(binDir, { recursive: true });
  49. const p = path.join(binDir, 'codegraph');
  50. fs.writeFileSync(p, '#!/bin/sh\necho "FAKE_BUNDLE_RAN args:$*"\n');
  51. fs.chmodSync(p, 0o755);
  52. }
  53. // A fake bundle launcher that echoes the threaded host pid, so we can prove the
  54. // shim passed CODEGRAPH_HOST_PPID down to the server (#1185).
  55. function writeHostPpidLauncher(binDir: string): void {
  56. fs.mkdirSync(binDir, { recursive: true });
  57. const p = path.join(binDir, 'codegraph');
  58. fs.writeFileSync(p, '#!/bin/sh\necho "HOST_PPID=[${CODEGRAPH_HOST_PPID}]"\n');
  59. fs.chmodSync(p, 0o755);
  60. }
  61. // Launch the shim with async spawn so the in-process HTTPS server can respond
  62. // while it runs (spawnSync would block this event loop and deadlock).
  63. function runShim(pkgDir: string, args: string[], env: Record<string, string>) {
  64. return new Promise<{ status: number | null; stdout: string; stderr: string }>((resolve) => {
  65. const child = spawn(process.execPath, [path.join(pkgDir, 'npm-shim.js'), ...args], {
  66. env: { ...process.env, ...env },
  67. });
  68. let stdout = '', stderr = '';
  69. child.stdout.on('data', (d) => { stdout += d.toString(); });
  70. child.stderr.on('data', (d) => { stderr += d.toString(); });
  71. child.on('close', (status) => resolve({ status, stdout, stderr }));
  72. });
  73. }
  74. // Static source guard (all platforms): every child spawn in the shim must set
  75. // windowsHide, or a console (conhost) window flashes when the shim runs as a
  76. // background MCP server on Windows (issue #1092). windowsHide is a Windows-only
  77. // spawn behavior that can't be observed from these POSIX-only subprocess tests,
  78. // so we assert it at the source level instead — and this also catches any new
  79. // spawn site added to the shim later.
  80. describe('npm-shim windowsHide (#1092)', () => {
  81. it('sets windowsHide: true on every spawn in the shim', () => {
  82. const src = fs.readFileSync(SHIM_SRC, 'utf8');
  83. const spawnLines = src.split('\n').filter((l) => /\.spawn(Sync)?\(/.test(l));
  84. expect(spawnLines.length).toBeGreaterThan(0); // guard against a false pass if the calls move
  85. for (const line of spawnLines) {
  86. expect(line, `spawn without windowsHide: ${line.trim()}`).toContain('windowsHide: true');
  87. }
  88. });
  89. });
  90. describe.skipIf(isWindows)('npm-shim launcher', () => {
  91. it('runs the installed optional-dependency bundle without any download', async () => {
  92. const pkg = makePkg();
  93. const platformPkg = path.join(pkg, 'node_modules', '@colbymchenry', `codegraph-${target}`);
  94. writeLauncher(path.join(platformPkg, 'bin'));
  95. fs.writeFileSync(path.join(platformPkg, 'package.json'),
  96. JSON.stringify({ name: `@colbymchenry/codegraph-${target}`, version: '9.9.9-test' }) + '\n');
  97. const cache = mkTmp('cache');
  98. const r = await runShim(pkg, ['--probe-abc'], { CODEGRAPH_INSTALL_DIR: cache });
  99. expect(r.status).toBe(0);
  100. expect(r.stdout).toContain('FAKE_BUNDLE_RAN');
  101. expect(r.stdout).toContain('--probe-abc'); // args passed through
  102. expect(r.stderr).not.toContain('downloading'); // never reached the fallback
  103. expect(fs.existsSync(path.join(cache, 'bundles'))).toBe(false);
  104. });
  105. it('uses an already-cached bundle even when downloads are disabled', async () => {
  106. const pkg = makePkg('1.2.3-cached');
  107. const cache = mkTmp('cache');
  108. writeLauncher(path.join(cache, 'bundles', `${target}-1.2.3-cached`, 'bin'));
  109. const r = await runShim(pkg, ['--probe-xyz'], {
  110. CODEGRAPH_INSTALL_DIR: cache,
  111. CODEGRAPH_NO_DOWNLOAD: '1',
  112. });
  113. expect(r.status).toBe(0);
  114. expect(r.stdout).toContain('FAKE_BUNDLE_RAN');
  115. expect(r.stdout).toContain('--probe-xyz');
  116. expect(r.stderr).toBe('');
  117. });
  118. it('prunes older cached bundles for this target, keeping the current one (#1074)', async () => {
  119. const pkg = makePkg('2.0.0-keep');
  120. const cache = mkTmp('cache');
  121. const bundles = path.join(cache, 'bundles');
  122. // current (matches pkg version) + an older bundle for the same target
  123. writeLauncher(path.join(bundles, `${target}-2.0.0-keep`, 'bin'));
  124. writeLauncher(path.join(bundles, `${target}-1.0.0-old`, 'bin'));
  125. // a different platform's bundle and an in-flight staging dir must survive
  126. const otherTarget = target === 'linux-x64' ? 'darwin-arm64' : 'linux-x64';
  127. writeLauncher(path.join(bundles, `${otherTarget}-1.0.0`, 'bin'));
  128. fs.mkdirSync(path.join(bundles, '.dl-inflight'), { recursive: true });
  129. const r = await runShim(pkg, ['--probe-prune'], {
  130. CODEGRAPH_INSTALL_DIR: cache,
  131. CODEGRAPH_NO_DOWNLOAD: '1',
  132. });
  133. expect(r.status).toBe(0);
  134. expect(r.stdout).toContain('FAKE_BUNDLE_RAN');
  135. // older same-target bundle pruned; current kept
  136. expect(fs.existsSync(path.join(bundles, `${target}-1.0.0-old`))).toBe(false);
  137. expect(fs.existsSync(path.join(bundles, `${target}-2.0.0-keep`))).toBe(true);
  138. // unrelated target + staging dir untouched
  139. expect(fs.existsSync(path.join(bundles, `${otherTarget}-1.0.0`))).toBe(true);
  140. expect(fs.existsSync(path.join(bundles, '.dl-inflight'))).toBe(true);
  141. });
  142. it('prints actionable guidance and exits 1 when disabled with no bundle', async () => {
  143. const pkg = makePkg();
  144. const r = await runShim(pkg, ['--version'], {
  145. CODEGRAPH_INSTALL_DIR: mkTmp('cache'),
  146. CODEGRAPH_NO_DOWNLOAD: '1',
  147. });
  148. expect(r.status).toBe(1);
  149. expect(r.stderr).toContain(`no prebuilt bundle for ${target}`);
  150. expect(r.stderr).toContain(`@colbymchenry/codegraph-${target}`);
  151. expect(r.stderr).toContain('--registry=https://registry.npmjs.org');
  152. expect(r.stderr).toContain('install.sh');
  153. });
  154. // #1185: the shim threads the MCP host's pid (its own parent) down to the
  155. // bundled server so the server's orphan watchdog can poll the host directly
  156. // — the fix for a server left orphaned when the launcher is killed during its
  157. // startup. The shim's own parent here is the vitest runner (a real live pid).
  158. it('threads CODEGRAPH_HOST_PPID to the bundled server (#1185)', async () => {
  159. const pkg = makePkg();
  160. const platformPkg = path.join(pkg, 'node_modules', '@colbymchenry', `codegraph-${target}`);
  161. writeHostPpidLauncher(path.join(platformPkg, 'bin'));
  162. fs.writeFileSync(path.join(platformPkg, 'package.json'),
  163. JSON.stringify({ name: `@colbymchenry/codegraph-${target}`, version: '9.9.9-test' }) + '\n');
  164. const r = await runShim(pkg, [], { CODEGRAPH_INSTALL_DIR: mkTmp('cache') });
  165. expect(r.status).toBe(0);
  166. // Non-empty and numeric — the shim's parent pid was passed through.
  167. const m = r.stdout.match(/HOST_PPID=\[(\d+)\]/);
  168. expect(m, `expected a numeric HOST_PPID, got: ${r.stdout}`).not.toBeNull();
  169. expect(Number(m![1])).toBeGreaterThan(0);
  170. });
  171. it('does not clobber an already-set CODEGRAPH_HOST_PPID (#1185)', async () => {
  172. const pkg = makePkg();
  173. const platformPkg = path.join(pkg, 'node_modules', '@colbymchenry', `codegraph-${target}`);
  174. writeHostPpidLauncher(path.join(platformPkg, 'bin'));
  175. fs.writeFileSync(path.join(platformPkg, 'package.json'),
  176. JSON.stringify({ name: `@colbymchenry/codegraph-${target}`, version: '9.9.9-test' }) + '\n');
  177. // An outer launcher already threaded the true host pid — it must win over
  178. // the shim's own parent, or a chain of launchers would each overwrite it.
  179. const r = await runShim(pkg, [], { CODEGRAPH_INSTALL_DIR: mkTmp('cache'), CODEGRAPH_HOST_PPID: '424242' });
  180. expect(r.status).toBe(0);
  181. expect(r.stdout).toContain('HOST_PPID=[424242]');
  182. });
  183. });
  184. describe.skipIf(!CAN_NET)('npm-shim download fallback (local HTTPS)', () => {
  185. let server: https.Server;
  186. let port = 0;
  187. let fixtureBytes: Buffer;
  188. let fixtureSha: string;
  189. let sumsBody: string | null = null; // per-test: SHA256SUMS contents, or null for 404
  190. beforeAll(async () => {
  191. // Self-signed cert for the mock release host.
  192. const cdir = mkTmp('tls');
  193. const keyP = path.join(cdir, 'key.pem');
  194. const certP = path.join(cdir, 'cert.pem');
  195. execSync(
  196. `openssl req -x509 -newkey rsa:2048 -nodes -keyout ${keyP} -out ${certP} -days 1 -subj "/CN=localhost"`,
  197. { stdio: 'ignore' },
  198. );
  199. // Build a fake bundle archive (codegraph-<target>/bin/codegraph), like a real release asset.
  200. const work = mkTmp('fixture');
  201. writeLauncher(path.join(work, `codegraph-${target}`, 'bin'));
  202. const archive = path.join(work, asset);
  203. execSync(`tar -czf ${JSON.stringify(archive)} -C ${JSON.stringify(work)} codegraph-${target}`);
  204. fixtureBytes = fs.readFileSync(archive);
  205. fixtureSha = crypto.createHash('sha256').update(fixtureBytes).digest('hex');
  206. server = https.createServer({ key: fs.readFileSync(keyP), cert: fs.readFileSync(certP) }, (req, res) => {
  207. const url = req.url || '';
  208. if (url.endsWith(`/${asset}`)) {
  209. res.writeHead(200); res.end(fixtureBytes);
  210. } else if (url.endsWith('/SHA256SUMS')) {
  211. if (sumsBody === null) { res.writeHead(404); res.end('not found'); }
  212. else { res.writeHead(200); res.end(sumsBody); }
  213. } else {
  214. res.writeHead(404); res.end('not found');
  215. }
  216. });
  217. await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
  218. port = (server.address() as AddressInfo).port;
  219. }, 30000);
  220. afterAll(() => { server?.close(); });
  221. function netEnv(cache: string): Record<string, string> {
  222. return {
  223. CODEGRAPH_INSTALL_DIR: cache,
  224. CODEGRAPH_DOWNLOAD_BASE: `https://127.0.0.1:${port}`,
  225. NODE_TLS_REJECT_UNAUTHORIZED: '0',
  226. };
  227. }
  228. it('downloads, verifies the checksum, extracts, and execs the bundle', async () => {
  229. sumsBody = `${fixtureSha} ${asset}\n`;
  230. const pkg = makePkg('5.0.0-net');
  231. const cache = mkTmp('cache');
  232. const r = await runShim(pkg, ['--probe-net'], netEnv(cache));
  233. expect(r.stderr).toContain('downloading');
  234. expect(r.stderr).toContain('checksum verified');
  235. expect(r.status).toBe(0);
  236. expect(r.stdout).toContain('FAKE_BUNDLE_RAN');
  237. expect(r.stdout).toContain('--probe-net');
  238. expect(fs.existsSync(path.join(cache, 'bundles', `${target}-5.0.0-net`, 'bin', 'codegraph'))).toBe(true);
  239. }, 20000);
  240. it('prunes older cached bundles after downloading a new one (#1074)', async () => {
  241. sumsBody = `${fixtureSha} ${asset}\n`;
  242. const pkg = makePkg('6.0.0-new');
  243. const cache = mkTmp('cache');
  244. const bundles = path.join(cache, 'bundles');
  245. // a stale bundle from a previous version (same target) left by an earlier run
  246. writeLauncher(path.join(bundles, `${target}-5.0.0-stale`, 'bin'));
  247. const r = await runShim(pkg, ['--probe-newdl'], netEnv(cache));
  248. expect(r.status).toBe(0);
  249. expect(r.stderr).toContain('downloading');
  250. expect(r.stdout).toContain('FAKE_BUNDLE_RAN');
  251. // freshly downloaded version present, stale one pruned
  252. expect(fs.existsSync(path.join(bundles, `${target}-6.0.0-new`, 'bin', 'codegraph'))).toBe(true);
  253. expect(fs.existsSync(path.join(bundles, `${target}-5.0.0-stale`))).toBe(false);
  254. }, 20000);
  255. it('aborts (exit 1) on a checksum mismatch and caches nothing', async () => {
  256. sumsBody = `${'0'.repeat(64)} ${asset}\n`;
  257. const pkg = makePkg('5.0.0-bad');
  258. const cache = mkTmp('cache');
  259. const r = await runShim(pkg, ['--version'], netEnv(cache));
  260. expect(r.status).toBe(1);
  261. expect(r.stderr).toContain('checksum mismatch');
  262. expect(r.stdout).not.toContain('FAKE_BUNDLE_RAN'); // never exec'd a tampered bundle
  263. expect(fs.existsSync(path.join(cache, 'bundles', `${target}-5.0.0-bad`))).toBe(false);
  264. }, 20000);
  265. it('proceeds when no SHA256SUMS is published (older releases)', async () => {
  266. sumsBody = null; // 404
  267. const pkg = makePkg('5.0.0-nosums');
  268. const cache = mkTmp('cache');
  269. const r = await runShim(pkg, ['--version'], netEnv(cache));
  270. expect(r.status).toBe(0);
  271. expect(r.stderr).toContain('downloading');
  272. expect(r.stderr).not.toContain('checksum verified'); // skipped, not failed
  273. expect(r.stdout).toContain('FAKE_BUNDLE_RAN');
  274. }, 20000);
  275. });