windows-cua-helper-assets.mjs 34 KB

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