Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Automate Windows release signing with a single PIN

Daniel18ce79b37266
diff --git a/docs/RELEASE-VERIFICATION.zh-CN.md b/docs/RELEASE-VERIFICATION.zh-CN.md
index e227426b41..7ce85b5fe9 100644
--- a/docs/RELEASE-VERIFICATION.zh-CN.md
+++ b/docs/RELEASE-VERIFICATION.zh-CN.md
@@ -108,7 +108,7 @@ WSL 同步安排在环境检查和签名证书检查之前。如果 SSH 需要
- 准备 Go、Node、pnpm、Windows 双架构编译器、gomobile、Android SDK/NDK、DevEco Studio 和 7-Zip;Appx 还需 `electron-windows-store`
- OCR 运行库归档缓存位于项目的 `.cache/ocr/`;手动下载时保留原文件名,不解压,脚本校验摘要后复用
- 停止正在运行的前端开发构建
-- 插好 YubiKey,签名时按系统提示输入 PIN
+- 插好 YubiKey,执行构建时隐藏输入一次签名 PIN
- 确认 Android、鸿蒙签名配置可用
- 桌面 `siyuan` 文件夹不要留有旧版本或同名安装包;分批构建时保留本次版本已验证的其他平台产物
@@ -130,6 +130,8 @@ python -X utf8 scripts/build-release.py --appx --execute
各平台按 Windows、Linux、Android、鸿蒙的顺序串行构建,中途失败会停止后续步骤。
+包含 Windows 时,先隐藏输入一次签名 PIN;预检验证通过后自动完成后续签名。仅查看计划或构建其他平台时不询问 PIN。WSL 的 SSH 认证仍在预检阶段完成,预检通过后再离开电脑。
+
补充:需要单独构建某个平台或排查构建问题时,可选择对应命令:
```powershell
@@ -302,6 +304,7 @@ python -X utf8 scripts/verify-release.py check D:/releases/siyuan --version 3.8.
- `--platforms` 接受逗号分隔的平台名称,可选 `windows`、`linux`、`android`、`harmony`;默认构建四个平台,Appx 需额外指定 `--appx`
- `--output` 可指定产物收集目录,默认桌面 `siyuan`;脚本不覆盖已有同名安装包
- `--records-dir` 可指定持久化记录根目录,默认主仓库同级 `release-records`;每次执行创建独立目录,保存日志和阶段进度,清理发布产物时保留
+- Windows 默认在预检前隐藏输入一次签名 PIN;自动执行环境可通过进程环境变量 `SIYUAN_SIGNING_PIN` 提供,脚本读取后移出父进程环境,不写入命令行参数、配置文件或发布记录;`--signing-ui` 可沿用系统 PIN 弹窗
- 脚本保留现有 Android 与鸿蒙签名配置,不读取或输出这些配置里的密码
- WSL 默认用户 `d`、仓库 `/home/d/88250/siyuan`,可通过 `--wsl-user`、`--wsl-repo`、`--wsl-distro` 调整;Linux 或鸿蒙构建预检时自动同步到 Windows 的确切提交,受检查的构建输入须一致,自动同步条件见步骤 2
- Android、鸿蒙仓库默认在思源仓库同级,可用 `--android-dir`、`--harmony-dir` 调整;构建工具路径可用 `--arm64-cc`、`--deveco` 调整;`--sevenzip` 仅传入完成后提示的手动校验命令,构建时不检查或调用该工具
@@ -320,7 +323,9 @@ python -X utf8 scripts/verify-release.py check D:/releases/siyuan --version 3.8.
### YubiKey PIN
-沿用 Windows 智能卡驱动和 Electron Builder 的 SignTool 签名链路,按系统提示输入 PIN。提示次数取决于驱动、密钥策略和签名会话,不能保证只有一次。脚本不存储 PIN、不模拟输入,也不改变 PIN 或触摸策略。
+默认通过 Windows 智能卡驱动和 Authenticode 接口自动签名,支持 CNG 的 RSA、ECDSA 签名密钥。启动时隐藏输入一次 PIN,预检先验证密钥可用,再进行耗时构建;PIN 仅在进程内存中暂存,经签名子进程的标准输入传递,不写入文件或日志。每个文件使用 SHA256 签名,并检查证书、签名和时间戳;仅设备通信中断自动重试一次,PIN 错误立即停止。
+
+自动执行时可由启动程序通过进程环境变量 `SIYUAN_SIGNING_PIN` 提供 PIN,无需把密码写进命令或脚本。仍需保持签名设备连接;脚本不改变 PIN 或触摸策略,需要触摸的密钥不能完全无人值守。若驱动不支持自动认证,可添加 `--signing-ui` 沿用系统弹窗。
默认按现有证书主题选择有效代码签名证书;多张证书时用 `--certificate-sha1` 指定 40 位公开指纹,它不是密码。SignTool 的 `/p` 是证书文件密码选项,不能当成通用 YubiKey PIN 参数。参见 [Yubico 驱动说明](https://www.yubico.com/support/download/smart-card-drivers-tools/) 和 [SignTool 文档](https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool)。
diff --git a/scripts/build-release.py b/scripts/build-release.py
index ef33284d30..0d5f8a7b7f 100644
--- a/scripts/build-release.py
+++ b/scripts/build-release.py
@@ -6,6 +6,7 @@ import codecs
from contextlib import contextmanager, nullcontext, redirect_stderr, redirect_stdout
from datetime import datetime
import importlib.util
+import getpass
import json
import os
from pathlib import Path
@@ -16,6 +17,7 @@ import subprocess
import sys
import tempfile
import time
+import warnings
import zipfile
@@ -179,6 +181,9 @@ def run(command, cwd, env=None, capture=False, interactive=False):
if any(re.search(r'[\r\n"&|<>^%!]', value) for value in command):
raise BuildError("批处理参数包含不支持的 shell 特殊字符")
invocation = subprocess.list2cmdline(command)
+ # Windows 批处理依赖此标识启用局部变量和延迟展开,自动启动环境可能未提供。
+ env = dict(os.environ if env is None else env)
+ env.setdefault("OS", "Windows_NT")
else:
invocation = command
if not capture:
@@ -259,6 +264,43 @@ def verify_signature(path, thumbprint):
powershell(script, {"SIYUAN_SIGNED_FILE": str(path), "SIYUAN_SIGNING_SHA1": thumbprint})
+def read_signing_pin(value=None):
+ if value is None:
+ try:
+ # 禁止 getpass 在没有可隐藏输入的终端时退回明文输入。
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", getpass.GetPassWarning)
+ value = getpass.getpass("Windows 签名 PIN(不回显):")
+ except (EOFError, getpass.GetPassWarning):
+ raise BuildError("无法隐藏输入签名 PIN,请从终端运行或通过 SIYUAN_SIGNING_PIN 提供") from None
+ if not value or any(character in value for character in ("\0", "\r", "\n")):
+ raise BuildError("签名 PIN 不能为空或包含换行、空字符")
+ return value
+
+
+def check_signing_pin(pin, thumbprint):
+ # 认证请求仅通过标准输入传递,不经命令行、配置文件或发布日志。
+ env = dict(os.environ)
+ for key in ("SIYUAN_SIGNING_PIN", "SIYUAN_RELEASE_SIGN_PIN", "PSModulePath"):
+ env.pop(key, None)
+ command = ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File",
+ str(ROOT / "scripts/release-sign-windows.ps1")]
+ request = json.dumps({"pin": pin, "thumbprint": thumbprint, "files": []}) + "\n"
+ for attempt in range(2):
+ try:
+ result = subprocess.run(command, cwd=ROOT, env=env, input=request, encoding="utf-8", errors="replace",
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, timeout=120,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
+ except (OSError, subprocess.TimeoutExpired):
+ raise BuildError("Windows 签名认证未完成,请检查签名设备和 Windows PowerShell") from None
+ if result.returncode == 0:
+ return
+ if result.returncode != 20 or attempt:
+ raise BuildError("Windows 签名认证失败,请检查 PIN、设备和证书;PIN 错误不会自动重试")
+ # 仅重试已识别的设备通信中断,不重试 PIN 错误。
+ time.sleep(1)
+
+
def copy_verified(source, destination, allowed_root):
source, destination, allowed_root = Path(source), Path(destination), Path(allowed_root).resolve()
if not destination.resolve().is_relative_to(allowed_root) or destination.resolve() == allowed_root:
@@ -355,6 +397,7 @@ class Builder:
self.artifacts = []
self.thumbprint = None
self.wsl_root = None
+ self.signing_pin = None
def wsl(self, command, directory=None, capture=False):
prefix = ["wsl.exe"]
@@ -397,7 +440,11 @@ class Builder:
source_preflight(self.args, self.version)
if "windows" in self.args.platforms:
self.thumbprint = certificate_thumbprint(self.args.certificate_subject, self.args.certificate_sha1)
- print(f"Windows 签名证书:{self.thumbprint};签名时请按系统提示输入 YubiKey PIN", flush=True)
+ if self.signing_pin is not None:
+ check_signing_pin(self.signing_pin, self.thumbprint)
+ print(f"Windows 签名证书:{self.thumbprint};PIN 已验证,后续自动签名", flush=True)
+ else:
+ print(f"Windows 签名证书:{self.thumbprint};签名时请按系统提示输入 YubiKey PIN", flush=True)
if {"linux", "harmony"} & set(self.args.platforms):
remote_head = self.wsl(["git", "rev-parse", "HEAD"], capture=True)
if local_head != remote_head:
@@ -464,11 +511,17 @@ class Builder:
self.check_kernel(kernel, arch)
copy_verified(ROOT / "app/elevator" / f"elevator-{arch}.exe", kernel.parent / "elevator.exe", self.work)
generated_config = self.work / f"windows-{arch}.json"
- run(["node", ROOT / "scripts/release-windows-config.cjs", ROOT / "app" / config,
- kernel.parent, output, self.thumbprint, generated_config], ROOT / "app")
+ config_command = ["node", ROOT / "scripts/release-windows-config.cjs", ROOT / "app" / config,
+ kernel.parent, output, self.thumbprint, generated_config]
+ if self.signing_pin is not None:
+ config_command.append(ROOT / "scripts/release-sign-windows.cjs")
+ run(config_command, ROOT / "app")
signing_env = dict(os.environ)
+ signing_env.setdefault("ELECTRON_MIRROR", "https://npmmirror.com/mirrors/electron/")
for key in ("CSC_LINK", "CSC_KEY_PASSWORD", "WIN_CSC_LINK", "WIN_CSC_KEY_PASSWORD"):
signing_env.pop(key, None)
+ if self.signing_pin is not None:
+ signing_env["SIYUAN_RELEASE_SIGN_PIN"] = self.signing_pin
run(["pnpm", "exec", "electron-builder", "--config", generated_config, "--win",
"--arm64" if arch == "arm64" else "--x64", "--publish=never"], ROOT / "app", signing_env)
suffix = "-arm64" if arch == "arm64" else ""
@@ -603,6 +656,7 @@ def parser():
help="持久化发布记录根目录,默认主仓库同级 release-records;每次执行创建独立子目录")
result.add_argument("--certificate-subject", default="Yunnan Liandi Technology Co., Ltd.", help="Windows 证书主题,可用指纹替代")
result.add_argument("--certificate-sha1", help="Windows 签名证书的 40 位公开指纹,不是密码")
+ result.add_argument("--signing-ui", action="store_true", help="Windows 签名沿用系统 PIN 弹窗,不使用自动签名")
result.add_argument("--arm64-cc", type=Path, default=Path("D:/Program Files/llvm-mingw-20240518-ucrt-x86_64/bin/aarch64-w64-mingw32-gcc.exe"))
result.add_argument("--wsl-distro", help="WSL 发行版名称,默认当前默认发行版")
result.add_argument("--wsl-user", default="d")
@@ -619,6 +673,8 @@ def main():
if hasattr(stream, "reconfigure"):
stream.reconfigure(encoding="utf-8")
args = parser().parse_args()
+ # 读取后立即移出父进程环境,避免后续无关构建命令继承输入 PIN。
+ signing_pin = os.environ.pop("SIYUAN_SIGNING_PIN", None)
args.platforms = list(dict.fromkeys(args.platforms.split(",")))
if not args.platforms or set(args.platforms) - set(PLATFORMS):
raise BuildError(f"平台只能是:{', '.join(PLATFORMS)}")
@@ -647,23 +703,29 @@ def main():
return 0
if os.name != "nt":
raise BuildError("此编排脚本需要在 Windows 上执行,Linux 和鸿蒙内核通过 WSL 构建")
+ signing_pin = read_signing_pin(signing_pin) if "windows" in args.platforms and not args.signing_ui else None
record = create_record(args, version)
- with record.session():
- print(f"版本:{version};平台:{', '.join(args.platforms)};收集目录:{args.output}")
- execute_build(args, version, record)
+ try:
+ with record.session():
+ print(f"版本:{version};平台:{', '.join(args.platforms)};收集目录:{args.output}")
+ execute_build(args, version, record, signing_pin)
+ finally:
+ signing_pin = None
return 0
-def execute_build(args, version, record):
+def execute_build(args, version, record, signing_pin=None):
with record.stage("preflight"):
with tempfile.TemporaryDirectory(prefix="siyuan-release-preflight-") as temporary:
probe = Builder(args, version, Path(temporary), record)
+ probe.signing_pin = signing_pin
probe.preflight()
work = Path(tempfile.mkdtemp(prefix=f"siyuan-release-{version}-{datetime.now():%Y%m%d}-"))
record.data["work_directory"] = str(work)
record.save()
builder = Builder(args, version, work, record)
builder.thumbprint, builder.wsl_root = probe.thumbprint, probe.wsl_root
+ builder.signing_pin = probe.signing_pin
print(f"本次构建目录:{work};失败时保留产物供检查", flush=True)
if set(args.platforms) & {"windows", "android", "harmony"}:
with record.stage("frontend"):
diff --git a/scripts/release-sign-windows.cjs b/scripts/release-sign-windows.cjs
new file mode 100644
index 0000000000..d1e7c2fdd1
--- /dev/null
+++ b/scripts/release-sign-windows.cjs
@@ -0,0 +1,50 @@
+const {spawn} = require("node:child_process");
+const path = require("node:path");
+
+const signingPin = process.env.SIYUAN_RELEASE_SIGN_PIN;
+delete process.env.SIYUAN_RELEASE_SIGN_PIN;
+
+// 智能卡逐个处理签名,前一项失败时停止后续认证。
+let queue = Promise.resolve();
+exports.default = function (options) {
+ queue = queue.then(() => sign(options));
+ return queue;
+};
+
+async function sign(options, retry = true) {
+ const thumbprint = options.options.signtoolOptions.certificateSha1;
+ if (!signingPin || options.hash !== "sha256" || !/^[0-9a-f]{40}$/i.test(thumbprint || "")) {
+ throw new Error("The hardware signing configuration is invalid");
+ }
+ await new Promise((resolve, reject) => {
+ const env = {...process.env};
+ delete env.PSModulePath;
+ const child = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File",
+ path.join(__dirname, "release-sign-windows.ps1")],
+ {windowsHide: true, env, stdio: ["pipe", "pipe", "pipe"]});
+ let output = "";
+ const timeout = setTimeout(() => {
+ child.kill();
+ reject(new Error("Hardware signing timed out"));
+ }, 120000);
+ child.stdout.on("data", data => { output += data.toString("utf8"); });
+ child.stderr.on("data", () => {});
+ child.stdin.on("error", () => {});
+ child.on("error", () => {
+ clearTimeout(timeout);
+ reject(new Error("Unable to start Windows hardware signing"));
+ });
+ child.on("close", code => {
+ clearTimeout(timeout);
+ if (code === 0) {
+ process.stdout.write(output);
+ resolve();
+ } else if (code === 20 && retry) {
+ setTimeout(() => { sign(options, false).then(resolve, reject); }, 1000);
+ } else {
+ reject(new Error("Hardware signing failed; check the PIN, token, certificate and timestamp connection"));
+ }
+ });
+ child.stdin.end(JSON.stringify({pin: signingPin, thumbprint, files: [options.path]}) + "\n");
+ });
+}
diff --git a/scripts/release-sign-windows.ps1 b/scripts/release-sign-windows.ps1
new file mode 100644
index 0000000000..63b47afcdf
--- /dev/null
+++ b/scripts/release-sign-windows.ps1
@@ -0,0 +1,99 @@
+$ErrorActionPreference = "Stop"
+[Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false)
+[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
+
+# 在同一进程内缓存智能卡 PIN,再调用 Authenticode 签名,避免跨进程重复认证。
+Add-Type -TypeDefinition @'
+using System;
+using System.Runtime.InteropServices;
+using System.Security.Cryptography;
+public static class SiYuanReleaseKey {
+ [DllImport("crypt32.dll", SetLastError=true)]
+ private static extern bool CryptAcquireCertificatePrivateKey(IntPtr certificate, uint flags, IntPtr reserved,
+ out IntPtr key, out uint spec, out bool callerFree);
+ [DllImport("ncrypt.dll", CharSet=CharSet.Unicode)]
+ private static extern int NCryptSetProperty(IntPtr key, string name, IntPtr value, uint length, uint flags);
+ [DllImport("ncrypt.dll")]
+ private static extern int NCryptSignHash(IntPtr key, IntPtr padding, byte[] hash, uint length,
+ byte[] signature, uint signatureLength, out uint resultLength, uint flags);
+ [DllImport("ncrypt.dll")]
+ private static extern int NCryptFreeObject(IntPtr key);
+ public static void Authenticate(IntPtr certificate, string pin, bool rsa) {
+ IntPtr key;
+ uint spec;
+ bool callerFree;
+ const uint acquireFlags = 0x00040000 | 0x00000040 | 0x00000001;
+ if (!CryptAcquireCertificatePrivateKey(certificate, acquireFlags, IntPtr.Zero, out key, out spec, out callerFree))
+ throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
+ IntPtr padding = IntPtr.Zero;
+ IntPtr algorithm = IntPtr.Zero;
+ try {
+ if (spec != 0xffffffff) throw new Exception("The signing key is not a CNG hardware key");
+ IntPtr value = Marshal.StringToHGlobalUni(pin);
+ try {
+ int status = NCryptSetProperty(key, "SmartCardPin", value, (uint)((pin.Length + 1) * 2), 0);
+ if (status != 0) throw new Exception("Set signing PIN failed: 0x" + status.ToString("x8"));
+ } finally { Marshal.ZeroFreeGlobalAllocUnicode(value); }
+ uint flags = 0x40;
+ if (rsa) {
+ algorithm = Marshal.StringToHGlobalUni("SHA256");
+ padding = Marshal.AllocHGlobal(IntPtr.Size);
+ Marshal.WriteIntPtr(padding, algorithm);
+ flags |= 2;
+ }
+ byte[] hash;
+ using (SHA256 sha = SHA256.Create()) {
+ hash = sha.ComputeHash(System.Text.Encoding.ASCII.GetBytes("SiYuan signing preflight"));
+ }
+ uint length;
+ int code = NCryptSignHash(key, padding, hash, (uint)hash.Length, null, 0, out length, flags);
+ if (code != 0) throw new Exception("Signature query failed: 0x" + code.ToString("x8"));
+ byte[] signature = new byte[length];
+ code = NCryptSignHash(key, padding, hash, (uint)hash.Length, signature, length, out length, flags);
+ if (code != 0) throw new Exception("Hardware authentication failed: 0x" + code.ToString("x8"));
+ } finally {
+ if (padding != IntPtr.Zero) Marshal.FreeHGlobal(padding);
+ if (algorithm != IntPtr.Zero) Marshal.FreeHGlobal(algorithm);
+ if (callerFree) NCryptFreeObject(key);
+ }
+ }
+}
+'@
+
+$payload = $null
+$certificate = $null
+try {
+ # PIN 仅通过标准输入传递,失败信息不包含请求内容。
+ $payload = [Console]::ReadLine() | ConvertFrom-Json
+ if ($payload.thumbprint -notmatch '^[0-9a-fA-F]{40}$' -or [string]::IsNullOrEmpty($payload.pin)) {
+ throw "Invalid signing request"
+ }
+ $certificate = Get-Item -LiteralPath ("Cert:\CurrentUser\My\" + $payload.thumbprint)
+ if (!$certificate.HasPrivateKey -or $certificate.NotAfter -le (Get-Date) -or
+ $certificate.NotBefore -ge (Get-Date) -or
+ !($certificate.EnhancedKeyUsageList.ObjectId -contains '1.3.6.1.5.5.7.3.3')) {
+ throw "The code signing certificate is unavailable"
+ }
+ $oid = $certificate.PublicKey.Oid.Value
+ if ($oid -notin @('1.2.840.113549.1.1.1', '1.2.840.10045.2.1')) {
+ throw "The signing key must use RSA or ECDSA"
+ }
+ [SiYuanReleaseKey]::Authenticate($certificate.Handle, $payload.pin, $oid -eq '1.2.840.113549.1.1.1')
+ $payload.pin = $null
+ foreach ($file in $payload.files) {
+ $signature = Set-AuthenticodeSignature -LiteralPath $file -Certificate $certificate -HashAlgorithm SHA256 -TimestampServer "http://timestamp.digicert.com"
+ if ($signature.Status -ne "Valid" -or $signature.SignerCertificate.Thumbprint -ne $certificate.Thumbprint -or
+ $null -eq $signature.TimeStamperCertificate) {
+ throw "Signature or timestamp verification failed"
+ }
+ Write-Output ("Signed and verified: " + $file)
+ }
+} catch {
+ [Console]::Error.WriteLine("Windows hardware signing failed; check the PIN, token, certificate and timestamp connection")
+ # 仅标识设备通信中断,PIN 错误不重试,避免消耗智能卡重试次数。
+ if ($_.Exception.ToString() -match '0x8010001f|0x80100068') { exit 20 }
+ exit 1
+} finally {
+ if ($null -ne $payload) { $payload.pin = $null }
+ if ($null -ne $certificate) { $certificate.Dispose() }
+}
diff --git a/scripts/release-windows-config.cjs b/scripts/release-windows-config.cjs
index 4bee5f20dd..f075dfb9e7 100644
--- a/scripts/release-windows-config.cjs
+++ b/scripts/release-windows-config.cjs
@@ -3,7 +3,7 @@ const path = require("node:path");
const {createRequire} = require("node:module");
async function main() {
- const [base, kernel, output, thumbprint, destination] = process.argv.slice(2);
+ const [base, kernel, output, thumbprint, destination, sign] = process.argv.slice(2);
if (!base || !kernel || !output || !/^[0-9a-f]{40}$/i.test(thumbprint || "") || !destination) {
throw new Error("Expected base config, kernel directory, output directory, certificate SHA1 and destination");
}
@@ -20,6 +20,10 @@ async function main() {
config.win.extraResources = [{from: path.resolve(kernel), to: "kernel"}];
config.win.signtoolOptions = {...config.win.signtoolOptions, certificateSha1: thumbprint};
delete config.win.signtoolOptions.certificateSubjectName;
+ if (sign) {
+ config.win.signtoolOptions.sign = path.resolve(sign);
+ config.win.signtoolOptions.signingHashAlgorithms = ["sha256"];
+ }
await validateConfiguration(config);
fs.writeFileSync(destination, JSON.stringify(config, null, 2) + "\n", {encoding: "utf8", flag: "wx"});
}
diff --git a/scripts/test_build_release.py b/scripts/test_build_release.py
index e0cefc2186..f70cd7c0b3 100644
--- a/scripts/test_build_release.py
+++ b/scripts/test_build_release.py
@@ -12,6 +12,7 @@ import sys
import tempfile
import time
import unittest
+import warnings
from unittest.mock import patch
import zipfile
@@ -47,6 +48,55 @@ class BuildTests(unittest.TestCase):
path.write_bytes(content)
return path
+ def test_signing_pin_uses_hidden_input_or_supplied_value(self):
+ with patch.object(build.getpass, "getpass", return_value="hidden-pin") as prompt:
+ self.assertEqual(build.read_signing_pin(), "hidden-pin")
+ self.assertEqual(build.read_signing_pin("environment-pin"), "environment-pin")
+ prompt.assert_called_once()
+
+ def test_signing_pin_rejects_echo_fallback_and_invalid_values(self):
+ def unsafe_prompt(*args):
+ warnings.warn("hidden input unavailable", build.getpass.GetPassWarning)
+
+ with patch.object(build.getpass, "getpass", side_effect=unsafe_prompt), self.assertRaises(build.BuildError):
+ build.read_signing_pin()
+ for value in ("", "pin\n", "pin\r", "pin\0"):
+ with self.subTest(value=value), self.assertRaises(build.BuildError):
+ build.read_signing_pin(value)
+
+ def test_signing_preflight_keeps_pin_out_of_arguments_and_environment(self):
+ result = subprocess.CompletedProcess([], 0, stdout="", stderr="")
+ with patch.dict(build.os.environ, {"SIYUAN_SIGNING_PIN": "secret", "PSModulePath": "foreign"}), \
+ patch.object(build.subprocess, "run", return_value=result) as run:
+ build.check_signing_pin("secret", "A" * 40)
+ command = run.call_args.args[0]
+ self.assertNotIn("secret", " ".join(command))
+ self.assertEqual(json.loads(run.call_args.kwargs["input"]),
+ {"pin": "secret", "thumbprint": "A" * 40, "files": []})
+ self.assertNotIn("SIYUAN_SIGNING_PIN", run.call_args.kwargs["env"])
+ self.assertNotIn("PSModulePath", run.call_args.kwargs["env"])
+
+ def test_signing_preflight_retries_only_device_communication(self):
+ for codes in ((20, 0), (20, 20), (1,)):
+ results = [subprocess.CompletedProcess([], code, stdout="secret", stderr="secret") for code in codes]
+ with self.subTest(codes=codes), patch.object(build.subprocess, "run", side_effect=results) as run, \
+ patch.object(build.time, "sleep"):
+ if codes[-1] == 0:
+ build.check_signing_pin("secret", "A" * 40)
+ else:
+ with self.assertRaises(build.BuildError) as error:
+ build.check_signing_pin("secret", "A" * 40)
+ self.assertNotIn("secret", str(error.exception))
+ self.assertEqual(run.call_count, len(codes))
+
+ @unittest.skipUnless(sys.platform == "win32", "需要 Windows 批处理")
+ def test_batch_restores_missing_windows_environment_marker(self):
+ batch = self.write(self.root / "environment.bat",
+ b'@echo off\r\nif "%OS%"=="Windows_NT" (echo Windows_NT) else (exit /b 7)\r\n')
+ with patch.dict(build.os.environ):
+ build.os.environ.pop("OS", None)
+ self.assertEqual(build.run([batch], self.root, capture=True), "Windows_NT")
+
def test_copy_rejects_destination_escape(self):
source = self.write(self.root / "input", b"new")
with self.assertRaises(build.BuildError):
@@ -176,7 +226,7 @@ class BuildTests(unittest.TestCase):
if command[:2] == ["go", "build"]:
self.write(command[command.index("-o") + 1])
if command[0] == "node":
- Path(command[-1]).write_text(json.dumps({
+ Path(command[6]).write_text(json.dumps({
"forceCodeSigning": True, "directories": {"output": command[4]},
"win": {"extraResources": [{"from": command[3], "to": "kernel"}],
"signtoolOptions": {"certificateSha1": command[5]}},
@@ -199,6 +249,34 @@ class BuildTests(unittest.TestCase):
self.assertEqual(signatures.call_count, 2)
self.assertFalse((root / "app/kernel").exists())
+ def test_windows_passes_pin_only_to_builder_and_references_public_signing_hook(self):
+ root = self.root / "repository"
+ self.write(root / "app/elevator/elevator-amd64.exe")
+ self.builder.thumbprint = "A" * 40
+ self.builder.signing_pin = "private-pin"
+ commands = []
+
+ def fake_run(command, cwd, env=None, capture=False):
+ command = [str(value) for value in command]
+ commands.append((command, env))
+ if command[0] == "node":
+ self.assertEqual(command[-1], str(root / "scripts/release-sign-windows.cjs"))
+ Path(command[6]).write_text(json.dumps({"win": {"signtoolOptions": {"sign": command[-1]}}}),
+ encoding="utf-8")
+ if command[:3] == ["pnpm", "exec", "electron-builder"]:
+ self.assertEqual(env["SIYUAN_RELEASE_SIGN_PIN"], "private-pin")
+ self.assertTrue(env["ELECTRON_MIRROR"])
+ else:
+ self.assertNotIn("SIYUAN_RELEASE_SIGN_PIN", env or {})
+ self.assertNotIn("private-pin", " ".join(command))
+ return ""
+
+ with patch.object(build, "ROOT", root), patch.object(build, "run", side_effect=fake_run), \
+ patch.object(build, "copy_verified"), patch.object(self.builder, "check_kernel"), \
+ patch.object(build, "verify_signature"), patch.object(self.builder, "collect"):
+ self.builder.windows_arch("amd64", "electron-builder.yml")
+ self.assertNotIn("private-pin", (self.builder.work / "windows-amd64.json").read_text(encoding="utf-8"))
+
@unittest.skipUnless(shutil.which("node") and (build.ROOT / "app/node_modules/electron-builder").exists(),
"需要已安装的 Electron Builder,仅加载配置,不执行构建")
def test_installed_builder_configuration_excludes_old_kernel(self):
@@ -214,6 +292,19 @@ class BuildTests(unittest.TestCase):
self.assertEqual(config["win"]["signtoolOptions"]["signingHashAlgorithms"], ["sha256"])
self.assertTrue(any(entry.get("to") == "stage" for entry in config["extraResources"]))
+ @unittest.skipUnless(shutil.which("node") and (build.ROOT / "app/node_modules/electron-builder").exists(),
+ "需要已安装的 Electron Builder")
+ def test_installed_builder_configuration_accepts_hardware_signing_hook(self):
+ destination = self.root / "hardware-windows.json"
+ hook = build.ROOT / "scripts/release-sign-windows.cjs"
+ with contextlib.redirect_stdout(io.StringIO()):
+ build.run(["node", build.ROOT / "scripts/release-windows-config.cjs",
+ build.ROOT / "app/electron-builder.yml", self.root / "kernel", self.root / "build",
+ "A" * 40, destination, hook], build.ROOT / "app", capture=True)
+ config = json.loads(destination.read_text(encoding="utf-8"))
+ self.assertEqual(config["win"]["signtoolOptions"]["sign"], str(hook))
+ self.assertEqual(config["win"]["signtoolOptions"]["signingHashAlgorithms"], ["sha256"])
+
def test_harmony_copies_each_architecture_before_next_build(self):
remote = self.root / "wsl"
self.builder.wsl_root = remote
@@ -460,6 +551,15 @@ class RecordTests(unittest.TestCase):
self.assertNotIn("private capture", content)
self.assertNotIn("private environment", content)
+ def test_signing_authentication_failure_does_not_record_pin_or_helper_output(self):
+ result = subprocess.CompletedProcess([], 1, stdout="private-pin", stderr="private-pin")
+ with contextlib.redirect_stdout(io.StringIO()), self.assertRaises(build.BuildError), \
+ patch.object(build.subprocess, "run", return_value=result):
+ with self.record.session(), self.record.stage("preflight"):
+ build.check_signing_pin("private-pin", "A" * 40)
+ for filename in ("build.log", "progress.json"):
+ self.assertNotIn("private-pin", (self.directory / filename).read_text(encoding="utf-8"))
+
def test_atomic_progress_write_preserves_previous_snapshot_on_failure(self):
self.record.save()
original = self.progress()
diff --git a/scripts/test_release_sign_windows.cjs b/scripts/test_release_sign_windows.cjs
new file mode 100644
index 0000000000..0f8916e160
--- /dev/null
+++ b/scripts/test_release_sign_windows.cjs
@@ -0,0 +1,74 @@
+const assert = require("node:assert/strict");
+const {EventEmitter} = require("node:events");
+const fs = require("node:fs");
+const path = require("node:path");
+const vm = require("node:vm");
+
+function load(codes = [0, 0]) {
+ const calls = [];
+ let active = 0;
+ let maximum = 0;
+ const env = {SIYUAN_RELEASE_SIGN_PIN: "test-secret", PSModulePath: "foreign-modules"};
+ const context = {
+ exports: {}, __dirname, setTimeout, clearTimeout,
+ process: {env, stdout: {write() {}}},
+ require(name) {
+ if (name === "node:path") { return path; }
+ assert.equal(name, "node:child_process");
+ return {spawn(executable, args, options) {
+ assert.equal(executable, "powershell.exe");
+ assert.ok(args.includes("-NonInteractive"));
+ assert.equal(options.env.SIYUAN_RELEASE_SIGN_PIN, undefined);
+ assert.equal(options.env.PSModulePath, undefined);
+ assert.ok(!args.join(" ").includes("test-secret"));
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.stdin = new EventEmitter();
+ child.stdin.end = value => {
+ calls.push(JSON.parse(value));
+ active += 1;
+ maximum = Math.max(maximum, active);
+ setImmediate(() => {
+ active -= 1;
+ child.stderr.emit("data", Buffer.from("test-secret"));
+ child.emit("close", codes.shift());
+ });
+ };
+ return child;
+ }};
+ },
+ };
+ vm.runInNewContext(fs.readFileSync(path.join(__dirname, "release-sign-windows.cjs"), "utf8"), context);
+ assert.equal(env.SIYUAN_RELEASE_SIGN_PIN, undefined);
+ return {sign: context.exports.default, calls, maximum: () => maximum};
+}
+
+const options = name => ({path: name, hash: "sha256", options: {signtoolOptions: {certificateSha1: "A".repeat(40)}}});
+
+async function main() {
+ const normal = load();
+ await Promise.all([normal.sign(options("first.exe")), normal.sign(options("second.exe"))]);
+ assert.equal(normal.maximum(), 1);
+ assert.deepEqual(normal.calls.map(call => call.files[0]), ["first.exe", "second.exe"]);
+ assert.equal(normal.calls[0].pin, "test-secret");
+ const failed = load([1]);
+ const errors = await Promise.allSettled([failed.sign(options("first.exe")), failed.sign(options("second.exe"))]);
+ assert.equal(failed.calls.length, 1);
+ assert.ok(errors.every(result => result.status === "rejected" && !result.reason.message.includes("test-secret")));
+ const retry = load([20, 0]);
+ await retry.sign(options("retry.exe"));
+ assert.equal(retry.calls.length, 2);
+ const exhausted = load([20, 20]);
+ await assert.rejects(exhausted.sign(options("twice.exe")), /Hardware signing failed/);
+ assert.equal(exhausted.calls.length, 2);
+ const invalid = load();
+ await assert.rejects(invalid.sign({...options("legacy.exe"), hash: "sha1"}), /configuration is invalid/);
+ assert.equal(invalid.calls.length, 0);
+ console.log("Windows signing hook tests passed");
+}
+
+main().catch(error => {
+ console.error(error);
+ process.exitCode = 1;
+});