release.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. import { createPublicKey, verify } from 'node:crypto';
  2. export type McodeUpdateChannel = 'stable' | 'preview';
  3. export type McodeReleaseTarget =
  4. | 'darwin-arm64'
  5. | 'darwin-x64'
  6. | 'linux-x64'
  7. | 'windows-x64'
  8. | 'windows-arm64';
  9. export interface McodeReleaseArtifact {
  10. url: string;
  11. sha256: string;
  12. size: number;
  13. }
  14. type McodeReleaseTargetArtifact = Omit<McodeReleaseArtifact, 'url'>;
  15. type McodeReleaseManifestV1Targets = Record<
  16. Exclude<McodeReleaseTarget, 'windows-arm64'>,
  17. McodeReleaseTargetArtifact
  18. > &
  19. Partial<Record<'windows-arm64', McodeReleaseTargetArtifact>>;
  20. export interface McodeReleaseManifestV1 {
  21. schemaVersion: 1;
  22. product: 'minimax-code';
  23. channel: McodeUpdateChannel | string;
  24. version: string;
  25. publishedAt: string;
  26. minNodeVersion: string;
  27. registry: string;
  28. installArtifact: McodeReleaseArtifact;
  29. targets: McodeReleaseManifestV1Targets;
  30. }
  31. const VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?$/u;
  32. const SHA256_PATTERN = /^[0-9a-f]{64}$/u;
  33. const CHANNEL_PATTERN = /^(?:stable|preview)$/u;
  34. const REQUIRED_V1_TARGETS = [
  35. 'darwin-arm64',
  36. 'darwin-x64',
  37. 'linux-x64',
  38. 'windows-x64',
  39. ] as const satisfies readonly McodeReleaseTarget[];
  40. const TARGETS = [...REQUIRED_V1_TARGETS, 'windows-arm64'] as const;
  41. export function parseMcodeUpdateChannel(value: string): McodeUpdateChannel {
  42. if (!CHANNEL_PATTERN.test(value)) {
  43. throw new Error(`Unsupported MCode update channel: ${JSON.stringify(value)}`);
  44. }
  45. return value as McodeUpdateChannel;
  46. }
  47. export function parseMcodeVersion(value: string): string {
  48. if (!VERSION_PATTERN.test(value)) {
  49. throw new Error(`Invalid MCode version: ${JSON.stringify(value)}`);
  50. }
  51. return value;
  52. }
  53. export function parseAndVerifyMcodeReleaseManifest(
  54. manifestBytes: Uint8Array,
  55. signatureText: string,
  56. publicKeyPem: string,
  57. ): McodeReleaseManifestV1 {
  58. const signature = readBase64Signature(signatureText);
  59. let authentic = false;
  60. try {
  61. authentic = verify(null, manifestBytes, createPublicKey(publicKeyPem), signature);
  62. } catch (error) {
  63. throw new Error(`MCode release signature could not be verified: ${errorMessage(error)}`);
  64. }
  65. if (!authentic) throw new Error('MCode release signature verification failed.');
  66. let parsed: unknown;
  67. try {
  68. parsed = JSON.parse(Buffer.from(manifestBytes).toString('utf8'));
  69. } catch (error) {
  70. throw new Error(`MCode release manifest is not valid JSON: ${errorMessage(error)}`);
  71. }
  72. return validateManifest(parsed);
  73. }
  74. function validateManifest(value: unknown): McodeReleaseManifestV1 {
  75. if (!isRecord(value)) throw new Error('MCode release manifest must be an object.');
  76. if (value.schemaVersion !== 1) {
  77. throw new Error(`Unsupported MCode release schema: ${String(value.schemaVersion)}`);
  78. }
  79. if (value.product !== 'minimax-code') {
  80. throw new Error(`Unexpected release product: ${String(value.product)}`);
  81. }
  82. const channel =
  83. typeof value.channel === 'string' && /^[0-9A-Za-z][0-9A-Za-z._-]*$/u.test(value.channel)
  84. ? value.channel
  85. : undefined;
  86. if (!channel) throw new Error('MCode release channel is invalid.');
  87. const version = typeof value.version === 'string' ? parseMcodeVersion(value.version) : undefined;
  88. if (!version) throw new Error('MCode release version is missing.');
  89. if (typeof value.publishedAt !== 'string' || !Number.isFinite(Date.parse(value.publishedAt))) {
  90. throw new Error('MCode release publishedAt is invalid.');
  91. }
  92. if (typeof value.minNodeVersion !== 'string' || !/^\d+\.\d+\.\d+$/u.test(value.minNodeVersion)) {
  93. throw new Error('MCode release minNodeVersion is invalid.');
  94. }
  95. const registry = readHttpsUrl(value.registry, 'registry');
  96. const installArtifact = readArtifact(value.installArtifact, true, 'installArtifact');
  97. if (!isRecord(value.targets)) throw new Error('MCode release targets are missing.');
  98. const targets: McodeReleaseManifestV1Targets = {
  99. 'darwin-arm64': readArtifact(value.targets['darwin-arm64'], false, 'targets.darwin-arm64'),
  100. 'darwin-x64': readArtifact(value.targets['darwin-x64'], false, 'targets.darwin-x64'),
  101. 'linux-x64': readArtifact(value.targets['linux-x64'], false, 'targets.linux-x64'),
  102. 'windows-x64': readArtifact(value.targets['windows-x64'], false, 'targets.windows-x64'),
  103. };
  104. if (value.targets['windows-arm64'] !== undefined) {
  105. targets['windows-arm64'] = readArtifact(
  106. value.targets['windows-arm64'],
  107. false,
  108. 'targets.windows-arm64',
  109. );
  110. }
  111. return {
  112. schemaVersion: 1,
  113. product: 'minimax-code',
  114. channel,
  115. version,
  116. publishedAt: value.publishedAt,
  117. minNodeVersion: value.minNodeVersion,
  118. registry,
  119. installArtifact,
  120. targets,
  121. };
  122. }
  123. function readArtifact(value: unknown, includeUrl: true, name: string): McodeReleaseArtifact;
  124. function readArtifact(
  125. value: unknown,
  126. includeUrl: false,
  127. name: string,
  128. ): Omit<McodeReleaseArtifact, 'url'>;
  129. function readArtifact(
  130. value: unknown,
  131. includeUrl: boolean,
  132. name: string,
  133. ): McodeReleaseArtifact | Omit<McodeReleaseArtifact, 'url'> {
  134. if (!isRecord(value)) throw new Error(`${name} is missing.`);
  135. if (typeof value.sha256 !== 'string' || !SHA256_PATTERN.test(value.sha256)) {
  136. throw new Error(`${name}.sha256 is invalid.`);
  137. }
  138. if (!Number.isSafeInteger(value.size) || (value.size as number) <= 0) {
  139. throw new Error(`${name}.size is invalid.`);
  140. }
  141. const base = { sha256: value.sha256, size: value.size as number };
  142. return includeUrl ? { ...base, url: readHttpsUrl(value.url, `${name}.url`) } : base;
  143. }
  144. function readHttpsUrl(value: unknown, name: string): string {
  145. if (typeof value !== 'string') throw new Error(`${name} must be an HTTPS URL.`);
  146. let url: URL;
  147. try {
  148. url = new URL(value);
  149. } catch {
  150. throw new Error(`${name} must be an HTTPS URL.`);
  151. }
  152. if (url.protocol !== 'https:' || url.username || url.password) {
  153. throw new Error(`${name} must be an HTTPS URL without embedded credentials.`);
  154. }
  155. return url.href;
  156. }
  157. function readBase64Signature(value: string): Buffer {
  158. const normalized = value.trim();
  159. if (!/^[A-Za-z0-9+/]+={0,2}$/u.test(normalized)) {
  160. throw new Error('MCode release signature is not valid base64.');
  161. }
  162. const signature = Buffer.from(normalized, 'base64');
  163. if (signature.length !== 64) throw new Error('MCode release signature has an invalid length.');
  164. return signature;
  165. }
  166. export function resolveMcodeReleaseTarget(
  167. platform = process.platform,
  168. arch = process.arch,
  169. ): McodeReleaseTarget {
  170. const candidate = `${platform === 'win32' ? 'windows' : platform}-${arch}`;
  171. if ((TARGETS as readonly string[]).includes(candidate)) {
  172. return candidate as McodeReleaseTarget;
  173. }
  174. throw new Error(`Unsupported MCode update host: ${platform}-${arch}`);
  175. }
  176. export function assertMcodeReleaseTargetAvailable(
  177. manifest: McodeReleaseManifestV1,
  178. target: McodeReleaseTarget,
  179. ): void {
  180. if (manifest.targets[target]) return;
  181. throw new Error(`MCode ${manifest.version} does not provide a release for ${target}.`);
  182. }
  183. interface ParsedVersion {
  184. core: number[];
  185. prerelease: Array<number | string>;
  186. }
  187. function parsedVersion(value: string): ParsedVersion {
  188. parseMcodeVersion(value);
  189. const [coreText = '', prereleaseText] = value.split('-', 2);
  190. return {
  191. core: coreText.split('.').map((part) => Number.parseInt(part, 10)),
  192. prerelease: prereleaseText
  193. ? prereleaseText.split('.').map((part) => (/^\d+$/u.test(part) ? Number(part) : part))
  194. : [],
  195. };
  196. }
  197. export function compareMcodeVersions(left: string, right: string): number {
  198. const leftVersion = parsedVersion(left);
  199. const rightVersion = parsedVersion(right);
  200. for (let index = 0; index < 3; index += 1) {
  201. const difference = (leftVersion.core[index] ?? 0) - (rightVersion.core[index] ?? 0);
  202. if (difference !== 0) return difference;
  203. }
  204. if (leftVersion.prerelease.length === 0 && rightVersion.prerelease.length > 0) return 1;
  205. if (rightVersion.prerelease.length === 0 && leftVersion.prerelease.length > 0) return -1;
  206. const length = Math.max(leftVersion.prerelease.length, rightVersion.prerelease.length);
  207. for (let index = 0; index < length; index += 1) {
  208. const leftPart = leftVersion.prerelease[index];
  209. const rightPart = rightVersion.prerelease[index];
  210. if (leftPart === undefined) return -1;
  211. if (rightPart === undefined) return 1;
  212. if (leftPart === rightPart) continue;
  213. if (typeof leftPart === 'number' && typeof rightPart === 'number') return leftPart - rightPart;
  214. if (typeof leftPart === 'number') return -1;
  215. if (typeof rightPart === 'number') return 1;
  216. return leftPart.localeCompare(rightPart);
  217. }
  218. return 0;
  219. }
  220. function isRecord(value: unknown): value is Record<string, unknown> {
  221. return typeof value === 'object' && value !== null && !Array.isArray(value);
  222. }
  223. function errorMessage(error: unknown): string {
  224. return error instanceof Error ? error.message : String(error);
  225. }