update-service.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import { createHash, generateKeyPairSync, sign } from 'node:crypto';
  2. import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
  3. import { tmpdir } from 'node:os';
  4. import path from 'node:path';
  5. import { afterEach, describe, expect, it, vi } from 'vitest';
  6. import { McodeUpdateService, type McodeUpdateDependencies } from '../../src/update/service.js';
  7. import type { McodeReleaseManifestV1 } from '../../src/update/release.js';
  8. const temporaryRoots: string[] = [];
  9. function temporaryRoot(): string {
  10. const root = mkdtempSync(path.join(tmpdir(), 'mcode-update-test-'));
  11. temporaryRoots.push(root);
  12. return root;
  13. }
  14. function releaseFixture(version = '1.2.4', artifact = Buffer.from('signed artifact bytes')) {
  15. const { privateKey, publicKey } = generateKeyPairSync('ed25519');
  16. const manifest: McodeReleaseManifestV1 = {
  17. schemaVersion: 1,
  18. product: 'minimax-code',
  19. channel: 'stable',
  20. version,
  21. publishedAt: '2026-07-27T00:00:00.000Z',
  22. minNodeVersion: '22.19.0',
  23. registry: 'https://registry.example.test/',
  24. installArtifact: {
  25. url: `https://downloads.example.test/releases/${version}/mcode.tgz`,
  26. sha256: createHash('sha256').update(artifact).digest('hex'),
  27. size: artifact.length,
  28. },
  29. targets: {
  30. 'darwin-arm64': { sha256: 'a'.repeat(64), size: 1 },
  31. 'darwin-x64': { sha256: 'b'.repeat(64), size: 1 },
  32. 'linux-x64': { sha256: 'c'.repeat(64), size: 1 },
  33. 'windows-x64': { sha256: 'd'.repeat(64), size: 1 },
  34. 'windows-arm64': { sha256: 'e'.repeat(64), size: 1 },
  35. },
  36. };
  37. const manifestBytes = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
  38. return {
  39. manifest,
  40. manifestBytes,
  41. signature: sign(null, manifestBytes, privateKey).toString('base64'),
  42. publicKey: publicKey.export({ format: 'pem', type: 'spki' }).toString(),
  43. artifact,
  44. };
  45. }
  46. afterEach(() => {
  47. for (const root of temporaryRoots.splice(0)) {
  48. rmSync(root, { recursive: true, force: true });
  49. }
  50. });
  51. describe('McodeUpdateService', () => {
  52. it('checks a signed channel manifest without mutating the install root', async () => {
  53. const root = temporaryRoot();
  54. const fixture = releaseFixture();
  55. const fetchBytes = vi.fn(async (url: string) =>
  56. url.endsWith('.sig') ? Buffer.from(fixture.signature) : fixture.manifestBytes,
  57. );
  58. const service = new McodeUpdateService({
  59. currentVersion: '1.2.3',
  60. installRoot: root,
  61. publicKey: fixture.publicKey,
  62. dependencies: { fetchBytes },
  63. });
  64. await expect(service.check({ channel: 'stable' })).resolves.toMatchObject({
  65. status: 'available',
  66. currentVersion: '1.2.3',
  67. latestVersion: '1.2.4',
  68. channel: 'stable',
  69. });
  70. expect(fetchBytes).toHaveBeenCalledTimes(2);
  71. expect(existsSync(path.join(root, 'update.json'))).toBe(false);
  72. });
  73. it.each([
  74. new Error('offline'),
  75. Object.assign(new Error('timed out'), { name: 'AbortError' }),
  76. new Error('release server returned HTTP 503'),
  77. ])(
  78. 'reports network and service failures without changing the active version',
  79. async (failure) => {
  80. const root = temporaryRoot();
  81. const currentFile = path.join(root, 'current');
  82. const dependencies: Partial<McodeUpdateDependencies> = {
  83. fetchBytes: vi.fn(async () => {
  84. throw failure;
  85. }),
  86. };
  87. const service = new McodeUpdateService({
  88. currentVersion: '1.2.3',
  89. installRoot: root,
  90. dependencies,
  91. });
  92. await expect(service.check({ channel: 'stable', timeoutMs: 100 })).rejects.toThrow();
  93. expect(() => readFileSync(currentFile, 'utf8')).toThrow();
  94. },
  95. );
  96. it('keeps the previous current pointer when install validation fails', async () => {
  97. const root = temporaryRoot();
  98. const fixture = releaseFixture();
  99. const dependencies: Partial<McodeUpdateDependencies> = {
  100. fetchBytes: vi.fn(async (url: string) =>
  101. url.endsWith('.sig')
  102. ? Buffer.from(fixture.signature)
  103. : url.endsWith('.tgz')
  104. ? Buffer.from('wrong bytes')
  105. : fixture.manifestBytes,
  106. ),
  107. installArtifact: vi.fn(async () => undefined),
  108. validateInstalledVersion: vi.fn(async () => undefined),
  109. };
  110. const service = new McodeUpdateService({
  111. currentVersion: '1.2.3',
  112. installRoot: root,
  113. publicKey: fixture.publicKey,
  114. dependencies,
  115. });
  116. await expect(service.apply({ channel: 'stable' })).rejects.toThrow(/checksum/i);
  117. expect(() => readFileSync(path.join(root, 'current'), 'utf8')).toThrow();
  118. expect(dependencies.installArtifact).not.toHaveBeenCalled();
  119. });
  120. it('activates only after staging installation and validation succeed', async () => {
  121. const root = temporaryRoot();
  122. const fixture = releaseFixture();
  123. const installArtifact = vi.fn(async () => undefined);
  124. const validateInstalledVersion = vi.fn(async () => undefined);
  125. const service = new McodeUpdateService({
  126. currentVersion: '1.2.3',
  127. installRoot: root,
  128. publicKey: fixture.publicKey,
  129. dependencies: {
  130. fetchBytes: vi.fn(async (url: string) =>
  131. url.endsWith('.sig')
  132. ? Buffer.from(fixture.signature)
  133. : url.endsWith('.tgz')
  134. ? fixture.artifact
  135. : fixture.manifestBytes,
  136. ),
  137. installArtifact,
  138. validateInstalledVersion,
  139. },
  140. });
  141. await expect(service.apply({ channel: 'stable' })).resolves.toMatchObject({
  142. applied: true,
  143. latestVersion: '1.2.4',
  144. });
  145. expect(installArtifact).toHaveBeenCalledOnce();
  146. expect(validateInstalledVersion).toHaveBeenCalled();
  147. expect(readFileSync(path.join(root, 'current'), 'utf8')).toBe('1.2.4\n');
  148. expect(existsSync(path.join(root, 'versions', '1.2.4'))).toBe(true);
  149. });
  150. it('preserves an existing active pointer when staged install validation fails', async () => {
  151. const root = temporaryRoot();
  152. mkdirSync(root, { recursive: true });
  153. writeFileSync(path.join(root, 'current'), '1.2.3\n');
  154. const fixture = releaseFixture();
  155. const service = new McodeUpdateService({
  156. currentVersion: '1.2.3',
  157. installRoot: root,
  158. publicKey: fixture.publicKey,
  159. dependencies: {
  160. fetchBytes: vi.fn(async (url: string) =>
  161. url.endsWith('.sig')
  162. ? Buffer.from(fixture.signature)
  163. : url.endsWith('.tgz')
  164. ? fixture.artifact
  165. : fixture.manifestBytes,
  166. ),
  167. installArtifact: vi.fn(async () => undefined),
  168. validateInstalledVersion: vi.fn(async () => {
  169. throw new Error('installed binary smoke failed');
  170. }),
  171. },
  172. });
  173. await expect(service.apply({ channel: 'stable' })).rejects.toThrow(/previous version/i);
  174. expect(readFileSync(path.join(root, 'current'), 'utf8')).toBe('1.2.3\n');
  175. expect(existsSync(path.join(root, 'versions', '1.2.4'))).toBe(false);
  176. });
  177. it('requires the explicit --to option before downgrading from a channel', async () => {
  178. const root = temporaryRoot();
  179. const fixture = releaseFixture('1.2.2');
  180. const service = new McodeUpdateService({
  181. currentVersion: '1.2.3',
  182. installRoot: root,
  183. publicKey: fixture.publicKey,
  184. dependencies: {
  185. fetchBytes: vi.fn(async (url: string) =>
  186. url.endsWith('.sig') ? Buffer.from(fixture.signature) : fixture.manifestBytes,
  187. ),
  188. },
  189. });
  190. await expect(service.apply({ channel: 'stable' })).rejects.toThrow(/--to/);
  191. });
  192. it('cancels before activation and keeps the previous active version unchanged', async () => {
  193. const root = temporaryRoot();
  194. mkdirSync(root, { recursive: true });
  195. writeFileSync(path.join(root, 'current'), '1.2.3\n');
  196. const fixture = releaseFixture();
  197. const controller = new AbortController();
  198. const phases: string[] = [];
  199. const service = new McodeUpdateService({
  200. currentVersion: '1.2.3',
  201. installRoot: root,
  202. publicKey: fixture.publicKey,
  203. dependencies: {
  204. fetchBytes: vi.fn(async (url: string) =>
  205. url.endsWith('.sig')
  206. ? Buffer.from(fixture.signature)
  207. : url.endsWith('.tgz')
  208. ? fixture.artifact
  209. : fixture.manifestBytes,
  210. ),
  211. },
  212. });
  213. await expect(
  214. service.apply({
  215. channel: 'stable',
  216. signal: controller.signal,
  217. onPhase: (event) => {
  218. phases.push(`${event.phase}:${String(event.cancellable)}`);
  219. if (event.phase === 'downloading') controller.abort();
  220. },
  221. }),
  222. ).rejects.toThrow(/cancelled/i);
  223. expect(phases).toContain('downloading:true');
  224. expect(phases).not.toContain('activating:false');
  225. expect(readFileSync(path.join(root, 'current'), 'utf8')).toBe('1.2.3\n');
  226. expect(existsSync(path.join(root, 'versions', '1.2.4'))).toBe(false);
  227. });
  228. it('locks cancellation at atomic activation and completes the pointer swap', async () => {
  229. const root = temporaryRoot();
  230. mkdirSync(root, { recursive: true });
  231. writeFileSync(path.join(root, 'current'), '1.2.3\n');
  232. const fixture = releaseFixture();
  233. const controller = new AbortController();
  234. const service = new McodeUpdateService({
  235. currentVersion: '1.2.3',
  236. installRoot: root,
  237. publicKey: fixture.publicKey,
  238. dependencies: {
  239. fetchBytes: vi.fn(async (url: string) =>
  240. url.endsWith('.sig')
  241. ? Buffer.from(fixture.signature)
  242. : url.endsWith('.tgz')
  243. ? fixture.artifact
  244. : fixture.manifestBytes,
  245. ),
  246. installArtifact: vi.fn(async () => undefined),
  247. validateInstalledVersion: vi.fn(async () => undefined),
  248. },
  249. });
  250. await expect(
  251. service.apply({
  252. channel: 'stable',
  253. signal: controller.signal,
  254. onPhase: (event) => {
  255. if (event.phase === 'activating') {
  256. expect(event.cancellable).toBe(false);
  257. controller.abort();
  258. }
  259. },
  260. }),
  261. ).resolves.toMatchObject({ applied: true, latestVersion: '1.2.4' });
  262. expect(readFileSync(path.join(root, 'current'), 'utf8')).toBe('1.2.4\n');
  263. });
  264. it('waits for installation to finish naturally before honoring cancellation', async () => {
  265. const root = temporaryRoot();
  266. mkdirSync(root, { recursive: true });
  267. writeFileSync(path.join(root, 'current'), '1.2.3\n');
  268. const fixture = releaseFixture();
  269. const controller = new AbortController();
  270. let finishInstall: (() => void) | undefined;
  271. const installArtifact = vi.fn(
  272. () =>
  273. new Promise<void>((resolve) => {
  274. finishInstall = resolve;
  275. }),
  276. );
  277. const service = new McodeUpdateService({
  278. currentVersion: '1.2.3',
  279. installRoot: root,
  280. publicKey: fixture.publicKey,
  281. dependencies: {
  282. fetchBytes: vi.fn(async (url: string) =>
  283. url.endsWith('.sig')
  284. ? Buffer.from(fixture.signature)
  285. : url.endsWith('.tgz')
  286. ? fixture.artifact
  287. : fixture.manifestBytes,
  288. ),
  289. installArtifact,
  290. validateInstalledVersion: vi.fn(async () => undefined),
  291. },
  292. });
  293. const apply = service.apply({
  294. channel: 'stable',
  295. signal: controller.signal,
  296. onPhase: (event) => {
  297. if (event.phase === 'installing') {
  298. expect(event.cancellable).toBe(false);
  299. controller.abort();
  300. }
  301. },
  302. });
  303. await vi.waitFor(() => expect(installArtifact).toHaveBeenCalledOnce());
  304. expect(installArtifact).toHaveBeenCalledWith(
  305. expect.not.objectContaining({ signal: expect.anything() }),
  306. );
  307. expect(readFileSync(path.join(root, 'current'), 'utf8')).toBe('1.2.3\n');
  308. finishInstall?.();
  309. await expect(apply).rejects.toThrow(/cancelled/i);
  310. expect(readFileSync(path.join(root, 'current'), 'utf8')).toBe('1.2.3\n');
  311. expect(existsSync(path.join(root, 'versions', '1.2.4'))).toBe(false);
  312. });
  313. });