refactor(repo)!: move apps, shared packages, and patch definitions
Everything sat in packages/: two programs next to the small libraries
they use, and the patch data loose at the root. The programs now live in
apps/ and the shared libraries in packages/:
apps/server the local server (was packages/local-service),
package @wto/server
packages/patcher builds the game copy (was packages/build),
package @wto/patcher
patches/exe exe patch definitions (was exe-patches)
patches/gui GUI script patches (was gui-patches)
Inside the server, the network layer folder becomes transport/ so it is
not server/server/, the entry module is server.ts, and startLocalService
and its types become startServer, ServerOptions and RunningServer. The
health answer names the app wto-server, and the TLS files in the data
folder are server.key and server.crt (made again on the next start).
Comments, logs and tool texts say "local server".
The patcher no longer reaches into the server's folder. It read the
default tuning/store.jsonc by a relative path to register bundle GUIDs
for the multi-vehicle packs, which also ignored the player's overrides
in <data>/tuning/. It now takes the pack ids from its caller; the
server exports multiVehiclePackIds(dataFolder), which reads them the way
the running server does. rebuildGuiPack takes the patch folder from its
caller as well.
The development build moves out of the patcher to
scripts/build-game-copy.ts, since it uses both the server and the
patcher. It needs --data (the folder the server will run with) and
defaults the patch folders and the hook library to this repository.
Checked with the root typecheck, check-patches, check-gui,
check-offsets, the native build, a run of build-game-copy.ts into a
scratch folder (12 exe patches, 35 GUI patches, 496 bundle GUIDs as
before) and a server start from apps/server answering wto-server.
BREAKING CHANGE: Use @wto/server and @wto/patcher from the new workspace paths. Run the development build with scripts/build-game-copy.ts and pass --data.
This commit is contained in:
1 parent
9c813ccf7d
commit
930ea07630
476 files changed
+275
-251
No files matched your search
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* 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 server 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;
|
||||
/** Public media bytes can already be recovered from the local media cache. */
|
||||
readonly omitResponseBody?: boolean;
|
||||
}
|
||||
|
||||
/** A Gaijin service emulated by the local server (one protocol-layer module each). */
|
||||
export interface Service {
|
||||
readonly name: string;
|
||||
accepts(request: ServiceRequest): boolean;
|
||||
handle(request: ServiceRequest): ServiceResponse | Promise<ServiceResponse>;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* The HTTP side of the local server's port. port-listener.ts hands it every connection
|
||||
* that is not the matching protocol (TLS already decrypted); connections in other protocols
|
||||
* (chat) 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 server and is ready. */
|
||||
export const HEALTH_PATH = '/_wto/health';
|
||||
|
||||
/** Connection number given by the port listener, for the traffic log. */
|
||||
export type ConnectionNumbers = (socket: Socket) => number;
|
||||
|
||||
export function createHttpServer(router: Router, log: TrafficLog, connectionOf: ConnectionNumbers): Server {
|
||||
const server = createServer({ requestTimeout: 0, headersTimeout: 0, keepAliveTimeout: 0 }, (incoming, outgoing) => {
|
||||
void readBody(incoming).then(
|
||||
(body) => respond(incoming, outgoing, body),
|
||||
() => { outgoing.writeHead(413).end(); },
|
||||
).catch((error: Error) => outgoing.destroy(error));
|
||||
});
|
||||
|
||||
async function respond(incoming: IncomingMessage, outgoing: ServerResponse, body: Buffer): Promise<void> {
|
||||
const target = parseRequestTarget(incoming.url ?? '/', incoming.headers.host);
|
||||
if (target.originalHost === undefined && target.path === HEALTH_PATH) {
|
||||
outgoing.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ app: 'wto-server', pid: process.pid }));
|
||||
return;
|
||||
}
|
||||
const request: ServiceRequest = { method: incoming.method ?? 'GET', ...target, headers: incoming.headers, body };
|
||||
const connection = connectionOf(incoming.socket);
|
||||
const { service, response } = await router.route(request);
|
||||
if (outgoing.destroyed) return;
|
||||
log.exchange(request, service, response, connection);
|
||||
outgoing.writeHead(response.status, response.headers ?? {});
|
||||
outgoing.end(response.body ?? '');
|
||||
}
|
||||
|
||||
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 ?? '/', incoming.headers.host);
|
||||
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,83 @@
|
||||
/**
|
||||
* The local server's single listening port. Every address in the game's network.blk points
|
||||
* here, and the network hook library routes all other outbound game
|
||||
* connections here as well (5.1). The first bytes of a connection decide which protocol handler
|
||||
* accepts it:
|
||||
* - Matching binary packet (first byte 1, matching/matching-frame.ts) -> MatchingService;
|
||||
* - Plaintext IRC handshake (`PASS` / `NICK` / `USER` / `CAP` / `PING`) -> IrcServer;
|
||||
* - TLS ClientHello (record type 0x16) -> decrypted with the local certificate, then routed
|
||||
* to IrcServer or the HTTP server based on the first decrypted bytes;
|
||||
* - Everything else -> HTTP server directly.
|
||||
*/
|
||||
import { createServer, type Server, type Socket } from 'node:net';
|
||||
import { createSecureContext, TLSSocket } from 'node:tls';
|
||||
import { startsIrcHandshake } from '../chat/irc-protocol.ts';
|
||||
import { IrcServer } from '../chat/irc-server.ts';
|
||||
import type { TlsCredentials } from './tls/tls-certificate.ts';
|
||||
import type { MatchingRequestTable } from '../matching/matching-requests.ts';
|
||||
import { MatchingService } from '../matching/matching-service.ts';
|
||||
import { startsMatchingPacket } from '../matching/matching-frame.ts';
|
||||
import type { TrafficLog } from '../traffic-log/traffic-log.ts';
|
||||
import { createHttpServer } from './http-listener.ts';
|
||||
import type { Router } from './router.ts';
|
||||
|
||||
export interface PortListener {
|
||||
readonly server: Server;
|
||||
readonly matching: MatchingService;
|
||||
/** Drop every open connection (on shutdown; the game keeps some open indefinitely). */
|
||||
destroyConnections(): void;
|
||||
}
|
||||
|
||||
const TLS_HANDSHAKE = 0x16;
|
||||
|
||||
export function createPortListener(router: Router, matchingRequests: MatchingRequestTable, log: TrafficLog,
|
||||
credentials: TlsCredentials): PortListener {
|
||||
const secureContext = createSecureContext({ key: credentials.key, cert: credentials.certificate });
|
||||
const numbers = new WeakMap<Socket, number>();
|
||||
const open = new Set<Socket>();
|
||||
let lastNumber = 0;
|
||||
const http = createHttpServer(router, log, (socket) => numbers.get(socket) ?? 0);
|
||||
const matching = new MatchingService(matchingRequests, log);
|
||||
const irc = new IrcServer();
|
||||
|
||||
const server = createServer((socket) => {
|
||||
lastNumber += 1;
|
||||
const number = lastNumber;
|
||||
numbers.set(socket, number);
|
||||
open.add(socket);
|
||||
log.connectionOpened(number, socket.remotePort);
|
||||
socket.on('close', () => {
|
||||
open.delete(socket);
|
||||
log.connectionClosed(number, socket.bytesRead, socket.bytesWritten);
|
||||
});
|
||||
socket.on('error', () => socket.destroy());
|
||||
|
||||
socket.once('data', (first: Buffer) => {
|
||||
socket.pause();
|
||||
socket.unshift(first);
|
||||
if (startsMatchingPacket(first)) matching.accept(socket, number);
|
||||
else if (startsIrcHandshake(first)) irc.accept(socket);
|
||||
else if (first[0] === TLS_HANDSHAKE) {
|
||||
const secure = new TLSSocket(socket, { isServer: true, secureContext });
|
||||
numbers.set(secure, number);
|
||||
secure.on('error', () => socket.destroy());
|
||||
secure.once('data', (innerFirst: Buffer) => {
|
||||
secure.pause();
|
||||
secure.unshift(innerFirst);
|
||||
if (startsIrcHandshake(innerFirst)) irc.accept(secure);
|
||||
else http.emit('connection', secure);
|
||||
process.nextTick(() => secure.resume());
|
||||
});
|
||||
} else http.emit('connection', socket);
|
||||
process.nextTick(() => socket.resume());
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
server,
|
||||
matching,
|
||||
destroyConnections: () => {
|
||||
for (const socket of open) socket.destroy();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/** Split a request into the original Gaijin host (when known), the path and the query. */
|
||||
|
||||
export interface RequestTarget {
|
||||
readonly originalHost: string | undefined;
|
||||
readonly path: string;
|
||||
readonly query: URLSearchParams;
|
||||
}
|
||||
|
||||
/**
|
||||
* Addresses rewritten by the build carry the original host as the first path segment (packages/patcher,
|
||||
* network/address-rewrite.ts moves only Gaijin hosts and external IPv4 addresses there, so only
|
||||
* those count as a host segment; "/login.php" is a path, not a host). Connections the network
|
||||
* hook library redirected keep their original URL, so their host is the
|
||||
* Host header (for https, the one sent inside the TLS stream) unless that names this machine.
|
||||
*/
|
||||
const GAIJIN_DOMAINS = ['gaijin.net', 'gaijinent.com', 'warthunder.com', 'gaijin.ops'];
|
||||
const IPV4 = /^\d{1,3}(\.\d{1,3}){3}$/;
|
||||
const LOCAL_HOSTS = new Set(['127.0.0.1', '127.0.0.2', 'localhost', '::1', '[::1]']);
|
||||
|
||||
export function parseRequestTarget(url: string, hostHeader?: 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: headerHost(hostHeader), path: parsed.pathname, query: parsed.searchParams };
|
||||
}
|
||||
|
||||
function isHostSegment(segment: string): boolean {
|
||||
return IPV4.test(segment) || GAIJIN_DOMAINS.some((domain) => segment === domain || segment.endsWith(`.${domain}`));
|
||||
}
|
||||
|
||||
function headerHost(header: string | undefined): string | undefined {
|
||||
const host = header?.trim().toLowerCase().replace(/:\d+$/, '');
|
||||
return host && !LOCAL_HOSTS.has(host) ? host : undefined;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
async route(request: ServiceRequest): Promise<RoutedResponse> {
|
||||
const service = this.#services.find((candidate) => candidate.accepts(request));
|
||||
if (!service) {
|
||||
return { service: 'none', response: { status: 404, body: 'no local server for this request', logNotes: { unhandled: true } } };
|
||||
}
|
||||
try {
|
||||
return { service: service.name, response: await 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 server error', logNotes: { summary: 'ERROR', responseText: message } } };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* The few ASN.1 DER encodings a self-signed X.509 certificate needs (ITU-T X.690). Node's
|
||||
* crypto makes keys and signatures but cannot build a certificate, so tls-certificate.ts
|
||||
* assembles one from these.
|
||||
*/
|
||||
|
||||
export function derSequence(...items: Buffer[]): Buffer {
|
||||
return tagged(0x30, Buffer.concat(items));
|
||||
}
|
||||
|
||||
export function derSet(...items: Buffer[]): Buffer {
|
||||
return tagged(0x31, Buffer.concat(items));
|
||||
}
|
||||
|
||||
/** A non-negative integer given as big-endian bytes. */
|
||||
export function derUnsignedInteger(bytes: Buffer): Buffer {
|
||||
let start = 0;
|
||||
while (start < bytes.length - 1 && bytes[start] === 0) start += 1;
|
||||
const trimmed = bytes.subarray(start);
|
||||
return tagged(0x02, (trimmed[0]! & 0x80) ? Buffer.concat([Buffer.from([0]), trimmed]) : trimmed);
|
||||
}
|
||||
|
||||
export function derSmallInteger(value: number): Buffer {
|
||||
return derUnsignedInteger(Buffer.from([value]));
|
||||
}
|
||||
|
||||
export function derObjectId(dotted: string): Buffer {
|
||||
const parts = dotted.split('.').map(Number);
|
||||
const bytes = [40 * parts[0]! + parts[1]!];
|
||||
for (const part of parts.slice(2)) {
|
||||
const groups = [part & 0x7f];
|
||||
for (let rest = part >>> 7; rest > 0; rest >>>= 7) groups.unshift((rest & 0x7f) | 0x80);
|
||||
bytes.push(...groups);
|
||||
}
|
||||
return tagged(0x06, Buffer.from(bytes));
|
||||
}
|
||||
|
||||
export function derUtf8String(text: string): Buffer {
|
||||
return tagged(0x0c, Buffer.from(text, 'utf8'));
|
||||
}
|
||||
|
||||
/** UTCTime, valid for the years 1950-2049. */
|
||||
export function derUtcTime(date: Date): Buffer {
|
||||
const text = date.toISOString().replace(/[-:T]/g, '').slice(2, 14) + 'Z';
|
||||
return tagged(0x17, Buffer.from(text, 'ascii'));
|
||||
}
|
||||
|
||||
export function derBitString(bytes: Buffer): Buffer {
|
||||
return tagged(0x03, Buffer.concat([Buffer.from([0]), bytes]));
|
||||
}
|
||||
|
||||
/** An explicitly tagged context-specific field: [number] EXPLICIT. */
|
||||
export function derExplicit(number: number, content: Buffer): Buffer {
|
||||
return tagged(0xa0 | number, content);
|
||||
}
|
||||
|
||||
function tagged(tag: number, content: Buffer): Buffer {
|
||||
return Buffer.concat([Buffer.from([tag]), length(content.length), content]);
|
||||
}
|
||||
|
||||
function length(size: number): Buffer {
|
||||
if (size < 0x80) return Buffer.from([size]);
|
||||
const bytes: number[] = [];
|
||||
for (let rest = size; rest > 0; rest >>>= 8) bytes.unshift(rest & 0xff);
|
||||
return Buffer.from([0x80 | bytes.length, ...bytes]);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* The local server's TLS certificate: the network hook library sends
|
||||
* the game's https connections to the local server's port, which answers them with this
|
||||
* self-signed certificate. It is made on first start and kept in <data folder>/tls/; it is
|
||||
* only ever presented to the game, never installed in the system's certificate store.
|
||||
*
|
||||
* Key: ECDSA P-256. Certificate: X.509 v3, subject and issuer "WTOffline local server",
|
||||
* signed with ecdsa-with-SHA256, valid from yesterday for 20 years.
|
||||
*/
|
||||
import { generateKeyPairSync, randomBytes, sign, type KeyObject } from 'node:crypto';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { writeFileAtomic } from '../../storage/atomic-file.ts';
|
||||
import { derBitString, derExplicit, derObjectId, derSequence, derSet, derSmallInteger, derUnsignedInteger, derUtcTime, derUtf8String } from './der.ts';
|
||||
|
||||
const FOLDER = 'tls';
|
||||
const KEY_FILE = 'server.key';
|
||||
const CERTIFICATE_FILE = 'server.crt';
|
||||
const COMMON_NAME = 'WTOffline local server';
|
||||
const ECDSA_WITH_SHA256 = '1.2.840.10045.4.3.2';
|
||||
const COMMON_NAME_ID = '2.5.4.3';
|
||||
const VALID_YEARS = 20;
|
||||
|
||||
export interface TlsCredentials {
|
||||
readonly key: string;
|
||||
readonly certificate: string;
|
||||
}
|
||||
|
||||
export function loadOrCreateCredentials(dataFolder: string): TlsCredentials {
|
||||
const folder = join(dataFolder, FOLDER);
|
||||
const keyPath = join(folder, KEY_FILE);
|
||||
const certificatePath = join(folder, CERTIFICATE_FILE);
|
||||
if (existsSync(keyPath) && existsSync(certificatePath)) {
|
||||
return { key: readFileSync(keyPath, 'utf8'), certificate: readFileSync(certificatePath, 'utf8') };
|
||||
}
|
||||
const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
|
||||
const credentials = {
|
||||
key: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(),
|
||||
certificate: pem('CERTIFICATE', selfSignedCertificate(privateKey, publicKey)),
|
||||
};
|
||||
writeFileAtomic(keyPath, credentials.key);
|
||||
writeFileAtomic(certificatePath, credentials.certificate);
|
||||
return credentials;
|
||||
}
|
||||
|
||||
function selfSignedCertificate(privateKey: KeyObject, publicKey: KeyObject): Buffer {
|
||||
const name = derSequence(derSet(derSequence(derObjectId(COMMON_NAME_ID), derUtf8String(COMMON_NAME))));
|
||||
const algorithm = derSequence(derObjectId(ECDSA_WITH_SHA256));
|
||||
const notBefore = new Date(Date.now() - 24 * 3600 * 1000);
|
||||
const notAfter = new Date(notBefore);
|
||||
notAfter.setUTCFullYear(notAfter.getUTCFullYear() + VALID_YEARS);
|
||||
const serial = randomBytes(16);
|
||||
serial[0]! &= 0x7f;
|
||||
const toBeSigned = derSequence(
|
||||
derExplicit(0, derSmallInteger(2)),
|
||||
derUnsignedInteger(serial),
|
||||
algorithm,
|
||||
name,
|
||||
derSequence(derUtcTime(notBefore), derUtcTime(notAfter)),
|
||||
name,
|
||||
publicKey.export({ type: 'spki', format: 'der' }),
|
||||
);
|
||||
const signature = sign('sha256', toBeSigned, { key: privateKey, dsaEncoding: 'der' });
|
||||
return derSequence(toBeSigned, algorithm, derBitString(signature));
|
||||
}
|
||||
|
||||
function pem(label: string, der: Buffer): string {
|
||||
const lines = der.toString('base64').match(/.{1,64}/g) ?? [];
|
||||
return `-----BEGIN ${label}-----\n${lines.join('\n')}\n-----END ${label}-----\n`;
|
||||
}
|
||||
Reference in new issue
Block a user