diff --git a/README.md b/README.md index 74c15ac..6671a84 100644 --- a/README.md +++ b/README.md @@ -8,5 +8,6 @@ | 目录 | 内容 | |---|---| -| `tools/` | Python 工具:数据包读写、exe 补丁引擎 | +| `packages/` | TypeScript(npm workspace):BLK 编解码、数据包读写、exe 补丁应用、构建流程,以后还有本地服务和启动器 | +| `tools/` | Python 开发端工具:数据包读写、exe 补丁引擎(特征码生成、汇编核对) | | `exe-patches/` | exe 补丁定义 | diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..cd4501c --- /dev/null +++ b/package-lock.json @@ -0,0 +1,83 @@ +{ + "name": "wto", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "wto", + "workspaces": [ + "packages/*" + ], + "devDependencies": { + "@types/node": "^24.19.2", + "typescript": "5.9" + }, + "engines": { + "node": ">=24" + } + }, + "node_modules/@types/node": { + "version": "24.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", + "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/@wto/blk": { + "resolved": "packages/blk", + "link": true + }, + "node_modules/@wto/build": { + "resolved": "packages/build", + "link": true + }, + "node_modules/@wto/exepatch": { + "resolved": "packages/exepatch", + "link": true + }, + "node_modules/@wto/vromfs": { + "resolved": "packages/vromfs", + "link": true + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "dev": true, + "license": "MIT" + }, + "packages/blk": { + "name": "@wto/blk", + "version": "0.1.0" + }, + "packages/build": { + "name": "@wto/build", + "version": "0.1.0" + }, + "packages/exepatch": { + "name": "@wto/exepatch", + "version": "0.1.0" + }, + "packages/vromfs": { + "name": "@wto/vromfs", + "version": "0.1.0" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..e42a713 --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "wto", + "private": true, + "description": "War Thunder offline project: local services emulating Gaijin's servers, and the build pipeline for the game copy.", + "type": "module", + "workspaces": [ + "packages/*" + ], + "scripts": { + "typecheck": "tsc -p tsconfig.json --noEmit" + }, + "engines": { + "node": ">=24" + }, + "devDependencies": { + "@types/node": "^24.19.2", + "typescript": "5.9" + } +} diff --git a/packages/blk/package.json b/packages/blk/package.json new file mode 100644 index 0000000..bebe66c --- /dev/null +++ b/packages/blk/package.json @@ -0,0 +1,9 @@ +{ + "name": "@wto/blk", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts" + } +} diff --git a/packages/blk/src/binary/byte-reader.ts b/packages/blk/src/binary/byte-reader.ts new file mode 100644 index 0000000..fba551b --- /dev/null +++ b/packages/blk/src/binary/byte-reader.ts @@ -0,0 +1,44 @@ +/** Sequential little-endian reader over a byte array, with the format's variable-length integers. */ +import { BlkFormatError } from '../errors.ts'; + +export class ByteReader { + readonly bytes: Uint8Array; + offset = 0; + + constructor(bytes: Uint8Array) { + this.bytes = bytes; + } + + get remaining(): number { + return this.bytes.length - this.offset; + } + + u8(): number { + this.require(1); + return this.bytes[this.offset++]!; + } + + take(length: number): Uint8Array { + this.require(length); + const slice = this.bytes.subarray(this.offset, this.offset + length); + this.offset += length; + return slice; + } + + /** Unsigned LEB128: 7 bits per byte, least significant group first, high bit = more bytes follow. */ + varUint(): number { + let value = 0; + for (let shift = 0; shift < 35; shift += 7) { + const byte = this.u8(); + value += (byte & 0x7f) * 2 ** shift; + if ((byte & 0x80) === 0) return value; + } + throw new BlkFormatError(`variable-length integer at offset ${this.offset} is too long`); + } + + private require(length: number): void { + if (length > this.remaining) { + throw new BlkFormatError(`unexpected end of data: need ${length} bytes at offset ${this.offset}, have ${this.remaining}`); + } + } +} diff --git a/packages/blk/src/binary/byte-writer.ts b/packages/blk/src/binary/byte-writer.ts new file mode 100644 index 0000000..2bb6115 --- /dev/null +++ b/packages/blk/src/binary/byte-writer.ts @@ -0,0 +1,55 @@ +/** Growable little-endian byte buffer, with the format's variable-length integers. */ +export class ByteWriter { + private buffer = new Uint8Array(256); + private view = new DataView(this.buffer.buffer); + length = 0; + + u8(value: number): void { + this.reserve(1); + this.buffer[this.length++] = value; + } + + u32(value: number): void { + this.reserve(4); + this.view.setUint32(this.length, value >>> 0, true); + this.length += 4; + } + + bytes(data: Uint8Array): void { + this.reserve(data.length); + this.buffer.set(data, this.length); + this.length += data.length; + } + + /** Unsigned LEB128, see ByteReader.varUint. */ + varUint(value: number): void { + if (!Number.isInteger(value) || value < 0 || value > 0xffff_ffff) { + throw new RangeError(`cannot encode ${value} as an unsigned 32-bit integer`); + } + let rest = value; + do { + const group = rest % 0x80; + rest = Math.floor(rest / 0x80); + this.u8(rest > 0 ? group | 0x80 : group); + } while (rest > 0); + } + + /** Pad with zero bytes until the length is a multiple of `alignment`. */ + align(alignment: number): void { + while (this.length % alignment !== 0) this.u8(0); + } + + toBytes(): Uint8Array { + return this.buffer.slice(0, this.length); + } + + private reserve(extra: number): void { + if (this.length + extra <= this.buffer.length) return; + let capacity = this.buffer.length * 2; + while (capacity < this.length + extra) capacity *= 2; + const grown = new Uint8Array(capacity); + grown.set(this.buffer.subarray(0, this.length)); + this.buffer = grown; + this.view = new DataView(grown.buffer); + } +} diff --git a/packages/blk/src/binary/dump-decoder.ts b/packages/blk/src/binary/dump-decoder.ts new file mode 100644 index 0000000..8fe1e55 --- /dev/null +++ b/packages/blk/src/binary/dump-decoder.ts @@ -0,0 +1,108 @@ +/** + * Decode the body of a binary BLK (after the format label) into a block tree. + * + * Layout (DagorEngine blk_serialize.cpp, DataBlock::loadFromBinDump): + * name table this document's own names (name-table.ts) + * varUint block count + * varUint parameter count + * varUint complex-data size + * complex data strings and values too large to store inline + * parameter records 8 bytes each, every block's parameters in block order + * block records, one per block in breadth-first order (block 0 is the root): + * varUint name index + 1 0 for the root + * varUint parameter count + * varUint sub-block count + * varUint first sub-block only when the sub-block count is not 0 + * varUint first parameter only in the deduplicated variant, and only with parameters + * + * Name indices count the shared name map (if any) first, then this document's own names. + */ +import type { BlkBlock, BlkParam } from '../model.ts'; +import { BlkFormatError } from '../errors.ts'; +import type { ByteReader } from './byte-reader.ts'; +import { readNameTable } from './name-table.ts'; +import { decodeValue, type DecodeContext } from './param-values.ts'; + +const PARAM_RECORD_SIZE = 8; + +export interface DumpLayout { + /** Names from the data pack's shared name map; empty for a self-contained document. */ + readonly sharedNames: readonly string[]; + /** Block records carry an explicit first-parameter index. */ + readonly deduplicated: boolean; +} + +interface BlockRecord { + readonly nameIndex: number | null; + readonly firstParam: number; + readonly paramCount: number; + readonly firstBlock: number; + readonly blockCount: number; +} + +export function decodeDump(reader: ByteReader, layout: DumpLayout): BlkBlock { + const names = [...layout.sharedNames, ...readNameTable(reader)]; + const blockCount = reader.varUint(); + const paramCount = reader.varUint(); + const complexSize = reader.varUint(); + if (blockCount === 0) throw new BlkFormatError('a BLK document has at least the root block'); + + const complex = reader.take(complexSize); + const params = decodeParams(reader.take(paramCount * PARAM_RECORD_SIZE), { names, complex }); + const records = readBlockRecords(reader, blockCount, params.length, names.length, layout.deduplicated); + return assembleTree(records, params, names); +} + +function decodeParams(records: Uint8Array, context: DecodeContext): BlkParam[] { + const view = new DataView(records.buffer, records.byteOffset, records.byteLength); + const params: BlkParam[] = []; + for (let offset = 0; offset < records.length; offset += PARAM_RECORD_SIZE) { + const header = view.getUint32(offset, true); + const nameIndex = header & 0xff_ffff; + const name = context.names[nameIndex]; + if (name === undefined) { + throw new BlkFormatError(`parameter ${offset / PARAM_RECORD_SIZE} refers to name ${nameIndex}, table has ${context.names.length}`); + } + params.push({ name, value: decodeValue(header >>> 24, view.getUint32(offset + 4, true), context) }); + } + return params; +} + +function readBlockRecords(reader: ByteReader, blockCount: number, paramCount: number, nameCount: number, + deduplicated: boolean): BlockRecord[] { + const records: BlockRecord[] = []; + let nextFirstBlock = 1; + let nextParam = 0; + for (let index = 0; index < blockCount; index++) { + const nameIndexPlusOne = reader.varUint(); + const ownParams = reader.varUint(); + const ownBlocks = reader.varUint(); + const firstBlock = ownBlocks ? reader.varUint() : 0; + const firstParam = deduplicated ? (ownParams ? reader.varUint() : 0) : nextParam; + + if (nameIndexPlusOne > nameCount) throw new BlkFormatError(`block ${index} refers to name ${nameIndexPlusOne - 1}, table has ${nameCount}`); + if (ownBlocks && (firstBlock !== nextFirstBlock || firstBlock + ownBlocks > blockCount)) { + throw new BlkFormatError(`block ${index} has an inconsistent sub-block range`); + } + if (firstParam + ownParams > paramCount) throw new BlkFormatError(`block ${index} has an inconsistent parameter range`); + + records.push({ nameIndex: nameIndexPlusOne ? nameIndexPlusOne - 1 : null, firstParam, paramCount: ownParams, firstBlock, blockCount: ownBlocks }); + nextFirstBlock += ownBlocks; + if (!deduplicated) nextParam += ownParams; + } + if (nextFirstBlock !== blockCount) throw new BlkFormatError(`${blockCount - nextFirstBlock} block(s) are unreachable from the root`); + return records; +} + +function assembleTree(records: readonly BlockRecord[], params: readonly BlkParam[], names: readonly string[]): BlkBlock { + const blocks: BlkBlock[] = records.map((record) => ({ + name: record.nameIndex === null ? '' : names[record.nameIndex]!, + // copied so that blocks sharing a parameter run (deduplicated variant) can be edited independently + params: params.slice(record.firstParam, record.firstParam + record.paramCount).map((param) => ({ ...param })), + blocks: [], + })); + records.forEach((record, index) => { + blocks[index]!.blocks = blocks.slice(record.firstBlock, record.firstBlock + record.blockCount); + }); + return blocks[0]!; +} diff --git a/packages/blk/src/binary/dump-encoder.ts b/packages/blk/src/binary/dump-encoder.ts new file mode 100644 index 0000000..b2bad59 --- /dev/null +++ b/packages/blk/src/binary/dump-encoder.ts @@ -0,0 +1,104 @@ +/** + * Encode a block tree as the body of a self-contained binary BLK (no shared name map, + * no deduplication). The layout is the one dump-decoder.ts reads; the order of work follows + * DagorEngine's DataBlock::saveToBinStreamWithoutNames: strings go into the complex-data + * area first, then, after aligning to 4 bytes, the other values too large to store inline. + * + * Every string value is stored in the complex-data area; the format also allows pointing + * at an equal entry of the name table, but nothing requires it. + */ +import type { BlkBlock, BlkParam } from '../model.ts'; +import { BlkFormatError } from '../errors.ts'; +import { typeByName } from '../param-types.ts'; +import { ByteWriter } from './byte-writer.ts'; +import { writeNameTable } from './name-table.ts'; +import { appendComplex, appendString, encodeInline, storesInline } from './param-values.ts'; + +const MAX_NAMES = 0xff_ffff; +const MAX_CHILDREN = 0xffff; + +export function encodeDump(writer: ByteWriter, root: BlkBlock): void { + const order = breadthFirst(root); + const params = order.flatMap((block) => block.params); + const names = collectNames(order, root); + const complex = new ByteWriter(); + const values = encodeValues(params, complex); + + writeNameTable(writer, names.list); + writer.varUint(order.length); + writer.varUint(params.length); + writer.varUint(complex.length); + writer.bytes(complex.toBytes()); + params.forEach((param, index) => { + writer.u32(names.indexOf(param.name) + typeByName(param.value.type).id * 0x100_0000); + writer.u32(values[index]!); + }); + + let nextFirstBlock = 1; + for (const block of order) { + if (block.params.length > MAX_CHILDREN || block.blocks.length > MAX_CHILDREN) { + throw new BlkFormatError(`block "${block.name}" has more than ${MAX_CHILDREN} parameters or sub-blocks`); + } + writer.varUint(block === root ? 0 : names.indexOf(block.name) + 1); + writer.varUint(block.params.length); + writer.varUint(block.blocks.length); + if (block.blocks.length) { + writer.varUint(nextFirstBlock); + nextFirstBlock += block.blocks.length; + } + } +} + +function breadthFirst(root: BlkBlock): BlkBlock[] { + const order = [root]; + for (let index = 0; index < order.length; index++) order.push(...order[index]!.blocks); + return order; +} + +function encodeValues(params: readonly BlkParam[], complex: ByteWriter): number[] { + const values = new Array(params.length); + params.forEach((param, index) => { + if (param.value.type === 'string') values[index] = appendString(complex, param.value.value); + }); + let aligned = false; + params.forEach((param, index) => { + if (param.value.type === 'string') return; + if (storesInline(param.value)) { + values[index] = encodeInline(param.value) >>> 0; + return; + } + if (!aligned) { + complex.align(4); + aligned = true; + } + values[index] = appendComplex(complex, param.value); + }); + return values; +} + +class NameIndex { + readonly list: string[] = []; + private readonly indices = new Map(); + + add(name: string): void { + if (this.indices.has(name)) return; + if (this.list.length >= MAX_NAMES) throw new BlkFormatError(`more than ${MAX_NAMES} distinct names`); + this.indices.set(name, this.list.length); + this.list.push(name); + } + + indexOf(name: string): number { + const index = this.indices.get(name); + if (index === undefined) throw new BlkFormatError(`name "${name}" was not collected`); + return index; + } +} + +function collectNames(order: readonly BlkBlock[], root: BlkBlock): NameIndex { + const names = new NameIndex(); + for (const block of order) { + if (block !== root) names.add(block.name); + for (const param of block.params) names.add(param.name); + } + return names; +} diff --git a/packages/blk/src/binary/format.ts b/packages/blk/src/binary/format.ts new file mode 100644 index 0000000..be1dfd8 --- /dev/null +++ b/packages/blk/src/binary/format.ts @@ -0,0 +1,88 @@ +/** + * The one-byte format label at the start of a binary BLK, and what follows it. + * + * Source: DagorEngine prog/engine/ioSys/dataBlock/blk_shared.h (dblk::BBF_*) and + * blk_parser.cpp (DataBlock::loadFromStream). Any other first byte means a text BLK, + * which this module does not read. + */ +import { zstdDecompressSync } from 'node:zlib'; +import type { BlkBlock } from '../model.ts'; +import { BlkFormatError } from '../errors.ts'; +import { ByteReader } from './byte-reader.ts'; +import { ByteWriter } from './byte-writer.ts'; +import { decodeDump } from './dump-decoder.ts'; +import { encodeDump } from './dump-encoder.ts'; + +export const BlkLabel = { + /** Self-contained: own name table, body follows uncompressed. */ + SelfContained: 1, + /** 3-byte compressed size, then zstd of a SelfContained document (label included). */ + SelfContainedZstd: 2, + /** Names come from the data pack's shared name map; body follows uncompressed. */ + SharedNames: 3, + /** As SharedNames, body is zstd-compressed to the end of the file. */ + SharedNamesZstd: 4, + /** As SharedNamesZstd, compressed with the data pack's zstd dictionary. */ + SharedNamesZstdDictionary: 5, + /** As SelfContained, block records carry explicit parameter offsets. */ + SelfContainedDeduplicated: 6, +} as const; + +/** What a document stored with a shared name map needs from its data pack. */ +export interface SharedNameContext { + readonly names: readonly string[]; + /** The pack's zstd dictionary, needed only for SharedNamesZstdDictionary documents. */ + readonly dictionary?: Uint8Array | undefined; +} + +export function decodeBlk(bytes: Uint8Array, shared?: SharedNameContext): BlkBlock { + const reader = new ByteReader(bytes); + const label = reader.u8(); + switch (label) { + case BlkLabel.SelfContained: + return decodeDump(reader, { sharedNames: [], deduplicated: false }); + case BlkLabel.SelfContainedDeduplicated: + return decodeDump(reader, { sharedNames: [], deduplicated: true }); + case BlkLabel.SelfContainedZstd: { + const size = reader.u8() | (reader.u8() << 8) | (reader.u8() << 16); + const inner = decompress(reader.take(size)); + if (inner[0] !== BlkLabel.SelfContained) throw new BlkFormatError('compressed BLK does not contain a self-contained document'); + return decodeBlk(inner); + } + case BlkLabel.SharedNames: + return decodeDump(reader, { sharedNames: requireShared(shared).names, deduplicated: false }); + case BlkLabel.SharedNamesZstd: { + const names = requireShared(shared).names; + return decodeDump(new ByteReader(decompress(reader.take(reader.remaining))), { sharedNames: names, deduplicated: false }); + } + case BlkLabel.SharedNamesZstdDictionary: { + const context = requireShared(shared); + if (!context.dictionary) throw new BlkFormatError('this BLK needs the data pack\'s zstd dictionary'); + const body = decompress(reader.take(reader.remaining), context.dictionary); + return decodeDump(new ByteReader(body), { sharedNames: context.names, deduplicated: false }); + } + default: + throw new BlkFormatError(`format label ${label} is not a binary BLK (text BLK is not supported)`); + } +} + +/** Encode as a self-contained binary BLK, which the game accepts in every loading mode. */ +export function encodeBlk(root: BlkBlock): Uint8Array { + const writer = new ByteWriter(); + writer.u8(BlkLabel.SelfContained); + encodeDump(writer, root); + return writer.toBytes(); +} + +export function decompress(data: Uint8Array, dictionary?: Uint8Array): Uint8Array { + try { + return dictionary ? zstdDecompressSync(data, { dictionary }) : zstdDecompressSync(data); + } catch (error) { + throw new BlkFormatError(`zstd decompression failed: ${(error as Error).message}`); + } +} + +function requireShared(shared: SharedNameContext | undefined): SharedNameContext { + if (!shared) throw new BlkFormatError('this BLK uses the data pack\'s shared name map, which was not supplied'); + return shared; +} diff --git a/packages/blk/src/binary/name-table.ts b/packages/blk/src/binary/name-table.ts new file mode 100644 index 0000000..b26fdb9 --- /dev/null +++ b/packages/blk/src/binary/name-table.ts @@ -0,0 +1,44 @@ +/** + * The name table: every block and parameter name of a document, referenced by index. + * + * Layout (DagorEngine blk_serialize.cpp, dblk::write_names_base / read_names_base): + * varUint count + * varUint total byte size of the names (only when count > 0) + * names, each UTF-8 and NUL-terminated + */ +import { BlkFormatError } from '../errors.ts'; +import type { ByteReader } from './byte-reader.ts'; +import type { ByteWriter } from './byte-writer.ts'; + +const utf8Decoder = new TextDecoder('utf-8', { fatal: true }); +const utf8Encoder = new TextEncoder(); + +export function readNameTable(reader: ByteReader): string[] { + const count = reader.varUint(); + if (count === 0) return []; + const size = reader.varUint(); + if (count > size) throw new BlkFormatError(`name table claims ${count} names in ${size} bytes`); + const blob = reader.take(size); + + const names: string[] = []; + let start = 0; + while (names.length < count) { + const end = blob.indexOf(0, start); + if (end < 0) throw new BlkFormatError(`name table ends after ${names.length} of ${count} names`); + names.push(utf8Decoder.decode(blob.subarray(start, end))); + start = end + 1; + } + return names; +} + +export function writeNameTable(writer: ByteWriter, names: readonly string[]): void { + writer.varUint(names.length); + if (names.length === 0) return; + const encoded = names.map((name) => utf8Encoder.encode(name)); + writer.varUint(encoded.reduce((total, bytes) => total + bytes.length + 1, 0)); + for (const bytes of encoded) { + if (bytes.includes(0)) throw new BlkFormatError('a name cannot contain a NUL character'); + writer.bytes(bytes); + writer.u8(0); + } +} diff --git a/packages/blk/src/binary/param-values.ts b/packages/blk/src/binary/param-values.ts new file mode 100644 index 0000000..42165cb --- /dev/null +++ b/packages/blk/src/binary/param-values.ts @@ -0,0 +1,126 @@ +/** + * Turning a parameter record's 32-bit value field into a typed value, and back. + * + * A parameter record is 8 bytes: u32 (name index in the low 24 bits, type id in the high + * 8 bits) and u32 `v`. For values of at most INLINE_SIZE bytes, `v` holds the value. For a + * string, `v` is either a name-table index with the top bit set, or an offset of a + * NUL-terminated UTF-8 string in the complex-data area. For any other larger value, `v` is + * an offset in the complex-data area. + */ +import type { BlkValue } from '../model.ts'; +import { BlkFormatError } from '../errors.ts'; +import { isInline, typeById, typeByName } from '../param-types.ts'; +import type { ByteWriter } from './byte-writer.ts'; + +export const NAME_TABLE_STRING_FLAG = 0x8000_0000; + +const utf8Decoder = new TextDecoder('utf-8', { fatal: true }); +const utf8Encoder = new TextEncoder(); +const bits = new DataView(new ArrayBuffer(4)); + +export interface DecodeContext { + readonly names: readonly string[]; + readonly complex: Uint8Array; +} + +export function decodeValue(typeId: number, v: number, context: DecodeContext): BlkValue { + const info = typeById(typeId); + if (info.type === 'string') return { type: 'string', value: decodeString(v, context) }; + if (isInline(info)) return decodeInline(info.type, v); + + const { complex } = context; + if (v + info.size > complex.length) { + throw new BlkFormatError(`${info.type} value at complex offset ${v} runs past the end (${complex.length} bytes)`); + } + const view = new DataView(complex.buffer, complex.byteOffset + v, info.size); + const floats = (count: number) => Array.from({ length: count }, (_, i) => view.getFloat32(i * 4, true)); + const ints = (count: number) => Array.from({ length: count }, (_, i) => view.getInt32(i * 4, true)); + + switch (info.type) { + case 'point2': return { type: 'point2', value: floats(2) as [number, number] }; + case 'point3': return { type: 'point3', value: floats(3) as [number, number, number] }; + case 'point4': return { type: 'point4', value: floats(4) as [number, number, number, number] }; + case 'ipoint2': return { type: 'ipoint2', value: ints(2) as [number, number] }; + case 'ipoint3': return { type: 'ipoint3', value: ints(3) as [number, number, number] }; + case 'ipoint4': return { type: 'ipoint4', value: ints(4) as [number, number, number, number] }; + case 'matrix': return { type: 'matrix', value: floats(12) }; + case 'int64': return { type: 'int64', value: view.getBigInt64(0, true) }; + default: throw new BlkFormatError(`no complex-data decoding for ${info.type}`); + } +} + +/** The value field for an inline value. */ +export function encodeInline(value: BlkValue): number { + switch (value.type) { + case 'int': return value.value | 0; + case 'bool': return value.value ? 1 : 0; + case 'color': return value.value >>> 0; + case 'real': + bits.setFloat32(0, value.value, true); + return bits.getUint32(0, true); + default: throw new BlkFormatError(`${value.type} is not stored inline`); + } +} + +export function storesInline(value: BlkValue): boolean { + return isInline(typeByName(value.type)); +} + +/** Append a string to the complex-data area; returns its offset. */ +export function appendString(complex: ByteWriter, text: string): number { + const encoded = utf8Encoder.encode(text); + if (encoded.includes(0)) throw new BlkFormatError('a string value cannot contain a NUL character'); + const offset = complex.length; + complex.bytes(encoded); + complex.u8(0); + return offset; +} + +/** Append a non-string, non-inline value to the complex-data area; returns its offset. */ +export function appendComplex(complex: ByteWriter, value: BlkValue): number { + const offset = complex.length; + const size = typeByName(value.type).size; + const view = new DataView(new ArrayBuffer(size)); + switch (value.type) { + case 'point2': case 'point3': case 'point4': case 'matrix': + value.value.forEach((item, i) => view.setFloat32(i * 4, item, true)); + break; + case 'ipoint2': case 'ipoint3': case 'ipoint4': + value.value.forEach((item, i) => view.setInt32(i * 4, item, true)); + break; + case 'int64': + view.setBigInt64(0, value.value, true); + break; + default: + throw new BlkFormatError(`${value.type} is not stored in the complex-data area`); + } + if (value.type === 'matrix' && value.value.length !== 12) { + throw new BlkFormatError(`a matrix has 12 numbers, got ${value.value.length}`); + } + complex.bytes(new Uint8Array(view.buffer)); + return offset; +} + +function decodeString(v: number, { names, complex }: DecodeContext): string { + if (v & NAME_TABLE_STRING_FLAG) { + const index = v & ~NAME_TABLE_STRING_FLAG; + const name = names[index]; + if (name === undefined) throw new BlkFormatError(`string refers to name ${index}, table has ${names.length}`); + return name; + } + const end = complex.indexOf(0, v); + if (v >= complex.length || end < 0) throw new BlkFormatError(`string at complex offset ${v} is not terminated`); + return utf8Decoder.decode(complex.subarray(v, end)); +} + +function decodeInline(type: BlkValue['type'], v: number): BlkValue { + switch (type) { + case 'int': return { type: 'int', value: v | 0 }; + case 'bool': return { type: 'bool', value: (v & 0xff) !== 0 }; + case 'color': return { type: 'color', value: v >>> 0 }; + case 'real': + bits.setUint32(0, v, true); + return { type: 'real', value: bits.getFloat32(0, true) }; + default: throw new BlkFormatError(`${type} is not stored inline`); + } +} diff --git a/packages/blk/src/errors.ts b/packages/blk/src/errors.ts new file mode 100644 index 0000000..478bb9d --- /dev/null +++ b/packages/blk/src/errors.ts @@ -0,0 +1,4 @@ +/** The bytes are not a BLK document this code understands, or a document cannot be encoded. */ +export class BlkFormatError extends Error { + override name = 'BlkFormatError'; +} diff --git a/packages/blk/src/index.ts b/packages/blk/src/index.ts new file mode 100644 index 0000000..c91dae3 --- /dev/null +++ b/packages/blk/src/index.ts @@ -0,0 +1,13 @@ +/** + * BLK documents, the data format of the Dagor engine: decode the binary forms found in the + * game's data packs, keep every value's type, and encode a self-contained binary document + * the game accepts. + * + * Format source: DagorEngine prog/engine/ioSys/dataBlock/ (BSD-3). + */ +export type { BlkBlock, BlkParam, BlkValue, BlkValueType } from './model.ts'; +export { emptyBlock } from './model.ts'; +export { BlkFormatError } from './errors.ts'; +export { BlkLabel, decodeBlk, encodeBlk, type SharedNameContext } from './binary/format.ts'; +export { parseSharedNameMap, type SharedNameMap } from './shared-name-map.ts'; +export { ensureBlock, findBlock, findParam, setParam, visitParams } from './tree.ts'; diff --git a/packages/blk/src/model.ts b/packages/blk/src/model.ts new file mode 100644 index 0000000..1a86880 --- /dev/null +++ b/packages/blk/src/model.ts @@ -0,0 +1,44 @@ +/** + * In-memory form of a BLK document. + * + * Every value keeps its BLK type, so a document read from the game can be written back + * without the game reading a different type than it expects (an int stays an int even + * when its value is 5, a real stays a real even when its value is 5.0). + * + * A block keeps its parameters and its sub-blocks as two ordered lists, because that is + * what the binary format stores: the relative order of a parameter and a sub-block is not + * recorded. Names may repeat; a repeated parameter is how BLK expresses a list. + */ + +export type BlkValue = + | { readonly type: 'string'; readonly value: string } + | { readonly type: 'int'; readonly value: number } + | { readonly type: 'real'; readonly value: number } + | { readonly type: 'point2'; readonly value: readonly [number, number] } + | { readonly type: 'point3'; readonly value: readonly [number, number, number] } + | { readonly type: 'point4'; readonly value: readonly [number, number, number, number] } + | { readonly type: 'ipoint2'; readonly value: readonly [number, number] } + | { readonly type: 'ipoint3'; readonly value: readonly [number, number, number] } + | { readonly type: 'ipoint4'; readonly value: readonly [number, number, number, number] } + | { readonly type: 'bool'; readonly value: boolean } + | { readonly type: 'color'; readonly value: number } + | { readonly type: 'matrix'; readonly value: readonly number[] } + | { readonly type: 'int64'; readonly value: bigint }; + +export type BlkValueType = BlkValue['type']; + +export interface BlkParam { + name: string; + value: BlkValue; +} + +export interface BlkBlock { + /** Empty for the root block. */ + name: string; + params: BlkParam[]; + blocks: BlkBlock[]; +} + +export function emptyBlock(name = ''): BlkBlock { + return { name, params: [], blocks: [] }; +} diff --git a/packages/blk/src/param-types.ts b/packages/blk/src/param-types.ts new file mode 100644 index 0000000..d3d6fd3 --- /dev/null +++ b/packages/blk/src/param-types.ts @@ -0,0 +1,54 @@ +/** + * Parameter type ids and value sizes of the binary format. + * + * Source: DagorEngine prog/dagorInclude/ioSys/dag_dataBlock.h (DataBlock::ParamType and + * dblk::get_type_size). A value of at most INLINE_SIZE bytes is stored inside the + * parameter record itself; a larger one is stored in the complex-data area and the + * record holds its offset. Strings are always referenced, never inline. + */ +import type { BlkValueType } from './model.ts'; +import { BlkFormatError } from './errors.ts'; + +export const INLINE_SIZE = 4; + +interface TypeInfo { + readonly id: number; + readonly type: BlkValueType; + /** Bytes of the value; 0 for strings, whose length varies. */ + readonly size: number; +} + +const TYPES: readonly TypeInfo[] = [ + { id: 1, type: 'string', size: 0 }, + { id: 2, type: 'int', size: 4 }, + { id: 3, type: 'real', size: 4 }, + { id: 4, type: 'point2', size: 8 }, + { id: 5, type: 'point3', size: 12 }, + { id: 6, type: 'point4', size: 16 }, + { id: 7, type: 'ipoint2', size: 8 }, + { id: 8, type: 'ipoint3', size: 12 }, + { id: 9, type: 'bool', size: 1 }, + { id: 10, type: 'color', size: 4 }, + { id: 11, type: 'matrix', size: 48 }, + { id: 12, type: 'int64', size: 8 }, + { id: 13, type: 'ipoint4', size: 16 }, +]; + +const BY_ID = new Map(TYPES.map((info) => [info.id, info])); +const BY_TYPE = new Map(TYPES.map((info) => [info.type, info])); + +export function typeById(id: number): TypeInfo { + const info = BY_ID.get(id); + if (!info) throw new BlkFormatError(`unknown parameter type id ${id}`); + return info; +} + +export function typeByName(type: BlkValueType): TypeInfo { + const info = BY_TYPE.get(type); + if (!info) throw new BlkFormatError(`unknown parameter type ${type}`); + return info; +} + +export function isInline(info: TypeInfo): boolean { + return info.type !== 'string' && info.size <= INLINE_SIZE; +} diff --git a/packages/blk/src/shared-name-map.ts b/packages/blk/src/shared-name-map.ts new file mode 100644 index 0000000..217a787 --- /dev/null +++ b/packages/blk/src/shared-name-map.ts @@ -0,0 +1,30 @@ +/** + * The shared name map of a data pack: the file named "nm" inside a .vromfs.bin. + * + * BLK documents with format labels 3, 4 and 5 refer to these names instead of carrying + * their own (format.ts). Layout, checked against the stock 2.61.0.37 char.vromfs.bin: + * 8 bytes hash of the names + * 32 bytes identifier of the pack's zstd dictionary; all zero when the pack has none + * rest zstd frame holding a name table (binary/name-table.ts) + */ +import { BlkFormatError } from './errors.ts'; +import { ByteReader } from './binary/byte-reader.ts'; +import { decompress } from './binary/format.ts'; +import { readNameTable } from './binary/name-table.ts'; + +const HASH_SIZE = 8; +const DICTIONARY_ID_SIZE = 32; + +export interface SharedNameMap { + readonly names: readonly string[]; + /** Hex identifier of the pack's zstd dictionary, or null when the pack has none. */ + readonly dictionaryId: string | null; +} + +export function parseSharedNameMap(file: Uint8Array, dictionary?: Uint8Array): SharedNameMap { + if (file.length <= HASH_SIZE + DICTIONARY_ID_SIZE) throw new BlkFormatError('shared name map is too short'); + const idBytes = file.subarray(HASH_SIZE, HASH_SIZE + DICTIONARY_ID_SIZE); + const dictionaryId = idBytes.some((byte) => byte !== 0) ? Buffer.from(idBytes).toString('hex') : null; + const body = decompress(file.subarray(HASH_SIZE + DICTIONARY_ID_SIZE), dictionary); + return { names: readNameTable(new ByteReader(body)), dictionaryId }; +} diff --git a/packages/blk/src/tree.ts b/packages/blk/src/tree.ts new file mode 100644 index 0000000..50fe49d --- /dev/null +++ b/packages/blk/src/tree.ts @@ -0,0 +1,37 @@ +/** Small helpers for reading and editing a block tree in place. */ +import type { BlkBlock, BlkParam, BlkValue } from './model.ts'; + +export function findBlock(block: BlkBlock, name: string): BlkBlock | undefined { + return block.blocks.find((child) => child.name === name); +} + +export function findParam(block: BlkBlock, name: string): BlkParam | undefined { + return block.params.find((param) => param.name === name); +} + +/** Return the first sub-block called `name`, adding an empty one if there is none. */ +export function ensureBlock(block: BlkBlock, name: string): BlkBlock { + const existing = findBlock(block, name); + if (existing) return existing; + const created: BlkBlock = { name, params: [], blocks: [] }; + block.blocks.push(created); + return created; +} + +/** Give the first parameter called `name` this value, or append one; later duplicates are removed. */ +export function setParam(block: BlkBlock, name: string, value: BlkValue): void { + const index = block.params.findIndex((param) => param.name === name); + if (index < 0) { + block.params.push({ name, value }); + return; + } + block.params[index] = { name, value }; + block.params = block.params.filter((param, position) => position <= index || param.name !== name); +} + +/** Visit every parameter of the tree, depth first, with the path of block names leading to it. */ +export function visitParams(block: BlkBlock, visit: (param: BlkParam, path: readonly string[]) => void, + path: readonly string[] = []): void { + for (const param of block.params) visit(param, path); + for (const child of block.blocks) visitParams(child, visit, [...path, child.name]); +} diff --git a/packages/build/package.json b/packages/build/package.json new file mode 100644 index 0000000..47ad3a5 --- /dev/null +++ b/packages/build/package.json @@ -0,0 +1,9 @@ +{ + "name": "@wto/build", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts" + } +} diff --git a/packages/build/src/char-pack.ts b/packages/build/src/char-pack.ts new file mode 100644 index 0000000..e5a92ac --- /dev/null +++ b/packages/build/src/char-pack.ts @@ -0,0 +1,35 @@ +/** + * Rebuild char.vromfs.bin with config/network.blk pointed at the local service. Every other + * file of the pack is kept byte for byte. The rewritten network.blk is stored self-contained + * (it no longer depends on the pack's shared name map), which the game accepts in every + * loading mode. + */ +import { decodeBlk, encodeBlk, parseSharedNameMap } from '@wto/blk'; +import { getFile, NAME_MAP_PATH, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs'; +import type { LocalEndpoint } from './network/local-endpoint.ts'; +import { redirectNetworkConfig, type NetworkRedirectReport } from './network/redirect-network-config.ts'; + +export const NETWORK_CONFIG_PATH = 'config/network.blk'; + +export interface CharPackResult { + readonly pack: Uint8Array; + readonly network: NetworkRedirectReport; +} + +export function rebuildCharPack(stockPack: Uint8Array, endpoint: LocalEndpoint): CharPackResult { + const archive = readArchive(stockPack); + const dictionary = findDictionary(archive); + const shared = parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary); + const networkConfig = decodeBlk(getFile(archive, NETWORK_CONFIG_PATH), { names: shared.names, dictionary }); + + const network = redirectNetworkConfig(networkConfig, endpoint); + putFile(archive, NETWORK_CONFIG_PATH, encodeBlk(networkConfig)); + return { pack: writeArchive(archive), network }; +} + +/** The pack's zstd dictionary, if it has one (char.vromfs.bin in 2.61.0.37 has none). */ +function findDictionary(archive: Archive): Uint8Array | undefined { + const dictionaries = [...archive.files.keys()].filter((path) => path.endsWith('.dict')); + if (dictionaries.length > 1) throw new Error(`the data pack has several zstd dictionaries: ${dictionaries.join(', ')}`); + return dictionaries.length ? archive.files.get(dictionaries[0]!) : undefined; +} diff --git a/packages/build/src/cli.ts b/packages/build/src/cli.ts new file mode 100644 index 0000000..c9d4fb6 --- /dev/null +++ b/packages/build/src/cli.ts @@ -0,0 +1,62 @@ +/** + * Development entry point of the build: read the stock files of a game folder, write the + * files of the game copy. + * + * node packages/build/src/cli.ts --game --out --port + * [--patches exe-patches] [--verbose] + * + * Writes /char.vromfs.bin and /win64/aces.exe. The stock folder is only read. + * The launcher will run the same steps at every launch, with the port the player chose. + */ +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { parseArgs } from 'node:util'; +import { rebuildCharPack } from './char-pack.ts'; +import { patchExecutable } from './executable.ts'; +import { assertWritableCopy, GAME_FILES } from './game-copy.ts'; +import { localEndpoint } from './network/local-endpoint.ts'; + +function main(): number { + const { values } = parseArgs({ + options: { + game: { type: 'string' }, + out: { type: 'string' }, + port: { type: 'string' }, + patches: { type: 'string', default: 'exe-patches' }, + verbose: { type: 'boolean', default: false }, + }, + }); + if (!values.game || !values.out || !values.port) { + console.error('usage: cli.ts --game --out --port [--patches exe-patches] [--verbose]'); + return 2; + } + assertWritableCopy(values.game, values.out); + const endpoint = localEndpoint(Number(values.port)); + + const executable = patchExecutable(readFileSync(join(values.game, GAME_FILES.executable)), values.patches); + console.log(executable.description); + if (!executable.executable) { + console.error('some patches are unavailable; nothing was written'); + return 1; + } + + const charPack = rebuildCharPack(readFileSync(join(values.game, GAME_FILES.charPack)), endpoint); + console.log(`network.blk: ${charPack.network.addresses.length} address(es) now point to ${endpoint.host}:${endpoint.port}; ` + + `environments configured: ${charPack.network.environments.join(', ')}`); + if (values.verbose) { + for (const change of charPack.network.addresses) console.log(` ${change.path}: ${change.before} -> ${change.after}`); + } + + writeOutput(values.out, GAME_FILES.charPack, charPack.pack); + writeOutput(values.out, GAME_FILES.executable, executable.executable); + return 0; +} + +function writeOutput(folder: string, relativePath: string, content: Uint8Array): void { + const path = join(folder, relativePath); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, content); + console.log(`wrote ${path}`); +} + +process.exitCode = main(); diff --git a/packages/build/src/executable.ts b/packages/build/src/executable.ts new file mode 100644 index 0000000..01977d7 --- /dev/null +++ b/packages/build/src/executable.ts @@ -0,0 +1,19 @@ +/** + * Patch a copy of aces.exe with every definition under exe-patches/. When any patch cannot be + * applied, no executable is produced; the result lists the unavailable patches and the + * features they cover. + */ +import { applyWrites, describePlan, loadPatches, PeImage, planPatches, type PatchPlan } from '@wto/exepatch'; + +export interface ExecutableResult { + /** The patched executable, or null when some patch was unavailable. */ + readonly executable: Uint8Array | null; + readonly plan: PatchPlan; + readonly description: string; +} + +export function patchExecutable(stockExecutable: Uint8Array, patchesRoot: string): ExecutableResult { + const plan = planPatches(new PeImage(stockExecutable), loadPatches(patchesRoot)); + const executable = plan.failures.length ? null : applyWrites(stockExecutable, plan.writes); + return { executable, plan, description: describePlan(plan) }; +} diff --git a/packages/build/src/game-copy.ts b/packages/build/src/game-copy.ts new file mode 100644 index 0000000..ccfe388 --- /dev/null +++ b/packages/build/src/game-copy.ts @@ -0,0 +1,29 @@ +/** + * Files the build reads from a stock game folder and writes into the game copy, and the + * checks that keep it from writing where it must not (working-rules 9: never the Steam + * installation, never the folder it reads from). + */ +import { realpathSync } from 'node:fs'; +import { join, resolve, sep } from 'node:path'; + +export const GAME_FILES = { + charPack: 'char.vromfs.bin', + executable: join('win64', 'aces.exe'), +} as const; + +export function assertWritableCopy(stockFolder: string, copyFolder: string): void { + const stock = canonical(stockFolder); + const copy = canonical(copyFolder); + if (copy === stock) throw new Error('the output folder is the folder the stock files are read from'); + if (copy.toLowerCase().split(sep).includes('steamapps')) { + throw new Error(`refusing to write into a Steam library: ${copy}`); + } +} + +function canonical(folder: string): string { + try { + return realpathSync(folder); + } catch { + return resolve(folder); + } +} diff --git a/packages/build/src/index.ts b/packages/build/src/index.ts new file mode 100644 index 0000000..a814136 --- /dev/null +++ b/packages/build/src/index.ts @@ -0,0 +1,10 @@ +/** + * The build pipeline for the game copy: point the client at the local + * service and patch the executable. Used by the development command line (cli.ts) and, + * later, by the launcher at every launch. + */ +export { NETWORK_CONFIG_PATH, rebuildCharPack, type CharPackResult } from './char-pack.ts'; +export { patchExecutable, type ExecutableResult } from './executable.ts'; +export { assertWritableCopy, GAME_FILES } from './game-copy.ts'; +export { hostPort, localEndpoint, localUrl, type LocalEndpoint } from './network/local-endpoint.ts'; +export { redirectNetworkConfig, type AddressChange, type NetworkRedirectReport } from './network/redirect-network-config.ts'; diff --git a/packages/build/src/network/address-rewrite.ts b/packages/build/src/network/address-rewrite.ts new file mode 100644 index 0000000..f013f3a --- /dev/null +++ b/packages/build/src/network/address-rewrite.ts @@ -0,0 +1,39 @@ +/** + * Rewrite one configuration string that names a Gaijin server so that it names the local + * service instead. Only values that clearly are server addresses are touched: + * + * http(s)://host[:port]/path -> http://127.0.0.1:/host/path (host is a Gaijin domain or an external IP) + * ws(s)://host[:port]/path -> ws://127.0.0.1:/host/path + * host:port -> 127.0.0.1: (raw TCP endpoints: matching, chat) + * host -> 127.0.0.1 (bare Gaijin domain, e.g. the event log host) + * + * Everything else (file patterns, placeholders such as "https://not.used", DNS server IPs) + * is left as it is. + */ +import { hostPort, localUrl, LOOPBACK, type LocalEndpoint } from './local-endpoint.ts'; + +/** gaijin.ops is Gaijin's internal domain, used by the internal test environments. */ +const GAIJIN_DOMAINS = ['gaijin.net', 'gaijinent.com', 'warthunder.com', 'gaijin.ops']; +const URL_PATTERN = /^(https?|wss?):\/\/([^/:?#]+)(?::\d+)?([/?#].*)?$/i; +const HOST_PORT_PATTERN = /^([a-z0-9.-]+):(\d{1,5})$/i; +const IPV4_PATTERN = /^\d{1,3}(?:\.\d{1,3}){3}$/; + +export function rewriteAddress(value: string, endpoint: LocalEndpoint): string | null { + const url = URL_PATTERN.exec(value); + if (url) { + const host = url[2]!.toLowerCase(); + const scheme = url[1]!.toLowerCase().startsWith('ws') ? 'ws' : 'http'; + return isServerHost(host) ? localUrl(endpoint, host, url[3] ?? '/', scheme) : null; + } + const hostAndPort = HOST_PORT_PATTERN.exec(value); + if (hostAndPort) return isServerHost(hostAndPort[1]!.toLowerCase()) ? hostPort(endpoint) : null; + return isGaijinDomain(value.toLowerCase()) ? LOOPBACK : null; +} + +function isServerHost(host: string): boolean { + return isGaijinDomain(host) || (IPV4_PATTERN.test(host) && !host.startsWith('127.')); +} + +function isGaijinDomain(host: string): boolean { + return GAIJIN_DOMAINS.some((domain) => host === domain || host.endsWith(`.${domain}`)); +} diff --git a/packages/build/src/network/local-endpoint.ts b/packages/build/src/network/local-endpoint.ts new file mode 100644 index 0000000..4bcdaf3 --- /dev/null +++ b/packages/build/src/network/local-endpoint.ts @@ -0,0 +1,27 @@ +/** Where the local service listens. The port is chosen at every launch. */ +export interface LocalEndpoint { + readonly host: string; + readonly port: number; +} + +export const LOOPBACK = '127.0.0.1'; + +export function localEndpoint(port: number): LocalEndpoint { + if (!Number.isInteger(port) || port < 1 || port > 65535) throw new RangeError(`port must be an integer from 1 to 65535, got ${port}`); + return { host: LOOPBACK, port }; +} + +/** `host:port` of the local service. */ +export function hostPort(endpoint: LocalEndpoint): string { + return `${endpoint.host}:${endpoint.port}`; +} + +/** + * Local URL standing in for a Gaijin URL. The original host becomes the first path segment, + * so the local service can tell which Gaijin service a request was meant for even when two + * services use the same path (char and inventory both use "/char"). + */ +export function localUrl(endpoint: LocalEndpoint, originalHost: string, originalPath: string, scheme: 'http' | 'ws' = 'http'): string { + const path = originalPath.startsWith('/') ? originalPath : `/${originalPath}`; + return `${scheme}://${hostPort(endpoint)}/${originalHost}${path}`; +} diff --git a/packages/build/src/network/login-overrides.ts b/packages/build/src/network/login-overrides.ts new file mode 100644 index 0000000..f4701a8 --- /dev/null +++ b/packages/build/src/network/login-overrides.ts @@ -0,0 +1,32 @@ +/** + * Settings of an environment block's `yuplay` sub-block, which the game hands to its login + * component. + * + * The URL keys get a local URL built from the login component's default address for that + * key, so the local service sees which login request was meant. Only `loginURL`'s default is + * certain (https://auth.gaijinent.com/login.php); the others are matched by name to the + * addresses in the executable's string table. + * + * The host keys replace the host of every other login-related address, so those requests + * stay on this machine as well. + */ +import { hostPort, localUrl, LOOPBACK, type LocalEndpoint } from './local-endpoint.ts'; + +const URL_DEFAULTS: ReadonlyArray = [ + ['loginURL', 'auth.gaijinent.com', '/login.php'], + ['tagUserURL', 'auth.gaijinent.com', '/tag.php'], + ['userStokenURL', 'api.gaijinent.com', '/user_stoken.php'], + ['stokenLoginURL', 'api.gaijinent.com', '/login_stoken.php'], + ['versionURL', 'yupmaster.gaijinent.com', '/yuitem/get_version.php'], + ['yupURL', 'yupmaster.gaijinent.com', '/yuitem/get_yup.php'], +]; + +const HOST_KEYS = ['authHost', 'ssoHost', 'storeApiHost', 'authFallbackHost']; + +export function loginOverrides(endpoint: LocalEndpoint): ReadonlyArray { + return [ + ...URL_DEFAULTS.map(([key, host, path]) => [key, localUrl(endpoint, host, path)] as const), + ...HOST_KEYS.map((key) => [key, hostPort(endpoint)] as const), + ['fallbackIP', LOOPBACK], + ]; +} diff --git a/packages/build/src/network/redirect-network-config.ts b/packages/build/src/network/redirect-network-config.ts new file mode 100644 index 0000000..9e130ae --- /dev/null +++ b/packages/build/src/network/redirect-network-config.ts @@ -0,0 +1,50 @@ +/** + * Point config/network.blk at the local service. + * + * The environment names stay as they are: the stock scripts branch on the environment name + * (for example on whether it contains "production"), so renaming it would change client + * behaviour. Instead: + * - every server address in the file is rewritten to the local service (address-rewrite.ts); + * - every environment block (a block with `charServer` entries) gets certificate checking + * turned off and its login component settings pointed at the local service. + */ +import { ensureBlock, findParam, setParam, visitParams, type BlkBlock } from '@wto/blk'; +import { rewriteAddress } from './address-rewrite.ts'; +import type { LocalEndpoint } from './local-endpoint.ts'; +import { loginOverrides } from './login-overrides.ts'; + +export interface AddressChange { + readonly path: string; + readonly before: string; + readonly after: string; +} + +export interface NetworkRedirectReport { + readonly environments: readonly string[]; + readonly addresses: readonly AddressChange[]; +} + +export function redirectNetworkConfig(root: BlkBlock, endpoint: LocalEndpoint): NetworkRedirectReport { + const addresses = rewriteAllAddresses(root, endpoint); + const environments = root.blocks.filter((block) => findParam(block, 'charServer')); + for (const environment of environments) configureEnvironment(environment, endpoint); + return { environments: environments.map((block) => block.name), addresses }; +} + +function rewriteAllAddresses(root: BlkBlock, endpoint: LocalEndpoint): AddressChange[] { + const changes: AddressChange[] = []; + visitParams(root, (param, path) => { + if (param.value.type !== 'string') return; + const rewritten = rewriteAddress(param.value.value, endpoint); + if (rewritten === null || rewritten === param.value.value) return; + changes.push({ path: [...path, param.name].join('/'), before: param.value.value, after: rewritten }); + param.value = { type: 'string', value: rewritten }; + }); + return changes; +} + +function configureEnvironment(environment: BlkBlock, endpoint: LocalEndpoint): void { + setParam(environment, 'enableSslCertCheck', { type: 'bool', value: false }); + const login = ensureBlock(environment, 'yuplay'); + for (const [key, value] of loginOverrides(endpoint)) setParam(login, key, { type: 'string', value }); +} diff --git a/packages/exepatch/package.json b/packages/exepatch/package.json new file mode 100644 index 0000000..b09a37e --- /dev/null +++ b/packages/exepatch/package.json @@ -0,0 +1,9 @@ +{ + "name": "@wto/exepatch", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts" + } +} diff --git a/packages/exepatch/src/apply.ts b/packages/exepatch/src/apply.ts new file mode 100644 index 0000000..b83539d --- /dev/null +++ b/packages/exepatch/src/apply.ts @@ -0,0 +1,21 @@ +/** + * Write a verified plan into a copy of the executable's bytes. The expected original bytes + * are checked again right before each write, so a plan made against other bytes is refused + * instead of landing half applied. The input is never modified. + */ +import { VerifyError } from './errors.ts'; +import type { PlannedWrite } from './plan.ts'; + +export function applyWrites(data: Uint8Array, writes: readonly PlannedWrite[]): Uint8Array { + const patched = Uint8Array.from(data); + for (const write of [...writes].sort((left, right) => left.fileOffset - right.fileOffset)) { + const end = write.fileOffset + write.payload.length; + const actual = Buffer.from(patched.subarray(write.fileOffset, end)); + if (!actual.equals(write.expectOriginal)) { + throw new VerifyError(`${write.patchId}: bytes at file offset 0x${write.fileOffset.toString(16)} are ${actual.toString('hex')}, ` + + `expected ${Buffer.from(write.expectOriginal).toString('hex')}; nothing was written`); + } + patched.set(write.payload, write.fileOffset); + } + return patched; +} diff --git a/packages/exepatch/src/definition.ts b/packages/exepatch/src/definition.ts new file mode 100644 index 0000000..101e24d --- /dev/null +++ b/packages/exepatch/src/definition.ts @@ -0,0 +1,134 @@ +/** + * Patch definitions as stored on disk, one directory per change to the program's behaviour, + * under exe-patches///: + * + * patch.json what the program does, what it does after the patch, why the executable + * has to change, which features depend on it, and the bytes to write + * locate.json how to find the site + * + * This code reads only what applying needs; the explanatory fields are for people. + */ +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join } from 'node:path'; +import { DefinitionError } from './errors.ts'; + +const PATCH_FILE = 'patch.json'; +const LOCATE_FILE = 'locate.json'; + +export interface PatchEdit { + /** Distance from the located site to the first byte written. */ + readonly offset: number; + readonly payload: Uint8Array; + readonly expectOriginal: Uint8Array; +} + +export interface LocateSpec { + readonly method: string; + readonly [key: string]: unknown; +} + +export interface PatchDefinition { + readonly id: string; + readonly title: string; + readonly features: readonly string[]; + readonly requires: readonly string[]; + readonly edit: PatchEdit; + readonly locate: LocateSpec; + readonly directory: string; +} + +/** Every definition under `root`, sorted by id. */ +export function loadPatches(root: string): PatchDefinition[] { + const definitions = findDefinitionDirectories(root).map(readDefinition); + rejectDuplicateIds(definitions); + rejectUnknownRequirements(definitions); + return definitions.sort((left, right) => left.id.localeCompare(right.id)); +} + +function findDefinitionDirectories(root: string): string[] { + const found: string[] = []; + for (const entry of readdirSync(root, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + const directory = join(root, entry.name); + if (isFile(join(directory, PATCH_FILE))) found.push(directory); + else found.push(...findDefinitionDirectories(directory)); + } + return found; +} + +function readDefinition(directory: string): PatchDefinition { + const patch = readJson(join(directory, PATCH_FILE)); + const locate = readJson(join(directory, LOCATE_FILE)); + const where = join(directory, PATCH_FILE); + if (typeof patch.id !== 'string' || typeof patch.title !== 'string') throw new DefinitionError(`${where}: needs string "id" and "title"`); + if (typeof locate.method !== 'string') throw new DefinitionError(`${join(directory, LOCATE_FILE)}: needs a string "method"`); + return { + id: patch.id, + title: patch.title, + features: stringList(patch.features, where, 'features'), + requires: stringList(patch.requires, where, 'requires'), + edit: readEdit(patch.edit, where), + locate: locate as LocateSpec, + directory, + }; +} + +function readEdit(raw: unknown, where: string): PatchEdit { + if (!raw || typeof raw !== 'object') throw new DefinitionError(`${where}: "edit" must be an object`); + const edit = raw as Record; + const payload = hexBytes(edit.bytes, where, 'bytes'); + const expectOriginal = hexBytes(edit.expect_original, where, 'expect_original'); + if (payload.length !== expectOriginal.length) { + throw new DefinitionError(`${where}: bytes is ${payload.length} bytes but expect_original is ${expectOriginal.length}`); + } + const offset = edit.offset ?? 0; + if (typeof offset !== 'number' || !Number.isInteger(offset)) throw new DefinitionError(`${where}: edit.offset must be an integer`); + return { offset, payload, expectOriginal }; +} + +function hexBytes(value: unknown, where: string, key: string): Uint8Array { + if (typeof value !== 'string' || !/^([0-9a-fA-F]{2})*$/.test(value)) throw new DefinitionError(`${where}: edit.${key} must be a hex string`); + return Buffer.from(value, 'hex'); +} + +function stringList(value: unknown, where: string, key: string): string[] { + if (value === undefined) return []; + if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) throw new DefinitionError(`${where}: "${key}" must be a list of strings`); + return value; +} + +function readJson(path: string): Record { + let data: unknown; + try { + data = JSON.parse(readFileSync(path, 'utf-8')); + } catch (error) { + throw new DefinitionError(`${path}: ${(error as Error).message}`); + } + if (!data || typeof data !== 'object' || Array.isArray(data)) throw new DefinitionError(`${path}: expected a JSON object`); + return data as Record; +} + +function isFile(path: string): boolean { + try { + return statSync(path).isFile(); + } catch { + return false; + } +} + +function rejectDuplicateIds(definitions: readonly PatchDefinition[]): void { + const seen = new Map(); + for (const definition of definitions) { + const previous = seen.get(definition.id); + if (previous) throw new DefinitionError(`two definitions use id "${definition.id}": ${previous} and ${definition.directory}`); + seen.set(definition.id, definition.directory); + } +} + +function rejectUnknownRequirements(definitions: readonly PatchDefinition[]): void { + const known = new Set(definitions.map((definition) => definition.id)); + for (const definition of definitions) { + const unknown = definition.requires.filter((id) => !known.has(id)); + if (unknown.length) throw new DefinitionError(`${definition.id} requires unknown patch(es): ${unknown.join(', ')}`); + } +} diff --git a/packages/exepatch/src/errors.ts b/packages/exepatch/src/errors.ts new file mode 100644 index 0000000..23a906a --- /dev/null +++ b/packages/exepatch/src/errors.ts @@ -0,0 +1,28 @@ +/** A patch cannot be applied, so nothing was written. */ +export class PatchError extends Error { + override name = 'PatchError'; +} + +/** A patch definition on disk is malformed. */ +export class DefinitionError extends PatchError { + override name = 'DefinitionError'; +} + +/** + * A patch site could not be found, or was found in more than one place. The caller reports + * which patches and features are affected; it never falls back to a guessed address + *. + */ +export class LocateError extends PatchError { + override name = 'LocateError'; +} + +/** The bytes at a located site are not what the definition expects: a different game build, or already patched. */ +export class VerifyError extends PatchError { + override name = 'VerifyError'; +} + +/** The file is not a PE executable this code understands. */ +export class PeFormatError extends Error { + override name = 'PeFormatError'; +} diff --git a/packages/exepatch/src/index.ts b/packages/exepatch/src/index.ts new file mode 100644 index 0000000..1b42d96 --- /dev/null +++ b/packages/exepatch/src/index.ts @@ -0,0 +1,11 @@ +/** + * Apply the declarative patches under exe-patches/ to aces.exe: locate every site and verify + * every original byte first, then write. A site that is missing or ambiguous is reported, + * never guessed. Authoring patches (building signatures, assembling) is development-side + * work done in tools/. + */ +export { applyWrites } from './apply.ts'; +export { loadPatches, type PatchDefinition, type PatchEdit } from './definition.ts'; +export { DefinitionError, LocateError, PatchError, PeFormatError, VerifyError } from './errors.ts'; +export { PeImage, type Section } from './pe-image.ts'; +export { describePlan, planPatches, type PatchFailure, type PatchPlan, type PlannedWrite } from './plan.ts'; diff --git a/packages/exepatch/src/locate/index.ts b/packages/exepatch/src/locate/index.ts new file mode 100644 index 0000000..cc275cc --- /dev/null +++ b/packages/exepatch/src/locate/index.ts @@ -0,0 +1,17 @@ +/** + * Ways to find a patch site. Each method returns every RVA it matched; it never picks a + * winner among several matches, the caller requires exactly one. + */ +import { DefinitionError } from '../errors.ts'; +import type { PeImage } from '../pe-image.ts'; +import * as signature from './signature.ts'; + +export type Locator = (image: PeImage, spec: Readonly>) => number[]; + +const METHODS: ReadonlyMap = new Map([[signature.METHOD, signature.locateSignature]]); + +export function locatorFor(method: string): Locator { + const locator = METHODS.get(method); + if (!locator) throw new DefinitionError(`unknown locate method "${method}"; known: ${[...METHODS.keys()].join(', ')}`); + return locator; +} diff --git a/packages/exepatch/src/locate/signature.ts b/packages/exepatch/src/locate/signature.ts new file mode 100644 index 0000000..506b5f2 --- /dev/null +++ b/packages/exepatch/src/locate/signature.ts @@ -0,0 +1,69 @@ +/** + * Find a patch site by a byte pattern with wildcards, e.g. "41 57 41 56 48 81 ec ?? ?? ?? ??". + * + * Wildcards cover what legitimately differs between builds: addresses inside rip-relative + * operands and the targets of relative calls and jumps. Patterns are produced on the + * development side (tools/, which has a disassembler) and stored in the definition. + * + * The search uses the longest run of fixed bytes as an anchor, then checks the whole pattern + * at each anchor match. + */ +import { DefinitionError } from '../errors.ts'; +import type { PeImage } from '../pe-image.ts'; + +export const METHOD = 'signature'; +const WILDCARD = '??'; +const DEFAULT_LIMIT = 8; + +type Token = number | null; + +export function locateSignature(image: PeImage, spec: Readonly>): number[] { + if (typeof spec.pattern !== 'string') throw new DefinitionError('signature locate needs a string "pattern"'); + const sectionName = typeof spec.section === 'string' ? spec.section : '.text'; + const limit = typeof spec.limit === 'number' ? spec.limit : DEFAULT_LIMIT; + + const tokens = parsePattern(spec.pattern); + const anchor = longestFixedRun(tokens); + const data = image.sectionBytes(sectionName); + const base = image.section(sectionName).rva; + + const haystack = Buffer.from(data.buffer, data.byteOffset, data.byteLength); + const hits: number[] = []; + for (let from = 0; hits.length < limit;) { + const found = haystack.indexOf(anchor.bytes, from); + if (found < 0) break; + const start = found - anchor.position; + if (start >= 0 && matchesAt(data, start, tokens)) hits.push(base + start); + from = found + 1; + } + return hits; +} + +function parsePattern(pattern: string): Token[] { + const parts = pattern.split(/\s+/).filter(Boolean); + if (!parts.length) throw new DefinitionError('signature pattern is empty'); + return parts.map((part) => { + if (part === WILDCARD) return null; + if (!/^[0-9a-fA-F]{2}$/.test(part)) throw new DefinitionError(`pattern token must be a hex byte or ${WILDCARD}, got "${part}"`); + return Number.parseInt(part, 16); + }); +} + +function longestFixedRun(tokens: readonly Token[]): { position: number; bytes: Buffer } { + let best = { position: 0, length: 0 }; + let runStart = 0; + tokens.forEach((token, index) => { + if (token === null) { + runStart = index + 1; + return; + } + if (index + 1 - runStart > best.length) best = { position: runStart, length: index + 1 - runStart }; + }); + if (!best.length) throw new DefinitionError('signature pattern has no fixed bytes'); + return { position: best.position, bytes: Buffer.from(tokens.slice(best.position, best.position + best.length) as number[]) }; +} + +function matchesAt(data: Uint8Array, start: number, tokens: readonly Token[]): boolean { + if (start + tokens.length > data.length) return false; + return tokens.every((token, index) => token === null || data[start + index] === token); +} diff --git a/packages/exepatch/src/pe-image.ts b/packages/exepatch/src/pe-image.ts new file mode 100644 index 0000000..0642796 --- /dev/null +++ b/packages/exepatch/src/pe-image.ts @@ -0,0 +1,73 @@ +/** + * Read-only view of a PE executable: its sections, and the mapping between RVAs (addresses + * relative to the image base) and file offsets. Only what locating and writing patches needs. + */ +import { PeFormatError } from './errors.ts'; + +export interface Section { + readonly name: string; + readonly rva: number; + readonly virtualSize: number; + readonly rawOffset: number; + readonly rawSize: number; +} + +const SECTION_HEADER_SIZE = 40; + +export class PeImage { + readonly data: Uint8Array; + readonly sections: readonly Section[]; + + constructor(data: Uint8Array) { + this.data = data; + this.sections = readSections(data); + } + + section(name: string): Section { + const section = this.sections.find((item) => item.name === name); + if (!section) throw new PeFormatError(`no section ${name}`); + return section; + } + + /** The bytes of a section that are present in the file. */ + sectionBytes(name: string): Uint8Array { + const section = this.section(name); + return this.data.subarray(section.rawOffset, section.rawOffset + Math.min(section.virtualSize, section.rawSize)); + } + + fileOffset(rva: number): number { + const section = this.sections.find((item) => item.rva <= rva && rva < item.rva + Math.max(item.virtualSize, item.rawSize)); + if (!section) throw new PeFormatError(`RVA 0x${rva.toString(16)} is outside every section`); + if (rva - section.rva >= section.rawSize) throw new PeFormatError(`RVA 0x${rva.toString(16)} has no file bytes`); + return rva - section.rva + section.rawOffset; + } + + read(rva: number, size: number): Uint8Array { + const offset = this.fileOffset(rva); + return this.data.subarray(offset, offset + size); + } +} + +function readSections(data: Uint8Array): Section[] { + const view = new DataView(data.buffer, data.byteOffset, data.byteLength); + if (data.length < 0x40 || view.getUint16(0, true) !== 0x5a4d) throw new PeFormatError('missing MZ header'); + const peOffset = view.getUint32(0x3c, true); + if (peOffset + 24 > data.length || view.getUint32(peOffset, true) !== 0x0000_4550) throw new PeFormatError('missing PE signature'); + const sectionCount = view.getUint16(peOffset + 6, true); + const optionalHeaderSize = view.getUint16(peOffset + 20, true); + const tableOffset = peOffset + 24 + optionalHeaderSize; + if (tableOffset + sectionCount * SECTION_HEADER_SIZE > data.length) throw new PeFormatError('section table runs past the end of the file'); + + return Array.from({ length: sectionCount }, (_, index) => { + const at = tableOffset + index * SECTION_HEADER_SIZE; + const rawName = data.subarray(at, at + 8); + const nameEnd = rawName.indexOf(0); + return { + name: Buffer.from(rawName.subarray(0, nameEnd < 0 ? 8 : nameEnd)).toString('latin1'), + virtualSize: view.getUint32(at + 8, true), + rva: view.getUint32(at + 12, true), + rawSize: view.getUint32(at + 16, true), + rawOffset: view.getUint32(at + 20, true), + }; + }); +} diff --git a/packages/exepatch/src/plan.ts b/packages/exepatch/src/plan.ts new file mode 100644 index 0000000..21736b3 --- /dev/null +++ b/packages/exepatch/src/plan.ts @@ -0,0 +1,104 @@ +/** + * Work out every write first; nothing is written here. + * + * Per patch: find the site, require exactly one match, check the bytes there are the ones the + * definition expects. A patch failing any of these gets a reason instead of a write, and so + * does every patch that depends on it, so a game update yields a list of unavailable patches + * and the features they cover rather than a broken executable. + */ +import type { PatchDefinition } from './definition.ts'; +import { DefinitionError, LocateError, PatchError, VerifyError } from './errors.ts'; +import { locatorFor } from './locate/index.ts'; +import type { PeImage } from './pe-image.ts'; + +export interface PlannedWrite { + readonly patchId: string; + readonly rva: number; + readonly fileOffset: number; + readonly payload: Uint8Array; + readonly expectOriginal: Uint8Array; +} + +export interface PatchFailure { + readonly patchId: string; + readonly features: readonly string[]; + readonly reason: string; +} + +export interface PatchPlan { + readonly writes: readonly PlannedWrite[]; + readonly failures: readonly PatchFailure[]; +} + +export function planPatches(image: PeImage, definitions: readonly PatchDefinition[]): PatchPlan { + const planned = new Map(); + const failed = new Map(); + for (const definition of definitions) { + try { + planned.set(definition.id, planOne(image, definition)); + } catch (error) { + if (!(error instanceof PatchError)) throw error; + failed.set(definition.id, error.message); + } + } + propagateFailures(definitions, failed); + + const writes = definitions.filter((item) => !failed.has(item.id)).map((item) => planned.get(item.id)!); + rejectOverlaps(writes); + const failures = definitions.filter((item) => failed.has(item.id)) + .map((item) => ({ patchId: item.id, features: item.features, reason: failed.get(item.id)! })); + return { writes, failures }; +} + +export function describePlan(plan: PatchPlan): string { + const lines = [`${plan.writes.length} patch(es) ready, ${plan.failures.length} unavailable`]; + for (const write of plan.writes) lines.push(` ready ${write.patchId} at 0x${write.rva.toString(16)}`); + for (const failure of plan.failures) lines.push(` FAILED ${failure.patchId}: ${failure.reason}`); + const features = [...new Set(plan.failures.flatMap((failure) => failure.features))].sort(); + if (plan.failures.length) lines.push(` features affected: ${features.join(', ') || 'none recorded'}`); + return lines.join('\n'); +} + +function planOne(image: PeImage, definition: PatchDefinition): PlannedWrite { + const hits = locatorFor(definition.locate.method)(image, definition.locate); + if (!hits.length) throw new LocateError('site not found: this game build differs from the verified ones, or the executable is already patched'); + if (hits.length > 1) throw new LocateError(`site found in ${hits.length} places, so it is ambiguous: ${hits.map(hex).join(', ')}`); + + const rva = hits[0]! + definition.edit.offset; + const actual = image.read(rva, definition.edit.expectOriginal.length); + if (!Buffer.from(actual).equals(definition.edit.expectOriginal)) { + throw new VerifyError(`bytes at ${hex(rva)} are ${Buffer.from(actual).toString('hex')}, expected ` + + `${Buffer.from(definition.edit.expectOriginal).toString('hex')} (different game build, or already patched)`); + } + return { patchId: definition.id, rva, fileOffset: image.fileOffset(rva), payload: definition.edit.payload, expectOriginal: definition.edit.expectOriginal }; +} + +/** A patch whose prerequisite is unavailable cannot be applied either. */ +function propagateFailures(definitions: readonly PatchDefinition[], failed: Map): void { + for (let changed = true; changed;) { + changed = false; + for (const definition of definitions) { + if (failed.has(definition.id)) continue; + const blocking = definition.requires.filter((id) => failed.has(id)); + if (blocking.length) { + failed.set(definition.id, `depends on unavailable patch(es): ${blocking.join(', ')}`); + changed = true; + } + } + } +} + +function rejectOverlaps(writes: readonly PlannedWrite[]): void { + const sorted = [...writes].sort((left, right) => left.fileOffset - right.fileOffset); + for (let index = 1; index < sorted.length; index++) { + const earlier = sorted[index - 1]!; + const later = sorted[index]!; + if (later.fileOffset < earlier.fileOffset + earlier.payload.length) { + throw new DefinitionError(`${earlier.patchId} and ${later.patchId} write overlapping bytes at ${hex(earlier.rva)} and ${hex(later.rva)}`); + } + } +} + +function hex(value: number): string { + return `0x${value.toString(16)}`; +} diff --git a/packages/vromfs/package.json b/packages/vromfs/package.json new file mode 100644 index 0000000..7e67569 --- /dev/null +++ b/packages/vromfs/package.json @@ -0,0 +1,9 @@ +{ + "name": "@wto/vromfs", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts" + } +} diff --git a/packages/vromfs/src/archive.ts b/packages/vromfs/src/archive.ts new file mode 100644 index 0000000..82ce9c4 --- /dev/null +++ b/packages/vromfs/src/archive.ts @@ -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; +} + +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; +} diff --git a/packages/vromfs/src/container.ts b/packages/vromfs/src/container.ts new file mode 100644 index 0000000..caad9d8 --- /dev/null +++ b/packages/vromfs/src/container.ts @@ -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(); +} diff --git a/packages/vromfs/src/errors.ts b/packages/vromfs/src/errors.ts new file mode 100644 index 0000000..e33ee29 --- /dev/null +++ b/packages/vromfs/src/errors.ts @@ -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'; +} diff --git a/packages/vromfs/src/image.ts b/packages/vromfs/src/image.ts new file mode 100644 index 0000000..5a620e8 --- /dev/null +++ b/packages/vromfs/src/image.ts @@ -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 } { + 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(); + 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): 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[] { + 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(); +} diff --git a/packages/vromfs/src/index.ts b/packages/vromfs/src/index.ts new file mode 100644 index 0000000..c5c2cf2 --- /dev/null +++ b/packages/vromfs/src/index.ts @@ -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'; diff --git a/packages/vromfs/src/obfuscation.ts b/packages/vromfs/src/obfuscation.ts new file mode 100644 index 0000000..4a51202 --- /dev/null +++ b/packages/vromfs/src/obfuscation.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; + }); +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..c2ed551 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2023", + "module": "nodenext", + "moduleResolution": "nodenext", + "lib": ["ES2023"], + "types": ["node"], + "strict": true, + "noUncheckedIndexedAccess": true, + "noImplicitOverride": true, + "exactOptionalPropertyTypes": true, + "verbatimModuleSyntax": true, + "erasableSyntaxOnly": true, + "allowImportingTsExtensions": true, + "noEmit": true, + "skipLibCheck": true + }, + "include": ["packages/*/src/**/*.ts"] +}