Files
cutdex/tool/macos/check_macos_release.py
T
lingjhf 27e77fff39 feat: initial Cutdex application
Add the Flutter video editing application with project management, media
import, timeline editing, preview, AI assistance, diagnostics and settings.

Include shared UI and native host packages, platform runners, application
tests and release tooling.

Provide usage and contribution guides, the MIT license and third-party
notices. Exclude local credentials, build outputs and validation data.
2026-10-05 23:36:23 +08:00

116 lines
5.9 KiB
Python

"""Audit a relocatable arm64 macOS app or processing runtime, without models."""
import argparse
import json
import os
from pathlib import Path
import plistlib
import re
import struct
import subprocess
import tempfile
REQUIRED = (
'bin/cutdex-processing-worker', 'bin/ffmpeg', 'bin/ffprobe',
'workers/asr/cutdex-asr-worker', 'workers/audio/cutdex-audio-worker',
'workers/translation/cutdex-m2m100-worker',
)
def output(*args, **kwargs):
return subprocess.check_output(args, text=True, timeout=60, **kwargs)
def system(path):
return path.startswith(('/System/Library/', '/usr/lib/'))
def audit(root, app=False):
root = root.resolve()
runtime = root / 'Contents/Resources/processing' if app else root
for name in REQUIRED:
path = runtime / name
if not path.is_file() or not os.access(path, os.X_OK):
raise RuntimeError(f'Missing executable: {path}')
executable = runtime / REQUIRED[0]
if app:
info = plistlib.loads((root / 'Contents/Info.plist').read_bytes())
executable = root / 'Contents/MacOS' / info['CFBundleExecutable']
assets = root / 'Contents/Frameworks/App.framework/Resources/flutter_assets'
if not executable.is_file() or not assets.is_dir():
raise RuntimeError('Missing app executable or Flutter assets')
output('/usr/bin/codesign', '--verify', '--deep', '--strict', str(root))
# Check actual contents, not only the native files declared by a manifest.
native = {}
for path in root.rglob('*'):
if path.is_symlink() and not path.resolve().is_relative_to(root):
raise RuntimeError(f'Symlink escapes bundle: {path}')
if not path.is_file() or path.is_symlink():
continue
with path.open('rb') as stream:
magic = stream.read(4)
if magic not in (b'\xcf\xfa\xed\xfe', b'\xfe\xed\xfa\xcf', b'\xca\xfe\xba\xbe', b'\xbe\xba\xfe\xca'):
continue
arch = output('/usr/bin/lipo', '-archs', str(path)).strip().split()
if 'arm64' not in arch:
raise RuntimeError(f'Missing arm64 slice: {path}: {arch}')
commands = output('/usr/bin/otool', '-arch', 'arm64', '-l', str(path))
versions = re.findall(r'\bminos ([\d.]+)', commands)
versions += re.findall(r'LC_VERSION_MIN_MACOSX\s+cmdsize \d+\s+version ([\d.]+)', commands)
if not versions or any(tuple((list(map(int, v.split('.'))) + [0, 0])[:3]) > (14, 0, 0) for v in versions):
raise RuntimeError(f'Minimum macOS exceeds 14.0: {path}: {versions}')
rpaths = re.findall(r'LC_RPATH\s+cmdsize \d+\s+path (.*?) \(offset', commands)
for entry in rpaths:
if not system(entry) and not entry.startswith(('@loader_path/', '@executable_path/')):
raise RuntimeError(f'External runtime search path: {path}: {entry}')
imports = output('/usr/bin/otool', '-arch', 'arm64', '-L', str(path)).splitlines()[1:]
identity = output('/usr/bin/otool', '-arch', 'arm64', '-D', str(path)).splitlines()[1:]
native[path] = (rpaths, [line.strip().split(' (compatibility version')[0] for line in imports if line.strip().split(' (compatibility version')[0] not in identity])
if executable.resolve() not in native:
raise RuntimeError(f'Not a Mach-O executable: {executable}')
for path, (rpaths, dependencies) in native.items():
def expand(entry, owner):
return Path(entry.replace('@loader_path', str(owner.parent)).replace('@executable_path', str(executable.parent)))
search = [expand(p, path) for p in rpaths]
search += [expand(p, executable) for p in native[executable.resolve()][0]]
for dependency in dependencies:
if system(dependency):
continue
if dependency.startswith('@rpath/'):
candidates = [p / dependency[len('@rpath/'):] for p in search]
elif dependency.startswith(('@loader_path/', '@executable_path/')):
candidates = [expand(dependency, path)]
else:
raise RuntimeError(f'External native dependency: {path}: {dependency}')
if not any(p.resolve().is_relative_to(root) and p.is_file() for p in candidates):
raise RuntimeError(f'Unresolved bundled dependency: {path}: {dependency}')
with tempfile.TemporaryDirectory(prefix='cutdex-package-check-') as temporary:
env = {'PATH': '/usr/bin:/bin', 'HOME': temporary, 'TMPDIR': temporary}
descriptors = json.loads(output(str(runtime / REQUIRED[0]), '--capabilities', env=env))
operations = {op for d in descriptors if d['available'] for op in d['operations']}
if not {'transcribeAudio', 'translateSubtitles', 'separateVocals'}.issubset(operations):
raise RuntimeError('Bundled processing capabilities unavailable')
for name in REQUIRED[1:3]:
output(str(runtime / name), '-version', env=env)
for name in REQUIRED[3:5]:
output(str(runtime / name), '--self-test', env=env)
result = subprocess.check_output([str(runtime / REQUIRED[5]), '--self-test'], env=env, timeout=60)
payload = '你好\r\n\x1a!'.encode('utf-8')
if result != struct.pack('<I', len(payload)) + payload:
raise RuntimeError('Translation worker self-test failed')
return {'root': str(root), 'nativeFiles': len(native), 'operations': sorted(operations), 'modelsRequired': False}
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--app', type=Path)
group.add_argument('--runtime', type=Path)
parser.add_argument('--report', type=Path)
args = parser.parse_args()
result = audit(args.app or args.runtime, app=args.app is not None)
encoded = json.dumps(result, indent=2) + '\n'
if args.report:
args.report.write_text(encoded)
print(encoded, end='')