PulseCanvas / app · pulsecanvas.ai / scripts / preset-provenance.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Generate pinned provenance; verify exact app/source subsets without inferring licenses.""" |
| 3 | import argparse |
| 4 | import hashlib |
| 5 | import io |
| 6 | import json |
| 7 | import pathlib |
| 8 | import plistlib |
| 9 | import re |
| 10 | import subprocess |
| 11 | import tarfile |
| 12 | import tempfile |
| 13 | |
| 14 | REPO = pathlib.Path(__file__).resolve().parents[1] |
| 15 | RESOURCE = pathlib.Path('Sources/PulseCanvas/Resources/ProjectM') |
| 16 | PRESET_COMMIT = '0180df21f5e0bd39b9060cc5de420ed2f1f9e509' |
| 17 | TEXTURE_COMMIT = '6368812f27bc747b517218fbf89d21d59afce4d9' |
| 18 | CREDIT = 'Cream of the Crop pack curated by ISOSCELES' |
| 19 | CREDIT_URL = 'https://www.patreon.com/posts/pack-nestdrop-91682111' |
| 20 | NOTICE_PATTERN = re.compile( |
| 21 | r'copyright|\blicen[cs]e\b|\bpermission\b|\battribution\b|\bauthor\b|' |
| 22 | r'\bcreator\b|\bcredits?\b|all rights reserved|public domain|' |
| 23 | r'\b(?:MIT|BSD|LGPL|GPL|SPDX|CC-BY)\b|creative commons|redistribut|' |
| 24 | r'commercial|https?://|www\.|©|created by|written by', re.IGNORECASE) |
| 25 | MANIFESTS = ['preset-manifest.json', 'preset-notices.json', 'texture-manifest.json'] |
| 26 | CURATION_FILE = 'preset-curation.json' |
| 27 | ADMISSIONS_FILE = 'preset-admissions.json' |
| 28 | |
| 29 | |
| 30 | def receipt_files(root): |
| 31 | return [name for name in [CURATION_FILE, ADMISSIONS_FILE] if (root / name).exists()] |
| 32 | |
| 33 | |
| 34 | def verify_admissions(root, manifest, current, removed, retired): |
| 35 | path = root / ADMISSIONS_FILE |
| 36 | if not path.exists(): |
| 37 | require('admissionsSHA256' not in manifest, 'Missing admissions receipt') |
| 38 | return 0 |
| 39 | require(manifest.get('admissionsSHA256') == digest(path.read_bytes()), 'Admissions receipt differs') |
| 40 | receipt = json.loads(path.read_text()) |
| 41 | require(receipt['schemaVersion'] == 1 and receipt['upstreamCommit'] == PRESET_COMMIT, 'Wrong admissions pin') |
| 42 | admitted = receipt['presets'] |
| 43 | ids = {x['id'] for x in admitted} |
| 44 | require(len(ids) == len(admitted), 'Duplicate admitted identity') |
| 45 | require(ids <= current and ids.isdisjoint(removed | retired), 'Admissions conflict with curation or retirement') |
| 46 | for entry in admitted: |
| 47 | require(entry['id'] == 'projectm:' + entry['path'], 'Admitted upstream identity changed') |
| 48 | path = pathlib.PurePosixPath(entry['path']) |
| 49 | require(not path.is_absolute() and '..' not in path.parts, 'Unsafe admission path') |
| 50 | require(entry.get('visualInspectionApproved') is True, 'Missing visual admission inspection') |
| 51 | checks = entry['checks'] |
| 52 | require(all(x['id'] == entry['id'] for x in checks), 'Admission check identity differs') |
| 53 | require({(x['width'], x['height']) for x in checks}.issuperset({(1920, 1080), (1080, 1920)}), 'Missing full-HD admission checks') |
| 54 | require(all(x['passed'] is True and x['frames'] >= 360 and x['soundtrackPCM'] is True for x in checks), 'Unverified admitted preset') |
| 55 | require(digest((root / 'Presets' / entry['path']).read_bytes()) == entry['sha256'], 'Admitted bytes changed') |
| 56 | return len(ids) |
| 57 | |
| 58 | |
| 59 | def digest(data): |
| 60 | return hashlib.sha256(data).hexdigest() |
| 61 | |
| 62 | |
| 63 | def require(condition, message): |
| 64 | if not condition: |
| 65 | raise ValueError(message) |
| 66 | |
| 67 | |
| 68 | def scan_notices(root, entries): |
| 69 | notices = [] |
| 70 | for entry in entries: |
| 71 | raw = (root / entry['path']).read_bytes() |
| 72 | try: |
| 73 | text = raw.decode('utf-8') |
| 74 | encoding = 'utf-8' |
| 75 | except UnicodeDecodeError: |
| 76 | text = raw.decode('latin-1') |
| 77 | encoding = 'latin-1' |
| 78 | hits = [{'line': n, 'text': line} for n, line in enumerate(text.splitlines(), 1) |
| 79 | if NOTICE_PATTERN.search(line)] |
| 80 | if hits: |
| 81 | notices.append({'path': entry['path'], 'sha256': digest(raw), |
| 82 | 'decoding': encoding, 'candidateLines': hits}) |
| 83 | return {'schemaVersion': 1, 'scannedFiles': len(entries), |
| 84 | 'method': 'Case-insensitive notice/credit/license/URL keyword scan of every file; ' |
| 85 | 'candidate lines are evidence, not license classifications. ' |
| 86 | 'Complete original bytes, including unmatched comments, are preserved ' |
| 87 | 'and verified by the preset manifest.', |
| 88 | 'pattern': NOTICE_PATTERN.pattern, 'filesWithCandidates': len(notices), |
| 89 | 'presets': notices} |
| 90 | |
| 91 | |
| 92 | def verify_files(root, entries, suffix=None): |
| 93 | expected = {entry['path'] for entry in entries} |
| 94 | require(len(expected) == len(entries), 'Duplicate manifest paths') |
| 95 | actual = {p.relative_to(root).as_posix() for p in root.rglob('*') if p.is_file()} |
| 96 | if suffix: |
| 97 | actual = {p for p in actual if p.lower().endswith(suffix)} |
| 98 | require(actual == expected, f'Subset differs in {root}: missing {len(expected-actual)}, extra {len(actual-expected)}') |
| 99 | for entry in entries: |
| 100 | path = pathlib.PurePosixPath(entry['path']) |
| 101 | require(not path.is_absolute() and '..' not in path.parts, 'Unsafe manifest path') |
| 102 | require(not (root / entry['path']).is_symlink(), 'Asset symlinks are unsupported') |
| 103 | require(digest((root / entry['path']).read_bytes()) == entry['sha256'], |
| 104 | f'Changed asset bytes: {entry["path"]}') |
| 105 | |
| 106 | |
| 107 | def verify_resource(root): |
| 108 | presets = json.loads((root / MANIFESTS[0]).read_text()) |
| 109 | textures = json.loads((root / MANIFESTS[2]).read_text()) |
| 110 | require(presets['upstreamCommit'] == PRESET_COMMIT, 'Wrong preset pin') |
| 111 | require(textures['upstreamCommit'] == TEXTURE_COMMIT, 'Wrong texture pin') |
| 112 | require(presets['upstreamMilkCount'] == 9795, 'Wrong upstream tree count') |
| 113 | expected_count = 7838 |
| 114 | curation_path = root / CURATION_FILE |
| 115 | if curation_path.exists(): |
| 116 | curation = json.loads(curation_path.read_text()) |
| 117 | require(curation['schemaVersion'] == 1 and curation['initialBundledCount'] == 7838, 'Wrong curation baseline') |
| 118 | require(presets.get('curationSHA256') == digest(curation_path.read_bytes()), 'Curation receipt differs') |
| 119 | removed, retained, reviewed = set(), set(), set() |
| 120 | retired = {x['id'] for x in json.loads((root / 'retired-presets.json').read_text())} |
| 121 | for batch in curation['batches']: |
| 122 | all_ids = set(batch['reviewedIDs']); keep = set(batch['retainedIDs']); discard = set(batch['removedIDs']) |
| 123 | require(batch['completedReview'] is True and batch['selectionSource'] == 'Finder red label', 'Incomplete curation') |
| 124 | require(len(all_ids) == len(batch['reviewedIDs']) and not (all_ids & reviewed), 'Duplicate reviewed identity') |
| 125 | require(keep.isdisjoint(discard) and keep | discard == all_ids, 'Curation partition differs') |
| 126 | removed.update(discard); retained.update(keep); reviewed.update(all_ids) |
| 127 | require(removed <= retired, 'Removed IDs missing retirement migration records') |
| 128 | current = {x['id'] for x in presets['presets']} |
| 129 | require(current.isdisjoint(removed) and retained <= current, 'Curation does not match bundled subset') |
| 130 | expected_count -= len(removed) |
| 131 | current = {x['id'] for x in presets['presets']} |
| 132 | removed = removed if curation_path.exists() else set() |
| 133 | retired = {x['id'] for x in json.loads((root / 'retired-presets.json').read_text())} if (root / 'retired-presets.json').exists() else set() |
| 134 | expected_count += verify_admissions(root, presets, current, removed, retired) |
| 135 | require(presets['bundledCount'] == len(presets['presets']) == expected_count, 'Wrong bundled count') |
| 136 | require(presets['credit'] == CREDIT and presets['creditURL'] == CREDIT_URL, 'Missing curator credit') |
| 137 | verify_files(root / 'Presets', presets['presets']) |
| 138 | verify_files(root / 'Textures', textures['files']) |
| 139 | require(textures['imageCount'] == sum(x['path'] != 'README.md' for x in textures['files']) == 67, |
| 140 | 'Wrong texture image count') |
| 141 | require(all(x['path'] == x['upstreamPath'] for x in textures['files']), 'Texture upstream path changed') |
| 142 | catalog = json.loads((root / 'catalog.json').read_text()) |
| 143 | require(len(catalog) == expected_count and len({x['id'] for x in catalog}) == expected_count, 'Catalog count/identity mismatch') |
| 144 | by_path = {x['path']: x for x in catalog} |
| 145 | require(len(by_path) == expected_count, 'Duplicate catalog paths') |
| 146 | for entry in presets['presets']: |
| 147 | item = by_path.get(entry['path']) |
| 148 | require(item is not None, f'Missing catalog entry: {entry["path"]}') |
| 149 | require(entry['upstreamPath'] == entry['path'], 'Original upstream path changed') |
| 150 | require(entry['originalTitle'] == pathlib.PurePosixPath(entry['path']).stem, |
| 151 | 'Original creator/title metadata differs from original filename') |
| 152 | require(all(item[k] == entry[k] for k in ['id', 'originalTitle']), 'Catalog provenance differs') |
| 153 | require(item['title'] == entry['displayTitle'], 'Display mapping differs') |
| 154 | for name, sha in presets['upstreamNotices'].items(): |
| 155 | require(digest((root / name).read_bytes()) == sha, f'Changed upstream notice: {name}') |
| 156 | require(json.loads((root / MANIFESTS[1]).read_text()) == scan_notices(root / 'Presets', presets['presets']), |
| 157 | 'Notice inventory differs from complete scan') |
| 158 | return presets, textures |
| 159 | |
| 160 | |
| 161 | def pinned_snapshot(checkout, commit, destination): |
| 162 | # Read Git objects at the pin, never an upstream working tree with local changes. |
| 163 | data = subprocess.check_output(['git', '-C', str(checkout), 'archive', commit]) |
| 164 | with tarfile.open(fileobj=io.BytesIO(data)) as archive: |
| 165 | safe_extract(archive, destination) |
| 166 | |
| 167 | |
| 168 | def safe_extract(archive, destination): |
| 169 | # Compatible with Apple's Python 3.9; reject traversal, links and special files. |
| 170 | for member in archive.getmembers(): |
| 171 | path = pathlib.PurePosixPath(member.name) |
| 172 | require(not path.is_absolute() and '..' not in path.parts, 'Unsafe archive path') |
| 173 | require(member.isfile() or member.isdir(), 'Archive links/special files are unsupported') |
| 174 | archive.extractall(destination) |
| 175 | |
| 176 | |
| 177 | def generate(preset_checkout, texture_checkout): |
| 178 | root = REPO / RESOURCE |
| 179 | catalog = json.loads((root / 'catalog.json').read_text()) |
| 180 | with tempfile.TemporaryDirectory() as temp: |
| 181 | temp = pathlib.Path(temp) |
| 182 | upstream = temp / 'presets' |
| 183 | textures = temp / 'textures' |
| 184 | pinned_snapshot(preset_checkout, PRESET_COMMIT, upstream) |
| 185 | pinned_snapshot(texture_checkout, TEXTURE_COMMIT, textures) |
| 186 | upstream_count = len(list(upstream.rglob('*.milk'))) |
| 187 | require(upstream_count == 9795, 'Unexpected pinned upstream tree') |
| 188 | entries = [] |
| 189 | for item in sorted(catalog, key=lambda item: item['path']): |
| 190 | path = item['path'] |
| 191 | raw = (root / 'Presets' / path).read_bytes() |
| 192 | require(raw == (upstream / path).read_bytes(), f'Preset differs from pin: {path}') |
| 193 | entries.append({'path': path, 'upstreamPath': path, 'sha256': digest(raw), |
| 194 | 'id': item['id'], 'originalTitle': item['originalTitle'], |
| 195 | 'displayTitle': item['title']}) |
| 196 | notices = {'Preset-README.md': 'README.md', 'Preset-notice.md': 'LICENSE.md'} |
| 197 | for bundled, source in notices.items(): |
| 198 | require((root / bundled).read_bytes() == (upstream / source).read_bytes(), |
| 199 | f'Upstream notice changed: {bundled}') |
| 200 | preset_manifest = { |
| 201 | 'schemaVersion': 1, |
| 202 | 'upstreamRepository': 'https://github.com/projectM-visualizer/presets-cream-of-the-crop', |
| 203 | 'upstreamCommit': PRESET_COMMIT, 'upstreamMilkCount': upstream_count, |
| 204 | 'bundledCount': len(entries), 'credit': CREDIT, 'creditURL': CREDIT_URL, |
| 205 | 'rightsStatus': 'Unresolved individual author permissions; upstream public-domain assumption ' |
| 206 | 'is not documented permission from every author. No MIT/BSD/clearance claim.', |
| 207 | 'upstreamNotices': {name: digest((root / name).read_bytes()) for name in notices}, |
| 208 | 'presets': entries} |
| 209 | if (root / CURATION_FILE).exists(): |
| 210 | preset_manifest['curationSHA256'] = digest((root / CURATION_FILE).read_bytes()) |
| 211 | if (root / ADMISSIONS_FILE).exists(): |
| 212 | preset_manifest['admissionsSHA256'] = digest((root / ADMISSIONS_FILE).read_bytes()) |
| 213 | texture_entries = [] |
| 214 | for path in sorted((root / 'Textures').rglob('*')): |
| 215 | if not path.is_file(): |
| 216 | continue |
| 217 | relative = path.relative_to(root / 'Textures').as_posix() |
| 218 | require(path.read_bytes() == (textures / relative).read_bytes(), f'Texture differs from pin: {relative}') |
| 219 | texture_entries.append({'path': relative, 'upstreamPath': relative, 'sha256': digest(path.read_bytes())}) |
| 220 | texture_manifest = { |
| 221 | 'schemaVersion': 1, |
| 222 | 'upstreamRepository': 'https://github.com/projectM-visualizer/presets-milkdrop-texture-pack', |
| 223 | 'upstreamCommit': TEXTURE_COMMIT, |
| 224 | 'imageCount': sum(entry['path'] != 'README.md' for entry in texture_entries), |
| 225 | 'rightsStatus': 'Individual asset grants unresolved; README recommends inclusion but ' |
| 226 | 'does not supply per-texture licenses. Separate from preset and engine terms.', |
| 227 | 'files': texture_entries} |
| 228 | for name, value in zip(MANIFESTS, [preset_manifest, scan_notices(root / 'Presets', entries), texture_manifest]): |
| 229 | (root / name).write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n') |
| 230 | verify_resource(root) |
| 231 | |
| 232 | |
| 233 | def verify_app(app): |
| 234 | info = plistlib.loads((app / 'Contents/Info.plist').read_bytes()) |
| 235 | config = ((REPO / 'Version.xcconfig').read_text() + '\n' + (REPO / 'macOS/Release.xcconfig').read_text()) |
| 236 | for field, key in [('CFBundleShortVersionString', 'MARKETING_VERSION'), |
| 237 | ('CFBundleVersion', 'CURRENT_PROJECT_VERSION')]: |
| 238 | expected = re.search(r'^' + key + r'\s*=\s*(\S+)', config, re.MULTILINE).group(1) |
| 239 | require(info[field] == expected, f'App version/build differs from source: {field}') |
| 240 | resources = app / 'Contents/Resources' |
| 241 | roots = (list(resources.glob('Resources/ProjectM')) |
| 242 | + list(resources.glob('*.bundle/Resources/ProjectM')) |
| 243 | + list(resources.glob('*.bundle/Contents/Resources/Resources/ProjectM'))) |
| 244 | require(len(roots) == 1, 'Expected one bundled ProjectM resource tree') |
| 245 | root = roots[0] |
| 246 | verify_resource(root) |
| 247 | require(set(resources.rglob('*.milk')) == set((root / 'Presets').rglob('*.milk')), |
| 248 | 'Unexpected presets outside the intended bundled subset') |
| 249 | curation_files = receipt_files(REPO / RESOURCE) |
| 250 | for name in MANIFESTS + ['Preset-README.md', 'Preset-notice.md', 'Provenance.md', 'catalog.json'] + curation_files: |
| 251 | require((root / name).read_bytes() == (REPO / RESOURCE / name).read_bytes(), f'App differs from checkout: {name}') |
| 252 | legal = resources / 'Legal' |
| 253 | for name in MANIFESTS + ['Preset-README.md', 'Preset-notice.md', 'Provenance.md'] + curation_files: |
| 254 | require((legal / name).read_bytes() == (root / name).read_bytes(), f'Legal resource differs: {name}') |
| 255 | require((legal / 'Texture-provenance.md').read_bytes() == (root / 'Textures/README.md').read_bytes(), 'Texture notice differs') |
| 256 | require((legal / 'PulseCanvas-LICENSE.txt').read_bytes() == (REPO / 'LICENSE').read_bytes(), 'Application license differs') |
| 257 | require((legal / 'ProjectM-LGPL-2.1.txt').read_bytes() == (REPO / '.build/projectm/source/LICENSE.txt').read_bytes(), 'Engine license differs') |
| 258 | require((legal / 'Third-Party-Notices.md').read_bytes() == (REPO / 'third_party/PROJECTM.md').read_bytes(), 'Component notices differ') |
| 259 | vendors = REPO / '.build/projectm/source/vendor' |
| 260 | for name, source in [('hlslparser-MIT.txt', vendors / 'hlslparser/LICENSE'), |
| 261 | ('projectm-eval-MIT.txt', vendors / 'projectm-eval/LICENSE.md')]: |
| 262 | require((legal / name).read_bytes() == source.read_bytes(), f'Vendor license differs: {name}') |
| 263 | for source in sorted((vendors / 'stb_image').iterdir()): |
| 264 | if source.suffix in ['.c', '.h']: |
| 265 | require((legal / source.name).read_bytes() == source.read_bytes(), f'Embedded vendor notices differ: {source.name}') |
| 266 | info = plistlib.loads((app / 'Contents/Info.plist').read_bytes()) |
| 267 | config = ((REPO / 'Version.xcconfig').read_text() + '\n' + (REPO / 'macOS/Release.xcconfig').read_text()) |
| 268 | version = re.search(r'^MARKETING_VERSION\s*=\s*(\S+)', config, re.M).group(1) |
| 269 | build = re.search(r'^CURRENT_PROJECT_VERSION\s*=\s*(\S+)', config, re.M).group(1) |
| 270 | # Portable development bundles use their existing development version. |
| 271 | if (resources / 'Resources/ProjectM').exists(): |
| 272 | require(info['CFBundleShortVersionString'] == version and info['CFBundleVersion'] == build, |
| 273 | 'App version/build differs from source configuration') |
| 274 | |
| 275 | |
| 276 | def verify_source(path, revision=None): |
| 277 | with tempfile.TemporaryDirectory() as temp: |
| 278 | with tarfile.open(path) as archive: |
| 279 | safe_extract(archive, temp) |
| 280 | root = pathlib.Path(temp) / 'PulseCanvas-source' |
| 281 | verify_resource(root / RESOURCE) |
| 282 | require(set(root.rglob('*.milk')) == set((root / RESOURCE / 'Presets').rglob('*.milk')), |
| 283 | 'Unexpected presets outside the source subset') |
| 284 | curation_files = receipt_files(REPO / RESOURCE) |
| 285 | for name in MANIFESTS + ['Preset-README.md', 'Preset-notice.md', 'Provenance.md', 'catalog.json'] + curation_files: |
| 286 | require((root / RESOURCE / name).read_bytes() == (REPO / RESOURCE / name).read_bytes(), f'Source differs: {name}') |
| 287 | for name in ['LICENSE', 'Version.xcconfig', 'macOS/Release.xcconfig', 'third_party/projectm-source.tar.gz', |
| 288 | 'third_party/PROJECTM.md', 'Sources/PulseCanvas/PulseCanvasApp.swift', |
| 289 | 'scripts/build-projectm.sh', 'scripts/build-app.sh', 'scripts/store-release.sh', |
| 290 | 'scripts/preset-provenance.py']: |
| 291 | require((root / name).read_bytes() == (REPO / name).read_bytes(), f'Source build input differs: {name}') |
| 292 | require((root / 'docs/licensing.md').is_file() and (root / 'docs/app-store/LICENSES.md').is_file(), |
| 293 | 'Source licensing guidance missing') |
| 294 | if revision: |
| 295 | require((root / 'REVISION.txt').read_text().strip() == revision, 'Source revision differs') |
| 296 | # Verify the entire committed build input set, not just the manifests. |
| 297 | inputs = ['Version.xcconfig', 'Localization', 'Sources', 'scripts', 'radio', 'macOS', 'PulseCanvas.xcodeproj', 'PulseCanvasMobile.xcodeproj', 'mobile', 'PulseCanvasVision.xcodeproj', |
| 298 | 'visionOS', 'third_party', 'assets', 'packaging', |
| 299 | 'Package.swift', 'Package.resolved', 'LICENSE', 'README.md', 'AGENTS.md', 'docs'] |
| 300 | snapshot = subprocess.check_output(['git', '-C', str(REPO), 'archive', revision, *inputs]) |
| 301 | with tarfile.open(fileobj=io.BytesIO(snapshot)) as committed: |
| 302 | expected = set() |
| 303 | for member in committed.getmembers(): |
| 304 | if member.isfile(): |
| 305 | expected.add(member.name) |
| 306 | require((root / member.name).read_bytes() == committed.extractfile(member).read(), |
| 307 | f'Committed source input differs: {member.name}') |
| 308 | actual = {p.relative_to(root).as_posix() for p in root.rglob('*') if p.is_file()} |
| 309 | require(actual == expected | {'BUILD.txt', 'REVISION.txt'}, 'Source package file set differs') |
| 310 | |
| 311 | |
| 312 | def main(): |
| 313 | parser = argparse.ArgumentParser(description=__doc__) |
| 314 | parser.add_argument('--generate', action='store_true') |
| 315 | parser.add_argument('--presets-checkout', type=pathlib.Path, default=REPO.parent / 'projectm-presets') |
| 316 | parser.add_argument('--textures-checkout', type=pathlib.Path, default=REPO.parent / 'projectm-textures') |
| 317 | parser.add_argument('--app', type=pathlib.Path) |
| 318 | parser.add_argument('--source', type=pathlib.Path) |
| 319 | parser.add_argument('--revision') |
| 320 | args = parser.parse_args() |
| 321 | if args.generate: |
| 322 | generate(args.presets_checkout, args.textures_checkout) |
| 323 | presets, textures = verify_resource(REPO / RESOURCE) |
| 324 | if args.app: |
| 325 | verify_app(args.app) |
| 326 | if args.source: |
| 327 | verify_source(args.source, args.revision) |
| 328 | notices = json.loads((REPO / RESOURCE / MANIFESTS[1]).read_text()) |
| 329 | print(json.dumps({'verifiedPresets': len(presets['presets']), 'upstreamMilkFiles': presets['upstreamMilkCount'], |
| 330 | 'verifiedTextureImages': textures['imageCount'], 'scannedPresets': notices['scannedFiles'], |
| 331 | 'presetsWithNoticeCandidates': notices['filesWithCandidates'], |
| 332 | 'app': str(args.app) if args.app else None, 'sourceArchive': str(args.source) if args.source else None}, indent=2)) |
| 333 | |
| 334 | |
| 335 | if __name__ == '__main__': |
| 336 | main() |