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
+15 -8
View File
@@ -17,7 +17,7 @@ CORE = sorted(str(p.relative_to(ROOT)) for folder in ("Models", "Monitors", "Ser
for p in (ROOT / "kymo/Core" / folder).glob("*.swift"))
CHECKS = {name: list(CORE) for name in (
"SamplingChecks", "SamplingIntervalChecks", "UnifiedPanelChecks", "MemoryChecks",
"GPUStatisticsChecks", "StageCChecks", "MachPortChecks")}
"GPUStatisticsChecks", "StageCChecks", "MachPortChecks", "ReleaseServiceChecks")}
CHECKS.update({
"ProcessEnergyChecks": ["kymo/Core/Models/ProcessMetrics.swift", "kymo/Core/Models/ProcessEnergy.swift", "kymo/Core/Monitors/ProcessEnergyMonitor.swift"],
"ProcessEnergyReaderChecks": ["kymo/Core/Models/ProcessMetrics.swift", "kymo/Core/Models/ProcessEnergy.swift", "SMARTService/ProcessEnergyReader.swift"],
@@ -60,6 +60,7 @@ CHECKS.update({
})
GUI = {"NativeMetricDrawingChecks", "NativeProcessTableChecks", "LanguageScopeChecks", "SettingsWindowChecks", "PanelWindowChecks"}
NETWORK = {"SandboxNetworkChecks"}
SERVICES = {"ReleaseServiceChecks"}
def run(command, *, timeout=120):
@@ -83,7 +84,7 @@ def entitlements(app):
return value
def test_bundle(work, name, executable, host_entitlements=None, resources=None):
def test_bundle(work, name, executable, host_entitlements=None, resources=None, service=None):
app = work / (name + ".app")
contents = app / "Contents"
(contents / "MacOS").mkdir(parents=True)
@@ -95,7 +96,11 @@ def test_bundle(work, name, executable, host_entitlements=None, resources=None):
}))
if resources:
shutil.copytree(resources, contents / "Resources")
if service:
shutil.copytree(service, contents / "XPCServices/SMARTService.xpc")
command = ["codesign", "--force", "--sign", "-"]
if service:
command += ["--options", "runtime"]
if host_entitlements:
path = work / "network.entitlements"
path.write_bytes(plistlib.dumps(host_entitlements))
@@ -122,6 +127,7 @@ def main():
parser.add_argument("--app", type=Path, help="Use an already built app instead of building")
parser.add_argument("--configuration", choices=["Debug", "Release"], default="Debug")
parser.add_argument("--gui", action="store_true", help="Also launch temporary native test apps")
parser.add_argument("--services", action="store_true", help="Test packaged XPC in a temporary hardened sandbox host")
parser.add_argument("--network", action="store_true", help="Also make a real sandboxed HTTPS request")
parser.add_argument("--only", nargs="+", choices=sorted(CHECKS), help="Run selected Swift checks")
parser.add_argument("--list", action="store_true")
@@ -131,16 +137,16 @@ def main():
parser.error("Checks missing from runner: " + ", ".join(sorted(unknown)))
if args.list:
for name in sorted(CHECKS):
print(name + (" [GUI]" if name in GUI else " [network]" if name in NETWORK else ""))
print(name + (" [GUI]" if name in GUI else " [network]" if name in NETWORK else "") + (" [services]" if name in SERVICES else ""))
return
requested = args.only or list(CHECKS)
selected = []
for name in requested:
disabled = (name in GUI and not args.gui) or (name in NETWORK and not args.network)
disabled = (name in GUI and not args.gui) or (name in NETWORK and not args.network) or (name in SERVICES and not args.services)
if disabled and args.only:
parser.error(f"{name} requires {'--gui' if name in GUI else '--network'}")
parser.error(f"{name} requires {'--gui' if name in GUI else '--services' if name in SERVICES else '--network'}")
if disabled:
print(f"SKIP: {name} (opt-in {'--gui' if name in GUI else '--network'})", flush=True)
print(f"SKIP: {name} (opt-in {'--gui' if name in GUI else '--services' if name in SERVICES else '--network'})", flush=True)
else:
selected.append(name)
with tempfile.TemporaryDirectory(prefix="kymo-checks-") as temp:
@@ -188,8 +194,9 @@ def main():
print(text.strip(), flush=True)
if "PASS:" not in text:
raise RuntimeError(f"{name} did not report success\n" + (error.read_text() if error.exists() else ""))
elif name in NETWORK or name == "NetworkAddressChecks":
bundle = test_bundle(work, name, executable, host_entitlements)
elif name in NETWORK or name in SERVICES or name == "NetworkAddressChecks":
service = app / "Contents/XPCServices/SMARTService.xpc" if name in SERVICES else None
bundle = test_bundle(work, name, executable, host_entitlements, service=service)
try:
run([bundle / "Contents/MacOS" / name], timeout=15)
finally:
+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))