363 lines
19 KiB
Python
363 lines
19 KiB
Python
#!/usr/bin/env python3
|
|
"""Octo patch server publisher (2026-11-23).
|
|
|
|
A channel repo is a static directory served over HTTP(S):
|
|
<repo>/<channel>/manifest.txt line manifest (format below), RSA-3072 PKCS#1 v1.5 SHA-256 signed
|
|
<repo>/<channel>/manifest.txt.sig raw signature
|
|
<repo>/<channel>/manifest-store.txt compact step list for STORE-capable updaters
|
|
<repo>/<channel>/manifest-store.txt.sig independent signature of the compact list
|
|
<repo>/<channel>/blobs/<sha256>.zst payloads (content addressed by the sha256 of the .zst bytes)
|
|
<repo>/<channel>/state.json publisher state (ordered steps); not read by clients
|
|
|
|
Step kinds, applied by OctoUpdater.exe in manifest order (STORE: see store_step.py; layout-independent, used
|
|
from build 56474304 on so compacted/repacked stores keep updating; CONTENT steps stay for older clients):
|
|
CONTENT a frozen content step (stage-plan.json): exact preconditions from the plan, new files, then the
|
|
.build.info switch last. Applied when the client's build key equals the step's parent key.
|
|
A new data.N archive ships as a zstd --patch-from delta against the parent's data.N-1, which the
|
|
plan already requires byte-exact on the client.
|
|
FILES a set of loose files (natives, addons): each PUT names the expected current state (sha256 / absent
|
|
/ any). Applied once; the client records applied FILES ids in _patch/applied.txt.
|
|
|
|
Manifest lines (space separated, paths use '/' and contain no spaces):
|
|
OCTO-PATCH 1
|
|
CHANNEL <name>
|
|
STEP CONTENT <id> <parent_build_key> <child_build_key>
|
|
REQ_SHA <target> <sha256>
|
|
REQ_IDX <bucket hex2> <idx file name> newest <bucket>*.idx in Data/data must be this name
|
|
REQ_SPAN <target> <offset> <bytes> <sha256>
|
|
REQ_ABSENT <target>
|
|
FILE <target> <sha256> <size> <blob sha256> <blob size> <zstd|zstd-patch> [<base target> <base sha256>]
|
|
ACTIVATE <target> <parent sha256> <child sha256> <blob sha256> <blob size>
|
|
STEP FILES <id>
|
|
PUT <target> <sha256> <size> <blob sha256> <blob size> <expect: any|absent|<sha256>>
|
|
STEP POLICY retired-paths
|
|
RETIRE <file-or-directory/> stop managing a file or a directory's descendants, leaving local copies in place
|
|
END
|
|
Usage:
|
|
publish.py --repo R --channel C add-content <frozen candidate dir> [--base-search DIR ...]
|
|
publish.py --repo R --channel C add-files <id> <target>=<source> ...
|
|
publish.py --repo R --channel C retire-path <file-or-directory/> [<file-or-directory/> ...]
|
|
publish.py --repo R --channel C sign (rewrite manifest + signature from state.json)
|
|
"""
|
|
import argparse, fcntl, hashlib, json, os, re, subprocess, sys, tempfile
|
|
from pathlib import Path
|
|
|
|
KEY = Path('/mnt/Games/@project/gateway/runtime/continuation-20261113/claude-linux-build-20261121/signing-key-PRIVATE/patch-manifest-key.pem')
|
|
PUBLIC_KEY = Path(__file__).with_name('patch-manifest-public.pem')
|
|
CLIENTS = [Path('/mnt/Games/OctoWoW-Windows-Client'), Path('/mnt/Games/OctoWoW-LOCAL-Client')]
|
|
|
|
def sha(p, chunk=1 << 24):
|
|
h = hashlib.sha256()
|
|
with open(p, 'rb') as f:
|
|
while b := f.read(chunk): h.update(b)
|
|
return h.hexdigest()
|
|
|
|
def blob(chan, src, base=None):
|
|
"""zstd-compress src (optionally as a delta against base) into blobs/<sha>.zst; return (sha, size)."""
|
|
d = chan / 'blobs'; d.mkdir(parents=True, exist_ok=True)
|
|
with tempfile.NamedTemporaryFile(dir=d, suffix='.tmp', delete=False) as t: tmp = Path(t.name)
|
|
cmd = ['zstd', '-q', '-f', '-19', '-T0', '--long=31', str(src), '-o', str(tmp)]
|
|
if base: cmd[1:1] = [f'--patch-from={base}']
|
|
subprocess.run(cmd, check=True)
|
|
s = sha(tmp); out = d / f'{s}.zst'
|
|
if out.exists(): tmp.unlink()
|
|
else: tmp.rename(out)
|
|
return s, out.stat().st_size
|
|
|
|
def find_base(target, want, cand, extra):
|
|
"""A local copy of the client's existing <target> with sha256 <want> (parent candidates, clients)."""
|
|
name = Path(target).name
|
|
seen = []
|
|
for d in [*extra, cand.parent]:
|
|
for p in Path(d).glob(f'*/physical/Data/data/{name}'): seen.append(p)
|
|
for c in CLIENTS: seen.append(c / target)
|
|
for p in seen:
|
|
if p.is_file() and p.stat().st_size and sha(p) == want: return p
|
|
raise SystemExit(f'no local copy of {target} with sha256 {want}')
|
|
|
|
def load_state(chan):
|
|
s = chan / 'state.json'
|
|
return json.loads(s.read_text()) if s.exists() else {'steps': []}
|
|
|
|
def save_state(chan, st):
|
|
checked_state_rules(st)
|
|
with tempfile.TemporaryDirectory(prefix='.manifest-', dir=chan) as work:
|
|
state = Path(work) / 'state.json'
|
|
state.write_text(json.dumps(st, indent=1) + '\n')
|
|
os.replace(state, chan / state.name)
|
|
|
|
def add_content(chan, cand, extra):
|
|
cand = cand.resolve(); plan = json.loads((cand / 'stage-plan.json').read_text())
|
|
st = load_state(chan); child = plan['candidate_build_key']
|
|
if any(s.get('child') == child for s in st['steps']): sys.exit(f'{child[:8]} already published')
|
|
check_frozen_plan('CONTENT', plan, checked_state_rules(st))
|
|
pre = plan['preconditions']; lines = []
|
|
have = {e['target']: e['sha256'] for e in pre['existing_exact_sha256']}
|
|
for t, s in have.items(): lines.append(f'REQ_SHA {t} {s}')
|
|
for b, n in pre['selected_index_generation_exact'].items(): lines.append(f'REQ_IDX {int(b):02x} {n}')
|
|
for s in pre['inherited_native_alias_exact_spans']: lines.append(f"REQ_SPAN {s['target']} {s['offset']} {s['bytes']} {s['sha256']}")
|
|
for t in pre['new_paths_absent']: lines.append(f'REQ_ABSENT {t}')
|
|
for e in plan['forward']['copy_verified_files']:
|
|
src = cand / e['artifact']; size = src.stat().st_size
|
|
assert sha(src) == e['sha256'], e['artifact']
|
|
tail = ''
|
|
name = Path(e['target']).name
|
|
if name.startswith('data.') and name[5:].isdigit():
|
|
bt = f"Data/data/data.{int(name[5:]) - 1:03d}"
|
|
if bt in have:
|
|
base = find_base(bt, have[bt], cand, extra)
|
|
bs, bz = blob(chan, src, base); enc = 'zstd-patch'; tail = f' {bt} {have[bt]}'
|
|
else: bs, bz = blob(chan, src); enc = 'zstd'
|
|
else: bs, bz = blob(chan, src); enc = 'zstd'
|
|
lines.append(f"FILE {e['target']} {e['sha256']} {size} {bs} {bz} {enc}{tail}")
|
|
print(f" {e['target']}: {size} -> {bz} ({enc})", flush=True)
|
|
fa = plan['forward']['final_activation']; src = cand / fa['file']
|
|
assert sha(src) == fa['child_sha256']
|
|
bs, bz = blob(chan, src)
|
|
lines.append(f"ACTIVATE {fa['target']} {fa['parent_sha256']} {fa['child_sha256']} {bs} {bz}")
|
|
st['steps'].append({'kind': 'CONTENT', 'id': child[:8], 'parent': plan['parent_build_key'], 'child': child,
|
|
'source': str(cand), 'lines': lines})
|
|
save_state(chan, st)
|
|
|
|
D3D12_NATIVES = {'GWNativeWire.dll', 'GWNativeBackend.dll', 'GWNativeBridge.dll', 'forever_codec.dll', 'version-hash.bin', 'addon-tail.bin'}
|
|
|
|
_WINDOWS_KEY = str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZ\\', 'abcdefghijklmnopqrstuvwxyz/')
|
|
_RESERVED_ROOTS = {'data', '_patch', '.build.info', 'octoupdater.exe', 'octoupdater.cfg'}
|
|
_DEVICE_NAME = re.compile(r'(?:con|prn|aux|nul|conin\$|conout\$|com[1-9]|lpt[1-9])', re.ASCII | re.IGNORECASE)
|
|
|
|
def canonical_file_path(path):
|
|
if not path or any(ch.isspace() or not ch.isprintable() or ch in '<>:"\\|?*' for ch in path):
|
|
return False
|
|
return all(part and not part.endswith('.') and not _DEVICE_NAME.fullmatch(part.split('.', 1)[0])
|
|
for part in path.split('/'))
|
|
|
|
def retirement_rules(paths):
|
|
if not isinstance(paths, list):
|
|
raise SystemExit('retired_paths must be a list of relative paths')
|
|
rules = {}
|
|
for path in paths:
|
|
if not isinstance(path, str) or not path.isascii() or not canonical_file_path(path.removesuffix('/')):
|
|
raise SystemExit(f'invalid retired path: {path!r}')
|
|
key = path.translate(_WINDOWS_KEY)
|
|
if key.split('/', 1)[0] in _RESERVED_ROOTS:
|
|
raise SystemExit(f'cannot retire reserved path: {path!r}')
|
|
rules.setdefault(key, path)
|
|
return rules
|
|
|
|
def retired_target(path, rules):
|
|
if not rules:
|
|
return False
|
|
# Older lists can spell the same Windows destination with backslashes,
|
|
# extra separators, dot components or trailing dots/spaces in a name.
|
|
# Keep '..' intact for the updater's existing traversal rejection.
|
|
parts = []
|
|
for part in path.translate(_WINDOWS_KEY).split('/'):
|
|
if part != '..':
|
|
part = part.rstrip(' .')
|
|
if part:
|
|
parts.append(part)
|
|
key = '/'.join(parts)
|
|
return key in rules or any(rule.endswith('/') and key.startswith(rule) for rule in rules)
|
|
|
|
def check_transition_targets(kind, sid, paths, rules):
|
|
for path in paths:
|
|
if retired_target(path, rules):
|
|
raise SystemExit(f"{kind} step {sid} requires retired path {path!r}")
|
|
|
|
def check_frozen_plan(kind, plan, rules):
|
|
if not rules:
|
|
return
|
|
# Refuse the candidate before writing any blob that the next server sync
|
|
# could copy. STORE exports only Data/config copies and final_activation.
|
|
forward = plan['forward']
|
|
targets = [forward['final_activation']['target']]
|
|
targets.extend(row['target'] for row in forward['copy_verified_files']
|
|
if kind == 'CONTENT' or row['target'].startswith('Data/config/'))
|
|
if kind == 'CONTENT':
|
|
pre = plan['preconditions']
|
|
targets.extend(pre['new_paths_absent'])
|
|
for field in ('existing_exact_sha256', 'inherited_native_alias_exact_spans'):
|
|
targets.extend(row['target'] for row in pre[field])
|
|
check_transition_targets(kind, plan['candidate_build_key'][:8], targets, rules)
|
|
|
|
def checked_state_rules(st):
|
|
rules = retirement_rules(st.get('retired_paths', []))
|
|
if not rules:
|
|
return rules
|
|
# Content transitions must remain replayable in full. This includes reads
|
|
# from the installed client (preconditions and delta bases) as well as writes.
|
|
for step in st['steps']:
|
|
if step['kind'] not in ('CONTENT', 'STORE'):
|
|
continue
|
|
for line in step['lines']:
|
|
fields = line.split()
|
|
if fields and fields[0] in ('FILE', 'CONF', 'ACTIVATE', 'REQ_SHA', 'REQ_SPAN', 'REQ_ABSENT'):
|
|
targets = [fields[1]]
|
|
if fields[0] == 'FILE' and len(fields) > 7 and fields[6] == 'zstd-patch':
|
|
targets.append(fields[7])
|
|
check_transition_targets(step['kind'], step['id'], targets, rules)
|
|
return rules
|
|
|
|
def retire_paths(chan, paths):
|
|
st = load_state(chan)
|
|
rules = retirement_rules(st.get('retired_paths', []))
|
|
for key, path in retirement_rules(paths).items():
|
|
rules.setdefault(key, path)
|
|
updated = list(rules.values())
|
|
if updated != st.get('retired_paths', []):
|
|
st['retired_paths'] = updated
|
|
save_state(chan, st)
|
|
|
|
def fresh_install_state(chan):
|
|
out = {}
|
|
path = chan / 'install.txt'
|
|
if path.exists():
|
|
for line in path.read_text().splitlines():
|
|
p = line.split(' ', 3)
|
|
if p[0] == 'F' and len(p) == 4: out[p[3]] = p[1]
|
|
return out
|
|
|
|
def add_files(chan, sid, pairs):
|
|
st = load_state(chan)
|
|
if any(s['id'] == sid for s in st['steps']): sys.exit(f'{sid} already published')
|
|
lines = []
|
|
# 2026-11-25: on Windows the app-local .\D3D12\D3D12Core.dll shim loads the Bridge from _classic_beta_/D3D12/ and
|
|
# the Bridge loads Wire/Backend/codec beside itself; Linux (Proton) loads the top-level copies. Every native goes
|
|
# to both, or Windows players keep running old natives (they ran 11-22 natives/11-23 codec until 2026-11-25).
|
|
pairs = list(pairs) + [f'_classic_beta_/D3D12/{t.split("/")[-1]}={src}' for t, _, src in (p.partition('=') for p in pairs)
|
|
if t.split('/')[-1] in D3D12_NATIVES and t == '_classic_beta_/' + t.split('/')[-1]
|
|
and not any(q.startswith(f'_classic_beta_/D3D12/{t.split("/")[-1]}=') for q in pairs)]
|
|
rules = retirement_rules(st.get('retired_paths', []))
|
|
if rules:
|
|
for pair in pairs:
|
|
target = pair.partition('=')[0]
|
|
if not canonical_file_path(target.replace('\\', '/')):
|
|
raise SystemExit(f'invalid loose file target: {target!r}')
|
|
if retired_target(target, rules):
|
|
raise SystemExit(f'cannot publish retired path: {target!r}')
|
|
# 2026-11-26: the 70334 client's integrity guard raises "Unsupported software detected" (0x1100, Security Crash
|
|
# at login/logout) for a GW native that lacks the project Authenticode signature. Refuse unsigned .dll natives.
|
|
for p in pairs:
|
|
target, _, src = p.partition('=')
|
|
if target.split('/')[-1] in D3D12_NATIVES and target.endswith('.dll') \
|
|
and b'OctoWoW Loader Dev' not in Path(src).read_bytes():
|
|
sys.exit(f'{src} is not signed (osslsigncode with the project key); unsigned natives crash the client')
|
|
for p in pairs:
|
|
target, _, src = p.partition('=')
|
|
src = Path(src); s = sha(src); bs, bz = blob(chan, src)
|
|
cur = None
|
|
for c in CLIENTS: # expected prior state = what the canonical client has now
|
|
if (c / target).exists(): cur = sha(c / target); break
|
|
# A file an earlier step already ships may be at any of its channel versions when a client replays the
|
|
# steps in order (out-of-order publishes, hand-installed clients); the replay ends on the newest anyway.
|
|
shipped = any(l.split()[0] == 'PUT' and l.split()[1] == target for st0 in st['steps'] if st0['kind'] == 'FILES' for l in st0['lines'])
|
|
# 2026-11-25: a fresh install starts from the frozen base release (install.txt), not from our canonical
|
|
# clients; multiclient's play-linux.sh said 'absent' while the base ships an older copy, so every fresh
|
|
# install stopped there. Strict expectations only when the base release agrees with the canonical client.
|
|
# 2026-11-29 (report dc422d): an add-on file a player edited (or kept from an older install) blocked every later
|
|
# update. Add-on Lua/XML/art is ours and safe to overwrite, so add-on targets never pin the old version.
|
|
addon = '/Interface/AddOns/' in target
|
|
base = fresh_install_state(chan).get(target)
|
|
strict = (cur or 'absent') if base == cur else None
|
|
lines.append(f"PUT {target} {s} {src.stat().st_size} {bs} {bz} {'any' if addon or shipped or cur == s or target == 'OctoUpdater.exe' or strict is None else strict}")
|
|
st['steps'].append({'kind': 'FILES', 'id': sid, 'lines': lines})
|
|
save_state(chan, st)
|
|
|
|
def compact_steps(steps):
|
|
# OctoUpdater selects the last STORE for a parent at the first matching
|
|
# CONTENT/STORE position. Preserve that position relative to FILES and
|
|
# other builds, including when a STORE was retrofitted later in the list.
|
|
stores = {s['parent']: s for s in steps if s['kind'] == 'STORE'}
|
|
for i, step in enumerate(steps):
|
|
if step['kind'] == 'CONTENT':
|
|
store = stores.get(step['parent'])
|
|
if store is not None and store['child'] == step['child']:
|
|
if i + 1 < len(steps) and steps[i + 1] is store:
|
|
continue
|
|
step = store
|
|
yield step
|
|
|
|
def published_steps(st):
|
|
rules = checked_state_rules(st)
|
|
if not rules:
|
|
return st['steps']
|
|
steps = [dict(kind='POLICY', id='retired-paths', lines=[f'RETIRE {path}' for path in rules.values()])]
|
|
for step in st['steps']:
|
|
if step['kind'] == 'FILES':
|
|
# Old clients ignore POLICY. Keep every FILES id, including empty
|
|
# steps, but never offer those clients a retired destination.
|
|
lines = []
|
|
for line in step['lines']:
|
|
fields = line.split(maxsplit=2)
|
|
if fields[:1] == ['PUT'] and retired_target(fields[1], rules):
|
|
continue
|
|
lines.append(line)
|
|
step = dict(step, lines=lines)
|
|
steps.append(step)
|
|
return steps
|
|
|
|
def write_signed_list(path, channel, steps, legacy_signature=None):
|
|
with path.open('w', encoding='utf-8', newline='\n') as out:
|
|
out.write(f'OCTO-PATCH 1\nCHANNEL {channel}\n')
|
|
if legacy_signature is not None:
|
|
# The in-game update notifier compares this legacy signature with
|
|
# its applied marker. Authenticate it inside the compact list.
|
|
out.write(f'LEGACY-SIGNATURE {legacy_signature.hex()}\n')
|
|
for step in steps:
|
|
header = f"STEP {step['kind']} {step['id']}"
|
|
if step['kind'] in ('CONTENT', 'STORE'):
|
|
header += f" {step['parent']} {step['child']}"
|
|
out.write(header + '\n')
|
|
for line in step['lines']:
|
|
out.write(line + '\n')
|
|
out.write('END\n')
|
|
signature = path.with_suffix('.txt.sig')
|
|
subprocess.run(['openssl', 'dgst', '-sha256', '-sign', str(KEY), '-out', signature, path], check=True)
|
|
subprocess.run(['openssl', 'dgst', '-sha256', '-verify', str(PUBLIC_KEY), '-signature', signature, path],
|
|
check=True, capture_output=True)
|
|
return signature
|
|
|
|
def sign(chan, name):
|
|
steps = published_steps(load_state(chan))
|
|
with tempfile.TemporaryDirectory(prefix='.manifest-', dir=chan) as work:
|
|
legacy = Path(work) / 'manifest.txt'
|
|
compact = Path(work) / 'manifest-store.txt'
|
|
legacy_sig = write_signed_list(legacy, name, steps)
|
|
compact_sig = write_signed_list(compact, name, compact_steps(steps), legacy_sig.read_bytes())
|
|
# Verify both products before replacing any served file. Each rename
|
|
# is atomic and each signature follows its complete body.
|
|
for source in (legacy, legacy_sig, compact, compact_sig):
|
|
os.replace(source, chan / source.name)
|
|
print('signed', chan / legacy.name, 'and', chan / compact.name)
|
|
|
|
def main():
|
|
a = argparse.ArgumentParser(); a.add_argument('--repo', required=True); a.add_argument('--channel', default='octo')
|
|
sub = a.add_subparsers(dest='cmd', required=True)
|
|
c = sub.add_parser('add-content'); c.add_argument('candidate'); c.add_argument('--base-search', action='append', default=[])
|
|
f = sub.add_parser('add-files'); f.add_argument('id'); f.add_argument('pairs', nargs='+')
|
|
r = sub.add_parser('retire-path'); r.add_argument('paths', nargs='+', metavar='PATH')
|
|
g = sub.add_parser('add-store'); g.add_argument('candidate')
|
|
sub.add_parser('sign')
|
|
x = a.parse_args(); chan = Path(x.repo) / x.channel; chan.mkdir(parents=True, exist_ok=True)
|
|
# Serialize state updates and signature promotion for this channel. Lock
|
|
# its directory inode so there is no lock file to publish or clean up.
|
|
directory = os.open(chan, os.O_RDONLY | os.O_DIRECTORY)
|
|
try:
|
|
fcntl.flock(directory, fcntl.LOCK_EX)
|
|
if x.cmd == 'add-content': add_content(chan, Path(x.candidate), [Path(p) for p in x.base_search])
|
|
elif x.cmd == 'add-files': add_files(chan, x.id, x.pairs)
|
|
elif x.cmd == 'retire-path': retire_paths(chan, x.paths)
|
|
elif x.cmd == 'add-store':
|
|
import store_step; st = load_state(chan); candidate = Path(x.candidate)
|
|
rules = checked_state_rules(st)
|
|
if rules:
|
|
check_frozen_plan('STORE', json.loads((candidate / 'stage-plan.json').read_text()), rules)
|
|
step = store_step.publish(chan, candidate)
|
|
if any(s.get('child') == step['child'] and s['kind'] == 'STORE' for s in st['steps']): sys.exit(f"{step['id']} already published as STORE")
|
|
st['steps'].append(step); save_state(chan, st)
|
|
sign(chan, x.channel)
|
|
finally:
|
|
os.close(directory)
|
|
|
|
if __name__ == '__main__': main()
|