windows-cua-helper-assets.mjs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. /* eslint-disable max-lines -- staging 与 afterPack verifier 共用同一发布契约,保持同模块避免 schema/PE 规则漂移。 */
  2. import { createHash, randomUUID } from "node:crypto";
  3. import { existsSync } from "node:fs";
  4. import { cp, lstat, mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
  5. import {
  6. basename,
  7. dirname,
  8. isAbsolute,
  9. parse,
  10. posix,
  11. relative,
  12. resolve,
  13. sep,
  14. win32,
  15. } from "node:path";
  16. import { setTimeout as delay } from "node:timers/promises";
  17. import { collectRuntimeModuleClosureEntries } from "./runtime-dependency-closure.mjs";
  18. import { resolveSharpRuntimePackageNames } from "./sharp-package-assets.mjs";
  19. const EXPECTED_PACKAGE_NAME = "@zcode/zcode-cua";
  20. const RUNTIME_MANIFEST = "runtime-manifest.json";
  21. const MODULE_TYPE_PACKAGE_JSON = "package.json";
  22. const REMOVE_DIRECTORY_OPTIONS = {
  23. recursive: true,
  24. force: true,
  25. maxRetries: 5,
  26. retryDelay: 100,
  27. };
  28. const PE_MACHINE_BY_ARCH = {
  29. x64: 0x8664,
  30. arm64: 0xaa64,
  31. };
  32. const ELECTRON_BUILDER_ARCH = {
  33. 1: "x64",
  34. 3: "arm64",
  35. };
  36. export function resolveElectronBuilderWindowsTarget({
  37. electronPlatformName,
  38. arch,
  39. configuredTargetPlatform,
  40. }) {
  41. if (electronPlatformName !== "win32") {
  42. throw new Error(
  43. `[windows-cua-helper-assets] electron-builder context platform is not win32: ${String(electronPlatformName)}`,
  44. );
  45. }
  46. const actualArch = ELECTRON_BUILDER_ARCH[arch];
  47. if (!actualArch) {
  48. throw new Error(
  49. `[windows-cua-helper-assets] unsupported electron-builder Windows architecture: ${String(arch)}`,
  50. );
  51. }
  52. const actualTarget = {
  53. os: "win32",
  54. arch: actualArch,
  55. key: `win32-${actualArch}`,
  56. };
  57. if (
  58. configuredTargetPlatform?.os !== actualTarget.os ||
  59. configuredTargetPlatform?.arch !== actualTarget.arch ||
  60. configuredTargetPlatform?.key !== actualTarget.key
  61. ) {
  62. // 根因:交叉构建时 process.env 目标可能与 electron-builder 实际 context 不同;
  63. // 继续使用全局目标会让 afterPack 跳过或按错误架构验收。
  64. throw new Error(
  65. `[windows-cua-helper-assets] configured target ${String(configuredTargetPlatform?.key)} does not match electron-builder target ${actualTarget.key}`,
  66. );
  67. }
  68. return actualTarget;
  69. }
  70. async function readContainedJson(
  71. physicalRoot,
  72. path,
  73. label,
  74. { lstatOperation = lstat, realpathOperation = realpath, readFileOperation = readFile } = {},
  75. ) {
  76. const bytes = await readRegularFileSnapshot(path, label, {
  77. lstatOperation,
  78. readFileOperation,
  79. });
  80. const physicalPath = await realpathOperation(path);
  81. assertPhysicalContainment(physicalRoot, physicalPath, label);
  82. try {
  83. return JSON.parse(Buffer.isBuffer(bytes) ? bytes.toString("utf8") : String(bytes));
  84. } catch (error) {
  85. throw new Error(`[windows-cua-helper-assets] invalid ${label}: ${path}`, {
  86. cause: error,
  87. });
  88. }
  89. }
  90. export async function readRegularFileSnapshot(
  91. path,
  92. artifact,
  93. { lstatOperation = lstat, readFileOperation = readFile } = {},
  94. ) {
  95. let stats;
  96. try {
  97. stats = await lstatOperation(path);
  98. } catch (error) {
  99. throw new Error(`[windows-cua-helper-assets] missing ${artifact}: ${path}`, {
  100. cause: error,
  101. });
  102. }
  103. if (stats.isSymbolicLink() || !stats.isFile()) {
  104. throw new Error(
  105. `[windows-cua-helper-assets] ${artifact} must be a regular file, not a symbolic link: ${path}`,
  106. );
  107. }
  108. try {
  109. // TOCTOU 根因:校验/哈希后再次按源路径复制,可能把变化后的另一组字节写入产物。
  110. // 这里只读取一次确定快照;后续校验、落盘和 manifest 都沿用这组字节。
  111. return await readFileOperation(path);
  112. } catch (error) {
  113. throw new Error(`[windows-cua-helper-assets] cannot snapshot ${artifact}: ${path}`, {
  114. cause: error,
  115. });
  116. }
  117. }
  118. function parsePeMachine(bytes, addonPath) {
  119. if (bytes.length < 0x40 || bytes.toString("ascii", 0, 2) !== "MZ") {
  120. throw new Error(`[windows-cua-helper-assets] invalid PE header: ${addonPath}`);
  121. }
  122. const peOffset = bytes.readUInt32LE(0x3c);
  123. if (
  124. peOffset > bytes.length - 6 ||
  125. bytes.toString("binary", peOffset, peOffset + 4) !== "PE\u0000\u0000"
  126. ) {
  127. throw new Error(`[windows-cua-helper-assets] invalid PE header: ${addonPath}`);
  128. }
  129. return bytes.readUInt16LE(peOffset + 4);
  130. }
  131. async function copyRuntimePackage(sourceRoot, targetRoot) {
  132. const skippedDirectories = new Set(["test", "tests", "__tests__", "node_modules"]);
  133. const skippedSuffixes = [".map", ".md", ".markdown", ".ts"];
  134. await cp(sourceRoot, targetRoot, {
  135. recursive: true,
  136. dereference: true,
  137. filter(source) {
  138. if (source === sourceRoot) {
  139. return true;
  140. }
  141. const name = basename(source);
  142. if (skippedDirectories.has(name)) {
  143. return false;
  144. }
  145. return !skippedSuffixes.some((suffix) => name.endsWith(suffix));
  146. },
  147. });
  148. }
  149. function resolveModuleLookupRoots(sourceRoot) {
  150. const lookupRoots = [sourceRoot];
  151. const volumeRoot = parse(sourceRoot).root;
  152. let currentDir = dirname(sourceRoot);
  153. while (currentDir !== volumeRoot) {
  154. if (basename(currentDir) === "node_modules") {
  155. lookupRoots.push(dirname(currentDir));
  156. break;
  157. }
  158. if (existsSync(resolve(currentDir, "pnpm-workspace.yaml"))) {
  159. lookupRoots.push(currentDir);
  160. break;
  161. }
  162. currentDir = dirname(currentDir);
  163. }
  164. return lookupRoots;
  165. }
  166. export async function renameDirectoryWithRetries(
  167. source,
  168. destination,
  169. { renameOperation = rename, retryDelayMs = 100, maxAttempts = 5 } = {},
  170. ) {
  171. const transientWindowsErrors = new Set(["EACCES", "EBUSY", "EPERM"]);
  172. for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
  173. try {
  174. await renameOperation(source, destination);
  175. return;
  176. } catch (error) {
  177. if (!transientWindowsErrors.has(error?.code) || attempt === maxAttempts) {
  178. throw error;
  179. }
  180. // Windows Defender 或索引器可能在原子目录切换的瞬间短暂持有文件句柄。
  181. await delay(retryDelayMs * attempt);
  182. }
  183. }
  184. }
  185. async function atomicallyReplaceDirectory(stagedTempRoot, outputDir) {
  186. const backupDir = `${outputDir}.backup-${randomUUID()}`;
  187. let movedExistingOutput = false;
  188. try {
  189. await renameDirectoryWithRetries(outputDir, backupDir);
  190. movedExistingOutput = true;
  191. } catch (error) {
  192. if (error?.code !== "ENOENT") {
  193. throw error;
  194. }
  195. }
  196. try {
  197. await renameDirectoryWithRetries(stagedTempRoot, outputDir);
  198. } catch (error) {
  199. if (movedExistingOutput) {
  200. await renameDirectoryWithRetries(backupDir, outputDir);
  201. }
  202. throw error;
  203. }
  204. if (movedExistingOutput) {
  205. await rm(backupDir, REMOVE_DIRECTORY_OPTIONS);
  206. }
  207. }
  208. function sha256(bytes) {
  209. return createHash("sha256").update(bytes).digest("hex");
  210. }
  211. function isPlainRecord(value) {
  212. return typeof value === "object" && value !== null && !Array.isArray(value);
  213. }
  214. function hasExactKeys(value, expectedKeys) {
  215. const actualKeys = Object.keys(value).sort();
  216. const sortedExpectedKeys = [...expectedKeys].sort();
  217. return (
  218. actualKeys.length === sortedExpectedKeys.length &&
  219. actualKeys.every((key, index) => key === sortedExpectedKeys[index])
  220. );
  221. }
  222. function isNonEmptyTrimmedString(value) {
  223. return typeof value === "string" && value.length > 0 && value.trim() === value;
  224. }
  225. function isCanonicalRelativeArtifactPath(artifact) {
  226. return (
  227. typeof artifact === "string" &&
  228. artifact.length > 0 &&
  229. !artifact.includes("\\") &&
  230. !isAbsolute(artifact) &&
  231. !posix.isAbsolute(artifact) &&
  232. !win32.isAbsolute(artifact) &&
  233. posix.normalize(artifact) === artifact &&
  234. !artifact.split("/").some(
  235. (segment) =>
  236. !segment ||
  237. segment === "." ||
  238. segment === ".." ||
  239. // Windows 会把冒号解释成 ADS、把 NUL 当作路径终止符,必须在进入文件系统前拒绝。
  240. segment.includes(":") ||
  241. segment.includes("\0"),
  242. )
  243. );
  244. }
  245. function resolveCanonicalPackagedArtifact(root, artifact, label) {
  246. if (!isCanonicalRelativeArtifactPath(artifact)) {
  247. throw new Error(
  248. `[windows-cua-helper-assets] invalid ${label} path in ${RUNTIME_MANIFEST}: ${String(artifact)}`,
  249. );
  250. }
  251. const artifactPath = resolve(root, ...artifact.split("/"));
  252. const relativePath = relative(root, artifactPath);
  253. if (
  254. !relativePath ||
  255. relativePath === ".." ||
  256. relativePath.startsWith(`..${sep}`) ||
  257. isAbsolute(relativePath)
  258. ) {
  259. throw new Error(`[windows-cua-helper-assets] ${label} path escapes packaged root: ${artifact}`);
  260. }
  261. return artifactPath;
  262. }
  263. // 2026-08-18:把「契约不满足」拆成逐条可读的判定。原来十一个条件挤在一个 if 里、只抛一句
  264. // "invalid zcodeCuaRuntime Windows artifact path contract",看不出是 producer 少给了契约、
  265. // 还是仓库读错了目录。本次审计正是被这条报错误导:node_modules 停在改 pin 之前的旧提交
  266. // (git 依赖改 pin 不会自动重装),旧包没有 zcodeCuaRuntime,于是被误读成 producer 回归。
  267. // 报错必须自证:谁(包名@版本)、在哪(源目录)、缺哪一条。
  268. function describeRuntimeContractViolation(packageJson) {
  269. if (!isPlainRecord(packageJson)) return "source package.json is not a JSON object";
  270. if (packageJson.name !== EXPECTED_PACKAGE_NAME) {
  271. return `unexpected package name ${JSON.stringify(packageJson.name)}`;
  272. }
  273. if (!isNonEmptyTrimmedString(packageJson.version)) {
  274. return `invalid package version ${JSON.stringify(packageJson.version)}`;
  275. }
  276. const contract = packageJson.zcodeCuaRuntime;
  277. if (contract === undefined) {
  278. return "zcodeCuaRuntime is missing — the producer package does not publish a Windows runtime contract";
  279. }
  280. if (!isPlainRecord(contract)) return "zcodeCuaRuntime is not a JSON object";
  281. if (!hasExactKeys(contract, ["schema", "windows"])) {
  282. return `zcodeCuaRuntime must have exactly the keys {schema, windows}, got {${Object.keys(contract).join(", ")}}`;
  283. }
  284. if (contract.schema !== 1) {
  285. return `zcodeCuaRuntime.schema must be 1, got ${JSON.stringify(contract.schema)}`;
  286. }
  287. const windowsContract = contract.windows;
  288. if (!isPlainRecord(windowsContract)) return "zcodeCuaRuntime.windows is not a JSON object";
  289. if (!hasExactKeys(windowsContract, ["entry", "nativeAddon"])) {
  290. return `zcodeCuaRuntime.windows must have exactly the keys {entry, nativeAddon}, got {${Object.keys(windowsContract).join(", ")}}`;
  291. }
  292. if (!isCanonicalRelativeArtifactPath(windowsContract.entry)) {
  293. return `zcodeCuaRuntime.windows.entry is not a canonical relative artifact path: ${JSON.stringify(windowsContract.entry)}`;
  294. }
  295. if (!isCanonicalRelativeArtifactPath(windowsContract.nativeAddon)) {
  296. return `zcodeCuaRuntime.windows.nativeAddon is not a canonical relative artifact path: ${JSON.stringify(windowsContract.nativeAddon)}`;
  297. }
  298. if (windowsContract.entry === windowsContract.nativeAddon) {
  299. return "zcodeCuaRuntime.windows.entry and zcodeCuaRuntime.windows.nativeAddon must differ";
  300. }
  301. return undefined;
  302. }
  303. function readProducerRuntimeContract(packageJson, sourceRoot) {
  304. const violation = describeRuntimeContractViolation(packageJson);
  305. if (violation) {
  306. const identity = isPlainRecord(packageJson)
  307. ? `${String(packageJson.name)}@${String(packageJson.version)}`
  308. : "<unreadable package.json>";
  309. throw new Error(
  310. `[windows-cua-helper-assets] invalid zcodeCuaRuntime Windows artifact path contract in ${identity} (${sourceRoot}): ${violation}`,
  311. );
  312. }
  313. const windowsContract = packageJson.zcodeCuaRuntime.windows;
  314. return {
  315. packageVersion: packageJson.version,
  316. entry: windowsContract.entry,
  317. addon: windowsContract.nativeAddon,
  318. };
  319. }
  320. function assertPhysicalContainment(root, artifactPath, label) {
  321. const relativePath = relative(root, artifactPath);
  322. if (
  323. !relativePath ||
  324. relativePath === ".." ||
  325. relativePath.startsWith(`..${sep}`) ||
  326. isAbsolute(relativePath)
  327. ) {
  328. throw new Error(
  329. `[windows-cua-helper-assets] ${label} physical path is not contained by packaged root`,
  330. );
  331. }
  332. }
  333. function samePhysicalPath(expected, actual) {
  334. const normalize = (path) => {
  335. const normalized = resolve(path);
  336. return process.platform === "win32" ? normalized.toLowerCase() : normalized;
  337. };
  338. return normalize(expected) === normalize(actual);
  339. }
  340. function resolvePackagedRuntimePackageRoot(nodeModulesRoot, packageName) {
  341. if (
  342. typeof packageName !== "string" ||
  343. !/^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/iu.test(packageName)
  344. ) {
  345. throw new Error(
  346. `[windows-cua-helper-assets] invalid runtime dependency name: ${String(packageName)}`,
  347. );
  348. }
  349. return resolve(nodeModulesRoot, ...packageName.split("/"));
  350. }
  351. async function verifyPackagedRuntimeDependencyClosure({
  352. root,
  353. physicalRoot,
  354. targetPlatform,
  355. lstatOperation,
  356. realpathOperation,
  357. readFileOperation,
  358. }) {
  359. const nodeModulesRoot = resolve(root, "node_modules");
  360. const visited = new Set();
  361. const verifyPackage = async (packageName) => {
  362. if (visited.has(packageName)) return;
  363. visited.add(packageName);
  364. const packageRoot = resolvePackagedRuntimePackageRoot(nodeModulesRoot, packageName);
  365. let packageStats;
  366. try {
  367. packageStats = await lstatOperation(packageRoot);
  368. } catch (error) {
  369. throw new Error(`[windows-cua-helper-assets] missing runtime dependency: ${packageName}`, {
  370. cause: error,
  371. });
  372. }
  373. if (packageStats.isSymbolicLink() || !packageStats.isDirectory()) {
  374. throw new Error(
  375. `[windows-cua-helper-assets] runtime dependency must be a regular directory, not a symbolic link: ${packageName}`,
  376. );
  377. }
  378. const physicalPackageRoot = await realpathOperation(packageRoot);
  379. assertPhysicalContainment(
  380. physicalRoot,
  381. physicalPackageRoot,
  382. `runtime dependency ${packageName}`,
  383. );
  384. const packageJsonPath = resolve(packageRoot, "package.json");
  385. const packageJsonBytes = await readRegularFileSnapshot(
  386. packageJsonPath,
  387. `runtime dependency ${packageName}/package.json`,
  388. { lstatOperation, readFileOperation },
  389. );
  390. const physicalPackageJsonPath = await realpathOperation(packageJsonPath);
  391. assertPhysicalContainment(
  392. physicalRoot,
  393. physicalPackageJsonPath,
  394. `runtime dependency ${packageName}/package.json`,
  395. );
  396. let packageJson;
  397. try {
  398. packageJson = JSON.parse(
  399. Buffer.isBuffer(packageJsonBytes)
  400. ? packageJsonBytes.toString("utf8")
  401. : String(packageJsonBytes),
  402. );
  403. } catch (error) {
  404. throw new Error(
  405. `[windows-cua-helper-assets] invalid runtime dependency package.json: ${packageName}`,
  406. { cause: error },
  407. );
  408. }
  409. if (
  410. !isPlainRecord(packageJson) ||
  411. packageJson.name !== packageName ||
  412. (packageJson.dependencies !== undefined && !isPlainRecord(packageJson.dependencies))
  413. ) {
  414. throw new Error(
  415. `[windows-cua-helper-assets] invalid runtime dependency metadata: ${packageName}`,
  416. );
  417. }
  418. for (const dependencyName of Object.keys(packageJson.dependencies ?? {}).sort()) {
  419. await verifyPackage(dependencyName);
  420. }
  421. };
  422. const runtimePackageNames = ["express", ...resolveSharpRuntimePackageNames(targetPlatform)];
  423. for (const packageName of runtimePackageNames) {
  424. await verifyPackage(packageName);
  425. }
  426. }
  427. /**
  428. * electron-builder 完成资源复制后,按发布 manifest 重新验证最终安装目录。
  429. */
  430. async function inspectPackagedWindowsCuaHelper({
  431. resourcesDir,
  432. targetPlatform,
  433. electronVersion,
  434. verifyHashes,
  435. lstatOperation = lstat,
  436. realpathOperation = realpath,
  437. readFileOperation = readFile,
  438. }) {
  439. if (targetPlatform?.os !== "win32") {
  440. return { status: "skipped", reason: "unsupported-platform" };
  441. }
  442. if (!isAbsolute(resourcesDir)) {
  443. throw new Error("[windows-cua-helper-assets] resourcesDir must be absolute");
  444. }
  445. const expectedMachine = PE_MACHINE_BY_ARCH[targetPlatform.arch];
  446. if (!expectedMachine) {
  447. throw new Error(
  448. `[windows-cua-helper-assets] unsupported Windows architecture: ${targetPlatform.arch}`,
  449. );
  450. }
  451. const expectedElectronVersion = electronVersion?.trim();
  452. if (!expectedElectronVersion) {
  453. throw new Error("[windows-cua-helper-assets] electronVersion is required");
  454. }
  455. const root = resolve(resourcesDir, "tools", "cua-helper");
  456. let rootStats;
  457. try {
  458. rootStats = await lstatOperation(root);
  459. } catch (error) {
  460. throw new Error(`[windows-cua-helper-assets] packaged root is missing: ${root}`, {
  461. cause: error,
  462. });
  463. }
  464. if (rootStats.isSymbolicLink() || !rootStats.isDirectory()) {
  465. throw new Error(
  466. `[windows-cua-helper-assets] packaged root must be a regular directory: ${root}`,
  467. );
  468. }
  469. const [physicalResourcesDir, physicalRoot] = await Promise.all([
  470. realpathOperation(resourcesDir),
  471. realpathOperation(root),
  472. ]);
  473. // 根因:root 自身不是链接并不能排除父级 tools 是 junction;整棵 Helper 树仍可能落到 resources 外。
  474. assertPhysicalContainment(physicalResourcesDir, physicalRoot, "packaged root");
  475. const manifestPath = resolve(root, RUNTIME_MANIFEST);
  476. const manifestBytes = await readRegularFileSnapshot(manifestPath, RUNTIME_MANIFEST, {
  477. lstatOperation,
  478. readFileOperation,
  479. });
  480. const physicalManifestPath = await realpathOperation(manifestPath);
  481. assertPhysicalContainment(physicalRoot, physicalManifestPath, RUNTIME_MANIFEST);
  482. let manifest;
  483. try {
  484. manifest = JSON.parse(
  485. Buffer.isBuffer(manifestBytes) ? manifestBytes.toString("utf8") : String(manifestBytes),
  486. );
  487. } catch (error) {
  488. throw new Error(`[windows-cua-helper-assets] invalid ${RUNTIME_MANIFEST}: ${manifestPath}`, {
  489. cause: error,
  490. });
  491. }
  492. if (
  493. !isPlainRecord(manifest) ||
  494. !isPlainRecord(manifest.sha256) ||
  495. !hasExactKeys(manifest, [
  496. "schemaVersion",
  497. "packageName",
  498. "packageVersion",
  499. "platform",
  500. "arch",
  501. "electronVersion",
  502. "entry",
  503. "addon",
  504. "sha256",
  505. ]) ||
  506. !hasExactKeys(manifest.sha256, ["entry", "addon"]) ||
  507. !isNonEmptyTrimmedString(manifest.packageVersion) ||
  508. typeof manifest.entry !== "string" ||
  509. typeof manifest.addon !== "string" ||
  510. typeof manifest.sha256.entry !== "string" ||
  511. typeof manifest.sha256.addon !== "string" ||
  512. !/^[0-9a-f]{64}$/u.test(manifest.sha256.entry) ||
  513. !/^[0-9a-f]{64}$/u.test(manifest.sha256.addon)
  514. ) {
  515. throw new Error(
  516. `[windows-cua-helper-assets] invalid ${RUNTIME_MANIFEST} shape: ${manifestPath}`,
  517. );
  518. }
  519. if (manifest.entry === manifest.addon) {
  520. throw new Error(
  521. `[windows-cua-helper-assets] ${RUNTIME_MANIFEST} entry and addon must be distinct artifacts`,
  522. );
  523. }
  524. const expectedManifestFields = {
  525. schemaVersion: 1,
  526. packageName: EXPECTED_PACKAGE_NAME,
  527. platform: "win32",
  528. arch: targetPlatform.arch,
  529. electronVersion: expectedElectronVersion,
  530. };
  531. for (const [field, expected] of Object.entries(expectedManifestFields)) {
  532. if (manifest[field] !== expected) {
  533. throw new Error(
  534. `[windows-cua-helper-assets] incompatible ${RUNTIME_MANIFEST} ${field}: expected ${String(expected)}`,
  535. );
  536. }
  537. }
  538. const moduleTypePackageJsonPath = resolve(root, MODULE_TYPE_PACKAGE_JSON);
  539. const moduleTypePackageJsonBytes = await readRegularFileSnapshot(
  540. moduleTypePackageJsonPath,
  541. MODULE_TYPE_PACKAGE_JSON,
  542. {
  543. lstatOperation,
  544. readFileOperation,
  545. },
  546. );
  547. const physicalModuleTypePackageJsonPath = await realpathOperation(moduleTypePackageJsonPath);
  548. assertPhysicalContainment(
  549. physicalRoot,
  550. physicalModuleTypePackageJsonPath,
  551. MODULE_TYPE_PACKAGE_JSON,
  552. );
  553. let moduleTypePackageJson;
  554. try {
  555. moduleTypePackageJson = JSON.parse(
  556. Buffer.isBuffer(moduleTypePackageJsonBytes)
  557. ? moduleTypePackageJsonBytes.toString("utf8")
  558. : String(moduleTypePackageJsonBytes),
  559. );
  560. } catch (error) {
  561. throw new Error(
  562. `[windows-cua-helper-assets] invalid ${MODULE_TYPE_PACKAGE_JSON}: ${moduleTypePackageJsonPath}`,
  563. { cause: error },
  564. );
  565. }
  566. if (
  567. !isPlainRecord(moduleTypePackageJson) ||
  568. moduleTypePackageJson.type !== "module" ||
  569. moduleTypePackageJson.version !== manifest.packageVersion
  570. ) {
  571. // 根因:entry 是 ESM;缺 module 声明或声明成 commonjs 时,模块类型只能靠 detect-module
  572. // 探测兜底,安装盘链上的杂散 package.json 会直接把 fork 打成 SyntaxError exit 1。
  573. throw new Error(
  574. `[windows-cua-helper-assets] ${MODULE_TYPE_PACKAGE_JSON} must declare {"type":"module"} and carry the same version as ${RUNTIME_MANIFEST}: ${moduleTypePackageJsonPath}`,
  575. );
  576. }
  577. const entryPath = resolveCanonicalPackagedArtifact(root, manifest.entry, "entry");
  578. const addonPath = resolveCanonicalPackagedArtifact(root, manifest.addon, "addon");
  579. const [entryBytes, addonBytes] = await Promise.all([
  580. readRegularFileSnapshot(entryPath, "entry", {
  581. lstatOperation,
  582. readFileOperation,
  583. }),
  584. readRegularFileSnapshot(addonPath, "addon", {
  585. lstatOperation,
  586. readFileOperation,
  587. }),
  588. ]);
  589. const [physicalEntryPath, physicalAddonPath] = await Promise.all([
  590. realpathOperation(entryPath),
  591. realpathOperation(addonPath),
  592. ]);
  593. // 根因:manifest 的词法路径即使位于 root 内,也可能经 junction/reparse point 指向 root 外。
  594. // afterPack 必须同时验证 realpath containment,不能只依赖 resolve/relative 的字符串检查。
  595. assertPhysicalContainment(physicalRoot, physicalEntryPath, "entry");
  596. assertPhysicalContainment(physicalRoot, physicalAddonPath, "addon");
  597. if (verifyHashes) {
  598. if (sha256(entryBytes) !== manifest.sha256.entry) {
  599. throw new Error("[windows-cua-helper-assets] entry SHA-256 hash mismatch");
  600. }
  601. if (sha256(addonBytes) !== manifest.sha256.addon) {
  602. throw new Error("[windows-cua-helper-assets] addon SHA-256 hash mismatch");
  603. }
  604. }
  605. const peMachine = parsePeMachine(addonBytes, addonPath);
  606. if (peMachine !== expectedMachine) {
  607. throw new Error(
  608. `[windows-cua-helper-assets] PE machine mismatch: expected 0x${expectedMachine.toString(16)}, got 0x${peMachine.toString(16)}`,
  609. );
  610. }
  611. // 根因:extraResources 会跳过 from 根目录下的 node_modules;仅校验 entry/addon 会让
  612. // “Helper 主树存在但 express/Sharp 闭包缺失”的安装包通过 afterPack。
  613. await verifyPackagedRuntimeDependencyClosure({
  614. root,
  615. physicalRoot,
  616. targetPlatform,
  617. lstatOperation,
  618. realpathOperation,
  619. readFileOperation,
  620. });
  621. return {
  622. status: "verified",
  623. root,
  624. entryPath,
  625. addonPath,
  626. peMachine,
  627. manifestPath,
  628. manifest,
  629. entryBytes,
  630. addonBytes,
  631. };
  632. }
  633. function toPackagedVerificationResult(inspection) {
  634. if (inspection.status === "skipped") return inspection;
  635. return {
  636. status: inspection.status,
  637. root: inspection.root,
  638. entryPath: inspection.entryPath,
  639. addonPath: inspection.addonPath,
  640. peMachine: inspection.peMachine,
  641. };
  642. }
  643. /**
  644. * electron-builder 完成资源复制后,按发布 manifest 严格验证最终安装目录。
  645. */
  646. export async function verifyPackagedWindowsCuaHelper(options) {
  647. const inspection = await inspectPackagedWindowsCuaHelper({
  648. ...options,
  649. verifyHashes: true,
  650. });
  651. return toPackagedVerificationResult(inspection);
  652. }
  653. /**
  654. * Windows extraResources 的原生文件在复制阶段完成签名;签名会改变字节,必须在 afterPack
  655. * 仅刷新最终产物哈希,然后用同一严格 verifier 再次闭环验证。
  656. */
  657. export async function finalizePackagedWindowsCuaHelper({
  658. writeFileOperation = writeFile,
  659. ...options
  660. }) {
  661. const inspection = await inspectPackagedWindowsCuaHelper({
  662. ...options,
  663. verifyHashes: false,
  664. });
  665. if (inspection.status === "skipped") return inspection;
  666. const finalizedManifest = {
  667. ...inspection.manifest,
  668. sha256: {
  669. entry: sha256(inspection.entryBytes),
  670. addon: sha256(inspection.addonBytes),
  671. },
  672. };
  673. await writeFileOperation(
  674. inspection.manifestPath,
  675. `${JSON.stringify(finalizedManifest, null, 2)}\n`,
  676. "utf8",
  677. );
  678. return verifyPackagedWindowsCuaHelper(options);
  679. }
  680. export async function resolveWindowsCuaHelperSourceRoot({
  681. runtimePackageDir,
  682. devRoot,
  683. servicesPackageRoot,
  684. }) {
  685. const explicitRuntimePackageDir = runtimePackageDir?.trim();
  686. const explicitDevRoot = devRoot?.trim();
  687. const explicitRoot = explicitRuntimePackageDir || explicitDevRoot;
  688. if (explicitRoot) {
  689. if (!isAbsolute(explicitRoot)) {
  690. const variableName = explicitRuntimePackageDir
  691. ? "ZCODE_CUA_HELPER_RUNTIME_PACKAGE_DIR"
  692. : "ZCODE_CUA_DEV_ROOT";
  693. throw new Error(`[windows-cua-helper-assets] ${variableName} must be absolute`);
  694. }
  695. return realpath(explicitRoot);
  696. }
  697. if (!isAbsolute(servicesPackageRoot)) {
  698. throw new Error("[windows-cua-helper-assets] servicesPackageRoot must be absolute");
  699. }
  700. // servicesPackageRoot 固定对应当前仓库的 packages/services;CUA producer 是同一 workspace 的
  701. // packages/zcode-cua,禁止向上扫描到用户目录或另一个仓库。
  702. const workspaceRoot = resolve(servicesPackageRoot, "..", "..");
  703. const workspaceMarkerPath = resolve(workspaceRoot, "pnpm-workspace.yaml");
  704. let markerStats;
  705. try {
  706. markerStats = await lstat(workspaceMarkerPath);
  707. } catch (error) {
  708. throw new Error(
  709. `[windows-cua-helper-assets] pnpm-workspace.yaml is unavailable: ${workspaceMarkerPath}`,
  710. { cause: error },
  711. );
  712. }
  713. if (!markerStats.isFile() || markerStats.isSymbolicLink()) {
  714. throw new Error(
  715. `[windows-cua-helper-assets] pnpm-workspace.yaml must be a regular file: ${workspaceMarkerPath}`,
  716. );
  717. }
  718. const packageRoot = resolve(workspaceRoot, "packages", "zcode-cua");
  719. try {
  720. return await realpath(packageRoot);
  721. } catch (error) {
  722. throw new Error(
  723. `[windows-cua-helper-assets] packaged helper runtime is unavailable: ${packageRoot}`,
  724. { cause: error },
  725. );
  726. }
  727. }
  728. export async function prepareWindowsCuaHelperAssets({
  729. sourceRoot,
  730. outputRoot,
  731. targetPlatform,
  732. electronVersion,
  733. afterArtifactSnapshot,
  734. lstatOperation = lstat,
  735. realpathOperation = realpath,
  736. readFileOperation = readFile,
  737. }) {
  738. if (targetPlatform?.os !== "win32") {
  739. return { status: "skipped", reason: "unsupported-platform" };
  740. }
  741. if (!isAbsolute(sourceRoot) || !isAbsolute(outputRoot)) {
  742. throw new Error("[windows-cua-helper-assets] sourceRoot and outputRoot must be absolute");
  743. }
  744. const expectedMachine = PE_MACHINE_BY_ARCH[targetPlatform.arch];
  745. if (!expectedMachine) {
  746. throw new Error(
  747. `[windows-cua-helper-assets] unsupported Windows architecture: ${targetPlatform.arch}`,
  748. );
  749. }
  750. if (!electronVersion?.trim()) {
  751. throw new Error("[windows-cua-helper-assets] electronVersion is required");
  752. }
  753. let sourceRootStats;
  754. try {
  755. sourceRootStats = await lstatOperation(sourceRoot);
  756. } catch (error) {
  757. throw new Error(`[windows-cua-helper-assets] source root is unavailable: ${sourceRoot}`, {
  758. cause: error,
  759. });
  760. }
  761. if (sourceRootStats.isSymbolicLink() || !sourceRootStats.isDirectory()) {
  762. throw new Error(
  763. `[windows-cua-helper-assets] source root must be a regular directory, not a symbolic link: ${sourceRoot}`,
  764. );
  765. }
  766. const physicalSourceRoot = await realpathOperation(sourceRoot);
  767. // 根因:只检查 sourceRoot 叶子会漏掉父级 junction;显式构建根必须已经解析到物理目录。
  768. if (!samePhysicalPath(sourceRoot, physicalSourceRoot)) {
  769. throw new Error(
  770. `[windows-cua-helper-assets] source root physical path does not match its configured location: ${sourceRoot}`,
  771. );
  772. }
  773. const packageJsonPath = resolve(sourceRoot, "package.json");
  774. const packageJson = await readContainedJson(
  775. physicalSourceRoot,
  776. packageJsonPath,
  777. "source package",
  778. { lstatOperation, realpathOperation, readFileOperation },
  779. );
  780. if (packageJson.name !== EXPECTED_PACKAGE_NAME) {
  781. throw new Error(
  782. `[windows-cua-helper-assets] unexpected package name: ${String(packageJson.name)}`,
  783. );
  784. }
  785. if (!isNonEmptyTrimmedString(packageJson.version)) {
  786. throw new Error(
  787. `[windows-cua-helper-assets] invalid package version: ${String(packageJson.version)}`,
  788. );
  789. }
  790. // 根因:消费端固定版本号和 artifact 目录会让生产者每次独立发版都必须同步改 ZCode。
  791. // package.json 的严格契约才是兼容边界;version 只作为安装产物的来源追踪信息。
  792. const producerContract = readProducerRuntimeContract(packageJson, sourceRoot);
  793. const entryPath = resolveCanonicalPackagedArtifact(
  794. sourceRoot,
  795. producerContract.entry,
  796. "zcodeCuaRuntime.windows.entry",
  797. );
  798. const addonPath = resolveCanonicalPackagedArtifact(
  799. sourceRoot,
  800. producerContract.addon,
  801. "zcodeCuaRuntime.windows.nativeAddon",
  802. );
  803. const [entryBytes, addonBytes] = await Promise.all([
  804. readRegularFileSnapshot(entryPath, "entry", {
  805. lstatOperation,
  806. readFileOperation,
  807. }),
  808. readRegularFileSnapshot(addonPath, "addon", {
  809. lstatOperation,
  810. readFileOperation,
  811. }),
  812. ]);
  813. const [physicalEntryPath, physicalAddonPath] = await Promise.all([
  814. realpathOperation(entryPath),
  815. realpathOperation(addonPath),
  816. ]);
  817. // 根因:规范相对路径仍可穿过中间 junction,必须在读取快照后核对最终物理位置。
  818. assertPhysicalContainment(physicalSourceRoot, physicalEntryPath, "entry");
  819. assertPhysicalContainment(physicalSourceRoot, physicalAddonPath, "addon");
  820. const actualMachine = parsePeMachine(addonBytes, addonPath);
  821. if (actualMachine !== expectedMachine) {
  822. throw new Error(
  823. `[windows-cua-helper-assets] PE machine mismatch: expected 0x${expectedMachine.toString(16)}, got 0x${actualMachine.toString(16)}`,
  824. );
  825. }
  826. await afterArtifactSnapshot?.();
  827. const targetKey = `win32-${targetPlatform.arch}`;
  828. const outputDir = resolve(outputRoot, targetKey, "cua-helper");
  829. const outputParent = dirname(outputDir);
  830. await mkdir(outputParent, { recursive: true });
  831. const stagedTempRoot = resolve(outputParent, `.cua-helper.tmp-${randomUUID()}`);
  832. await mkdir(stagedTempRoot, { recursive: true });
  833. try {
  834. const stagedEntryPath = resolveCanonicalPackagedArtifact(
  835. stagedTempRoot,
  836. producerContract.entry,
  837. "entry",
  838. );
  839. const stagedAddonPath = resolveCanonicalPackagedArtifact(
  840. stagedTempRoot,
  841. producerContract.addon,
  842. "addon",
  843. );
  844. await Promise.all([
  845. mkdir(dirname(stagedEntryPath), { recursive: true }),
  846. mkdir(dirname(stagedAddonPath), { recursive: true }),
  847. mkdir(resolve(stagedTempRoot, "node_modules"), { recursive: true }),
  848. ]);
  849. await Promise.all([
  850. writeFile(stagedEntryPath, entryBytes),
  851. writeFile(stagedAddonPath, addonBytes),
  852. ]);
  853. const moduleLookupRoots = resolveModuleLookupRoots(sourceRoot);
  854. const expressEntries = collectRuntimeModuleClosureEntries(["express"], moduleLookupRoots);
  855. const sharpModuleNames = resolveSharpRuntimePackageNames({
  856. os: "win32",
  857. arch: targetPlatform.arch,
  858. });
  859. const sharpModuleNameSet = new Set(sharpModuleNames);
  860. // Sharp 声明了所有平台的 optionalDependencies;这里只保留当前目标集合,
  861. // 避免把其他架构的原生包带进安装包和签名面。
  862. const sharpEntries = collectRuntimeModuleClosureEntries(
  863. sharpModuleNames,
  864. moduleLookupRoots,
  865. ).filter((entry) => sharpModuleNameSet.has(entry.moduleName));
  866. const runtimeEntries = [
  867. ...new Map(
  868. [...expressEntries, ...sharpEntries].map((entry) => [entry.moduleName, entry]),
  869. ).values(),
  870. ];
  871. for (const entry of runtimeEntries) {
  872. if (!entry.sourceModulePath) {
  873. throw new Error(
  874. `[windows-cua-helper-assets] missing runtime dependency: ${entry.moduleName}`,
  875. );
  876. }
  877. await copyRuntimePackage(
  878. entry.sourceModulePath,
  879. resolve(stagedTempRoot, "node_modules", entry.moduleName),
  880. );
  881. }
  882. const [stagedEntryBytes, stagedAddonBytes] = await Promise.all([
  883. readFile(stagedEntryPath),
  884. readFile(stagedAddonPath),
  885. ]);
  886. const manifest = {
  887. schemaVersion: 1,
  888. packageName: EXPECTED_PACKAGE_NAME,
  889. packageVersion: producerContract.packageVersion,
  890. platform: "win32",
  891. arch: targetPlatform.arch,
  892. electronVersion: electronVersion.trim(),
  893. entry: producerContract.entry,
  894. addon: producerContract.addon,
  895. sha256: {
  896. entry: sha256(stagedEntryBytes),
  897. addon: sha256(stagedAddonBytes),
  898. },
  899. };
  900. await writeFile(
  901. resolve(stagedTempRoot, RUNTIME_MANIFEST),
  902. `${JSON.stringify(manifest, null, 2)}\n`,
  903. "utf8",
  904. );
  905. // 根因(ZCT-2093176018262081536):entry 是含裸 import 的 ESM,staging 只拷 entry/addon
  906. // 时把 producer 的 package.json 留在了源目录,安装目录的模块类型解析只能退到盘符根。
  907. // Node ≥22.7 的 detect-module 兜底了默认场景,但安装盘链上任何带 "type" 的杂散
  908. // package.json 都会禁用探测,fork 将以 SyntaxError exit 1 变成 broker_unavailable。
  909. // 在运行时根落一份显式 module 声明,让 entry 的模块类型不依赖探测、不受外部目录影响。
  910. const moduleTypePackageJson = {
  911. name: "@zcode/zcode-cua-helper-runtime",
  912. version: producerContract.packageVersion,
  913. type: "module",
  914. private: true,
  915. main: producerContract.entry,
  916. };
  917. await writeFile(
  918. resolve(stagedTempRoot, MODULE_TYPE_PACKAGE_JSON),
  919. `${JSON.stringify(moduleTypePackageJson, null, 2)}\n`,
  920. "utf8",
  921. );
  922. await atomicallyReplaceDirectory(stagedTempRoot, outputDir);
  923. return { status: "staged", outputDir, manifest, peMachine: actualMachine };
  924. } catch (error) {
  925. await rm(stagedTempRoot, REMOVE_DIRECTORY_OPTIONS);
  926. throw error;
  927. }
  928. }