electronBuilderSecurity.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. import { afterEach, expect, it, vi } from "vitest";
  2. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  3. import { createRequire } from "node:module";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { parse as parseYaml } from "yaml";
  7. import { NsisUpdater } from "electron-updater";
  8. import { writeWindowsUpdatePublisher } from "../scripts/windows-update-publisher.mjs";
  9. const require = createRequire(import.meta.url);
  10. it("Windows 更新发布者来自已签名应用,并保留原更新配置", async () => {
  11. const root = await mkdtemp(join(tmpdir(), "zcode-update-publisher-"));
  12. const configPath = join(root, "resources/app-update.yml");
  13. try {
  14. await mkdir(join(root, "resources"));
  15. await writeFile(
  16. configPath,
  17. "provider: generic\nurl: https://updates.example.com\nupdaterCacheDirName: example-updater\n",
  18. );
  19. const readSignature = vi.fn(async () => ({
  20. status: 0,
  21. subject: "CN=Example Publisher, O=Example Company, C=US",
  22. }));
  23. vi.stubEnv("ZCODE_WINDOWS_UPDATE_TRUSTED_PUBLISHER_DNS", "invalid retired setting");
  24. await writeWindowsUpdatePublisher({
  25. appOutDir: root,
  26. executableName: "Example",
  27. readSignature,
  28. });
  29. expect(readSignature).toHaveBeenCalledWith(join(root, "Example.exe"));
  30. expect(parseYaml(await readFile(configPath, "utf8"))).toEqual({
  31. provider: "generic",
  32. url: "https://updates.example.com",
  33. updaterCacheDirName: "example-updater",
  34. publisherName: ["CN=Example Publisher, O=Example Company, C=US"],
  35. });
  36. // 用锁定版本的真实更新器消费生成配置,确认不再落入缺失 publisherName 的免检分支。
  37. const updater = new NsisUpdater(null, {
  38. version: "1.0.0",
  39. name: "Example",
  40. isPackaged: true,
  41. appUpdateConfigPath: configPath,
  42. userDataPath: root,
  43. baseCachePath: root,
  44. whenReady: async () => {},
  45. relaunch: () => {},
  46. quit: () => {},
  47. onQuit: () => {},
  48. });
  49. const verifier = vi.fn(async () => null as string | null);
  50. updater.verifyUpdateCodeSignature = verifier;
  51. const verify = updater as unknown as { verifySignature(path: string): Promise<string | null> };
  52. const installer = join(root, "update.exe");
  53. expect(await verify.verifySignature(installer)).toBeNull();
  54. expect(verifier).toHaveBeenCalledWith(
  55. ["CN=Example Publisher, O=Example Company, C=US"],
  56. installer,
  57. );
  58. verifier.mockResolvedValueOnce("invalid signature");
  59. expect(await verify.verifySignature(installer)).toBe("invalid signature");
  60. } finally {
  61. await rm(root, { recursive: true, force: true });
  62. }
  63. });
  64. it.each([
  65. { status: 1, subject: "CN=Example" },
  66. { status: 0, subject: "" },
  67. { status: 0, subject: null },
  68. ])("无效签名或缺少发布者时不生成可发布更新配置 %j", async (signature) => {
  69. const root = await mkdtemp(join(tmpdir(), "zcode-update-publisher-"));
  70. const configPath = join(root, "resources/app-update.yml");
  71. const original = "provider: generic\nurl: https://updates.example.com\n";
  72. try {
  73. await mkdir(join(root, "resources"));
  74. await writeFile(configPath, original);
  75. await expect(
  76. writeWindowsUpdatePublisher({
  77. appOutDir: root,
  78. executableName: "Example",
  79. readSignature: async () => signature,
  80. }),
  81. ).rejects.toThrow();
  82. expect(await readFile(configPath, "utf8")).toBe(original);
  83. } finally {
  84. await rm(root, { recursive: true, force: true });
  85. }
  86. });
  87. it("签名读取错误或缺少更新配置时构建失败", async () => {
  88. const root = await mkdtemp(join(tmpdir(), "zcode-update-publisher-"));
  89. try {
  90. await expect(
  91. writeWindowsUpdatePublisher({
  92. appOutDir: root,
  93. executableName: "Example",
  94. readSignature: async () => {
  95. throw new Error("signature unavailable");
  96. },
  97. }),
  98. ).rejects.toThrow("signature unavailable");
  99. await expect(
  100. writeWindowsUpdatePublisher({
  101. appOutDir: root,
  102. executableName: "Example",
  103. readSignature: async () => ({ status: 0, subject: "CN=Example" }),
  104. }),
  105. ).rejects.toThrow();
  106. } finally {
  107. await rm(root, { recursive: true, force: true });
  108. }
  109. });
  110. afterEach(() => {
  111. vi.unstubAllEnvs();
  112. vi.resetModules();
  113. });
  114. it("精确锁定 Electron 44 与配套打包更新工具链", async () => {
  115. const desktopPackage = JSON.parse(
  116. await readFile(new URL("../package.json", import.meta.url), "utf8"),
  117. );
  118. expect(desktopPackage.devDependencies.electron).toBe("44.7.0");
  119. expect(desktopPackage.devDependencies["electron-builder"]).toBe("26.17.0");
  120. expect(desktopPackage.dependencies["electron-updater"]).toBe("6.8.10");
  121. expect(require("electron-builder/package.json").version).toBe("26.17.0");
  122. expect(require("electron-updater/package.json").version).toBe("6.8.10");
  123. });
  124. it("安装包使用 desktop 依赖中的唯一 Electron 版本,并声明 macOS 13 下限", async () => {
  125. const desktopPackage = JSON.parse(
  126. await readFile(new URL("../package.json", import.meta.url), "utf8"),
  127. );
  128. const { default: config } = await import("../electron-builder.config.js");
  129. expect(config.electronVersion).toBe(desktopPackage.devDependencies.electron);
  130. expect(config.mac?.minimumSystemVersion).toBe("13.0.0");
  131. });
  132. it("macOS afterExtract 从 app Resources 保留 Electron 原始许可", async () => {
  133. vi.stubEnv("ZCODE_TARGET_OS", "darwin");
  134. const { default: config } = await import("../electron-builder.config.js");
  135. const root = await mkdtemp(join(tmpdir(), "zcode-electron-license-mac-"));
  136. const appName = "Electron.app";
  137. const resources = join(root, appName, "Contents", "Resources");
  138. try {
  139. await mkdir(resources, { recursive: true });
  140. await writeFile(join(resources, "LICENSE.electron.txt"), "electron-license");
  141. await writeFile(join(resources, "LICENSES.chromium.html"), "chromium-license");
  142. await config.afterExtract?.({
  143. appOutDir: root,
  144. electronPlatformName: "darwin",
  145. packager: { info: { framework: { distMacOsAppName: appName, version: "44.7.0" } } },
  146. } as never);
  147. expect(await readFile(join(resources, "licenses/electron/LICENSE"), "utf8")).toBe(
  148. "electron-license",
  149. );
  150. expect(
  151. await readFile(join(resources, "licenses/electron/LICENSES.chromium.html"), "utf8"),
  152. ).toBe("chromium-license");
  153. } finally {
  154. await rm(root, { recursive: true, force: true });
  155. }
  156. });
  157. it("Windows afterExtract 继续从 appOutDir 根目录保留 Electron 原始许可", async () => {
  158. vi.stubEnv("ZCODE_TARGET_OS", "win32");
  159. const { default: config } = await import("../electron-builder.config.js");
  160. const root = await mkdtemp(join(tmpdir(), "zcode-electron-license-win-"));
  161. const resources = join(root, "resources");
  162. try {
  163. await mkdir(resources, { recursive: true });
  164. await writeFile(join(root, "LICENSE.electron.txt"), "electron-license");
  165. await writeFile(join(root, "LICENSES.chromium.html"), "chromium-license");
  166. await config.afterExtract?.({
  167. appOutDir: root,
  168. electronPlatformName: "win32",
  169. packager: { info: { framework: { distMacOsAppName: "Electron.app", version: "44.7.0" } } },
  170. } as never);
  171. expect(await readFile(join(resources, "licenses/electron/LICENSE"), "utf8")).toBe(
  172. "electron-license",
  173. );
  174. expect(
  175. await readFile(join(resources, "licenses/electron/LICENSES.chromium.html"), "utf8"),
  176. ).toBe("chromium-license");
  177. } finally {
  178. await rm(root, { recursive: true, force: true });
  179. }
  180. });
  181. it("缺失生产依赖时打包必须失败", async () => {
  182. const { default: config } = await import("../electron-builder.config.js");
  183. expect(config.allowMissingDependencies).toBe(false);
  184. });
  185. it("Windows 打包关闭 Node Inspector,保留 Agent 所需的 RunAsNode", async () => {
  186. vi.stubEnv("ZCODE_TARGET_OS", "win32");
  187. const { default: config } = await import("../electron-builder.config.js");
  188. expect(config.electronFuses?.enableNodeCliInspectArguments).toBe(false);
  189. expect(config.electronFuses?.runAsNode).toBeUndefined();
  190. expect(config.win?.verifyUpdateCodeSignature).toBe(true);
  191. });
  192. it.each(["darwin", "linux"])("%s 保留现有 fuse 配置", async (platform) => {
  193. vi.stubEnv("ZCODE_TARGET_OS", platform);
  194. const { default: config } = await import("../electron-builder.config.js");
  195. expect(config.electronFuses).toBeUndefined();
  196. });
  197. it("DMG contents 不得引用镜像内生成的隐藏文件", async () => {
  198. const { default: config } = await import("../electron-builder.config.js");
  199. // dmg-builder@1.2.5 的 dmgbuild 会把每个 type:"file" 条目当作真实源文件 ditto;
  200. // .background/.VolumeIcon 等隐藏文件由 dmgbuild 在镜像内生成,列入 contents
  201. // 会在 DMG 阶段以 "Cannot get the real path" 硬失败。
  202. const fileEntries = (config.dmg?.contents ?? []).filter((item) => item.type === "file");
  203. const generatedHiddenFiles = fileEntries.filter(
  204. (item) =>
  205. typeof item.path === "string" &&
  206. (item.path.startsWith(".") ||
  207. item.path.includes("/.background") ||
  208. item.path.includes("/.VolumeIcon")),
  209. );
  210. expect(generatedHiddenFiles).toEqual([]);
  211. });
  212. it("files 规则裁剪已核实为构建期的依赖,且保留 @babel/runtime", async () => {
  213. const { default: config } = await import("../electron-builder.config.js");
  214. const files = config.files as string[];
  215. // 26.17 收集器按 lockfile 全平台图收包,以下依赖经全仓运行时代码 grep
  216. // 确认零引用,属于构建链被误收进 app.asar 的部分(2026-10-26 asar 逐包对账)。
  217. for (const pattern of [
  218. "!node_modules/shadcn/**",
  219. "!node_modules/@ts-morph/**",
  220. "!node_modules/ts-morph/**",
  221. "!node_modules/@babel/**",
  222. "!node_modules/caniuse-lite/**",
  223. "!node_modules/browserslist/**",
  224. "!node_modules/baseline-browser-mapping/**",
  225. "!node_modules/node-gyp/**",
  226. "!node_modules/node-addon-api/**",
  227. "!node_modules/cpu-features/**",
  228. "!node_modules/nan/**",
  229. ]) {
  230. expect(files).toContain(pattern);
  231. }
  232. // @babel/runtime 被部分库运行时 require,重新包含必须晚于整目录排除(后序模式优先)。
  233. expect(files.indexOf("node_modules/@babel/runtime/**")).toBeGreaterThan(
  234. files.indexOf("!node_modules/@babel/**"),
  235. );
  236. });