"""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('