#!/usr/bin/env python3 """Publish reviewed native BRD helpers without request-time provisioning.""" import argparse, datetime, hashlib, json, os from pathlib import Path import re, shutil, subprocess, tempfile EXPECTED={ 'system-board-provision.php':'4f2335dd0a0e2204d851e0b53692393d3b4d6889eff5490b30190e51a1345608', 'system-board-membership.php':'277df1d4c30dd749cd343e0eab880d9fd8ff848ab72cb0a0bdd7f14bb96e5282', 'system-board-policy.php':'c2ecdc2542e213a76f0d95b2f437973980908f88510da502e5709a7233f1db34', 'system-board.php':'0633650eec888bcbf0abf587a14101c507b3c9cf39ec19f6df8463ddcb0033eb'} PHASES={'prepare':['system-board-policy.php','system-board-provision.php','board-key-publication.php','publish-board-keys.php'],'enable':['system-board.php','system-board-membership.php']} def changes(source,target,names): result=[] for name in names: destination=target/name if destination.is_symlink():raise RuntimeError('Refusing native symlink: '+name) content=(source/name).read_bytes();old=destination.read_bytes() if destination.exists() else None if old==content:continue if old is not None and hashlib.sha256(old).hexdigest()!=EXPECTED.get(name):raise RuntimeError('Unreviewed native helper: '+name) if old is None and name in EXPECTED:raise RuntimeError('Existing helper missing: '+name) result.append((name,content,old)) return result def main(): parser=argparse.ArgumentParser();parser.add_argument('--phase',choices=PHASES,required=True);parser.add_argument('--apply',action='store_true');args=parser.parse_args() release=Path(__file__).resolve().parents[1];current=Path('/home/dunerealms/apps/dunerealms/current').resolve(strict=True) if current!=release or not re.fullmatch(r'ci-[0-9a-f]{40}',release.name):raise RuntimeError('Use the active CI-promoted release') promoted=Path('/mnt/HC_Volume_107481500/dunegit/ci/promotion/deployed').read_text().strip() if promoted!=release.name[3:]:raise RuntimeError('Active publication receipt differs') source=release/'integrations/mybb';target=Path('/home/dunerealms/apps/integrations/mybb').resolve(strict=True) if not (target/'global.php').is_file():raise RuntimeError('Native MyBB installation unavailable') planned=changes(source,target,PHASES[args.phase]) for name in sum(PHASES.values(),[]):subprocess.run(['php','-l',str(source/name)],check=True,capture_output=True) for name in ['test-system-board-policy.php','test-system-board-provision.php','test-board-key-publication.php','test-board-key-recovery.php','test-board-key-read-path.php']:subprocess.run(['php',str(source/name)],check=True,capture_output=True) if args.phase=='enable': for name in PHASES['prepare']: if not (target/name).is_file() or (target/name).read_bytes()!=(source/name).read_bytes():raise RuntimeError('Prepare helpers before enabling page reads') node='/home/dunerealms/.nvm/versions/node/v22.23.3/bin/node' status=subprocess.run(['runuser','-u','dunerealms','--',node,'--env-file=/home/dunerealms/.config/dunerealms.env',str(release/'ops/board-key-status.mjs'),'--require-applied'],check=True,capture_output=True,text=True) json.loads(status.stdout) if not args.apply:print(json.dumps({'applied':False,'phase':args.phase,'files':[r[0] for r in planned]}));return reference=(target/'system-board-membership.php').stat();backup=Path('/var/backups/dunerealms-board-keys')/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ') if planned:backup.mkdir(parents=True,mode=0o700,exist_ok=False) for name,content,old in planned: destination=target/name if (destination.read_bytes() if destination.exists() else None)!=old:raise RuntimeError('Native helper changed during publication: '+name) if old is not None:shutil.copy2(destination,backup/name) fd,temporary=tempfile.mkstemp(prefix='.dune-brd-',dir=target) try: with os.fdopen(fd,'wb') as out:out.write(content) os.chmod(temporary,reference.st_mode&0o777);os.chown(temporary,reference.st_uid,reference.st_gid);os.replace(temporary,destination) finally: if os.path.exists(temporary):os.unlink(temporary) print(json.dumps({'applied':True,'phase':args.phase,'files':[r[0] for r in planned],'backup':str(backup) if planned else None,'boardProvisioningExecuted':False})) if __name__=='__main__':main()