From eeee72a91e7a09a84ea91747a15f1456db1e8a60 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:49:57 +0100 Subject: [PATCH 1/7] Remove retired menu resources and recover failed backend installs --- .forgejo/workflows/plugins.yml | 9 ++ DuneMenus/build.gradle.kts | 10 -- tools/install-dunemenus-release.py | 180 ++++++++++++++++++++--------- tools/test_dunemenus_installer.py | 144 +++++++++++++++++++++++ 4 files changed, 279 insertions(+), 64 deletions(-) create mode 100644 tools/test_dunemenus_installer.py diff --git a/.forgejo/workflows/plugins.yml b/.forgejo/workflows/plugins.yml index 837231e1..edc3c16a 100644 --- a/.forgejo/workflows/plugins.yml +++ b/.forgejo/workflows/plugins.yml @@ -56,6 +56,15 @@ jobs: path: plugin-artifacts/ if-no-files-found: error + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Test release installer failure recovery + shell: bash + run: | + set -euo pipefail + python -m pip install PyYAML==6.0.3 + python -m unittest discover -s tools -p test_dunemenus_installer.py -v - name: Test and build the replacement DuneMenus plugin shell: bash run: | diff --git a/DuneMenus/build.gradle.kts b/DuneMenus/build.gradle.kts index 999ea2d1..595838a4 100644 --- a/DuneMenus/build.gradle.kts +++ b/DuneMenus/build.gradle.kts @@ -21,16 +21,6 @@ tasks.withType { options.encoding = "UTF-8" } tasks.jar { archiveFileName.set("DuneMenus.jar") } tasks.processResources { filesMatching("plugin.yml") { expand("version" to project.version) } - from("../website/web/assets/dunerealms-season-logo-v2.png") { into("mcgui") } - from("../DuneLobby/artwork/exchange.png") { into("mcgui/native") } - from("../website/web/assets/seals") { - include("house-aerdrecht-v1.png", "house-harkveen-v1.png", "house-korenholt-v1.png", "house-oordwijk-v1.png", "house-vrijduin-v1.png") - into("mcgui/native") - } - from("../website/web/assets/gui") { - include("mentat-atreides-v1.png", "mentat-harkonnen-v1.png", "mentat-corrino-v1.png", "mentat-ordos-v1.png", "mentat-fremen-v1.png") - into("mcgui/native") - } } tasks.test { useJUnitPlatform() } diff --git a/tools/install-dunemenus-release.py b/tools/install-dunemenus-release.py index 486f3053..27bfa877 100644 --- a/tools/install-dunemenus-release.py +++ b/tools/install-dunemenus-release.py @@ -1,55 +1,127 @@ -"""Install one verified build into one explicitly named backend. Called from the build artifact.""" +"""Install one recorded build into one backend, with bounded file/service recovery.""" from pathlib import Path -import datetime,hashlib,json,os,shutil,subprocess,sys,yaml -bundle=Path(__file__).resolve().parent -manifest=json.loads((bundle/'release.json').read_text()) -root=Path(sys.argv[1]).resolve();unit=sys.argv[2] -allowed={ - '/opt/dunerealms/lobby':'dune-lobby.service', - **{f'/opt/dunerealms/servers/{x}':f'dune-{x}.service' for x in ['arrakis','caladan','giedi_prime','kaitain','sigma_draconis_iv']}} -assert allowed.get(str(root))==unit,'Unexpected backend/unit' -for name,record in manifest['files'].items(): - assert '/' not in name and hashlib.sha256((bundle/name).read_bytes()).hexdigest()==record['sha256'],name -plugins=root/'plugins';target=plugins/'DuneMenus.jar';data=plugins/'DuneMenus' -assert target.is_file() and (data/'config.yml').is_file() -jars=[name for name in manifest['files'] if name.endswith('.jar') and (plugins/name).exists()] -assert 'DuneMenus.jar' in jars -stamp=datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ') -backup=Path('/root/dunemenus-before-'+stamp+'-'+root.name);backup.mkdir(mode=0o700) -for p in [*[plugins/name for name in jars],data/'config.yml',data/'gui-pack.yml']: - if p.exists():shutil.copy2(p,backup/p.name) -excluded=set(jars)|{'DunerealmsGUI.jar','DuneFullscreenPaper.jar','MCGUI.jar'} -others={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in plugins.glob('*.jar') if p.name not in excluded} -(backup/'other-jars.json').write_text(json.dumps(others,indent=2)) -config=yaml.safe_load((data/'config.yml').read_text()) or {} -config.setdefault('fullscreen',{})['enabled']=True -config.pop('mcgui',None) -pack=yaml.safe_load((data/'gui-pack.yml').read_text()) or {} -pin={'url':manifest['pack_url'],'sha1':manifest['files']['DuneRealms-Network-Artwork-v7.zip']['sha1']} -pack.update({'world':pin,'lobby':pin}) -subprocess.run(['systemctl','stop',unit],check=True,timeout=120) -owner=target.stat();removed=[] -for name in ['DunerealmsGUI.jar','DuneFullscreenPaper.jar','MCGUI.jar','DunerealmsGUI','DuneFullscreenPaper','MCGUI']: - p=plugins/name - if not p.exists():continue - assert p.resolve().is_relative_to(plugins.resolve()) - shutil.move(str(p),str(backup/name));removed.append(name) -for name in ['mcgui']: - p=data/name - if p.is_dir():shutil.move(str(p),str(backup/('DuneMenus-'+name)));removed.append('DuneMenus/'+name) -for name in jars: - dst=plugins/name;tmp=dst.with_suffix('.jar.build-staged');shutil.copy2(bundle/name,tmp);os.chown(tmp,owner.st_uid,owner.st_gid);os.replace(tmp,dst) -for name,content in [('config.yml',config),('gui-pack.yml',pack)]: - p=data/name;p.write_text(yaml.safe_dump(content,sort_keys=False,allow_unicode=True));os.chown(p,owner.st_uid,owner.st_gid) -cache=plugins/'.paper-remapped' -if cache.is_dir(): - for p in cache.glob('*.jar'): - if p.name in jars or any(x in p.name.lower() for x in ['dunemenus','dunerealmsgui','dunefullscreen','mcgui']): - shutil.move(str(p),str(backup/('remapped-'+p.name))) -after={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in plugins.glob('*.jar') if p.name not in excluded} -assert others==after,'Unrelated plugins changed' -assert hashlib.sha256(target.read_bytes()).hexdigest()==manifest['files']['DuneMenus.jar']['sha256'] -for name in jars:assert hashlib.sha256((plugins/name).read_bytes()).hexdigest()==manifest['files'][name]['sha256'] -subprocess.run(['systemctl','start',unit],check=True,timeout=120) -report={'source':manifest['source'],'server':str(root),'unit':unit,'backup':str(backup),'removed':removed,'jars':{name:manifest['files'][name]['sha256'] for name in jars},'pack':pin,'other_plugins_unchanged':True,'runtime_verified':False} -(backup/'deployment.json').write_text(json.dumps(report,indent=2));print(json.dumps(report)) +import datetime, hashlib, json, os, re, shutil, subprocess, sys, yaml + +ALLOWED = {'/opt/dunerealms/lobby': 'dune-lobby.service', **{ + f'/opt/dunerealms/servers/{x}': f'dune-{x}.service' + for x in ['arrakis', 'caladan', 'giedi_prime', 'kaitain', 'sigma_draconis_iv']}} +JARS = {'DuneMenus.jar', 'DuneRealms-Essentials.jar', 'DuneRealms-Lobby.jar', + 'DuneRealms-Core.jar', 'jarvistranslator.jar'} +LEGACY = ('DunerealmsGUI.jar', 'DuneRealmsGUI.jar', 'DuneFullscreenPaper.jar', 'MCGUI.jar', + 'DunerealmsGUI', 'DuneRealmsGUI', 'DuneFullscreenPaper', 'MCGUI') +PACK = 'DuneRealms-Network-Artwork-v7.zip' + +def require(ok, message): + if not ok: + raise ValueError(message) + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + +def run(argv): + return subprocess.run(argv, check=True, timeout=120, capture_output=True, text=True) + +def owned_replace(source, target): + info = target.stat() + tmp = target.with_name(target.name + '.build-staged') + require(not tmp.exists() and not tmp.is_symlink(), f'Staging path exists: {tmp}') + try: + shutil.copy2(source, tmp) + os.chmod(tmp, info.st_mode & 0o777) + if hasattr(os, 'chown'): + os.chown(tmp, info.st_uid, info.st_gid) + os.replace(tmp, target) + finally: + if tmp.exists(): + tmp.unlink() + +def install(bundle, root, unit, backup_base=Path('/root'), runner=run): + bundle, root = Path(bundle).resolve(), Path(root).resolve() + require(ALLOWED.get(str(root)) == unit, 'Unexpected backend/unit') + manifest = json.loads((bundle/'release.json').read_text()) + require(re.fullmatch(r'[0-9a-f]{40}', manifest.get('source', '')), 'Missing source commit') + files = manifest['files'] + for name, record in files.items(): + require(name not in ('.', '..') and '/' not in name and '\\' not in name, 'Unsafe artifact name') + artifact = bundle/name + require(artifact.is_file() and not artifact.is_symlink(), 'Invalid artifact: '+name) + require(digest(artifact) == record['sha256'], 'Artifact checksum differs: '+name) + require(JARS <= files.keys() and PACK in files, 'Incomplete release') + require(hashlib.sha1((bundle/PACK).read_bytes()).hexdigest() == files[PACK]['sha1'], 'Pack SHA1 differs') + require(manifest['pack_url'] == 'https://www.dunerealms.com/downloads/'+PACK, 'Unexpected pack URL') + plugins = root/'plugins'; data = plugins/'DuneMenus' + require(not plugins.is_symlink() and not data.is_symlink(), 'Symlinked plugin directory') + configs = [data/'config.yml', data/'gui-pack.yml'] + require(all(p.is_file() and not p.is_symlink() for p in configs), 'Missing/symlinked configuration') + require((plugins/'DuneMenus.jar').is_file(), 'DuneMenus is not installed') + config, pack = [yaml.safe_load(p.read_text()) or {} for p in configs] + require(isinstance(config, dict) and isinstance(pack, dict), 'Configuration must be a mapping') + require(isinstance(config.get('fullscreen', {}), dict), 'fullscreen must be a mapping') + config.setdefault('fullscreen', {})['enabled'] = True; config.pop('mcgui', None) + pin = {'url': manifest['pack_url'], 'sha1': files[PACK]['sha1']} + pack.update({'world': pin, 'lobby': pin}) + jars = sorted(name for name in JARS if (plugins/name).is_file()) + targets = [*[plugins/name for name in jars], *configs] + require(all(not p.is_symlink() for p in targets), 'Symlinked replacement target') + legacy = [plugins/name for name in LEGACY if (plugins/name).exists()] + if (data/'mcgui').exists(): legacy.append(data/'mcgui') + cache = plugins/'.paper-remapped' + if cache.exists(): + require(not cache.is_symlink(), 'Symlinked remapped cache') + legacy += [p for p in cache.glob('*.jar') if p.name in JARS or + any(x in p.name.lower() for x in ('dunemenus', 'dunerealmsgui', 'dunefullscreen', 'mcgui'))] + require(all(not p.is_symlink() and p.resolve().is_relative_to(plugins.resolve()) for p in legacy), 'Unsafe legacy path') + excluded = set(jars) | set(LEGACY) + others = {p.name: digest(p) for p in plugins.glob('*.jar') if p.name not in excluded} + runner(['systemctl', 'is-active', '--quiet', unit]) + stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ') + backup = Path(backup_base)/('dunemenus-before-'+stamp+'-'+root.name); backup.mkdir(mode=0o700) + originals = {} + for target in targets: + saved = backup/'files'/target.relative_to(plugins) + saved.parent.mkdir(parents=True, exist_ok=True); shutil.copy2(target, saved); originals[target] = saved + (backup/'other-jars.json').write_text(json.dumps(others, indent=2)) + staged = backup/'prepared'; staged.mkdir() + for target, content in zip(configs, (config, pack)): + (staged/target.name).write_text(yaml.safe_dump(content, sort_keys=False, allow_unicode=True)) + moved = []; changed = []; stop_attempted = False + try: + stop_attempted = True; runner(['systemctl', 'stop', unit]) + require(all(digest(p) == digest(saved) for p, saved in originals.items()), 'Backend files changed after preflight') + for target in legacy: + saved = backup/'retired'/target.relative_to(plugins); saved.parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(target), str(saved)); moved.append((target, saved)) + for target in targets: + source = bundle/target.name if target.suffix == '.jar' else staged/target.name + changed.append(target); owned_replace(source, target) + require(all(digest(plugins/name) == files[name]['sha256'] for name in jars), 'Installed checksum differs') + require(others == {p.name: digest(p) for p in plugins.glob('*.jar') if p.name not in excluded}, 'Unrelated plugins changed') + require(all(not p.exists() for p in legacy), 'Retired GUI remains active') + runner(['systemctl', 'start', unit]); runner(['systemctl', 'is-active', '--quiet', unit]) + except Exception as failure: + errors = [] + if changed or moved: + try: runner(['systemctl', 'stop', unit]) + except Exception as error: errors.append('Cannot stop backend for recovery: '+str(error)) + if not errors: + for target in reversed(changed): + try: owned_replace(originals[target], target) + except Exception as error: errors.append('Restore failed: '+str(error)) + for target, saved in reversed(moved): + try: shutil.move(str(saved), str(target)) + except Exception as error: errors.append('Retired-file restore failed: '+str(error)) + if stop_attempted and not errors: + try: + runner(['systemctl', 'start', unit]); runner(['systemctl', 'is-active', '--quiet', unit]) + except Exception as error: errors.append('Recovery startup failed: '+str(error)) + report = {'installed': False, 'error': str(failure), 'backup': str(backup), 'recovered': not errors, 'recovery_errors': errors} + (backup/'failure.json').write_text(json.dumps(report, indent=2)) + raise RuntimeError(json.dumps(report)) from failure + report = {'source': manifest['source'], 'server': str(root), 'unit': unit, 'backup': str(backup), + 'removed': [str(p.relative_to(plugins)) for p in legacy], 'jars': {name: files[name]['sha256'] for name in jars}, + 'pack': pin, 'other_plugins_unchanged': True, 'runtime_verified': False} + (backup/'deployment.json').write_text(json.dumps(report, indent=2)); return report + +if __name__ == '__main__': + require(len(sys.argv) == 3, 'Usage: installer BACKEND UNIT') + print(json.dumps(install(Path(__file__).resolve().parent, sys.argv[1], sys.argv[2]))) diff --git a/tools/test_dunemenus_installer.py b/tools/test_dunemenus_installer.py new file mode 100644 index 00000000..72544cd8 --- /dev/null +++ b/tools/test_dunemenus_installer.py @@ -0,0 +1,144 @@ +import hashlib +import importlib.util +import json +import pathlib +import tempfile +import unittest +from unittest.mock import patch + +SPEC = importlib.util.spec_from_file_location('installer', pathlib.Path(__file__).with_name('install-dunemenus-release.py')) +m = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(m) + + +class InstallerTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + base = pathlib.Path(self.temp.name) + self.bundle = base / 'bundle' + self.bundle.mkdir() + self.root = base / 'arrakis' + self.plugins = self.root / 'plugins' + self.data = self.plugins / 'DuneMenus' + self.data.mkdir(parents=True) + self.backup = base / 'backups' + self.backup.mkdir() + self.unit = 'test.service' + guard = patch.dict(m.ALLOWED, {str(self.root.resolve()): self.unit}) + guard.start() + self.addCleanup(guard.stop) + files = {} + for name in sorted(m.JARS | {m.PACK}): + payload = ('new-' + name).encode() + (self.bundle / name).write_bytes(payload) + files[name] = {'sha256': hashlib.sha256(payload).hexdigest(), 'sha1': hashlib.sha1(payload).hexdigest()} + if name in m.JARS: + (self.plugins / name).write_bytes(('old-' + name).encode()) + (self.bundle / 'release.json').write_text(json.dumps({ + 'source': 'a' * 40, 'files': files, + 'pack_url': 'https://www.dunerealms.com/downloads/' + m.PACK})) + (self.data / 'config.yml').write_text('owner-setting: preserve\nfullscreen:\n enabled: false\n') + (self.data / 'gui-pack.yml').write_text('unrelated: keep\n') + (self.plugins / 'other.jar').write_bytes(b'unrelated') + (self.plugins / 'MCGUI.jar').write_bytes(b'legacy') + (self.data / 'mcgui').mkdir() + (self.data / 'mcgui' / 'old.png').write_bytes(b'old-art') + self.before = self.snapshot() + self.calls = [] + + def snapshot(self): + return {p.relative_to(self.plugins).as_posix(): p.read_bytes() + for p in self.plugins.rglob('*') if p.is_file()} + + def run_service(self, args): + self.calls.append(args) + + def invoke(self, runner=None): + return m.install(self.bundle, self.root, self.unit, self.backup, runner or self.run_service) + + def test_success_removes_legacy_and_preserves_unrelated_config(self): + result = self.invoke() + self.assertFalse(result['runtime_verified']) + self.assertFalse((self.plugins / 'MCGUI.jar').exists()) + self.assertFalse((self.data / 'mcgui').exists()) + self.assertEqual((self.plugins / 'other.jar').read_bytes(), b'unrelated') + self.assertIn('owner-setting: preserve', (self.data / 'config.yml').read_text()) + self.assertIn('unrelated: keep', (self.data / 'gui-pack.yml').read_text()) + for name in m.JARS: + self.assertEqual((self.plugins / name).read_bytes(), (self.bundle / name).read_bytes()) + + def test_checksum_failure_does_not_stop_service(self): + (self.bundle / 'DuneMenus.jar').write_bytes(b'corrupt') + with self.assertRaisesRegex(ValueError, 'checksum'): + self.invoke() + self.assertEqual(self.calls, []) + self.assertEqual(self.before, self.snapshot()) + + def test_missing_config_does_not_stop_service(self): + (self.data / 'gui-pack.yml').unlink() + with self.assertRaisesRegex(ValueError, 'configuration'): + self.invoke() + self.assertEqual(self.calls, []) + + def test_partial_jar_and_config_failures_restore_all_files(self): + for failing_name in ['DuneMenus.jar', 'gui-pack.yml']: + real = m.owned_replace + failed = False + + def injected(source, target): + nonlocal failed + if target.name == failing_name and not failed: + failed = True + raise OSError('injected copy/config failure') + return real(source, target) + + with patch.object(m, 'owned_replace', side_effect=injected): + with self.assertRaisesRegex(RuntimeError, 'injected'): + self.invoke() + self.assertEqual(self.before, self.snapshot()) + self.assertEqual(self.calls[-1], ['systemctl', 'is-active', '--quiet', self.unit]) + + def test_failed_start_restores_files_then_restarts_old_release(self): + failed = False + + def runner(args): + nonlocal failed + self.calls.append(args) + if args[1] == 'start' and not failed: + failed = True + raise OSError('injected start failure') + + with self.assertRaisesRegex(RuntimeError, 'injected start'): + self.invoke(runner) + self.assertEqual(self.before, self.snapshot()) + self.assertEqual(sum(c[1] == 'start' for c in self.calls), 2) + + def test_recovery_start_failure_is_explicit(self): + def runner(args): + self.calls.append(args) + if args[1] == 'start': + raise OSError('cannot start') + + with self.assertRaisesRegex(RuntimeError, 'Recovery startup failed'): + self.invoke(runner) + self.assertEqual(self.before, self.snapshot()) + + def test_changed_config_at_shutdown_is_preserved(self): + def runner(args): + self.calls.append(args) + if args[1] == 'stop': + (self.data / 'config.yml').write_text('new-owner-setting: keep\n') + + with self.assertRaisesRegex(RuntimeError, 'changed after preflight'): + self.invoke(runner) + self.assertEqual((self.data / 'config.yml').read_text(), 'new-owner-setting: keep\n') + + def test_wrong_backend_does_not_stop_service(self): + with self.assertRaisesRegex(ValueError, 'Unexpected backend'): + m.install(self.bundle, self.root, 'wrong', self.backup, self.run_service) + self.assertEqual(self.calls, []) + + +if __name__ == '__main__': + unittest.main() -- 2.53.0 From b204c2e978542cd3735f8e770c86f575568f0320 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:51:20 +0100 Subject: [PATCH 2/7] Replace installed plugins by identity across legacy JAR filenames --- tools/install-dunemenus-release.py | 42 +++++++++++++++++++++++++----- tools/test_dunemenus_installer.py | 21 ++++++++++++++- 2 files changed, 55 insertions(+), 8 deletions(-) diff --git a/tools/install-dunemenus-release.py b/tools/install-dunemenus-release.py index 27bfa877..d39adf68 100644 --- a/tools/install-dunemenus-release.py +++ b/tools/install-dunemenus-release.py @@ -1,6 +1,7 @@ """Install one recorded build into one backend, with bounded file/service recovery.""" from pathlib import Path import datetime, hashlib, json, os, re, shutil, subprocess, sys, yaml +from zipfile import ZipFile ALLOWED = {'/opt/dunerealms/lobby': 'dune-lobby.service', **{ f'/opt/dunerealms/servers/{x}': f'dune-{x}.service' @@ -10,6 +11,13 @@ JARS = {'DuneMenus.jar', 'DuneRealms-Essentials.jar', 'DuneRealms-Lobby.jar', LEGACY = ('DunerealmsGUI.jar', 'DuneRealmsGUI.jar', 'DuneFullscreenPaper.jar', 'MCGUI.jar', 'DunerealmsGUI', 'DuneRealmsGUI', 'DuneFullscreenPaper', 'MCGUI') PACK = 'DuneRealms-Network-Artwork-v7.zip' +IDENTITIES = {'DuneMenus.jar': 'DuneMenus', 'DuneRealms-Essentials.jar': 'DuneEss', + 'DuneRealms-Lobby.jar': 'DuneLobby', 'DuneRealms-Core.jar': 'DuneCore', + 'jarvistranslator.jar': 'JarvisTranslator'} + +def plugin_name(path): + with ZipFile(path) as archive: + return yaml.safe_load(archive.read('plugin.yml'))['name'] def require(ok, message): if not ok: @@ -60,18 +68,37 @@ def install(bundle, root, unit, backup_base=Path('/root'), runner=run): config.setdefault('fullscreen', {})['enabled'] = True; config.pop('mcgui', None) pin = {'url': manifest['pack_url'], 'sha1': files[PACK]['sha1']} pack.update({'world': pin, 'lobby': pin}) - jars = sorted(name for name in JARS if (plugins/name).is_file()) - targets = [*[plugins/name for name in jars], *configs] + installed = {} + for jar in plugins.glob('*.jar'): + try: + identity = plugin_name(jar) + except Exception: + require(not any(jar.name.lower().startswith(prefix) for prefix in + ('dunemenus', 'dunecore', 'duneess', 'dunelobby', 'dunerealms-core', + 'dunerealms-essentials', 'dunerealms-lobby', 'jarvistranslator')), + 'Unreadable first-party plugin: '+jar.name) + continue + if identity in IDENTITIES.values(): + require(identity not in installed, 'Duplicate installed plugin: '+identity) + installed[identity] = jar + require('DuneMenus' in installed, 'DuneMenus identity missing') + replacements = {} + for name, identity in IDENTITIES.items(): + require(plugin_name(bundle/name) == identity, 'Unexpected artifact plugin identity: '+name) + if identity in installed: + replacements[name] = installed[identity] + jars = sorted(replacements) + targets = [*replacements.values(), *configs] require(all(not p.is_symlink() for p in targets), 'Symlinked replacement target') legacy = [plugins/name for name in LEGACY if (plugins/name).exists()] if (data/'mcgui').exists(): legacy.append(data/'mcgui') cache = plugins/'.paper-remapped' if cache.exists(): require(not cache.is_symlink(), 'Symlinked remapped cache') - legacy += [p for p in cache.glob('*.jar') if p.name in JARS or + legacy += [p for p in cache.glob('*.jar') if p.name in JARS or p.name in {t.name for t in targets} or any(x in p.name.lower() for x in ('dunemenus', 'dunerealmsgui', 'dunefullscreen', 'mcgui'))] require(all(not p.is_symlink() and p.resolve().is_relative_to(plugins.resolve()) for p in legacy), 'Unsafe legacy path') - excluded = set(jars) | set(LEGACY) + excluded = {p.name for p in replacements.values()} | set(LEGACY) others = {p.name: digest(p) for p in plugins.glob('*.jar') if p.name not in excluded} runner(['systemctl', 'is-active', '--quiet', unit]) stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ') @@ -92,9 +119,9 @@ def install(bundle, root, unit, backup_base=Path('/root'), runner=run): saved = backup/'retired'/target.relative_to(plugins); saved.parent.mkdir(parents=True, exist_ok=True) shutil.move(str(target), str(saved)); moved.append((target, saved)) for target in targets: - source = bundle/target.name if target.suffix == '.jar' else staged/target.name + source = next((bundle/name for name, path in replacements.items() if path == target), staged/target.name) changed.append(target); owned_replace(source, target) - require(all(digest(plugins/name) == files[name]['sha256'] for name in jars), 'Installed checksum differs') + require(all(digest(replacements[name]) == files[name]['sha256'] for name in jars), 'Installed checksum differs') require(others == {p.name: digest(p) for p in plugins.glob('*.jar') if p.name not in excluded}, 'Unrelated plugins changed') require(all(not p.exists() for p in legacy), 'Retired GUI remains active') runner(['systemctl', 'start', unit]); runner(['systemctl', 'is-active', '--quiet', unit]) @@ -118,7 +145,8 @@ def install(bundle, root, unit, backup_base=Path('/root'), runner=run): (backup/'failure.json').write_text(json.dumps(report, indent=2)) raise RuntimeError(json.dumps(report)) from failure report = {'source': manifest['source'], 'server': str(root), 'unit': unit, 'backup': str(backup), - 'removed': [str(p.relative_to(plugins)) for p in legacy], 'jars': {name: files[name]['sha256'] for name in jars}, + 'removed': [str(p.relative_to(plugins)) for p in legacy], + 'jars': {replacements[name].name: files[name]['sha256'] for name in jars}, 'pack': pin, 'other_plugins_unchanged': True, 'runtime_verified': False} (backup/'deployment.json').write_text(json.dumps(report, indent=2)); return report diff --git a/tools/test_dunemenus_installer.py b/tools/test_dunemenus_installer.py index 72544cd8..512efd33 100644 --- a/tools/test_dunemenus_installer.py +++ b/tools/test_dunemenus_installer.py @@ -5,6 +5,7 @@ import pathlib import tempfile import unittest from unittest.mock import patch +from zipfile import ZipFile SPEC = importlib.util.spec_from_file_location('installer', pathlib.Path(__file__).with_name('install-dunemenus-release.py')) m = importlib.util.module_from_spec(SPEC) @@ -32,9 +33,16 @@ class InstallerTests(unittest.TestCase): for name in sorted(m.JARS | {m.PACK}): payload = ('new-' + name).encode() (self.bundle / name).write_bytes(payload) + if name in m.JARS: + with ZipFile(self.bundle / name, 'w') as archive: + archive.writestr('plugin.yml', 'name: ' + m.IDENTITIES[name]) + archive.writestr('build.txt', payload) + payload = (self.bundle / name).read_bytes() files[name] = {'sha256': hashlib.sha256(payload).hexdigest(), 'sha1': hashlib.sha1(payload).hexdigest()} if name in m.JARS: - (self.plugins / name).write_bytes(('old-' + name).encode()) + with ZipFile(self.plugins / name, 'w') as archive: + archive.writestr('plugin.yml', 'name: ' + m.IDENTITIES[name]) + archive.writestr('build.txt', 'old-' + name) (self.bundle / 'release.json').write_text(json.dumps({ 'source': 'a' * 40, 'files': files, 'pack_url': 'https://www.dunerealms.com/downloads/' + m.PACK})) @@ -139,6 +147,17 @@ class InstallerTests(unittest.TestCase): m.install(self.bundle, self.root, 'wrong', self.backup, self.run_service) self.assertEqual(self.calls, []) + def test_legacy_versioned_filenames_are_replaced_without_duplicates(self): + aliases = {'DuneRealms-Core.jar': 'DuneCore-1.0.10.jar', + 'DuneRealms-Essentials.jar': 'DuneEss-1.0.2.jar'} + for source, target in aliases.items(): + (self.plugins / source).rename(self.plugins / target) + result = self.invoke() + for source, target in aliases.items(): + self.assertFalse((self.plugins / source).exists()) + self.assertEqual((self.plugins / target).read_bytes(), (self.bundle / source).read_bytes()) + self.assertIn(target, result['jars']) + if __name__ == '__main__': unittest.main() -- 2.53.0 From 3b69a7eb74b9b0f4ccf549f04e4b32e30ebcd503 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:53:59 +0100 Subject: [PATCH 3/7] Use runner system Python for installer regression checks --- .forgejo/workflows/plugins.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.forgejo/workflows/plugins.yml b/.forgejo/workflows/plugins.yml index edc3c16a..3c6c287e 100644 --- a/.forgejo/workflows/plugins.yml +++ b/.forgejo/workflows/plugins.yml @@ -56,15 +56,15 @@ jobs: path: plugin-artifacts/ if-no-files-found: error - - uses: actions/setup-python@v5 - with: - python-version: '3.12' - name: Test release installer failure recovery shell: bash run: | set -euo pipefail - python -m pip install PyYAML==6.0.3 - python -m unittest discover -s tools -p test_dunemenus_installer.py -v + if ! python3 -c 'import yaml'; then + apt-get update + apt-get install -y --no-install-recommends python3-yaml + fi + python3 -m unittest discover -s tools -p test_dunemenus_installer.py -v - name: Test and build the replacement DuneMenus plugin shell: bash run: | -- 2.53.0 From 94419ab22bd92a1ae04dbf7dfdcda361114ea84c Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:59:31 +0100 Subject: [PATCH 4/7] Publish recorded menu pack through existing download host --- tools/build-dunemenus-release.py | 2 ++ tools/publish-dunemenus-pack.py | 59 ++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 tools/publish-dunemenus-pack.py diff --git a/tools/build-dunemenus-release.py b/tools/build-dunemenus-release.py index 3952cf8e..c2dfd847 100644 --- a/tools/build-dunemenus-release.py +++ b/tools/build-dunemenus-release.py @@ -23,6 +23,8 @@ with zipfile.ZipFile(pack,'w',zipfile.ZIP_DEFLATED,compresslevel=9) as z: for module,name in [('DuneMenus','DuneMenus.jar'),('DuneEss','DuneRealms-Essentials.jar'),('DuneLobby','DuneRealms-Lobby.jar'),('DuneRealms-minecraft-only','DuneRealms-Core.jar'),('JarvisConnector','jarvistranslator.jar')]: shutil.copy2(root/module/'build/libs'/name,out/name) shutil.copy2(root/'tools/install-dunemenus-release.py',out/'install-dunemenus-release.py') +shutil.copy2(root/'network/resource-pack/dunemenus-v7.nginx.conf',out/'dunemenus-v7.nginx.conf') +shutil.copy2(root/'tools/publish-dunemenus-pack.py',out/'publish-dunemenus-pack.py') manifest={'source':subprocess.check_output(['git','rev-parse','HEAD'],cwd=root,text=True).strip(),'input_zip_sha256':'6d3cde343ba09fb7088a3a07b0c54c96eeb629c82c527993a76000013c305b60','pack_url':'https://www.dunerealms.com/downloads/'+pack.name,'files':{}} for p in sorted(out.iterdir()): if p.is_file() and p.name!='release.json': diff --git a/tools/publish-dunemenus-pack.py b/tools/publish-dunemenus-pack.py new file mode 100644 index 00000000..e2b0ebca --- /dev/null +++ b/tools/publish-dunemenus-pack.py @@ -0,0 +1,59 @@ +"""Publish the recorded v7 pack at its exact existing DuneRealms download host.""" +from pathlib import Path +import datetime +import hashlib +import json +import os +import shutil +import subprocess + +bundle = Path(__file__).resolve().parent +manifest = json.loads((bundle / 'release.json').read_text()) +names = ['DuneRealms-Network-Artwork-v7.zip', 'dunemenus-v7.nginx.conf'] +for name in names: + if hashlib.sha256((bundle / name).read_bytes()).hexdigest() != manifest['files'][name]['sha256']: + raise ValueError('Publication checksum differs: ' + name) +downloads = Path('/var/lib/dunerealms-public-downloads') +parent = Path('/etc/nginx/snippets/dunerealms-gui-download-v3.conf') +route = Path('/etc/nginx/snippets/dunemenus-v7.nginx.conf') +pack = downloads / names[0] +if not downloads.is_dir() or not parent.is_file() or any(p.is_symlink() for p in [parent, route, pack]): + raise ValueError('Unexpected publication paths') +include = 'include /etc/nginx/snippets/dunemenus-v7.nginx.conf;' +old_parent = parent.read_bytes() +if include not in old_parent.decode() and names[0] in old_parent.decode(): + raise ValueError('An unmanaged v7 route already exists') +for path, source in [(pack, bundle / names[0]), (route, bundle / names[1])]: + if path.exists() and path.read_bytes() != source.read_bytes(): + raise ValueError('Refusing to overwrite different versioned content: ' + str(path)) +stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ') +backup = Path('/root/dunemenus-pack-before-' + stamp) +backup.mkdir(mode=0o700) +originals = {p: p.read_bytes() if p.exists() else None for p in [pack, route, parent]} +for path, content in originals.items(): + if content is not None: + shutil.copy2(path, backup / path.name) +try: + for destination, source in [(pack, bundle / names[0]), (route, bundle / names[1])]: + staged = destination.with_name(destination.name + '.build-staged') + if staged.exists() or staged.is_symlink(): + raise ValueError('Staging path exists') + shutil.copyfile(source, staged) + os.chmod(staged, 0o644) + os.replace(staged, destination) + if include not in old_parent.decode(): + parent.write_bytes(old_parent.rstrip() + b'\n' + include.encode() + b'\n') + subprocess.run(['nginx', '-t'], check=True, timeout=30) + subprocess.run(['systemctl', 'reload', 'nginx'], check=True, timeout=30) +except Exception: + for path, content in originals.items(): + if content is None: + if path.exists(): + path.unlink() + else: + path.write_bytes(content) + subprocess.run(['nginx', '-t'], check=True, timeout=30) + subprocess.run(['systemctl', 'reload', 'nginx'], check=True, timeout=30) + raise +print(json.dumps({'source': manifest['source'], 'backup': str(backup), 'url': manifest['pack_url'], + 'sha256': manifest['files'][names[0]]['sha256']})) -- 2.53.0 From 5690ae3db668ec6560ecbe8e91a96c8c281f9a2c Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:59:43 +0100 Subject: [PATCH 5/7] Include exact versioned pack download route --- network/resource-pack/dunemenus-v7.nginx.conf | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 network/resource-pack/dunemenus-v7.nginx.conf diff --git a/network/resource-pack/dunemenus-v7.nginx.conf b/network/resource-pack/dunemenus-v7.nginx.conf new file mode 100644 index 00000000..127cced7 --- /dev/null +++ b/network/resource-pack/dunemenus-v7.nginx.conf @@ -0,0 +1,6 @@ +location = /downloads/DuneRealms-Network-Artwork-v7.zip { + alias /var/lib/dunerealms-public-downloads/DuneRealms-Network-Artwork-v7.zip; + default_type application/zip; + add_header Cache-Control "public, max-age=31536000, immutable"; + add_header X-Content-Type-Options nosniff; +} -- 2.53.0 From 955424b42c5a8514aa2554ea7e0b37a2fdbab979 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:01:53 +0100 Subject: [PATCH 6/7] Include requested existing NPC features in the combined release --- tools/build-dunemenus-release.py | 2 +- tools/install-dunemenus-release.py | 6 +++--- tools/test_dunemenus_installer.py | 3 ++- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/tools/build-dunemenus-release.py b/tools/build-dunemenus-release.py index c2dfd847..b62fd6fc 100644 --- a/tools/build-dunemenus-release.py +++ b/tools/build-dunemenus-release.py @@ -20,7 +20,7 @@ pack=out/'DuneRealms-Network-Artwork-v7.zip' with zipfile.ZipFile(pack,'w',zipfile.ZIP_DEFLATED,compresslevel=9) as z: for name,data in sorted(entries.items()): zi=zipfile.ZipInfo(name,(2026,11,28,0,0,0));zi.compress_type=zipfile.ZIP_DEFLATED;z.writestr(zi,data) -for module,name in [('DuneMenus','DuneMenus.jar'),('DuneEss','DuneRealms-Essentials.jar'),('DuneLobby','DuneRealms-Lobby.jar'),('DuneRealms-minecraft-only','DuneRealms-Core.jar'),('JarvisConnector','jarvistranslator.jar')]: +for module,name in [('DuneMenus','DuneMenus.jar'),('DuneEss','DuneRealms-Essentials.jar'),('DuneLobby','DuneRealms-Lobby.jar'),('DuneRealms-minecraft-only','DuneRealms-Core.jar'),('DuneNPC','DuneRealms-NPC.jar'),('JarvisConnector','jarvistranslator.jar')]: shutil.copy2(root/module/'build/libs'/name,out/name) shutil.copy2(root/'tools/install-dunemenus-release.py',out/'install-dunemenus-release.py') shutil.copy2(root/'network/resource-pack/dunemenus-v7.nginx.conf',out/'dunemenus-v7.nginx.conf') diff --git a/tools/install-dunemenus-release.py b/tools/install-dunemenus-release.py index d39adf68..69d8b402 100644 --- a/tools/install-dunemenus-release.py +++ b/tools/install-dunemenus-release.py @@ -7,13 +7,13 @@ ALLOWED = {'/opt/dunerealms/lobby': 'dune-lobby.service', **{ f'/opt/dunerealms/servers/{x}': f'dune-{x}.service' for x in ['arrakis', 'caladan', 'giedi_prime', 'kaitain', 'sigma_draconis_iv']}} JARS = {'DuneMenus.jar', 'DuneRealms-Essentials.jar', 'DuneRealms-Lobby.jar', - 'DuneRealms-Core.jar', 'jarvistranslator.jar'} + 'DuneRealms-Core.jar', 'DuneRealms-NPC.jar', 'jarvistranslator.jar'} LEGACY = ('DunerealmsGUI.jar', 'DuneRealmsGUI.jar', 'DuneFullscreenPaper.jar', 'MCGUI.jar', 'DunerealmsGUI', 'DuneRealmsGUI', 'DuneFullscreenPaper', 'MCGUI') PACK = 'DuneRealms-Network-Artwork-v7.zip' IDENTITIES = {'DuneMenus.jar': 'DuneMenus', 'DuneRealms-Essentials.jar': 'DuneEss', 'DuneRealms-Lobby.jar': 'DuneLobby', 'DuneRealms-Core.jar': 'DuneCore', - 'jarvistranslator.jar': 'JarvisTranslator'} + 'DuneRealms-NPC.jar': 'DuneNPC', 'jarvistranslator.jar': 'JarvisTranslator'} def plugin_name(path): with ZipFile(path) as archive: @@ -74,7 +74,7 @@ def install(bundle, root, unit, backup_base=Path('/root'), runner=run): identity = plugin_name(jar) except Exception: require(not any(jar.name.lower().startswith(prefix) for prefix in - ('dunemenus', 'dunecore', 'duneess', 'dunelobby', 'dunerealms-core', + ('dunemenus', 'dunecore', 'duneess', 'dunelobby', 'dunenpc', 'dunerealms-npc', 'dunerealms-core', 'dunerealms-essentials', 'dunerealms-lobby', 'jarvistranslator')), 'Unreadable first-party plugin: '+jar.name) continue diff --git a/tools/test_dunemenus_installer.py b/tools/test_dunemenus_installer.py index 512efd33..94be3d81 100644 --- a/tools/test_dunemenus_installer.py +++ b/tools/test_dunemenus_installer.py @@ -149,7 +149,8 @@ class InstallerTests(unittest.TestCase): def test_legacy_versioned_filenames_are_replaced_without_duplicates(self): aliases = {'DuneRealms-Core.jar': 'DuneCore-1.0.10.jar', - 'DuneRealms-Essentials.jar': 'DuneEss-1.0.2.jar'} + 'DuneRealms-Essentials.jar': 'DuneEss-1.0.2.jar', + 'DuneRealms-NPC.jar': 'DuneNPC-1.0.0.jar'} for source, target in aliases.items(): (self.plugins / source).rename(self.plugins / target) result = self.invoke() -- 2.53.0 From c2018d6abea68536091ef4d247e45b79ddbe55f3 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:03:00 +0100 Subject: [PATCH 7/7] Include requested Spy Module assets from owner backup --- tools/build-dunemenus-release.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/build-dunemenus-release.py b/tools/build-dunemenus-release.py index b62fd6fc..fa0c4fd6 100644 --- a/tools/build-dunemenus-release.py +++ b/tools/build-dunemenus-release.py @@ -12,6 +12,9 @@ assets=[art/'assets/dunerealms/font/gui.json',*sorted((art/'assets/dunerealms/te assert len(assets)==13 font=json.loads(assets[0].read_text(encoding='utf-8')) for p in assets:entries[p.relative_to(art).as_posix()]=p.read_bytes() +for name in ['items/spy_module.json','models/item/spy_module.json','textures/item/spy_module.png']: + p=art/'assets/dunerealms'/name + entries[p.relative_to(art).as_posix()]=p.read_bytes() for provider in font['providers']: if provider.get('type')=='bitmap': namespace,path=provider['file'].split(':',1) -- 2.53.0