Files
baji-vc/scripts/select-character-assets.py

198 lines
9.5 KiB
Python

#!/usr/bin/env python3
"""Select immutable runtime references, common assets and explicit legacy retention.
No generation, decoding, source modification or gateway operation. Full media admission
remains the existing production gate. Unlisted source directories never enter the APK.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import shutil
import tempfile
ROOT = Path(__file__).resolve().parents[1]
CATALOG = ROOT / 'manifests/character-build-profiles.json'
def require(ok, reason):
if not ok:
raise ValueError(reason)
def relative(value):
require(isinstance(value, str) and value and '\\' not in value, 'invalid asset path')
path = PurePosixPath(value)
require(not path.is_absolute() and str(path) == value and all(p not in ('..', '.') for p in path.parts), 'asset path escape')
return value
def digest(data):
return hashlib.sha256(data).hexdigest()
def catalog():
data = json.loads(CATALOG.read_bytes())
require(data['schemaVersion'] == 1 and set(data['profiles']) == {'main', 'lvbu-test', 'liam-test', 'liam-test-square540'}, 'unsupported profile catalog')
return data
def framing(profile, media_bundle, preset=None):
data = catalog(); role = data['profiles'][profile]
expected = role.get('framingPreset', 'legacy')
preset = expected if preset is None else preset
require(preset == expected, 'profile/framing preset mismatch')
if preset == 'legacy':
return {'id': preset, 'zoom': 1, 'centerY': .5}
row = data['framingPresets'][preset]
require(row['profile'] == profile and row['mediaBundle'] == media_bundle and
row['indexSha256'] == data['mediaBundles'][media_bundle]['indexSha256'], 'preset/media pin mismatch')
return {'id': preset, **row}
def build_directory(profile, preset=None):
role = catalog()['profiles'][profile]
expected = role.get('framingPreset', 'legacy')
require(preset is None or preset == expected, 'profile/framing build directory mismatch')
base = ROOT / ('app/build' if profile == 'main' else 'app/build/characters/' + profile)
return base if expected == 'legacy' else base / 'framing' / expected
def authorized_debug_sha(pin):
return any(row.get('userAuthorizedDebug') is True and row['indexSha256']==pin
for row in catalog()['mediaBundles'].values())
def selection(assets, profile='main', *, emotion_sha='', user_assets=False, mouth=False, startup=False, media_bundle=None):
data = catalog()
require(profile in data['profiles'], 'unknown character profile')
role = data['profiles'][profile]
require(not media_bundle or emotion_sha, 'explicit media needs an exact pin')
bundle_id = (media_bundle or ('black-correct03' if user_assets else 'white-full04')) if emotion_sha else None
require(bundle_id is None or bundle_id in data['mediaBundles'], 'unknown media bundle')
allowed = [role['mediaSelection'], *role.get('additionalMediaSelections', [])]
require((role['mediaSelection'] == 'existing-build-flags' and bundle_id in (None,'black-correct03','white-full04')) or
bundle_id in allowed and mouth and startup, 'profile/media flags mismatch')
preset = framing(profile, bundle_id)
bundle = data['mediaBundles'][bundle_id] if bundle_id else None
if bundle:
require(emotion_sha == bundle['indexSha256'], 'selected exact index mismatch')
require(user_assets == bundle.get('userAuthorizedDebug',False), 'media authorization mode mismatch')
assets = Path(assets).resolve(strict=True)
files = {}
def source(name):
name = relative(name)
p = assets / name
require(all(not (assets / Path(*PurePosixPath(name).parts[:i])).is_symlink()
for i in range(1, len(PurePosixPath(name).parts) + 1)), 'asset symlink rejected')
require(p.is_file() and p.resolve().is_relative_to(assets), 'missing/escaped asset: ' + name)
return p
def add(name, sha, size=None):
p = source(name)
raw = p.read_bytes()
require(len(raw) <= 128_000_000 and digest(raw) == sha and (size is None or len(raw) == size), 'asset hash/bytes mismatch: ' + name)
row = {'sha256': sha, 'bytes': len(raw)}
require(name not in files or files[name] == row, 'conflicting asset reference')
files[name] = row
return raw
for name, row in data['commonAssets'].items():
add(name, row['sha256'], row['bytes'])
legacy = json.loads((ROOT / data['retainedInventory']).read_bytes())
require(legacy['schemaVersion'] == 1 and len(legacy['files']) == 594, 'legacy retention inventory mismatch')
for name, row in legacy['files'].items():
if not mouth and name.startswith('avatar/a01-neutral-graph-v1/runtime-04/'):
continue
add(name, row['sha256'], row['bytes'])
if bundle:
base = bundle['assetRoot']
index = json.loads(add(base + 'manifest.json', emotion_sha))
require(index['identityId'] == bundle['identityId'] and index['packId'] == bundle['packId'], 'media identity mismatch')
require(bool(index.get('waiting')) == bundle.get('waitingContract',False), 'waiting contract/catalog mismatch')
declared = {relative(r['path']): r for r in index['files']}
def payload(name, sha):
row = declared.get(relative(name))
require(row is not None and row['sha256'] == sha, 'index inventory reference mismatch')
return add(base + name, sha, row['bytes'])
def runtime(ref):
raw = payload(ref['path'], ref['sha256'])
body = json.loads(raw)
require(body['identityId'] == bundle['identityId'], 'runtime media identity mismatch')
parent = str(PurePosixPath(ref['path']).parent) + '/'
payload(parent + body['body']['path'], body['body']['sha256'])
for patch in body['patches']:
for level in patch['levels']:
payload(parent + level['path'], level['sha256'])
for row in index['conversationPackages']:
runtime(row['runtimeManifest'])
for edge in index['edges']:
payload(edge['clip']['path'], edge['clip']['sha256'])
if edge.get('mouthRuntimeManifest'):
runtime(edge['mouthRuntimeManifest'])
for pose in index.get('waiting',{}).get('poses',[]):
payload(pose['clip']['path'],pose['clip']['sha256'])
for action in index['actions']:
payload(action['clip']['path'], action['clip']['sha256'])
if startup:
boot_root = bundle['bootstrapRoot']
boot = json.loads(add(boot_root + 'manifest.json', bundle['bootstrapSha256']))
require(boot['sourceIndexSha256'] == emotion_sha and boot['body']['path'] in files and
files[boot['body']['path']]['sha256'] == boot['body']['sha256'], 'bootstrap/index/body mismatch')
poster = add(boot_root + 'poster.png', boot['posterSha256'])
resource = ROOT / bundle.get('resourceDirectory','app/src/main/res') / 'drawable-nodpi' / (bundle['posterResource'] + '.png')
require(resource.read_bytes() == poster, 'drawable/bootstrap poster mismatch')
return {'schemaVersion': 1, 'profile': profile, 'application_id': role['applicationId'],
'persona': role['persona'], 'framing_preset': preset['id'], 'media_bundle': bundle_id, 'media_identity': bundle['identityId'] if bundle else 'a01',
'index_sha256': emotion_sha, 'files': files, 'file_count': len(files)}
def stage(assets, output, report):
output = Path(output)
expected = build_directory(report['profile'], report.get('framing_preset')) / 'generated/packagedAssets'
require(not output.is_symlink() and output.resolve() == expected, 'staging must use isolated app build output')
output.parent.mkdir(parents=True, exist_ok=True)
temporary = Path(tempfile.mkdtemp(prefix='.character-assets-', dir=output.parent))
try:
for name, row in report['files'].items():
dest = temporary / name
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(Path(assets) / name, dest)
require(dest.stat().st_size == row['bytes'] and digest(dest.read_bytes()) == row['sha256'], 'source changed during staging')
if output.exists():
shutil.rmtree(output)
os.rename(temporary, output)
finally:
if temporary.exists():
shutil.rmtree(temporary)
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--profile', choices=sorted(catalog()['profiles']), required=True)
p.add_argument('--assets', type=Path, default=ROOT / 'app/src/main/assets')
p.add_argument('--emotion-sha', default='')
p.add_argument('--media-bundle', default='')
for flag in ('user-assets', 'mouth', 'startup'):
p.add_argument('--' + flag, choices=['true', 'false'], default='false')
p.add_argument('--output', type=Path)
p.add_argument('--report', type=Path)
a = p.parse_args()
result = selection(a.assets, a.profile, emotion_sha=a.emotion_sha, user_assets=a.user_assets == 'true',
mouth=a.mouth == 'true', startup=a.startup == 'true', media_bundle=a.media_bundle or None)
if a.output:
stage(a.assets, a.output, result)
if a.report:
a.report.parent.mkdir(parents=True, exist_ok=True)
a.report.write_text(json.dumps(result, indent=2, ensure_ascii=False) + '\n')
print(json.dumps({k: v for k, v in result.items() if k != 'files'}, ensure_ascii=False))
if __name__ == '__main__':
main()