feat(patcher): build a loopback client copy with TypeScript
Add the shared BLK, VROMFS, executable patch, and build packages. Preserve typed fields and shared name tables when reading BLK data. Rewrite the service endpoints in place so the original environment names remain available to the client, then build the client copy.
This commit is contained in:
1 parent
89aa5198c3
commit
c3914ec0d6
44 files changed
+1986
-1
No files matched your search
@@ -0,0 +1,33 @@
|
||||
/** A whole .vromfs.bin data pack: read it, change files, write it back. */
|
||||
import { buildContainer, parseContainer, type ContainerInfo } from './container.ts';
|
||||
import { VromfsFormatError } from './errors.ts';
|
||||
import { buildImage, parseImage, type ImageLayout } from './image.ts';
|
||||
|
||||
export interface Archive {
|
||||
readonly container: ContainerInfo;
|
||||
readonly layout: ImageLayout;
|
||||
readonly files: Map<string, Uint8Array>;
|
||||
}
|
||||
|
||||
export function readArchive(data: Uint8Array): Archive {
|
||||
const { info, image } = parseContainer(data);
|
||||
const { layout, files } = parseImage(image);
|
||||
return { container: info, layout, files };
|
||||
}
|
||||
|
||||
export function writeArchive(archive: Archive): Uint8Array {
|
||||
return buildContainer(archive.container, buildImage(archive.layout, archive.files));
|
||||
}
|
||||
|
||||
/** Add or replace a file. The game lower-cases lookup paths, so stored paths must be lower case. */
|
||||
export function putFile(archive: Archive, path: string, content: Uint8Array): void {
|
||||
if (path !== path.toLowerCase()) throw new VromfsFormatError(`archive paths must be lower case: ${path}`);
|
||||
if (path.startsWith('/') || path.includes('\\')) throw new VromfsFormatError(`archive paths are relative and use '/': ${path}`);
|
||||
archive.files.set(path, content);
|
||||
}
|
||||
|
||||
export function getFile(archive: Archive, path: string): Uint8Array {
|
||||
const content = archive.files.get(path);
|
||||
if (!content) throw new VromfsFormatError(`the data pack has no file ${path}`);
|
||||
return content;
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* 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
|
||||
* 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.
|
||||
* Reading keeps everything except the image, so writing back reproduces the same container.
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { constants, zstdCompressSync, zstdDecompressSync } from 'node:zlib';
|
||||
import { VromfsFormatError } from './errors.ts';
|
||||
import { toggleObfuscation } from './obfuscation.ts';
|
||||
|
||||
export const SIGNATURE_SIZE = 0x100;
|
||||
const HEADER_SIZE = 16;
|
||||
const EXT_HEADER_SIZE = 8;
|
||||
const SIZE_MASK = 0x03ff_ffff;
|
||||
const COMPRESSION_LEVEL = 9;
|
||||
|
||||
export const PackType = {
|
||||
ZstdNoCheck: 0x10,
|
||||
Plain: 0x20,
|
||||
Zstd: 0x30,
|
||||
} as const;
|
||||
export type PackType = (typeof PackType)[keyof typeof PackType];
|
||||
|
||||
export interface ContainerInfo {
|
||||
readonly magic: 'VRFs' | 'VRFx';
|
||||
readonly platform: Uint8Array;
|
||||
readonly packType: PackType;
|
||||
/** Extended header (VRFx only): flags and the four version bytes exactly as stored. */
|
||||
readonly extended: { readonly flags: number; readonly version: Uint8Array } | null;
|
||||
readonly signature: Uint8Array;
|
||||
}
|
||||
|
||||
export function parseContainer(data: Uint8Array): { info: ContainerInfo; image: Uint8Array } {
|
||||
if (data.length < HEADER_SIZE) throw new VromfsFormatError('file too short for a container header');
|
||||
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
||||
const magic = Buffer.from(data.subarray(0, 4)).toString('latin1');
|
||||
if (magic !== 'VRFs' && magic !== 'VRFx') throw new VromfsFormatError(`unknown container magic ${JSON.stringify(magic)}`);
|
||||
const platform = data.slice(4, 8);
|
||||
const unpackedSize = view.getUint32(8, true);
|
||||
const packedWord = view.getUint32(12, true);
|
||||
const packType = toPackType(packedWord >>> 26);
|
||||
let cursor = HEADER_SIZE;
|
||||
|
||||
let extended: ContainerInfo['extended'] = null;
|
||||
if (magic === 'VRFx') {
|
||||
const extSize = view.getUint16(cursor, true);
|
||||
if (extSize !== EXT_HEADER_SIZE) throw new VromfsFormatError(`unexpected extended header size ${extSize}`);
|
||||
extended = { flags: view.getUint16(cursor + 2, true), version: data.slice(cursor + 4, cursor + 8) };
|
||||
cursor += EXT_HEADER_SIZE;
|
||||
}
|
||||
|
||||
const compressed = packType !== PackType.Plain;
|
||||
const storedSize = compressed ? packedWord & SIZE_MASK : unpackedSize;
|
||||
const image = unpackPayload(data.subarray(cursor, cursor + storedSize), compressed, unpackedSize);
|
||||
cursor += storedSize;
|
||||
|
||||
if (packType !== PackType.ZstdNoCheck) {
|
||||
if (!md5(image).equals(data.subarray(cursor, cursor + 16))) throw new VromfsFormatError('image MD5 does not match the container digest');
|
||||
cursor += 16;
|
||||
}
|
||||
|
||||
const signature = data.slice(cursor);
|
||||
if (signature.length !== 0 && signature.length !== SIGNATURE_SIZE) {
|
||||
throw new VromfsFormatError(`unexpected trailing data of ${signature.length} bytes`);
|
||||
}
|
||||
return { info: { magic, platform, packType, extended, signature }, image };
|
||||
}
|
||||
|
||||
/** Pack an image with the container settings it was read with. The signature tail is kept as read. */
|
||||
export function buildContainer(info: ContainerInfo, image: Uint8Array): Uint8Array {
|
||||
const compressed = info.packType !== PackType.Plain;
|
||||
const stored = compressed ? toggleObfuscation(zstdCompressSync(image, { params: { [constants.ZSTD_c_compressionLevel]: COMPRESSION_LEVEL } })) : image;
|
||||
if (compressed && stored.length > SIZE_MASK) throw new VromfsFormatError('compressed payload too large for the 26-bit size field');
|
||||
|
||||
const header = Buffer.alloc(HEADER_SIZE);
|
||||
header.write(info.magic, 0, 'latin1');
|
||||
header.set(info.platform, 4);
|
||||
header.writeUInt32LE(image.length, 8);
|
||||
header.writeUInt32LE(((info.packType << 26) | (compressed ? stored.length : 0)) >>> 0, 12);
|
||||
|
||||
const parts: Uint8Array[] = [header];
|
||||
if (info.magic === 'VRFx') {
|
||||
const ext = Buffer.alloc(EXT_HEADER_SIZE);
|
||||
ext.writeUInt16LE(EXT_HEADER_SIZE, 0);
|
||||
ext.writeUInt16LE(info.extended?.flags ?? 0, 2);
|
||||
if (info.extended) ext.set(info.extended.version, 4);
|
||||
parts.push(ext);
|
||||
}
|
||||
parts.push(stored);
|
||||
if (info.packType !== PackType.ZstdNoCheck) parts.push(md5(image));
|
||||
parts.push(info.signature);
|
||||
return Buffer.concat(parts);
|
||||
}
|
||||
|
||||
function unpackPayload(stored: Uint8Array, compressed: boolean, unpackedSize: number): Uint8Array {
|
||||
if (!compressed) return stored;
|
||||
let image: Uint8Array;
|
||||
try {
|
||||
image = zstdDecompressSync(toggleObfuscation(stored), { maxOutputLength: unpackedSize });
|
||||
} catch (error) {
|
||||
throw new VromfsFormatError(`payload decompression failed: ${(error as Error).message}`);
|
||||
}
|
||||
if (image.length !== unpackedSize) throw new VromfsFormatError(`image is ${image.length} bytes, header says ${unpackedSize}`);
|
||||
return image;
|
||||
}
|
||||
|
||||
function toPackType(value: number): PackType {
|
||||
if (value === PackType.ZstdNoCheck || value === PackType.Plain || value === PackType.Zstd) return value;
|
||||
throw new VromfsFormatError(`unknown pack type ${value.toString(16)}`);
|
||||
}
|
||||
|
||||
function md5(data: Uint8Array): Buffer {
|
||||
return createHash('md5').update(data).digest();
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/** The bytes are not a .vromfs.bin data pack this code understands, or an edit would make it invalid. */
|
||||
export class VromfsFormatError extends Error {
|
||||
override name = 'VromfsFormatError';
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* 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 shared name map "nm" (stored as "\xff?nm") last.
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { VromfsFormatError } from './errors.ts';
|
||||
|
||||
export const NAME_MAP_PATH = 'nm';
|
||||
const NAME_MAP_STORED = Buffer.from([0xff, 0x3f, 0x6e, 0x6d]);
|
||||
const ALIGN = 16;
|
||||
const DIGEST_SIZE = 20;
|
||||
|
||||
export interface ImageLayout {
|
||||
readonly hasDigestHeader: boolean;
|
||||
readonly hasDigests: boolean;
|
||||
}
|
||||
|
||||
export function parseImage(image: Uint8Array): { layout: ImageLayout; files: Map<string, Uint8Array> } {
|
||||
const view = new DataView(image.buffer, image.byteOffset, image.byteLength);
|
||||
const namesOffset = view.getUint32(0x00, true);
|
||||
const count = view.getUint32(0x04, true);
|
||||
const dataOffset = view.getUint32(0x10, true);
|
||||
if (view.getUint32(0x14, true) !== count) throw new VromfsFormatError('name count differs from data count');
|
||||
const hasDigestHeader = namesOffset === 0x30;
|
||||
const digestsBegin = hasDigestHeader ? view.getUint16(0x28, true) : 0;
|
||||
|
||||
const files = new Map<string, Uint8Array>();
|
||||
for (let index = 0; index < count; index++) {
|
||||
const path = readName(image, Number(view.getBigUint64(namesOffset + index * 8, true)));
|
||||
const offset = view.getUint32(dataOffset + index * ALIGN, true);
|
||||
const size = view.getUint32(dataOffset + index * ALIGN + 4, true);
|
||||
const content = image.slice(offset, offset + size);
|
||||
if (digestsBegin) {
|
||||
const expected = image.subarray(digestsBegin + index * DIGEST_SIZE, digestsBegin + (index + 1) * DIGEST_SIZE);
|
||||
if (!sha1(content).equals(expected)) throw new VromfsFormatError(`SHA-1 mismatch for ${path}`);
|
||||
}
|
||||
files.set(path, content);
|
||||
}
|
||||
return { layout: { hasDigestHeader, hasDigests: digestsBegin !== 0 }, files };
|
||||
}
|
||||
|
||||
export function buildImage(layout: ImageLayout, files: ReadonlyMap<string, Uint8Array>): Uint8Array {
|
||||
if (layout.hasDigests && !layout.hasDigestHeader) throw new VromfsFormatError('digests require the digest header');
|
||||
const paths = sortedPaths(files);
|
||||
const count = paths.length;
|
||||
const namesOffset = layout.hasDigestHeader ? 0x30 : 0x20;
|
||||
const namesBlobOffset = namesOffset + aligned(8 * count);
|
||||
|
||||
const encodedNames = paths.map((path) => (path === NAME_MAP_PATH ? NAME_MAP_STORED : Buffer.from(path, 'utf-8')));
|
||||
const nameOffsets: number[] = [];
|
||||
let namesSize = 0;
|
||||
for (const name of encodedNames) {
|
||||
nameOffsets.push(namesBlobOffset + namesSize);
|
||||
namesSize += name.length + 1;
|
||||
}
|
||||
const dataTableOffset = namesBlobOffset + aligned(namesSize);
|
||||
const digestsOffset = dataTableOffset + ALIGN * count;
|
||||
const firstDataOffset = digestsOffset + (layout.hasDigests ? aligned(DIGEST_SIZE * count) : 0);
|
||||
|
||||
const dataOffsets: number[] = [];
|
||||
let dataSize = 0;
|
||||
for (const path of paths) {
|
||||
dataOffsets.push(firstDataOffset + dataSize);
|
||||
dataSize += aligned(files.get(path)!.length);
|
||||
}
|
||||
|
||||
const out = Buffer.alloc(firstDataOffset + dataSize);
|
||||
out.writeUInt32LE(namesOffset, 0x00);
|
||||
out.writeUInt32LE(count, 0x04);
|
||||
out.writeUInt32LE(dataTableOffset, 0x10);
|
||||
out.writeUInt32LE(count, 0x14);
|
||||
if (layout.hasDigestHeader) {
|
||||
const [begin, end] = layout.hasDigests ? [digestsOffset, digestsOffset + DIGEST_SIZE * count] : [0, firstDataOffset];
|
||||
out.writeBigUInt64LE(BigInt(end), 0x20);
|
||||
out.writeUInt16LE(begin, 0x28);
|
||||
}
|
||||
paths.forEach((path, index) => {
|
||||
out.writeBigUInt64LE(BigInt(nameOffsets[index]!), namesOffset + index * 8);
|
||||
out.set(encodedNames[index]!, nameOffsets[index]!);
|
||||
const content = files.get(path)!;
|
||||
out.writeUInt32LE(dataOffsets[index]!, dataTableOffset + index * ALIGN);
|
||||
out.writeUInt32LE(content.length, dataTableOffset + index * ALIGN + 4);
|
||||
if (layout.hasDigests) out.set(sha1(content), digestsOffset + index * DIGEST_SIZE);
|
||||
out.set(content, dataOffsets[index]!);
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** File order the game expects: byte-wise path order, name map last. */
|
||||
export function sortedPaths(files: ReadonlyMap<string, Uint8Array>): string[] {
|
||||
const paths = [...files.keys()].filter((path) => path !== NAME_MAP_PATH)
|
||||
.sort((left, right) => Buffer.compare(Buffer.from(left, 'utf-8'), Buffer.from(right, 'utf-8')));
|
||||
if (files.has(NAME_MAP_PATH)) paths.push(NAME_MAP_PATH);
|
||||
return paths;
|
||||
}
|
||||
|
||||
function readName(image: Uint8Array, offset: number): string {
|
||||
const end = image.indexOf(0, offset);
|
||||
if (end < 0) throw new VromfsFormatError(`file name at ${offset} is not terminated`);
|
||||
const raw = Buffer.from(image.subarray(offset, end));
|
||||
return raw.equals(NAME_MAP_STORED) ? NAME_MAP_PATH : raw.toString('utf-8');
|
||||
}
|
||||
|
||||
function aligned(size: number): number {
|
||||
return Math.ceil(size / ALIGN) * ALIGN;
|
||||
}
|
||||
|
||||
function sha1(data: Uint8Array): Buffer {
|
||||
return createHash('sha1').update(data).digest();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* The game's .vromfs.bin data packs. Two layers:
|
||||
* - container (container.ts): header, zstd compression with a small XOR obfuscation, an MD5
|
||||
* of the inner image, and a 256-byte signature tail;
|
||||
* - image (image.ts): the file table (names, offsets, optional SHA-1 digests) and file data.
|
||||
*/
|
||||
export { getFile, putFile, readArchive, writeArchive, type Archive } from './archive.ts';
|
||||
export { PackType, type ContainerInfo } from './container.ts';
|
||||
export { VromfsFormatError } from './errors.ts';
|
||||
export { NAME_MAP_PATH, type ImageLayout } from './image.ts';
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
const KEY_WORDS = ['55aa55aa', '0ff00ff0', '55aa55aa', '48124812'].map((word) => Buffer.from(word, 'hex'));
|
||||
const HEAD_KEY = Buffer.concat(KEY_WORDS);
|
||||
const TAIL_KEY = Buffer.concat([...KEY_WORDS].reverse());
|
||||
const SIZE_MASK = 0x03ff_ffff;
|
||||
|
||||
export function toggleObfuscation(payload: Uint8Array): Uint8Array {
|
||||
const buffer = Uint8Array.from(payload);
|
||||
const size = buffer.length & SIZE_MASK;
|
||||
if (size >= 16) xorInto(buffer, 0, HEAD_KEY);
|
||||
if (size >= 32) xorInto(buffer, (size & 0x03ff_fffc) - 16, TAIL_KEY);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function xorInto(buffer: Uint8Array, start: number, key: Uint8Array): void {
|
||||
key.forEach((keyByte, index) => {
|
||||
buffer[start + index]! ^= keyByte;
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user