diff --git a/.forgejo/workflows/kaitain-typewriter.yml b/.forgejo/workflows/kaitain-typewriter.yml new file mode 100644 index 00000000..faaed2fd --- /dev/null +++ b/.forgejo/workflows/kaitain-typewriter.yml @@ -0,0 +1,31 @@ +name: Kaitain Typewriter Compatibility +on: + workflow_dispatch: + push: + branches: ['ops/kaitain-typewriter-*'] +jobs: + typewriter: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - name: Test guard and verify official matching extension + shell: bash + run: | + set -euo pipefail + python3 tools/test_kaitain_typewriter.py -v + python3 tools/fix-kaitain-typewriter.py --build typewriter-artifacts + printf '%s\n' "$(git rev-parse HEAD)" > typewriter-artifacts/SOURCE_COMMIT + (cd typewriter-artifacts && sha256sum -- *.jar *.json *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Kaitain-Typewriter + path: typewriter-artifacts/ + if-no-files-found: error diff --git a/docs/KAITAIN-TYPEWRITER-20261201.md b/docs/KAITAIN-TYPEWRITER-20261201.md new file mode 100644 index 00000000..5ab43309 --- /dev/null +++ b/docs/KAITAIN-TYPEWRITER-20261201.md @@ -0,0 +1,25 @@ +# Kaitain BasicExtension compatibility repair + +The installed engine file is named Typewriter-0.8.0.jar but its actual descriptor is +0.9.0-beta-177. BasicExtension is actually 0.8.0, and the engine explicitly rejects +it. Consequently all 25 Navigator entries fail to load. Their blueprint IDs exist +in both extensions; rewriting or deleting the page would not fix the dependency. + +This operation installs only the official BasicExtension from Modrinth version +728uFaZd, engineVersion 0.9.0-beta-177, verified against its published SHA-512 +and the reviewed SHA-256. Source provenance and all exact pins are in +tools/kaitain-typewriter.json. No vendor binary is committed to Git. + +The dedicated build validates declared class closure and downloads the unchanged +official asset. The installer refuses other roots, changed engine bytes, unknown +predecessors, missing blueprint implementations and dangling page triggers. +It retains the existing Navigator pages, staging, editor-off configuration and +all other JARs. It saves the small prior extension for rollback, stops Kaitain, +checks for drift before writing, atomically replaces the extension, then starts +Kaitain. It does not reset or copy any world/player data. A successful start +request is not readiness: verify fresh Paper Done, successful Basic loading, +25 loaded entries and absence of the old mismatch/missing-entry errors. + +Tests cover exact-engine refusal, unknown page references, vendor drift, +wrong-target refusal, failed-start rollback and stale-plan no-write preservation. +No disposable Paper runtime or real transaction is required on a production host. diff --git a/tools/fix-kaitain-typewriter.py b/tools/fix-kaitain-typewriter.py new file mode 100644 index 00000000..f5f2a60c --- /dev/null +++ b/tools/fix-kaitain-typewriter.py @@ -0,0 +1,166 @@ +"""Replace only Kaitain's incompatible BasicExtension with its official matching release.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import urllib.request +import zipfile + +ROOT = Path('/opt/dunerealms/servers/kaitain') +UNIT = 'dune-kaitain.service' +POLICY = json.loads(Path(__file__).with_name('kaitain-typewriter.json').read_text()) +RELATIVE = 'plugins/Typewriter/extensions/BasicExtension.jar' + + +def digest(path, algorithm='sha256'): + return hashlib.new(algorithm, Path(path).read_bytes()).hexdigest() + + +def extension(path, policy=POLICY): + if digest(path) != policy['extensionSha256'] or digest(path, 'sha512') != policy['extensionSha512']: + raise ValueError('Unreviewed BasicExtension bytes') + with zipfile.ZipFile(path) as jar: + if len(jar.namelist()) != len(set(jar.namelist())): + raise ValueError('Duplicate extension archive entries') + data = json.loads(jar.read('extension.json')) + info = data['extension'] + if info['name'] != 'Basic' or info['engineVersion'] != policy['engineVersion']: + raise ValueError('Extension does not match the retained engine') + for entry in data['entries']: + if entry['className'].replace('.', '/') + '.class' not in jar.namelist(): + raise ValueError('Missing declared entry implementation') + return data + + +def validate_page(page, metadata): + known = {entry['id'] for entry in metadata['entries']} + ids = {entry['id'] for entry in page['entries']} + if len(ids) != len(page['entries']): + raise ValueError('Duplicate Navigator entry IDs') + for entry in page['entries']: + if entry['blueprintId'] not in known: + raise ValueError('Navigator uses an unavailable entry: ' + entry['id']) + triggers = entry.get('triggers', []) + [t for option in entry.get('options', []) for t in option.get('triggers', [])] + if any(t not in ids for t in triggers): + raise ValueError('Navigator trigger references a missing entry') + + +def snapshot(root): + paths = list((root/'plugins').glob('*.jar')) + paths += [p for p in (root/'plugins/Typewriter').rglob('*') if p.is_file()] + paths += [root/name for name in ['server.properties', 'spigot.yml', 'bukkit.yml'] if (root/name).is_file()] + result = {} + for path in paths: + if path.is_symlink(): + raise ValueError('Unexpected symlink in reviewed inputs') + st = path.stat() + result[path.relative_to(root).as_posix()] = {'sha256': digest(path), 'uid': st.st_uid, 'gid': st.st_gid, + 'mode': st.st_mode & 0o7777, 'mtimeNs': st.st_mtime_ns} + return result + + +def plan(candidate, root=ROOT, unit=UNIT): + if root != ROOT or unit != UNIT or root.is_symlink(): + raise ValueError('Only the reviewed Kaitain server is supported') + metadata = extension(candidate) + engine = root/'plugins/Typewriter-0.8.0.jar' + if engine.is_symlink() or digest(engine) != POLICY['engineSha256']: + raise ValueError('Retained Typewriter engine differs') + target = root/RELATIVE + if target.is_symlink() or digest(target) not in [POLICY['previousExtensionSha256'], POLICY['extensionSha256']]: + raise ValueError('Unreviewed installed extension') + for folder in ['pages', 'staging']: + pages = list((root/'plugins/Typewriter'/folder).glob('*.json')) + if [p.name for p in pages] != ['dunerealms_navigator.json']: + raise ValueError('Unexpected Typewriter page set') + validate_page(json.loads(pages[0].read_text(encoding='utf-8')), metadata) + return snapshot(root) + + +def control(*args): + return subprocess.run(['systemctl', *args], text=True, capture_output=True, check=True).stdout.strip() + + +def apply(candidate, backup, root=ROOT, unit=UNIT, service=control): + before = plan(candidate, root, unit) + if service('is-active', unit) != 'active': + raise ValueError('Kaitain must be active before replacement') + backup.mkdir(parents=True, exist_ok=False) + target = root/RELATIVE + shutil.copy2(target, backup/'BasicExtension.jar') + receipt = {'before': before, 'status': 'prepared', 'newSha256': POLICY['extensionSha256']} + record = backup/'receipt.json' + record.write_text(json.dumps(receipt, indent=2)) + service('stop', unit) + wrote = False + try: + if service('show', unit, '--property=ActiveState', '--value') not in ['inactive', 'failed']: + raise RuntimeError('Kaitain did not stop') + if snapshot(root) != before: + raise ValueError('Reviewed files changed after planning') + stat = target.stat() + fd, name = tempfile.mkstemp(prefix='.basic-', dir=target.parent) + os.close(fd) + temporary = Path(name) + try: + shutil.copyfile(candidate, temporary) + extension(temporary) + temporary.chmod(stat.st_mode & 0o7777) + if hasattr(os, 'chown'): + os.chown(temporary, stat.st_uid, stat.st_gid) + temporary.replace(target) + wrote = True + finally: + temporary.unlink(missing_ok=True) + after = snapshot(root) + if set(after) != set(before) or any(v != after[k] for k, v in before.items() if k != RELATIVE): + raise ValueError('Unrelated file drift before restart') + service('start', unit) + receipt['status'] = 'start-accepted' + except Exception: + if wrote: + shutil.copy2(backup/'BasicExtension.jar', target) + st = before[RELATIVE] + if hasattr(os, 'chown'): + os.chown(target, st['uid'], st['gid']) + service('start', unit) + receipt['status'] = 'restored' if wrote else 'no-write-abort' + record.write_text(json.dumps(receipt, indent=2)) + raise + record.write_text(json.dumps(receipt, indent=2)) + return str(record) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--build', type=Path) + parser.add_argument('--candidate', type=Path) + parser.add_argument('--apply', action='store_true') + parser.add_argument('--backup', type=Path) + args = parser.parse_args() + if args.build: + args.build.mkdir(parents=True, exist_ok=False) + candidate = args.build/'BasicExtension.jar' + urllib.request.urlretrieve(POLICY['url'], candidate) + metadata = extension(candidate) + shutil.copy2(__file__, args.build/Path(__file__).name) + shutil.copy2(Path(__file__).with_name('kaitain-typewriter.json'), args.build/'kaitain-typewriter.json') + print(json.dumps({'officialExtension': POLICY['extensionSha256'], 'entries': len(metadata['entries'])})) + elif args.candidate: + if args.apply: + if not args.backup: + parser.error('--backup is required for the extension rollback copy') + print(json.dumps({'receipt': apply(args.candidate, args.backup)})) + else: + before = plan(args.candidate) + print(json.dumps({'target': str(ROOT/RELATIVE), 'retainedFiles': len(before)-1, 'enginePreserved': True})) + else: + parser.error('Choose --build or --candidate') + + +if __name__ == '__main__': + main() diff --git a/tools/kaitain-typewriter.json b/tools/kaitain-typewriter.json new file mode 100644 index 00000000..7d1c004a --- /dev/null +++ b/tools/kaitain-typewriter.json @@ -0,0 +1,10 @@ +{ + "engineVersion": "0.9.0-beta-177", + "engineSha256": "ffea29388b83b43f5bd48bba787e826deee6bfe8c0511a250f04e53977a1d4f8", + "previousExtensionSha256": "6f93cee929a5e7ada58b2e434d62c7e6c45db7a11980bd73609339fe764566a4", + "extensionSha256": "2e50f02e9889ed7b0f3813f6fb67ccf5ddb4ee17b5671ca828a45c51121c09f5", + "extensionSha512": "e732d2b0fc5e157956126839783f47dbd8f4df892e5bc41e723b5b79ed55d055d5e2f6917e8d350832ac88a93acd0631ac4c81817f27d52804fa20548a19665e", + "officialVersion": "https://modrinth.com/plugin/typewriter/version/728uFaZd", + "url": "https://cdn.modrinth.com/data/Vm7B3ymm/versions/728uFaZd/BasicExtension.jar", + "documentation": "https://docs.typewritermc.com/beta/docs/getting-started/installation" +} diff --git a/tools/test_kaitain_typewriter.py b/tools/test_kaitain_typewriter.py new file mode 100644 index 00000000..be0e1384 --- /dev/null +++ b/tools/test_kaitain_typewriter.py @@ -0,0 +1,97 @@ +import hashlib +import importlib.util +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch +import zipfile + +spec = importlib.util.spec_from_file_location('repair', Path(__file__).with_name('fix-kaitain-typewriter.py')) +repair = importlib.util.module_from_spec(spec) +spec.loader.exec_module(repair) + + +class CompatibilityGuard(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name)/'kaitain' + self.root.mkdir() + p = self.root/'plugins' + (p/'Typewriter/extensions').mkdir(parents=True) + self.candidate = Path(self.tmp.name)/'incoming.jar' + self.metadata = {'extension': {'name': 'Basic', 'engineVersion': '0.9.0-beta-177'}, + 'entries': [{'id': 'option', 'className': 'fixture.Option'}]} + with zipfile.ZipFile(self.candidate, 'w') as z: + z.writestr('extension.json', json.dumps(self.metadata)) + z.writestr('fixture/Option.class', b'\xca\xfe\xba\xbe') + (p/'Typewriter-0.8.0.jar').write_bytes(b'retained engine') + (p/'OtherPlugin.jar').write_bytes(b'other runtime') + (self.root/repair.RELATIVE).write_bytes(b'old extension') + self.page = {'entries': [{'id': 'home', 'blueprintId': 'option', 'triggers': []}]} + for folder in ['pages', 'staging']: + d = p/'Typewriter'/folder + d.mkdir() + (d/'dunerealms_navigator.json').write_text(json.dumps(self.page)) + (p/'Typewriter/config.yml').write_text('enabled: false\n') + self.policy = {**repair.POLICY, 'engineSha256': repair.digest(p/'Typewriter-0.8.0.jar'), + 'previousExtensionSha256': repair.digest(self.root/repair.RELATIVE), + 'extensionSha256': repair.digest(self.candidate), + 'extensionSha512': repair.digest(self.candidate, 'sha512')} + self.addCleanup(patch.stopall) + patch.object(repair, 'ROOT', self.root).start() + patch.dict(repair.POLICY, self.policy).start() + + def test_exact_engine_and_existing_page_are_required(self): + before = repair.plan(self.candidate, self.root) + self.assertIn('plugins/OtherPlugin.jar', before) + (self.root/'plugins/Typewriter-0.8.0.jar').write_bytes(b'wrong version') + with self.assertRaisesRegex(ValueError, 'engine differs'): + repair.plan(self.candidate, self.root) + + def test_unknown_entries_and_dangling_triggers_are_rejected(self): + for entry in [{'id': 'x', 'blueprintId': 'absent'}, + {'id': 'x', 'blueprintId': 'option', 'triggers': ['missing']}]: + with self.assertRaises(ValueError): + repair.validate_page({'entries': [entry]}, self.metadata) + + def test_vendor_byte_drift_is_rejected(self): + self.candidate.write_bytes(b'not the official release') + with self.assertRaisesRegex(ValueError, 'Unreviewed'): + repair.extension(self.candidate) + + def test_other_server_is_refused(self): + with self.assertRaisesRegex(ValueError, 'Only the reviewed Kaitain'): + repair.plan(self.candidate, self.root.parent) + + def test_failed_start_restores_only_extension(self): + before = repair.snapshot(self.root) + starts = [] + def service(*args): + if args[0] == 'is-active': return 'active' + if args[0] == 'show': return 'inactive' + if args[0] == 'start': + starts.append(1) + if len(starts) == 1: raise RuntimeError('start refused') + return '' + with self.assertRaisesRegex(RuntimeError, 'start refused'): + repair.apply(self.candidate, Path(self.tmp.name)/'rollback', self.root, service=service) + self.assertEqual(repair.snapshot(self.root), before) + self.assertEqual(len(starts), 2) + + def test_stale_plan_does_not_restore_over_new_config(self): + config = self.root/'plugins/Typewriter/config.yml' + def service(*args): + if args[0] == 'is-active': return 'active' + if args[0] == 'stop': config.write_text('new independent setting\n') + if args[0] == 'show': return 'inactive' + return '' + with self.assertRaisesRegex(ValueError, 'changed after planning'): + repair.apply(self.candidate, Path(self.tmp.name)/'rollback', self.root, service=service) + self.assertEqual(config.read_text(), 'new independent setting\n') + self.assertEqual((self.root/repair.RELATIVE).read_bytes(), b'old extension') + + +if __name__ == '__main__': + unittest.main()