An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Add release build and package verification scripts https://github.com/siyuan-note/siyuan/issues/19608
Danielbea7d5706bec
diff --git a/docs/RELEASE-VERIFICATION.zh-CN.md b/docs/RELEASE-VERIFICATION.zh-CN.mdnew file mode 100644index 0000000000..79fd412e75--- /dev/null+++ b/docs/RELEASE-VERIFICATION.zh-CN.md@@ -0,0 +1,100 @@+# 发布构建与安装包校验++需要 Python 3.11 或更新版本。安装包检查不需要更改打包流程,也不需要从其他机器带回基准文件。EXE、DMG、AppImage、DEB、RPM 等格式还需要 7-Zip,可用 `--sevenzip` 指定路径。++## 直接检查安装包++把安装包放入桌面 `siyuan` 文件夹,在仓库根目录执行:++```text+python -X utf8 scripts/verify-release.py check+```++默认从包名推断发布版本。版本混杂、包名不含版本,或希望明确检查目标时指定版本:++```text+python -X utf8 scripts/verify-release.py check --version 3.8.4+python -X utf8 scripts/verify-release.py check D:/releases/siyuan --version 3.8.4 --report D:/releases/verification.json+```++报告路径必须是尚不存在的 `.json` 文件。退出码 `0` 表示所有包通过当前检查,`1` 表示失败或无法验证。检查不会运行安装器、内核或包内 JavaScript,不修改安装包;每个包使用独立临时目录,检查后清理。++### 检查内容++- 从 PE、ELF 或 Mach-O 内核中的完整 `SiYuan v… (pdfcpu ` 标识读取版本,该标识由 `kernel/model/export.go` 的 `util.Ver` 编译生成;同时交叉检查可识别的桌面 CLI 完整版本标识,不把任意版本子串当成通过依据+- 检查内核版本与发布版本一致,并识别可判定的内核架构和格式错误+- 从 HTML 实际引用的 JavaScript 读取 `Constants.SIYUAN_VERSION`,检查前端与内核一致,不使用未被入口引用的新文件掩盖旧入口+- 检查 HTML、CSS 的可解析本地资源引用,以及当前 webpack 的数字分块哈希映射,发现缺失脚本、样式、字体或动态分块+- 检查导出前端版本、语言 JSON、用户指南和正式版当前更新日志;桌面包额外检查 `resources/app/package.json` 版本+- 展开 NSIS 内层压缩包、移动端 `app.zip`、AAB、HAP、APP 和 Linux 安装包载荷+- macOS 不依赖本机存在对应构建产物;7-Zip 无法完整提取时明确失败+- IPA 尝试从主程序识别静态链接内核;加密、缺少标识或无法唯一确定版本时明确失败++已用真实 Windows、Android 和鸿蒙包验证解包及版本检查。Linux、macOS 和 iOS 尚未完成真实安装包验证。++### 检查边界++仅凭安装包不能证明“同一版本号多次构建中,这是最后一次构建”,也不能证明所有资源与当前源代码逐字节一致。脚本能发现旧版本内核、旧版本前端和可解析引用缺失。没有统一发布标识的图标、第三方库版本,以及任意运行时拼接的 URL,不能全部自动判定。++未知文件或目录、空目录、解包失败和无法识别版本均不算通过。`checksum.exe`、`SHA256SUMS.txt`、`.blockmap`、YAML 更新元数据及可选基准 JSON 不作为安装包处理。独立检查脚本目前不验证校验和清单、签名、证书或原生外壳功能,也不推断此次应发布哪些平台。++## 自动构建++在 Windows 上先查看四个平台的计划,再执行:++```text+python -X utf8 scripts/build-release.py+python -X utf8 scripts/build-release.py --execute+```++可分批选择平台,Windows Store 包通过 `--appx` 额外启用:++```text+python -X utf8 scripts/build-release.py --platforms windows --appx --execute+python -X utf8 scripts/build-release.py --platforms linux,android,harmony --execute+```++不传 `--execute` 只显示计划,不构建、不修改文件。完整流水线尚未实际运行,回归测试使用模拟构建产物;首次使用应按平台分批执行,确认本机工具链和签名环境。++### 执行前准备++- 按原流程完成版本号、更新日志和数据库版本准备;脚本检查内核 `Ver`、`Mode`、Android、鸿蒙版本,以及启用 Appx 时的清单版本,不自动修改版本号或 `versionCode`+- 停止前端开发构建再执行正式构建,脚本会调用生产构建命令+- 准备 Go、Node、pnpm、Windows 双架构编译器、gomobile、Android SDK/NDK、DevEco Studio 和 7-Zip;Appx 还需 `electron-windows-store`+- 插好 YubiKey,保留现有 Android 与鸿蒙签名配置;脚本不读取或输出这些配置里的密码+- WSL 默认用户 `d`、仓库 `/home/d/88250/siyuan`,可通过 `--wsl-user`、`--wsl-repo`、`--wsl-distro` 调整;Windows 与 WSL 必须处于同一提交,受检查的构建输入须一致+- Android、鸿蒙仓库默认在思源仓库同级,可用 `--android-dir`、`--harmony-dir` 调整;工具路径可用 `--arm64-cc`、`--deveco`、`--sevenzip` 调整++### 流程++- 本地前端生产构建一次,Linux 前端在 WSL 中构建+- Windows 在全新目录构建两个架构内核,生成临时 Electron Builder 配置启用证书签名,不修改仓库 YAML,不复用开发内核目录;默认生成两个 NSIS 包并检查 Authenticode 签名+- Linux 调用现有 `scripts/linux-build.sh --target=all`,收集双架构 TAR、AppImage、DEB、RPM 共八个包+- Android 在本次临时目录生成新 AAR,确认内核版本和架构后复制到工程;生成并复制新 `app.zip`,再运行 `gradlew clean buildReleaseTask` 生成四个渠道包;官方版收集为 `siyuan-版本号.apk`(例如 `siyuan-3.8.4.apk`),不带 `official` 或 `release` 后缀,其他渠道保持原文件名+- 鸿蒙先构建并复制 ARM64 内核,再构建并复制 x86_64 内核,避免同名 `libkernel.so` 被覆盖后拷错;使用同一份新 `app.zip`,通过 Hvigor release 模式生成 APP 和已签名 HAP+- 每条命令失败立即停止,产物必须是本次生成,复制时再次核对摘要+- 新安装包全部验证通过后才收集到桌面 `siyuan`,不覆盖同名包;分批构建会检查目录中已有的其他包,并更新覆盖所有包的 `SHA256SUMS.txt`+- 构建目录保留在系统临时目录,控制台打印实际路径,失败后可检查并取回产物;不会自动提交、推送、打标签、上传或发布公告++### YubiKey PIN++沿用 Windows 智能卡驱动和 Electron Builder 的 SignTool 签名链路,按系统提示输入 PIN。提示次数取决于驱动、密钥策略和签名会话,不能保证只有一次。脚本不存储 PIN、不模拟输入,也不改变 PIN 或触摸策略。++默认按现有证书主题选择有效代码签名证书;多张证书时用 `--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)。++## 可选的完整摘要基准++通常无需使用。如果将来要比较同版本号的字节差异,可以从可信构建产物生成基准,使用 `check --baseline` 显式启用。不能从待验包反向生成基准。++```text+python -X utf8 scripts/verify-release.py baseline --version 3.8.4 --target android-arm64 --kernel kernel/kernel.aar --resources app --output android-arm64.release-baseline.json+python -X utf8 scripts/verify-release.py check --version 3.8.4 --baseline android-arm64.release-baseline.json+```++资源目录必须对应实际打包的集合。桌面包筛选外观文件并裁剪更新日志,不能直接比较未筛选的 `app/`;macOS 签名也可能改变内核摘要。++## 回归测试++```text+python -X utf8 -m unittest discover -s scripts -p "test_*release.py"+```diff --git a/scripts/build-release.py b/scripts/build-release.pynew file mode 100644index 0000000000..2ab451d051--- /dev/null+++ b/scripts/build-release.py@@ -0,0 +1,459 @@+#!/usr/bin/env python3+"""在 Windows 上编排 Windows、WSL Linux、Android 和鸿蒙发布构建。默认仅显示计划。"""++import argparse+from datetime import datetime+import importlib.util+import json+import os+from pathlib import Path+import re+import shlex+import shutil+import subprocess+import sys+import tempfile+import time+import zipfile+++ROOT = Path(__file__).resolve().parents[1]+SPEC = importlib.util.spec_from_file_location("verify_release", Path(__file__).with_name("verify-release.py"))+VERIFY = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(VERIFY)+PLATFORMS = ("windows", "linux", "android", "harmony")+++class BuildError(Exception):+ pass+++def run(command, cwd, env=None, capture=False):+ command = [str(value) for value in command]+ executable = shutil.which(command[0]) or command[0]+ command[0] = executable+ shell = os.name == "nt" and Path(executable).suffix.lower() in {".bat", ".cmd"}+ if shell:+ # 批处理由 cmd 解释,拒绝会被解释为额外命令或变量展开的参数。+ if any(re.search(r'[\r\n"&|<>^%!]', value) for value in command):+ raise BuildError("批处理参数包含不支持的 shell 特殊字符")+ invocation = subprocess.list2cmdline(command)+ else:+ invocation = command+ if not capture:+ print(f"[{cwd}] {subprocess.list2cmdline(command)}", flush=True)+ result = subprocess.run(invocation, cwd=cwd, env=env, shell=shell, check=False,+ stdout=subprocess.PIPE if capture else None,+ stderr=subprocess.PIPE if capture else None,+ encoding="utf-8", errors="replace")+ if result.returncode:+ detail = (result.stderr or "").strip() if capture else "请查看上方输出"+ raise BuildError(f"命令失败({result.returncode}):{command[0]};{detail}")+ return (result.stdout or "").strip() if capture else ""+++def powershell(script, values=None):+ env = dict(os.environ, **(values or {}))+ executable = shutil.which("pwsh") or "powershell.exe"+ # 避免从另一版本 PowerShell 继承模块搜索路径而加载不兼容的系统模块。+ env.pop("PSModulePath", None)+ return run([executable, "-NoProfile", "-NonInteractive", "-Command", script], ROOT, env, capture=True)+++def certificate_thumbprint(subject, thumbprint=None):+ # 只枚举公开证书信息,不读取私钥,也不尝试验证 PIN。+ script = "$ErrorActionPreference='Stop'; [Console]::OutputEncoding=[Text.Encoding]::UTF8; " \+ "Import-Module Microsoft.PowerShell.Security; " \+ "$items=@(Get-ChildItem -LiteralPath Cert:\\CurrentUser\\My | " \+ "Where-Object { $_.HasPrivateKey -and $_.NotAfter -gt (Get-Date) -and " \+ "$_.NotBefore -lt (Get-Date) -and " \+ "($_.EnhancedKeyUsageList.ObjectId -contains '1.3.6.1.5.5.7.3.3') }); " \+ "$items | Select-Object Subject,Thumbprint | ConvertTo-Json -Compress"+ raw = powershell(script).lstrip("\ufeff")+ values = json.loads(raw) if raw else []+ if isinstance(values, dict):+ values = [values]+ matches = [value for value in values if+ (value["Thumbprint"].upper() == thumbprint.upper() if thumbprint else subject in value["Subject"])]+ if len(matches) != 1:+ raise BuildError("无法唯一选择有效代码签名证书,请插好 YubiKey,并用 --certificate-sha1 指定证书指纹")+ return matches[0]["Thumbprint"]+++def verify_signature(path, thumbprint):+ script = "$ErrorActionPreference='Stop'; " \+ "$s=Get-AuthenticodeSignature -LiteralPath $env:SIYUAN_SIGNED_FILE; " \+ "if ($s.Status -ne 'Valid' -or $s.SignerCertificate.Thumbprint -ne $env:SIYUAN_SIGNING_SHA1) " \+ "{ throw ('Signature check failed: '+$s.Status) }"+ powershell(script, {"SIYUAN_SIGNED_FILE": str(path), "SIYUAN_SIGNING_SHA1": thumbprint})+++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:+ raise BuildError(f"复制目标超出指定目录:{destination}")+ if not source.is_file() or source.stat().st_size == 0:+ raise BuildError(f"构建产物不存在或为空:{source}")+ destination.parent.mkdir(parents=True, exist_ok=True)+ with tempfile.NamedTemporaryFile(dir=destination.parent, prefix=".siyuan-copy-", delete=False) as stream:+ temporary = Path(stream.name)+ try:+ shutil.copyfile(source, temporary)+ if VERIFY.digest(source) != VERIFY.digest(temporary):+ raise BuildError(f"复制摘要不匹配:{source}")+ os.replace(temporary, destination)+ finally:+ temporary.unlink(missing_ok=True)+++def check_version(text, expression, expected, label):+ matches = re.findall(expression, text, re.M)+ if matches != [expected]:+ raise BuildError(f"{label} 版本不匹配:{matches},预期 {expected};请先完成发布版本准备")+++def source_preflight(args, version):+ working = (ROOT / "kernel/util/working.go").read_text(encoding="utf-8")+ check_version(working, r'^const Ver = "([^"]+)"', version, "内核")+ if not re.search(r'^var Mode = "prod"', working, re.M):+ raise BuildError("内核 Mode 必须为 prod")+ if "-" not in version and not (ROOT / "app/changelogs" / f"v{version}").is_dir():+ raise BuildError(f"缺少 v{version} 更新日志")+ if "android" in args.platforms:+ check_version((args.android_dir / "build.gradle").read_text(encoding="utf-8"),+ r'^\s*siyuanVersionName\s*=\s*"([^"]+)"', version, "Android")+ for relative in ("gradlew.bat", "signings.gradle", "buildRelease.gradle"):+ if not (args.android_dir / relative).is_file():+ raise BuildError(f"Android 工程缺少 {relative}")+ if "harmony" in args.platforms:+ check_version((args.harmony_dir / "AppScope/app.json5").read_text(encoding="utf-8"),+ r'"versionName"\s*:\s*"([^"]+)"', version, "鸿蒙")+ for relative in ("tools/hvigor/bin/hvigorw.js", "tools/node/node.exe", "tools/ohpm/bin/ohpm.bat"):+ if not (args.deveco / relative).is_file():+ raise BuildError(f"DevEco Studio 缺少 {relative},请指定 --deveco")+ if "windows" in args.platforms and not args.arm64_cc.is_file():+ raise BuildError("找不到 Windows ARM64 交叉编译器,请指定 --arm64-cc")+ if args.appx and "windows" in args.platforms:+ for filename in ("AppxManifest.xml", "AppxManifest-arm64.xml"):+ check_version((ROOT / "app/appx" / filename).read_text(encoding="utf-8"),+ r'\bVersion="([^"]+)"', version.split("-")[0] + ".0", filename)+ if not VERIFY.find_7z(args.sevenzip):+ raise BuildError("最终安装包验证需要 7-Zip,请安装或指定 --sevenzip")+ commands = {"git"}+ if set(args.platforms) & {"windows", "android", "harmony"}:+ commands.update(("node", "pnpm"))+ if set(args.platforms) & {"windows", "android"}:+ commands.add("go")+ if "android" in args.platforms:+ commands.add("gomobile")+ if set(args.platforms) & {"linux", "harmony"}:+ commands.add("wsl.exe")+ if args.appx and "windows" in args.platforms:+ commands.add("electron-windows-store")+ for command in sorted(commands):+ if not shutil.which(command):+ raise BuildError(f"找不到构建工具:{command}")+++def create_mobile_assets(destination, version):+ destination.parent.mkdir(parents=True, exist_ok=True)+ with zipfile.ZipFile(destination, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:+ for group in VERIFY.GROUPS:+ folder = ROOT / "app" / group+ if group == "changelogs":+ if "-" in version:+ continue+ folder = folder / f"v{version}"+ if not folder.is_dir():+ raise BuildError(f"资源目录不存在:{folder}")+ for path in sorted(folder.rglob("*")):+ relative = path.relative_to(ROOT / "app")+ if path.is_symlink() or not path.is_file() or any(+ part in {".git", ".idea", ".gitignore", ".DS_Store"} for part in relative.parts):+ continue+ archive.write(path, relative.as_posix())+ for filename in ("LICENSE", "THIRD_PARTY_NOTICES.md"):+ archive.write(ROOT / filename, filename)+++class Builder:+ def __init__(self, args, version, work):+ self.args, self.version, self.work = args, version, work+ self.artifacts = []+ self.thumbprint = None+ self.wsl_root = None++ def wsl(self, command, directory=None, capture=False):+ prefix = ["wsl.exe"]+ if self.args.wsl_distro:+ prefix += ["--distribution", self.args.wsl_distro]+ prefix += ["--user", self.args.wsl_user, "--cd", directory or self.args.wsl_repo,+ "--exec", "bash", "-lc", "exec " + shlex.join([str(item) for item in command])]+ return run(prefix, ROOT, capture=capture)++ def preflight(self):+ 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 {"linux", "harmony"} & set(self.args.platforms):+ local_head = run(["git", "rev-parse", "HEAD"], ROOT, capture=True)+ remote_head = self.wsl(["git", "rev-parse", "HEAD"], capture=True)+ if local_head != remote_head:+ raise BuildError("WSL 与 Windows 仓库提交不同;请先同步到同一次发布提交")+ # 只比较构建输入,Windows 平台检出时的换行差异不应改变比较结果。+ for repo_path in ("kernel", "app", "scripts"):+ local_diff = run(["git", "diff", "HEAD", "--", repo_path], ROOT, capture=True)+ remote_diff = self.wsl(["git", "diff", "HEAD", "--", repo_path], capture=True)+ if local_diff.replace("\r\n", "\n") != remote_diff.replace("\r\n", "\n"):+ raise BuildError(f"WSL 与 Windows 的未提交构建输入不同:{repo_path}")+ command = ["git", "ls-files", "--others", "--exclude-standard", "--", "kernel", "app"]+ if run(command, ROOT, capture=True) or self.wsl(command, capture=True):+ raise BuildError("Windows 或 WSL 存在未跟踪的内核/前端文件,请先纳入同一次发布提交")+ self.wsl_root = Path(self.wsl(["wslpath", "-w", self.args.wsl_repo], capture=True))+ check_version((self.wsl_root / "kernel/util/working.go").read_text(encoding="utf-8"),+ r'^const Ver = "([^"]+)"', self.version, "WSL 内核")++ def build_ui(self):+ run(["pnpm", "install", "--frozen-lockfile"], ROOT / "app")+ run(["pnpm", "run", "install:electron"], ROOT / "app")+ run(["pnpm", "run", "build"], ROOT / "app")++ def collect(self, paths, label, started, names=None):+ paths = sorted(paths)+ if not paths:+ raise BuildError(f"{label} 没有产出安装包")+ for path in paths:+ if not path.is_file() or path.stat().st_size == 0 or path.stat().st_mtime < started - 2:+ raise BuildError(f"{label} 产物不是本次构建生成的有效文件:{path}")+ name = (names or {}).get(path.name, path.name)+ target = self.work / "packages" / name+ if target.exists():+ raise BuildError(f"安装包文件名重复:{name}")+ copy_verified(path, target, self.work)+ self.artifacts.append(target)++ def windows(self):+ run(["go", "install", "github.com/josephspurrier/goversioninfo/cmd/goversioninfo@latest"], ROOT / "kernel")+ go_bin = run(["go", "env", "GOBIN"], ROOT, capture=True)+ if not go_bin:+ go_bin = str(Path(run(["go", "env", "GOPATH"], ROOT, capture=True).split(os.pathsep)[0]) / "bin")+ run([Path(go_bin) / "goversioninfo.exe", "-platform-specific=true", "-icon=resource/icon.ico",+ "-manifest=resource/goversioninfo.exe.manifest"], ROOT / "kernel")+ output = self.work / "windows"+ for arch, config in (("amd64", "electron-builder.yml"), ("arm64", "electron-builder-arm64.yml")):+ started = time.time()+ env = dict(os.environ, GOOS="windows", GOARCH=arch, CGO_ENABLED="1")+ if arch == "arm64":+ env["CC"] = '"' + str(self.args.arm64_cc) + '"'+ kernel = self.work / "kernels" / arch / "SiYuan-Kernel.exe"+ kernel.parent.mkdir(parents=True, exist_ok=True)+ run(["go", "build", "-tags", "fts5 sqlcipher", "-ldflags=-s -w", "-o", kernel, "."], ROOT / "kernel", env)+ 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")+ signing_env = dict(os.environ)+ for key in ("CSC_LINK", "CSC_KEY_PASSWORD", "WIN_CSC_LINK", "WIN_CSC_KEY_PASSWORD"):+ signing_env.pop(key, None)+ 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 ""+ installer = output / f"siyuan-{self.version}-win{suffix}.exe"+ verify_signature(installer, self.thumbprint)+ self.collect([installer], "Windows", started)+ if self.args.appx:+ unpacked = output / ("win-arm64-unpacked" if arch == "arm64" else "win-unpacked")+ (unpacked / "resources/ms-store").touch()+ appx_output = self.work / "appx" / arch+ appx_output.mkdir(parents=True)+ run(["electron-windows-store", "--input-directory", unpacked, "--output-directory", appx_output,+ "--package-version", self.version.split("-")[0] + ".0", "--package-name", "SiYuan" + suffix,+ "--manifest", ROOT / "app/appx" / ("AppxManifest-arm64.xml" if arch == "arm64" else "AppxManifest.xml"),+ "--assets", ROOT / "app/appx/assets", "--make-pri", "true"], ROOT)+ self.collect(appx_output.glob("*.appx"), "Windows Appx", started)++ def linux(self):+ started = time.time()+ self.wsl(["bash", "scripts/linux-build.sh", "--target=all"])+ folder = self.wsl_root / "app/build"+ expected = [folder / f"siyuan-{self.version}-linux{arch}.{extension}"+ for arch in ("", "-arm64") for extension in ("tar.gz", "AppImage", "deb", "rpm")]+ self.collect(expected, "Linux", started)++ def check_kernel(self, path, architecture):+ info = VERIFY.kernel_info(path)+ if info["version"] != self.version or info["architecture"] != architecture:+ raise BuildError(f"新构建内核的版本或架构不匹配:{path},{info['version']},{info['architecture']}")++ def android(self, assets):+ env = dict(os.environ)+ for key in ("GOOS", "GOARCH", "CC", "CXX"):+ env.pop(key, None)+ env["JAVA_TOOL_OPTIONS"] = (env.get("JAVA_TOOL_OPTIONS", "") + " -Dfile.encoding=UTF-8").strip()+ env["CGO_ENABLED"] = "1"+ sdk = env.get("ANDROID_HOME") or env.get("ANDROID_SDK_ROOT")+ properties = self.args.android_dir / "local.properties"+ if not sdk and properties.is_file():+ match = re.search(r"^sdk.dir=(.+)$", properties.read_text(encoding="utf-8"), re.M)+ if match:+ sdk = match[1].strip().replace("\\:", ":").replace("\\\\", "\\")+ if not sdk or not Path(sdk).is_dir():+ raise BuildError("找不到 Android SDK,请设置 ANDROID_HOME 或 Android 工程的 local.properties")+ env["ANDROID_HOME"] = sdk+ if not env.get("ANDROID_NDK_HOME"):+ ndks = [path for path in (Path(sdk) / "ndk").glob("*") if path.is_dir() and re.fullmatch(r"[0-9.]+", path.name)]+ if not ndks:+ raise BuildError("找不到 Android NDK,请设置 ANDROID_NDK_HOME")+ env["ANDROID_NDK_HOME"] = str(max(ndks, key=lambda path: tuple(int(v) for v in path.name.split("."))))+ aar = self.work / "android/kernel.aar"+ aar.parent.mkdir(parents=True, exist_ok=True)+ run(["gomobile", "bind", "-tags", "fts5 sqlcipher", "-ldflags=-s -w", "-v", "-o", aar,+ "-target=android/arm64", "-androidapi", "26", "./mobile/"], ROOT / "kernel", env)+ with tempfile.TemporaryDirectory(prefix="siyuan-aar-check-") as temporary:+ layers = VERIFY.Unpacker(Path(temporary)).layers(aar)+ kernels = VERIFY.kernel_files(layers)+ if len(kernels) != 1:+ raise BuildError("Android AAR 应包含一个 ARM64 内核")+ self.check_kernel(kernels[0], "arm64")+ copy_verified(aar, self.args.android_dir / "app/libs/kernel.aar", self.args.android_dir)+ copy_verified(assets, self.args.android_dir / "app/src/main/assets/app.zip", self.args.android_dir)+ started = time.time()+ run([self.args.android_dir / "gradlew.bat", "clean", "buildReleaseTask", "--no-daemon"], self.args.android_dir, env)+ folder = self.args.android_dir / "app/build-release" / f"siyuan-{self.version}-all"+ packages = [path for path in folder.glob("*") if path.suffix in {".apk", ".aab"}]+ if len(packages) != 4:+ raise BuildError(f"Android 应产出四个渠道包,实际 {len(packages)} 个:{folder}")+ official_name = f"siyuan-{self.version}.apk"+ official = [path for path in packages if path.name in {+ official_name, f"siyuan-{self.version}-official.apk", f"siyuan-{self.version}-official-release.apk",+ }]+ if len(official) != 1:+ raise BuildError(f"无法唯一确定 Android 官方版 APK:{folder}")+ self.collect(packages, "Android", started, {official[0].name: official_name})++ def harmony(self, assets):+ directory = self.args.wsl_repo.rstrip("/") + "/kernel/harmony"+ for script, abi, architecture in (("build.sh", "arm64-v8a", "arm64"), ("build-win.sh", "x86_64", "amd64")):+ started = time.time()+ self.wsl(["bash", "-e", script], directory)+ source = self.wsl_root / "kernel/harmony/libkernel.so"+ if source.stat().st_mtime < started - 2:+ raise BuildError(f"鸿蒙内核未更新:{source}")+ self.check_kernel(source, architecture)+ # 两个脚本写同一个文件名,必须在下一次构建前分别复制。+ copy_verified(source, self.args.harmony_dir / "entry/libs" / abi / "libkernel.so", self.args.harmony_dir)+ copy_verified(assets, self.args.harmony_dir / "entry/src/main/resources/rawfile/app.zip", self.args.harmony_dir)+ env = dict(os.environ)+ env["DEVECO_SDK_HOME"] = str(self.args.deveco / "sdk")+ env["JAVA_HOME"] = str(self.args.deveco / "jbr")+ env["PATH"] = str(self.args.deveco / "tools/node") + os.pathsep + env.get("PATH", "")+ run([self.args.deveco / "tools/ohpm/bin/ohpm.bat", "install", "--all"], self.args.harmony_dir, env)+ command = [self.args.deveco / "tools/node/node.exe", self.args.deveco / "tools/hvigor/bin/hvigorw.js",+ "--mode", "project", "-p", "product=default", "-p", "buildMode=release", "--no-daemon"]+ run(command + ["clean"], self.args.harmony_dir, env)+ started = time.time()+ run(command + ["assembleApp"], self.args.harmony_dir, env)+ app = self.args.harmony_dir / "build/outputs/default/siyuan-harmony-default-unsigned.app"+ hap = self.args.harmony_dir / "entry/build/default/outputs/default/entry-default-signed.hap"+ self.collect([app, hap], "鸿蒙", started)++ def finish(self):+ for artifact in self.artifacts:+ print(f"校验安装包:{artifact.name}", flush=True)+ VERIFY.verify_package(artifact, sevenzip=VERIFY.find_7z(self.args.sevenzip), version=self.version)+ output = self.args.output+ output.mkdir(parents=True, exist_ok=True)+ for artifact in self.artifacts:+ if (output / artifact.name).exists():+ raise BuildError(f"输出目录已有同名文件,未覆盖:{output / artifact.name};验证后的产物保留在 {self.work}")+ existing = [path for path in output.iterdir() if path.is_file() and path.name.lower() != "checksum.exe"+ and path.name.lower().endswith(VERIFY.PACKAGES)]+ for path in existing:+ VERIFY.verify_package(path, sevenzip=VERIFY.find_7z(self.args.sevenzip), version=self.version)+ for artifact in self.artifacts:+ copy_verified(artifact, output / artifact.name, output)+ checksums = "".join(f"{VERIFY.digest(artifact)} {artifact.name}\n" for artifact in sorted(existing + self.artifacts))+ sums = self.work / "SHA256SUMS.txt"+ with sums.open("w", encoding="utf-8", newline="\n") as stream:+ stream.write(checksums)+ copy_verified(sums, output / "SHA256SUMS.txt", output)+ print(f"完成:{len(self.artifacts)} 个安装包已校验并收集到 {output}")+++def parser():+ result = argparse.ArgumentParser(description=__doc__, epilog="示例:python scripts/build-release.py --platforms windows,linux,android,harmony --execute。执行前停止前端开发构建并完成各仓库版本号准备。不会自动提交、打标签或上传发布。")+ result.add_argument("--platforms", default=",".join(PLATFORMS), help="逗号分隔的平台,可分批构建")+ result.add_argument("--execute", action="store_true", help="实际执行;不传时只显示计划")+ result.add_argument("--appx", action="store_true", help="Windows 额外生成两个 Microsoft Store Appx 包")+ result.add_argument("--output", type=Path, help="安装包收集目录,默认桌面 siyuan;不覆盖已有产物")+ result.add_argument("--certificate-subject", default="Yunnan Liandi Technology Co., Ltd.", help="Windows 证书主题,可用指纹替代")+ result.add_argument("--certificate-sha1", help="Windows 签名证书的 40 位公开指纹,不是密码")+ 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")+ result.add_argument("--wsl-repo", default="/home/d/88250/siyuan")+ result.add_argument("--android-dir", type=Path, default=ROOT.parent / "siyuan-android")+ result.add_argument("--harmony-dir", type=Path, default=ROOT.parent / "siyuan-harmony")+ result.add_argument("--deveco", type=Path, default=Path("D:/Program Files/Huawei/DevEco Studio"))+ result.add_argument("--sevenzip", help="安装包校验使用的 7-Zip 可执行文件")+ return result+++def main():+ for stream in (sys.stdout, sys.stderr):+ if hasattr(stream, "reconfigure"):+ stream.reconfigure(encoding="utf-8")+ args = parser().parse_args()+ args.platforms = list(dict.fromkeys(args.platforms.split(",")))+ if not args.platforms or set(args.platforms) - set(PLATFORMS):+ raise BuildError(f"平台只能是:{', '.join(PLATFORMS)}")+ if args.certificate_sha1 and not re.fullmatch(r"[0-9a-fA-F]{40}", args.certificate_sha1):+ raise BuildError("证书指纹必须为 40 位十六进制字符串")+ version = json.loads((ROOT / "app/package.json").read_text(encoding="utf-8"))["version"]+ args.output = (args.output or VERIFY.desktop_folder()).resolve()+ for name in ("android_dir", "harmony_dir", "deveco", "arm64_cc"):+ setattr(args, name, getattr(args, name).resolve())+ print(f"版本:{version}\n平台:{', '.join(args.platforms)}\n收集目录:{args.output}")+ descriptions = {+ "windows": "构建 AMD64/ARM64 内核 - YubiKey 签名 - 生成两个 NSIS 安装包 - 检查签名",+ "linux": f"WSL 用户 {args.wsl_user}、目录 {args.wsl_repo} - 检查源代码一致 - 双架构构建 TAR/AppImage/DEB/RPM",+ "android": "生成新 kernel.aar - 核对版本和架构 - 自动复制内核及 app.zip - Gradle 四渠道 release 构建",+ "harmony": "WSL 构建两种架构内核并分别复制 - 更新 app.zip - Hvigor release 构建 APP/HAP",+ }+ print("本地前端仅构建一次;Linux 前端在 WSL 中构建")+ for platform in args.platforms:+ print(f" {platform}: {descriptions[platform]}")+ print("最后逐个验证安装包,全部通过后复制产物并生成 SHA256SUMS.txt")+ if not args.execute:+ print("当前仅显示计划,没有执行构建或修改文件;添加 --execute 开始")+ return 0+ if os.name != "nt":+ raise BuildError("此编排脚本需要在 Windows 上执行,Linux 和鸿蒙内核通过 WSL 构建")+ with tempfile.TemporaryDirectory(prefix="siyuan-release-preflight-") as temporary:+ probe = Builder(args, version, Path(temporary))+ probe.preflight()+ work = Path(tempfile.mkdtemp(prefix=f"siyuan-release-{version}-{datetime.now():%Y%m%d}-"))+ builder = Builder(args, version, work)+ builder.thumbprint, builder.wsl_root = probe.thumbprint, probe.wsl_root+ print(f"本次构建目录:{work};失败时保留产物供检查", flush=True)+ if set(args.platforms) & {"windows", "android", "harmony"}:+ builder.build_ui()+ assets = work / "mobile/app.zip"+ if set(args.platforms) & {"android", "harmony"}:+ create_mobile_assets(assets, version)+ for platform in PLATFORMS:+ if platform in args.platforms:+ method = getattr(builder, platform)+ method(assets) if platform in {"android", "harmony"} else method()+ builder.finish()+ return 0+++if __name__ == "__main__":+ try:+ sys.exit(main())+ except (BuildError, VERIFY.VerificationError, OSError, ValueError, subprocess.SubprocessError) as error:+ print(f"[FAIL] {error}", file=sys.stderr)+ sys.exit(1)diff --git a/scripts/release-windows-config.cjs b/scripts/release-windows-config.cjsnew file mode 100644index 0000000000..4bee5f20dd--- /dev/null+++ b/scripts/release-windows-config.cjs@@ -0,0 +1,30 @@+const fs = require("node:fs");+const path = require("node:path");+const {createRequire} = require("node:module");++async function main() {+ const [base, kernel, output, thumbprint, destination] = 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");+ }+ const project = path.dirname(path.resolve(base));+ const projectRequire = createRequire(path.join(project, "package.json"));+ const builderRequire = createRequire(projectRequire.resolve("electron-builder"));+ const library = path.dirname(builderRequire.resolve("app-builder-lib"));+ const {getConfig, validateConfiguration} = require(path.join(library, "util/config/config.js"));+ const config = await getConfig(project, path.resolve(base), null);+ // 先展开继承配置,再替换内核资源列表,避免合并时保留开发内核目录。+ delete config.extends;+ config.directories = {...config.directories, output: path.resolve(output)};+ config.forceCodeSigning = true;+ config.win.extraResources = [{from: path.resolve(kernel), to: "kernel"}];+ config.win.signtoolOptions = {...config.win.signtoolOptions, certificateSha1: thumbprint};+ delete config.win.signtoolOptions.certificateSubjectName;+ await validateConfiguration(config);+ fs.writeFileSync(destination, JSON.stringify(config, null, 2) + "\n", {encoding: "utf8", flag: "wx"});+}++main().catch(error => {+ console.error(error.message);+ process.exitCode = 1;+});diff --git a/scripts/test_build_release.py b/scripts/test_build_release.pynew file mode 100644index 0000000000..24b3347b6c--- /dev/null+++ b/scripts/test_build_release.py@@ -0,0 +1,209 @@+"""发布编排回归测试,使用模拟构建产物,不调用编译器或签名密钥。"""++import contextlib+import importlib.util+import io+import json+from pathlib import Path+import shutil+import struct+import tempfile+import time+import unittest+from unittest.mock import patch+import zipfile+++SPEC = importlib.util.spec_from_file_location("build_release", Path(__file__).with_name("build-release.py"))+build = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(build)+++def kernel(version="3.8.4", architecture="arm64"):+ header = bytearray(64)+ header[:6] = b"\x7fELF\x02\x01"+ struct.pack_into("<H", header, 18, 183 if architecture == "arm64" else 62)+ return bytes(header) + f"SiYuan v{version} (pdfcpu ".encode("ascii")+++class BuildTests(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.root = Path(self.temp.name)+ self.args = build.parser().parse_args([])+ self.args.android_dir = self.root / "android"+ self.args.harmony_dir = self.root / "harmony"+ self.args.output = self.root / "output"+ self.args.platforms = ["windows", "linux", "android", "harmony"]+ self.builder = build.Builder(self.args, "3.8.4", self.root / "work")+ self.builder.work.mkdir()++ def write(self, path, content=b"data"):+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(content)+ return path++ def test_copy_rejects_destination_escape(self):+ source = self.write(self.root / "input", b"new")+ with self.assertRaises(build.BuildError):+ build.copy_verified(source, self.root / "outside", self.root / "allowed")+ self.assertFalse((self.root / "outside").exists())++ def test_copy_updates_old_file_and_verifies_hash(self):+ source = self.write(self.root / "source", b"new kernel")+ target = self.write(self.root / "target", b"old kernel")+ build.copy_verified(source, target, self.root)+ self.assertEqual(target.read_bytes(), b"new kernel")+ self.assertEqual(list(self.root.glob(".siyuan-copy-*")), [])++ def test_collect_missing_output_fails(self):+ with self.assertRaises(build.BuildError):+ self.builder.collect([self.root / "missing.apk"], "Android", time.time())++ def test_old_kernel_version_is_rejected(self):+ path = self.write(self.root / "libkernel.so", kernel("3.8.3"))+ with self.assertRaises(build.BuildError):+ self.builder.check_kernel(path, "arm64")++ def test_wrong_kernel_architecture_is_rejected(self):+ path = self.write(self.root / "libkernel.so", kernel(architecture="amd64"))+ with self.assertRaises(build.BuildError):+ self.builder.check_kernel(path, "arm64")++ def test_windows_uses_fresh_kernel_directories_and_forces_signing(self):+ root = self.root / "repository"+ for arch in ("amd64", "arm64"):+ self.write(root / "app/elevator" / f"elevator-{arch}.exe")+ self.builder.thumbprint = "A" * 40+ commands = []++ def fake_run(command, cwd, env=None, capture=False):+ command = [str(value) for value in command]+ commands.append(command)+ if command[:3] in (["go", "env", "GOBIN"], ["go", "env", "GOPATH"]):+ return str(self.root / "go-bin")+ if command[:2] == ["go", "build"]:+ self.write(command[command.index("-o") + 1])+ if command[0] == "node":+ Path(command[-1]).write_text(json.dumps({+ "forceCodeSigning": True, "directories": {"output": command[4]},+ "win": {"extraResources": [{"from": command[3], "to": "kernel"}],+ "signtoolOptions": {"certificateSha1": command[5]}},+ }), encoding="utf-8")+ if command[:3] == ["pnpm", "exec", "electron-builder"]:+ config = json.loads(Path(command[command.index("--config") + 1]).read_text(encoding="utf-8"))+ self.assertTrue(config["forceCodeSigning"])+ self.assertEqual(config["win"]["signtoolOptions"]["certificateSha1"], "A" * 40)+ kernel_dir = Path(config["win"]["extraResources"][0]["from"])+ self.assertTrue(kernel_dir.is_relative_to(self.builder.work))+ self.assertEqual({p.name for p in kernel_dir.iterdir()}, {"SiYuan-Kernel.exe", "elevator.exe"})+ suffix = "-arm64" if "--arm64" in command else ""+ self.write(Path(config["directories"]["output"]) / f"siyuan-3.8.4-win{suffix}.exe")+ return ""++ with patch.object(build, "ROOT", root), patch.object(build, "run", side_effect=fake_run), \+ patch.object(build, "verify_signature") as signatures, patch.object(self.builder, "check_kernel"):+ self.builder.windows()+ self.assertEqual(len(self.builder.artifacts), 2)+ self.assertEqual(signatures.call_count, 2)+ self.assertFalse((root / "app/kernel").exists())++ @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):+ destination = self.root / "windows.json"+ with contextlib.redirect_stdout(io.StringIO()):+ build.run(["node", build.ROOT / "scripts/release-windows-config.cjs",+ build.ROOT / "app/electron-builder.yml", self.root / "new-kernel",+ self.root / "build", "A" * 40, destination], build.ROOT / "app", capture=True)+ config = json.loads(destination.read_text(encoding="utf-8"))+ self.assertEqual(config["win"]["extraResources"], [{"from": str(self.root / "new-kernel"), "to": "kernel"}])+ self.assertTrue(config["forceCodeSigning"])+ self.assertNotIn("extends", config)+ self.assertEqual(config["win"]["signtoolOptions"]["signingHashAlgorithms"], ["sha256"])+ self.assertTrue(any(entry.get("to") == "stage" for entry in config["extraResources"]))++ def test_harmony_copies_each_architecture_before_next_build(self):+ remote = self.root / "wsl"+ self.builder.wsl_root = remote+ assets = self.write(self.root / "app.zip", b"current assets")++ def fake_wsl(command, directory=None, capture=False):+ architecture = "arm64" if command[-1] == "build.sh" else "amd64"+ self.write(remote / "kernel/harmony/libkernel.so", kernel(architecture=architecture))++ def fake_run(command, cwd, env=None, capture=False):+ if command[-1] == "assembleApp":+ self.assertIn("buildMode=release", command)+ self.write(self.args.harmony_dir / "build/outputs/default/siyuan-harmony-default-unsigned.app")+ self.write(self.args.harmony_dir / "entry/build/default/outputs/default/entry-default-signed.hap")+ return ""++ with patch.object(self.builder, "wsl", side_effect=fake_wsl), patch.object(build, "run", side_effect=fake_run):+ self.builder.harmony(assets)+ arm = self.args.harmony_dir / "entry/libs/arm64-v8a/libkernel.so"+ amd = self.args.harmony_dir / "entry/libs/x86_64/libkernel.so"+ self.assertEqual(arm.read_bytes(), kernel(architecture="arm64"))+ self.assertEqual(amd.read_bytes(), kernel(architecture="amd64"))+ self.assertEqual(len(self.builder.artifacts), 2)++ def test_android_new_aar_is_copied_before_gradle(self):+ sdk = self.root / "sdk"+ (sdk / "ndk/27.0.1").mkdir(parents=True)+ assets = self.write(self.root / "app.zip", b"new assets")+ old = self.write(self.args.android_dir / "app/libs/kernel.aar", b"old aar")+ self.write(self.args.android_dir / "local.properties", f"sdk.dir={sdk.as_posix()}\n".encode("utf-8"))++ def fake_run(command, cwd, env=None, capture=False):+ command = [str(value) for value in command]+ if command[0] == "gomobile":+ with zipfile.ZipFile(command[command.index("-o") + 1], "w") as archive:+ archive.writestr("jni/arm64-v8a/libgojni.so", kernel())+ if command[0].endswith("gradlew.bat"):+ self.assertNotEqual(old.read_bytes(), b"old aar")+ self.assertEqual((self.args.android_dir / "app/src/main/assets/app.zip").read_bytes(), b"new assets")+ self.assertIn("buildReleaseTask", command)+ for channel, ext in (("cn", "apk"), ("official", "apk"), ("googleplay", "aab"), ("huawei", "aab")):+ self.write(self.args.android_dir / "app/build-release/siyuan-3.8.4-all" / f"siyuan-3.8.4-{channel}-release.{ext}")+ return ""++ with patch.dict(build.os.environ, {"ANDROID_HOME": str(sdk)}, clear=True), patch.object(build, "run", side_effect=fake_run):+ self.builder.android(assets)+ self.assertEqual(len(self.builder.artifacts), 4)+ self.assertEqual({path.name for path in self.builder.artifacts}, {+ "siyuan-3.8.4.apk", "siyuan-3.8.4-cn-release.apk",+ "siyuan-3.8.4-googleplay-release.aab", "siyuan-3.8.4-huawei-release.aab",+ })++ def test_failed_validation_does_not_publish(self):+ self.builder.artifacts = [self.write(self.builder.work / "bad.apk")]+ with patch.object(build.VERIFY, "verify_package", side_effect=build.VERIFY.VerificationError("old kernel")):+ with self.assertRaises(build.VERIFY.VerificationError), contextlib.redirect_stdout(io.StringIO()):+ self.builder.finish()+ self.assertFalse(self.args.output.exists())++ def test_add_platform_updates_checksums_without_overwriting_packages(self):+ existing = self.write(self.args.output / "siyuan-3.8.4-win.exe", b"signed windows")+ artifact = self.write(self.builder.work / "siyuan-3.8.4.apk", b"android")+ self.write(self.args.output / "SHA256SUMS.txt", b"old sums")+ self.builder.artifacts = [artifact]+ with patch.object(build.VERIFY, "verify_package"), contextlib.redirect_stdout(io.StringIO()):+ self.builder.finish()+ sums = (self.args.output / "SHA256SUMS.txt").read_text(encoding="utf-8")+ self.assertIn(build.VERIFY.digest(existing), sums)+ self.assertIn(build.VERIFY.digest(artifact), sums)+ self.assertIn(" siyuan-3.8.4.apk\n", sums)+ self.assertTrue((self.args.output / "siyuan-3.8.4.apk").is_file())+ self.assertEqual(existing.read_bytes(), b"signed windows")++ def test_default_plan_does_not_run_commands(self):+ with patch.object(build.sys, "argv", ["build-release.py"]), patch.object(build, "run") as command, \+ contextlib.redirect_stdout(io.StringIO()):+ self.assertEqual(build.main(), 0)+ command.assert_not_called()+++if __name__ == "__main__":+ unittest.main()diff --git a/scripts/test_verify_release.py b/scripts/test_verify_release.pynew file mode 100644index 0000000000..64a567a955--- /dev/null+++ b/scripts/test_verify_release.py@@ -0,0 +1,243 @@+"""发布包校验回归测试:旧内核、资源遗漏、嵌套载荷与空目录。"""++import argparse+import contextlib+import importlib.util+import io+import json+from pathlib import Path+import tempfile+import unittest+import zipfile+++SPEC = importlib.util.spec_from_file_location("verify_release", Path(__file__).with_name("verify-release.py"))+release = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(release)+++class ReleaseTests(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.root = Path(self.temp.name)+ self.resources = {+ "stage/build/mobile/index.html": b"<html></html>",+ "stage/build/mobile/main.js": b"current frontend",+ "appearance/langs/en.json": b"{}",+ "guide/document.sy": b"guide",+ "changelogs/v3.8.4/en.md": b"release notes",+ }+ self.kernel = b"new kernel"+ self.baseline = {+ "file": "test.release-baseline.json", "target": "android-arm64", "version": "3.8.4",+ "kernels": [release.hashlib.sha256(self.kernel).hexdigest()],+ "resources": {name: release.hashlib.sha256(data).hexdigest()+ for name, data in self.resources.items()},+ }++ def package(self, kernel=None, resources=None):+ path = self.root / "test.apk"+ with zipfile.ZipFile(path, "w") as archive:+ archive.writestr("lib/arm64-v8a/libgojni.so", self.kernel if kernel is None else kernel)+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w") as assets:+ for name, data in (self.resources if resources is None else resources).items():+ assets.writestr(name, data)+ archive.writestr("assets/app.zip", buffer.getvalue())+ return path++ def test_nested_android_passes(self):+ result = release.verify_package(self.package(), [self.baseline], None)+ self.assertEqual(result["resource_count"], len(self.resources))++ def test_old_kernel_fails_even_with_current_frontend(self):+ with self.assertRaisesRegex(release.VerificationError, "内核与所有基准均不匹配"):+ release.verify_package(self.package(kernel=b"old kernel"), [self.baseline], None)++ def test_missing_and_changed_resources_fail(self):+ for name, data in [("stage/build/mobile/main.js", b"old frontend"),+ ("appearance/langs/en.json", None), ("guide/document.sy", None),+ ("changelogs/v3.8.4/en.md", None)]:+ with self.subTest(name=name):+ resources = dict(self.resources)+ if data is None:+ resources.pop(name)+ else:+ resources[name] = data+ with self.assertRaises(release.VerificationError):+ release.verify_package(self.package(resources=resources), [self.baseline], None)++ def test_extra_resource_fails(self):+ resources = dict(self.resources, **{"stage/build/mobile/old.js": b"stale"})+ with self.assertRaisesRegex(release.VerificationError, "多余资源"):+ release.verify_package(self.package(resources=resources), [self.baseline], None)++ def test_wrong_abi_kernel_set_fails(self):+ package = self.package()+ with zipfile.ZipFile(package, "a") as archive:+ archive.writestr("lib/x86_64/libgojni.so", b"unexpected kernel")+ with self.assertRaises(release.VerificationError):+ release.verify_package(package, [self.baseline], None)++ def test_android_native_resources_case_collision(self):+ package = self.package()+ with zipfile.ZipFile(package, "a") as archive:+ archive.writestr("res/2f.xml", b"first")+ archive.writestr("res/2F.xml", b"second")+ release.verify_package(package, [self.baseline], None)++ def test_check_continues_after_failed_package(self):+ baseline = self.root / "android.release-baseline.json"+ baseline.write_text(json.dumps(dict(self.baseline, schema=1)), encoding="utf-8")+ self.package(kernel=b"old kernel").rename(self.root / "a-old.apk")+ self.package().rename(self.root / "b-new.apk")+ report = self.root / "result.json"+ args = argparse.Namespace(directory=self.root, version="3.8.4", baseline=[baseline],+ report=report, sevenzip=None)+ with contextlib.redirect_stdout(io.StringIO()):+ self.assertEqual(release.verify(args), 1)+ statuses = [entry["status"] for entry in json.loads(report.read_text(encoding="utf-8"))["packages"]]+ self.assertEqual(statuses, ["FAIL", "PASS"])++ def test_empty_directory_fails(self):+ args = argparse.Namespace(directory=self.root, version="3.8.4", baseline=None, report=None)+ with self.assertRaisesRegex(release.VerificationError, "没有安装包"):+ release.verify(args)++ def test_zip_traversal_fails(self):+ path = self.root / "unsafe.zip"+ with zipfile.ZipFile(path, "w") as archive:+ archive.writestr("../outside", b"bad")+ with self.assertRaises(release.VerificationError):+ release.Unpacker(self.root).extract(path)+ self.assertFalse((self.root.parent / "outside").exists())++ def test_duplicate_zip_member_fails(self):+ path = self.root / "duplicate.zip"+ with zipfile.ZipFile(path, "w") as archive:+ archive.writestr("app/Main.js", b"first")+ archive.writestr("app/main.js", b"second")+ with self.assertRaisesRegex(release.VerificationError, "归档路径重复"):+ release.Unpacker(self.root).extract(path)++ def test_nsis_split_resources_merge(self):+ outer, inner = self.root / "outer", self.root / "inner"+ for name, data in self.resources.items():+ layer = outer if name.startswith("guide/") else inner+ path = layer / "resources" / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(data)+ (inner / "resources/guide").mkdir()+ actual = release.package_resources([outer, inner], inner / "resources")+ self.assertEqual(actual, self.baseline["resources"])++ def test_baseline_roundtrip(self):+ resources = self.root / "resources"+ for name, data in self.resources.items():+ path = resources / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(data)+ kernel = self.root / "libgojni.so"+ kernel.write_bytes(self.kernel)+ output = self.root / "android.release-baseline.json"+ args = argparse.Namespace(resources=resources, version="3.8.4", kernel=kernel,+ sevenzip=None, target="android-arm64", output=output)+ with contextlib.redirect_stdout(io.StringIO()):+ release.create_baseline(args)+ baseline = release.load_baselines([output], "3.8.4")+ release.verify_package(self.package(), baseline, None)+ with self.assertRaises(release.VerificationError):+ release.load_baselines([output], "3.8.5")+ with self.assertRaises(FileExistsError):+ release.create_baseline(args)+++class DirectReleaseTests(unittest.TestCase):+ package = ReleaseTests.package++ def setUp(self):+ ReleaseTests.setUp(self)+ self.kernel = self.native_kernel("3.8.4")+ self.resources["stage/build/mobile/index.html"] = b'<script src="main.js"></script><link rel="stylesheet" href="base.css">'+ self.resources["stage/build/mobile/main.js"] = b'e.d(exports,{Constants:()=>i});const d="3.8.4",H="production";let i={};i.SIYUAN_VERSION=d,i.NODE_ENV=H;'+ self.resources["stage/build/mobile/base.css"] = b"body{color:black}"+ self.resources["stage/build/export/protyle-method.js"] = self.resources["stage/build/mobile/main.js"]++ @staticmethod+ def native_kernel(version):+ header = bytearray(64)+ header[:6] = b"\x7fELF\x02\x01"+ release.struct.pack_into("<H", header, 18, 183)+ return bytes(header) + f"SiYuan v{version} (pdfcpu ".encode("ascii")++ def test_no_baseline_needed(self):+ result = release.verify_package(self.package(), version="3.8.4")+ self.assertEqual(result["kernels"][0]["version"], "3.8.4")+ self.assertEqual(result["frontend_versions"]["stage/build/mobile/index.html"], ["3.8.4"])++ def test_beta_kernel_in_stable_apk(self):+ with self.assertRaisesRegex(release.VerificationError, "3.8.4-beta.2"):+ release.verify_package(self.package(kernel=self.native_kernel("3.8.4-beta.2")), version="3.8.4")++ def test_unrelated_version_string_does_not_pass(self):+ with self.assertRaisesRegex(release.VerificationError, "无法唯一确定内核版本"):+ release.verify_package(self.package(kernel=self.native_kernel("3.8.4").split(b"SiYuan v")[0] + b"v3.8.4"), version="3.8.4")++ def test_conflicting_kernel_markers(self):+ with self.assertRaisesRegex(release.VerificationError, "无法唯一确定内核版本"):+ release.verify_package(self.package(kernel=self.kernel + b"SiYuan v3.8.3 (pdfcpu "), version="3.8.4")++ def test_frontend_version_mismatch(self):+ self.resources["stage/build/mobile/main.js"] = self.resources["stage/build/mobile/main.js"].replace(b"3.8.4", b"3.8.3")+ with self.assertRaisesRegex(release.VerificationError, "前端版本不匹配"):+ release.verify_package(self.package(), version="3.8.4")++ def test_unreferenced_current_bundle_cannot_hide_old_frontend(self):+ self.resources["stage/build/mobile/unused.js"] = self.resources["stage/build/mobile/main.js"]+ self.resources["stage/build/mobile/main.js"] = self.resources["stage/build/mobile/main.js"].replace(b"3.8.4", b"3.8.3")+ with self.assertRaisesRegex(release.VerificationError, "前端版本不匹配"):+ release.verify_package(self.package(), version="3.8.4")++ def test_missing_stylesheet(self):+ del self.resources["stage/build/mobile/base.css"]+ with self.assertRaisesRegex(release.VerificationError, "资源引用缺失"):+ release.verify_package(self.package(), version="3.8.4")++ def test_missing_css_font(self):+ self.resources["stage/build/mobile/base.css"] = b'@font-face{src:url("/appearance/fonts/missing.woff2?v=2")}'+ with self.assertRaisesRegex(release.VerificationError, "样式资源缺失"):+ release.verify_package(self.package(), version="3.8.4")++ def test_missing_lazy_chunk(self):+ self.resources["stage/build/mobile/main.js"] += b'r.u=e=>""+e+"."+{125:"4019a1017e22ca53a1c0"}[e]+".js";'+ with self.assertRaisesRegex(release.VerificationError, "动态分块缺失"):+ release.verify_package(self.package(), version="3.8.4")++ def test_missing_export_frontend(self):+ del self.resources["stage/build/export/protyle-method.js"]+ with self.assertRaisesRegex(release.VerificationError, "缺少导出前端"):+ release.verify_package(self.package(), version="3.8.4")++ def test_kernel_abi_path_mismatch(self):+ header = bytearray(self.kernel)+ release.struct.pack_into("<H", header, 18, 62)+ with self.assertRaisesRegex(release.VerificationError, "ABI 目录"):+ release.verify_package(self.package(kernel=bytes(header)), version="3.8.4")++ def test_automatic_expected_version(self):+ self.package().rename(self.root / "siyuan-3.8.4.apk")+ args = argparse.Namespace(directory=self.root, version=None, baseline=None, report=None, sevenzip=None)+ with contextlib.redirect_stdout(io.StringIO()):+ self.assertEqual(release.verify(args), 0)++ def test_mixed_release_filenames_fail(self):+ self.package().rename(self.root / "siyuan-3.8.4-official-release.apk")+ self.package().rename(self.root / "siyuan-3.8.3-cn-release.apk")+ args = argparse.Namespace(directory=self.root, version=None, baseline=None, report=None, sevenzip=None)+ with self.assertRaisesRegex(release.VerificationError, "唯一发布版本"):+ release.verify(args)+++if __name__ == "__main__":+ unittest.main()diff --git a/scripts/verify-release.py b/scripts/verify-release.pynew file mode 100644index 0000000000..84f6bc728f--- /dev/null+++ b/scripts/verify-release.py@@ -0,0 +1,586 @@+#!/usr/bin/env python3+"""直接检查发布安装包的内核版本、前端版本和资源引用,无需增加打包步骤。"""++import argparse+import hashlib+from html.parser import HTMLParser+import json+import os+from pathlib import Path, PurePosixPath+import plistlib+import posixpath+import re+import shutil+import stat+import struct+import subprocess+import sys+import tarfile+import tempfile+import zipfile+from urllib.parse import unquote, urlsplit+++REPO = Path(__file__).resolve().parents[1]+GROUPS = ("stage", "appearance", "guide", "changelogs")+PACKAGES = (".exe", ".zip", ".7z", ".tar.gz", ".tgz", ".deb", ".rpm",+ ".appimage", ".dmg", ".apk", ".aab", ".hap", ".app", ".ipa", ".appx", ".msix")+SIDECARS = (".blockmap", ".yml", ".yaml", ".release-baseline.json")+KERNEL_NAMES = {"siyuan-kernel", "siyuan-kernel.exe", "libgojni.so", "libkernel.so"}+VERSION = r"[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z.-]+)?"+PACKAGE_VERSION = re.compile(r"^siyuan-(\d+\.\d+\.\d+(?:-(?:alpha|beta|rc)(?:\.[0-9A-Za-z]+)*)?)(?=[-.])", re.I)+++class VerificationError(Exception):+ pass+++def digest(path):+ with path.open("rb") as stream:+ return hashlib.file_digest(stream, "sha256").hexdigest()+++def desktop_folder():+ if os.name == "nt":+ import winreg+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER,+ r"Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders") as key:+ return Path(os.path.expandvars(winreg.QueryValueEx(key, "Desktop")[0])) / "siyuan"+ return Path.home() / "Desktop" / "siyuan"+++def find_7z(explicit=None):+ candidates = [explicit, shutil.which("7zz"), shutil.which("7z")]+ if os.name == "nt":+ candidates += [str(Path(os.environ.get("ProgramFiles", "C:/Program Files")) / "7-Zip/7z.exe"),+ "D:/Program Files/7-Zip/7z.exe"]+ return next((str(Path(p).resolve()) for p in candidates if p and Path(p).is_file()), None)+++def safe_name(name):+ path = PurePosixPath(name.replace("\\", "/"))+ if path.is_absolute() or ".." in path.parts or any(":" in part for part in path.parts):+ raise VerificationError(f"归档包含不安全路径:{name}")+ return path+++class Unpacker:+ def __init__(self, root, sevenzip=None):+ self.root = root+ self.sevenzip = sevenzip+ self.count = 0++ def extract(self, source):+ self.count += 1+ if self.count > 64:+ raise VerificationError("嵌套归档超过 64 个,停止解包")+ dest = self.root / str(self.count)+ dest.mkdir()+ if zipfile.is_zipfile(source):+ with zipfile.ZipFile(source) as archive:+ names = set()+ for entry in archive.infolist():+ name = safe_name(entry.filename).as_posix()+ # Android 的 res 中存在仅大小写不同的原生外壳文件,Windows 无法同时落盘。+ if source.suffix.lower() in {".apk", ".aab"}:+ parts = PurePosixPath(name).parts+ if not any(part in {"lib", "assets"} for part in parts):+ continue+ if name.casefold() in names:+ raise VerificationError(f"归档路径重复:{name}")+ names.add(name.casefold())+ if stat.S_ISLNK(entry.external_attr >> 16):+ continue+ target = dest / name+ if entry.is_dir():+ target.mkdir(parents=True, exist_ok=True)+ else:+ target.parent.mkdir(parents=True, exist_ok=True)+ with archive.open(entry) as src, target.open("wb") as out:+ shutil.copyfileobj(src, out)+ elif tarfile.is_tarfile(source):+ with tarfile.open(source) as archive:+ names = set()+ for entry in archive:+ name = safe_name(entry.name).as_posix()+ if not entry.isfile():+ continue+ if name.casefold() in names:+ raise VerificationError(f"归档路径重复:{name}")+ names.add(name.casefold())+ target = dest / name+ target.parent.mkdir(parents=True, exist_ok=True)+ with archive.extractfile(entry) as src, target.open("wb") as out:+ shutil.copyfileobj(src, out)+ else:+ if not self.sevenzip:+ raise VerificationError(f"解包 {source.name} 需要 7-Zip,请指定 --sevenzip")+ command = [self.sevenzip, "x", "-y", "-bd", "-bso0", "-bsp0", f"-o{dest}", str(source)]+ result = subprocess.run(command, capture_output=True, text=True, errors="replace", timeout=600)+ if result.returncode:+ raise VerificationError(f"7-Zip 无法完整解包 {source.name}:{result.stderr.strip()}")+ return dest++ def layers(self, package):+ queue = [self.extract(package)]+ result = []+ while queue:+ layer = queue.pop(0)+ result.append(layer)+ for path in sorted(layer.rglob("*")):+ if not path.is_file() or path.is_symlink():+ continue+ name = path.name.lower()+ # 只展开安装器的载荷,不展开前端资源中的第三方归档。+ if (name == "app.zip" or name.endswith((".hap", ".appx", ".msix", ".cpio", ".hfs", ".img"))+ or (name.startswith("app-") and name.endswith(".7z"))+ or name.startswith("data.tar") or ".cpio." in name):+ queue.append(self.extract(path))+ return result+++def resource_files(root, partial=False):+ result = {}+ for group in GROUPS:+ folder = root / group+ if not folder.is_dir():+ if partial or group == "changelogs":+ continue+ raise VerificationError(f"缺少资源目录:{folder}")+ for path in sorted(folder.rglob("*")):+ if not path.is_file() or path.is_symlink():+ continue+ rel = path.relative_to(root)+ if any(part in {".git", ".idea", ".DS_Store", ".gitignore"} for part in rel.parts):+ continue+ result[rel.as_posix()] = digest(path)+ return result+++def package_resources(layers, root):+ actual = resource_files(root, partial=True)+ # NSIS 将部分大文件放在外层 resources 中,合并同一逻辑目录的载荷。+ owner = next(layer for layer in layers if root.is_relative_to(layer))+ relative = root.relative_to(owner)+ for layer in layers:+ supplement = layer / relative+ if supplement == root or not supplement.is_dir():+ continue+ for name, checksum in resource_files(supplement, partial=True).items():+ if name in actual and actual[name] != checksum:+ raise VerificationError(f"安装器内外层资源冲突:{name}")+ actual[name] = checksum+ return actual+++def resource_paths(layers, root):+ owner = next(layer for layer in layers if root.is_relative_to(layer))+ relative = root.relative_to(owner)+ result = {}+ for layer in layers:+ folder = layer / relative+ for group in GROUPS:+ for path in (folder / group).rglob("*"):+ if path.is_file() and not path.is_symlink():+ result[path.relative_to(folder).as_posix()] = path+ return result+++def kernel_files(layers):+ result = []+ for layer in layers:+ for path in sorted(layer.rglob("*")):+ if path.is_file() and not path.is_symlink() and path.name.lower() in KERNEL_NAMES:+ result.append(path)+ return result+++def resource_roots(layers):+ return [path.parent for layer in layers for path in layer.rglob("stage")+ if path.is_dir() and (path / "build").is_dir()]+++def compare_files(expected, actual):+ errors = []+ for name in sorted(expected.keys() - actual.keys()):+ errors.append(f"缺少资源:{name}")+ for name in sorted(actual.keys() - expected.keys()):+ errors.append(f"多余资源:{name}")+ for name in sorted(expected.keys() & actual.keys()):+ if expected[name] != actual[name]:+ errors.append(f"资源内容不匹配:{name}")+ return errors+++def create_baseline(args):+ resources = args.resources.resolve()+ files = resource_files(resources)+ version = args.version+ if not version:+ version = json.loads((REPO / "app/package.json").read_text(encoding="utf-8"))["version"]+ for metadata in (resources / "package.json", resources / "app/package.json"):+ if metadata.is_file():+ actual_version = json.loads(metadata.read_text(encoding="utf-8")).get("version")+ if actual_version != version:+ raise VerificationError(f"资源目录的应用版本为 {actual_version},与 {version} 不匹配")+ if "-" not in version and not any(name.startswith(f"changelogs/v{version}/") for name in files):+ raise VerificationError(f"资源缺少当前版本更新日志:v{version}")+ with tempfile.TemporaryDirectory(prefix="siyuan-baseline-") as temp:+ kernel = args.kernel.resolve()+ if kernel.suffix.lower() == ".aar":+ layers = Unpacker(Path(temp), find_7z(args.sevenzip)).layers(kernel)+ kernels = kernel_files(layers)+ elif kernel.is_dir():+ kernels = kernel_files([kernel])+ else:+ kernels = [kernel] if kernel.is_file() else []+ if not kernels:+ raise VerificationError("没有找到内核文件")+ hashes = sorted({digest(path) for path in kernels})+ manifest = {"schema": 1, "version": version, "target": args.target,+ "kernels": hashes, "resources": files}+ # 基准必须来自本次构建的可信输入,不能由待验安装包反向生成。+ with args.output.open("x", encoding="utf-8", newline="\n") as stream:+ json.dump(manifest, stream, ensure_ascii=False, indent=2)+ stream.write("\n")+ print(f"已生成基准:{args.output}({len(hashes)} 个内核,{len(files)} 个资源)")+++def load_baselines(paths, version):+ result = []+ for path in paths:+ value = json.loads(path.read_text(encoding="utf-8"))+ if value.get("schema") != 1 or value.get("version") != version:+ raise VerificationError(f"基准格式或版本不匹配:{path}")+ if not value.get("kernels") or not value.get("resources") or not value.get("target"):+ raise VerificationError(f"基准内容不完整:{path}")+ if not isinstance(value["resources"], dict) or not isinstance(value["kernels"], list):+ raise VerificationError(f"基准字段类型错误:{path}")+ for group in ("stage", "appearance", "guide"):+ if not any(name.startswith(group + "/") for name in value["resources"]):+ raise VerificationError(f"基准缺少 {group} 资源:{path}")+ for name in value["resources"]:+ safe_name(name)+ for checksum in [*value["kernels"], *value["resources"].values()]:+ if not isinstance(checksum, str) or not re.fullmatch(r"[0-9a-f]{64}", checksum):+ raise VerificationError(f"基准摘要无效:{path}")+ value["file"] = str(path)+ result.append(value)+ return result+++def binary_architecture(data):+ try:+ if data[:4] == b"\x7fELF":+ if data[4] not in (1, 2) or data[5] not in (1, 2):+ raise VerificationError("无效的 ELF 头")+ machine = struct.unpack_from("<H" if data[5] == 1 else ">H", data, 18)[0]+ return "ELF", {62: "amd64", 183: "arm64", 40: "arm", 3: "386"}.get(machine, str(machine))+ if data[:2] == b"MZ":+ offset = struct.unpack_from("<I", data, 60)[0]+ if data[offset:offset + 4] != b"PE\0\0":+ raise VerificationError("无效的 PE 头")+ machine = struct.unpack_from("<H", data, offset + 4)[0]+ return "PE", {0x8664: "amd64", 0xAA64: "arm64", 0x14C: "386"}.get(machine, str(machine))+ magic = data[:4]+ if magic in (b"\xcf\xfa\xed\xfe", b"\xce\xfa\xed\xfe", b"\xfe\xed\xfa\xcf", b"\xfe\xed\xfa\xce"):+ endian = "<" if magic[0] in (0xCF, 0xCE) else ">"+ cpu = struct.unpack_from(endian + "I", data, 4)[0]+ return "Mach-O", {0x1000007: "amd64", 0x100000C: "arm64"}.get(cpu, str(cpu))+ if magic in (b"\xca\xfe\xba\xbe", b"\xca\xfe\xba\xbf"):+ count = struct.unpack_from(">I", data, 4)[0]+ size = 32 if magic[-1] == 0xBF else 20+ if not 1 <= count <= 16 or 8 + count * size > len(data):+ raise VerificationError("无效的通用 Mach-O 头")+ cpus = [struct.unpack_from(">I", data, 8 + i * size)[0] for i in range(count)]+ return "Mach-O", "+".join(sorted({{0x1000007: "amd64", 0x100000C: "arm64"}.get(cpu, str(cpu)) for cpu in cpus}))+ except (IndexError, struct.error) as error:+ raise VerificationError("内核二进制头不完整") from error+ raise VerificationError("内核不是可识别的 PE、ELF 或 Mach-O 二进制")+++def kernel_info(path):+ data = path.read_bytes()+ binary_format, architecture = binary_architecture(data)+ # 此完整前缀由 model/export.go 中的 util.Ver 编译生成,不能用任意版本子串代替。+ versions = {match.decode("ascii") for match in re.findall(+ rb"SiYuan v(" + VERSION.encode("ascii") + rb") \(pdfcpu ", data)}+ versions.update(match.decode("ascii") for match in re.findall(+ rb"SiYuan Kernel v(" + VERSION.encode("ascii") + rb")\. Manage workspace data directly or start the HTTP server\.", data))+ if len(versions) != 1:+ raise VerificationError(f"{path.name} 无法唯一确定内核版本:{sorted(versions)}")+ return {"name": path.name, "version": versions.pop(), "format": binary_format,+ "architecture": architecture, "sha256": hashlib.sha256(data).hexdigest()}+++def frontend_versions(text):+ versions = set()+ assignment = re.compile(r"\bSIYUAN_VERSION\s*=\s*(?:[\"'](" + VERSION + r")[\"']|([A-Za-z_$][\w$]*))")+ for match in assignment.finditer(text):+ if match[1]:+ versions.add(match[1])+ continue+ # 仅解析 Constants 模块内紧邻赋值的常量,不执行安装包里的 JavaScript。+ prefix = text[max(0, match.start() - 3000):match.start()]+ marker = prefix.rfind("Constants:")+ if marker < 0:+ marker = prefix.rfind("class Constants")+ if marker < 0:+ continue+ prefix = prefix[marker:]+ binding = re.compile(r"(?:\bconst\s+|\blet\s+|\bvar\s+|,)" + re.escape(match[2])+ + r"\s*=\s*[\"'](" + VERSION + r")[\"']")+ candidates = {item[1] for item in binding.finditer(prefix)}+ if len(candidates) == 1:+ versions.update(candidates)+ return versions+++class ResourceReferences(HTMLParser):+ def __init__(self):+ super().__init__()+ self.urls = []++ def handle_starttag(self, tag, attributes):+ attrs = dict(attributes)+ if tag in {"script", "img", "source"} and attrs.get("src"):+ self.urls.append(attrs["src"])+ if tag == "link" and attrs.get("href") and attrs.get("rel") != "manifest":+ self.urls.append(attrs["href"])+++def resolve_resource(source, url):+ parsed = urlsplit(url)+ if parsed.scheme or parsed.netloc or not parsed.path or "${" in url:+ return None+ path = unquote(parsed.path)+ if path.startswith("/"):+ if not path.startswith(("/stage/", "/appearance/")):+ return None+ return path.lstrip("/")+ result = posixpath.normpath(posixpath.join(posixpath.dirname(source), path))+ if result.startswith("../"):+ raise VerificationError(f"资源引用越界:{source} -> {url}")+ return result+++def check_frontend(paths, expected_version, mobile):+ errors = []+ versions = {}+ entry = "stage/build/mobile/index.html" if mobile else "stage/build/app/index.html"+ if entry not in paths:+ errors.append(f"缺少前端入口:{entry}")+ html_files = [name for name in paths if name.startswith("stage/build/") and name.endswith(".html")]+ for name in html_files:+ parser = ResourceReferences()+ parser.feed(paths[name].read_text(encoding="utf-8"))+ found = set()+ for url in parser.urls:+ reference = resolve_resource(name, url)+ if reference is None:+ continue+ if reference not in paths:+ errors.append(f"资源引用缺失:{name} -> {reference}")+ continue+ if reference.endswith(".js") and reference.startswith("stage/build/"):+ found.update(frontend_versions(paths[reference].read_text(encoding="utf-8")))+ if found != {expected_version}:+ errors.append(f"前端版本不匹配或无法识别:{name},实际 {sorted(found)},预期 {expected_version}")+ versions[name] = sorted(found)+ export = "stage/build/export/protyle-method.js"+ if export in paths:+ found = frontend_versions(paths[export].read_text(encoding="utf-8"))+ if found != {expected_version}:+ errors.append(f"导出前端版本不匹配或无法识别:{sorted(found)}")+ versions[export] = sorted(found)+ else:+ errors.append(f"缺少导出前端:{export}")+ for name, path in paths.items():+ if name.startswith("stage/build/") and name.endswith(".css"):+ for match in re.finditer(r"url\(\s*['\"]?([^)'\"]+)['\"]?\s*\)", path.read_text(encoding="utf-8")):+ reference = resolve_resource(name, match[1].strip())+ if reference and reference not in paths:+ errors.append(f"样式资源缺失:{name} -> {reference}")+ if name.startswith("stage/build/") and name.endswith(".js") and not Path(name).name.startswith("vendors"):+ text = path.read_text(encoding="utf-8")+ # 识别当前 webpack 生成的数字分块与内容哈希映射。+ for match in re.finditer(r'\.u=\w+=>""\+\w+\+"\."\+\{([^{}]+)\}\[\w+\]\+"\.js"', text):+ for chunk, checksum in re.findall(r'(\d+):"([0-9a-f]+)"', match[1]):+ reference = posixpath.join(posixpath.dirname(name), f"{chunk}.{checksum}.js")+ if reference not in paths:+ errors.append(f"动态分块缺失:{name} -> {reference}")+ for group in ("appearance", "guide"):+ if not any(name.startswith(group + "/") for name in paths):+ errors.append(f"缺少或为空的资源目录:{group}")+ if "appearance/langs/en.json" not in paths:+ errors.append("缺少语言文件:appearance/langs/en.json")+ for name, path in paths.items():+ if name.startswith("appearance/langs/") and name.endswith(".json"):+ json.loads(path.read_text(encoding="utf-8"))+ if "-" not in expected_version and not any(name.startswith(f"changelogs/v{expected_version}/") for name in paths):+ errors.append(f"缺少当前版本更新日志:v{expected_version}")+ return versions, errors+++def verify_package(package, baselines=None, sevenzip=None, version=None):+ with tempfile.TemporaryDirectory(prefix="siyuan-release-") as temp:+ layers = Unpacker(Path(temp), sevenzip).layers(package)+ kernels = kernel_files(layers)+ roots = resource_roots(layers)+ if not kernels and package.suffix.lower() == ".ipa":+ for layer in layers:+ for info in layer.glob("Payload/*.app/Info.plist"):+ metadata = plistlib.loads(info.read_bytes())+ executable = metadata.get("CFBundleExecutable", "")+ if executable and Path(executable).name == executable and (info.parent / executable).is_file():+ kernels.append(info.parent / executable)+ if not kernels:+ raise VerificationError("未找到可独立校验的内核;iOS 静态链接或加密内核需要另行验证")+ if len(roots) != 1:+ raise VerificationError(f"应找到一个完整前端资源目录,实际找到 {len(roots)} 个")+ kernel_hashes = sorted({digest(path) for path in kernels})+ actual = package_resources(layers, roots[0])+ if not baselines:+ expected = version+ if not expected:+ match = PACKAGE_VERSION.match(package.name)+ if not match:+ raise VerificationError("无法从包名确定发布版本,请指定 --version")+ expected = match[1]+ infos = [kernel_info(path) for path in kernels]+ errors = [f"内核版本不匹配:{info['name']} 为 {info['version']},预期 {expected}"+ for info in infos if info["version"] != expected]+ package_version = PACKAGE_VERSION.match(package.name)+ if package_version and package_version[1] != expected:+ errors.append(f"包名版本不匹配:{package_version[1]},预期 {expected}")+ mobile = package.suffix.lower() in {".apk", ".aab", ".hap", ".app", ".ipa"}+ for info in infos:+ if "-arm64" in package.name.lower() and info["architecture"] != "arm64":+ errors.append(f"内核架构与包名不匹配:{info['architecture']}")+ if package.suffix.lower() in {".apk", ".aab", ".hap", ".app"} and info["format"] != "ELF":+ errors.append(f"移动端内核格式不匹配:{info['format']}")+ for path, info in zip(kernels, infos):+ for abi, architecture in (("arm64-v8a", "arm64"), ("armeabi-v7a", "arm"), ("x86_64", "amd64"), ("x86", "386")):+ if abi in path.parts and info["architecture"] != architecture:+ errors.append(f"内核架构与 ABI 目录 {abi} 不匹配:{info['architecture']}")+ paths = resource_paths(layers, roots[0])+ frontend, frontend_errors = check_frontend(paths, expected, mobile)+ errors.extend(frontend_errors)+ metadata = roots[0] / "app/package.json"+ if metadata.is_file():+ actual_version = json.loads(metadata.read_text(encoding="utf-8")).get("version")+ if actual_version != expected:+ errors.append(f"桌面外壳版本不匹配:{actual_version},预期 {expected}")+ if errors:+ raise VerificationError("\n".join(errors[:40]))+ return {"target": ", ".join(f"{info['format']}/{info['architecture']}" for info in infos),+ "version": expected, "kernels": infos, "frontend_versions": frontend,+ "kernel_sha256": kernel_hashes, "resource_count": len(actual),+ "scope": "包内版本及可解析资源引用检查;不证明同版本产物为最新构建"}+ metadata = roots[0] / "app/package.json"+ if metadata.is_file():+ actual_version = json.loads(metadata.read_text(encoding="utf-8"))["version"]+ if actual_version != baselines[0]["version"]:+ raise VerificationError(f"桌面应用版本不匹配:{actual_version}")+ candidates = [b for b in baselines if b["kernels"] == kernel_hashes]+ if not candidates:+ raise VerificationError("内核与所有基准均不匹配:可能漏拷贝内核、选错架构,或缺少该平台基准;"+ + "SHA-256=" + ",".join(kernel_hashes))+ comparisons = [(b, compare_files(b["resources"], actual)) for b in candidates]+ for baseline, errors in comparisons:+ if not errors:+ return {"target": baseline["target"], "baseline": baseline["file"],+ "kernel_sha256": kernel_hashes, "resource_count": len(actual)}+ baseline, errors = min(comparisons, key=lambda pair: len(pair[1]))+ raise VerificationError(f"与基准 {baseline['target']} 比较,{len(errors)} 项资源不匹配:\n"+ + "\n".join(errors[:30]))+++def verify(args):+ folder = (args.directory or desktop_folder()).resolve()+ if not folder.is_dir():+ raise VerificationError(f"安装包目录不存在:{folder}")+ if args.report:+ args.report = args.report.resolve()+ if args.report.suffix.lower() != ".json" or args.report.exists():+ raise VerificationError("报告必须使用尚不存在的 .json 文件路径,避免覆盖已有文件")+ version = args.version+ paths = args.baseline or []+ packages = []+ unknown = []+ for path in sorted(folder.iterdir()):+ if path in paths or path == args.report:+ continue+ lower = path.name.lower()+ if lower in {"sha256sums.txt", "checksum.exe"} or lower.endswith(SIDECARS):+ continue+ if path.is_file() and lower.endswith(PACKAGES):+ packages.append(path)+ else:+ unknown.append(path.name)+ if not packages:+ raise VerificationError(f"没有安装包,不能判定通过:{folder}")+ if not version:+ versions = {match[1] for path in packages if (match := PACKAGE_VERSION.match(path.name))}+ if len(versions) != 1:+ raise VerificationError(f"包名中无法确定唯一发布版本:{sorted(versions)},请指定 --version")+ version = versions.pop()+ if not re.fullmatch(VERSION, version):+ raise VerificationError(f"无效版本号:{version}")+ baselines = load_baselines(paths, version)+ print(f"预期发布版本:{version};{'基准对比' if baselines else '直接检查安装包'}")+ report = {"version": version, "directory": str(folder), "unknown": unknown, "packages": []}+ failed = bool(unknown)+ for name in unknown:+ print(f"[FAIL] 未识别文件或目录:{name}")+ for package in packages:+ print(f"正在校验:{package.name}", flush=True)+ entry = {"name": package.name, "sha256": digest(package)}+ try:+ entry.update(verify_package(package, baselines, find_7z(args.sevenzip), version))+ entry["status"] = "PASS"+ detail = "摘要与基准一致" if baselines else "内核及前端版本检查通过"+ print(f"[PASS] {package.name}:{entry['target']},{detail},扫描 {entry['resource_count']} 个资源")+ except (VerificationError, OSError, ValueError, tarfile.TarError, zipfile.BadZipFile,+ subprocess.SubprocessError) as error:+ entry.update(status="FAIL", error=str(error))+ failed = True+ print(f"[FAIL] {package.name}:{error}")+ report["packages"].append(entry)+ if args.report:+ args.report.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")+ print(f"校验完成:{len(packages)} 个安装包,{'未通过' if failed else '全部通过'}")+ return 1 if failed else 0+++def main():+ for stream in (sys.stdout, sys.stderr):+ if hasattr(stream, "reconfigure"):+ stream.reconfigure(encoding="utf-8")+ parser = argparse.ArgumentParser(description=__doc__)+ sub = parser.add_subparsers(dest="command", required=True)+ check = sub.add_parser("check", help="校验目录中的所有安装包,默认桌面 siyuan 目录")+ check.add_argument("directory", nargs="?", type=Path)+ check.add_argument("--baseline", type=Path, action="append", help="可选,额外按可信基准比较完整摘要;通常无需使用")+ check.add_argument("--report", type=Path, help="写入 JSON 报告")+ baseline = sub.add_parser("baseline", help="从独立可信构建产物生成基准")+ baseline.add_argument("--resources", type=Path, required=True, help="包含 stage、appearance、guide、changelogs 的目录")+ baseline.add_argument("--kernel", type=Path, required=True, help="本次构建的内核文件、内核目录或 kernel.aar")+ baseline.add_argument("--target", required=True, help="平台及架构,例如 android-arm64、mac-arm64")+ baseline.add_argument("--output", type=Path, required=True, help="建议以 .release-baseline.json 结尾,不覆盖已有文件")+ for command in (check, baseline):+ command.add_argument("--version", help="预期发布版本;check 默认从包名推断,baseline 默认 app/package.json")+ command.add_argument("--sevenzip", help="7z 或 7zz 的可执行文件路径")+ args = parser.parse_args()+ try:+ if args.command == "baseline":+ create_baseline(args)+ return 0+ return verify(args)+ except (VerificationError, OSError, ValueError, KeyError) as error:+ print(f"[FAIL] {error}", file=sys.stderr)+ return 1+++if __name__ == "__main__":+ sys.exit(main())