plugins/tools/fix-kaitain-typewriter.py
unimatrixgit 6cbe5a6380
All checks were successful
Kaitain Typewriter Compatibility / typewriter (push) Successful in 6s
DuneRealms Plugin CI / plugins (push) Successful in 2m27s
Accept byte-identical Typewriter staging writes during shutdown
2026-12-01 18:59:02 +01:00

179 lines
7.7 KiB
Python

"""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 unchanged(before, after):
if set(before) != set(after):
return False
for key, value in before.items():
# Typewriter writes the same staging JSON at shutdown. Only its mtime may change.
if key == 'plugins/Typewriter/staging/dunerealms_navigator.json':
if any(value[field] != after[key][field] for field in ['sha256', 'uid', 'gid', 'mode']):
return False
elif value != after[key]:
return False
return True
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 not unchanged(before, snapshot(root)):
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 not unchanged({k:v for k,v in before.items() if k != RELATIVE}, {k:v for k,v in after.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()