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 5421268fbf
commit 18f63bf33e
55 files changed
+1559 -58

No files matched your search

@@ -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 } } };
}
}
}