"""Offline Foundry/Gitea/GitHub release generation. Never contacts a Git host.""" from __future__ import annotations import argparse import hashlib import ipaddress import json from pathlib import Path import re import subprocess import sys import urllib.parse import zipfile ROOT=Path(__file__).resolve().parents[1] DEFAULT_REPOSITORY='https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music' ZIP_TIME=(2000,1,1,0,0,0) if str(ROOT/'scripts') not in sys.path:sys.path.insert(0,str(ROOT/'scripts')) def public_url(value): parsed=urllib.parse.urlsplit(value) if parsed.scheme!='https' or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment: raise ValueError('public HTTPS URL required') try: address=ipaddress.ip_address(parsed.hostname) except ValueError: if parsed.hostname in ('localhost',) or parsed.hostname.endswith(('.local','.invalid')):raise ValueError('placeholder/local release URL') else: if not address.is_global:raise ValueError('private release address') return value.rstrip('/') def urls(repository,version,branch='main'): repository=public_url(repository) parsed=urllib.parse.urlsplit(repository) if repository.endswith('.git'):repository=repository[:-4] if not re.fullmatch(r'[A-Za-z0-9._-]+',branch):raise ValueError('invalid branch') if not re.fullmatch(r'\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?',version):raise ValueError('invalid release version') if parsed.hostname=='github.com': parts=urllib.parse.urlsplit(repository).path.strip('/').split('/') if len(parts)!=2:raise ValueError('GitHub owner/repo required') manifest=f'https://raw.githubusercontent.com/{parts[0]}/{parts[1]}/{branch}/module.json' else:manifest=f'{repository}/raw/branch/{branch}/module.json' return {'url':repository,'manifest':manifest,'download':f'{repository}/releases/download/v{version}/adaptive-music.zip'} def release_manifest(repository=DEFAULT_REPOSITORY,version=None,branch='main'): manifest=json.loads((ROOT/'module.json').read_text()) if version is not None and version!=manifest['version']:raise ValueError('tag/version must match source module.json') manifest['version']=version or manifest['version'];manifest.update(urls(repository,manifest['version'],branch)) validate_manifest(manifest);return manifest def validate_manifest(manifest): if not isinstance(manifest,dict) or any(k not in manifest for k in ('id','authors','compatibility','version','url','manifest','download','esmodules')):raise ValueError('incomplete manifest') if manifest.get('id')!='adaptive-music' or manifest.get('authors')!=[{'name':'CheddahBoxMB'}]:raise ValueError('module identity mismatch') if manifest.get('compatibility',{}).get('minimum')!='14' or manifest['compatibility'].get('maximum')!='14' or 'verified' in manifest['compatibility']:raise ValueError('unsupported compatibility claim') if manifest.get('relationships',{}).get('requires',[]) or manifest.get('systems'):raise ValueError('mandatory system/module dependency') expected=urls(manifest['url'],manifest['version']) for key in ('manifest','download'): public_url(manifest[key]) if manifest[key]!=expected[key]:raise ValueError('manifest/update URL mismatch') if 'v'+manifest['version'] not in manifest['download']:raise ValueError('unversioned download') def module_files(): names=['module.json','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES'] for directory,pattern in [('src','*.mjs'),('styles','*.css'),('licenses','*'),('vendor','*')]: names.extend(str(p.relative_to(ROOT)) for p in sorted((ROOT/directory).rglob(pattern)) if p.is_file()) return names def write_zip(path,entries): path.parent.mkdir(parents=True,exist_ok=True) with zipfile.ZipFile(path,'w',zipfile.ZIP_DEFLATED) as archive: for name,data in sorted(entries.items()): info=zipfile.ZipInfo(name,ZIP_TIME);info.compress_type=zipfile.ZIP_DEFLATED;info.external_attr=0o100644<<16 archive.writestr(info,data) def module_entries(manifest): result={} for name in module_files(): path=ROOT/name if path.is_symlink():raise ValueError('package symlink refused') data=(json.dumps(manifest,indent=2)+'\n').encode() if name=='module.json' else path.read_bytes() if name.endswith('.mjs') and (b'node:' in data or b"from '../../gateway/" in data):raise ValueError('server code in browser package') result['adaptive-music/'+name]=data return result def validate_package(path,manifest=None): from audit_repository import findings with zipfile.ZipFile(path) as archive: names=archive.namelist() if len(names)!=len(set(names)) or any(not n.startswith('adaptive-music/') or '..' in Path(n).parts or '/.local/' in n or '/node_modules/' in n or '/gateway/' in n for n in names):raise ValueError('unsafe package inventory') actual=json.loads(archive.read('adaptive-music/module.json'));validate_manifest(actual) if manifest and actual!=manifest:raise ValueError('embedded and standalone manifest mismatch') for name in names: data=archive.read(name);problems=findings(name,data.decode(errors='replace')) if problems:raise ValueError('private content in release: '+name) if name.endswith('.mjs'): text=data.decode();relative_imports=re.findall(r"(?:from\s*|import\s*\()['\"](\.[^'\"]+)['\"]",text) import posixpath for relative in relative_imports: resolved=posixpath.normpath(posixpath.join(posixpath.dirname(name),relative)) if resolved not in names:raise ValueError('missing browser import: '+resolved) for asset in actual['esmodules']+actual.get('styles',[]): if 'adaptive-music/'+asset not in names:raise ValueError('missing manifest asset') provenance=json.loads(archive.read('adaptive-music/vendor/provenance.json')) if hashlib.sha256(archive.read('adaptive-music/vendor/sendspin-5.0.0.mjs')).hexdigest()!=provenance['sha256']:raise ValueError('SDK bundle hash mismatch') required=['licenses/VGM-MIT.txt','licenses/Apache-2.0.txt','licenses/vendor/-sendspin-sendspin-js.txt','licenses/vendor/-noble-ciphers.txt','licenses/vendor/-noble-curves.txt','licenses/vendor/-noble-hashes.txt'] if any('adaptive-music/'+name not in names for name in required):raise ValueError('missing license') return actual def local_revision(): try:return subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip() except (subprocess.CalledProcessError,FileNotFoundError): file=ROOT/'SOURCE_REVISION.txt' return file.read_text().strip() if file.is_file() else 'unknown (source archive without Git metadata)' def source_entries(manifest): from audit_repository import findings try:names=subprocess.check_output(['git','ls-files','-z','--cached','--others','--exclude-standard'],cwd=ROOT,stderr=subprocess.DEVNULL).decode().split('\0') except (subprocess.CalledProcessError,FileNotFoundError): names=[p.name for p in ROOT.iterdir() if p.is_file() and p.name in {'.gitignore','AGENTS.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','module.json','package.json','package-lock.json','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES','SOURCE_REVISION.txt'}] for directory in ('src','styles','licenses','vendor','gateway','scripts','tests','evidence','.github','.gitea'): names.extend(str(p.relative_to(ROOT)) for p in (ROOT/directory).rglob('*') if p.is_file() and '__pycache__' not in p.parts and p.suffix!='.pyc') entries={} for name in sorted(set(filter(None,names))): path=ROOT/name if name.startswith(('.local/','dist/','node_modules/','.git/')) or path.is_symlink():raise ValueError('private/unsafe source path') if path.is_file(): data=path.read_bytes() if findings(name,data.decode(errors='replace')):raise ValueError('private material in source: '+name) entries['adaptive-music-source/'+name]=data entries['adaptive-music-source/module.json']=(json.dumps(manifest,indent=2)+'\n').encode() entries['adaptive-music-source/SOURCE_REVISION.txt']=(local_revision()+'\n').encode() return entries def build_release(repository=DEFAULT_REPOSITORY,version=None,output=None): manifest=release_manifest(repository,version);version=manifest['version'];output=output or ROOT/'dist/releases'/('v'+version) output=Path(output).resolve() if output.is_relative_to(ROOT) and not output.is_relative_to(ROOT/'dist'):raise ValueError('in-repository output must be under ignored dist/') output.mkdir(parents=True,exist_ok=True) allowed={'adaptive-music.zip','module.json','adaptive-music-source.zip','README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES','release.json','SHA256SUMS',f'adaptive-music-release-v{version}.zip',f'adaptive-music-release-v{version}.zip.sha256'} allowed.update(str(p.relative_to(ROOT)) for p in (ROOT/'licenses').rglob('*') if p.is_file()) for file in output.rglob('*'): if file.is_symlink() or file.is_file() and str(file.relative_to(output)) not in allowed:raise ValueError('unmanaged file in release output') write_zip(output/'adaptive-music.zip',module_entries(manifest));validate_package(output/'adaptive-music.zip',manifest) (output/'module.json').write_text(json.dumps(manifest,indent=2)+'\n') write_zip(output/'adaptive-music-source.zip',source_entries(manifest)) for name in ('README.md','INSTALL.md','CHANGELOG.md','ARCHITECTURE.md','SECURITY.md','TESTING.md','PROGRESS.md','LICENSE','THIRD-PARTY-NOTICES'):(output/name).write_bytes((ROOT/name).read_bytes()) for path in (ROOT/'licenses').rglob('*'): if path.is_file():target=output/path.relative_to(ROOT);target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(path.read_bytes()) metadata={'version':version,'repository':manifest['url'],'manifest':manifest['manifest'],'download':manifest['download'], 'sourceCommit':local_revision(),'sourceRevisionStatus':'base revision; included source archive is authoritative','sourceArchiveSHA256':hashlib.sha256((output/'adaptive-music-source.zip').read_bytes()).hexdigest(),'destinationStatus':'user-reported existing Gitea; never contacted by this builder','foundryLiveVerified':False,'networkAccessRequired':False} (output/'release.json').write_text(json.dumps(metadata,indent=2)+'\n') files={str(p.relative_to(output)):p.read_bytes() for p in output.rglob('*') if p.is_file() and p.name not in ('SHA256SUMS',) and not p.name.startswith('adaptive-music-release-')} (output/'SHA256SUMS').write_text(''.join(f'{hashlib.sha256(data).hexdigest()} {name}\n' for name,data in sorted(files.items()))) files['SHA256SUMS']=(output/'SHA256SUMS').read_bytes();bundle=output/f'adaptive-music-release-v{version}.zip';write_zip(bundle,files) (output/(bundle.name+'.sha256')).write_text(hashlib.sha256(bundle.read_bytes()).hexdigest()+' '+bundle.name+'\n') return bundle if __name__=='__main__': parser=argparse.ArgumentParser();parser.add_argument('--repository',default=DEFAULT_REPOSITORY);parser.add_argument('--version');parser.add_argument('--output',type=Path);parser.add_argument('--validate',type=Path);args=parser.parse_args() if args.validate:validate_package(args.validate);print('PASS: standalone Foundry package, imports, manifest/update URLs, privacy and licenses') else:print(build_release(args.repository,args.version,args.output))