#!/usr/bin/env python3 """Package the verified formal Dayu Color installation through the PKG Forge skill.""" import argparse import datetime import hashlib import json import os from pathlib import Path import plistlib import shutil import stat import subprocess import tempfile import xml.etree.ElementTree as ET import sys ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT / "tools")) from template_payload import template_files APP = Path("/Library/Plug-Ins/FxPlug/大鱼调色.app") CACHE = Path.home() / "Library/Caches/CodexBuilds/com.dayu.color" LOCK = Path.home() / ".codex/app-delivery-locks/com.dayu.color.lock" def run(*args, cwd=None): return subprocess.check_output(args, cwd=cwd, text=True, stderr=subprocess.STDOUT).strip() def history(profile, keychain): return json.loads(run("xcrun", "notarytool", "history", "--keychain-profile", profile, "--keychain", keychain, "--output-format", "json"))["history"] def check_bundle_access(entries): for path, mode in entries: if stat.S_ISLNK(mode): continue required = 0o555 if stat.S_ISDIR(mode) or mode & stat.S_IXUSR else 0o444 if mode & required != required: raise ValueError(f"普通用户无法读取或执行安装载荷:{path}({stat.S_IMODE(mode):04o})") def check_package_bundle_access(package): prefix = "." + str(APP) with tempfile.TemporaryDirectory(dir=CACHE) as scratch: expanded = Path(scratch) / "expanded" run("pkgutil", "--expand", str(package), str(expanded)) entries = {} for bom in expanded.glob("*.pkg/Bom"): for line in run("lsbom", "-p", "fm", str(bom)).splitlines(): path, mode = line.rsplit("\t", 1) if path == prefix or path.startswith(prefix + "/"): if not any(part.startswith("._") for part in Path(path).parts): entries[path] = int(mode, 8) if prefix not in entries: raise ValueError(f"安装载荷清单缺少正式 APP:{APP}") check_bundle_access(entries.items()) return len(entries) def prepare_resident_entry(skill, destination): """Reuse Forge core; add our resident wrapper to its normal-quit checks.""" runner = skill / "package_fxplug.py" entry = skill / "PackageFxPlug.swift" source = entry.read_text() anchor = " var hosts = ApplicationToClose.presets\n" assert source.count(anchor) == 1, "PKG 工坊入口变化,须重新核对常驻 APP 退出规则" replacement = anchor + """ for item in items where item.kind == .fxPlug { hosts.append(try ApplicationToClose.read(URL(fileURLWithPath: item.sourcePath))) } """ destination.mkdir() shutil.copy2(runner, destination / runner.name) (destination / entry.name).write_text(source.replace(anchor, replacement)) return dict(upstreamEntrySHA256=hashlib.sha256(entry.read_bytes()).hexdigest(), adaptedEntrySHA256=hashlib.sha256((destination / entry.name).read_bytes()).hexdigest(), requiredApplication="com.dayu.color") def check_resident_close(package): with tempfile.TemporaryDirectory(dir=CACHE) as scratch: expanded = Path(scratch) / "expanded" run("pkgutil", "--expand", str(package), str(expanded)) distribution = ET.parse(expanded / "Distribution") identifiers = [x.attrib.get("id") for x in distribution.findall(".//must-close/app")] assert "com.dayu.color" in identifiers, "安装器必须正常退出常驻主 APP" preinstalls = list(expanded.glob("*.pkg/Scripts/preinstall")) assert preinstalls and all("'com.dayu.color'" in p.read_text() for p in preinstalls) return dict(identifiers=identifiers, preinstallGuardCount=len(preinstalls), normalQuit=True) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--pkg-forge-repo", type=Path, default=Path.home() / "Documents/dayu-git/repositories/pkg-forge") parser.add_argument("--output-dir", type=Path, default=ROOT.parent / "发行包") parser.add_argument("--prepare-only", action="store_true") args = parser.parse_args() args.output_dir = args.output_dir.expanduser().resolve() forge = args.pkg_forge_repo.expanduser().resolve() skill = forge / "skills/pkg-forge/scripts" assert (skill / "package_fxplug.py").is_file(), "请指定含 pkg-forge 技能的 PKG 工坊 checkout" delivery = json.loads((ROOT / "verification/Delivery.json").read_text()) info = plistlib.loads((APP / "Contents/Info.plist").read_bytes()) assert delivery["path"] == str(APP) # Preparation only stages and validates inputs. Creating a distributable # package still requires completed host acceptance of the formal install. assert args.prepare_only or delivery["status"] == "verified", "正式安装尚未完成宿主验收" assert info["CFBundleIdentifier"] == "com.dayu.color" assert (info["CFBundleShortVersionString"], info["CFBundleVersion"]) == (delivery["version"], delivery["build"]) args.output_dir.mkdir(parents=True, exist_ok=True) CACHE.mkdir(parents=True, exist_ok=True) LOCK.parent.mkdir(parents=True, exist_ok=True) LOCK.mkdir() (LOCK / "owner.json").write_text(json.dumps(dict(PID=os.getpid(), cwd=str(ROOT), product="大鱼调色", phase="PKG packaging", started=datetime.datetime.now(datetime.timezone.utc).isoformat()))) stage = None try: check_bundle_access((path, path.lstat().st_mode) for path in [APP, *APP.rglob("*")]) source = APP / "Contents/Resources/FCP Templates" # Use a fresh staging directory, so historical files cannot leak into # the new payload or override the intended effect list. stage = Path(tempfile.mkdtemp(prefix="pkg-inputs-", dir=CACHE)) staged = stage / "大鱼调色" hashes = {} for reference, bundled, installed in template_files(): data = (source / bundled).read_bytes() assert data == (ROOT / "template" / reference).read_bytes(), installed target = staged / installed target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(data) target.chmod(0o644) if target.suffix == ".png": os.chflags(target, 2) hashes[str(installed)] = hashlib.sha256(data).hexdigest() keychain = str(Path.home() / "Library/Keychains/login.keychain-db") profile = "codex-dayu-notary-B3W25FX5H5" version = info["CFBundleShortVersionString"] manifest = dict(name="大鱼调色", output=str(args.output_dir / "大鱼调色.pkg"), identifierPrefix="com.dayu.color.installer", resources=[dict(source=str(APP)), dict(source=str(staged), destination="~/Movies/Motion Templates.localized/Effects.localized")], signing=dict(identity="Developer ID Installer: zhong luo (B3W25FX5H5)", profile=profile, keychain=keychain, notaryKeychain=keychain), appearance=dict(title="大鱼调色", subtitle="适用于 Final Cut Pro 与 Motion 的原生调色效果", badgeImage=str(ROOT / "design/dayu-color-app-icon-v1.png"), authorContact="https://dayu.media"), pages=dict(welcome="安装大鱼调色 " + version + ",包含原生 FxPlug 调色插件和 Final Cut Pro 效果入口。", readme="系统要求:macOS 14.6 或更高版本。本发行构建适用于 Apple Silicon Mac。\n\n安装内容:\n/Library/Plug-Ins/FxPlug/大鱼调色.app\n登录用户“影片/Motion Templates/Effects/大鱼调色”中的效果模板与预览图。\n\n重新打开 Final Cut Pro 后,在“效果 → 大鱼调色”中应用;Motion 中可选择原生滤镜。\n本安装包不包含用户自选 LUT、预设或媒体文件。\n\n公测诊断默认开启,可在主 APP 关闭。仅发送版本、系统环境、阶段耗时、资源使用与本产品崩溃/卡顿调用栈摘要到 dayu.media;不发送素材、预设或账号,保留30天。主 APP 启动时检查更新,新版由用户确认安装。", license="", conclusion="大鱼调色已安装。主 APP 自动注册插件,成功后保持运行。关闭窗口仍在后台收集已开启的诊断;菜单栏可重新打开或退出。请重开宿主并实际检查效果。")) manifest_path = CACHE / "dayu-color-package-manifest.json" manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n") adapter = stage / "forge-entry" adapter_record = prepare_resident_entry(skill, adapter) command = ["/usr/bin/python3", str(adapter / "package_fxplug.py"), "--repo", str(forge), "--manifest", str(manifest_path)] subprocess.run(command + ["--check"], check=True) if args.prepare_only: print("清单:" + str(manifest_path)) return before = {x["id"] for x in history(profile, keychain)} log_path = CACHE / "pkg-release-build.log" with log_path.open("w") as log: subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=True) package = args.output_dir / ("大鱼调色-" + version + ".pkg") verified_payload_entries = check_package_bundle_access(package) resident_close = check_resident_close(package) report_path = ROOT / "verification/Package.json" subprocess.run(["/usr/bin/python3", str(skill / "verify_fxplug_package.py"), "--manifest", str(manifest_path), "--package", str(package), "--report", str(report_path)], check=True) jobs = [x for x in history(profile, keychain) if x["id"] not in before and x["name"] == package.name] assert len(jobs) == 1, "安装包已生成,请核对公证 ID;不要重复提交同一包" job = json.loads(run("xcrun", "notarytool", "info", jobs[0]["id"], "--keychain-profile", profile, "--keychain", keychain, "--output-format", "json")) assert job["status"] == "Accepted" report = json.loads(report_path.read_text()) report.update(notarization=job, appCompiledSource=delivery["sourceCommit"], appBuild=info["CFBundleVersion"], packageBuilderRemote="https://dayu.media/git/dayu/pkg-forge.git", residentAppClosing=resident_close, packageEntryAdaptation=adapter_record, packageBuilderCommit=run("git", "rev-parse", "HEAD", cwd=forge), templateSHA256=hashes, payloadBundleAccess=dict(entries=verified_payload_entries, scope="Read/traverse modes for installer-owned app entries, from the package BOM"), installedAppHostAcceptance=delivery.get("hostVerification", "verification/HostLUTLoading.json"), installScope="本轮仅生成并验包,未再次执行系统安装;正式 APP 已有独立宿主验收。") report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n") print("正式安装包:" + str(package)) finally: if stage and not args.prepare_only: for preview in stage.rglob("*.png"): os.chflags(preview, 0) shutil.rmtree(stage) (LOCK / "owner.json").unlink() LOCK.rmdir() if __name__ == "__main__": main()