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.
This commit is contained in:
lingjhf committed 2026-10-05 23:36:23 +08:00
commit 27e77fff39
718 files changed
+183958

No files matched your search

+85
View File
@@ -0,0 +1,85 @@
#!/bin/bash
set -euo pipefail
if [ "$#" -eq 1 ] && { [ "$1" = "--help" ] || [ "$1" = "-h" ]; }; then
echo "Usage: $0 <processing-runtime-directory> [output-directory]"
exit 0
fi
if [[ $# -lt 1 || $# -gt 2 ]]; then
echo "Usage: $0 <processing-runtime-directory> [output-directory]" >&2
exit 2
fi
repo_root="$(cd "$(dirname "$0")/../.." && pwd)"
runtime_root="$(cd "$1" && pwd)"
output_root="${2:-$repo_root/dist/macos}"
signing_identity="${CUTDEX_CODESIGN_IDENTITY:--}"
python="${PYTHON:-python3}"
flutter="${FLUTTER:-flutter}"
app="$repo_root/build/macos/Build/Products/Release-production/cutdex.app"
resources="$app/Contents/Resources"
embedded_runtime="$resources/processing"
mkdir -p "$output_root"
output_root="$(cd "$output_root" && pwd)"
archive="$output_root/cutdex-macos14-arm64.zip"
dmg="$output_root/cutdex-macos14-arm64.dmg"
if [[ -n "${CUTDEX_NOTARY_PROFILE:-}" && "$signing_identity" == "-" ]]; then
echo "CUTDEX_NOTARY_PROFILE requires a Developer ID signing identity" >&2
exit 1
fi
if [[ -n "${CUTDEX_UPDATE_FEED_URL:-}${CUTDEX_UPDATE_PUBLIC_KEY:-}" ]]; then
if [[ -z "${CUTDEX_UPDATE_FEED_URL:-}" || -z "${CUTDEX_UPDATE_PUBLIC_KEY:-}" ]]; then
echo "Set both CUTDEX_UPDATE_FEED_URL and CUTDEX_UPDATE_PUBLIC_KEY" >&2
exit 1
fi
fi
# Fail before the Flutter build if a worker or a transitive library is missing.
"$python" "$repo_root/tool/macos/check_macos_release.py" --runtime "$runtime_root"
cd "$repo_root"
bash "$repo_root/tool/macos/check_macos_build_target.sh" "$app/Contents/MacOS/cutdex"
rm -rf "$embedded_runtime"
"$flutter" build macos --release --flavor production \
--split-debug-info=build/symbols/macos
mkdir -p "$resources" "$output_root"
ditto "$runtime_root" "$embedded_runtime"
if [[ -n "${CUTDEX_UPDATE_FEED_URL:-}" ]]; then
"$python" "$repo_root/tool/macos/macos_updates.py" configure --app "$app" \
--feed "$CUTDEX_UPDATE_FEED_URL" --public-key "$CUTDEX_UPDATE_PUBLIC_KEY"
fi
bash "$repo_root/tool/macos/sign_macos_app.sh" "$app"
"$python" "$repo_root/tool/macos/check_macos_release.py" --app "$app" \
--report "$output_root/package-check.json"
rm -f "$archive"
ditto -c -k --sequesterRsrc --keepParent "$app" "$archive"
if [[ -n "${CUTDEX_NOTARY_PROFILE:-}" ]]; then
xcrun notarytool submit "$archive" \
--keychain-profile "$CUTDEX_NOTARY_PROFILE" --wait
xcrun stapler staple "$app"
rm -f "$archive"
ditto -c -k --sequesterRsrc --keepParent "$app" "$archive"
fi
bash "$repo_root/tool/macos/create_macos_dmg.sh" "$app" "$dmg"
if [[ -n "${CUTDEX_NOTARY_PROFILE:-}" ]]; then
xcrun notarytool submit "$dmg" \
--keychain-profile "$CUTDEX_NOTARY_PROFILE" --wait
xcrun stapler staple "$dmg"
xcrun stapler validate "$dmg"
fi
echo "App: $app"
echo "Archive: $archive"
shasum -a 256 "$archive"
echo "DMG: $dmg"
shasum -a 256 "$dmg"
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
set -eu
if [ "$#" -eq 1 ] && { [ "$1" = "--help" ] || [ "$1" = "-h" ]; }; then
echo "Usage: $0 <app-executable>"
exit 0
fi
# Replacing native assets under a live Flutter process can load a second SQLite
# image on a later lazy FFI lookup, mixing its globals with existing handles.
# Check the exact build product, not other installed copies of the application.
if [ "$#" -ne 1 ]; then
echo 'usage: check_macos_build_target.sh <app-executable>' >&2
exit 2
fi
if /bin/ps -axo comm= | /usr/bin/grep -Fx -- "$1" >/dev/null; then
echo 'error: Cutdex is running from this build target. Save your edits and quit it (or stop the debugger), then rebuild. Hot reload does not require a native rebuild.' >&2
exit 1
fi
+115
View File
@@ -0,0 +1,115 @@
"""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='')
+61
View File
@@ -0,0 +1,61 @@
#!/bin/bash
set -euo pipefail
if [ "$#" -eq 1 ] && { [ "$1" = "--help" ] || [ "$1" = "-h" ]; }; then
echo "Usage: $0 <cutdex.app> <output.dmg>"
exit 0
fi
if [[ $# -ne 2 ]]; then
echo "Usage: $0 <cutdex.app> <output.dmg>" >&2
exit 2
fi
app="$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"
output="$2"
if [[ ! -f "$app/Contents/Info.plist" ]]; then
echo "Missing macOS application: $app" >&2
exit 1
fi
icon="$app/Contents/Resources/AppIcon.icns"
if [[ ! -f "$icon" ]]; then
echo "Missing application icon: $icon" >&2
exit 1
fi
if [[ "$output" != *.dmg ]]; then
echo "Output must have a .dmg extension: $output" >&2
exit 2
fi
mkdir -p "$(dirname "$output")"
output="$(cd "$(dirname "$output")" && pwd)/$(basename "$output")"
stage="$(mktemp -d "${TMPDIR:-/tmp}/cutdex-dmg.XXXXXX")"
source="$stage/source"
mount="$stage/mounted"
mounted=false
cleanup() {
if [[ "$mounted" == true ]]; then
hdiutil detach -quiet "$mount" || true
fi
rm -rf "$stage"
}
trap cleanup EXIT
mkdir "$source" "$mount"
ditto "$app" "$source/$(basename "$app")"
ln -s /Applications "$source/Applications"
ditto "$icon" "$source/.VolumeIcon.icns"
hdiutil create -quiet -format UDRW -volname Cutdex -srcfolder "$source" "$stage/uncompressed.dmg"
hdiutil attach -quiet -readwrite -nobrowse -mountpoint "$mount" "$stage/uncompressed.dmg"
mounted=true
xcrun SetFile -a C "$mount"
hdiutil detach -quiet "$mount"
mounted=false
hdiutil convert -quiet "$stage/uncompressed.dmg" -format UDZO -o "$output" -ov
hdiutil verify -quiet "$output"
swift "$(dirname "$0")/set_macos_file_icon.swift" "$icon" "$output"
echo "DMG: $output"
shasum -a 256 "$output"
+157
View File
@@ -0,0 +1,157 @@
#!/usr/bin/env python3
"""Configure Sparkle before signing and prepare full-only update publications."""
import argparse
import base64
from pathlib import Path
import plistlib
import re
import shutil
import subprocess
import tempfile
from urllib.parse import urlsplit
import xml.etree.ElementTree as ET
SPARKLE = 'http://www.andymatuschak.org/xml-namespaces/sparkle'
def validate_url(value, local=False):
url = urlsplit(value)
if not url.hostname or url.username or url.password or url.fragment or url.query:
raise ValueError('Use an absolute update URL without credentials, query or fragment')
if url.scheme != 'https' and not (
local and url.scheme == 'http' and url.hostname == 'localhost'
):
raise ValueError('Updates require HTTPS (local testing permits http://localhost only)')
return value
def validate_key(value):
if len(base64.b64decode(value, validate=True)) != 32:
raise ValueError('Sparkle requires a base64-encoded 32-byte public key')
return value
def configure(app, feed, public_key, local=False):
info_path = app / 'Contents/Info.plist'
info = plistlib.loads(info_path.read_bytes())
if local and info['CFBundleIdentifier'] != 'app.cutdex.desktop.dev':
raise ValueError('Local updates are restricted to the development app')
info['DeskupAllowLocalHTTP'] = bool(local)
info['SUFeedURL'] = validate_url(feed, local)
info['SUPublicEDKey'] = validate_key(public_key)
info['SUEnableAutomaticChecks'] = False
info['SUAllowsAutomaticUpdates'] = False
info['SUAutomaticallyUpdate'] = False
if local:
# Narrow ATS exception: no arbitrary network loads, never in production.
ats = info.setdefault('NSAppTransportSecurity', {})
ats.setdefault('NSExceptionDomains', {})['localhost'] = {
'NSExceptionAllowsInsecureHTTPLoads': True,
'NSIncludesSubdomains': False,
}
info_path.write_bytes(plistlib.dumps(info))
def validate_app(app, local=False):
info = plistlib.loads((app / 'Contents/Info.plist').read_bytes())
validate_url(info['SUFeedURL'], local)
validate_key(info['SUPublicEDKey'])
expected_id = 'app.cutdex.desktop.dev' if local else 'app.cutdex.desktop'
if info['CFBundleIdentifier'] != expected_id:
raise ValueError('Wrong application identity for this update channel')
if not re.fullmatch(r'[0-9]+(?:\.[0-9]+){0,2}', info['CFBundleVersion']):
raise ValueError('Use a monotonically increasing numeric build version')
framework = app / 'Contents/Frameworks/Sparkle.framework'
for file in ['Sparkle', 'Autoupdate', 'Updater.app/Contents/MacOS/Updater']:
if not (framework / file).is_file():
raise ValueError(f'Missing Sparkle component: {file}')
subprocess.run(['codesign', '--verify', '--deep', '--strict', str(app)], check=True)
if not local:
subprocess.run(['xcrun', 'stapler', 'validate', str(app)], check=True)
subprocess.run(['spctl', '--assess', '--type', 'execute', str(app)], check=True)
return info
def version_key(version):
if not re.fullmatch(r'[0-9]+(?:\.[0-9]+){0,2}', version):
raise ValueError(f'Invalid numeric build version: {version}')
parts = tuple(map(int, version.split('.')))
return parts + (0,) * (3 - len(parts))
def require_newer_build(output, version):
feed = output / 'appcast.xml'
if not feed.exists():
return
items = ET.parse(feed).findall('./channel/item')
for item in items:
current = item.findtext(f'{{{SPARKLE}}}version')
if current is None:
enclosure = item.find('enclosure')
current = None if enclosure is None else enclosure.get(f'{{{SPARKLE}}}version')
if current is None:
raise ValueError('Existing appcast item is missing its build version')
if version_key(version) <= version_key(current):
raise ValueError(f'New build {version} must be newer than published build {current}')
def publish(app, output, base_url, tools, key_file=None, local=False):
"""Stage a complete publication; never mutate an existing version archive."""
validate_url(base_url, local)
info = validate_app(app, local)
output.mkdir(parents=True, exist_ok=True)
require_newer_build(output, info['CFBundleVersion'])
filename = f"cutdex-{info['CFBundleVersion']}-macos-arm64.zip"
archive = output / filename
if archive.exists():
raise ValueError(f'Refusing to replace published archive: {archive}')
with tempfile.TemporaryDirectory(prefix='cutdex-update-') as directory:
stage = Path(directory)
subprocess.run(['ditto', '-c', '-k', '--sequesterRsrc', '--keepParent',
str(app), str(stage / filename)], check=True)
command = [str(tools / 'generate_appcast'), '--maximum-deltas', '0',
'--download-url-prefix', base_url.rstrip('/') + '/',
'-o', str(stage / 'appcast.xml')]
if key_file:
command.extend(['--ed-key-file', str(key_file)])
subprocess.run([*command, str(stage)], check=True)
tree = ET.parse(stage / 'appcast.xml')
if tree.findall(f'.//{{{SPARKLE}}}deltas'):
raise ValueError('This release pipeline only permits full updates')
enclosures = tree.findall('.//enclosure')
if len(enclosures) != 1 or not enclosures[0].get(f'{{{SPARKLE}}}edSignature'):
raise ValueError('Expected exactly one signed full update')
# Upload archive first, appcast last. Local replacement is atomic too.
shutil.copy2(stage / filename, archive)
pending = output / 'appcast.xml.pending'
shutil.copy2(stage / 'appcast.xml', pending)
pending.replace(output / 'appcast.xml')
return archive
def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest='command', required=True)
config = commands.add_parser('configure')
config.add_argument('--app', type=Path, required=True)
config.add_argument('--feed', required=True)
config.add_argument('--public-key', required=True)
config.add_argument('--local', action='store_true')
release = commands.add_parser('publish')
release.add_argument('--app', type=Path, required=True)
release.add_argument('--output', type=Path, required=True)
release.add_argument('--base-url', required=True)
release.add_argument('--tools', type=Path, required=True, help='Sparkle bin directory')
release.add_argument('--key-file', type=Path)
release.add_argument('--local', action='store_true')
args = parser.parse_args()
if args.command == 'configure':
configure(args.app, args.feed, args.public_key, args.local)
else:
print(publish(args.app, args.output, args.base_url, args.tools.resolve(),
args.key_file, args.local))
if __name__ == '__main__':
main()
+19
View File
@@ -0,0 +1,19 @@
import AppKit
import Foundation
let arguments = Array(CommandLine.arguments.dropFirst())
let usage = "Usage: swift set_macos_file_icon.swift <icon-file> <target-file>\n"
if arguments == ["--help"] || arguments == ["-h"] {
print(usage, terminator: "")
exit(0)
}
guard arguments.count == 2 else {
fputs(usage, stderr)
exit(2)
}
guard FileManager.default.fileExists(atPath: arguments[1]),
let icon = NSImage(contentsOfFile: arguments[0]),
NSWorkspace.shared.setIcon(icon, forFile: arguments[1], options: []) else {
fputs("Failed to set file icon: verify the icon and target paths\n", stderr)
exit(1)
}
+44
View File
@@ -0,0 +1,44 @@
#!/bin/bash
set -euo pipefail
if [ "$#" -eq 1 ] && { [ "$1" = "--help" ] || [ "$1" = "-h" ]; }; then
echo "Usage: $0 <app-bundle>"
exit 0
fi
if [[ $# != 1 ]]; then
echo "Usage: $0 <app-bundle>" >&2
exit 2
fi
repo_root="$(cd "$(dirname "$0")/../.." && pwd)"
app="$1"
signing_identity="${CUTDEX_CODESIGN_IDENTITY:--}"
# Flutter's prebuilt engine carries an unused Homebrew search path. Remove it
# from our copy before signing; the audit rejects any remaining external paths.
engine="$app/Contents/Frameworks/FlutterMacOS.framework/Versions/A/FlutterMacOS"
if /usr/bin/otool -l "$engine" | grep -F 'path /usr/local/lib/. (offset' >/dev/null; then
/usr/bin/install_name_tool -delete_rpath /usr/local/lib/. "$engine"
fi
codesign_args=(--force --sign "$signing_identity")
if [[ "$signing_identity" == "-" ]]; then
codesign_args+=(--timestamp=none)
else
codesign_args+=(--timestamp --options runtime)
fi
while IFS= read -r binary; do
if file "$binary" | grep -q 'Mach-O'; then
codesign "${codesign_args[@]}" --preserve-metadata=entitlements "$binary"
fi
done < <(find "$app/Contents" -type f -print | sort)
# Every nested bundle must use the same identity as the outer app. Mixing the
# Xcode development signature with an ad-hoc or Developer ID signature causes
# dyld to reject FlutterMacOS.framework on a clean launch.
while IFS= read -r bundle; do
codesign "${codesign_args[@]}" --preserve-metadata=entitlements "$bundle"
done < <(find "$app/Contents" -type d \( \
-name '*.framework' -o -name '*.appex' -o -name '*.xpc' -o -name '*.app' \
\) -print | awk '{ print length, $0 }' | sort -rn | cut -d' ' -f2-)
codesign "${codesign_args[@]}" \
--entitlements "$repo_root/macos/Runner/Release.entitlements" "$app"
+44
View File
@@ -0,0 +1,44 @@
// Local simulation only. Creates an isolated key file; never touches Keychain.
import CryptoKit
import Foundation
let arguments = Array(CommandLine.arguments.dropFirst())
let usage = "Usage: swift sparkle_test_key.swift <test-key-directory>\n"
if arguments == ["--help"] || arguments == ["-h"] {
print(usage, terminator: "")
exit(0)
}
guard arguments.count == 1 else {
fputs(usage, stderr)
exit(2)
}
do {
let directory = URL(fileURLWithPath: arguments[0], isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true,
attributes: [.posixPermissions: 0o700])
let privateURL = directory.appendingPathComponent("private.key")
let key: Curve25519.Signing.PrivateKey
if FileManager.default.fileExists(atPath: privateURL.path) {
let encoded = try String(contentsOf: privateURL, encoding: .utf8)
guard let data = Data(base64Encoded: encoded) else {
fputs("Invalid test key file\n", stderr)
exit(1)
}
key = try Curve25519.Signing.PrivateKey(rawRepresentation: data)
} else {
key = Curve25519.Signing.PrivateKey()
guard FileManager.default.createFile(atPath: privateURL.path,
contents: key.rawRepresentation.base64EncodedData(),
attributes: [.posixPermissions: 0o600]) else {
fputs("Could not write test key file\n", stderr)
exit(1)
}
}
try key.publicKey.rawRepresentation.base64EncodedString().write(
to: directory.appendingPathComponent("public.key"), atomically: true, encoding: .utf8)
} catch {
// Do not print private key contents in diagnostics.
fputs("Could not create or read test key files\n", stderr)
exit(1)
}
+56
View File
@@ -0,0 +1,56 @@
"""Fault injection against a real extracted runtime; never modifies the source."""
import argparse
import importlib.util
from pathlib import Path
import shutil
import subprocess
import tempfile
spec = importlib.util.spec_from_file_location('release_check', Path(__file__).with_name('check_macos_release.py'))
check = importlib.util.module_from_spec(spec)
spec.loader.exec_module(check)
def rejected(root, expected):
try:
check.audit(root)
except RuntimeError as error:
if expected not in str(error):
raise
print(f'Correctly rejected: {expected}')
else:
raise AssertionError(f'Did not reject: {expected}')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--runtime', type=Path, required=True)
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix='cutdex-audit-faults-') as temporary:
root = Path(temporary) / 'runtime'
shutil.copytree(args.runtime, root, symlinks=True)
worker = root / 'workers/asr/cutdex-asr-worker'
held = worker.with_suffix('.held')
worker.rename(held)
rejected(root, 'Missing executable')
held.rename(worker)
# Use the actual package's version instead of pinning FFmpeg's ABI.
library = next((root / 'lib').glob('libavcodec.*.dylib'))
saved = Path(temporary) / library.name
library.rename(saved)
rejected(root, 'Unresolved bundled dependency')
saved.rename(library)
link = root / 'external-library'
link.symlink_to('/usr/lib')
rejected(root, 'Symlink escapes bundle')
link.unlink()
backup = Path(temporary) / 'asr-backup'
shutil.copy2(worker, backup)
subprocess.run(['/usr/bin/install_name_tool', '-add_rpath', '/tmp/developer-libraries', str(worker)], check=True)
rejected(root, 'External runtime search path')
shutil.copy2(backup, worker)
print(check.audit(root))
if __name__ == '__main__':
main()
+82
View File
@@ -0,0 +1,82 @@
"""Build and relocate a Release smoke app; exercise no-model and configured-model startup.
The JSON config supplies WHISPER_SOURCE, M2M100_SOURCE, MELBAND_SOURCE and
CUTDEX_ASR_FIXTURE. Models are copied into the app-managed resource layout.
Run build_macos_release.sh afterwards to produce the normal application.
"""
import argparse
import json
import os
import shutil
from pathlib import Path
import subprocess
import tempfile
def run(command, **kwargs):
subprocess.run(list(map(str, command)), check=True, timeout=900, **kwargs)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--runtime', type=Path, required=True)
parser.add_argument('--config', type=Path, required=True)
parser.add_argument('--report', type=Path, required=True)
args = parser.parse_args()
repo = Path(__file__).resolve().parents[2]
config = json.loads(args.config.read_text())
model_keys = ['WHISPER_SOURCE', 'M2M100_SOURCE', 'MELBAND_SOURCE']
for key in model_keys + ['CUTDEX_ASR_FIXTURE']:
if not Path(config[key]).is_absolute() or not Path(config[key]).exists():
raise ValueError(f'Missing absolute input path: {key}')
runtime = args.runtime.resolve()
run([os.environ.get('FLUTTER', 'flutter'), 'build', 'macos', '--release',
'--flavor=production', '--target=tool/testing/release_smoke.dart'], cwd=repo)
with tempfile.TemporaryDirectory(prefix='cutdex relocated release ') as temporary:
root = Path(temporary)
app = root / 'cutdex.app'
run(['/usr/bin/ditto', repo / 'build/macos/Build/Products/Release-production/cutdex.app', app])
# A previous release build may have embedded a different runtime.
embedded = app / 'Contents/Resources/processing'
if embedded.exists():
shutil.rmtree(embedded)
run(['/usr/bin/ditto', runtime, embedded])
run(['/bin/bash', repo / 'tool/macos/sign_macos_app.sh', app])
run([os.environ.get('PYTHON', 'python3'), repo / 'tool/macos/check_macos_release.py', '--app', app])
results = []
for configured in [False, True]:
home = root / ('with-models' if configured else 'without-models')
home.mkdir()
report = home / 'result.json'
env = {'PATH': '/usr/bin:/bin', 'HOME': str(home), 'TMPDIR': str(home),
'CUTDEX_SMOKE_REPORT': str(report), 'CUTDEX_SMOKE_MODELS': str(int(configured)),
'CUTDEX_SMOKE_MEDIA': config['CUTDEX_ASR_FIXTURE']}
# No CUTDEX_PROCESSING_ROOT: exercise the executable-relative Bundle default.
if configured:
processing = home / 'Documents/Cutdex/Resources/Processing'
shutil.copytree(config['WHISPER_SOURCE'],
processing / 'Transcription/whisper-turbo/1')
shutil.copytree(config['M2M100_SOURCE'],
processing / 'Translation/m2m100-418m/1')
vocals = processing / 'VocalSeparation/melband/1'
vocals.mkdir(parents=True)
shutil.copy2(config['MELBAND_SOURCE'], vocals / 'melband.pt')
with (home / 'app.log').open('w') as log:
try:
run([app / 'Contents/MacOS/cutdex'], env=env, stdout=log, stderr=subprocess.STDOUT)
except Exception:
print((home / 'app.log').read_text())
if report.exists():
print(report.read_text())
raise
result = json.loads(report.read_text())
if not result['passed']:
raise RuntimeError(result)
results.append(result)
args.report.parent.mkdir(parents=True, exist_ok=True)
args.report.write_text(json.dumps(results, indent=2) + '\n')
print('Release smoke passed: no models; three configured capabilities and real translation.')
if __name__ == '__main__':
main()
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""Prepare two development apps and serve a signed full update on localhost."""
import argparse
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
import os
from pathlib import Path
import plistlib
import subprocess
from macos_updates import configure, publish
class UpdateHandler(SimpleHTTPRequestHandler):
def end_headers(self):
self.send_header('Cache-Control', 'no-store')
super().end_headers()
def list_directory(self, path):
self.send_error(404)
return None
def prepare(source, root, tools, port):
repository = Path(__file__).resolve().parents[2]
root = root.resolve()
public = root / 'public'
keys = root / 'keys'
if (root / 'installed').exists() or public.exists():
raise ValueError('Use a fresh output directory to preserve existing test installs')
subprocess.run(['swift', str(repository / 'tool/macos/sparkle_test_key.swift'), str(keys)], check=True)
public_key = (keys / 'public.key').read_text()
feed = f'http://localhost:{port}/appcast.xml'
info = plistlib.loads((source / 'Contents/Info.plist').read_bytes())
if info['CFBundleIdentifier'] != 'app.cutdex.desktop.dev':
raise ValueError('Build with --flavor development first')
for folder, version in [('installed', '900001'), ('candidate', '900002')]:
app = root / folder / 'cutdex.app'
app.parent.mkdir(parents=True)
subprocess.run(['ditto', str(source), str(app)], check=True)
path = app / 'Contents/Info.plist'
bundle = plistlib.loads(path.read_bytes())
bundle['CFBundleVersion'] = version
path.write_bytes(plistlib.dumps(bundle))
configure(app, feed, public_key, local=True)
subprocess.run(['bash', str(repository / 'tool/macos/sign_macos_app.sh'), str(app)],
env={**os.environ, 'CUTDEX_CODESIGN_IDENTITY': '-'}, check=True)
publish(root / 'candidate/cutdex.app', public, f'http://localhost:{port}',
tools.resolve(), keys / 'private.key', local=True)
print(f'Open: {root / "installed/cutdex.app"}', flush=True)
print('Settings → Check for updates: 900001 → 900002 (full ZIP)', flush=True)
return public
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--app', type=Path, help='Built development app')
parser.add_argument('--tools', type=Path, help='Sparkle bin directory')
parser.add_argument('--output', type=Path, default=Path('.local/update-test'))
parser.add_argument('--port', type=int, default=8765)
parser.add_argument('--serve-only', action='store_true')
args = parser.parse_args()
if args.serve_only:
public = args.output.resolve() / 'public'
else:
if not args.app or not args.tools:
parser.error('--app and --tools are required unless --serve-only')
public = prepare(args.app, args.output, args.tools, args.port)
if not (public / 'appcast.xml').is_file():
parser.error('No prepared appcast.xml')
# Only public artifacts are served. Private keys live outside this root.
server = ThreadingHTTPServer(('127.0.0.1', args.port),
partial(UpdateHandler, directory=str(public)))
print(f'Serving http://localhost:{args.port}/appcast.xml', flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
if __name__ == '__main__':
main()
+82
View File
@@ -0,0 +1,82 @@
"""Release channel isolation and full update validation regression tests."""
import base64
from pathlib import Path
import plistlib
import tempfile
import unittest
from unittest.mock import patch
from macos_updates import configure, validate_url, publish, SPARKLE
class UpdateConfigurationTests(unittest.TestCase):
def test_production_rejects_local_feed(self):
with self.assertRaises(ValueError):
validate_url('http://localhost:8765/appcast.xml')
with self.assertRaises(ValueError):
validate_url('http://example.com/appcast.xml', local=True)
with self.assertRaises(ValueError):
validate_url('https://user:password@example.com/appcast.xml')
def test_local_configuration_is_scoped_to_development(self):
with tempfile.TemporaryDirectory() as directory:
app = Path(directory) / 'cutdex.app'
(app / 'Contents').mkdir(parents=True)
path = app / 'Contents/Info.plist'
key = base64.b64encode(bytes(range(32))).decode()
original = {'CFBundleIdentifier': 'app.cutdex.desktop'}
path.write_bytes(plistlib.dumps(original))
with self.assertRaises(ValueError):
configure(app, 'http://localhost:8765/appcast.xml', key, local=True)
self.assertEqual(plistlib.loads(path.read_bytes()), original)
original['CFBundleIdentifier'] += '.dev'
path.write_bytes(plistlib.dumps(original))
configure(app, 'http://localhost:8765/appcast.xml', key, local=True)
info = plistlib.loads(path.read_bytes())
self.assertFalse(info['SUAllowsAutomaticUpdates'])
self.assertFalse(info['SUEnableAutomaticChecks'])
self.assertNotIn('NSAllowsArbitraryLoads', info['NSAppTransportSecurity'])
self.assertEqual(set(info['NSAppTransportSecurity']['NSExceptionDomains']), {'localhost'})
def test_invalid_public_key_does_not_change_app(self):
with tempfile.TemporaryDirectory() as directory:
app = Path(directory)
(app / 'Contents').mkdir()
path = app / 'Contents/Info.plist'
original = plistlib.dumps({'CFBundleIdentifier': 'app.cutdex.desktop'})
path.write_bytes(original)
with self.assertRaises(ValueError):
configure(app, 'https://updates.example.com/appcast.xml', 'YQ==')
self.assertEqual(path.read_bytes(), original)
class PublicationVersionTests(unittest.TestCase):
def test_older_or_equivalent_build_cannot_replace_current_feed(self):
for current, candidate in [('900002', '900001'), ('2', '2.0'), ('2.10', '2.9')]:
with self.subTest(current=current, candidate=candidate), tempfile.TemporaryDirectory() as directory:
output = Path(directory)
feed = output / 'appcast.xml'
original = (f'<rss xmlns:sparkle="{SPARKLE}"><channel><item>'
f'<sparkle:version>{current}</sparkle:version>'
'</item></channel></rss>').encode()
feed.write_bytes(original)
def generate(command, **kwargs):
if command[0] == 'ditto':
Path(command[-1]).write_bytes(b'archive')
else:
Path(command[command.index('-o') + 1]).write_text(
f'<rss xmlns:sparkle="{SPARKLE}"><channel><item>'
f'<sparkle:version>{candidate}</sparkle:version>'
'<enclosure sparkle:edSignature="test-signature"/>'
'</item></channel></rss>')
with patch('macos_updates.validate_app', return_value={'CFBundleVersion': candidate}), \
patch('macos_updates.subprocess.run', side_effect=generate) as run:
with self.assertRaisesRegex(ValueError, 'newer'):
publish(Path('app'), output, 'https://example.com/', Path('tools'))
run.assert_not_called()
self.assertEqual(feed.read_bytes(), original)
self.assertEqual(list(output.glob('*.zip')), [])
if __name__ == '__main__':
unittest.main()