build(release): 加固主程序并生成可校验的免费测试包

This commit is contained in:
2026-11-04 21:52:59 +08:00
parent c24aa4b999
commit 630448986d
11 changed files with 197 additions and 10 deletions
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""Build and verify a local ad-hoc Release ZIP; does not publish or notarize."""
import argparse
import hashlib
from pathlib import Path
import plistlib
import shutil
import subprocess
import tempfile
import zipfile
ROOT = Path(__file__).resolve().parents[1]
def run(command):
result = subprocess.run([str(v) for v in command], cwd=ROOT, capture_output=True)
if result.returncode:
raise RuntimeError(result.stdout.decode(errors="replace")[-5000:] + result.stderr.decode(errors="replace")[-5000:])
return result
def verify(app):
run(["codesign", "--verify", "--deep", "--strict", app])
for target in [app, app / "Contents/XPCServices/SMARTService.xpc"]:
details = run(["codesign", "-dvvv", target]).stderr.decode()
if "Signature=adhoc" not in details or "runtime)" not in details:
raise RuntimeError("Expected ad-hoc signature with Hardened Runtime: " + str(target))
signed = run(["codesign", "-d", "--entitlements", "-", "--xml", target])
entitlements = plistlib.loads(signed.stdout)
expected = {"com.apple.security.app-sandbox": True,
"com.apple.security.network.client": True,
"com.apple.security.files.user-selected.read-only": True} if target == app else {}
if entitlements != expected:
raise RuntimeError("Unexpected release entitlements: " + str(target))
for path in app.rglob("*"):
if path.name in {".DS_Store", ".git", "xcuserdata"} or path.suffix in {".swift", ".xcstrings", ".md", ".py", ".dSYM"}:
raise RuntimeError("Development file in application: " + str(path))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, default=ROOT / "dist", help="Output directory (existing ZIPs are preserved)")
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix="kymo-release-") as temp:
work = Path(temp)
print("Building ordinary ad-hoc Release…", flush=True)
run(["xcodebuild", "-project", "kymo.xcodeproj", "-scheme", "kymo", "-configuration", "Release",
"-derivedDataPath", work / "build", "SWIFT_EMIT_LOC_STRINGS=NO", "SWIFT_ACTIVE_COMPILATION_CONDITIONS=",
"CODE_SIGN_IDENTITY=-", "build"])
app = work / "build/Build/Products/Release/kymo.app"
verify(app)
info = plistlib.loads((app / "Contents/Info.plist").read_bytes())
architectures = run(["lipo", "-archs", app / "Contents/MacOS/kymo"]).stdout.decode().strip().replace(" ", "-")
name = "kymo-{}-{}-{}-adhoc.zip".format(info["CFBundleShortVersionString"], info["CFBundleVersion"], architectures)
package = work / name
run(["ditto", "-c", "-k", "--keepParent", "--norsrc", "--noextattr", app, package])
with zipfile.ZipFile(package) as archive:
if any(not item.filename.startswith("kymo.app/") or ".." in Path(item.filename).parts
or item.filename.startswith("/") for item in archive.infolist()):
raise RuntimeError("Unexpected archive contents")
unpacked = work / "unpacked"
run(["ditto", "-x", "-k", package, unpacked])
verify(unpacked / "kymo.app")
output = args.output.expanduser().resolve()
output.mkdir(parents=True, exist_ok=True)
destination = output / name
checksum = output / (name + ".sha256")
if destination.exists() or checksum.exists():
raise RuntimeError("Output already exists; choose another --output directory")
digest = hashlib.sha256(package.read_bytes()).hexdigest()
shutil.copy2(package, destination)
checksum.write_text(digest + " " + name + "\n")
print("PASS: original and extracted app signatures, runtime, entitlements and archive contents")
print("Minimum macOS:", info.get("LSMinimumSystemVersion"), "architectures:", architectures)
print("ZIP:", destination, "bytes:", destination.stat().st_size)
print("SHA256:", digest)
print("Not notarized; not verified under default Gatekeeper policy on another Mac.")
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error:
raise SystemExit(str(error))