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:
N0VAN0M4LY committed 2026-11-24 00:35:13 +08:00
1 parent 0117c02677
commit 5421268fbf
44 files changed
+1986 -1

No files matched your search

+35
View File
@@ -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;
}
+62
View File
@@ -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 <stock game folder> --out <game copy folder> --port <n>
* [--patches exe-patches] [--verbose]
*
* Writes <out>/char.vromfs.bin and <out>/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 <stock game folder> --out <game copy folder> --port <n> [--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();
+19
View File
@@ -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) };
}
+29
View File
@@ -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);
}
}
+10
View File
@@ -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';
@@ -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:<port>/host/path (host is a Gaijin domain or an external IP)
* ws(s)://host[:port]/path -> ws://127.0.0.1:<port>/host/path
* host:port -> 127.0.0.1:<port> (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}`));
}
@@ -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}`;
}
@@ -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<readonly [key: string, host: string, path: string]> = [
['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<readonly [key: string, value: string]> {
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],
];
}
@@ -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 });
}