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:
N0VAN0M4LY committed 2026-11-29 03:20:54 +08:00
1 parent 9c813ccf7d
commit 930ea07630
476 files changed
+275 -251

No files matched your search

@@ -0,0 +1,85 @@
/**
* The `mrpc.generic_notify` message that starts a local battle (`from: "wto_battle"`,
* `func: "launch"`), received by the client's launch script patch
* (patches/gui/battle/launch-local-battle-from-queue).
*
* - `mission`: the complete mission settings for `select_training_mission`, as a typed tree
* `{ p: [[name, type, value], ...], b: [[name, node], ...] }` with type "t", "i", "r" or "b".
* Matching notifications are JSON, which cannot tell 1 from 1.0; the engine reads ints and reals
* with typed getters, so the type travels with every value. Repeated blocks stay separate.
* - `lobby`: the session lobby settings the client's own room scripts read during the battle
* (game mode and both sides' countries).
* - `battle`: what the client keeps for this battle (session id for the settlement, extra slots,
* `spawnScore` for Ground Realistic Battles, and `awards` for the in-battle reward banner).
*/
import type { BlkBlock, BlkValue } from '@wto/blk';
import type { BannerParams } from '../battle/battle-economy.ts';
import type { BattleLaunchPlan } from '../battle/battle-matchmaker.ts';
import { battleMissionSettings } from '../battle/battle-mission-settings.ts';
type WireParam = readonly [name: string, type: 't' | 'i' | 'r' | 'b', value: string | number | boolean];
interface WireBlock {
readonly p: readonly WireParam[];
readonly b: ReadonlyArray<readonly [name: string, block: WireBlock]>;
}
export interface BattleLaunchNotify extends Record<string, unknown> {
readonly from: 'wto_battle';
readonly func: 'launch';
readonly mission: WireBlock;
readonly lobby: Readonly<Record<string, unknown>>;
readonly battle: Readonly<Record<string, unknown>>;
}
export function battleLaunchNotify(
plan: BattleLaunchPlan,
awards: BannerParams,
scores: Readonly<Record<string, number>>,
): BattleLaunchNotify {
return {
from: 'wto_battle',
func: 'launch',
mission: toWire(battleMissionSettings(plan, scores)),
lobby: {
game_mode_id: plan.modeId,
game_mode_name: plan.modeName,
economicName: plan.economicName,
symmetricTeams: plan.symmetricTeams,
country_allies: plan.countriesAllies.map(withCountryPrefix),
country_axis: plan.countriesAxis.map(withCountryPrefix),
mission: { name: plan.missionName, difficulty: plan.difficulty },
},
battle: {
sessionId: plan.sessionId,
modeName: plan.modeName,
economicName: plan.economicName,
country: plan.country,
missionName: plan.missionName,
extraBattleSlots: plan.extraBattleSlots,
...(plan.spawnScore ? { spawnScore: plan.spawnScore } : {}),
awards,
},
};
}
function toWire(block: BlkBlock): WireBlock {
return {
p: block.params.map((param) => [param.name, ...wireValue(param.name, param.value)] as const),
b: block.blocks.map((child) => [child.name, toWire(child)] as const),
};
}
function wireValue(name: string, value: BlkValue): readonly ['t' | 'i' | 'r' | 'b', string | number | boolean] {
switch (value.type) {
case 'string': return ['t', value.value];
case 'int': return ['i', value.value];
case 'real': return ['r', value.value];
case 'bool': return ['b', value.value];
default: throw new Error(`mission settings parameter ${name} has type ${value.type}, which the launch message cannot carry`);
}
}
function withCountryPrefix(country: string): string {
return country.startsWith('country_') ? country : `country_${country}`;
}
@@ -0,0 +1,87 @@
/**
* Matching request `wto_battle.fact` (patches/gui/battle/record-local-battle-awards): one fact of a
* running LocalMP battle; the answer lists the battle awards it completed, which the client shows
* as the stock award banner (scripts/streaks.nut add_streak_message). Online the battle server
* sends those banners.
*
* params: sessionId:s localPlayerId:i localTeam:i kind:s, and by kind
* "event": time:f unit:s code:i expClass:s victim:s victimIsPlayer:b friendly:b modifier:s damage:i
* "life": unit:s start:f end:f died:b
* "kill": time:f killer:i killerTeam:i victim:i victimTeam:i
* "strike": time:f the local player's nuclear bomb exploded
* answer: { streaks: [{ id:s stage:i (-1 = single-stage) stageParam:i wp:i exp:i }] }
*/
import type { BattleLiveLogs } from '../battle/battle-live-log.ts';
import type { BattleSessionStore } from '../battle/battle-session-store.ts';
import type { BattleStreaks } from '../battle/battle-streaks.ts';
import { withoutSupportPlanes } from '../battle/battle-support-planes.ts';
import type { MatchingRequestHandler } from './matching-requests.ts';
export interface BattleLiveDependencies {
readonly sessions: BattleSessionStore;
readonly liveLogs: BattleLiveLogs;
readonly streaks: BattleStreaks;
/** Units whose lives and events earn no awards (battle-support-planes.ts). */
readonly supportPlanes: ReadonlySet<string>;
}
export function battleLiveRequests(deps: BattleLiveDependencies): Array<[string, MatchingRequestHandler]> {
return [['wto_battle.fact', (request, connection) => {
const userId = connection.authenticatedUserId();
const p = request.params;
const sessionId = typeof p.sessionId === 'string' ? p.sessionId.toLowerCase() : '';
const session = userId ? deps.sessions.findForUser(sessionId, userId) : undefined;
if (!session || session.settled) return { streaks: [] };
const log = deps.liveLogs.of(session.sessionId);
if (!recordFact(log, p)) return { streaks: [] };
const awarded = deps.streaks.evaluate({
...withoutSupportPlanes({ events: log.events, lives: log.lives }, deps.supportPlanes),
feed: log.feed,
nuclearStrikes: log.nuclearStrikes,
localPlayerId: int(p.localPlayerId, -1),
localTeam: int(p.localTeam, 0),
sessionEnd: Math.max(0, ...log.lives.map((life) => life.end), ...log.events.map((e) => e.time), ...log.nuclearStrikes),
}, session);
const fresh = awarded.filter((streak) => !streak.hidden && !log.announced.has(streak.key));
for (const streak of fresh) log.announced.add(streak.key);
return {
streaks: fresh.map((streak) => ({
id: streak.id, stage: streak.stage ?? -1, stageParam: streak.stageParam, wp: streak.wp, exp: streak.exp,
})),
};
}]];
}
function recordFact(log: ReturnType<BattleLiveLogs['of']>, p: Readonly<Record<string, unknown>>): boolean {
switch (p.kind) {
case 'event':
log.events.push({
time: num(p.time), unit: str(p.unit), code: int(p.code, -1), expClass: str(p.expClass), victim: str(p.victim),
victimIsPlayer: p.victimIsPlayer === true, friendly: p.friendly === true, modifier: str(p.modifier), damage: int(p.damage, 0),
});
return true;
case 'life':
log.lives.push({ unit: str(p.unit), start: num(p.start), end: num(p.end), died: p.died === true });
return true;
case 'kill':
log.feed.push({ time: num(p.time), killer: int(p.killer, -1), killerTeam: int(p.killerTeam, 0), victim: int(p.victim, -1), victimTeam: int(p.victimTeam, 0) });
return true;
case 'strike':
log.nuclearStrikes.push(num(p.time));
return true;
default:
return false;
}
}
function str(value: unknown): string {
return typeof value === 'string' ? value : '';
}
function num(value: unknown): number {
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
}
function int(value: unknown, fallback: number): number {
return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : fallback;
}
@@ -0,0 +1,183 @@
/**
* Matching-server RPC handlers for hangar battle-rating display and battle queueing
*:
* - `wtmm_static.calc_ranks` (scripts/battlerating.nut:179)
* - `match.enqueue` (scripts/matching/servicenotifications/match.nut:75)
* - `match.leave_queue` (scripts/queue/queuestate.nut:28)
* - `match.check_reconnect`
*/
import { economyDifficulty, type BattleEconomy } from '../battle/battle-economy.ts';
import type { BattleMatchmaker } from '../battle/battle-matchmaker.ts';
import { maxModeMrank, unitClassOfExpClass, unitClassOfTypeCode, type CraftRankEntry } from '../battle/battle-ranks.ts';
import type { BattleSessionStore } from '../battle/battle-session-store.ts';
import type { GameModes, OfferedGameMode } from '../game-modes/game-modes.ts';
import { crewSlotVehicleOfCountry, crewVehiclesOfCountry } from '../profile/profile-crews.ts';
import type { PlayerProfiles } from '../profile/player-profiles.ts';
import { battleLaunchNotify, type BattleLaunchNotify } from './battle-launch-notify.ts';
import type { MatchingRequestHandler } from './matching-requests.ts';
export interface BattleQueueDependencies {
readonly gameModes: GameModes;
readonly profiles: PlayerProfiles;
readonly matchmaker: BattleMatchmaker;
readonly sessions: BattleSessionStore;
readonly economy: BattleEconomy;
readonly notifyLaunch: (userId: string, payload: BattleLaunchNotify) => void;
}
export function battleQueueRequests(deps: BattleQueueDependencies): Array<[string, MatchingRequestHandler]> {
return [
['wtmm_static.calc_ranks', (request) => answerCalcRanks(request.params, deps.gameModes)],
['match.enqueue', (request, session) => handleEnqueue(request.params, session, deps)],
['match.leave_queue', (_request, session) => {
const userId = session.authenticatedUserId();
if (userId) deps.sessions.cancelPendingForUser(userId);
return {};
}],
['match.check_reconnect', () => ({})],
];
}
function answerCalcRanks(params: Readonly<Record<string, unknown>>, gameModes: GameModes): Record<string, unknown> {
const mode = typeof params.gameModeId === 'number' ? gameModes.byId(params.gameModeId) : undefined;
const players = Array.isArray(params.players) ? params.players : [];
const answer: Record<string, Array<{ mrank: number }>> = {};
for (const rawPlayer of players) {
if (!isRecord(rawPlayer) || typeof rawPlayer.name !== 'string' || !rawPlayer.name) continue;
const crafts = parsePlayerCrafts(rawPlayer.crafts);
const slot = typeof rawPlayer.slot === 'number' && Number.isInteger(rawPlayer.slot) ? rawPlayer.slot : -1;
const singleSlotCraft = mode?.declaration.multiSlot === false && slot >= 0 && slot < crafts.length
? crafts[slot]
: undefined;
const scopedCrafts = singleSlotCraft && singleSlotCraft.unitClass === mode?.declaration.requiredClass
? [singleSlotCraft]
: crafts;
const mrank = mode
? maxModeMrank(scopedCrafts, mode.declaration.requiredClass, mode.declaration.allowedClasses)
: scopedCrafts.reduce((max, craft) => Math.max(max, craft.mrank), 0);
answer[rawPlayer.name] = [{ mrank }];
}
return answer;
}
function handleEnqueue(
params: Readonly<Record<string, unknown>>,
session: { authenticatedUserId(): string | undefined; note(text: string): void },
deps: BattleQueueDependencies,
): Record<string, unknown> {
const userId = session.authenticatedUserId();
if (!userId) {
session.note('rejected: matching session is not authenticated');
return { error: 'AUTH_REQ_ERROR' };
}
const modes = resolveQueuedModes(params, deps.gameModes);
if (modes.length === 0) {
session.note('rejected: unknown game mode');
return { error: 'UNKNOWN_GAME_MODE' };
}
const playerEntry = extractPlayerEntry(params, userId);
if (!playerEntry) {
session.note('rejected: missing player country in match.enqueue');
return { error: 'BAD_PARAMS' };
}
const profile = deps.profiles.profileOf(userId);
const slotVehicles = crewVehiclesOfCountry(profile, playerEntry.country);
const selectedSlotVehicle = playerEntry.selectedSlot !== undefined
? crewSlotVehicleOfCountry(profile, playerEntry.country, playerEntry.selectedSlot)
: undefined;
const outcome = deps.matchmaker.enqueue({
userId,
mode: modes[0]!,
modes,
country: playerEntry.country,
slotVehicles,
...(selectedSlotVehicle !== undefined ? { selectedSlotVehicle } : {}),
bannedMissions: playerEntry.bannedMissions,
dislikedMissions: playerEntry.dislikedMissions,
});
if (!outcome.ok) {
session.note(`rejected: ${outcome.error}`);
return { error: outcome.error };
}
const { launch } = outcome;
session.note(`mode=${launch.modeName}, mission=${launch.missionName}, mrank=${launch.minMrank}..${launch.maxMrank}`);
const playerVehicles = new Set([
...slotVehicles,
...launch.extraBattleSlots.map((slot) => slot.unitName),
]);
const awards = deps.economy.bannerParams(playerVehicles, economyDifficulty(modes[0]!.declaration.difficulty));
setImmediate(() => {
if (!deps.sessions.isPending(userId, launch.sessionId)) return;
deps.sessions.clearPending(userId, launch.sessionId);
deps.notifyLaunch(userId, battleLaunchNotify(launch, awards, deps.economy.missionScores()));
});
return {};
}
function parsePlayerCrafts(rawCrafts: unknown): CraftRankEntry[] {
if (!Array.isArray(rawCrafts)) return [];
return rawCrafts.flatMap((craft): CraftRankEntry[] => {
if (!isRecord(craft) || typeof craft.mrank !== 'number' || !Number.isFinite(craft.mrank)) return [];
const fromExp = typeof craft.craftType === 'string' ? unitClassOfExpClass(craft.craftType) : undefined;
const fromCode = typeof craft.unitTypeCode === 'number' ? unitClassOfTypeCode(craft.unitTypeCode) : undefined;
return [{ unitClass: fromExp ?? fromCode, mrank: Math.max(0, Math.trunc(craft.mrank)) }];
});
}
/**
* Resolve every candidate `OfferedGameMode` allowed by `match.enqueue` (`scripts/queue/queue/queueevent.nut:191-207`):
* - `game_mode_id`: explicit single mode ID;
* - `game_modes_list`: filtered IDs after applying `onlyTags` / `excludedTags`;
* - `mode`: sent when `onlyTags` and `excludedTags` are both empty (classic mode plus every
* sub-mode of that `economicName` is enabled; server-side BR/craft guards still apply).
*/
function resolveQueuedModes(params: Readonly<Record<string, unknown>>, gameModes: GameModes): OfferedGameMode[] {
if (typeof params.game_mode_id === 'number') {
const found = gameModes.byId(params.game_mode_id);
return found ? [found] : [];
}
if (Array.isArray(params.game_modes_list)) {
return params.game_modes_list.flatMap((id) => (typeof id === 'number' ? gameModes.byId(id) ?? [] : []));
}
if (typeof params.mode === 'string' && params.mode) {
const primary = gameModes.byName(params.mode);
if (!primary) return [];
const family = gameModes.byEconomicName(primary.declaration.economicName);
return family.length > 0 ? [...family] : [primary];
}
return [];
}
function extractPlayerEntry(
params: Readonly<Record<string, unknown>>,
userId: string,
): {
readonly country: string;
readonly selectedSlot?: number;
readonly bannedMissions: Set<string>;
readonly dislikedMissions: Set<string>;
} | undefined {
const players = isRecord(params.players) ? params.players : undefined;
const entry = players && isRecord(players[userId]) ? players[userId] : undefined;
const rawCountry = typeof entry?.country === 'string' ? entry.country.trim() : '';
if (!rawCountry) return undefined;
const country = rawCountry.startsWith('country_') ? rawCountry : `country_${rawCountry}`;
const slots = isRecord(entry?.slots) ? entry.slots : undefined;
const rawSlot = slots?.[country] ?? slots?.[rawCountry];
const selectedSlot = typeof rawSlot === 'number' && Number.isInteger(rawSlot) && rawSlot >= 0 ? rawSlot : undefined;
return {
country,
...(selectedSlot !== undefined ? { selectedSlot } : {}),
bannedMissions: toStringSet(entry?.bannedMissions),
dislikedMissions: toStringSet(entry?.dislikedMissions),
};
}
function toStringSet(raw: unknown): Set<string> {
if (!Array.isArray(raw)) return new Set();
return new Set(raw.filter((item): item is string => typeof item === 'string' && item.length > 0));
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+19
View File
@@ -0,0 +1,19 @@
/**
* wtmm_static.fetch_clusters_list: the list of server regions ("clusters") the player can
* pick for matchmaking.
*
* The stock UI script asks for it right after the matching sign-in
* (gui.vromfs.bin scripts/onlineInfo/clustersManagement.nut, updateClustersList): the answer
* must carry a non-empty array "clusters" of cluster names, otherwise the script retries and,
* after MAX_FETCH_RETRIES (5), signs the player out — the endless re-login loop seen in lab
* run 6. The names are the ones the stock scripts know (scripts/onlineInfo/defaultClusters.nut
* maps every country to one of them and preselects it; the UI shows loc "cluster/<name>").
*
* Everything runs on the player's machine, so the region has no effect on where anything
* connects; the list only has to be valid for the stock UI.
*/
import type { MatchingRequestHandler } from './matching-requests.ts';
const CLUSTERS = ['EU', 'NA', 'CIS', 'SA'] as const;
export const fetchClustersList: MatchingRequestHandler = () => ({ clusters: [...CLUSTERS] });
@@ -0,0 +1,27 @@
/**
* The game-mode requests of the matching server (gui.vromfs.bin
* scripts/matching/matchingGameModes.nut, docs/implementation notes):
*
* - wtmm_static.fetch_game_modes_digest {timeout}: answered with "modes", the list of
* game-mode ids. After login the script asks for it, then fetches the modes it names.
* - match.fetch_game_modes_info {byId: [ids], asString: true, timeout}: the script asks for
* at most 5 ids at a time and reads "modes_str", a JSON array of mode definitions
* (game-modes/mode-definition.ts). local verification logged exactly these parameters.
*
* Five failed digest fetches sign the player out, so both answers must always be well formed.
*/
import type { GameModes } from '../game-modes/game-modes.ts';
import type { MatchingRequestHandler } from './matching-requests.ts';
export function gameModeRequests(gameModes: GameModes): [string, MatchingRequestHandler][] {
return [
['wtmm_static.fetch_game_modes_digest', () => ({ modes: gameModes.ids() })],
['match.fetch_game_modes_info', (request, session) => {
const { byId, asString } = request.params;
const ids = Array.isArray(byId) ? byId.filter((id): id is number => typeof id === 'number') : [];
const modes = gameModes.definitions(ids);
session.note(`${modes.length} of ${ids.length} requested modes`);
return asString === false ? { modes } : { modes_str: JSON.stringify(modes) };
}],
];
}
+22
View File
@@ -0,0 +1,22 @@
/**
* Static matching-server feature flags (`wtmm_static.fetch_game_settings`,
* `scripts/matching/matchinggamesettings.nut` -> `scripts/user/matchingfeature.nut`).
*
* Stock `matchingfeature.nut` defaults `hasChat`, `hasBattleChatModeAll`, and
* `hasBattleChatModeTeam` to `false` until `wtmm_static.fetch_game_settings` returns
* `features.<key> = true`. Enabling them lets DaRG `hudLogs.nut` and the built-in
* LocalMP host chat dispatcher (`aces.exe` 0x154f540 -> 0x133ba10) accept in-battle
* All/Team/Squad chat and quick-radio voice messages.
*/
import type { MatchingRequestHandler } from './matching-requests.ts';
export const fetchGameSettings: MatchingRequestHandler = () => ({
features: {
hasChat: true,
hasMenuChat: true,
hasBattleChatModeAll: true,
hasBattleChatModeTeam: true,
hasBattleChatModeSquad: true,
hasMenuChatMPlobby: true,
},
});
+61
View File
@@ -0,0 +1,61 @@
/**
* LZ4 block format (lz4.org, "LZ4 Block Format Description"), as the matching client uses it
* for message payloads (aces.exe 2.61.0.37 calls LZ4_decompress_safe at 0x45afe70).
*
* Decoding is complete. Encoding writes a block of literals only: valid LZ4 that any decoder
* reads, just not smaller than the input. Messages to the client are small; compression
* buys nothing on a local connection.
*/
export function decodeLz4Block(block: Uint8Array, decodedSize: number): Uint8Array {
const output = new Uint8Array(decodedSize);
let at = 0;
let out = 0;
while (at < block.length) {
const token = block[at++]!;
let literalLength = token >> 4;
if (literalLength === 15) literalLength += readLengthExtension();
if (out + literalLength > decodedSize || at + literalLength > block.length) throw new Error('lz4: literals run past the end');
output.set(block.subarray(at, at + literalLength), out);
at += literalLength;
out += literalLength;
if (at >= block.length) break; // the last sequence has literals only
const offset = block[at]! | (block[at + 1]! << 8);
at += 2;
if (offset === 0 || offset > out) throw new Error('lz4: bad match offset');
let matchLength = (token & 15) + 4;
if ((token & 15) === 15) matchLength += readLengthExtension();
if (out + matchLength > decodedSize) throw new Error('lz4: match runs past the end');
for (let i = 0; i < matchLength; i++, out++) output[out] = output[out - offset]!; // overlapping copies are allowed
}
if (out !== decodedSize) throw new Error(`lz4: decoded ${out} bytes, expected ${decodedSize}`);
return output;
function readLengthExtension(): number {
let total = 0;
let byte: number;
do {
if (at >= block.length) throw new Error('lz4: truncated length');
byte = block[at++]!;
total += byte;
} while (byte === 255);
return total;
}
}
export function encodeLz4BlockLiterals(data: Uint8Array): Uint8Array {
const extension: number[] = [];
if (data.length >= 15) {
let rest = data.length - 15;
while (rest >= 255) {
extension.push(255);
rest -= 255;
}
extension.push(rest);
}
const block = new Uint8Array(1 + extension.length + data.length);
block[0] = Math.min(data.length, 15) << 4;
block.set(extension, 1);
block.set(data, 1 + extension.length);
return block;
}
@@ -0,0 +1,72 @@
/**
* Packets of the matching server's TCP protocol.
*
* Source: aces.exe 2.61.0.37, net::TCPClientImpl::readSocketData (0x55cadd0) and
* the message unpacking at 0x44f3550. A packet is a 9-byte header and an LZ4 block:
*
* byte 0 packet type (the client sends 1)
* bytes 1..4 packet size including the header, little endian
* bytes 5..8 size of the decoded payload, little endian
* bytes 9.. LZ4 block of the payload
*
* The client rejects packets of 1 MiB or more ("packet too large").
*/
import { decodeLz4Block, encodeLz4BlockLiterals } from './lz4-block.ts';
const HEADER_SIZE = 9;
const MAX_PACKET_SIZE = 0x100000;
export const PACKET_TYPE = 1;
export interface MatchingPacket {
readonly type: number;
readonly payload: Uint8Array;
}
/**
* Collects bytes from one connection and hands out whole packets one at a time, so the
* caller can stop after any packet (when the connection switches to encryption) and take
* the bytes that follow it.
*/
export class PacketReader {
#pending: Buffer = Buffer.alloc(0);
append(chunk: Buffer): void {
this.#pending = this.#pending.length === 0 ? chunk : Buffer.concat([this.#pending, chunk]);
}
/** The next complete packet, or undefined when more bytes are needed. */
next(): MatchingPacket | undefined {
if (this.#pending.length < HEADER_SIZE) return undefined;
const size = this.#pending.readUInt32LE(1);
if (size < HEADER_SIZE || size >= MAX_PACKET_SIZE) throw new Error(`matching: bad packet size ${size}`);
if (this.#pending.length < size) return undefined;
const decodedSize = this.#pending.readUInt32LE(5);
const payload = decodeLz4Block(this.#pending.subarray(HEADER_SIZE, size), decodedSize);
const packet = { type: this.#pending[0]!, payload };
this.#pending = this.#pending.subarray(size);
return packet;
}
/** Remove and return the bytes not yet read as packets. */
takeRest(): Buffer {
const rest = this.#pending;
this.#pending = Buffer.alloc(0);
return rest;
}
}
export function encodePacket(payload: Uint8Array): Buffer {
const block = encodeLz4BlockLiterals(payload);
const packet = Buffer.alloc(HEADER_SIZE + block.length);
packet[0] = PACKET_TYPE;
packet.writeUInt32LE(packet.length, 1);
packet.writeUInt32LE(payload.length, 5);
packet.set(block, HEADER_SIZE);
if (packet.length >= MAX_PACKET_SIZE) throw new Error(`matching: packet of ${packet.length} bytes is too large for the client`);
return packet;
}
/** The first byte of a connection tells the matching protocol from HTTP and TLS. */
export function startsMatchingPacket(firstBytes: Uint8Array): boolean {
return firstBytes[0] === PACKET_TYPE;
}
@@ -0,0 +1,103 @@
/**
* Messages inside matching packets: one byte naming the kind of message, then JSON.
*
* Source: aces.exe 2.61.0.37.
* - Requests from the client: kind 0x1a; JSON {"data": {"data": <parameters>, "name": <request
* name>}, "id": <request number>, "type": 52} (envelope built at 0x44ea0e0, request body at
* 0x44e9bc0, kind passed to the sender at 0x44ea3b9).
* - The client sorts what it receives by kind (matching::ClientImpl::handleServerPacket,
* 0x44e7540): kind 0x1b goes to the answer queue, handled at 0x44ec4b0, which finds the
* pending request by "id", treats a missing or zero "error" as success and passes "data" on
* (the result itself is inside it, see answerTo);
* every other kind is a server notification (0x44eab40). Every message needs a "type",
* otherwise the client drops it ("bad message. type not set").
*/
export const MessageKind = {
Request: 0x1a,
Answer: 0x1b,
} as const;
/** Value of "type" in the client's requests (0x44e9fcd). */
export const REQUEST_TYPE = 52;
/** Value of "type" in server push notifications (0x44eaba6 -> 0x44ec1ba). */
export const NOTIFY_TYPE = 49;
export interface MatchingMessage {
readonly kind: number;
readonly json: Record<string, unknown>;
}
export function decodeMessage(payload: Uint8Array): MatchingMessage {
if (payload.length === 0) throw new Error('matching: empty message');
const text = Buffer.from(payload.subarray(1)).toString('utf8');
const json: unknown = JSON.parse(text);
if (typeof json !== 'object' || json === null || Array.isArray(json)) throw new Error('matching: message is not a JSON object');
return { kind: payload[0]!, json: json as Record<string, unknown> };
}
export function encodeMessage(message: MatchingMessage): Uint8Array {
const text = Buffer.from(JSON.stringify(message.json), 'utf8');
const payload = new Uint8Array(1 + text.length);
payload[0] = message.kind;
payload.set(text, 1);
return payload;
}
export interface MatchingRequest {
readonly id: number;
readonly type: number;
readonly name: string;
readonly params: Record<string, unknown>;
}
/**
* Value of "type" in the client's keep-alive: about 30 s after the last traffic the client
* sends {"id", "type": 100} through the same request sender as named requests (0x44ea0e0,
* called at 0x44edf0b) with its own completion callback (0x44f21d0). The answer handler
* finds it by "id" like any request; status 0 logs "got CLN_PING response", and no answer
* within 15 s closes the connection ("CLN_PING got no response").
*/
export const PING_TYPE = 100;
/** The ping's id, or undefined when the message is not a keep-alive. */
export function asPing(message: MatchingMessage): number | undefined {
const { id, type } = message.json;
return message.kind === MessageKind.Request && type === PING_TYPE && typeof id === 'number' ? id : undefined;
}
export function pingAnswer(id: number): MatchingMessage {
return { kind: MessageKind.Answer, json: { id, type: PING_TYPE } };
}
/** Undefined when the message is not a request the client expects an answer to. */
export function asRequest(message: MatchingMessage): MatchingRequest | undefined {
if (message.kind !== MessageKind.Request) return undefined;
const { id, type, data } = message.json;
if (typeof id !== 'number' || typeof data !== 'object' || data === null) return undefined;
const { name, data: params } = data as Record<string, unknown>;
return {
id,
type: typeof type === 'number' ? type : REQUEST_TYPE,
name: typeof name === 'string' ? name : '',
params: typeof params === 'object' && params !== null ? params as Record<string, unknown> : {},
};
}
/**
* The answer's result sits one level deeper than "data", mirroring the request envelope:
* {"id", "type", "data": {"data": <result>}}. The answer handler (0x44ec4b0) passes the
* message's "data" to the request's completion wrapper (0x44f1c00, set by the request sender
* 0x44e9bc0), which logs "got response on …" and hands that object's own "data" to the
* caller; for script requests (matching_call, 0x46e1e70) that is the table the UI script
* receives, with "error" added (0x46e5ee0). local verification: a result placed directly in "data"
* reached the script as an empty table.
*/
export function answerTo(request: MatchingRequest, result: Record<string, unknown>): MatchingMessage {
return { kind: MessageKind.Answer, json: { id: request.id, type: request.type, data: { data: result } } };
}
/** Server notification (any packet kind != 0x1b, type 49; aces.exe 0x44eaba6..0x44ec1d5). */
export function notifyMessage(name: string, data: Record<string, unknown>): MatchingMessage {
return { kind: MessageKind.Request, json: { type: NOTIFY_TYPE, data: { name, data } } };
}
@@ -0,0 +1,76 @@
/**
* What the local matching server answers, by request name.
*
* mlogin.login: the client's sign-in to the matching server (built at aces.exe 2.61.0.37
* 0x44e8160: auth_jwt_enc, login (sealed session key, session-crypto/session-key.ts),
* user_id, name, protocol, caps, version, platform). Its result handler (0x44f1850) treats
* error 0 as success, marks the client signed in and passes "data" to the online layer.
* Nothing local checks the credentials (single-player machine); the session key is needed
* because the client encrypts everything after this request.
*/
import type { AccountStore } from '../accounts/account-store.ts';
import type { GameModes } from '../game-modes/game-modes.ts';
import { battleLiveRequests, type BattleLiveDependencies } from './battle-live-requests.ts';
import { battleQueueRequests, type BattleQueueDependencies } from './battle-queue-requests.ts';
import { fetchClustersList } from './cluster-list.ts';
import { gameModeRequests } from './game-modes-requests.ts';
import { fetchGameSettings } from './game-settings.ts';
import type { MatchingRequest } from './matching-message.ts';
import { jwtDecryptsWith, unwrapSessionKey } from './session-crypto/session-key.ts';
/** What a request handler may do to its connection besides answering. */
export interface MatchingSessionControl {
/** Encrypt this connection from the answer to the current request on. */
useSessionKey(key: Buffer): void;
/** Bind this matching connection to a verified local account. */
authenticateUser(userId: string): void;
/** The local account bound during `mlogin.login`, or undefined when unauthenticated. */
authenticatedUserId(): string | undefined;
/** Add a line to the traffic log entry of the current request. */
note(text: string): void;
}
export type MatchingRequestHandler = (request: MatchingRequest, session: MatchingSessionControl) => Record<string, unknown>;
export type MatchingRequestTable = ReadonlyMap<string, MatchingRequestHandler>;
export interface MatchingRules {
readonly gameModes: GameModes;
readonly accounts?: AccountStore;
readonly battle?: BattleQueueDependencies;
readonly battleLive?: BattleLiveDependencies;
}
export function matchingRequests({ gameModes, accounts, battle, battleLive }: MatchingRules): MatchingRequestTable {
return new Map<string, MatchingRequestHandler>([
['mlogin.login', (request, session) => signIn(request, session, accounts)],
['wtmm_static.fetch_clusters_list', fetchClustersList],
['wtmm_static.fetch_game_settings', fetchGameSettings],
['mrooms.leave_room', () => ({})],
...gameModeRequests(gameModes),
...(battle ? battleQueueRequests(battle) : []),
...(battleLive ? battleLiveRequests(battleLive) : []),
]);
}
function signIn(request: MatchingRequest, session: MatchingSessionControl, accounts?: AccountStore): Record<string, unknown> {
const { login, auth_jwt_enc: authJwtEnc, user_id: rawUserId } = request.params;
if (typeof login === 'string') {
const { sessionKey, fields } = unwrapSessionKey(login);
const verified = typeof authJwtEnc === 'string' && jwtDecryptsWith(sessionKey, authJwtEnc);
session.note(`session key unwrapped (sealed fields: ${fields.join(', ')}); auth_jwt_enc ${verified ? 'decrypts with it' : 'does NOT decrypt with it'}`);
session.useSessionKey(sessionKey);
} else {
session.note('no sealed login field: the connection stays unencrypted');
}
const userIdText = typeof rawUserId === 'number' && Number.isSafeInteger(rawUserId)
? String(rawUserId)
: typeof rawUserId === 'string' ? rawUserId.trim() : '';
const account = userIdText && accounts ? accounts.byUserId(userIdText) : undefined;
if (account) {
session.authenticateUser(account.userId);
session.note(`authenticated user ${account.userId} (${account.nick})`);
}
return {};
}
@@ -0,0 +1,155 @@
/**
* The local matching server: one session per TCP connection the client opens to the
* matching address (network.blk, pointed at the local server's port by the build).
*
* A connection starts unencrypted; the client sends mlogin.login in clear packets and from
* then on encrypts both directions with the session key sealed in that request
* (session-crypto/). The answer to mlogin.login is already encrypted.
*
* Every request gets an answer. A request with no handler yet is answered with success and
* empty data and marked unhandled in the traffic log, so the client carries on and shows
* what it asks for next (the same policy as the char service). Keep-alive pings are
* answered with their id (matching-message.ts). Other messages are only logged.
*/
import type { Socket } from 'node:net';
import type { TrafficLog } from '../traffic-log/traffic-log.ts';
import { encodePacket, PacketReader } from './matching-frame.ts';
import { answerTo, asPing, asRequest, decodeMessage, encodeMessage, notifyMessage, pingAnswer, type MatchingMessage } from './matching-message.ts';
import type { MatchingRequestTable, MatchingSessionControl } from './matching-requests.ts';
import { messageLogText } from './message-redaction.ts';
import { EnvelopeReader, sealEnvelope } from './session-crypto/encrypted-envelope.ts';
export class MatchingService {
readonly #requests: MatchingRequestTable;
readonly #log: TrafficLog;
readonly #sessions = new Set<MatchingSession>();
constructor(requests: MatchingRequestTable, log: TrafficLog) {
this.#requests = requests;
this.#log = log;
}
accept(socket: Socket, connectionId: number): void {
const session = new MatchingSession(socket, connectionId, this.#requests, this.#log);
this.#sessions.add(session);
socket.on('close', () => this.#sessions.delete(session));
socket.on('data', (chunk: Buffer) => {
try {
session.receive(chunk);
} catch (error) {
this.#log.matchingError(connectionId, error instanceof Error ? error.message : String(error));
socket.destroy();
}
});
socket.on('error', () => socket.destroy());
}
/** Push a matching notification (such as mrpc.generic_notify) to every active client session. */
broadcastNotify(name: string, data: Record<string, unknown>): void {
const message = notifyMessage(name, data);
for (const session of this.#sessions) session.pushNotify(message, name);
}
/** Push a matching notification only to active sessions authenticated as `userId`. */
notifyUser(userId: string, name: string, data: Record<string, unknown>): boolean {
const message = notifyMessage(name, data);
let sent = false;
for (const session of this.#sessions) {
if (session.userId() === userId && session.pushNotify(message, name)) sent = true;
}
return sent;
}
}
class MatchingSession {
readonly #socket: Socket;
readonly #connectionId: number;
readonly #requests: MatchingRequestTable;
readonly #log: TrafficLog;
readonly #packets = new PacketReader();
#sessionKey: Buffer | undefined;
#envelopes: EnvelopeReader | undefined;
#userId: string | undefined;
constructor(socket: Socket, connectionId: number, requests: MatchingRequestTable, log: TrafficLog) {
this.#socket = socket;
this.#connectionId = connectionId;
this.#requests = requests;
this.#log = log;
}
userId(): string | undefined {
return this.#userId;
}
receive(chunk: Buffer): void {
if (this.#envelopes) {
for (const plaintext of this.#envelopes.push(chunk)) this.#readPackets(plaintext);
return;
}
this.#readPackets(chunk);
// The request just handled switched the connection to encryption: what followed it in
// the same read is already encrypted.
if (this.#envelopes) {
const rest = this.#packets.takeRest();
if (rest.length) this.receive(rest);
}
}
#readPackets(plaintext: Buffer): void {
this.#packets.append(plaintext);
const wasEncrypted = this.#envelopes !== undefined;
for (let packet = this.#packets.next(); packet; packet = this.#packets.next()) {
this.#handle(decodeMessage(packet.payload));
if (!wasEncrypted && this.#envelopes) return;
}
}
#handle(message: MatchingMessage): void {
const pingId = asPing(message);
if (pingId !== undefined) {
this.#record('in', message, `ping #${pingId}`, false);
this.#send(pingAnswer(pingId));
return;
}
const request = asRequest(message);
if (!request) {
this.#record('in', message, 'not a request', false);
return;
}
const handler = this.#requests.get(request.name);
const notes: string[] = [];
const control: MatchingSessionControl = {
useSessionKey: (key) => {
this.#sessionKey = key;
this.#envelopes = new EnvelopeReader(key);
},
authenticateUser: (userId) => {
this.#userId = userId;
},
authenticatedUserId: () => this.#userId,
note: (text) => notes.push(text),
};
const data = handler ? handler(request, control) : {};
this.#record('in', message, `${request.name} #${request.id}${notes.length ? ` (${notes.join('; ')})` : ''}`, !handler);
const answer = answerTo(request, data);
this.#record('out', answer, `answer ${request.name} #${request.id}${this.#sessionKey ? ' (encrypted)' : ''}`, false);
this.#send(answer);
}
#send(message: MatchingMessage): void {
const packet = encodePacket(encodeMessage(message));
this.#socket.write(this.#sessionKey ? sealEnvelope(this.#sessionKey, packet) : packet);
}
pushNotify(message: MatchingMessage, summaryName: string): boolean {
if (!this.#sessionKey || this.#socket.destroyed) return false;
this.#record('out', message, `notify ${summaryName} (encrypted)`, false);
this.#send(message);
return true;
}
#record(direction: 'in' | 'out', message: MatchingMessage, summary: string, unhandled: boolean): void {
this.#log.matchingMessage(this.#connectionId, { direction, kind: message.kind, summary, unhandled, text: messageLogText(message) });
}
}
@@ -0,0 +1,11 @@
/**
* Readable text of a matching message for the traffic log, with sign-in secrets masked
* (the client masks the same fields in its own log: aces.exe 2.61.0.37 0x44e77c0).
*/
import type { MatchingMessage } from './matching-message.ts';
const SECRET_KEYS = new Set(['auth_jwt', 'auth_jwt_enc', 'session_key_evp', 'chard_token', 'login']);
export function messageLogText(message: MatchingMessage): string {
return JSON.stringify(message.json, (key, value: unknown) => (SECRET_KEYS.has(key) && typeof value === 'string' ? '<hidden>' : value), 2);
}
@@ -0,0 +1,53 @@
/**
* Encrypted matching traffic, used in both directions once mlogin.login has been sent
* (the client installs the session key for sending and receiving at aces.exe 2.61.0.37
* 0x55cc3c0).
*
* Each envelope (send: 0x55ccb0a, receive: 0x55cb125..0x55cb4b4):
* bytes 0..3 ciphertext length, little endian
* bytes 4..15 IV material; the IV is these 16 header bytes with bytes 0..3 set to zero
* bytes 16.. AES-128-CBC ciphertext with PKCS#7 padding (cipher NID 419, no
* EVP_CIPHER_CTX_set_padding call)
* The plaintext is ordinary matching packets (matching-frame.ts).
*/
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
const HEADER_BYTES = 16;
const MAX_CIPHERTEXT_BYTES = 0x100000;
export class EnvelopeReader {
readonly #key: Buffer;
#pending: Buffer = Buffer.alloc(0);
constructor(sessionKey: Buffer) {
this.#key = sessionKey;
}
/** Decrypted bytes of every complete envelope received so far. */
push(chunk: Buffer): Buffer[] {
this.#pending = this.#pending.length === 0 ? chunk : Buffer.concat([this.#pending, chunk]);
const plaintexts: Buffer[] = [];
while (this.#pending.length >= HEADER_BYTES) {
const length = this.#pending.readUInt32LE(0);
if (length === 0 || length >= MAX_CIPHERTEXT_BYTES) throw new Error(`matching: bad encrypted envelope length ${length}`);
if (this.#pending.length < HEADER_BYTES + length) break;
const iv = Buffer.from(this.#pending.subarray(0, HEADER_BYTES));
iv.writeUInt32LE(0, 0);
const decipher = createDecipheriv('aes-128-cbc', this.#key, iv);
const ciphertext = this.#pending.subarray(HEADER_BYTES, HEADER_BYTES + length);
plaintexts.push(Buffer.concat([decipher.update(ciphertext), decipher.final()]));
this.#pending = this.#pending.subarray(HEADER_BYTES + length);
}
return plaintexts;
}
}
export function sealEnvelope(sessionKey: Buffer, plaintext: Uint8Array): Buffer {
const header = Buffer.alloc(HEADER_BYTES);
randomBytes(HEADER_BYTES - 4).copy(header, 4);
const iv = Buffer.from(header); // bytes 0..3 are still zero
const cipher = createCipheriv('aes-128-cbc', sessionKey, iv);
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
header.writeUInt32LE(ciphertext.length, 0);
return Buffer.concat([header, ciphertext]);
}
@@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCw+AP/8LWelCG3
I6ls7gCl0GwklK0QMdql8z1KUp+GO5pfEmDuCf2I2RgNf2oKKNcQf2K78FWAjZ3Z
GYcjV8KGYSdG1i8eIGBhiEHyWQyvRMcNaBbtToSZKPI9nXDa5m5QoO6qSXyuSye9
5PT4/PmAArVLJzNC167TGgeGz9C4831Eb+624Jar+Hqo+d0+H5VCszCvWfzx5fhY
UMwhFHTlejPRIs/WrmbY+ucrWNDxqxJO9T91NsfMxf5djJT2LkZJfZu44+6DxAPV
SYQlbGiNJ3xH3OzxhcByeLchsXKAOU28/ULevV+O2DWipphFfHg8NMZry+02mbjl
3te1PIpZAgMBAAECggEALQQ6CD4UBS3LUcnpjEMSuRtGlxuW1nrIEtTIL4LK/5tj
znFfZM33x3rp6m0R7VmsM48j74jYRyY/E/2xaaUmX4aRNiy/uZskyUqe8+YBGwiU
1e03f9AsXMWUsWW+UoCxaSM28uxUogWOK3j1c+zuDskhkud627L/zsVdSsbMYm9p
S8r0wSkZsTBvstuC2ZweSKFkg4+kRsr85KVwDhMSxzcRIMdkwnbty0Cu1ZvEaYYC
KYu90r7sh5R+WrxqyT/DWVjhDDMBCtUfXKORRbsBumyqkXV6IkR7kYHC2fZnUzYy
1qBAqwLslfQLcdYTYX7O2aWLTi8mxKG5m8LRMdhRnQKBgQDkejvssNrzbuKcVDow
ckpnpJMmb16MIaUQ1Y1balhVTgcLx62y26CB45+OLafHrgE6W4eRyaUWhbsuBfB1
x0LvnQH9pVVRcQy3OJr04fRTlq1kuyyzYXhLGKlgvd9Q44PLpzuGBs0YwCxw1cnj
+nal/+T1oYbDolvv+vflfKim8wKBgQDGSVzFCwPT8YQ73Cef0YuvnDH9LsQF+Z5Z
uBMM6EGJ5ZVlICFacAaYptGiNDYkSVLHomGCwg3fTpzGEMauPrZSCNiD6JcWHJZf
fPz4AJbhBaxeH7TC2W3xVdu9V0F1O0RhMfLy/BfHRw1pV3kKWs5J4fNzLx8Ui29N
5KVMx9N0gwKBgQDUPC+aKJba9rAOY7dB9YjkSd5fH6kGJuK8hoMu3dR8OWUWLkBO
GvI4dgdq/UITnLGLUibW6Ccwir1bfSznW1f0WTbWNVTRuGAFetGGlLZvR1J+ddiK
MQqbR6dfNEFTVGTDMu96CqtOSIV/szg9TBYXEWPQQGF9LT6V592LEYdgvQKBgG3x
a4DN1LeFqJ5QOaBB3cPnRUhuz73IZGa2y8lSVlSReb5yjEvK5b1qcb4QWRzRkxai
EJMh6fMxcXfZAXDH0Ou3f+XT50IZY79aXCFeoknujV47Ek0fpfg0dPyNDvxjekyy
F1VnNgAGg4cvOyvkoZERuZzaOc94aKS17HmgKrzlAoGAPzruAXPedSlQ4/xoxdDa
mPnb8UVYG2CRKwvnkEcQg/TGiVK1ppKStT0MCLLWBmLuvjcYXo1DwHs3vrC9jijA
Aaldyl7aQROsFJtYTRswDE8XFujMOPtfAn3KFboxaqqnvIHWgNo5YZRggzQVrSNU
NzZytBCda0PuVYQ0exhIP1I=
-----END PRIVATE KEY-----
@@ -0,0 +1,78 @@
/**
* The matching connection's session key, as the client sends it in mlogin.login.
*
* Source: aces.exe 2.61.0.37, mlogin.login assembly (0x44e8160):
* - the client picks a random 16-byte session key;
* - "session_key_evp" (base64 of the key) and other fields such as "chard_token" go into a
* small JSON object, which is encrypted with the matching server's RSA public key
* (PKCS#1 v1.5 padding, 0x44e9518) and sent base64-encoded as the request's "login" field;
* - "auth_jwt_enc" is the sign-in JWT under AES-128-GCM with the session key: base64 of
* 12-byte nonce, ciphertext and 16-byte tag (0x44e8d3c..0x44e8e5d).
*
* The exe patch online/matching-server-public-key puts the local server's public key in
* place of Gaijin's; local-matching-server.key.pem is the matching private key. It protects
* nothing (both ends run on the player's machine) and is fixed so the patch bytes are fixed.
*/
import { constants, createDecipheriv, createPrivateKey, privateDecrypt, type KeyObject } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
const SESSION_KEY_BYTES = 16;
const GCM_NONCE_BYTES = 12;
const GCM_TAG_BYTES = 16;
let serverKey: KeyObject | undefined;
function localServerKey(): KeyObject {
serverKey ??= createPrivateKey(readFileSync(join(import.meta.dirname, 'local-matching-server.key.pem')));
return serverKey;
}
export interface UnwrappedLogin {
readonly sessionKey: Buffer;
/** The decrypted JSON's field names, for the traffic log (values stay private). */
readonly fields: readonly string[];
}
/** Decrypt the "login" field of mlogin.login and read the session key from it. */
export function unwrapSessionKey(loginField: string): UnwrappedLogin {
const sealed = Buffer.from(loginField, 'base64');
// PKCS#1 v1.5 padding is removed here rather than by OpenSSL: Node refuses that padding
// for private-key decryption (CVE-2023-46809), which matters only for servers exposed to
// attackers, not for a local server talking to its own client.
const padded = privateDecrypt({ key: localServerKey(), padding: constants.RSA_NO_PADDING }, sealed);
const text = stripPkcs1Type2(padded).toString('utf8');
const inner: unknown = JSON.parse(text);
if (typeof inner !== 'object' || inner === null) throw new Error('matching login: sealed content is not a JSON object');
const encoded = (inner as Record<string, unknown>).session_key_evp;
if (typeof encoded !== 'string') throw new Error('matching login: no session_key_evp in the sealed content');
const sessionKey = Buffer.from(encoded, 'base64');
if (sessionKey.length !== SESSION_KEY_BYTES) throw new Error(`matching login: session key is ${sessionKey.length} bytes, expected ${SESSION_KEY_BYTES}`);
return { sessionKey, fields: Object.keys(inner) };
}
/** True when "auth_jwt_enc" decrypts with the session key, i.e. the key was read correctly. */
export function jwtDecryptsWith(sessionKey: Buffer, authJwtEnc: string): boolean {
const sealed = Buffer.from(authJwtEnc, 'base64');
if (sealed.length < GCM_NONCE_BYTES + GCM_TAG_BYTES) return false;
const nonce = sealed.subarray(0, GCM_NONCE_BYTES);
const tag = sealed.subarray(sealed.length - GCM_TAG_BYTES);
const body = sealed.subarray(GCM_NONCE_BYTES, sealed.length - GCM_TAG_BYTES);
try {
const decipher = createDecipheriv('aes-128-gcm', sessionKey, nonce);
decipher.setAuthTag(tag);
decipher.update(body);
decipher.final();
return true;
} catch {
return false;
}
}
/** RSAES-PKCS1-v1_5 decoding (RFC 8017 7.2.2): 00 02 <at least 8 nonzero bytes> 00 <message>. */
function stripPkcs1Type2(block: Buffer): Buffer {
if (block[0] !== 0x00 || block[1] !== 0x02) throw new Error('matching login: sealed block has no PKCS#1 v1.5 encryption padding (wrong key?)');
const separator = block.indexOf(0x00, 2);
if (separator < 10) throw new Error('matching login: malformed PKCS#1 v1.5 padding');
return block.subarray(separator + 1);
}