mcode-tools-integration.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. import { execFileSync } from 'node:child_process';
  2. import { chmod, copyFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
  3. import { tmpdir } from 'node:os';
  4. import path from 'node:path';
  5. import { fileURLToPath, pathToFileURL } from 'node:url';
  6. import type {
  7. McodeToolsAuthStatusSnapshot,
  8. McodeToolsHostAuthSession,
  9. ValidatedMcodeToolsResource,
  10. } from '@mavis/mcode-tools-host';
  11. import { afterEach, describe, expect, it, vi } from 'vitest';
  12. import {
  13. activateTuiMcodeToolsHostEnvironment,
  14. configureMcodeToolsChildEnvironment,
  15. } from '../../src/cli/mcode-tools-environment.js';
  16. import {
  17. createTuiMcodeToolsRuntimeDir,
  18. prepareTuiMcodeToolsIntegration,
  19. resolveBundledMcodeToolsResourceDir,
  20. } from '../../src/runtime/mcode-tools-integration.js';
  21. const temporaryDirectories: string[] = [];
  22. afterEach(async () => {
  23. await Promise.all(
  24. temporaryDirectories.splice(0).map((directory) =>
  25. rm(directory, { recursive: true, force: true }),
  26. ),
  27. );
  28. });
  29. describe('TUI mcode-tools integration readiness', () => {
  30. it.skipIf(process.platform === 'win32')(
  31. 'keeps the POSIX broker socket path below platform limits',
  32. async () => {
  33. const runtimeDir = await createTuiMcodeToolsRuntimeDir();
  34. temporaryDirectories.push(runtimeDir);
  35. expect(runtimeDir).toMatch(/^\/tmp\/mcode-tools-tui-\d+-/u);
  36. expect(path.join(runtimeDir, 'run', 'mcode-auth-lease-v1.sock').length).toBeLessThan(100);
  37. },
  38. );
  39. it('does no resource or broker work when the capability is not requested', async () => {
  40. const validateResource = vi.fn();
  41. const startBroker = vi.fn();
  42. const result = await prepareTuiMcodeToolsIntegration(
  43. {
  44. requested: false,
  45. dataDir: '/profile',
  46. buildEnv: 'test',
  47. region: 'cn',
  48. session: createSession({ status: 'anonymous', generation: 0 }).session,
  49. entryUrl: pathToFileURL('/package/cli.js').href,
  50. },
  51. { validateResource, startBroker },
  52. );
  53. expect(result).toMatchObject({ requested: false, ready: false, category: 'disabled' });
  54. expect(validateResource).not.toHaveBeenCalled();
  55. expect(startBroker).not.toHaveBeenCalled();
  56. });
  57. it('keeps the package-owned command active while the broker owns authentication', async () => {
  58. const dataDir = await makeTemporaryDirectory();
  59. const runtimeDir = path.join(dataDir, 'run', 'mcode-tools', 'tui', 'runtime');
  60. const environment: Record<string, string | undefined> = {
  61. PATH: ['/usr/bin', '/bin'].join(path.delimiter),
  62. };
  63. const auth = createSession({ status: 'anonymous', generation: 1 });
  64. const brokerDispose = vi.fn(async () => undefined);
  65. const removeRuntimeDir = vi.fn(async () => undefined);
  66. const validateResource = vi.fn(() => validatedResource('/package/embedded/mcode-tools'));
  67. const startBroker = vi.fn(async () => ({
  68. endpoint: path.join(runtimeDir, 'broker.sock'),
  69. capabilityFile: path.join(runtimeDir, 'broker.cap'),
  70. dispose: brokerDispose,
  71. }));
  72. const result = await prepareTuiMcodeToolsIntegration(
  73. {
  74. requested: true,
  75. dataDir,
  76. buildEnv: 'dev',
  77. region: 'en',
  78. bedrockLane: 'oauth2',
  79. session: auth.session,
  80. entryUrl: pathToFileURL('/package/cli.js').href,
  81. environment,
  82. },
  83. {
  84. validateResource,
  85. startBroker,
  86. createRuntimeDir: vi.fn(async () => runtimeDir),
  87. removeRuntimeDir,
  88. },
  89. );
  90. expect(result).toMatchObject({
  91. requested: true,
  92. ready: true,
  93. category: 'ready',
  94. buildEnv: 'test',
  95. version: '0.0.0-test.1',
  96. });
  97. expect(validateResource).toHaveBeenCalledWith({
  98. resourceDir: path.resolve('/package', 'embedded', 'mcode-tools'),
  99. expectedBuildEnv: 'test',
  100. });
  101. expect(startBroker).toHaveBeenCalledWith({
  102. dataDir: runtimeDir,
  103. session: auth.session,
  104. logger: expect.any(Object),
  105. });
  106. expect(environment.__MAVIS_MCODE_TOOLS_BROKER_ENDPOINT).toBe(
  107. path.join(runtimeDir, 'broker.sock'),
  108. );
  109. expect(environment.__MAVIS_MCODE_TOOLS_BROKER_CAPABILITY_FILE).toBe(
  110. path.join(runtimeDir, 'broker.cap'),
  111. );
  112. expect(environment.__MAVIS_MCODE_TOOLS_CONFIG_DIR).toBe(
  113. path.join(dataDir, 'integrations', 'mcode-tools', 'en'),
  114. );
  115. expect(environment.__MAVIS_MCODE_TOOLS_REGION).toBe('en');
  116. expect(environment.__MAVIS_MCODE_TOOLS_EXTRA_HEADERS).toBe(
  117. 'bedrock_lane:oauth2,bedrock-lane:oauth2',
  118. );
  119. expect(environment.__MAVIS_MCODE_TOOLS_RUNTIME_EXECUTABLE).toBe(process.execPath);
  120. expect(environment.PATH?.split(path.delimiter)[0]).toBe(
  121. path.resolve('/package', 'internal-bin'),
  122. );
  123. environment.PATH = ['/stale/profile/bin', environment.PATH ?? ''].join(path.delimiter);
  124. result.ensureCommandPath();
  125. expect(environment.PATH.split(path.delimiter)[0]).toBe(path.resolve('/package', 'internal-bin'));
  126. await result.dispose();
  127. await result.dispose();
  128. expect(brokerDispose).toHaveBeenCalledOnce();
  129. expect(removeRuntimeDir).toHaveBeenCalledOnce();
  130. expect(environment.__MAVIS_MCODE_TOOLS_BROKER_ENDPOINT).toBeUndefined();
  131. expect(environment.__MAVIS_MCODE_TOOLS_RUNTIME_EXECUTABLE).toBeUndefined();
  132. expect(environment.PATH?.split(path.delimiter)).not.toContain(
  133. path.resolve('/package', 'internal-bin'),
  134. );
  135. });
  136. it('keeps concurrent TUI broker and command environments independent', async () => {
  137. const sharedDataDir = await makeTemporaryDirectory();
  138. const firstEnvironment: Record<string, string | undefined> = { PATH: '/usr/bin' };
  139. const secondEnvironment: Record<string, string | undefined> = { PATH: '/usr/bin' };
  140. const brokerDisposals: ReturnType<typeof vi.fn>[] = [];
  141. const startBroker = vi.fn(async ({ dataDir }: { dataDir: string }) => {
  142. const dispose = vi.fn(async () => undefined);
  143. brokerDisposals.push(dispose);
  144. return {
  145. endpoint: path.join(dataDir, 'broker.sock'),
  146. capabilityFile: path.join(dataDir, 'broker.cap'),
  147. dispose,
  148. };
  149. });
  150. const dependencies = {
  151. validateResource: vi.fn(() => validatedResource('/package/embedded/mcode-tools')),
  152. startBroker,
  153. };
  154. const options = {
  155. requested: true,
  156. dataDir: sharedDataDir,
  157. buildEnv: 'test' as const,
  158. region: 'en' as const,
  159. session: createSession({ status: 'authenticated' as const, generation: 1 }).session,
  160. entryUrl: pathToFileURL('/package/cli.js').href,
  161. };
  162. const [first, second] = await Promise.all([
  163. prepareTuiMcodeToolsIntegration(
  164. { ...options, environment: firstEnvironment },
  165. dependencies,
  166. ),
  167. prepareTuiMcodeToolsIntegration(
  168. { ...options, environment: secondEnvironment },
  169. dependencies,
  170. ),
  171. ]);
  172. try {
  173. expect(first).toMatchObject({ ready: true, category: 'ready' });
  174. expect(second).toMatchObject({ ready: true, category: 'ready' });
  175. expect(firstEnvironment.__MAVIS_MCODE_TOOLS_BROKER_ENDPOINT).not.toBe(
  176. secondEnvironment.__MAVIS_MCODE_TOOLS_BROKER_ENDPOINT,
  177. );
  178. expect(firstEnvironment.PATH?.split(path.delimiter)[0]).toBe(
  179. path.resolve('/package', 'internal-bin'),
  180. );
  181. expect(secondEnvironment.PATH?.split(path.delimiter)[0]).toBe(
  182. path.resolve('/package', 'internal-bin'),
  183. );
  184. await first.dispose();
  185. expect(firstEnvironment.__MAVIS_MCODE_TOOLS_BROKER_ENDPOINT).toBeUndefined();
  186. expect(secondEnvironment.__MAVIS_MCODE_TOOLS_BROKER_ENDPOINT).toBeDefined();
  187. expect(second).toMatchObject({ ready: true, category: 'ready' });
  188. expect(brokerDisposals.map((dispose) => dispose.mock.calls.length).sort()).toEqual([0, 1]);
  189. } finally {
  190. await first.dispose();
  191. await second.dispose();
  192. }
  193. });
  194. it('falls back with a sanitized category when resource validation fails', async () => {
  195. const warnings: string[] = [];
  196. const result = await prepareTuiMcodeToolsIntegration(
  197. {
  198. requested: true,
  199. dataDir: '/Users/private/profile',
  200. buildEnv: 'test',
  201. region: 'cn',
  202. session: createSession({ status: 'anonymous', generation: 0 }).session,
  203. entryUrl: pathToFileURL('/Users/private/package/cli.js').href,
  204. logger: { info: () => undefined, warn: (message) => warnings.push(message) },
  205. },
  206. {
  207. validateResource: () => {
  208. throw new Error('mcode-tools manifest is missing at /Users/private/secret');
  209. },
  210. },
  211. );
  212. expect(result).toMatchObject({
  213. requested: true,
  214. ready: false,
  215. category: 'resource_unavailable',
  216. });
  217. expect(warnings.join('\n')).not.toContain('/Users/private');
  218. });
  219. it('uses only an explicit absolute dev resource override', () => {
  220. expect(
  221. resolveBundledMcodeToolsResourceDir(pathToFileURL('/pkg/cli.js').href, {
  222. MAVIS_DEV_MCODE_TOOLS_MODE: 'published',
  223. MAVIS_DEV_MCODE_TOOLS_RESOURCE_DIR: path.resolve(tmpdir(), 'mcode-tools-resource'),
  224. }),
  225. ).toBe(path.resolve(tmpdir(), 'mcode-tools-resource'));
  226. expect(() =>
  227. resolveBundledMcodeToolsResourceDir(pathToFileURL('/pkg/cli.js').href, {
  228. MAVIS_DEV_MCODE_TOOLS_MODE: 'published',
  229. MAVIS_DEV_MCODE_TOOLS_RESOURCE_DIR: '../mcode-tools-resource',
  230. }),
  231. ).toThrow(/absolute/u);
  232. });
  233. });
  234. describe('mcode-tools command environment', () => {
  235. it('uses the TUI runtime even when PATH resolves a different node', async () => {
  236. const temporaryRoot = await makeTemporaryDirectory();
  237. const packageRoot = path.join(temporaryRoot, 'package with spaces');
  238. const internalBin = path.join(packageRoot, 'internal-bin');
  239. const fakeBin = path.join(packageRoot, 'fake-bin');
  240. const launcherName = process.platform === 'win32' ? 'mcode-tools.cmd' : 'mcode-tools';
  241. const fakeNodeName = process.platform === 'win32' ? 'node.cmd' : 'node';
  242. const launcher = path.join(internalBin, launcherName);
  243. await mkdir(internalBin, { recursive: true });
  244. await mkdir(fakeBin, { recursive: true });
  245. await copyFile(
  246. fileURLToPath(
  247. new URL(`../../src/cli/mcode-tools-launchers/${launcherName}`, import.meta.url),
  248. ),
  249. launcher,
  250. );
  251. if (process.platform !== 'win32') await chmod(launcher, 0o755);
  252. await writeFile(
  253. path.join(packageRoot, 'mcode-tools.js'),
  254. 'console.log(JSON.stringify({ execPath: process.execPath, args: process.argv.slice(2) }));\n',
  255. );
  256. await writeFile(
  257. path.join(fakeBin, fakeNodeName),
  258. process.platform === 'win32' ? '@exit /b 97\r\n' : '#!/bin/sh\nexit 97\n',
  259. );
  260. if (process.platform !== 'win32') await chmod(path.join(fakeBin, fakeNodeName), 0o755);
  261. const environment: Record<string, string | undefined> = {
  262. ...process.env,
  263. PATH: [fakeBin, '/usr/bin', '/bin'].join(path.delimiter),
  264. };
  265. const activation = activateTuiMcodeToolsHostEnvironment(environment, {
  266. runtimeExecutable: process.execPath,
  267. brokerEndpoint: path.join(packageRoot, 'broker.sock'),
  268. brokerCapabilityFile: path.join(packageRoot, 'broker.cap'),
  269. configDir: path.join(packageRoot, 'config'),
  270. region: 'en',
  271. commandBinDir: internalBin,
  272. });
  273. let output: string;
  274. try {
  275. output =
  276. process.platform === 'win32'
  277. ? execFileSync(
  278. process.env.ComSpec ?? 'cmd.exe',
  279. ['/d', '/s', '/c', `""${launcher}" probe "two words""`],
  280. { encoding: 'utf8', env: environment, windowsVerbatimArguments: true },
  281. )
  282. : execFileSync(launcher, ['probe', 'two words'], {
  283. encoding: 'utf8',
  284. env: environment,
  285. });
  286. } finally {
  287. activation.restore();
  288. }
  289. expect(JSON.parse(output)).toEqual({
  290. execPath: process.execPath,
  291. args: ['probe', 'two words'],
  292. });
  293. });
  294. it('preserves standalone user configuration outside a TUI-owned process', () => {
  295. const environment = {
  296. MCODE_AUTH_PROVIDER: 'user-provider',
  297. MCODE_CONFIG_DIR: '/user/config',
  298. };
  299. expect(configureMcodeToolsChildEnvironment(environment)).toBe(false);
  300. expect(environment).toEqual({
  301. MCODE_AUTH_PROVIDER: 'user-provider',
  302. MCODE_CONFIG_DIR: '/user/config',
  303. });
  304. });
  305. it('maps the TUI broker into the child and removes inherited routing overrides', () => {
  306. const environment: Record<string, string | undefined> = {
  307. __MAVIS_MCODE_TOOLS_BROKER_ENDPOINT: '/runtime/broker.sock',
  308. __MAVIS_MCODE_TOOLS_BROKER_CAPABILITY_FILE: '/runtime/broker.cap',
  309. __MAVIS_MCODE_TOOLS_CONFIG_DIR: '/profile/integrations/mcode-tools/cn',
  310. __MAVIS_MCODE_TOOLS_REGION: 'cn',
  311. __MAVIS_MCODE_TOOLS_EXTRA_HEADERS: 'bedrock_lane:oauth2,bedrock-lane:oauth2',
  312. __MAVIS_MCODE_TOOLS_RUNTIME_EXECUTABLE: process.execPath,
  313. MCODE_AUTH_PROVIDER: 'attacker-provider',
  314. MCODE_API_BASE_URL: 'https://attacker.invalid/api',
  315. MCODE_AUTH_BASE_URL: 'https://attacker.invalid/oauth',
  316. MCODE_CLIENT_ID: 'attacker-client',
  317. MCODE_SCOPE: 'attacker-scope',
  318. IS_SANDBOX: '1',
  319. MAVIS_BUILD_ENV: 'prod',
  320. MAVIS_REGION: 'us',
  321. MAVIS_AGENT: 'agent',
  322. MAVIS_SESSION: 'session',
  323. __MAVIS_RUNTIME_SECRET: 'runtime-secret',
  324. AGENTARCHON_SECRET: 'legacy-secret',
  325. mcode_api_base_url: 'https://case-insensitive-attacker.invalid/api',
  326. __mavis_parent_access_token: 'case-insensitive-token',
  327. };
  328. expect(configureMcodeToolsChildEnvironment(environment)).toBe(true);
  329. expect(environment).toMatchObject({
  330. ELECTRON_RUN_AS_NODE: '1',
  331. MCODE_REGION: 'cn',
  332. MCODE_CONFIG_DIR: '/profile/integrations/mcode-tools/cn',
  333. MCODE_AUTH_PROVIDER: 'shared-broker',
  334. MCODE_AUTH_BROKER_ENDPOINT: '/runtime/broker.sock',
  335. MCODE_AUTH_BROKER_CAPABILITY_FILE: '/runtime/broker.cap',
  336. MCODE_EXTRA_HEADERS: 'bedrock_lane:oauth2,bedrock-lane:oauth2',
  337. });
  338. expect(environment.MCODE_API_BASE_URL).toBeUndefined();
  339. expect(environment.MCODE_AUTH_BASE_URL).toBeUndefined();
  340. expect(environment.MCODE_CLIENT_ID).toBeUndefined();
  341. expect(environment.MCODE_SCOPE).toBeUndefined();
  342. expect(environment.IS_SANDBOX).toBeUndefined();
  343. expect(environment.MAVIS_BUILD_ENV).toBeUndefined();
  344. expect(environment.MAVIS_REGION).toBeUndefined();
  345. expect(environment.MAVIS_AGENT).toBeUndefined();
  346. expect(environment.MAVIS_SESSION).toBeUndefined();
  347. expect(environment.__MAVIS_RUNTIME_SECRET).toBeUndefined();
  348. expect(environment.AGENTARCHON_SECRET).toBeUndefined();
  349. expect(environment.mcode_api_base_url).toBeUndefined();
  350. expect(environment.__mavis_parent_access_token).toBeUndefined();
  351. expect(environment.__MAVIS_MCODE_TOOLS_BROKER_ENDPOINT).toBeUndefined();
  352. expect(environment.__MAVIS_MCODE_TOOLS_RUNTIME_EXECUTABLE).toBeUndefined();
  353. });
  354. it('rejects a partial TUI host environment', () => {
  355. expect(() =>
  356. configureMcodeToolsChildEnvironment({
  357. __MAVIS_MCODE_TOOLS_BROKER_ENDPOINT: '/runtime/broker.sock',
  358. }),
  359. ).toThrow(/Restart MCode/u);
  360. });
  361. });
  362. function createSession(initialStatus: McodeToolsAuthStatusSnapshot): {
  363. session: McodeToolsHostAuthSession;
  364. status: McodeToolsAuthStatusSnapshot;
  365. emit(status: McodeToolsAuthStatusSnapshot): void;
  366. stopWatching: ReturnType<typeof vi.fn>;
  367. } {
  368. let listener: ((status: McodeToolsAuthStatusSnapshot) => void) | undefined;
  369. const stopWatching = vi.fn();
  370. const state = {
  371. status: initialStatus,
  372. session: {
  373. getStatus: vi.fn(async () => state.status),
  374. getAccessToken: vi.fn(),
  375. handleUnauthorized: vi.fn(),
  376. watch: vi.fn((nextListener: (status: McodeToolsAuthStatusSnapshot) => void) => {
  377. listener = nextListener;
  378. return stopWatching;
  379. }),
  380. } satisfies McodeToolsHostAuthSession,
  381. emit(status: McodeToolsAuthStatusSnapshot): void {
  382. state.status = status;
  383. listener?.(status);
  384. },
  385. stopWatching,
  386. };
  387. return state;
  388. }
  389. function validatedResource(rootDir: string): ValidatedMcodeToolsResource {
  390. return {
  391. rootDir,
  392. cliPath: path.join(rootDir, 'cli.mjs'),
  393. manifest: {
  394. schemaVersion: 3,
  395. packageName: '@minimax/mcode-tools-test',
  396. version: '0.0.0-test.1',
  397. gitSha: 'abc1234',
  398. buildEnv: 'test',
  399. bedrockLane: 'oauth',
  400. nodeRange: '>=20',
  401. entry: 'cli.mjs',
  402. auth: {
  403. mode: 'shared-broker',
  404. protocol: {
  405. name: '@mavis/oauth-lease-protocol',
  406. version: '0.1.0-beta.0',
  407. wireVersion: 1,
  408. },
  409. },
  410. nativePackages: [],
  411. resources: [{ path: 'cli.mjs', sha256: '0'.repeat(64) }],
  412. },
  413. };
  414. }
  415. async function makeTemporaryDirectory(): Promise<string> {
  416. const directory = await mkdtemp(path.join(tmpdir(), 'mcode-tools-tui-integration-'));
  417. temporaryDirectories.push(directory);
  418. return directory;
  419. }