feat(accounts): implement local login

Route login and character requests by their original host names on one
loopback port. Add local accounts, saves, and credential redaction.
This commit is contained in:
N0VAN0M4LY committed 2026-11-24 05:01:26 +08:00
1 parent c3914ec0d6
commit 7f482ae530
55 files changed
+1559 -58

No files matched your search

+1 -1
View File
@@ -8,6 +8,6 @@
| 目录 | 内容 |
|---|---|
| `packages/` | TypeScript(npm workspace):BLK 编解码、数据包读写、exe 补丁应用、构建流程,以后还有本地服务和启动器 |
| `packages/` | TypeScript(npm workspace):BLK 编解码、数据包读写、exe 补丁应用、构建流程、本地服务,以后还有启动器 |
| `tools/` | Python 开发端工具:数据包读写、exe 补丁引擎(特征码生成、汇编核对) |
| `exe-patches/` | exe 补丁定义 |
@@ -0,0 +1,11 @@
{
"method": "signature",
"section": ".text",
"how": [
"反作弊初始化函数里,从\"是否已经初始化\"的检查到\"Disabled from CMD\"分支结束,共 109 字节。rip 相对地址和相对跳转目标已通配(authoring.py 生成)。",
"在 2.61.0.37 原版 aces.exe 上唯一命中 0x30c7112;要改的 je 在 +0x4a(0x30c715c)。"
],
"pattern": "48 83 3d ?? ?? ?? ?? 00 74 ?? 48 8d 15 ?? ?? ?? ?? 31 db b9 03 00 00 00 45 31 c0 45 31 c9 e8 ?? ?? ?? ?? e9 ?? ?? ?? ?? 49 89 ce c7 44 24 50 01 00 00 00 48 8d 0d ?? ?? ?? ?? 48 8d 54 24 50 45 31 c0 e8 ?? ?? ?? ?? 48 85 c0 74 ?? 48 8d 15 ?? ?? ?? ?? b9 03 00 00 00 45 31 c0 45 31 c9 e8 ?? ?? ?? ?? bb 01 00 00 00 e9 ?? ?? ?? ??"
}
@@ -0,0 +1,41 @@
{
"id": "isolation/never-load-battleye",
"title": "反作弊 BattlEye 永远不加载,和带上原版启动参数 -nobeac 的效果相同",
"program_behaviour": {
"stock": "反作弊初始化时,程序先检查命令行里有没有 -nobeac。没有的话就加载 win64\\BEClient_x64.dll 并初始化,反作弊随后尝试连接 BattlEye 主服务器(端口 20010)。",
"patched": "这一处检查永远走\"命令行带了 -nobeac\"的分支:记录 \"[BEAC] Disabled from CMD\",不加载反作弊 DLL,初始化照常返回成功。"
},
"derivation": {
"requirement": "开发纪律第 18 条、功能清单 A「与正版隔离」「不连 Gaijin」。反作弊在改过的程序里运行,一旦有一次上报成功,就可能牵连玩家的机器和账号。离线版里它没有任何用处。",
"cause": "反作弊在启动时默认加载。实验副本的游戏日志:[BEAC] Loading DLL …BEClient_x64.dll / Initialized (v1.250),并反复尝试重连主服务器。",
"lighter_options_ruled_out": [
"原生自带:-nobeac 启动参数正是这个开关,启动器会带上它;但玩家绕过启动器、直接运行 exe 时就没有了。这个补丁保证任何启动方式下都不加载。",
"删除 BEClient_x64.dll:程序会走加载失败的分支,行为没有核对过;不如走原版自带的\"关闭\"分支。",
"本地服务:不适用,反作弊连接的是 BattlEye 的服务器。"
],
"conclusion": "启动参数 + 这个补丁,两层保证。",
"if_not_applied": "玩家不经启动器直接运行时,反作弊会加载,并尝试向 BattlEye 上报。"
},
"why_this_site": [
"检查本身是 call(查找命令行参数)、test rax,rax、je(没找到就去加载)。把 je 换成两个 nop,就等于\"找到了 -nobeac\",走的是原版自己的关闭分支,后续流程全部是原版代码。",
"只改 2 个字节,不新增代码。"
],
"features": ["A-与正版隔离", "A-不连 Gaijin"],
"requires": [],
"evidence": [
"2.61.0.37 原版 aces.exe:反作弊初始化函数 0x30c7100。0x30c7145 取 \"nobeac\",0x30c7154 调用命令行查找,0x30c715c 的 je 跳过 0x30c715e 的 \"[BEAC] Disabled from CMD\" 分支(该分支设返回值为 1 后退出)。",
"尚未在游戏里验证,由隔离观察确认(日志应出现 \"[BEAC] Disabled from CMD\",不出现 \"Loading DLL\")。"
],
"verified_on": [],
"edit": {
"offset": 74,
"asm": ["nop", "nop"],
"bytes": "9090",
"expect_original": "7421"
}
}
@@ -0,0 +1,11 @@
{
"method": "signature",
"section": ".text",
"how": [
"取命令行开关、查找、根据结果设置 dl、调用 crashpad 设置函数的这一段,共 45 字节。rip 相对地址和相对调用目标已通配(authoring.py 生成)。",
"在 2.61.0.37 原版 aces.exe 上唯一命中 0x40f5930;要改的 sete dl 在 +0x1a(0x40f594a)。"
],
"pattern": "48 8d 0d ?? ?? ?? ?? 48 8d 94 24 f0 00 00 00 45 31 c0 e8 ?? ?? ?? ?? 48 85 c0 0f 94 c2 48 89 d9 e8 ?? ?? ?? ?? 48 89 f9 ba 01 00 00 00"
}
@@ -0,0 +1,40 @@
{
"id": "isolation/never-upload-crash-reports",
"title": "崩溃报告永远不上传,和带上原版启动参数 -crashpad-disable-upload 的效果相同",
"program_behaviour": {
"stock": "程序启动崩溃报告组件 crashpad 时检查命令行有没有 -crashpad-disable-upload。没有就允许上传:游戏崩溃时,崩溃转储会被发往 Gaijin。",
"patched": "这一处永远按\"带了 -crashpad-disable-upload\"处理:崩溃转储只留在本机,不上传。"
},
"derivation": {
"requirement": "开发纪律第 18 条、功能清单 A「不连 Gaijin」。崩溃转储包含进程内存,来自改过的程序,不能发给 Gaijin。",
"cause": "上传默认开启(实验副本日志:crashpad enabled)。",
"lighter_options_ruled_out": [
"原生自带:-crashpad-disable-upload 启动参数正是这个开关,启动器会带上它;但玩家直接运行 exe 时就没有了。这个补丁保证任何启动方式下都不上传。",
"本地服务:上传地址不在 network.blk 里,没法统一改到本机。"
],
"conclusion": "启动参数 + 这个补丁,两层保证。",
"if_not_applied": "玩家不经启动器直接运行且游戏崩溃时,崩溃转储会上传给 Gaijin。"
},
"why_this_site": [
"检查是 call(查找命令行参数)、test rax,rax、sete dl:dl 就是\"允许上传\",作为参数传给 crashpad 的设置函数。把 sete dl 换成 xor dl,dl(再补一个 nop),参数恒为\"不允许\",等同于命令行带了这个开关。",
"只改 3 个字节,不新增代码。"
],
"features": ["A-不连 Gaijin"],
"requires": [],
"evidence": [
"2.61.0.37 原版 aces.exe:0x40f5930 取 \"crashpad-disable-upload\",0x40f5942 调用命令行查找,0x40f594a 的 sete dl 把\"没找到\"变成\"允许上传\",0x40f5950 把它传给设置函数。",
"尚未在游戏里验证,由隔离观察确认(不应出现发往崩溃上报地址的连接)。"
],
"verified_on": [],
"edit": {
"offset": 26,
"asm": ["xor dl, dl", "nop"],
"bytes": "30d290",
"expect_original": "0f94c2"
}
}
@@ -0,0 +1,11 @@
{
"method": "signature",
"section": ".rdata",
"how": [
"常量区里完整的宽字符串 L\"Software\\\\Gaijin\\\\WarThunder\",包括结尾的 0,共 54 字节。",
"在 2.61.0.37 原版 aces.exe 上唯一命中 0x7a39c4e。"
],
"pattern": "53 00 6f 00 66 00 74 00 77 00 61 00 72 00 65 00 5c 00 47 00 61 00 69 00 6a 00 69 00 6e 00 5c 00 57 00 61 00 72 00 54 00 68 00 75 00 6e 00 64 00 65 00 72 00 00 00"
}
@@ -0,0 +1,41 @@
{
"id": "isolation/registry-key",
"title": "把注册表位置从 Software\\Gaijin\\WarThunder 改成 Software\\WTOffline,不碰正版保存的登录信息",
"program_behaviour": {
"stock": "程序把\"记住的账号、密码、登录凭证\"等保存在注册表 HKEY_CURRENT_USER\\Software\\Gaijin\\WarThunder(IntAuthLogin、IntAuthPass、IntAuthShortToken、IntAuthSaveBitset)。Steam 正版用的是同一个位置。",
"patched": "改用 HKEY_CURRENT_USER\\Software\\WTOffline。离线版读不到正版保存的登录信息,登录时也不会覆盖它。"
},
"derivation": {
"requirement": "开发纪律第 18 条、功能清单 A「与正版隔离」。实测中,未打这个补丁的副本在登录时写入了这个注册表位置(最后写入时间与登录时间一致)。",
"cause": "注册表路径是程序里的常量(游戏身份表 0x7a9a7c8 的第二个字段)。",
"lighter_options_ruled_out": [
"原生自带:没有改这个路径的配置项或启动参数。",
"本地服务:不适用,这是客户端在本机读写注册表。"
],
"conclusion": "只能改 exe。改的是数据(一个字符串),不改代码。",
"if_not_applied": "离线版的登录窗口会读到正版保存的账号和凭证;在离线版登录会覆盖正版保存的登录信息。"
},
"why_this_site": [
"这个字符串只被身份表的注册表字段引用。",
"新路径比原来短,原地替换,剩余位置补 0。"
],
"features": ["A-与正版隔离"],
"requires": [],
"evidence": [
"2.61.0.37 原版 aces.exe:身份表 0x7a9a7c8 第二个字段指向 0x7a39c4e 的宽字符串 L\"Software\\\\Gaijin\\\\WarThunder\"。",
"用户机器上 HKCU\\Software\\Gaijin\\WarThunder 含 IntAuthLogin / IntAuthPass / IntAuthShortToken / IntAuthSaveBitset,最后写入时间是实验副本登录的时刻。",
"尚未在游戏里验证,由隔离观察确认。"
],
"verified_on": [],
"edit": {
"offset": 0,
"data": { "encoding": "utf-16-le", "text": "Software\\WTOffline" },
"bytes": "53006f006600740077006100720065005c00570054004f00660066006c0069006e006500000000000000000000000000000000000000",
"expect_original": "53006f006600740077006100720065005c004700610069006a0069006e005c005700610072005400680075006e006400650072000000"
}
}
@@ -0,0 +1,11 @@
{
"method": "signature",
"section": ".rdata",
"how": [
"常量区里的 \"WarThunder\" 字符串,连同前一个字节(上一个字符串的结尾 0)和后面紧跟的 \"War Thunder\",共 24 字节,用来确保命中的是身份表引用的那一处。",
"在 2.61.0.37 原版 aces.exe 上唯一命中 0x777eb96,字符串本身在 0x777eb97。"
],
"pattern": "00 57 61 72 54 68 75 6e 64 65 72 00 57 61 72 20 54 68 75 6e 64 65 72 00"
}
@@ -0,0 +1,43 @@
{
"id": "isolation/user-data-folder-name",
"title": "把游戏名从 WarThunder 改成 WTOffline,让离线版的用户数据目录和正版分开",
"program_behaviour": {
"stock": "程序的游戏身份表里,游戏名是 \"WarThunder\"。引擎的文件夹模块用它拼出用户数据目录:我的文档\\My Games\\WarThunder(设置、上次登录的账号、机器识别码),以及 AppData\\Local\\WarThunder;日志路径、内置浏览器缓存、\"同一时间只能运行一个游戏\" 的检查也用它。这些位置和 Steam 正版完全相同。",
"patched": "游戏名变成 \"WTOffline\"。上面这些位置全部变成离线版自己的:我的文档\\My Games\\WTOffline 等,正版的数据既不会被读到,也不会被改写。"
},
"derivation": {
"requirement": "开发纪律第 18 条、功能清单 A「与正版隔离」:离线版不得读写正版的任何数据。实测中,未打这个补丁的副本在退出时改写了正版账号的 global.blk、machine.blk,并把\"上次登录的账号\"改成了测试账号。",
"cause": "目录由引擎按游戏名拼出(DagorEngine prog/gameLibs/folders/platform/windows.cpp,get_gamedata_dir:我的文档 + \"My Games\" + 游戏名),游戏名是程序里的常量。",
"lighter_options_ruled_out": [
"原生自带:文件夹模块没有改默认目录的配置项(folders.cpp:load_custom_folders 只能新增具名位置,不能覆盖 gamedatadir)。",
"本地服务:不适用。这是客户端在本机读写文件,不经过网络。",
"换 Windows 用户运行:只适合开发期的观察,不能要求玩家这样做。"
],
"conclusion": "只能改 exe。改的是数据(一个字符串),不改代码。",
"if_not_applied": "离线版会读写正版的设置目录:退出时改写正版账号的设置,登录时改写\"上次登录的账号\"。"
},
"why_this_site": [
"游戏身份表(0x7a9a7c8)的游戏名字段和第三个字段都指向这同一个字符串,程序里其他地方不直接引用它。改这一个字符串,所有由游戏名派生的位置一起改变。",
"用到游戏名的 13 处都已核对:反作弊初始化、浏览器缓存路径、日志路径、单实例检查、脚本里的 app 名、语音客户端名、Steam 初始化。没有一处影响玩法;原版界面脚本不按游戏名分支。",
"新名字比原来短,原地替换即可,不需要新增数据。"
],
"features": ["A-与正版隔离"],
"requires": [],
"evidence": [
"2.61.0.37 原版 aces.exe:身份表 0x7a9a7c8 = { \"WarThunder\", L\"Software\\\\Gaijin\\\\WarThunder\", \"WarThunder\", \"wt\", …, \"production\", \"aces.vromfs.bin\" }。",
"Original client logs show that the default save directory is shared with the retail installation.",
"尚未在游戏里验证改名后的效果,由隔离观察(local development tool)确认。"
],
"verified_on": [],
"edit": {
"offset": 1,
"data": { "encoding": "ascii", "text": "WTOffline" },
"bytes": "57544f66666c696e6500",
"expect_original": "5761725468756e646572"
}
}
+8
View File
@@ -38,6 +38,10 @@
"resolved": "packages/exepatch",
"link": true
},
"node_modules/@wto/local-service": {
"resolved": "packages/local-service",
"link": true
},
"node_modules/@wto/vromfs": {
"resolved": "packages/vromfs",
"link": true
@@ -75,6 +79,10 @@
"name": "@wto/exepatch",
"version": "0.1.0"
},
"packages/local-service": {
"name": "@wto/local-service",
"version": "0.1.0"
},
"packages/vromfs": {
"name": "@wto/vromfs",
"version": "0.1.0"
+1
View File
@@ -11,3 +11,4 @@ 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';
export { formatBlkText } from './text/format-text.ts';
+74
View File
@@ -0,0 +1,74 @@
/**
* Write a BLK document in the engine's text syntax, for people to read (request logs, save
* inspection). The game reads binary BLK from us, so this module only writes text.
*
* Syntax source: DagorEngine prog/engine/ioSys/dataBlock/blk_writer.cpp (type suffixes,
* `~` escapes inside quoted strings, `yes`/`no` booleans).
*/
import type { BlkBlock, BlkValue } from '../model.ts';
const INDENT = ' ';
export function formatBlkText(root: BlkBlock): string {
const lines: string[] = [];
writeBody(root, '', lines);
return lines.join('\n') + (lines.length ? '\n' : '');
}
function writeBody(block: BlkBlock, indent: string, lines: string[]): void {
for (const param of block.params) lines.push(`${indent}${name(param.name)}:${formatValue(param.value)}`);
for (const child of block.blocks) {
lines.push(`${indent}${name(child.name)}{`);
writeBody(child, indent + INDENT, lines);
lines.push(`${indent}}`);
}
}
function formatValue(value: BlkValue): string {
switch (value.type) {
case 'string': return `t=${quote(value.value)}`;
case 'int': return `i=${value.value}`;
case 'real': return `r=${real(value.value)}`;
case 'point2': return `p2=${value.value.map(real).join(', ')}`;
case 'point3': return `p3=${value.value.map(real).join(', ')}`;
case 'point4': return `p4=${value.value.map(real).join(', ')}`;
case 'ipoint2': return `ip2=${value.value.join(', ')}`;
case 'ipoint3': return `ip3=${value.value.join(', ')}`;
case 'ipoint4': return `ip4=${value.value.join(', ')}`;
case 'bool': return `b=${value.value ? 'yes' : 'no'}`;
case 'color': return `c=${color(value.value)}`;
case 'matrix': return `m=${matrix(value.value)}`;
case 'int64': return `i64=${value.value}`;
}
}
/** E3DCOLOR is stored as 0xAARRGGBB; the text form is r, g, b, a. */
function color(packed: number): string {
const channel = (shift: number) => (packed >>> shift) & 0xff;
return [channel(16), channel(8), channel(0), channel(24)].join(', ');
}
/** A TMatrix is four rows of three reals. */
function matrix(values: readonly number[]): string {
const rows: string[] = [];
for (let row = 0; row < values.length; row += 3) rows.push(`[${values.slice(row, row + 3).map(real).join(', ')}]`);
return `[${rows.join(' ')}]`;
}
function real(value: number): string {
return Number.isInteger(value) ? value.toFixed(1) : String(value);
}
function name(text: string): string {
return /^[A-Za-z0-9_.\-]+$/.test(text) ? text : quote(text);
}
function quote(text: string): string {
const escaped = text
.replaceAll('~', '~~')
.replaceAll('"', '~"')
.replaceAll('\r', '~r')
.replaceAll('\n', '~n')
.replaceAll('\t', '~t');
return `"${escaped}"`;
}
+4 -23
View File
@@ -1,13 +1,7 @@
/**
* 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';
/** Rebuild char.vromfs.bin with config/network.blk pointed at the local service. */
import type { LocalEndpoint } from './network/local-endpoint.ts';
import { redirectNetworkConfig, type NetworkRedirectReport } from './network/redirect-network-config.ts';
import { editPackBlk } from './pack-edit.ts';
export const NETWORK_CONFIG_PATH = 'config/network.blk';
@@ -17,19 +11,6 @@ export interface CharPackResult {
}
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;
const { pack, report } = editPackBlk(stockPack, NETWORK_CONFIG_PATH, (root) => redirectNetworkConfig(root, endpoint));
return { pack, network: report };
}
+8 -1
View File
@@ -5,7 +5,8 @@
* 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.
* Writes <out>/char.vromfs.bin, <out>/aces.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';
@@ -14,6 +15,7 @@ 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 { rebuildMainPack } from './main-pack.ts';
import { localEndpoint } from './network/local-endpoint.ts';
function main(): number {
@@ -47,7 +49,12 @@ function main(): number {
for (const change of charPack.network.addresses) console.log(` ${change.path}: ${change.before} -> ${change.after}`);
}
const mainPack = rebuildMainPack(readFileSync(join(values.game, GAME_FILES.mainPack)), endpoint);
console.log(`settings.blk: ${mainPack.addresses.length} address(es) now point to ${endpoint.host}:${endpoint.port}`);
for (const change of mainPack.addresses) console.log(` ${change.path}: ${change.before} -> ${change.after}`);
writeOutput(values.out, GAME_FILES.charPack, charPack.pack);
writeOutput(values.out, GAME_FILES.mainPack, mainPack.pack);
writeOutput(values.out, GAME_FILES.executable, executable.executable);
return 0;
}
+1
View File
@@ -8,6 +8,7 @@ import { join, resolve, sep } from 'node:path';
export const GAME_FILES = {
charPack: 'char.vromfs.bin',
mainPack: 'aces.vromfs.bin',
executable: join('win64', 'aces.exe'),
} as const;
+3 -1
View File
@@ -6,5 +6,7 @@
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 { ENGINE_SETTINGS_PATH, rebuildMainPack, type MainPackResult } from './main-pack.ts';
export { redirectAddresses, type AddressChange } from './network/address-rewrite.ts';
export { hostPort, localEndpoint, localUrl, type LocalEndpoint } from './network/local-endpoint.ts';
export { redirectNetworkConfig, type AddressChange, type NetworkRedirectReport } from './network/redirect-network-config.ts';
export { redirectNetworkConfig, type NetworkRedirectReport } from './network/redirect-network-config.ts';
+35
View File
@@ -0,0 +1,35 @@
/**
* Rebuild aces.vromfs.bin with the engine settings' server addresses pointed at the local
* service.
*
* config/settings.blk, block `network`: publicConfigsUrl and publicConfigsUrls are where the
* engine's public-configs module downloads files at startup, including a signed network.blk
* that would replace the one in char.vromfs.bin (DagorEngine prog/gameLibs/publicConfigs/
* publicConfigs.cpp, init). On a machine with internet access the download would succeed and
* point the game back at Gaijin's servers. Redirected, the request reaches the local service;
* it has no such file, so the game keeps the network.blk of char.vromfs.bin.
*
* Only the `network` block is touched: the rest of settings.blk is engine configuration, not
* server addresses.
*/
import { findBlock } from '@wto/blk';
import { redirectAddresses, type AddressChange } from './network/address-rewrite.ts';
import type { LocalEndpoint } from './network/local-endpoint.ts';
import { editPackBlk } from './pack-edit.ts';
export const ENGINE_SETTINGS_PATH = 'config/settings.blk';
const NETWORK_BLOCK = 'network';
export interface MainPackResult {
readonly pack: Uint8Array;
readonly addresses: readonly AddressChange[];
}
export function rebuildMainPack(stockPack: Uint8Array, endpoint: LocalEndpoint): MainPackResult {
const { pack, report } = editPackBlk(stockPack, ENGINE_SETTINGS_PATH, (root) => {
const network = findBlock(root, NETWORK_BLOCK);
if (!network) throw new Error(`${ENGINE_SETTINGS_PATH} has no "${NETWORK_BLOCK}" block; this game build differs from the verified ones`);
return redirectAddresses(network, endpoint, [NETWORK_BLOCK]);
});
return { pack, addresses: report };
}
@@ -10,8 +10,28 @@
* Everything else (file patterns, placeholders such as "https://not.used", DNS server IPs)
* is left as it is.
*/
import { visitParams, type BlkBlock } from '@wto/blk';
import { hostPort, localUrl, LOOPBACK, type LocalEndpoint } from './local-endpoint.ts';
export interface AddressChange {
readonly path: string;
readonly before: string;
readonly after: string;
}
/** Rewrite every server address among the string parameters of `root`, in place. */
export function redirectAddresses(root: BlkBlock, endpoint: LocalEndpoint, pathPrefix: readonly string[] = []): 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: [...pathPrefix, ...path, param.name].join('/'), before: param.value.value, after: rewritten });
param.value = { type: 'string', value: rewritten };
});
return changes;
}
/** 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;
@@ -7,10 +7,12 @@
* 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.
* The host keys replace only the host name of every login-related address and keep the
* address's port (yuplay2 YuSession::updateApiHost sets the host part). They therefore get
* the bare loopback address: "127.0.0.1:<port>" would turn the local login URL into
* http://127.0.0.1:<port>:<port>/..., which the game rejects as malformed.
*/
import { hostPort, localUrl, LOOPBACK, type LocalEndpoint } from './local-endpoint.ts';
import { 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'],
@@ -26,7 +28,7 @@ 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),
...HOST_KEYS.map((key) => [key, LOOPBACK] as const),
['fallbackIP', LOOPBACK],
];
}
@@ -8,41 +8,23 @@
* - 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 { ensureBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
import { redirectAddresses, type AddressChange } 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 addresses = redirectAddresses(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');
+30
View File
@@ -0,0 +1,30 @@
/**
* Rebuild a data pack with one of its BLK documents edited. Every other file of the pack is
* kept byte for byte. The edited document 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, type BlkBlock } from '@wto/blk';
import { getFile, NAME_MAP_PATH, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs';
export interface PackEditResult<T> {
readonly pack: Uint8Array;
readonly report: T;
}
export function editPackBlk<T>(stockPack: Uint8Array, blkPath: string, edit: (root: BlkBlock) => T): PackEditResult<T> {
const archive = readArchive(stockPack);
const dictionary = findDictionary(archive);
const names = archive.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names : [];
const root = decodeBlk(getFile(archive, blkPath), { names, dictionary });
const report = edit(root);
putFile(archive, blkPath, encodeBlk(root));
return { pack: writeArchive(archive), report };
}
/** The pack's zstd dictionary, if it has one. */
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;
}
+9
View File
@@ -0,0 +1,9 @@
{
"name": "@wto/local-service",
"version": "0.1.0",
"private": true,
"type": "module",
"exports": {
".": "./src/index.ts"
}
}
@@ -0,0 +1,76 @@
/**
* Local accounts behind the login service (implementation notes, "本地账号").
*
* Signing in with a login name that does not exist yet registers it with the password given;
* later sign-ins must use the same password. Accounts are kept in <data>/accounts.json.
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { writeFileAtomic } from '../storage/atomic-file.ts';
import { hashPassword, verifyPassword } from './password.ts';
export interface Account {
/** What the player types into the login window; matched without regard to case. */
readonly login: string;
/** Decimal user id, as the login service and the char service exchange it. */
readonly userId: string;
readonly nick: string;
readonly passwordHash: string;
readonly created: string;
}
export type SignInResult =
| { readonly kind: 'signed-in'; readonly account: Account; readonly registered: boolean }
| { readonly kind: 'wrong-password' };
interface AccountFile {
formatVersion: 1;
nextUserId: number;
accounts: Account[];
}
const FIRST_USER_ID = 100000001;
const NICK_MAX_LENGTH = 16;
export class AccountStore {
readonly #path: string;
#file: AccountFile;
constructor(dataFolder: string) {
this.#path = join(dataFolder, 'accounts.json');
this.#file = existsSync(this.#path) ? readAccountFile(this.#path) : { formatVersion: 1, nextUserId: FIRST_USER_ID, accounts: [] };
}
signIn(login: string, password: string): SignInResult {
const existing = this.#find(login);
if (existing) return verifyPassword(password, existing.passwordHash) ? { kind: 'signed-in', account: existing, registered: false } : { kind: 'wrong-password' };
const userId = String(this.#file.nextUserId);
const account: Account = { login, userId, nick: nickFromLogin(login, userId), passwordHash: hashPassword(password), created: new Date().toISOString() };
this.#file = { ...this.#file, nextUserId: this.#file.nextUserId + 1, accounts: [...this.#file.accounts, account] };
writeFileAtomic(this.#path, JSON.stringify(this.#file, null, 2));
return { kind: 'signed-in', account, registered: true };
}
byUserId(userId: string): Account | undefined {
return this.#file.accounts.find((account) => account.userId === userId);
}
#find(login: string): Account | undefined {
const key = login.toLowerCase();
return this.#file.accounts.find((account) => account.login.toLowerCase() === key);
}
}
function readAccountFile(path: string): AccountFile {
const file = JSON.parse(readFileSync(path, 'utf8')) as AccountFile;
if (file.formatVersion !== 1) throw new Error(`${path}: unsupported account file version ${String(file.formatVersion)}`);
return file;
}
/** A login is often an e-mail address; the nick is its readable part. */
function nickFromLogin(login: string, userId: string): string {
const local = login.split('@')[0] ?? '';
const cleaned = local.replace(/[^A-Za-z0-9_\-]/g, '').slice(0, NICK_MAX_LENGTH);
return cleaned || `Player${userId}`;
}
@@ -0,0 +1,17 @@
/** Password hashes for local accounts (scrypt, per-account random salt). */
import { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
const KEY_LENGTH = 32;
export function hashPassword(password: string): string {
const salt = randomBytes(16);
return `scrypt$${salt.toString('hex')}$${scryptSync(password, salt, KEY_LENGTH).toString('hex')}`;
}
export function verifyPassword(password: string, stored: string): boolean {
const [scheme, saltHex, hashHex] = stored.split('$');
if (scheme !== 'scrypt' || !saltHex || !hashHex) return false;
const expected = Buffer.from(hashHex, 'hex');
const actual = scryptSync(password, Buffer.from(saltHex, 'hex'), expected.length);
return timingSafeEqual(actual, expected);
}
@@ -0,0 +1,15 @@
/** Char action names mapped to their handlers (full list of names: research-data/char_actions_37.json). */
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharActionHandler } from '../char-action.ts';
import { initialMeta, legacyUserData } from './online-init-actions.ts';
export interface ActionDependencies {
readonly profiles: PlayerProfiles;
}
export function actionTable(deps: ActionDependencies): ReadonlyMap<string, CharActionHandler> {
return new Map<string, CharActionHandler>([
['cln_get_initial_meta', initialMeta()],
['cln_legacy_get_userdata', legacyUserData(deps.profiles)],
]);
}
@@ -0,0 +1,31 @@
/**
* Char actions of the online initialisation after sign-in, up to the profile
*.
*/
import { emptyBlock } from '@wto/blk';
import type { PlayerProfiles } from '../../profile/player-profiles.ts';
import type { CharAnswer } from '../char-answers.ts';
import type { CharActionContext, CharActionHandler } from '../char-action.ts';
/**
* cln_get_initial_meta: server-side metadata the client reads in GameSaveData's initial-meta
* handling (aces.exe 0xeb5f60). binaryDataMetainfo lists server-side binary files the client
* must fetch and compare by hash; the local service has none, so the list is empty and no
* downloads follow.
*/
export function initialMeta(): CharActionHandler {
return () => {
const meta = emptyBlock();
meta.blocks.push(emptyBlock('binaryDataMetainfo'), emptyBlock('generalBlkMeta'));
return { kind: 'data', blk: meta };
};
}
/** cln_legacy_get_userdata: the whole profile (ClientEconomicState::loadOnline, aces.exe 0x2a23b0). */
export function legacyUserData(profiles: PlayerProfiles): CharActionHandler {
return (context) => withUser(context, (userId) => ({ kind: 'data', blk: profiles.profileOf(userId) }));
}
function withUser(context: CharActionContext, run: (userId: string) => CharAnswer): CharAnswer {
return context.userId ? run(context.userId) : { kind: 'error', code: 'AUTH_REQ_ERROR' };
}
@@ -0,0 +1,12 @@
/** What a char action handler gets and returns. Handlers belong to the rules layer's domains. */
import type { BlkBlock } from '@wto/blk';
import type { CharAnswer } from './char-answers.ts';
export interface CharActionContext {
/** From the request's userid header; undefined when the client sent none. */
readonly userId: string | undefined;
/** The request's BLK parameters, when the body carried a BLK. */
readonly payload: BlkBlock | undefined;
}
export type CharActionHandler = (context: CharActionContext) => CharAnswer;
@@ -0,0 +1,29 @@
/**
* The char service's three kinds of answer (implementation notes; aces.exe 2.61.0.37,
* CharServerClient::handleReqResult at 0x336d590):
* - data: HTTP 200, a compression marker and a BLK;
* - done: HTTP 200 with a body starting "!OK", for requests that expect no data;
* - error: a body starting "!ERROR:" followed by an error code.
*/
import { formatBlkText, type BlkBlock } from '@wto/blk';
import type { ServiceResponse } from '../server/exchange.ts';
import { encodeDataAnswer } from './char-payload.ts';
export type CharAnswer =
| { readonly kind: 'data'; readonly blk: BlkBlock }
| { readonly kind: 'done' }
| { readonly kind: 'error'; readonly code: string };
export function toResponse(answer: CharAnswer): ServiceResponse {
switch (answer.kind) {
case 'data':
return { status: 200, headers: BINARY, body: encodeDataAnswer(answer.blk), logNotes: { responseText: formatBlkText(answer.blk) } };
case 'done':
return { status: 200, headers: TEXT, body: '!OK' };
case 'error':
return { status: 200, headers: TEXT, body: `!ERROR:${answer.code}` };
}
}
const BINARY = { 'content-type': 'application/octet-stream' };
const TEXT = { 'content-type': 'text/plain' };
@@ -0,0 +1,46 @@
/**
* Bodies exchanged with the char service.
*
* Answers carrying data are a compression marker followed by a binary BLK; the client loads
* them with loadBlkFromAnswer (aces.exe 0x336fd60). We always send them uncompressed.
*
* What the client sends in request bodies is not established yet, so
* decoding is attempted in the forms that are plausible (marked or bare binary BLK, form
* text) and the traffic log records which form it was.
*/
import { decodeBlk, encodeBlk, formatBlkText, type BlkBlock } from '@wto/blk';
import { markUncompressed, unpackMarked } from './compression-marker.ts';
export function encodeDataAnswer(blk: BlkBlock): Uint8Array {
return markUncompressed(encodeBlk(blk));
}
export interface DecodedPayload {
/** How the body was laid out, for the traffic log. */
readonly form: string;
readonly blk?: BlkBlock;
/** Readable rendering for the traffic log. */
readonly text: string;
}
const BINARY_BLK_LABELS = new Set([1, 2, 3, 6]);
export function decodeRequestPayload(body: Uint8Array): DecodedPayload {
if (body.length === 0) return { form: 'empty', text: '' };
try {
const marked = unpackMarked(body);
if (marked) {
if (!marked.data) return { form: `marked ${marked.method}, not unpacked`, text: '' };
return describeBlk(`marked ${marked.method}`, marked.data);
}
if (BINARY_BLK_LABELS.has(body[0]!)) return describeBlk('bare binary BLK', body);
} catch (error) {
return { form: `undecodable (${(error as Error).message})`, text: '' };
}
return { form: 'text', text: Buffer.from(body).toString('utf8') };
}
function describeBlk(form: string, bytes: Uint8Array): DecodedPayload {
const blk = decodeBlk(bytes);
return { form, blk, text: formatBlkText(blk) };
}
@@ -0,0 +1,57 @@
/**
* char service: profiles and player actions.
*
* The client names the action in the request header "action" and identifies the player in
* "userid" (request headers assembled at aces.exe 0x336c590). The local service trusts
* userid as it is: there is nothing to protect on a single-player machine.
*
* An action with no handler yet gets a data answer holding an empty BLK and is marked
* unhandled in the traffic log. handleReqResult treats any 200 answer that is not "!ERROR:"
* or "!RETRY" as success for both data requests and requests that expect "!OK", so this
* default lets the client continue and reveal what it asks for next.
*/
import { emptyBlock } from '@wto/blk';
import type { Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts';
import type { CharActionHandler } from './char-action.ts';
import { toResponse, type CharAnswer } from './char-answers.ts';
import { decodeRequestPayload } from './char-payload.ts';
const CHAR_HOST = /^char-[a-z0-9-]+\.warthunder\.com$/;
export class CharService implements Service {
readonly name = 'char';
readonly #actions: ReadonlyMap<string, CharActionHandler>;
constructor(actions: ReadonlyMap<string, CharActionHandler>) {
this.#actions = actions;
}
accepts(request: ServiceRequest): boolean {
return request.originalHost !== undefined && CHAR_HOST.test(request.originalHost);
}
handle(request: ServiceRequest): ServiceResponse {
const action = header(request, 'action') ?? '(no action header)';
const payload = decodeRequestPayload(request.body);
const handler = this.#actions.get(action);
const answer: CharAnswer = handler
? handler({ userId: header(request, 'userid'), payload: payload.blk })
: { kind: 'data', blk: emptyBlock() };
const response = toResponse(answer);
return {
...response,
logNotes: {
...response.logNotes,
summary: `${action} [request body: ${payload.form}] -> ${answer.kind}${answer.kind === 'error' ? ` ${answer.code}` : ''}`,
unhandled: !handler,
requestText: payload.text,
},
};
}
}
function header(request: ServiceRequest, name: string): string | undefined {
const value = request.headers[name];
const text = Array.isArray(value) ? value[0] : value;
return text ? text : undefined;
}
@@ -0,0 +1,45 @@
/**
* Data answers of the char service start with one byte naming how the rest is compressed.
*
* Source: aces.exe 2.61.0.37. The client's table of compression methods is filled at
* 0x3373cd0 (name, implementation, marker byte); the answer is unpacked by
* processPotentiallyCompressedAnswer (0x3372190), which takes the bytes after an 'i' marker
* as they are. Only the methods Node can unpack are decoded here.
*/
import { gunzipSync, inflateSync, zstdDecompressSync } from 'node:zlib';
export const MARKER_NONE = 0x69; // 'i'
const DECODERS: ReadonlyMap<number, { readonly name: string; readonly unpack?: (data: Uint8Array) => Uint8Array }> = new Map([
[MARKER_NONE, { name: 'none', unpack: (data: Uint8Array) => data }],
[0x5a, { name: 'zstd', unpack: (data: Uint8Array) => zstdDecompressSync(data) }], // 'Z'
[0x7a, { name: 'zlib', unpack: (data: Uint8Array) => inflateSync(data) }], // 'z'
[0x1f, { name: 'gzip', unpack: (data: Uint8Array) => gunzipSync(data) }],
[0x4c, { name: 'lz4hc' }], // 'L'
[0x6c, { name: 'lz4' }], // 'l'
[0x73, { name: 'snappy' }], // 's'
[0x62, { name: 'bzip2' }], // 'b'
[0x56, { name: 'vromfs' }], // 'V'
]);
export interface UnpackResult {
readonly method: string;
/** Undefined when the method is known but cannot be unpacked here. */
readonly data: Uint8Array | undefined;
}
/** Undefined when the first byte is not a compression marker. */
export function unpackMarked(bytes: Uint8Array): UnpackResult | undefined {
const decoder = DECODERS.get(bytes[0] ?? -1);
if (!decoder) return undefined;
// gzip's marker is the first byte of the gzip stream itself.
const rest = decoder.name === 'gzip' ? bytes : bytes.subarray(1);
return { method: decoder.name, data: decoder.unpack ? decoder.unpack(rest) : undefined };
}
export function markUncompressed(data: Uint8Array): Uint8Array {
const marked = new Uint8Array(data.length + 1);
marked[0] = MARKER_NONE;
marked.set(data, 1);
return marked;
}
+41
View File
@@ -0,0 +1,41 @@
/**
* Development entry point of the local service.
*
* node packages/local-service/src/cli.ts --game <game folder> --data <data folder> --port <n>
*
* The port must match the one the game copy was built with (packages/build). The launcher
* will start the service the same way. Stops on Ctrl+C.
*/
import { parseArgs } from 'node:util';
import { LOOPBACK, startLocalService } from './local-service.ts';
async function main(): Promise<number> {
const { values } = parseArgs({
options: {
game: { type: 'string' },
data: { type: 'string' },
port: { type: 'string' },
},
});
const port = Number(values.port);
if (!values.game || !values.data || !Number.isInteger(port) || port < 1 || port > 65535) {
console.error('usage: cli.ts --game <game folder> --data <data folder> --port <n>');
return 2;
}
let service;
try {
service = await startLocalService({ gameFolder: values.game, dataFolder: values.data, port });
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
console.error(code === 'EADDRINUSE' ? `port ${port} is already in use; choose another port` : String(error));
return 1;
}
console.log(`local service listening on ${LOOPBACK}:${port}`);
console.log(`traffic log: ${service.logFolder}`);
const running = service;
await new Promise<void>((resolve) => process.once('SIGINT', resolve));
await running.close();
return 0;
}
process.exitCode = await main();
@@ -0,0 +1,27 @@
/**
* The game files the local service reads, opened lazily from the player's game folder.
*/
import { join } from 'node:path';
import type { BlkBlock } from '@wto/blk';
import { GamePack } from './game-pack.ts';
/** Gaijin's template for a new account's profile. */
const NEW_ACCOUNT_TEMPLATE = 'config/default_user.blk';
export class GameFiles {
readonly #gameFolder: string;
#charPack: GamePack | undefined;
constructor(gameFolder: string) {
this.#gameFolder = gameFolder;
}
newAccountTemplate(): BlkBlock {
return this.#char().readBlk(NEW_ACCOUNT_TEMPLATE);
}
#char(): GamePack {
this.#charPack ??= GamePack.open(join(this.#gameFolder, 'char.vromfs.bin'));
return this.#charPack;
}
}
@@ -0,0 +1,33 @@
/**
* Read BLK documents out of one of the player's game data packs (implementation notes: the
* game's own files are the source of every static fact; nothing is shipped with us).
*/
import { readFileSync } from 'node:fs';
import { decodeBlk, parseSharedNameMap, type BlkBlock, type SharedNameContext } from '@wto/blk';
import { getFile, NAME_MAP_PATH, readArchive, type Archive } from '@wto/vromfs';
export class GamePack {
readonly #archive: Archive;
readonly #shared: SharedNameContext;
private constructor(archive: Archive) {
this.#archive = archive;
const dictionary = findDictionary(archive);
const names = archive.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names : [];
this.#shared = { names, dictionary };
}
static open(packPath: string): GamePack {
return new GamePack(readArchive(readFileSync(packPath)));
}
readBlk(pathInPack: string): BlkBlock {
return decodeBlk(getFile(this.#archive, pathInPack), this.#shared);
}
}
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;
}
+6
View File
@@ -0,0 +1,6 @@
/**
* The local service: emulates Gaijin's servers on this machine so the unmodified game logic
* signs in, loads the profile and sends player actions as it would online.
*/
export { LOOPBACK, startLocalService, type LocalServiceOptions, type RunningLocalService } from './local-service.ts';
export { HEALTH_PATH } from './server/http-listener.ts';
@@ -0,0 +1,59 @@
/**
* Assemble the local service: data layer, save layer, rules, the
* protocol-layer services, and the listening port.
*/
import type { Server } from 'node:http';
import { AccountStore } from './accounts/account-store.ts';
import { actionTable } from './char/actions/action-table.ts';
import { CharService } from './char/char-service.ts';
import { GameFiles } from './game-data/game-files.ts';
import { LoginService } from './login/login-service.ts';
import { PlayerProfiles } from './profile/player-profiles.ts';
import { SaveStore } from './saves/save-store.ts';
import { createListener } from './server/http-listener.ts';
import { Router } from './server/router.ts';
import { TrafficLog } from './traffic-log/traffic-log.ts';
export interface LocalServiceOptions {
/** The player's game folder; its data packs are read, never written. */
readonly gameFolder: string;
/** Accounts, saves and logs. */
readonly dataFolder: string;
readonly port: number;
}
export const LOOPBACK = '127.0.0.1';
export interface RunningLocalService {
readonly logFolder: string;
close(): Promise<void>;
}
export async function startLocalService(options: LocalServiceOptions): Promise<RunningLocalService> {
const gameFiles = new GameFiles(options.gameFolder);
const profiles = new PlayerProfiles(new SaveStore(options.dataFolder), gameFiles);
const router = new Router([
new LoginService(new AccountStore(options.dataFolder)),
new CharService(actionTable({ profiles })),
]);
const log = new TrafficLog(options.dataFolder);
const server = createListener(router, log);
await listen(server, options.port);
return {
logFolder: log.folder,
close: () => new Promise((resolve) => {
server.close(() => resolve());
server.closeAllConnections();
}),
};
}
function listen(server: Server, port: number): Promise<void> {
return new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(port, LOOPBACK, () => {
server.off('error', reject);
resolve();
});
});
}
@@ -0,0 +1,15 @@
/**
* Mask secrets in a login-component form before it is written to the traffic log. A player
* may type a real Gaijin password into the login window; it must never reach the disk.
*/
/** Form fields of the login component's requests that carry secrets (yuplay2auth session/yu_sessionLogin.cpp). */
const SECRET_FIELD = /pass|token|code|secret|sign|jwt|ticket/i;
export function redactLoginForm(body: Buffer): string {
const form = new URLSearchParams(body.toString('utf8'));
for (const name of [...form.keys()]) {
if (SECRET_FIELD.test(name)) form.set(name, '***');
}
return form.toString();
}
@@ -0,0 +1,76 @@
/**
* Login service: the yuplay2 login component's protocol.
*
* Sign-in with login and password (loginURL, an HTML form POST with login, password, v=2):
* the answer fields are the ones the component reads on success
* (DagorEngine prog/1stPartyLibs/yuplay2auth/session/yu_sessionLoginBase.cpp,
* CommonLoginAction::parseServerAnswer). Fields read as strings are sent as strings, the
* expiry is sent as an integer.
*
* The component's other requests (token sign-in, version checks and so on) are answered with
* status ERROR and marked unhandled in the traffic log until they are implemented.
*/
import type { AccountStore } from '../accounts/account-store.ts';
import type { LogNotes, Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts';
import { redactLoginForm } from './form-redaction.ts';
import { issueCredentials } from './session-credentials.ts';
import { yuplayAnswer } from './yuplay-answer.ts';
/** Hosts of the login component's default addresses. */
const LOGIN_HOSTS = new Set(['auth.gaijinent.com', 'auth-fallback.gaijinent.com', 'login.gaijin.net', 'api.gaijinent.com', 'yupmaster.gaijinent.com']);
const SIGN_IN_PATH = '/login.php';
/** Paths of login-component requests that can arrive without the host segment (see exchange.ts). */
const HOSTLESS_PATH = /\.php$/;
export class LoginService implements Service {
readonly name = 'login';
readonly #accounts: AccountStore;
constructor(accounts: AccountStore) {
this.#accounts = accounts;
}
accepts(request: ServiceRequest): boolean {
if (request.originalHost !== undefined) return LOGIN_HOSTS.has(request.originalHost);
return HOSTLESS_PATH.test(request.path);
}
handle(request: ServiceRequest): ServiceResponse {
const redactedRequestBody = redactLoginForm(request.body);
const response = request.method === 'POST' && request.path === SIGN_IN_PATH
? this.#signIn(request)
: withNotes(yuplayAnswer('ERROR', {}, `${request.path} not implemented`), { unhandled: true });
return withNotes(response, { redactedRequestBody, requestText: redactedRequestBody });
}
#signIn(request: ServiceRequest): ServiceResponse {
const form = new URLSearchParams(request.body.toString('utf8'));
const login = form.get('login')?.trim() ?? '';
const password = form.get('password') ?? '';
if (!login) return yuplayAnswer('LOGINERROR', {}, 'sign-in: empty login');
const result = this.#accounts.signIn(login, password);
if (result.kind === 'wrong-password') return yuplayAnswer('LOGINERROR', {}, `sign-in ${login}: wrong password`);
const { account } = result;
const credentials = issueCredentials(account);
return yuplayAnswer('OK', {
login: account.login,
nick: account.nick,
user_id: account.userId,
token: credentials.token,
jwt: credentials.jwt,
tags: '',
lang: 'en',
country: '',
token_exp: credentials.expires,
nickorig: account.nick,
nicksfx: '',
meta: {},
}, `sign-in ${login} -> user ${account.userId}${result.registered ? ' (new account)' : ''}`);
}
}
function withNotes(response: ServiceResponse, notes: LogNotes): ServiceResponse {
return { ...response, logNotes: { ...response.logNotes, ...notes } };
}
@@ -0,0 +1,35 @@
/**
* The session credentials a successful sign-in hands to the game: a session token and a JWT.
* Nothing local checks them (the char service identifies the player by the userid header);
* they only have to be well-formed for the game's own use.
*/
import { createHmac, randomBytes } from 'node:crypto';
import type { Account } from '../accounts/account-store.ts';
/** Seconds a session stays valid; long enough that the game never has to renew it. */
const SESSION_LIFETIME_SECONDS = 365 * 24 * 60 * 60;
const signingKey = randomBytes(32);
export interface SessionCredentials {
readonly token: string;
readonly jwt: string;
/** Unix time in seconds. */
readonly expires: number;
}
export function issueCredentials(account: Account): SessionCredentials {
const issued = Math.floor(Date.now() / 1000);
const expires = issued + SESSION_LIFETIME_SECONDS;
return { token: randomBytes(16).toString('hex'), jwt: jwt({ uid: account.userId, nick: account.nick, iat: issued, exp: expires }), expires };
}
function jwt(claims: object): string {
const header = base64Url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
const payload = base64Url(JSON.stringify(claims));
const signature = createHmac('sha256', signingKey).update(`${header}.${payload}`).digest('base64url');
return `${header}.${payload}.${signature}`;
}
function base64Url(text: string): string {
return Buffer.from(text, 'utf8').toString('base64url');
}
@@ -0,0 +1,18 @@
/**
* Answers in the login component's format: a JSON object whose "status" string decides the
* result. Status names are the ones the component maps to its YU2_* codes (DagorEngine
* prog/1stPartyLibs/yuplay2auth/session/yu_sessionHttp.cpp, checkJsonAnswer).
*/
import type { ServiceResponse } from '../server/exchange.ts';
export type YuplayStatus = 'OK' | 'ERROR' | 'LOGINERROR';
export function yuplayAnswer(status: YuplayStatus, fields: Readonly<Record<string, unknown>> = {}, summary?: string): ServiceResponse {
const body = JSON.stringify({ status, ...fields });
return {
status: 200,
headers: { 'content-type': 'application/json' },
body,
logNotes: { summary: summary ?? status, responseText: body },
};
}
@@ -0,0 +1,9 @@
/**
* A new account's profile. The starting content is Gaijin's own new-account template from
* the player's game files (config/default_user.blk), copied as it is.
*/
import type { BlkBlock } from '@wto/blk';
export function newProfile(template: BlkBlock): BlkBlock {
return structuredClone(template);
}
@@ -0,0 +1,26 @@
/**
* The one way services get a player's profile: the saved one, or a new one that is written
* to the save before it is handed out.
*/
import type { BlkBlock } from '@wto/blk';
import type { GameFiles } from '../game-data/game-files.ts';
import type { SaveStore } from '../saves/save-store.ts';
import { newProfile } from './new-profile.ts';
export class PlayerProfiles {
readonly #saves: SaveStore;
readonly #gameFiles: GameFiles;
constructor(saves: SaveStore, gameFiles: GameFiles) {
this.#saves = saves;
this.#gameFiles = gameFiles;
}
profileOf(userId: string): BlkBlock {
const saved = this.#saves.loadProfile(userId);
if (saved) return saved;
const created = newProfile(this.#gameFiles.newAccountTemplate());
this.#saves.saveProfile(userId, created);
return created;
}
}
@@ -0,0 +1,62 @@
/**
* Save layer: one save per account, holding the profile in Gaijin's
* profile structure.
*
* <data>/saves/<userId>/save.json format version and bookkeeping
* <data>/saves/<userId>/profile.blk the profile, binary BLK with every value's type kept
*
* Every write reaches the disk before the caller replies to the game. A save written by an
* older format version is upgraded step by step when it is opened (save-upgrades.ts).
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { decodeBlk, encodeBlk, type BlkBlock } from '@wto/blk';
import { writeFileAtomic } from '../storage/atomic-file.ts';
import { CURRENT_SAVE_FORMAT, upgradeSave } from './save-upgrades.ts';
interface SaveInfo {
formatVersion: number;
created: string;
updated: string;
}
export class SaveStore {
readonly #folder: string;
constructor(dataFolder: string) {
this.#folder = join(dataFolder, 'saves');
}
/** The account's profile, or undefined when the account has no save yet. */
loadProfile(userId: string): BlkBlock | undefined {
const infoPath = this.#infoPath(userId);
if (!existsSync(infoPath)) return undefined;
const info = JSON.parse(readFileSync(infoPath, 'utf8')) as SaveInfo;
const profile = decodeBlk(readFileSync(this.#profilePath(userId)));
if (info.formatVersion === CURRENT_SAVE_FORMAT) return profile;
const upgraded = upgradeSave(profile, info.formatVersion);
this.saveProfile(userId, upgraded);
return upgraded;
}
saveProfile(userId: string, profile: BlkBlock): void {
const now = new Date().toISOString();
const previous = existsSync(this.#infoPath(userId)) ? (JSON.parse(readFileSync(this.#infoPath(userId), 'utf8')) as SaveInfo) : undefined;
writeFileAtomic(this.#profilePath(userId), encodeBlk(profile));
const info: SaveInfo = { formatVersion: CURRENT_SAVE_FORMAT, created: previous?.created ?? now, updated: now };
writeFileAtomic(this.#infoPath(userId), JSON.stringify(info, null, 2));
}
#infoPath(userId: string): string {
return join(this.#folder, safeId(userId), 'save.json');
}
#profilePath(userId: string): string {
return join(this.#folder, safeId(userId), 'profile.blk');
}
}
function safeId(userId: string): string {
if (!/^\d+$/.test(userId)) throw new Error(`invalid user id: ${userId}`);
return userId;
}
@@ -0,0 +1,19 @@
/**
* Save format versions. Each change to what a save holds adds one upgrade step from the
* previous version, so a save made by any earlier release still opens.
*/
import type { BlkBlock } from '@wto/blk';
export const CURRENT_SAVE_FORMAT = 1;
/** UPGRADES[n] turns a version n+1 profile into a version n+2 profile. */
const UPGRADES: ReadonlyArray<(profile: BlkBlock) => BlkBlock> = [];
export function upgradeSave(profile: BlkBlock, fromVersion: number): BlkBlock {
if (!Number.isInteger(fromVersion) || fromVersion < 1 || fromVersion > CURRENT_SAVE_FORMAT) {
throw new Error(`save format version ${fromVersion} is not supported by this version (current: ${CURRENT_SAVE_FORMAT})`);
}
let upgraded = profile;
for (let version = fromVersion; version < CURRENT_SAVE_FORMAT; version++) upgraded = UPGRADES[version - 1]!(upgraded);
return upgraded;
}
@@ -0,0 +1,49 @@
/**
* One HTTP request from the game and the answer to it, as the services see them.
*
* The build points every Gaijin URL at the local service with the original host as the first
* path segment: https://char-lw-….warthunder.com/char becomes
* http://127.0.0.1:<port>/char-lw-….warthunder.com/char. Requests whose host the login
* component replaced on its own (YU2_AUTH_HOST and the like keep only the path) arrive
* without that segment; originalHost is then undefined.
*/
import type { IncomingHttpHeaders } from 'node:http';
export interface ServiceRequest {
readonly method: string;
readonly originalHost: string | undefined;
/** Path below the original host, starting with '/', without the query. */
readonly path: string;
readonly query: URLSearchParams;
readonly headers: IncomingHttpHeaders;
readonly body: Buffer;
}
export interface ServiceResponse {
readonly status: number;
readonly headers?: Readonly<Record<string, string>>;
readonly body?: Uint8Array | string;
/** Readable extras for the traffic log (decoded BLK and the like); never sent to the game. */
readonly logNotes?: LogNotes;
}
export interface LogNotes {
/** Short text for the one-line summary, e.g. the char action name. */
readonly summary?: string;
/** True when no service implements this request yet and a default answer was given. */
readonly unhandled?: boolean;
/**
* The request body with secrets (passwords and the like) masked. When a service sets it,
* the traffic log stores this instead of the body the game sent.
*/
readonly redactedRequestBody?: string;
readonly requestText?: string;
readonly responseText?: string;
}
/** A Gaijin service emulated by the local service (one protocol-layer module each). */
export interface Service {
readonly name: string;
accepts(request: ServiceRequest): boolean;
handle(request: ServiceRequest): ServiceResponse;
}
@@ -0,0 +1,85 @@
/**
* The local service's one listening port. Every address in the game's network.blk points
* here, so besides HTTP it also receives connections in other protocols
* (TLS from addresses that still say https://, the matching server's and chat's own
* protocols). Those are recorded in the traffic log and left open without an answer.
*/
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
import type { Socket } from 'node:net';
import { describeFirstBytes } from '../traffic-log/first-bytes.ts';
import type { TrafficLog } from '../traffic-log/traffic-log.ts';
import type { ServiceRequest } from './exchange.ts';
import { parseRequestTarget } from './request-target.ts';
import type { Router } from './router.ts';
const MAX_BODY_BYTES = 64 * 1024 * 1024;
/** Lets a launcher check that this process is the local service and is ready. */
export const HEALTH_PATH = '/_wto/health';
export function createListener(router: Router, log: TrafficLog): Server {
const connections = new WeakMap<Socket, number>();
let nextConnection = 0;
const connectionOf = (socket: Socket) => connections.get(socket) ?? 0;
const server = createServer({ requestTimeout: 0, headersTimeout: 0, keepAliveTimeout: 0 }, (incoming, outgoing) => {
readBody(incoming).then(
(body) => respond(incoming, outgoing, body),
() => outgoing.writeHead(413).end(),
);
});
function respond(incoming: IncomingMessage, outgoing: ServerResponse, body: Buffer): void {
const target = parseRequestTarget(incoming.url ?? '/');
if (target.originalHost === undefined && target.path === HEALTH_PATH) {
outgoing.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ app: 'wto-local-service', pid: process.pid }));
return;
}
const request: ServiceRequest = { method: incoming.method ?? 'GET', ...target, headers: incoming.headers, body };
const { service, response } = router.route(request);
log.exchange(request, service, response, connectionOf(incoming.socket));
outgoing.writeHead(response.status, response.headers ?? {});
outgoing.end(response.body ?? '');
}
server.on('connection', (socket: Socket) => {
nextConnection += 1;
const id = nextConnection;
connections.set(socket, id);
log.connectionOpened(id, socket.remotePort);
socket.on('close', () => log.connectionClosed(id, socket.bytesRead, socket.bytesWritten));
});
server.on('clientError', (error: NodeJS.ErrnoException & { rawPacket?: Buffer }, socket: Socket) => {
if (error.rawPacket && error.rawPacket.length > 0) {
log.nonHttpConnection(connectionOf(socket), describeFirstBytes(error.rawPacket), error.code ?? error.message);
return;
}
socket.destroy();
});
server.on('upgrade', (incoming: IncomingMessage, socket: Socket) => {
const target = parseRequestTarget(incoming.url ?? '/');
log.webSocket(connectionOf(socket), { method: incoming.method ?? 'GET', ...target, headers: incoming.headers, body: Buffer.alloc(0) });
socket.destroy();
});
return server;
}
function readBody(incoming: IncomingMessage): Promise<Buffer> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let size = 0;
incoming.on('data', (chunk: Buffer) => {
size += chunk.length;
if (size > MAX_BODY_BYTES) {
reject(new Error('request body too large'));
incoming.destroy();
return;
}
chunks.push(chunk);
});
incoming.on('end', () => resolve(Buffer.concat(chunks)));
incoming.on('error', reject);
});
}
@@ -0,0 +1,27 @@
/** Split a request URL into the original Gaijin host (when present), the path and the query. */
export interface RequestTarget {
readonly originalHost: string | undefined;
readonly path: string;
readonly query: URLSearchParams;
}
/**
* The build only moves Gaijin hosts and external IPv4 addresses into the path (packages/build,
* network/address-rewrite.ts uses the same domain list), so only those count as a host
* segment; "/login.php" is a path, not a host.
*/
const GAIJIN_DOMAINS = ['gaijin.net', 'gaijinent.com', 'warthunder.com', 'gaijin.ops'];
const IPV4 = /^\d{1,3}(\.\d{1,3}){3}$/;
export function parseRequestTarget(url: string): RequestTarget {
const parsed = new URL(url, 'http://local');
const segments = parsed.pathname.split('/');
const first = (segments[1] ?? '').toLowerCase();
if (isHostSegment(first)) return { originalHost: first, path: `/${segments.slice(2).join('/')}`, query: parsed.searchParams };
return { originalHost: undefined, path: parsed.pathname, query: parsed.searchParams };
}
function isHostSegment(segment: string): boolean {
return IPV4.test(segment) || GAIJIN_DOMAINS.some((domain) => segment === domain || segment.endsWith(`.${domain}`));
}
@@ -0,0 +1,31 @@
/**
* Hand each request to the service that accepts it. A request no service accepts is answered
* with 404 and marked in the traffic log, so missing services show up there.
*/
import type { Service, ServiceRequest, ServiceResponse } from './exchange.ts';
export interface RoutedResponse {
readonly service: string;
readonly response: ServiceResponse;
}
export class Router {
readonly #services: readonly Service[];
constructor(services: readonly Service[]) {
this.#services = services;
}
route(request: ServiceRequest): RoutedResponse {
const service = this.#services.find((candidate) => candidate.accepts(request));
if (!service) {
return { service: 'none', response: { status: 404, body: 'no local service for this request', logNotes: { unhandled: true } } };
}
try {
return { service: service.name, response: service.handle(request) };
} catch (error) {
const message = error instanceof Error ? error.stack ?? error.message : String(error);
return { service: service.name, response: { status: 500, body: 'local service error', logNotes: { summary: 'ERROR', responseText: message } } };
}
}
}
@@ -0,0 +1,19 @@
/**
* Write a file so that a crash leaves either the old or the new content, never a mix:
* write a temporary file next to it, flush it to disk, then rename it over the target.
*/
import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, writeSync } from 'node:fs';
import { dirname } from 'node:path';
export function writeFileAtomic(path: string, content: Uint8Array | string): void {
mkdirSync(dirname(path), { recursive: true });
const temporary = `${path}.${process.pid}.tmp`;
const fd = openSync(temporary, 'w');
try {
writeSync(fd, typeof content === 'string' ? Buffer.from(content, 'utf8') : content);
fsyncSync(fd);
} finally {
closeSync(fd);
}
renameSync(temporary, path);
}
@@ -0,0 +1,55 @@
/**
* Describe the first bytes of a connection that did not speak HTTP, for the traffic log:
* a TLS handshake (an address still using https://), or some other protocol (the matching
* server and chat connect to the same port with their own protocols).
*/
export interface FirstBytesInfo {
readonly kind: 'tls' | 'other';
/** Host name the client asked for in a TLS handshake (server name indication), if any. */
readonly serverName?: string;
readonly hexHead: string;
readonly textHead: string;
}
const TLS_HANDSHAKE_RECORD = 0x16;
const CLIENT_HELLO = 0x01;
const SERVER_NAME_EXTENSION = 0x0000;
export function describeFirstBytes(bytes: Uint8Array): FirstBytesInfo {
const head = bytes.subarray(0, 64);
const common = {
hexHead: Buffer.from(head).toString('hex'),
textHead: Buffer.from(head).toString('latin1').replace(/[^\x20-\x7e]/g, '.'),
};
if (bytes[0] !== TLS_HANDSHAKE_RECORD) return { kind: 'other', ...common };
const serverName = readServerName(bytes);
return serverName === undefined ? { kind: 'tls', ...common } : { kind: 'tls', serverName, ...common };
}
/** Walk a TLS ClientHello (RFC 8446 4.1.2) to the server_name extension (RFC 6066 3). */
function readServerName(bytes: Uint8Array): string | undefined {
const view = Buffer.from(bytes);
try {
let at = 5;
if (view[at] !== CLIENT_HELLO) return undefined;
at += 4 + 2 + 32;
at += 1 + view.readUInt8(at);
at += 2 + view.readUInt16BE(at);
at += 1 + view.readUInt8(at);
const extensionsEnd = at + 2 + view.readUInt16BE(at);
at += 2;
while (at + 4 <= extensionsEnd) {
const type = view.readUInt16BE(at);
const length = view.readUInt16BE(at + 2);
if (type === SERVER_NAME_EXTENSION) {
const nameLength = view.readUInt16BE(at + 4 + 3);
return view.toString('ascii', at + 4 + 5, at + 4 + 5 + nameLength);
}
at += 4 + length;
}
} catch {
return undefined;
}
return undefined;
}
@@ -0,0 +1,101 @@
/**
* Record of everything the game sent to the local service, so that what the client actually
* asks for can be read off instead of guessed (implementation notes, milestone 1 steps 3 and 4).
*
* <data>/logs/<start time>/requests.jsonl one JSON line per HTTP exchange or raw connection
* <data>/logs/<start time>/bodies/ request and response bodies, plus readable text
* (decoded BLK) next to them
*
* Each exchange also prints one line to the console.
*/
import { appendFileSync, mkdirSync, writeFileSync } from 'node:fs';
import type { IncomingHttpHeaders } from 'node:http';
import { join } from 'node:path';
import type { ServiceRequest, ServiceResponse } from '../server/exchange.ts';
import type { FirstBytesInfo } from './first-bytes.ts';
export class TrafficLog {
readonly folder: string;
readonly #linesPath: string;
readonly #bodiesFolder: string;
#sequence = 0;
constructor(dataFolder: string) {
this.folder = join(dataFolder, 'logs', new Date().toISOString().replace(/[:.]/g, '-'));
this.#linesPath = join(this.folder, 'requests.jsonl');
this.#bodiesFolder = join(this.folder, 'bodies');
mkdirSync(this.#bodiesFolder, { recursive: true });
}
exchange(request: ServiceRequest, service: string, response: ServiceResponse, connectionId: number): void {
const id = this.#next();
const notes = response.logNotes ?? {};
const files = {
request: this.#writeBody(id, 'req.bin', notes.redactedRequestBody ?? request.body),
requestText: this.#writeBody(id, 'req.txt', notes.requestText),
response: this.#writeBody(id, 'resp.bin', response.body),
responseText: this.#writeBody(id, 'resp.txt', notes.responseText),
};
this.#append({
id, time: new Date().toISOString(), kind: 'http', connection: connectionId,
method: request.method, host: request.originalHost ?? null, path: request.path, query: request.query.toString(),
headers: plainHeaders(request.headers), requestBytes: request.body.length,
service, summary: notes.summary ?? null, unhandled: notes.unhandled ?? false,
status: response.status, responseBytes: byteLength(response.body), files,
});
const flag = notes.unhandled ? ' [UNHANDLED]' : '';
console.log(`#${id} ${request.method} ${request.originalHost ?? '(no host)'}${request.path} -> ${service}` +
`${notes.summary ? ` ${notes.summary}` : ''} = ${response.status}${flag}`);
}
connectionOpened(connectionId: number, remotePort: number | undefined): void {
this.#append({ id: this.#next(), time: new Date().toISOString(), kind: 'connection-open', connection: connectionId, remotePort: remotePort ?? null });
}
connectionClosed(connectionId: number, bytesRead: number, bytesWritten: number): void {
this.#append({ id: this.#next(), time: new Date().toISOString(), kind: 'connection-close', connection: connectionId, bytesRead, bytesWritten });
}
nonHttpConnection(connectionId: number, info: FirstBytesInfo, error: string): void {
const id = this.#next();
const { kind, ...details } = info;
this.#append({ id, time: new Date().toISOString(), kind: `non-http-${kind}`, connection: connectionId, ...details, parserError: error });
console.log(`#${id} non-HTTP connection (${info.kind}${info.serverName ? `, asks for ${info.serverName}` : ''}): ${info.textHead}`);
}
webSocket(connectionId: number, request: ServiceRequest): void {
const id = this.#next();
this.#append({ id, time: new Date().toISOString(), kind: 'websocket', connection: connectionId, host: request.originalHost ?? null,
path: request.path, query: request.query.toString(), headers: plainHeaders(request.headers) });
console.log(`#${id} WebSocket ${request.originalHost ?? '(no host)'}${request.path} (refused)`);
}
#next(): number {
this.#sequence += 1;
return this.#sequence;
}
#append(line: object): void {
appendFileSync(this.#linesPath, JSON.stringify(line) + '\n');
}
#writeBody(id: number, suffix: string, content: Uint8Array | string | undefined): string | null {
if (content === undefined || byteLength(content) === 0) return null;
const name = `${String(id).padStart(6, '0')}.${suffix}`;
writeFileSync(join(this.#bodiesFolder, name), content);
return name;
}
}
function byteLength(body: Uint8Array | string | undefined): number {
if (body === undefined) return 0;
return typeof body === 'string' ? Buffer.byteLength(body) : body.length;
}
function plainHeaders(headers: IncomingHttpHeaders): Record<string, string> {
const result: Record<string, string> = {};
for (const [name, value] of Object.entries(headers)) {
if (value !== undefined) result[name] = Array.isArray(value) ? value.join(', ') : value;
}
return result;
}
+1
View File
@@ -12,6 +12,7 @@ dependencies = [
"capstone>=5.0",
"keystone-engine>=0.9.2",
"zstandard>=0.22",
"procmon-parser>=0.4",
]
[project.scripts]
+2 -2
View File
@@ -46,9 +46,9 @@ def _check_patches(args: argparse.Namespace) -> int:
problem = disagreement(definition)
if problem:
mismatched += 1
print(f" assembly disagrees with stored bytes: {definition.identifier}: {problem}")
print(f" source disagrees with stored bytes: {definition.identifier}: {problem}")
if not mismatched:
print(" every patch's assembly source compiles to its stored bytes")
print(" every patch's source (assembly or data text) encodes to its stored bytes")
plan = plan_patches(PeImage(args.exe.read_bytes()), definitions)
print(plan.describe())
+19 -5
View File
@@ -27,12 +27,26 @@ def assemble(lines: tuple[str, ...] | list[str]) -> bytes:
return bytes(encoding)
def encode_data(data: dict, length: int) -> bytes:
"""Encode a data edit's text and pad it with zero bytes to `length`."""
try:
encoded = str(data["text"]).encode(str(data["encoding"]))
except (KeyError, LookupError) as error:
raise DefinitionError(f"data edit needs a valid 'encoding' and 'text': {error}") from error
if len(encoded) > length:
raise DefinitionError(f"data text is {len(encoded)} bytes, longer than the {length}-byte edit")
return encoded + bytes(length - len(encoded))
def disagreement(definition: PatchDefinition) -> str | None:
"""Why a definition's assembly source and stored bytes differ, or None if they agree."""
if not definition.edit.asm:
return "no assembly source recorded for the stored bytes"
compiled = assemble(definition.edit.asm)
"""Why a definition's source (assembly or data text) and stored bytes differ, or None if they agree."""
if definition.edit.data is not None:
source, compiled = "data text", encode_data(definition.edit.data, len(definition.edit.payload))
elif definition.edit.asm:
source, compiled = "assembly", assemble(definition.edit.asm)
else:
return "no assembly source or data text recorded for the stored bytes"
if compiled != definition.edit.payload:
return (f"assembly compiles to {compiled.hex()} but the stored bytes are "
return (f"{source} encodes to {compiled.hex()} but the stored bytes are "
f"{definition.edit.payload.hex()}")
return None
@@ -30,6 +30,9 @@ class PatchEdit:
payload: bytes
expect_original: bytes
asm: tuple[str, ...]
# For edits to constant data (strings) instead of code: {"encoding": ..., "text": ...}.
# The text, encoded and padded with zero bytes to the edit's length, must equal the payload.
data: dict | None = None
def __post_init__(self) -> None:
if len(self.payload) != len(self.expect_original):
@@ -94,6 +97,7 @@ def _read_edit(directory: Path, raw: object) -> PatchEdit:
payload=_hex(directory, "bytes", raw["bytes"]),
expect_original=_hex(directory, "expect_original", raw["expect_original"]),
asm=tuple(str(line) for line in raw.get("asm", ())),
data=raw.get("data") if isinstance(raw.get("data"), dict) else None,
)