sign-windows-hook.cjs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const { open } = require("node:fs/promises");
  2. const { resolve } = require("node:path");
  3. const signScriptPath = resolve(__dirname, "../../../scripts/sign-windows.ps1");
  4. async function isWindowsPortableExecutable(filePath) {
  5. // 修复原因:electron-builder 26.17 的 pnpm 收集器按 lockfile 图把 sharp 的全平台
  6. // optionalDependencies(darwin/linux 变体,Mach-O/ELF 格式)一并打进 app.asar.unpacked,
  7. // signApp 阶段遍历 unpacked 目录时会把它们送进 Windows 签名;vsigntool/DigiCert token
  8. // 处理非 PE 输入后会进入坏状态,同一 job 里后续所有签名连锁报 0x8010006a
  9. // (2026-10-26 CI 实况:第一簇纯 win32 PE 签名全绿,第二簇起全部拒绝)。
  10. // Windows Authenticode 只对 PE 有意义,仅在成功读取魔数且确认非 MZ 时跳过;
  11. // 打开/读取失败必须向上抛(评审 CR-01:读取失败被静默当作非 PE 会让
  12. // 真实 PE 漏签且构建不失败,签名链必须 fail-closed)。
  13. let fileHandle;
  14. try {
  15. fileHandle = await open(filePath, "r");
  16. const magic = Buffer.alloc(2);
  17. const { bytesRead } = await fileHandle.read(magic, 0, 2, 0);
  18. if (bytesRead < 2) {
  19. return false;
  20. }
  21. return magic[0] === 0x4d && magic[1] === 0x5a;
  22. } finally {
  23. if (fileHandle !== undefined) {
  24. await fileHandle.close();
  25. }
  26. }
  27. }
  28. async function sign(configuration) {
  29. if (configuration.isNest) {
  30. // Bugfix: electron-builder 会按 sha1/sha256 多次调用 Windows signer,
  31. // 但 vsigntool 这套封装本身会完成完整签名流程,重复再签只会增加不确定性。
  32. // 这里跳过嵌套签名,统一以首轮调用为准,避免同一文件被重复处理。
  33. return;
  34. }
  35. if ((await isWindowsPortableExecutable(configuration.path)) === false) {
  36. console.log(`[sign-windows-hook] skip non-PE file: ${configuration.path}`);
  37. return;
  38. }
  39. // 在调用点 require:模块加载期解构会固化 spawnSync 原引用,测试无法替换。
  40. const { spawnSync } = require("node:child_process");
  41. const result = spawnSync(
  42. "powershell.exe",
  43. [
  44. "-NoProfile",
  45. "-ExecutionPolicy",
  46. "Bypass",
  47. "-File",
  48. signScriptPath,
  49. "-FilePath",
  50. configuration.path,
  51. ],
  52. {
  53. stdio: "inherit",
  54. env: process.env,
  55. },
  56. );
  57. if (result.error) {
  58. throw result.error;
  59. }
  60. if (result.status !== 0) {
  61. throw new Error(
  62. `[sign-windows-hook] vsigntool failed for ${configuration.path} with code ${result.status ?? "unknown"}`,
  63. );
  64. }
  65. }
  66. module.exports = sign;
  67. module.exports.sign = sign;
  68. module.exports.isWindowsPortableExecutable = isWindowsPortableExecutable;