cockatrice-custom-tokens/scripts/publish.py

260 lines
13 KiB
Python

#!/usr/bin/env python3
"""Prepare and atomically publish static Cockatrice assets on a mounted web root."""
import argparse
import base64
import hashlib
import json
import io
from urllib.parse import unquote, urlsplit
import os
from pathlib import Path
import shutil
import tempfile
import xml.etree.ElementTree as ET
from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo
ROOT = Path(__file__).resolve().parents[1]
IMAGE_SUFFIXES = {'.png', '.jpg', '.jpeg', '.webp', '.gif'}
def sources(sets):
"""Return the complete, validated flat public filename mapping."""
result = {}
for folder in sorted(sets.iterdir()):
if folder.is_symlink():
raise ValueError(f'Symlink set directory: {folder}')
if not folder.is_dir():
continue
for path in sorted(folder.rglob('*')):
if path.is_symlink():
raise ValueError(f'Symlinks are not supported: {path}')
if not path.is_file():
continue
if path.parent == folder and path.suffix == '.xml':
root = ET.parse(path).getroot()
codes = {node.text for node in root.findall('./sets/set/name')}
if root.tag != 'cockatrice_carddatabase' or folder.name not in codes:
raise ValueError(f'Invalid Cockatrice set: {path}')
destination = Path('xml') / path.name
elif 'artwork' in path.relative_to(folder).parts[:-1] and path.suffix.lower() in IMAGE_SUFFIXES:
destination = Path('cards') / path.name
else:
continue
if path.stat().st_size == 0:
raise ValueError(f'Empty source: {path}')
if destination in result:
raise ValueError(f'Duplicate public filename: {destination}')
result[destination] = path
if not any(p.parts[0] == 'xml' for p in result) or not any(p.parts[0] == 'cards' for p in result):
raise ValueError('Publication requires nonempty XML and artwork sources')
return result
def customsets_archive(entries):
"""XML files at archive root, ready to extract into Cockatrice customsets/."""
buffer = io.BytesIO()
with ZipFile(buffer, 'w', compression=ZIP_DEFLATED) as archive:
for relative, source in sorted(entries.items()):
if relative.parts[0] != 'xml':
continue
entry = ZipInfo(relative.name)
entry.compress_type = ZIP_DEFLATED
entry.create_system = 3
entry.external_attr = 0o100644 << 16
archive.writestr(entry, source.read_bytes())
return buffer.getvalue()
def installer_files(entries):
files = []
destinations = set()
for relative, source in sorted(entries.items()):
if relative.parts[0] != 'xml':
continue
files.append({'source': relative.as_posix(), 'destination': 'customsets/' + relative.name,
'size': source.stat().st_size, 'sha256': hashlib.sha256(source.read_bytes()).hexdigest()})
for card in ET.parse(source).getroot().findall('./cards/card'):
name = card.findtext('name', '')
for printing in card.findall('set'):
url = printing.get('picurl', '')
parsed = urlsplit(url)
if parsed.scheme != 'https' or parsed.netloc != 'assets.dandaedre.com' or not parsed.path.startswith('/mtg/cards/') or parsed.query or parsed.fragment:
raise ValueError(f'Card artwork must use the published assets host: {url}')
image = Path(unquote(parsed.path[len('/mtg/'):]))
if image not in entries:
raise ValueError(f'Artwork missing from publication: {image}')
code = printing.text or ''
for component in (code, name):
if not component or component in ('.', '..') or any(c in component for c in '/\\') or any(ord(c) < 32 for c in component):
raise ValueError(f'Unsafe set or card name for local artwork: {component!r}')
# Cockatrice looks for cardName_UUID before the generic cardName.
# Distinct files prevent alternative printings overwriting each other.
suffix = ''
if len(card.findall('set')) > 1:
printing_uuid = printing.get('uuid', '')
if not printing_uuid or any(c not in '0123456789abcdefABCDEF-' for c in printing_uuid):
raise ValueError(f'Alternative printing requires a safe UUID: {name}')
suffix = '_' + printing_uuid
destination = f'pics/{code}/{name}{suffix}{image.suffix}'
picture = entries[image]
item = {'source': image.as_posix(), 'destination': destination,
'size': picture.stat().st_size, 'sha256': hashlib.sha256(picture.read_bytes()).hexdigest()}
if destination in destinations:
if item not in files:
raise ValueError(f'Conflicting local card artwork: {destination}')
else:
destinations.add(destination)
files.append(item)
manifest = (json.dumps({'version': 1, 'files': files}, indent=2) + '\n').encode()
code = (ROOT / 'scripts/install.py').read_text()
# Invocation is the last line: a truncated download cannot execute a partial body.
wrapper = ("#!/bin/sh\n# Generated from scripts/install.py; do not edit this generated file.\n"
"install_cockatrice_tokens() {\n"
" command -v python3 >/dev/null 2>&1 || { echo 'ERROR: Python 3.8+ is required.' >&2; return 1; }\n"
" python3 -c 'import sys; sys.exit(sys.version_info < (3, 8))' || { echo 'ERROR: Python 3.8+ is required.' >&2; return 1; }\n"
" python3 - \"$@\" <<'COCKATRICE_INSTALLER_PYTHON'\n" + code +
"\nCOCKATRICE_INSTALLER_PYTHON\n}\ninstall_cockatrice_tokens \"$@\"\n")
powershell = (ROOT / 'install.ps1').read_text().replace(
'__COCKATRICE_PYTHON_BASE64__', base64.b64encode(code.encode()).decode())
return {Path('manifest.json'): manifest, Path('install.sh'): wrapper.encode(),
Path('install.ps1'): powershell.encode(),
Path('customsets.zip'): customsets_archive(entries)}
def prepare(sets, output):
entries = sources(sets)
controls = installer_files(entries)
if output.exists():
raise ValueError(f'Output already exists; use a clean build: {output}')
for relative, source in entries.items():
target = output / relative
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, target)
for relative, data in controls.items():
(output / relative).write_bytes(data)
return entries
def verify(sets, output):
expected = sources(sets)
controls = installer_files(expected)
actual = payload_files(output / 'publish')
for relative, data in controls.items():
if actual.pop(relative).read_bytes() != data:
raise ValueError(f'Installer output differs from sources: {relative}')
if set(expected) != set(actual):
raise ValueError('Publication payload does not match the set sources')
for relative in expected:
if expected[relative].read_bytes() != actual[relative].read_bytes():
raise ValueError(f'Payload differs from source: {relative}')
folders = sorted(path for path in sets.iterdir() if path.is_dir())
if {p.name for p in output.glob('*.zip')} != ({f'{p.name}.zip' for p in folders} | {'customsets.zip'}):
raise ValueError('ZIP outputs do not match the set directories')
manual = output / 'customsets.zip'
if manual.is_symlink() or manual.read_bytes() != controls[Path('customsets.zip')]:
raise ValueError('customsets.zip differs from generated XML')
for folder in folders:
bundle = output / f'{folder.name}.zip'
if bundle.is_symlink() or not bundle.is_file() or bundle.stat().st_size == 0:
raise ValueError(f'Missing or invalid ZIP: {bundle}')
files = {p.relative_to(sets).as_posix(): p for p in folder.rglob('*') if p.is_file()}
with ZipFile(bundle) as archive:
if len(archive.namelist()) != len(files) or set(archive.namelist()) != set(files):
raise ValueError(f'Unexpected ZIP contents: {bundle}')
for name, source in files.items():
if archive.read(name) != source.read_bytes():
raise ValueError(f'ZIP differs from source: {name}')
print('Verified nonempty publication files and ZIP contents')
def payload_files(payload):
entries = {}
for category in ('cards', 'xml'):
directory = payload / category
if directory.is_symlink() or not directory.is_dir():
raise ValueError(f'Missing or unsafe payload directory: {directory}')
files = sorted(directory.iterdir())
if not files:
raise ValueError(f'Empty payload directory: {directory}')
for path in files:
if path.is_symlink() or not path.is_file() or path.stat().st_size == 0:
raise ValueError(f'Invalid payload file: {path}')
if category == 'xml':
if path.suffix != '.xml' or ET.parse(path).getroot().tag != 'cockatrice_carddatabase':
raise ValueError(f'Invalid XML payload: {path}')
elif path.suffix.lower() not in IMAGE_SUFFIXES:
raise ValueError(f'Unsupported image: {path}')
entries[Path(category) / path.name] = path
for name in ('install.sh', 'install.ps1', 'manifest.json', 'customsets.zip'):
path = payload / name
if path.is_symlink() or not path.is_file() or path.stat().st_size == 0:
raise ValueError(f'Missing or unsafe installer output: {path}')
entries[Path(name)] = path
return entries
def publish(payload, web_root):
entries = payload_files(payload)
if not web_root.is_absolute() or web_root == Path('/'):
raise ValueError('Web root must be an absolute, non-root mount path')
if web_root.resolve() != web_root or not web_root.is_dir() or not os.path.ismount(web_root):
raise ValueError(f'Web root must be an existing mount without symlinks: {web_root}')
destination = web_root / 'mtg'
# Check every destination before changing any published file.
for directory in (destination, destination / 'cards', destination / 'xml'):
if directory.is_symlink() or (directory.exists() and not directory.is_dir()):
raise ValueError(f'Unsafe destination directory: {directory}')
for relative in entries:
target = destination / relative
if target.is_symlink() or (target.exists() and not target.is_file()):
raise ValueError(f'Unsafe destination file: {target}')
for directory in (destination, destination / 'cards', destination / 'xml'):
if not directory.exists():
directory.mkdir(mode=0o755)
directory.chmod(0o755)
# Publish artwork before XML, so new XML does not precede its images.
# Publish the manifest last so clients reject any mixed-version downloads.
ordered = sorted(entries.items(), key=lambda item: (item[0].name == 'manifest.json', item[0].as_posix()))
for relative, source in ordered:
target = destination / relative
temporary = None
try:
with tempfile.NamedTemporaryFile(dir=target.parent, prefix='.publish-', delete=False) as stream:
temporary = Path(stream.name)
with source.open('rb') as incoming:
shutil.copyfileobj(incoming, stream)
stream.flush()
os.fchmod(stream.fileno(), 0o644)
os.fsync(stream.fileno())
os.replace(temporary, target)
finally:
if temporary is not None and temporary.exists():
temporary.unlink()
print(f'Published mtg/{relative.as_posix()}')
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
sub.add_parser('prepare')
sub.add_parser('verify')
deploy = sub.add_parser('publish')
deploy.add_argument('--web-root', type=Path, required=True)
args = parser.parse_args()
payload = ROOT / 'dist' / 'publish'
if args.command in ('prepare', 'verify'):
from generate_xml import generate
generate(ROOT / 'sets', ROOT / 'dist/sets', check=True)
if args.command == 'prepare':
prepare(ROOT / 'dist/sets', payload)
print('Prepared dist/publish/cards and dist/publish/xml')
elif args.command == 'verify':
verify(ROOT / 'dist/sets', ROOT / 'dist')
else:
publish(payload, args.web_root)
if __name__ == '__main__':
main()