fix(server): persist squadrons and align inventory wire formats

Read squadron action parameters from the request headers and persist
squadron state on profile refresh. Use floating-point trophy weights
to match the client probability display and assign unique log IDs
when opening multiple chests.

Tighten shop, marketplace, squadron, and cloud settings validation.
Move PBBD and inventory encoding into the protocol modules and share
CSV reading. Update the research and acceptance instructions.

Type checking and all eight executable patch checks passed.
In-game acceptance is pending.
This commit is contained in:
N0VAN0M4LY committed 2026-11-25 09:10:09 +08:00
1 parent b68f321b84
commit 29e5cf2bd8
40 files changed
+1347 -1248

No files matched your search

@@ -1,212 +0,0 @@
/**
* Wire codecs for War Thunder's cloud settings subsystem (`online_storage` / `generalBlk`,
* implementation notes; aces.exe 2.61.0.37 at 0x4662a70..0x466b2ec and 0x41537d0..0x4154020).
*/
import { createHash } from 'node:crypto';
import { gunzipSync, inflateSync, zstdDecompressSync } from 'node:zlib';
import {
decodeBlk,
emptyBlock,
encodeBlk,
findBlock,
findParam,
setParam,
type BlkBlock,
} from '@wto/blk';
import { unpackMarked } from '../char/compression-marker.ts';
/**
* The three GeneralBlk types accepted by `PlayerProfile::applyGeneralBlk` (0xf5afb0) and
* `PlayerProfile::storeGeneralBlk` (0xf5b080).
*/
export const GENERAL_BLK_TYPES = [
'GBT_GENERAL_STORAGE',
'GBT_GENERAL_SETTINGS',
'GBT_GENERAL_MACHINE_SETTINGS',
] as const;
/**
* Compression methods advertised in `cln_get_meta_blk`'s `compressionSupported`. Put `zstd`
* first so `online_storage::Context::selectCompression` (0x4665de1) selects pure Zstandard
* frames (0x3372ca0), which Node's built-in `node:zlib` unpacks directly.
*/
export const SUPPORTED_CLOUD_COMPRESSIONS = 'zstd;zlib;gzip';
export const PBBD_MAGIC = 0x44424250; // "PBBD" little-endian (0x4663427: 0x144424250)
export interface ParsedGblkUpload {
readonly blkType: string;
readonly version: number;
readonly contentHash: string;
readonly container: BlkBlock;
}
export function isPbbdStream(bytes: Uint8Array): boolean {
if (bytes.byteLength < 8) return false;
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
return view.getUint32(0, true) === PBBD_MAGIC && view.getUint16(4, true) === 1;
}
/**
* Unpack a single `cln_set_general_blk` request body (0x4666ee7 -> 0x3371f30 -> 0x3371cc0).
* Unlike CharServer answers, `0x3371cc0` omits the 1-byte marker and names the compressor in
* the HTTP `compr` header (`zstd`: pure Zstd frame; `zlib`: 4-byte BE size + zlib stream;
* `gzip`: standard gzip; omitted/`none`: raw binary BLK).
*/
export function unpackCloudBlk(bytes: Uint8Array, comprHeader: string | undefined): BlkBlock | undefined {
if (bytes.byteLength === 0) return undefined;
const raw = decompressCloudBytes(bytes, comprHeader);
if (!raw || raw.byteLength === 0) return undefined;
try {
return decodeBlk(raw);
} catch {
return undefined;
}
}
/**
* Parse a `cln_bulk_set_gblk` `PBBD` stream (0x4663080..0x4663f1c, 0x41537d0..0x4154020).
* Header is 8 bytes: `"PBBD"` + `uint16_le(1)` + `uint16_le(chunkCount)`.
* Each chunk is `uint32_le(payloadLen)` + `uint8(marker)` + `payload`.
* Each `desc:t="store_gblk"` descriptor chunk is immediately followed by its `ContainerBlk` chunk.
*/
export function parsePbbdBulkUploads(bytes: Uint8Array): ReadonlyArray<ParsedGblkUpload> {
if (!isPbbdStream(bytes)) return [];
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const chunkCount = view.getUint16(6, true);
const chunks: Array<BlkBlock | undefined> = [];
let offset = 8;
for (let i = 0; i < chunkCount; i++) {
if (offset + 5 > bytes.byteLength) break;
const payloadLen = view.getUint32(offset, true);
const marker = bytes[offset + 4]!;
offset += 5;
if (offset + payloadLen > bytes.byteLength) break;
const slice = bytes.subarray(offset, offset + payloadLen);
offset += payloadLen;
chunks.push(decodeMarkedChunk(marker, slice));
}
const uploads: ParsedGblkUpload[] = [];
for (let i = 0; i < chunks.length; i++) {
const meta = chunks[i];
if (!meta) continue;
const desc = stringOf(meta, 'desc');
if (desc === 'store_gblk') {
const containerCandidate = chunks[i + 1];
i += 1;
const blkType = stringOf(meta, 'blkType');
if (!blkType || !containerCandidate) continue;
const fallbackVersion = intOf(meta, 'version') ?? 1;
const extracted = normalizeContainerBlk(containerCandidate, fallbackVersion);
const contentHash = stringOf(meta, 'contentHash') || computeContentHash(extracted.content);
uploads.push({
blkType,
version: extracted.version,
contentHash,
container: extracted.container,
});
} else if (desc === 'bigquery' || desc === 'logout') {
// Both `bigquery` (0x4663916) and `logout` (0x4663b66) append one companion payload chunk.
i += 1;
}
}
return uploads;
}
/**
* Normalize an uploaded `ContainerBlk` (`version:i` + `content { ... }`, 0x4664b55 / 0x466a810)
* so stored `.blk` files always carry an authoritative positive `version:i` and a `content` block.
*/
export function normalizeContainerBlk(
incoming: BlkBlock,
fallbackVersion: number,
): { readonly version: number; readonly content: BlkBlock; readonly container: BlkBlock } {
const existingContent = findBlock(incoming, 'content');
const rawVersion = intOf(incoming, 'version') ?? fallbackVersion;
const version = rawVersion > 0 ? rawVersion : Math.max(1, fallbackVersion);
const content = existingContent
? cloneAsContent(existingContent)
: cloneAsContent(incoming);
const container = buildContainerBlk(version, content);
return { version, content, container };
}
export function buildContainerBlk(version: number, content: BlkBlock): BlkBlock {
const container = emptyBlock();
setParam(container, 'version', { type: 'int', value: Math.max(1, Math.trunc(version)) });
container.blocks.push(cloneAsContent(content));
return container;
}
/** MD5 hex of the serialized `content` DataBlock (`ContainerBlk::calcHash` at 0x466af40 -> 0x4661840). */
export function computeContentHash(content: BlkBlock): string {
const rootCopy = emptyBlock();
rootCopy.params.push(...content.params);
rootCopy.blocks.push(...content.blocks);
return createHash('md5').update(encodeBlk(rootCopy)).digest('hex');
}
export function describePbbdForLog(bytes: Uint8Array): string {
const uploads = parsePbbdBulkUploads(bytes);
if (uploads.length === 0) return 'PBBD stream (0 store_gblk items)';
return uploads.map((u) => `${u.blkType} v${u.version} (${u.contentHash})`).join(', ');
}
function cloneAsContent(source: BlkBlock): BlkBlock {
return {
name: 'content',
params: [...source.params],
blocks: [...source.blocks],
};
}
function decompressCloudBytes(bytes: Uint8Array, comprHeader: string | undefined): Uint8Array | undefined {
const method = comprHeader?.trim().toLowerCase();
try {
if (method === 'zstd') return zstdDecompressSync(bytes);
if (method === 'zlib') return bytes.byteLength > 4 ? inflateSync(bytes.subarray(4)) : undefined;
if (method === 'gzip') return gunzipSync(bytes);
if (!method || method === 'none') {
const marked = unpackMarked(bytes);
return marked?.data ?? bytes;
}
const marked = unpackMarked(bytes);
return marked?.data;
} catch {
const marked = unpackMarked(bytes);
return marked?.data;
}
}
function decodeMarkedChunk(marker: number, payload: Uint8Array): BlkBlock | undefined {
if (payload.byteLength === 0) return emptyBlock();
try {
let raw: Uint8Array | undefined;
if (marker === 0x69) {
raw = payload; // 'i' uncompressed
} else if (marker === 0x5a) {
raw = zstdDecompressSync(payload); // 'Z' zstd (0-byte header)
} else if (marker === 0x7a) {
raw = payload.byteLength > 4 ? inflateSync(payload.subarray(4)) : undefined; // 'z' 4B BE size + zlib
} else if (marker === 0x1f) {
raw = gunzipSync(payload); // gzip
}
return raw ? decodeBlk(raw) : undefined;
} catch {
return undefined;
}
}
function stringOf(block: BlkBlock, name: string): string | undefined {
const param = findParam(block, name);
return param?.value.type === 'string' ? param.value.value : undefined;
}
function intOf(block: BlkBlock, name: string): number | undefined {
const param = findParam(block, name);
return param?.value.type === 'int' ? param.value.value : undefined;
}
@@ -8,11 +8,32 @@ import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { decodeBlk, emptyBlock, encodeBlk, ensureBlock, setParam, type BlkBlock } from '@wto/blk';
import { writeFileAtomic } from '../storage/atomic-file.ts';
import {
GENERAL_BLK_TYPES,
SUPPORTED_CLOUD_COMPRESSIONS,
type ParsedGblkUpload,
} from './cloud-settings-codec.ts';
/**
* The three GeneralBlk types accepted by `PlayerProfile::applyGeneralBlk` (0xf5afb0) and
* `PlayerProfile::storeGeneralBlk` (0xf5b080).
*/
export const GENERAL_BLK_TYPES = [
'GBT_GENERAL_STORAGE',
'GBT_GENERAL_SETTINGS',
'GBT_GENERAL_MACHINE_SETTINGS',
] as const;
/**
* Compression methods advertised in `cln_get_meta_blk`'s `compressionSupported`. Put `zstd`
* first so `online_storage::Context::selectCompression` (0x4665de1) selects pure Zstandard
* frames (0x3372ca0), which Node's built-in `node:zlib` unpacks directly.
*/
export const SUPPORTED_CLOUD_COMPRESSIONS = 'zstd;zlib;gzip';
const SUPPORTED_BLK_TYPE_SET: ReadonlySet<string> = new Set(GENERAL_BLK_TYPES);
export interface ParsedGblkUpload {
readonly blkType: string;
readonly version: number;
readonly contentHash: string;
readonly container: BlkBlock;
}
interface StoredBlockMeta {
version: number;
@@ -32,11 +53,6 @@ export class CloudSettingsStore {
this.#savesRoot = join(dataFolder, 'saves');
}
/**
* Build the `generalBlkMeta` / `cln_get_meta_blk` DataBlock (aces.exe 0x4665cf4..0x4666900).
* Every registered `blkType` is marked `perMachine:b=no` in `__schema` so settings travel
* with the player's save across machines without hardware-ID partitioning.
*/
buildMetaBlk(userId?: string, blockName?: string): BlkBlock {
const meta = blockName ? emptyBlock(blockName) : emptyBlock();
setParam(meta, 'machineHash', { type: 'string', value: `hhh${userId ?? '0'}` });
@@ -44,7 +60,7 @@ export class CloudSettingsStore {
const schema = ensureBlock(meta, '__schema');
const saved = userId && isValidUserId(userId) ? this.#loadMeta(userId).blocks : {};
const allTypes = new Set<string>([...GENERAL_BLK_TYPES, ...Object.keys(saved)]);
const allTypes = new Set<string>([...GENERAL_BLK_TYPES, ...Object.keys(saved).filter(isSupportedGeneralBlkType)]);
for (const blkType of allTypes) {
const schemaEntry = ensureBlock(schema, blkType);
@@ -57,11 +73,9 @@ export class CloudSettingsStore {
setParam(typeBlock, 'contentHash', { type: 'string', value: entry.contentHash });
}
}
return meta;
}
/** Load a stored `ContainerBlk` (`version:i` + `content { ... }`) for `cln_get_general_blk`. */
loadContainer(userId: string, blkType: string): BlkBlock | undefined {
if (!isValidUserId(userId) || !isSupportedGeneralBlkType(blkType)) return undefined;
const blkPath = this.#blkPath(userId, blkType);
@@ -73,7 +87,6 @@ export class CloudSettingsStore {
}
}
/** Persist a single uploaded `ContainerBlk` and update `meta.json` atomically. */
saveUpload(userId: string, upload: ParsedGblkUpload): boolean {
if (!isValidUserId(userId) || !isSupportedGeneralBlkType(upload.blkType)) return false;
const meta = this.#loadMeta(userId);
@@ -90,7 +103,6 @@ export class CloudSettingsStore {
return true;
}
/** Persist a batch of uploads from `cln_bulk_set_gblk`. */
saveBulkUploads(userId: string, uploads: ReadonlyArray<ParsedGblkUpload>): number {
let savedCount = 0;
for (const upload of uploads) {
@@ -126,8 +138,6 @@ export class CloudSettingsStore {
}
}
const SUPPORTED_BLK_TYPE_SET: ReadonlySet<string> = new Set(GENERAL_BLK_TYPES);
function isValidUserId(userId: string): boolean {
return /^\d+$/.test(userId);
}