powershell-command.mjs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import childProcess from "node:child_process";
  2. const POWERSHELL_COMMON_ARGS = ["-NoLogo", "-NoProfile", "-NonInteractive"];
  3. const WINDOWS_POWERSHELL_SECURITY_BOOTSTRAP = [
  4. // 首次模块导入会向 stderr 写进度 CLIXML;只静默进度,实际错误仍须拒绝更新。
  5. "$ProgressPreference='SilentlyContinue';",
  6. "$ErrorActionPreference='Stop';",
  7. "try{",
  8. "$zcodeSecurityModule=[IO.Path]::Combine($PSHOME,'Modules','Microsoft.PowerShell.Security','Microsoft.PowerShell.Security.psd1');",
  9. "Import-Module -Name $zcodeSecurityModule -Force -ErrorAction Stop;",
  10. "}catch{",
  11. "[Console]::Error.WriteLine(('Windows PowerShell Security module load failed: {0}' -f $_.Exception.Message));",
  12. "exit 26;",
  13. "};",
  14. ].join("");
  15. function encodeUtf8Value(value) {
  16. return Buffer.from(value, "utf8").toString("base64");
  17. }
  18. export function createEncodedPowerShellArgs(script, values = []) {
  19. // Windows PowerShell 5.1 会把普通 `-Command` 后续 argv 拼回命令文本,
  20. // 不会把它们注入 `$args`。动态值先单独编码,再放进 `-EncodedCommand`,同时避免
  21. // Program Files 空格、引号或分号被 PowerShell 二次解析成脚本内容。
  22. const valueBindings = values
  23. .map(
  24. (value, index) =>
  25. `$zcodeArg${index}=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodeUtf8Value(value)}'));`,
  26. )
  27. .join("");
  28. const encodedCommand = Buffer.from(`${valueBindings}${script}`, "utf16le").toString("base64");
  29. return [...POWERSHELL_COMMON_ARGS, "-EncodedCommand", encodedCommand];
  30. }
  31. export function createWindowsPowerShellSecurityArgs(script, values = []) {
  32. // 由 pwsh 启动的 Node 会继承 PowerShell 7 的 PSModulePath,随后再启动
  33. // Windows PowerShell 5.1 时可能错误发现不兼容的 Security 模块。直接从当前
  34. // powershell.exe 的 PSHOME 加载系统模块,避免把外部环境变量当作模块信任根。
  35. return createEncodedPowerShellArgs(`${WINDOWS_POWERSHELL_SECURITY_BOOTSTRAP}${script}`, values);
  36. }
  37. export async function readWindowsAuthenticodeSignature(filePath) {
  38. const script = [
  39. "[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false);",
  40. "$signature=Get-AuthenticodeSignature -LiteralPath $zcodeArg0;",
  41. "@{status=[int]$signature.Status;subject=$signature.SignerCertificate.Subject}|ConvertTo-Json -Compress;",
  42. ].join("");
  43. const stdout = await new Promise((resolve, reject) => {
  44. childProcess.execFile(
  45. "powershell.exe",
  46. createWindowsPowerShellSecurityArgs(script, [filePath]),
  47. { encoding: "utf8", timeout: 30_000, windowsHide: true },
  48. (error, output, stderr) => {
  49. if (error || stderr) reject(error ?? new Error(stderr));
  50. else resolve(output);
  51. },
  52. );
  53. });
  54. return JSON.parse(stdout.replace(/^\uFEFF/u, "").trim());
  55. }
  56. export async function verifyWindowsAuthenticodeSignature(filePath) {
  57. const signature = await readWindowsAuthenticodeSignature(filePath);
  58. // 官方 HTTPS 清单与文件哈希决定发布授权;这里只检查 Windows 签名有效性。
  59. // 不固定证书 DN,避免换证后长期未升级的客户端只能依赖过渡版本。
  60. if (
  61. signature.status !== 0 ||
  62. typeof signature.subject !== "string" ||
  63. !signature.subject.trim()
  64. ) {
  65. return "Windows update requires a valid Authenticode signature";
  66. }
  67. return null;
  68. }