feat(vromfs): read and rebuild VROMFS script packs

Split container handling from the file table and add a read-only PE view
for the patch engine. Apply declarative script edits at unique anchors and
preserve the input line endings and unmodified bytes.

Round-trip the 2.61.0.37 GUI pack byte-for-byte and verify that invalid
edit definitions and ambiguous matches are rejected.
This commit is contained in:
N0VAN0M4LY committed 2026-11-23 13:19:27 +08:00
1 parent b89e3c1ce7
commit 8d26ad0fbd
15 files changed
+677

No files matched your search

+1
View File
@@ -34,3 +34,4 @@ __pycache__/
.idea/
Thumbs.db
Desktop.ini
*.egg-info/
+21
View File
@@ -0,0 +1,21 @@
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "wtotools"
version = "0.1.0"
description = "Developer and installer tools for the War Thunder offline rewrite: script archives, exe patches, data extraction."
requires-python = ">=3.12"
dependencies = [
"pefile>=2024.8.26",
"capstone>=5.0",
"keystone-engine>=0.9.2",
"zstandard>=0.22",
]
[project.scripts]
wtotools = "wtotools.cli:main"
[tool.setuptools.packages.find]
where = ["src"]
+7
View File
@@ -0,0 +1,7 @@
"""Tools for the War Thunder offline rewrite.
Subpackages:
- vromfs: read and write the game's .vromfs.bin script/resource archives
- pe: read-only view of a PE executable (address mapping, sections, functions)
- exepatch: locate and apply declarative exe patches from the exe-patches/ tree
"""
+21
View File
@@ -0,0 +1,21 @@
"""Assemble the files that get deployed into a game copy.
Modules:
- overrides: declarative edit records for stock files (anchor + insert/replace)
- script_archive: produce a new .vromfs.bin from the stock one plus our overrides and added files
Nothing here reads or writes a game folder; callers pass bytes and get bytes back.
"""
from .errors import BuildError, OverrideError
from .overrides import OverrideRecord, apply_edits, load_overrides
from .script_archive import ScriptArchiveReport, build_script_archive
__all__ = [
"BuildError",
"OverrideError",
"OverrideRecord",
"ScriptArchiveReport",
"apply_edits",
"build_script_archive",
"load_overrides",
]
+10
View File
@@ -0,0 +1,10 @@
class BuildError(Exception):
"""A build input is unusable, so nothing was produced."""
class OverrideError(BuildError):
"""An override record does not fit the stock file it targets.
Raised instead of writing a guessed result: the caller reports which override
failed and which features depend on it, and the player decides how to proceed.
"""
+148
View File
@@ -0,0 +1,148 @@
"""Declarative edits to stock game files.
We keep our changes to stock files as records rather than as modified copies, so the
repository holds no game content and the same record can be applied to whatever game
version the player has. Each record is one JSON file:
{
"archive": "gui.vromfs.bin",
"path": "scripts/main.nut",
"why": "load the offline adapter before any interface code runs",
"features": ["A-offline-start"],
"edits": [
{"kind": "insert-after", "anchor": "#default:forbid-root-table\\n", "text": "...\\n"}
]
}
Every edit is anchored on text that must occur exactly once. If an anchor is missing or
ambiguous the record is refused (OverrideError) and nothing is written, so a game update
that moves the anchor produces a clear report instead of a corrupted file.
Records are written with plain "\\n" line breaks. Stock files use CRLF in places and LF in
others, sometimes within one file, so the engine matches the anchor against whichever form
the file actually uses and writes the inserted text the same way. The rest of the file is
left byte for byte as it was.
"""
from __future__ import annotations
import json
from dataclasses import dataclass
from pathlib import Path
from .errors import OverrideError
INSERT_AFTER = "insert-after"
INSERT_BEFORE = "insert-before"
REPLACE = "replace"
_KINDS = (INSERT_AFTER, INSERT_BEFORE, REPLACE)
@dataclass(frozen=True)
class Edit:
kind: str
anchor: str
text: str
@dataclass(frozen=True)
class OverrideRecord:
archive: str
path: str
why: str
features: tuple[str, ...]
edits: tuple[Edit, ...]
source: Path | None = None
@property
def label(self) -> str:
return f"{self.archive}:{self.path}"
def load_overrides(directory: Path) -> list[OverrideRecord]:
"""Read every *.json override record under `directory`, sorted by file name."""
records = [_parse_record(path, json.loads(path.read_text("utf-8"))) for path in sorted(directory.rglob("*.json"))]
_reject_duplicate_targets(records)
return records
def apply_edits(text: str, edits: tuple[Edit, ...], label: str) -> str:
"""Apply every edit to `text`, or raise OverrideError without changing anything."""
for index, edit in enumerate(edits):
text = _apply_one(text, edit, f"{label} edit {index + 1}")
return text
def _apply_one(text: str, edit: Edit, where: str) -> str:
newline = _resolve_newline(text, edit.anchor, where)
anchor = edit.anchor.replace("\n", newline)
replacement = edit.text.replace("\n", newline)
occurrences = text.count(anchor)
if occurrences == 0:
raise OverrideError(f"{where}: anchor not found in the stock file: {edit.anchor!r}")
if occurrences > 1:
raise OverrideError(f"{where}: anchor occurs {occurrences} times, so the position is ambiguous: {edit.anchor!r}")
if edit.kind == REPLACE:
return text.replace(anchor, replacement)
if replacement in text:
raise OverrideError(f"{where}: the text to insert is already present; the file looks already modified")
position = text.index(anchor)
if edit.kind == INSERT_AFTER:
position += len(anchor)
return text[:position] + replacement + text[position:]
def _resolve_newline(text: str, anchor: str, where: str) -> str:
"""Which line break this file uses where the anchor sits."""
if "\n" not in anchor:
return _dominant_newline(text)
matching = [newline for newline in ("\r\n", "\n") if anchor.replace("\n", newline) in text]
if len(matching) > 1:
raise OverrideError(f"{where}: anchor matches with both CRLF and LF line breaks, so the position is ambiguous")
return matching[0] if matching else _dominant_newline(text)
def _dominant_newline(text: str) -> str:
crlf = text.count("\r\n")
return "\r\n" if crlf >= text.count("\n") - crlf else "\n"
def _parse_record(source: Path, raw: object) -> OverrideRecord:
if not isinstance(raw, dict):
raise OverrideError(f"{source}: expected a JSON object")
missing = [key for key in ("archive", "path", "why", "edits") if key not in raw]
if missing:
raise OverrideError(f"{source}: missing required key(s): {', '.join(missing)}")
edits = tuple(_parse_edit(source, item) for item in raw["edits"])
if not edits:
raise OverrideError(f"{source}: the record has no edits")
return OverrideRecord(
archive=str(raw["archive"]),
path=str(raw["path"]),
why=str(raw["why"]),
features=tuple(str(item) for item in raw.get("features", ())),
edits=edits,
source=source,
)
def _parse_edit(source: Path, raw: object) -> Edit:
if not isinstance(raw, dict):
raise OverrideError(f"{source}: every edit must be a JSON object")
kind = str(raw.get("kind", ""))
if kind not in _KINDS:
raise OverrideError(f"{source}: edit kind must be one of {', '.join(_KINDS)}, got {kind!r}")
for key in ("anchor", "text"):
if not isinstance(raw.get(key), str) or not raw[key]:
raise OverrideError(f"{source}: edit needs a non-empty string {key!r}")
return Edit(kind=kind, anchor=raw["anchor"], text=raw["text"])
def _reject_duplicate_targets(records: list[OverrideRecord]) -> None:
seen: dict[str, Path | None] = {}
for record in records:
if record.label in seen:
raise OverrideError(f"two records target {record.label}: {seen[record.label]} and {record.source}")
seen[record.label] = record.source
@@ -0,0 +1,61 @@
"""Produce a deployable .vromfs.bin from the stock one plus our changes.
Two kinds of change go in:
- overrides: anchored edits to files that already exist in the stock archive
- added files: our own new files, which must not collide with a stock path
Everything is validated before any output is produced, so a failure leaves the caller
with an error and no half-built archive.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from ..vromfs import read_archive, write_archive
from .errors import BuildError, OverrideError
from .overrides import OverrideRecord, apply_edits
@dataclass
class ScriptArchiveReport:
archive: str
stock_file_count: int
overridden: list[str] = field(default_factory=list)
added: list[str] = field(default_factory=list)
@property
def summary(self) -> str:
return (f"{self.archive}: {self.stock_file_count} stock files, "
f"{len(self.overridden)} overridden, {len(self.added)} added")
def build_script_archive(
archive_name: str,
stock: bytes,
overrides: list[OverrideRecord],
added_files: dict[str, bytes],
) -> tuple[bytes, ScriptArchiveReport]:
archive = read_archive(stock)
report = ScriptArchiveReport(archive=archive_name, stock_file_count=len(archive.files))
for record in [item for item in overrides if item.archive == archive_name]:
archive.files[record.path] = _edited(archive.files, record)
report.overridden.append(record.path)
for path, content in sorted(added_files.items()):
if path in archive.files:
raise BuildError(f"{archive_name}: {path} already exists in the stock archive; use an override record")
archive.put(path, content)
report.added.append(path)
return write_archive(archive), report
def _edited(files: dict[str, bytes], record: OverrideRecord) -> bytes:
if record.path not in files:
raise OverrideError(f"{record.label}: the stock archive has no such file")
try:
text = files[record.path].decode("utf-8")
except UnicodeDecodeError as error:
raise OverrideError(f"{record.label}: stock file is not UTF-8 text, cannot apply text edits") from error
return apply_edits(text, record.edits, record.label).encode("utf-8")
+4
View File
@@ -0,0 +1,4 @@
"""Read-only view of a PE executable."""
from .image import PeImage, Section
__all__ = ["PeImage", "Section"]
+77
View File
@@ -0,0 +1,77 @@
"""Address mapping, sections and function ranges of a PE image held in memory.
Addresses are RVAs (relative to the image base) unless a name says otherwise.
The view never modifies the bytes it was built from.
"""
from __future__ import annotations
import bisect
import struct
from dataclasses import dataclass
from functools import cached_property
import pefile
_EXCEPTION_DIRECTORY = 3
@dataclass(frozen=True)
class Section:
name: str
rva: int
virtual_size: int
raw_offset: int
raw_size: int
def contains_rva(self, rva: int) -> bool:
return self.rva <= rva < self.rva + max(self.virtual_size, self.raw_size)
class PeImage:
def __init__(self, data: bytes):
self.data = data
self._pe = pefile.PE(data=data, fast_load=True)
self.image_base = self._pe.OPTIONAL_HEADER.ImageBase
self.sections = [
Section(s.Name.rstrip(b"\0").decode(), s.VirtualAddress, s.Misc_VirtualSize, s.PointerToRawData, s.SizeOfRawData)
for s in self._pe.sections
]
def section(self, name: str) -> Section:
for section in self.sections:
if section.name == name:
return section
raise KeyError(f"no section {name}")
def section_of(self, rva: int) -> Section:
for section in self.sections:
if section.contains_rva(rva):
return section
raise ValueError(f"RVA {rva:#x} is outside every section")
def file_offset(self, rva: int) -> int:
section = self.section_of(rva)
if rva - section.rva >= section.raw_size:
raise ValueError(f"RVA {rva:#x} has no file bytes (uninitialised data)")
return rva - section.rva + section.raw_offset
def read(self, rva: int, size: int) -> bytes:
offset = self.file_offset(rva)
return self.data[offset:offset + size]
def section_bytes(self, name: str) -> bytes:
section = self.section(name)
return self.data[section.raw_offset:section.raw_offset + min(section.virtual_size, section.raw_size)]
@cached_property
def functions(self) -> list[tuple[int, int]]:
"""(begin, end) RVA pairs from the exception directory, sorted by begin."""
directory = self._pe.OPTIONAL_HEADER.DATA_DIRECTORY[_EXCEPTION_DIRECTORY]
raw = self.read(directory.VirtualAddress, directory.Size)
return sorted((begin, end) for begin, end, _unwind in struct.iter_unpack("<III", raw))
def function_containing(self, rva: int) -> tuple[int, int] | None:
index = bisect.bisect_right(self.functions, (rva, 1 << 32)) - 1
if index >= 0 and self.functions[index][0] <= rva < self.functions[index][1]:
return self.functions[index]
return None
+13
View File
@@ -0,0 +1,13 @@
"""Read and write .vromfs.bin archives.
A .vromfs.bin file has two layers:
- container (container.py): header, zstd compression with a small XOR obfuscation,
an MD5 of the inner image, and a 256-byte signature tail;
- image (image.py): the file table (names, offsets, optional SHA-1 digests) and file data.
archive.py ties them together; most callers only need `read_archive` / `write_archive`.
"""
from .archive import Archive, read_archive, write_archive
from .errors import VromfsFormatError
__all__ = ["Archive", "VromfsFormatError", "read_archive", "write_archive"]
+33
View File
@@ -0,0 +1,33 @@
"""High-level archive access: read a .vromfs.bin, change files, write it back."""
from __future__ import annotations
from dataclasses import dataclass, field
from .container import ContainerInfo, build_container, parse_container
from .errors import VromfsFormatError
from .image import ImageLayout, build_image, parse_image
@dataclass
class Archive:
container: ContainerInfo
layout: ImageLayout
files: dict[str, bytes] = field(default_factory=dict)
def put(self, path: str, content: bytes) -> None:
"""Add or replace a file. The game lower-cases lookup paths, so stored paths must be lower case."""
if path != path.lower():
raise VromfsFormatError(f"archive paths must be lower case: {path}")
if path.startswith("/") or "\\" in path:
raise VromfsFormatError(f"archive paths are relative and use '/': {path}")
self.files[path] = content
def read_archive(data: bytes) -> Archive:
container, image = parse_container(data)
layout, files = parse_image(image)
return Archive(container, layout, files)
def write_archive(archive: Archive) -> bytes:
return build_container(archive.container, build_image(archive.layout, archive.files))
+128
View File
@@ -0,0 +1,128 @@
"""Outer layer of a .vromfs.bin file.
Layout:
header 16 bytes: magic (VRFs | VRFx), platform, unpacked size, packed word
ext header 8 bytes, only for VRFx: size (=8), flags, version (stored reversed)
payload compressed (zstd, obfuscated) or plain image bytes
digest 16-byte MD5 of the unpacked image, absent for the "no check" pack type
signature 0 or 256 trailing bytes
The packed word is little-endian: top 6 bits are the pack type, low 26 bits the packed size.
"""
from __future__ import annotations
import hashlib
import struct
from dataclasses import dataclass
from enum import Enum
import zstandard
from . import obfuscation
from .errors import VromfsFormatError
SIGNATURE_SIZE = 0x100
_HEADER = struct.Struct("<4s4sII")
_EXT_HEADER = struct.Struct("<HH4s")
class Magic(Enum):
VRFS = b"VRFs"
VRFX = b"VRFx"
class PackType(Enum):
ZSTD_NO_CHECK = 0x10
PLAIN = 0x20
ZSTD = 0x30
@property
def compressed(self) -> bool:
return self is not PackType.PLAIN
@property
def checked(self) -> bool:
return self is not PackType.ZSTD_NO_CHECK
@dataclass(frozen=True)
class ContainerInfo:
"""Everything about the container except the image itself; reused when writing back."""
magic: Magic
platform: bytes
pack_type: PackType
ext_flags: int | None
version: tuple[int, int, int, int] | None
signature: bytes
def parse_container(data: bytes) -> tuple[ContainerInfo, bytes]:
"""Return the container description and the unpacked inner image."""
if len(data) < _HEADER.size:
raise VromfsFormatError("file too short for a container header")
magic_raw, platform, unpacked_size, packed_word = _HEADER.unpack_from(data, 0)
try:
magic = Magic(magic_raw)
pack_type = PackType(packed_word >> 26)
except ValueError as error:
raise VromfsFormatError(f"unknown container header: {error}") from error
packed_size = packed_word & 0x03FF_FFFF
cursor = _HEADER.size
ext_flags = version = None
if magic is Magic.VRFX:
ext_size, ext_flags, version_raw = _EXT_HEADER.unpack_from(data, cursor)
if ext_size != _EXT_HEADER.size:
raise VromfsFormatError(f"unexpected extended header size {ext_size}")
version = tuple(reversed(version_raw))
cursor += _EXT_HEADER.size
stored_size = packed_size if pack_type.compressed else unpacked_size
stored = data[cursor:cursor + stored_size]
cursor += stored_size
image = _unpack_payload(stored, pack_type, unpacked_size)
if pack_type.checked:
digest = data[cursor:cursor + 16]
cursor += 16
if hashlib.md5(image).digest() != digest:
raise VromfsFormatError("image MD5 does not match the container digest")
signature = data[cursor:]
if len(signature) not in (0, SIGNATURE_SIZE):
raise VromfsFormatError(f"unexpected trailing data of {len(signature)} bytes")
info = ContainerInfo(magic, platform, pack_type, ext_flags, version, signature)
return info, image
def build_container(info: ContainerInfo, image: bytes) -> bytes:
"""Pack an inner image using the same container settings it was read with."""
stored = _pack_payload(image, info.pack_type)
packed_size = len(stored) if info.pack_type.compressed else 0
if packed_size > 0x03FF_FFFF:
raise VromfsFormatError("compressed payload too large for the 26-bit size field")
parts = [_HEADER.pack(info.magic.value, info.platform, len(image), (info.pack_type.value << 26) | packed_size)]
if info.magic is Magic.VRFX:
parts.append(_EXT_HEADER.pack(_EXT_HEADER.size, info.ext_flags or 0, bytes(reversed(info.version))))
parts.append(stored)
if info.pack_type.checked:
parts.append(hashlib.md5(image).digest())
parts.append(info.signature)
return b"".join(parts)
def _unpack_payload(stored: bytes, pack_type: PackType, unpacked_size: int) -> bytes:
if not pack_type.compressed:
return stored
compressed = obfuscation.toggle(stored)
image = zstandard.ZstdDecompressor().decompress(compressed, max_output_size=unpacked_size)
if len(image) != unpacked_size:
raise VromfsFormatError(f"image is {len(image)} bytes, header says {unpacked_size}")
return image
def _pack_payload(image: bytes, pack_type: PackType) -> bytes:
if not pack_type.compressed:
return image
compressed = zstandard.ZstdCompressor(level=9, write_content_size=True).compress(image)
return obfuscation.toggle(compressed)
+2
View File
@@ -0,0 +1,2 @@
class VromfsFormatError(ValueError):
"""The bytes are not a .vromfs.bin archive this tool understands, or an edit would make it invalid."""
+124
View File
@@ -0,0 +1,124 @@
"""Inner image of a .vromfs.bin: the file table and file data.
Layout (every block aligned to 16 bytes):
0x00 names header: u32 offset of the name-offset table, u32 file count
0x10 data header: u32 offset of the data table, u32 file count
0x20 digest header: u64 end, u16 begin (only when names offset == 0x30)
name offsets: count x u64, each pointing at a NUL-terminated path
names
data table: count x 16 bytes: u32 offset, u32 size, 8 bytes padding
digests: count x 20-byte SHA-1 (only when digest begin != 0)
file data
The game binary-searches the full path bytes, so entries are sorted by their UTF-8
bytes, with the special name-map file "nm" (stored as b"\\xff?nm") last.
"""
from __future__ import annotations
import hashlib
import struct
from dataclasses import dataclass
from .errors import VromfsFormatError
NAME_MAP_PATH = "nm"
_NAME_MAP_STORED = b"\xff?nm"
_ALIGN = 16
_PAIR = struct.Struct("<II")
_DIGEST_HEADER = struct.Struct("<QH")
_DIGEST_SIZE = 20
@dataclass(frozen=True)
class ImageLayout:
"""Optional features of the file table, kept so a rewritten image matches the original."""
has_digest_header: bool
has_digests: bool
def parse_image(image: bytes) -> tuple[ImageLayout, dict[str, bytes]]:
names_offset, count = _PAIR.unpack_from(image, 0x00)
data_offset, data_count = _PAIR.unpack_from(image, 0x10)
if count != data_count:
raise VromfsFormatError(f"name count {count} differs from data count {data_count}")
has_digest_header = names_offset == 0x30
digests_begin = _DIGEST_HEADER.unpack_from(image, 0x20)[1] if has_digest_header else 0
paths = [_read_name(image, offset) for offset in struct.unpack_from(f"<{count}Q", image, names_offset)]
files: dict[str, bytes] = {}
for index, path in enumerate(paths):
offset, size = _PAIR.unpack_from(image, data_offset + index * _ALIGN)
content = image[offset:offset + size]
if digests_begin:
expected = image[digests_begin + index * _DIGEST_SIZE:digests_begin + (index + 1) * _DIGEST_SIZE]
if hashlib.sha1(content).digest() != expected:
raise VromfsFormatError(f"SHA-1 mismatch for {path}")
files[path] = content
return ImageLayout(has_digest_header, bool(digests_begin)), files
def build_image(layout: ImageLayout, files: dict[str, bytes]) -> bytes:
if layout.has_digests and not layout.has_digest_header:
raise VromfsFormatError("digests require the digest header")
paths = sorted_paths(files)
count = len(paths)
names_offset = 0x30 if layout.has_digest_header else 0x20
names_blob, name_offsets = _build_names(paths, names_offset + _aligned(8 * count))
data_table_offset = names_offset + _aligned(8 * count) + len(names_blob)
digests_offset = data_table_offset + _ALIGN * count
first_data_offset = digests_offset + (_aligned(_DIGEST_SIZE * count) if layout.has_digests else 0)
data_blob, data_entries = _build_data(paths, files, first_data_offset)
out = bytearray(first_data_offset)
_PAIR.pack_into(out, 0x00, names_offset, count)
_PAIR.pack_into(out, 0x10, data_table_offset, count)
if layout.has_digest_header:
begin, end = (digests_offset, digests_offset + _DIGEST_SIZE * count) if layout.has_digests else (0, first_data_offset)
_DIGEST_HEADER.pack_into(out, 0x20, end, begin)
struct.pack_into(f"<{count}Q", out, names_offset, *name_offsets)
out[names_offset + _aligned(8 * count):data_table_offset] = names_blob
for index, (offset, size) in enumerate(data_entries):
_PAIR.pack_into(out, data_table_offset + index * _ALIGN, offset, size)
if layout.has_digests:
for index, path in enumerate(paths):
out[digests_offset + index * _DIGEST_SIZE:digests_offset + (index + 1) * _DIGEST_SIZE] = hashlib.sha1(files[path]).digest()
return bytes(out) + data_blob
def sorted_paths(files: dict[str, bytes]) -> list[str]:
"""File order the game expects: byte-wise path order, name map last."""
paths = sorted((path for path in files if path != NAME_MAP_PATH), key=lambda path: path.encode("utf-8"))
if NAME_MAP_PATH in files:
paths.append(NAME_MAP_PATH)
return paths
def _read_name(image: bytes, offset: int) -> str:
raw = image[offset:image.index(b"\0", offset)]
return NAME_MAP_PATH if raw == _NAME_MAP_STORED else raw.decode("utf-8")
def _build_names(paths: list[str], base: int) -> tuple[bytes, list[int]]:
blob = bytearray()
offsets = []
for path in paths:
offsets.append(base + len(blob))
blob += (_NAME_MAP_STORED if path == NAME_MAP_PATH else path.encode("utf-8")) + b"\0"
blob += bytes(_aligned(len(blob)) - len(blob))
return bytes(blob), offsets
def _build_data(paths: list[str], files: dict[str, bytes], base: int) -> tuple[bytes, list[tuple[int, int]]]:
blob = bytearray()
entries = []
for path in paths:
content = files[path]
entries.append((base + len(blob), len(content)))
blob += content + bytes(_aligned(len(content)) - len(content))
return bytes(blob), entries
def _aligned(size: int) -> int:
return (size + _ALIGN - 1) & ~(_ALIGN - 1)
+27
View File
@@ -0,0 +1,27 @@
"""XOR obfuscation applied to the compressed payload of a container.
The first 16 bytes are XORed with a fixed key; if the payload is at least 32 bytes long,
the 16 bytes ending at the last 4-byte boundary are XORed with the same key words in
reverse order. The operation is its own inverse.
"""
_KEY_WORDS = tuple(bytes.fromhex(word) for word in ("55aa55aa", "0ff00ff0", "55aa55aa", "48124812"))
_HEAD_KEY = b"".join(_KEY_WORDS)
_TAIL_KEY = b"".join(reversed(_KEY_WORDS))
_SIZE_MASK = 0x03FF_FFFF
def _xor_into(buffer: bytearray, start: int, key: bytes) -> None:
for index, key_byte in enumerate(key):
buffer[start + index] ^= key_byte
def toggle(payload: bytes) -> bytes:
"""Obfuscate or de-obfuscate (same operation) a compressed payload."""
buffer = bytearray(payload)
size = len(buffer) & _SIZE_MASK
if size >= 16:
_xor_into(buffer, 0, _HEAD_KEY)
if size >= 32:
_xor_into(buffer, (size & 0x03FF_FFFC) - 16, _TAIL_KEY)
return bytes(buffer)