From 129d796095005c125dcb4246ef85e24514051253 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:33:41 +0800 Subject: [PATCH] feat(store): add GJN balances, a local store, and redemption codes Support currency and entitlement purchases, including packs, from the local store and the in-game payment flow. Expose the supported redemption codes. --- .../build/src/features/offline-features.ts | 6 +- packages/build/src/main-pack.ts | 45 ++- .../src/network/redirect-network-config.ts | 2 + .../src/accounts/account-store.ts | 21 +- .../src/char/actions/action-table.ts | 4 + .../src/char/actions/store-actions.ts | 42 +++ .../src/game-data/datasets/dataset-cache.ts | 8 + .../src/game-data/datasets/dataset.ts | 1 + .../src/game-data/datasets/store-bundles.ts | 27 ++ .../src/game-data/datasets/unit-names.ts | 96 ++++++ .../game-data/datasets/vehicle-catalogue.ts | 6 +- .../local-service/src/game-data/game-files.ts | 2 +- .../local-service/src/game-data/game-pack.ts | 4 + packages/local-service/src/local-service.ts | 4 +- .../src/login/session-credentials.ts | 24 +- .../local-service/src/login/yuplay-answer.ts | 2 +- .../local-service/src/profile/new-profile.ts | 5 +- .../src/profile/profile-currency.ts | 40 ++- .../src/profile/profile-entitlements.ts | 67 ++++ .../src/research/research-rules.ts | 9 +- packages/local-service/src/save-cli.ts | 22 +- .../local-service/src/store/redeem-codes.ts | 84 +++++ .../src/store/store-catalogue.ts | 225 ++++++++++++ .../local-service/src/store/store-page.ts | 326 ++++++++++++++++++ .../local-service/src/store/store-purchase.ts | 68 ++++ .../local-service/src/store/store-service.ts | 241 +++++++++++++ 26 files changed, 1352 insertions(+), 29 deletions(-) create mode 100644 packages/local-service/src/char/actions/store-actions.ts create mode 100644 packages/local-service/src/game-data/datasets/store-bundles.ts create mode 100644 packages/local-service/src/game-data/datasets/unit-names.ts create mode 100644 packages/local-service/src/profile/profile-entitlements.ts create mode 100644 packages/local-service/src/store/redeem-codes.ts create mode 100644 packages/local-service/src/store/store-catalogue.ts create mode 100644 packages/local-service/src/store/store-page.ts create mode 100644 packages/local-service/src/store/store-purchase.ts create mode 100644 packages/local-service/src/store/store-service.ts diff --git a/packages/build/src/features/offline-features.ts b/packages/build/src/features/offline-features.ts index e26db61..1343763 100644 --- a/packages/build/src/features/offline-features.ts +++ b/packages/build/src/features/offline-features.ts @@ -9,12 +9,16 @@ * offer (scripts/tutorials/nextTutorialHandler.nut) enables its skip and close buttons only * with this feature (tutorialsData.nut canSkipByFeature). The offline version makes the * tutorial optional (local verification). + * + * PaymentMethods: lets scripts/onlineShop/onlinePurchase.nut offer GJN payment directly + * inside the Golden Eagles and Premium Account windows (stock game_settings.blk restricts it + * with PS4Access; implementation notes). */ import { ensureBlock, setParam, type BlkBlock } from '@wto/blk'; export const GAME_SETTINGS_PATH = 'config/game_settings.blk'; -export const OFFLINE_FEATURES: readonly string[] = ['AllowedToSkipBaseTutorials']; +export const OFFLINE_FEATURES: readonly string[] = ['AllowedToSkipBaseTutorials', 'PaymentMethods']; /** Give every player the features; returns the ones that were not on for everyone before. */ export function enableFeaturesForEveryone(gameSettings: BlkBlock, names: readonly string[]): string[] { diff --git a/packages/build/src/main-pack.ts b/packages/build/src/main-pack.ts index c096195..99897da 100644 --- a/packages/build/src/main-pack.ts +++ b/packages/build/src/main-pack.ts @@ -12,24 +12,53 @@ * Only the `network` block is touched: the rest of settings.blk is engine configuration, not * server addresses. */ -import { findBlock } from '@wto/blk'; +import { ensureBlock, findBlock, setParam, type BlkBlock } 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'; +import { editPackBlks } from './pack-edit.ts'; export const ENGINE_SETTINGS_PATH = 'config/settings.blk'; +export const GUI_CONFIG_PATH = 'config/gui.blk'; const NETWORK_BLOCK = 'network'; +/** + * GUIDs added to config/gui.blk bundles/guid so scripts/onlineShop/entitlementsInfo.nut + * requests GJN prices for GJN-priced Premium Account tiers alongside the stock eagles* packs + *. + */ +export const EXTRA_STORE_BUNDLE_GUIDS: ReadonlyArray = [ + ['wto_prem_20d', 'A1E00020-5754-4F46-8F00-000000000020'], + ['wto_prem_60d', 'A1E00060-5754-4F46-8F00-000000000060'], + ['wto_prem_180d', 'A1E00180-5754-4F46-8F00-000000000180'], +]; + 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 }; + let addresses: AddressChange[] = []; + const pack = editPackBlks(stockPack, [ + { + path: ENGINE_SETTINGS_PATH, + edit: (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`); + addresses = redirectAddresses(network, endpoint, [NETWORK_BLOCK]); + }, + }, + { + path: GUI_CONFIG_PATH, + edit: (root) => registerStoreBundleGuids(root), + }, + ]); + return { pack, addresses }; +} + +function registerStoreBundleGuids(guiRoot: BlkBlock): void { + const guidBlock = ensureBlock(ensureBlock(guiRoot, 'bundles'), 'guid'); + for (const [entitlement, guid] of EXTRA_STORE_BUNDLE_GUIDS) { + setParam(guidBlock, entitlement, { type: 'string', value: guid }); + } } diff --git a/packages/build/src/network/redirect-network-config.ts b/packages/build/src/network/redirect-network-config.ts index 61d5c3e..06ce31a 100644 --- a/packages/build/src/network/redirect-network-config.ts +++ b/packages/build/src/network/redirect-network-config.ts @@ -27,6 +27,8 @@ export function redirectNetworkConfig(root: BlkBlock, endpoint: LocalEndpoint): function configureEnvironment(environment: BlkBlock, endpoint: LocalEndpoint): void { setParam(environment, 'enableSslCertCheck', { type: 'bool', value: false }); + // Open the local web store directly without SSO redirection to login.gaijin.net. + setParam(environment, 'webstoreURL', { type: 'string', value: `http://${endpoint.host}:${endpoint.port}/store` }); const login = ensureBlock(environment, 'yuplay'); for (const [key, value] of loginOverrides(endpoint)) setParam(login, key, { type: 'string', value }); } diff --git a/packages/local-service/src/accounts/account-store.ts b/packages/local-service/src/accounts/account-store.ts index 98cdfd6..47e6b5f 100644 --- a/packages/local-service/src/accounts/account-store.ts +++ b/packages/local-service/src/accounts/account-store.ts @@ -35,6 +35,7 @@ const NICK_MAX_LENGTH = 16; export class AccountStore { readonly #path: string; #file: AccountFile; + #lastSignedInUserId: string | undefined; constructor(dataFolder: string) { this.#path = join(dataFolder, 'accounts.json'); @@ -43,15 +44,33 @@ export class AccountStore { 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' }; + if (existing) { + if (!verifyPassword(password, existing.passwordHash)) return { kind: 'wrong-password' }; + this.#lastSignedInUserId = existing.userId; + return { kind: 'signed-in', account: existing, registered: false }; + } 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)); + this.#lastSignedInUserId = account.userId; return { kind: 'signed-in', account, registered: true }; } + all(): readonly Account[] { + return this.#file.accounts; + } + + /** User id of the account that signed in most recently, or the newest account when none signed in yet. */ + activeAccount(): Account | undefined { + if (this.#lastSignedInUserId !== undefined) { + const active = this.byUserId(this.#lastSignedInUserId); + if (active) return active; + } + return this.#file.accounts[this.#file.accounts.length - 1]; + } + byUserId(userId: string): Account | undefined { return this.#file.accounts.find((account) => account.userId === userId); } diff --git a/packages/local-service/src/char/actions/action-table.ts b/packages/local-service/src/char/actions/action-table.ts index c9bcfbd..c01f369 100644 --- a/packages/local-service/src/char/actions/action-table.ts +++ b/packages/local-service/src/char/actions/action-table.ts @@ -17,6 +17,7 @@ import { buyAircraft, buySlot } from './purchase-actions.ts'; import { convertExp, resetResearchable, setResearchable } from './research-actions.ts'; import { setStartingInfo } from './starting-info-actions.ts'; import { activateBoosterAction, activateDiscountAction, applySpareItemAction, buyItemAction, startWagerAction } from './item-actions.ts'; +import { buyEntitlementAction, entitlementsPriceEx } from './store-actions.ts'; export interface ActionDependencies { readonly profiles: PlayerProfiles; @@ -61,5 +62,8 @@ export function actionTable(deps: ActionDependencies): ReadonlyMap 0x2a1240 sends `entitlement` and `costGold` + * in the HTTP headers, job type 5, answer applied as a full profile update). + */ +import type { AccountStore } from '../../accounts/account-store.ts'; +import { clientProfile } from '../../profile/client-profile.ts'; +import type { PlayerProfiles } from '../../profile/player-profiles.ts'; +import { serverTimeNow } from '../../profile/server-time.ts'; +import type { ResearchRules } from '../../research/research-rules.ts'; +import type { RuleOutcome } from '../../research/rule-outcome.ts'; +import { buyGoldEntitlement } from '../../store/store-purchase.ts'; +import type { CharActionHandler } from '../char-action.ts'; +import { withAccount } from './account-context.ts'; +import { intParam, stringParam } from './payload-params.ts'; + +export function entitlementsPriceEx(rules: ResearchRules): CharActionHandler { + const table = rules.store.entitlementsPriceBlk(); + return () => ({ kind: 'data', blk: table }); +} + +export function buyEntitlementAction(profiles: PlayerProfiles, accounts: AccountStore, rules: ResearchRules): CharActionHandler { + return (context) => withAccount(context, accounts, (account) => { + const entitlement = context.headerParam('entitlement') ?? (context.payload ? stringParam(context.payload, 'entitlement') : undefined); + const headerGold = context.headerParam('costGold'); + const offeredGold = headerGold !== undefined && /^\d+$/.test(headerGold) + ? Number(headerGold) + : (context.payload ? intParam(context.payload, 'costGold') : undefined); + if (!entitlement) return { kind: 'error', code: 'BAD_PARAMS' }; + + let outcome: RuleOutcome = { ok: false, refusal: 'BAD_PARAMS' }; + const now = serverTimeNow(); + const updated = profiles.updateWhen(account.userId, (saved) => { + outcome = buyGoldEntitlement(saved, rules.store, entitlement, offeredGold, now); + return outcome.ok; + }); + if (updated) return { kind: 'data', blk: clientProfile(updated, account) }; + return { kind: 'error', code: outcome.ok ? 'BAD_PARAMS' : outcome.refusal }; + }); +} diff --git a/packages/local-service/src/game-data/datasets/dataset-cache.ts b/packages/local-service/src/game-data/datasets/dataset-cache.ts index 93c4ff3..387dcdb 100644 --- a/packages/local-service/src/game-data/datasets/dataset-cache.ts +++ b/packages/local-service/src/game-data/datasets/dataset-cache.ts @@ -119,6 +119,14 @@ class TrackedSource implements DatasetSource { return gamePack.readBlk(path); } + readText(pack: GamePackName, path: string): string { + const gamePack = this.#gameFiles.pack(pack); + const sha1 = gamePack.fileDigest(path); + if (sha1 === undefined) throw new Error(`${pack} has no file ${path}`); + this.#files.set(`${pack}/${path}`, { pack, path, sha1 }); + return gamePack.readText(path); + } + listFiles(pack: GamePackName): readonly string[] { const paths = this.#gameFiles.pack(pack).paths(); this.#listings.set(pack, { pack, sha1: listingDigest(paths) }); diff --git a/packages/local-service/src/game-data/datasets/dataset.ts b/packages/local-service/src/game-data/datasets/dataset.ts index 3f51a81..59e109c 100644 --- a/packages/local-service/src/game-data/datasets/dataset.ts +++ b/packages/local-service/src/game-data/datasets/dataset.ts @@ -11,6 +11,7 @@ import type { GamePackName } from '../game-files.ts'; export interface DatasetSource { readBlk(pack: GamePackName, path: string): BlkBlock; + readText(pack: GamePackName, path: string): string; /** Every file path in a pack, sorted. */ listFiles(pack: GamePackName): readonly string[]; } diff --git a/packages/local-service/src/game-data/datasets/store-bundles.ts b/packages/local-service/src/game-data/datasets/store-bundles.ts new file mode 100644 index 0000000..246bc3e --- /dev/null +++ b/packages/local-service/src/game-data/datasets/store-bundles.ts @@ -0,0 +1,27 @@ +/** + * Dataset: entitlement-to-GUID mappings from aces.vromfs.bin config/gui.blk bundles/guid + * (gui.vromfs.bin scripts/onlineShop/onlineBundles.nut, implementation notes). + */ +import { findBlock } from '@wto/blk'; +import type { Dataset } from './dataset.ts'; + +const GUI_CONFIG = 'config/gui.blk'; + +/** Entitlement name -> store item GUID (upper-case UUID string). */ +export type StoreBundleGuids = Readonly>; + +export const storeBundles: Dataset = { + id: 'store-bundles', + version: 1, + extract: (source) => { + const gui = source.readBlk('aces.vromfs.bin', GUI_CONFIG); + const guidBlock = findBlock(findBlock(gui, 'bundles') ?? { name: '', params: [], blocks: [] }, 'guid'); + const result: Record = {}; + for (const param of guidBlock?.params ?? []) { + if (param.value.type === 'string' && param.value.value) { + result[param.name] = param.value.value; + } + } + return result; + }, +}; diff --git a/packages/local-service/src/game-data/datasets/unit-names.ts b/packages/local-service/src/game-data/datasets/unit-names.ts new file mode 100644 index 0000000..4e99bdf --- /dev/null +++ b/packages/local-service/src/game-data/datasets/unit-names.ts @@ -0,0 +1,96 @@ +/** + * Dataset: localized vehicle names from lang.vromfs.bin lang/units.csv. + * + * Used by the local web store and generated inventory coupon definitions so players see the + * game's own English and Chinese vehicle names without shipping game text with the service. + */ +import type { Dataset } from './dataset.ts'; + +const UNITS_CSV = 'lang/units.csv'; + +export interface LocalizedText { + readonly en: string; + readonly zh: string; +} + +export type UnitNamesMap = Readonly>; + +export const unitNames: Dataset = { + id: 'unit-names', + version: 1, + extract: (source) => { + const csv = source.readText('lang.vromfs.bin', UNITS_CSV); + const lines = csv.split(/\r?\n/); + const header = parseCsvRow(lines[0] ?? ''); + const enCol = Math.max(1, header.indexOf('')); + const zhCol = header.indexOf(''); + const hzhCol = header.indexOf(''); + + const shopNames = new Map(); + const fullNames = new Map(); + for (let i = 1; i < lines.length; i++) { + const line = lines[i]!; + if (!line.startsWith('"')) continue; + const firstSemi = line.indexOf(';'); + if (firstSemi <= 2) continue; + const key = line.slice(1, firstSemi - 1); + const isShop = key.endsWith('_shop'); + const isFull = !isShop && key.endsWith('_0'); + if (!isShop && !isFull) continue; + + const cols = parseCsvRow(line); + const en = cleanText(cols[enCol] ?? ''); + if (!en) continue; + const zh = cleanText((hzhCol >= 0 ? cols[hzhCol] : '') || (zhCol >= 0 ? cols[zhCol] : '') || en); + const unitId = key.slice(0, isShop ? -5 : -2); + if (isShop) shopNames.set(unitId, { en, zh }); + else fullNames.set(unitId, { en, zh }); + } + + const result: Record = {}; + for (const [unitId, text] of fullNames) result[unitId] = text; + for (const [unitId, text] of shopNames) result[unitId] = text; + return result; + }, +}; + +function parseCsvRow(line: string): string[] { + const fields: string[] = []; + let i = 0; + while (i < line.length) { + if (line[i] === '"') { + i++; + let value = ''; + while (i < line.length) { + if (line[i] === '"') { + if (line[i + 1] === '"') { + value += '"'; + i += 2; + } else { + i++; + break; + } + } else { + value += line[i]!; + i++; + } + } + fields.push(value); + if (line[i] === ';') i++; + } else { + const next = line.indexOf(';', i); + if (next < 0) { + fields.push(line.slice(i)); + break; + } + fields.push(line.slice(i, next)); + i = next + 1; + } + } + return fields; +} + +function cleanText(raw: string): string { + // Strip zero-width word-break spaces Gaijin inserts into CJK localization strings. + return raw.replace(/\u200b/g, '').trim(); +} diff --git a/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts b/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts index 9a6bcf8..2f459bd 100644 --- a/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts +++ b/packages/local-service/src/game-data/datasets/vehicle-catalogue.ts @@ -52,11 +52,13 @@ export interface CatalogueVehicle { readonly parts: readonly string[]; /** shop.blk showOnlyWhenBought. */ readonly onlyShownWhenOwned: boolean; + /** shop.blk marketplaceItemdefId (vehicles traded as coupons on the market, implementation notes). */ + readonly marketplaceItemdefId?: number; } export const vehicleCatalogue: Dataset = { id: 'vehicle-catalogue', - version: 2, + version: 3, extract: (source) => { const shopEntries = new Map(); for (const country of source.readBlk('char.vromfs.bin', SHOP).blocks) { @@ -70,6 +72,7 @@ function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined): C const requires = stringField(vehicle, 'reqAir'); const researchType = stringField(vehicle, 'researchType'); const requiredUnlock = stringField(shopEntry, 'reqUnlock'); + const marketplaceItemdefId = numberField(shopEntry, 'marketplaceItemdefId') ?? numberField(vehicle, 'marketplaceItemdefId'); return { name: vehicle.name, country: stringField(vehicle, 'country') ?? '', @@ -87,6 +90,7 @@ function catalogueVehicle(vehicle: BlkBlock, shopEntry: BlkBlock | undefined): C ...(requiredUnlock ? { requiredUnlock } : {}), parts: shopEntry ? shopEntry.params.flatMap((param) => (param.name === 'slaveUnit' && param.value.type === 'string' && param.value.value ? [param.value.value] : [])) : [], onlyShownWhenOwned: boolField(shopEntry, 'showOnlyWhenBought') ?? false, + ...(marketplaceItemdefId !== undefined ? { marketplaceItemdefId } : {}), }; } diff --git a/packages/local-service/src/game-data/game-files.ts b/packages/local-service/src/game-data/game-files.ts index ded3edb..43dbb8e 100644 --- a/packages/local-service/src/game-data/game-files.ts +++ b/packages/local-service/src/game-data/game-files.ts @@ -7,7 +7,7 @@ import type { BlkBlock } from '@wto/blk'; import { GamePack } from './game-pack.ts'; /** The data packs the local service reads (file names in the game folder). */ -export type GamePackName = 'char.vromfs.bin' | 'mis.vromfs.bin'; +export type GamePackName = 'char.vromfs.bin' | 'mis.vromfs.bin' | 'aces.vromfs.bin' | 'gui.vromfs.bin' | 'lang.vromfs.bin'; /** What identifies one version of a pack file cheaply (implementation notes, first check). */ export interface PackStamp { diff --git a/packages/local-service/src/game-data/game-pack.ts b/packages/local-service/src/game-data/game-pack.ts index 1bba607..669fb70 100644 --- a/packages/local-service/src/game-data/game-pack.ts +++ b/packages/local-service/src/game-data/game-pack.ts @@ -26,6 +26,10 @@ export class GamePack { return decodeBlk(getFile(this.#archive, pathInPack), this.#shared); } + readText(pathInPack: string): string { + return Buffer.from(getFile(this.#archive, pathInPack)).toString('utf8'); + } + /** Every file path in the pack, sorted. */ paths(): string[] { return [...this.#archive.files.keys()].sort(); diff --git a/packages/local-service/src/local-service.ts b/packages/local-service/src/local-service.ts index bee5461..d256163 100644 --- a/packages/local-service/src/local-service.ts +++ b/packages/local-service/src/local-service.ts @@ -18,6 +18,7 @@ import { setUpProfiles } from './profiles-setup.ts'; import { createPortListener } from './server/port-listener.ts'; import { Router } from './server/router.ts'; import { loadOrCreateCredentials } from './server/tls/tls-certificate.ts'; +import { StoreService } from './store/store-service.ts'; import { TrafficLog } from './traffic-log/traffic-log.ts'; export interface LocalServiceOptions { @@ -46,9 +47,10 @@ export async function startLocalService(options: LocalServiceOptions): Promise 0n ? id.toString(10) : undefined; +} + +/** Extract the user id from a JWT issued by issueCredentials. */ +export function userIdFromJwt(token: string | undefined): string | undefined { + if (!token) return undefined; + const parts = token.split('.'); + if (parts.length !== 3 || !parts[1]) return undefined; + try { + const parsed = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')) as { uid?: unknown }; + return typeof parsed.uid === 'string' && /^\d+$/.test(parsed.uid) ? parsed.uid : undefined; + } catch { + return undefined; + } } function jwt(claims: object): string { diff --git a/packages/local-service/src/login/yuplay-answer.ts b/packages/local-service/src/login/yuplay-answer.ts index e132997..eccc718 100644 --- a/packages/local-service/src/login/yuplay-answer.ts +++ b/packages/local-service/src/login/yuplay-answer.ts @@ -5,7 +5,7 @@ */ import type { ServiceResponse } from '../server/exchange.ts'; -export type YuplayStatus = 'OK' | 'ERROR' | 'LOGINERROR'; +export type YuplayStatus = 'OK' | 'ERROR' | 'LOGINERROR' | 'NOMONEY' | 'ALREADY' | 'NOTFOUND' | 'BADPAYMENT'; export function yuplayAnswer(status: YuplayStatus, fields: Readonly> = {}, summary?: string): ServiceResponse { const body = JSON.stringify({ status, ...fields }); diff --git a/packages/local-service/src/profile/new-profile.ts b/packages/local-service/src/profile/new-profile.ts index 7a290ff..e694796 100644 --- a/packages/local-service/src/profile/new-profile.ts +++ b/packages/local-service/src/profile/new-profile.ts @@ -5,15 +5,16 @@ * eagles (local verification); the template has none. */ import type { BlkBlock } from '@wto/blk'; -import { setGoldenEagles, setSilverLions, type Balance } from './profile-currency.ts'; +import { setGjn, setGoldenEagles, setSilverLions, type Balance } from './profile-currency.ts'; import { applyStartingContent, type StartingContent } from './starting-content.ts'; -export const STARTING_BALANCE: Balance = { silverLions: 150_000, goldenEagles: 500 }; +export const STARTING_BALANCE: Balance = { silverLions: 150_000, goldenEagles: 500, gjn: 0 }; export function newProfile(template: BlkBlock, content: StartingContent): BlkBlock { const profile = structuredClone(template); applyStartingContent(profile, content); setSilverLions(profile, STARTING_BALANCE.silverLions); setGoldenEagles(profile, STARTING_BALANCE.goldenEagles); + setGjn(profile, STARTING_BALANCE.gjn); return profile; } diff --git a/packages/local-service/src/profile/profile-currency.ts b/packages/local-service/src/profile/profile-currency.ts index ea84bf6..cd631c7 100644 --- a/packages/local-service/src/profile/profile-currency.ts +++ b/packages/local-service/src/profile/profile-currency.ts @@ -5,6 +5,8 @@ * warpointsPos:i64 silver lions earned in total * warpointsNeg:i64 silver lions spent in total * goldBalance:i golden eagles (read and written as a 32-bit integer, 0x91b570 / 0x91b5cb) + * gjnBalance:i64 GJN balance for the offline store and market (implementation notes; + * ignored by the client when loading a profile) * * The silver lion balance is warpointsPos - warpointsNeg; setting it keeps the amount spent * and adjusts the amount earned. @@ -14,15 +16,21 @@ import { findParam, setParam, type BlkBlock } from '@wto/blk'; const EARNED = 'warpointsPos'; const SPENT = 'warpointsNeg'; const GOLD = 'goldBalance'; +const GJN = 'gjnBalance'; const MAX_GOLD = 0x7fffffff; export interface Balance { readonly silverLions: number; readonly goldenEagles: number; + readonly gjn: number; } export function balanceOf(profile: BlkBlock): Balance { - return { silverLions: numberParam(profile, EARNED) - numberParam(profile, SPENT), goldenEagles: numberParam(profile, GOLD) }; + return { + silverLions: numberParam(profile, EARNED) - numberParam(profile, SPENT), + goldenEagles: numberParam(profile, GOLD), + gjn: numberParam(profile, GJN), + }; } export function setSilverLions(profile: BlkBlock, amount: number): void { @@ -35,8 +43,34 @@ export function setGoldenEagles(profile: BlkBlock, amount: number): void { setParam(profile, GOLD, { type: 'int', value: amount }); } -/** A price in both currencies. */ -export type Price = Balance; +export function setGjn(profile: BlkBlock, amount: number): void { + requireAmount(amount, Number.MAX_SAFE_INTEGER); + setParam(profile, GJN, { type: 'int64', value: BigInt(amount) }); +} + +export function addGoldenEagles(profile: BlkBlock, amount: number): void { + requireAmount(amount, MAX_GOLD); + const next = Math.min(MAX_GOLD, numberParam(profile, GOLD) + amount); + setGoldenEagles(profile, next); +} + +export function addSilverLions(profile: BlkBlock, amount: number): void { + requireAmount(amount, Number.MAX_SAFE_INTEGER); + setParam(profile, EARNED, { type: 'int64', value: BigInt(numberParam(profile, EARNED) + amount) }); +} + +export function payGjn(profile: BlkBlock, amount: number): void { + requireAmount(amount, Number.MAX_SAFE_INTEGER); + const current = numberParam(profile, GJN); + if (current < amount) throw new RangeError('the player cannot afford this GJN price'); + setGjn(profile, current - amount); +} + +/** A price in the two in-game currencies. */ +export interface Price { + readonly silverLions: number; + readonly goldenEagles: number; +} export function canAfford(profile: BlkBlock, price: Price): boolean { const balance = balanceOf(profile); diff --git a/packages/local-service/src/profile/profile-entitlements.ts b/packages/local-service/src/profile/profile-entitlements.ts new file mode 100644 index 0000000..06a61c9 --- /dev/null +++ b/packages/local-service/src/profile/profile-entitlements.ts @@ -0,0 +1,67 @@ +/** + * Entitlements and Premium Account in the profile (implementation notes; read by aces.exe + * 2.61.0.37 0x91daf0..0x91e474, has_entitlement 0x179ec70, entitlement_expires_in 0x179ed60): + * + * entitlementsInfo{ + * PremiumAccount{ + * count:i=1 + * expiredTime:i64= + * } + * wto_pack_f-5c{ + * count:i=1 + * } + * } + */ +import { ensureBlock, findBlock, findParam, setParam, type BlkBlock } from '@wto/blk'; + +const ENTITLEMENTS_INFO = 'entitlementsInfo'; +export const PREMIUM_ACCOUNT_ENTITLEMENT = 'PremiumAccount'; +const TICKS_PER_SECOND = 10_000_000n; +const TICKS_PER_DAY = 86_400n * TICKS_PER_SECOND; + +export function hasEntitlement(profile: BlkBlock, name: string, nowFiletime: bigint): boolean { + const entry = findBlock(findBlock(profile, ENTITLEMENTS_INFO) ?? emptyRef, name); + if (!entry) return false; + const count = intField(entry, 'count'); + if (count <= 0) return false; + const expires = int64Field(entry, 'expiredTime'); + return expires === 0n || expires > nowFiletime; +} + +export function recordEntitlementPurchase(profile: BlkBlock, name: string): void { + const entry = ensureBlock(ensureBlock(profile, ENTITLEMENTS_INFO), name); + const previous = intField(entry, 'count'); + setParam(entry, 'count', { type: 'int', value: previous + 1 }); +} + +export function extendPremiumAccount(profile: BlkBlock, days: number, nowFiletime: bigint): void { + if (!Number.isSafeInteger(days) || days <= 0) throw new RangeError(`invalid premium days: ${days}`); + const entry = ensureBlock(ensureBlock(profile, ENTITLEMENTS_INFO), PREMIUM_ACCOUNT_ENTITLEMENT); + const previousCount = intField(entry, 'count'); + const previousExpiry = int64Field(entry, 'expiredTime'); + const base = previousExpiry > nowFiletime ? previousExpiry : nowFiletime; + setParam(entry, 'count', { type: 'int', value: previousCount + 1 }); + setParam(entry, 'expiredTime', { type: 'int64', value: base + BigInt(days) * TICKS_PER_DAY }); +} + +/** Remaining whole days (rounded up) of Premium Account, or 0 when inactive. */ +export function remainingPremiumDays(profile: BlkBlock, nowFiletime: bigint): number { + const entry = findBlock(findBlock(profile, ENTITLEMENTS_INFO) ?? emptyRef, PREMIUM_ACCOUNT_ENTITLEMENT); + if (!entry || intField(entry, 'count') <= 0) return 0; + const expires = int64Field(entry, 'expiredTime'); + if (expires <= nowFiletime) return 0; + return Number((expires - nowFiletime + TICKS_PER_DAY - 1n) / TICKS_PER_DAY); +} + +const emptyRef: BlkBlock = { name: '', params: [], blocks: [] }; + +function intField(block: BlkBlock, name: string): number { + const value = findParam(block, name)?.value; + return value?.type === 'int' ? value.value : 0; +} + +function int64Field(block: BlkBlock, name: string): bigint { + const value = findParam(block, name)?.value; + if (value?.type === 'int64') return value.value; + return value?.type === 'int' ? BigInt(value.value) : 0n; +} diff --git a/packages/local-service/src/research/research-rules.ts b/packages/local-service/src/research/research-rules.ts index 8dec321..ebb7c89 100644 --- a/packages/local-service/src/research/research-rules.ts +++ b/packages/local-service/src/research/research-rules.ts @@ -16,7 +16,10 @@ import { EquipmentCatalogue } from '../modifications/equipment-catalogue.ts'; import { unlockPrices } from '../game-data/datasets/unlock-prices.ts'; import { UnlockShop } from '../unlocks/unlock-purchase.ts'; import { itemCatalogue } from '../game-data/datasets/item-catalogue.ts'; +import { storeBundles } from '../game-data/datasets/store-bundles.ts'; +import { unitNames } from '../game-data/datasets/unit-names.ts'; import { ItemCatalogue } from '../items/item-catalogue.ts'; +import { StoreCatalogue } from '../store/store-catalogue.ts'; import { TechTree } from './tech-tree.ts'; export interface ResearchRules { @@ -35,11 +38,14 @@ export interface ResearchRules { readonly unlocks: UnlockShop; /** Classic items: boosters, personal discounts, contracts, universal spares. */ readonly items: ItemCatalogue; + /** Paid store catalogue: GE packs, SL packs, Premium Account, vehicle packs. */ + readonly store: StoreCatalogue; } export function loadResearchRules(datasets: DatasetCache): ResearchRules { + const vehicles = datasets.load(vehicleCatalogue); return { - techTree: new TechTree(datasets.load(vehicleCatalogue)), + techTree: new TechTree(vehicles), eraRequirements: datasets.load(eraRequirements), vehicleUnlocks: datasets.load(vehicleUnlocks), crewSlotPrices: datasets.load(crewSlotPrices), @@ -49,5 +55,6 @@ export function loadResearchRules(datasets: DatasetCache): ResearchRules { crew: new CrewSkillCatalogue(datasets.load(crewSkillData)), unlocks: new UnlockShop(datasets.load(unlockPrices)), items: new ItemCatalogue(datasets.load(itemCatalogue)), + store: new StoreCatalogue(vehicles, datasets.load(storeBundles), datasets.load(unitNames)), }; } diff --git a/packages/local-service/src/save-cli.ts b/packages/local-service/src/save-cli.ts index aaa1e11..83cce7f 100644 --- a/packages/local-service/src/save-cli.ts +++ b/packages/local-service/src/save-cli.ts @@ -3,7 +3,7 @@ * section A; the launcher will call the same profile functions). * * node packages/local-service/src/save-cli.ts --game --data - * --player [--silver ] [--gold ] [--free-rp ] + * --player [--silver ] [--gold ] [--gjn ] [--free-rp ] * [--give-item [:]]... * * --free-rp sets the free research points. --give-item gives classic @@ -17,14 +17,15 @@ import { DatasetCache } from './game-data/datasets/dataset-cache.ts'; import { GameFiles } from './game-data/game-files.ts'; import type { ItemDefinition } from './game-data/datasets/item-catalogue.ts'; import { grantItem } from './items/item-grants.ts'; -import { balanceOf, setGoldenEagles, setSilverLions } from './profile/profile-currency.ts'; +import { balanceOf, setGjn, setGoldenEagles, setSilverLions } from './profile/profile-currency.ts'; +import { remainingPremiumDays } from './profile/profile-entitlements.ts'; import { ownedItems } from './profile/profile-items.ts'; import { freeResearchPoints, setFreeResearchPoints } from './profile/profile-research-points.ts'; import { serverTimeNow } from './profile/server-time.ts'; import { setUpProfiles } from './profiles-setup.ts'; const USAGE = 'usage: save-cli.ts --game --data --player ' - + '[--silver ] [--gold ] [--free-rp ] [--give-item [:]]...'; + + '[--silver ] [--gold ] [--gjn ] [--free-rp ] [--give-item [:]]...'; function main(): number { const { values } = parseArgs({ @@ -34,6 +35,7 @@ function main(): number { player: { type: 'string' }, silver: { type: 'string' }, gold: { type: 'string' }, + gjn: { type: 'string' }, 'free-rp': { type: 'string' }, 'give-item': { type: 'string', multiple: true }, }, @@ -44,9 +46,10 @@ function main(): number { } const silver = optionalAmount(values.silver); const gold = optionalAmount(values.gold); + const gjn = optionalAmount(values.gjn); const freeRp = optionalAmount(values['free-rp']); - if (silver === null || gold === null || freeRp === null) { - console.error('--silver, --gold and --free-rp take a whole number of 0 or more'); + if (silver === null || gold === null || gjn === null || freeRp === null) { + console.error('--silver, --gold, --gjn and --free-rp take a whole number of 0 or more'); return 2; } const accounts = new AccountStore(values.data); @@ -69,18 +72,21 @@ function main(): number { } gifts.push({ item, pieces }); } - const changes = silver !== undefined || gold !== undefined || freeRp !== undefined || gifts.length > 0; + const changes = silver !== undefined || gold !== undefined || gjn !== undefined || freeRp !== undefined || gifts.length > 0; + const now = serverTimeNow(); const profile = !changes ? profiles.profileOf(account.userId) : profiles.update(account.userId, (saved) => { if (silver !== undefined) setSilverLions(saved, silver); if (gold !== undefined) setGoldenEagles(saved, gold); + if (gjn !== undefined) setGjn(saved, gjn); if (freeRp !== undefined) setFreeResearchPoints(saved, freeRp); - const now = serverTimeNow(); for (const gift of gifts) grantItem(saved, gift.item, gift.pieces, now); }); const balance = balanceOf(profile); - console.log(`${account.login} (${account.userId}): ${balance.silverLions} silver lions, ${balance.goldenEagles} golden eagles, ${freeResearchPoints(profile)} free research points`); + const premiumDays = remainingPremiumDays(profile, now); + const premiumNote = premiumDays > 0 ? `, premium: ${premiumDays}d` : ''; + console.log(`${account.login} (${account.userId}): ${balance.silverLions} silver lions, ${balance.goldenEagles} golden eagles, ${balance.gjn} GJN, ${freeResearchPoints(profile)} free research points${premiumNote}`); const items = ownedItems(profile); if (items.length) console.log(`items: ${items.map((item) => `${item.id} x${item.count}`).join(', ')}`); return 0; diff --git a/packages/local-service/src/store/redeem-codes.ts b/packages/local-service/src/store/redeem-codes.ts new file mode 100644 index 0000000..a979917 --- /dev/null +++ b/packages/local-service/src/store/redeem-codes.ts @@ -0,0 +1,84 @@ +/** + * Redeem codes (implementation notes section G; implementation notes): + * - PREMIUM-D / VIP-D (e.g. PREMIUM-7D, PREMIUM-30D, PREMIUM-365D): adds days of + * Premium Account (1..3650 days); + * - WTO-GJN- / GJN- (e.g. WTO-GJN-100, WTO-GJN-1000): adds GJN (1..100000); + * - WTO-STARTER (once per save): grants 7 days of Premium Account, 1,000 Golden Eagles and 100 GJN. + */ +import type { BlkBlock } from '@wto/blk'; +import type { LocalizedText } from '../game-data/datasets/unit-names.ts'; +import { addGoldenEagles, balanceOf, setGjn } from '../profile/profile-currency.ts'; +import { extendPremiumAccount, hasEntitlement, recordEntitlementPurchase } from '../profile/profile-entitlements.ts'; + +const STARTER_ENTITLEMENT = 'wto_redeem_starter'; + +export type RedeemOutcome = + | { readonly ok: true; readonly message: LocalizedText } + | { readonly ok: false; readonly reason: 'INVALID_CODE' | 'ALREADY_REDEEMED'; readonly message: LocalizedText }; + +export function redeemStoreCode(profile: BlkBlock, rawCode: string, nowFiletime: bigint): RedeemOutcome { + const code = rawCode.trim().toUpperCase(); + if (!code) { + return { ok: false, reason: 'INVALID_CODE', message: { en: 'Enter a redeem code.', zh: '请输入兑换码。' } }; + } + + if (code === 'WTO-STARTER') { + if (hasEntitlement(profile, STARTER_ENTITLEMENT, nowFiletime)) { + return { + ok: false, + reason: 'ALREADY_REDEEMED', + message: { en: 'This starter code has already been redeemed on this save.', zh: '当前存档已使用过该新手礼包兑换码。' }, + }; + } + recordEntitlementPurchase(profile, STARTER_ENTITLEMENT); + extendPremiumAccount(profile, 7, nowFiletime); + addGoldenEagles(profile, 1_000); + setGjn(profile, balanceOf(profile).gjn + 100); + return { + ok: true, + message: { + en: 'Redeemed WTO-STARTER: +7d Premium Account, +1,000 Golden Eagles, +100 GJN.', + zh: '兑换成功:高级账户 +7 天、金鹰 +1,000、GJN +100。', + }, + }; + } + + const premiumMatch = /^(?:PREMIUM|PREM|VIP)-(\d{1,4})D$/.exec(code); + if (premiumMatch) { + const days = Number(premiumMatch[1]); + if (days >= 1 && days <= 3_650) { + extendPremiumAccount(profile, days, nowFiletime); + return { + ok: true, + message: { + en: `Redeemed ${code}: +${days} days of Premium Account.`, + zh: `兑换成功:高级账户增加 ${days} 天。`, + }, + }; + } + } + + const gjnMatch = /^(?:WTO-GJN|GJN)-(\d{1,6})$/.exec(code); + if (gjnMatch) { + const amount = Number(gjnMatch[1]); + if (amount >= 1 && amount <= 100_000) { + setGjn(profile, balanceOf(profile).gjn + amount); + return { + ok: true, + message: { + en: `Redeemed ${code}: +${amount.toLocaleString('en-US')} GJN.`, + zh: `兑换成功:GJN 增加 ${amount.toLocaleString('en-US')}。`, + }, + }; + } + } + + return { + ok: false, + reason: 'INVALID_CODE', + message: { + en: 'Unknown redeem code. Examples: PREMIUM-7D, PREMIUM-30D, PREMIUM-365D, WTO-GJN-100, WTO-STARTER.', + zh: '无效的兑换码。可用示例:PREMIUM-7D、PREMIUM-30D、PREMIUM-365D、WTO-GJN-100、WTO-STARTER。', + }, + }; +} diff --git a/packages/local-service/src/store/store-catalogue.ts b/packages/local-service/src/store/store-catalogue.ts new file mode 100644 index 0000000..9c034c9 --- /dev/null +++ b/packages/local-service/src/store/store-catalogue.ts @@ -0,0 +1,225 @@ +/** + * Local store catalogue: Golden Eagles packs, Silver Lions packs, + * Premium Account durations (both Golden Eagles and GJN), and one vehicle pack per gift + * vehicle in the tech tree. + */ +import { emptyBlock, setParam, type BlkBlock } from '@wto/blk'; +import type { CatalogueVehicle } from '../game-data/datasets/vehicle-catalogue.ts'; +import type { StoreBundleGuids } from '../game-data/datasets/store-bundles.ts'; +import type { LocalizedText, UnitNamesMap } from '../game-data/datasets/unit-names.ts'; + +export type StoreProductKind = 'eagles' | 'warpoints' | 'premium-gold' | 'premium-gjn' | 'vehicle-pack'; + +export interface StoreProduct { + readonly id: string; + readonly kind: StoreProductKind; + readonly chapter: string; + readonly title: LocalizedText; + /** Store item GUID when offered via item_info.php / item_purchase.php. */ + readonly guid?: string; + /** Price in Golden Eagles (in-game purchase via cln_buy_entitlement). */ + readonly goldCost?: number; + /** Price in GJN (onlinePurchase via item_purchase.php or the local web store). */ + readonly gjnCost?: number; + /** Golden Eagles granted on purchase. */ + readonly goldIncome?: number; + /** Silver Lions granted on purchase. */ + readonly silverIncome?: number; + /** Premium Account days granted on purchase. */ + readonly premiumDays?: number; + /** Gift vehicle granted on purchase, with any split-vehicle parts. */ + readonly vehicle?: CatalogueVehicle; +} + +const EAGLES_PACKS: ReadonlyArray<{ readonly id: string; readonly gold: number; readonly gjn: number }> = [ + { id: 'eagles150', gold: 150, gjn: 1 }, + { id: 'eagles500', gold: 500, gjn: 3 }, + { id: 'eagles1000', gold: 1_000, gjn: 6 }, + { id: 'eagles2500', gold: 2_500, gjn: 14 }, + { id: 'eagles5000', gold: 5_000, gjn: 25 }, + { id: 'eagles10000', gold: 10_000, gjn: 50 }, + { id: 'eagles15000', gold: 15_000, gjn: 72 }, + { id: 'eagles20000', gold: 20_000, gjn: 95 }, + { id: 'eagles25000', gold: 25_000, gjn: 115 }, +]; + +const SILVER_LIONS_PACKS: ReadonlyArray<{ readonly id: string; readonly silver: number; readonly goldCost: number }> = [ + { id: 'warpoints1k', silver: 1_000, goldCost: 3 }, + { id: 'warpoints10k', silver: 10_000, goldCost: 30 }, + { id: 'warpoints50k', silver: 50_000, goldCost: 120 }, + { id: 'warpoints120k', silver: 120_000, goldCost: 300 }, + { id: 'warpoints630k', silver: 630_000, goldCost: 1_500 }, + { id: 'warpoints1300k', silver: 1_300_000, goldCost: 3_000 }, +]; + +const PREMIUM_GOLD_TIERS: ReadonlyArray<{ readonly id: string; readonly days: number; readonly goldCost: number }> = [ + { id: 'prem_1d', days: 1, goldCost: 190 }, + { id: 'prem_7d', days: 7, goldCost: 690 }, + { id: 'prem_15d', days: 15, goldCost: 1_190 }, + { id: 'prem_30d', days: 30, goldCost: 1_900 }, + { id: 'prem_90d', days: 90, goldCost: 4_900 }, + { id: 'prem_365d', days: 365, goldCost: 14_900 }, +]; + +const PREMIUM_GJN_TIERS: ReadonlyArray<{ readonly id: string; readonly fallbackGuid: string; readonly days: number; readonly gjn: number }> = [ + { id: 'wto_prem_20d', fallbackGuid: 'A1E00020-5754-4F46-8F00-000000000020', days: 20, gjn: 8 }, + { id: 'wto_prem_60d', fallbackGuid: 'A1E00060-5754-4F46-8F00-000000000060', days: 60, gjn: 20 }, + { id: 'wto_prem_180d', fallbackGuid: 'A1E00180-5754-4F46-8F00-000000000180', days: 180, gjn: 40 }, +]; + +interface PackTier { + readonly gjn: number; + readonly bonusGold: number; + readonly bonusDays: number; +} + +function packTierForRank(rank: number): PackTier { + if (rank <= 2) return { gjn: 15, bonusGold: 1_000, bonusDays: 7 }; + if (rank === 3) return { gjn: 25, bonusGold: 1_000, bonusDays: 7 }; + if (rank === 4) return { gjn: 35, bonusGold: 1_000, bonusDays: 7 }; + if (rank === 5) return { gjn: 50, bonusGold: 2_000, bonusDays: 15 }; + if (rank === 6) return { gjn: 60, bonusGold: 2_000, bonusDays: 15 }; + if (rank === 7) return { gjn: 70, bonusGold: 2_500, bonusDays: 20 }; + return { gjn: 75, bonusGold: 3_000, bonusDays: 30 }; +} + +export class StoreCatalogue { + readonly #byId = new Map(); + readonly #byGuid = new Map(); + readonly #priceBlk: BlkBlock; + + constructor(vehicles: readonly CatalogueVehicle[], bundleGuids: StoreBundleGuids, names: UnitNamesMap) { + const products: StoreProduct[] = []; + + for (const pack of EAGLES_PACKS) { + const guid = bundleGuids[pack.id]; + products.push({ + id: pack.id, + kind: 'eagles', + chapter: 'eagles', + title: { en: `${pack.gold.toLocaleString('en-US')} Golden Eagles`, zh: `${pack.gold.toLocaleString('en-US')} 金鹰` }, + ...(guid ? { guid } : {}), + gjnCost: pack.gjn, + goldIncome: pack.gold, + }); + } + + for (const pack of SILVER_LIONS_PACKS) { + products.push({ + id: pack.id, + kind: 'warpoints', + chapter: 'warpoints', + title: { en: `${pack.silver.toLocaleString('en-US')} Silver Lions`, zh: `${pack.silver.toLocaleString('en-US')} 银狮` }, + goldCost: pack.goldCost, + silverIncome: pack.silver, + }); + } + + for (const tier of PREMIUM_GOLD_TIERS) { + products.push({ + id: tier.id, + kind: 'premium-gold', + chapter: 'premium', + title: { en: `Premium Account (${tier.days}d)`, zh: `高级账户(${tier.days} 天)` }, + goldCost: tier.goldCost, + premiumDays: tier.days, + }); + } + + for (const tier of PREMIUM_GJN_TIERS) { + const guid = bundleGuids[tier.id] ?? tier.fallbackGuid; + products.push({ + id: tier.id, + kind: 'premium-gjn', + chapter: 'premium', + title: { en: `Premium Account (${tier.days}d)`, zh: `高级账户(${tier.days} 天)` }, + guid, + gjnCost: tier.gjn, + premiumDays: tier.days, + }); + } + + for (const vehicle of vehicles) { + if (!isPackVehicle(vehicle)) continue; + const tier = packTierForRank(vehicle.rank); + const unitLabel = names[vehicle.name] ?? { en: vehicle.name, zh: vehicle.name }; + products.push({ + id: `wto_pack_${vehicle.name}`, + kind: 'vehicle-pack', + chapter: 'bonuses', + title: { en: `${unitLabel.en} Pack`, zh: `${unitLabel.zh} 礼包` }, + gjnCost: tier.gjn, + goldIncome: tier.bonusGold, + premiumDays: tier.bonusDays, + vehicle, + }); + } + + for (const product of products) { + this.#byId.set(product.id, product); + if (product.guid) this.#byGuid.set(product.guid.toUpperCase(), product); + } + this.#priceBlk = buildEntitlementsPriceBlk(products); + } + + allProducts(): readonly StoreProduct[] { + return [...this.#byId.values()]; + } + + byId(id: string): StoreProduct | undefined { + return this.#byId.get(id); + } + + byGuid(guid: string): StoreProduct | undefined { + return this.#byGuid.get(guid.trim().toUpperCase()); + } + + entitlementsPriceBlk(): BlkBlock { + return this.#priceBlk; + } +} + +function isPackVehicle(vehicle: CatalogueVehicle): boolean { + return vehicle.inTechTree + && vehicle.gift + && !vehicle.event + && vehicle.marketplaceItemdefId === undefined + && !vehicle.onlyShownWhenOwned; +} + +function buildEntitlementsPriceBlk(products: readonly StoreProduct[]): BlkBlock { + const root = emptyBlock(); + for (const product of products) { + const block = emptyBlock(product.id); + setParam(block, 'chapter', { type: 'string', value: product.chapter }); + + if (product.kind === 'eagles') { + setParam(block, 'onlinePurchase', { type: 'bool', value: true }); + setParam(block, 'group', { type: 'string', value: 'eagles100' }); + setParam(block, 'useGroupAmount', { type: 'bool', value: true }); + setParam(block, 'goldIncome', { type: 'int', value: product.goldIncome! }); + } else if (product.kind === 'warpoints') { + setParam(block, 'group', { type: 'string', value: '1KWP' }); + setParam(block, 'useGroupAmount', { type: 'bool', value: true }); + setParam(block, 'wpIncome', { type: 'int', value: product.silverIncome! }); + setParam(block, 'goldCost', { type: 'int', value: product.goldCost! }); + } else if (product.kind === 'premium-gold') { + setParam(block, 'alias', { type: 'string', value: 'PremiumAccount' }); + setParam(block, 'group', { type: 'string', value: 'PremiumAccount' }); + setParam(block, 'ttl', { type: 'int', value: product.premiumDays! }); + setParam(block, 'goldCost', { type: 'int', value: product.goldCost! }); + } else if (product.kind === 'premium-gjn') { + setParam(block, 'onlinePurchase', { type: 'bool', value: true }); + setParam(block, 'alias', { type: 'string', value: 'PremiumAccount' }); + setParam(block, 'group', { type: 'string', value: 'PremiumAccount' }); + setParam(block, 'ttl', { type: 'int', value: product.premiumDays! }); + } else if (product.kind === 'vehicle-pack' && product.vehicle) { + setParam(block, 'onlinePurchase', { type: 'bool', value: true }); + setParam(block, 'aircraftGift', { type: 'string', value: product.vehicle.name }); + if (product.goldIncome) setParam(block, 'goldIncome', { type: 'int', value: product.goldIncome }); + } + + root.blocks.push(block); + } + return root; +} diff --git a/packages/local-service/src/store/store-page.ts b/packages/local-service/src/store/store-page.ts new file mode 100644 index 0000000..715ce80 --- /dev/null +++ b/packages/local-service/src/store/store-page.ts @@ -0,0 +1,326 @@ +/** + * Single-page HTML interface for the local web store (/store, implementation notes; + * implementation notes section G). All dynamic data comes from /store/api/* as JSON. + */ +export function renderStorePageHtml(): string { + return ` + + + + +War Thunder Offline — 本地商店 + + + +
+
WAR THUNDER OFFLINE 本地商店 · 切回游戏窗口自动同步档案
+
+ +
GJN 余额 0
+
金鹰 0
+
银狮 0
+
高级账户 未激活
+
+
+
+
+
+ + + + +
+
+ + + +
+
+ +
+ + +`; +} diff --git a/packages/local-service/src/store/store-purchase.ts b/packages/local-service/src/store/store-purchase.ts new file mode 100644 index 0000000..b5d0757 --- /dev/null +++ b/packages/local-service/src/store/store-purchase.ts @@ -0,0 +1,68 @@ +/** + * Store purchase rules: + * - buyGoldEntitlement: Golden-Eagle-priced entitlements (Premium Account days, Silver Lions packs) + * bought through cln_buy_entitlement; + * - buyGjnProduct: GJN-priced products (Golden Eagles packs, GJN Premium Account, vehicle packs) + * bought through item_purchase.php or the local web store. + */ +import type { BlkBlock } from '@wto/blk'; +import { addGoldenEagles, addSilverLions, balanceOf, canAfford, pay, payGjn } from '../profile/profile-currency.ts'; +import { extendPremiumAccount, hasEntitlement, recordEntitlementPurchase } from '../profile/profile-entitlements.ts'; +import { addOwnedVehicle, ownsVehicle } from '../profile/profile-hangar.ts'; +import { ACCEPTED, refused, type RuleOutcome } from '../research/rule-outcome.ts'; +import type { StoreCatalogue, StoreProduct } from './store-catalogue.ts'; + +export function buyGoldEntitlement( + profile: BlkBlock, + catalogue: StoreCatalogue, + entitlementId: string, + offeredGoldCost: number | undefined, + nowFiletime: bigint, +): RuleOutcome { + const product = catalogue.byId(entitlementId); + if (!product || product.goldCost === undefined) return refused('BAD_PARAMS'); + if (offeredGoldCost !== undefined && offeredGoldCost !== product.goldCost) return refused('PRICE_CHANGED'); + const price = { silverLions: 0, goldenEagles: product.goldCost }; + if (!canAfford(profile, price)) return refused('NOT_ENOUGH_MONEY'); + + pay(profile, price); + grantProductRewards(profile, product, nowFiletime); + return ACCEPTED; +} + +export type GjnPurchaseOutcome = + | { readonly ok: true } + | { readonly ok: false; readonly reason: 'NOT_FOUND' | 'ALREADY_BOUGHT' | 'NOT_ENOUGH_GJN' }; + +export function canBuyGjnProduct(profile: BlkBlock, product: StoreProduct, nowFiletime: bigint): boolean { + if (product.gjnCost === undefined) return false; + if (product.kind === 'vehicle-pack' && product.vehicle) { + return !ownsVehicle(profile, product.vehicle.name) && !hasEntitlement(profile, product.id, nowFiletime); + } + return true; +} + +export function buyGjnProduct(profile: BlkBlock, product: StoreProduct, nowFiletime: bigint): GjnPurchaseOutcome { + if (product.gjnCost === undefined) return { ok: false, reason: 'NOT_FOUND' }; + if (product.kind === 'vehicle-pack' && product.vehicle) { + if (ownsVehicle(profile, product.vehicle.name) || hasEntitlement(profile, product.id, nowFiletime)) { + return { ok: false, reason: 'ALREADY_BOUGHT' }; + } + } + if (balanceOf(profile).gjn < product.gjnCost) return { ok: false, reason: 'NOT_ENOUGH_GJN' }; + + payGjn(profile, product.gjnCost); + grantProductRewards(profile, product, nowFiletime); + return { ok: true }; +} + +function grantProductRewards(profile: BlkBlock, product: StoreProduct, nowFiletime: bigint): void { + if (product.id !== 'PremiumAccount') recordEntitlementPurchase(profile, product.id); + if (product.goldIncome) addGoldenEagles(profile, product.goldIncome); + if (product.silverIncome) addSilverLions(profile, product.silverIncome); + if (product.premiumDays) extendPremiumAccount(profile, product.premiumDays, nowFiletime); + if (product.vehicle) { + addOwnedVehicle(profile, product.vehicle.name); + for (const part of product.vehicle.parts) addOwnedVehicle(profile, part); + } +} diff --git a/packages/local-service/src/store/store-service.ts b/packages/local-service/src/store/store-service.ts new file mode 100644 index 0000000..9adec7b --- /dev/null +++ b/packages/local-service/src/store/store-service.ts @@ -0,0 +1,241 @@ +/** + * Store service (implementation notes; implementation notes): + * 1. Native yuplay2 store API on api.gaijinent.com: + * - POST /item_info.php (multi-guid and single-guid item pricing in GJN) + * - POST /item_purchase.php (pay=gjn purchase from in-game modals) + * - POST /redeem_code.php (ActivateAction redeem code) + * 2. Local web store at /store and /store/api/* for browsing vehicle packs, viewing GJN + * balance, purchasing with GJN, and redeeming codes. + */ +import type { Account, AccountStore } from '../accounts/account-store.ts'; +import { redactLoginForm } from '../login/form-redaction.ts'; +import { userIdFromJwt, userIdFromToken } from '../login/session-credentials.ts'; +import { yuplayAnswer } from '../login/yuplay-answer.ts'; +import type { PlayerProfiles } from '../profile/player-profiles.ts'; +import { balanceOf } from '../profile/profile-currency.ts'; +import { remainingPremiumDays } from '../profile/profile-entitlements.ts'; +import { serverTimeNow } from '../profile/server-time.ts'; +import type { Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts'; +import { redeemStoreCode, type RedeemOutcome } from './redeem-codes.ts'; +import type { StoreCatalogue, StoreProduct } from './store-catalogue.ts'; +import { renderStorePageHtml } from './store-page.ts'; +import { buyGjnProduct, canBuyGjnProduct, type GjnPurchaseOutcome } from './store-purchase.ts'; + +const STORE_API_PATHS = new Set(['/item_info.php', '/item_purchase.php', '/redeem_code.php']); + +export class StoreService implements Service { + readonly name = 'store'; + readonly #accounts: AccountStore; + readonly #profiles: PlayerProfiles; + readonly #catalogue: StoreCatalogue; + + constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: StoreCatalogue) { + this.#accounts = accounts; + this.#profiles = profiles; + this.#catalogue = catalogue; + } + + accepts(request: ServiceRequest): boolean { + if (request.path === '/store' || request.path.startsWith('/store/')) return true; + if (!STORE_API_PATHS.has(request.path)) return false; + return request.originalHost === undefined || request.originalHost === 'api.gaijinent.com' || request.originalHost === 'store.gaijin.net'; + } + + handle(request: ServiceRequest): ServiceResponse { + if (request.path === '/store' || request.path === '/store/') return this.#storePage(); + if (request.path === '/store/api/state' && request.method === 'GET') return this.#webState(request); + if (request.path === '/store/api/buy' && request.method === 'POST') return this.#webBuy(request); + if (request.path === '/store/api/redeem' && request.method === 'POST') return this.#webRedeem(request); + + const redacted = redactLoginForm(request.body); + const apiResponse = request.method !== 'POST' + ? yuplayAnswer('ERROR', {}, `${request.method} ${request.path} not supported`) + : request.path === '/item_info.php' + ? this.#itemInfo(request) + : request.path === '/item_purchase.php' + ? this.#itemPurchase(request) + : this.#redeemCode(request); + return { ...apiResponse, logNotes: { ...apiResponse.logNotes, redactedRequestBody: redacted, requestText: redacted } }; + } + + #itemInfo(request: ServiceRequest): ServiceResponse { + const form = new URLSearchParams(request.body.toString('utf8')); + const guids = [...form.getAll('guids[]'), ...form.getAll('guids'), ...form.getAll('guid')].filter(Boolean); + const account = this.#accountFromForm(form); + const profile = account ? this.#profiles.profileOf(account.userId) : undefined; + const now = serverTimeNow(); + + const items: Record = {}; + let numericId = 1; + for (const rawGuid of guids) { + const product = this.#catalogue.byGuid(rawGuid); + if (!product || product.gjnCost === undefined) continue; + const canBuy = profile ? canBuyGjnProduct(profile, product, now) : true; + items[rawGuid] = { + item_id: numericId++, + shop_price: product.gjnCost, + price_usd: product.gjnCost, + discount_mul: 1.0, + discount_till: 0, + title: product.title.en, + url: '', + short_desc: product.title.en, + shop_price_curr: 'gjn', + multi_purch: product.kind !== 'vehicle-pack', + can_be_bought: canBuy, + }; + } + return yuplayAnswer('OK', { items }, `item_info (${Object.keys(items).length}/${guids.length} items)`); + } + + #itemPurchase(request: ServiceRequest): ServiceResponse { + const form = new URLSearchParams(request.body.toString('utf8')); + const account = this.#accountFromForm(form); + if (!account) return yuplayAnswer('LOGINERROR', {}, 'item_purchase: unknown token'); + + const payMethod = (form.get('pay') ?? 'gjn').toLowerCase(); + if (payMethod !== 'gjn') return yuplayAnswer('BADPAYMENT', {}, `item_purchase: unsupported pay=${payMethod}`); + + const guid = form.get('guid') ?? ''; + const product = this.#catalogue.byGuid(guid); + if (!product) return yuplayAnswer('NOTFOUND', {}, `item_purchase: unknown guid ${guid}`); + + let outcome: GjnPurchaseOutcome = { ok: false, reason: 'NOT_FOUND' }; + const now = serverTimeNow(); + this.#profiles.updateWhen(account.userId, (saved) => { + outcome = buyGjnProduct(saved, product, now); + return outcome.ok; + }); + if (outcome.ok) return yuplayAnswer('OK', {}, `item_purchase ${product.id} (${product.gjnCost} GJN)`); + if (outcome.reason === 'NOT_ENOUGH_GJN') return yuplayAnswer('NOMONEY', {}, `item_purchase ${product.id}: insufficient GJN`); + if (outcome.reason === 'ALREADY_BOUGHT') return yuplayAnswer('ALREADY', {}, `item_purchase ${product.id}: already owned`); + return yuplayAnswer('NOTFOUND', {}, `item_purchase ${product.id}: not available`); + } + + #redeemCode(request: ServiceRequest): ServiceResponse { + const form = new URLSearchParams(request.body.toString('utf8')); + const account = this.#accountFromForm(form); + if (!account) return yuplayAnswer('LOGINERROR', {}, 'redeem_code: unknown token'); + + const code = form.get('code') ?? ''; + let outcome: RedeemOutcome = { ok: false, reason: 'INVALID_CODE', message: { en: '', zh: '' } }; + const now = serverTimeNow(); + this.#profiles.updateWhen(account.userId, (saved) => { + outcome = redeemStoreCode(saved, code, now); + return outcome.ok; + }); + if (outcome.ok) return yuplayAnswer('OK', {}, `redeem_code ${code} -> OK`); + return yuplayAnswer(outcome.reason === 'ALREADY_REDEEMED' ? 'ALREADY' : 'NOTFOUND', {}, `redeem_code ${code} -> ${outcome.reason}`); + } + + #storePage(): ServiceResponse { + return { + status: 200, + headers: { 'content-type': 'text/html; charset=utf-8' }, + body: renderStorePageHtml(), + logNotes: { summary: 'store web page' }, + }; + } + + #webState(request: ServiceRequest): ServiceResponse { + const requestedId = request.query.get('userId') ?? ''; + const account = (requestedId ? this.#accounts.byUserId(requestedId) : undefined) ?? this.#accounts.activeAccount(); + const now = serverTimeNow(); + const profile = account ? this.#profiles.profileOf(account.userId) : undefined; + const balance = profile ? balanceOf(profile) : { silverLions: 0, goldenEagles: 0, gjn: 0 }; + const premiumDays = profile ? remainingPremiumDays(profile, now) : 0; + + const products = this.#catalogue.allProducts() + .filter((product) => product.gjnCost !== undefined) + .map((product) => toWebProduct(product, profile ? !canBuyGjnProduct(profile, product, now) : false)); + + return jsonResponse({ + accounts: this.#accounts.all().map((entry) => ({ userId: entry.userId, login: entry.login, nick: entry.nick })), + activeUserId: account?.userId ?? '', + balance, + premiumDays, + products, + }, 'store web state'); + } + + #webBuy(request: ServiceRequest): ServiceResponse { + const body = parseJsonBody(request.body); + const userId = typeof body.userId === 'string' ? body.userId : ''; + const productId = typeof body.productId === 'string' ? body.productId : ''; + const account = this.#accounts.byUserId(userId); + const product = this.#catalogue.byId(productId); + if (!account || !product || product.gjnCost === undefined) { + return jsonResponse({ ok: false, message: '未找到账号或商品。' }, 'store web buy: invalid request'); + } + + let outcome: GjnPurchaseOutcome = { ok: false, reason: 'NOT_FOUND' }; + const now = serverTimeNow(); + this.#profiles.updateWhen(account.userId, (saved) => { + outcome = buyGjnProduct(saved, product, now); + return outcome.ok; + }); + if (outcome.ok) { + return jsonResponse({ ok: true, message: `已购买「${product.title.zh}」(花费 ${product.gjnCost} GJN)。切回游戏窗口即可自动刷新。` }, `store web buy ${product.id}`); + } + const msg = outcome.reason === 'NOT_ENOUGH_GJN' + ? `GJN 余额不足(需要 ${product.gjnCost} GJN,可在兑换码页使用 GJN 充值码或运行 save-cli --gjn)。` + : outcome.reason === 'ALREADY_BOUGHT' + ? '已拥有该礼包载具。' + : '该商品当前不可购买。'; + return jsonResponse({ ok: false, message: msg }, `store web buy ${product.id}: ${outcome.reason}`); + } + + #webRedeem(request: ServiceRequest): ServiceResponse { + const body = parseJsonBody(request.body); + const userId = typeof body.userId === 'string' ? body.userId : ''; + const code = typeof body.code === 'string' ? body.code : ''; + const account = this.#accounts.byUserId(userId); + if (!account) return jsonResponse({ ok: false, message: '请先在游戏内登录一个本地账号。' }, 'store web redeem: no account'); + + let outcome: RedeemOutcome = { ok: false, reason: 'INVALID_CODE', message: { en: '', zh: '无效的兑换码。' } }; + const now = serverTimeNow(); + this.#profiles.updateWhen(account.userId, (saved) => { + outcome = redeemStoreCode(saved, code, now); + return outcome.ok; + }); + return jsonResponse({ ok: outcome.ok, message: outcome.message.zh }, `store web redeem ${code.trim() || '(empty)'}`); + } + + #accountFromForm(form: URLSearchParams): Account | undefined { + const userId = userIdFromToken(form.get('token') ?? undefined) ?? userIdFromJwt(form.get('jwt') ?? undefined); + return (userId ? this.#accounts.byUserId(userId) : undefined) ?? this.#accounts.activeAccount(); + } +} + +function toWebProduct(product: StoreProduct, owned: boolean): Record { + return { + id: product.id, + kind: product.kind, + titleZh: product.title.zh, + titleEn: product.title.en, + gjnCost: product.gjnCost, + ...(product.goldIncome ? { goldIncome: product.goldIncome } : {}), + ...(product.premiumDays ? { premiumDays: product.premiumDays } : {}), + ...(product.vehicle ? { unitName: product.vehicle.name, country: product.vehicle.country, rank: product.vehicle.rank } : {}), + owned, + }; +} + +function parseJsonBody(raw: Buffer): Record { + try { + const parsed = JSON.parse(raw.toString('utf8')) as unknown; + return parsed && typeof parsed === 'object' ? (parsed as Record) : {}; + } catch { + return {}; + } +} + +function jsonResponse(payload: unknown, summary: string): ServiceResponse { + const body = JSON.stringify(payload); + return { + status: 200, + headers: { 'content-type': 'application/json; charset=utf-8' }, + body, + logNotes: { summary, responseText: body }, + }; +}