/** * External inventory HTTP service (`inventory-proxy-0{1,2}.gaijin.net/char`). * * Unlike CharService (which prepends the `0x69` uncompressed marker to binary BLK answers), * `charsq` (`0x459cac0 -> 0x459e020`) parses the raw HTTP body directly as UTF-8 JSON unless * it equals `"!OK"` or starts with `"!ERROR:"`. */ import type { Account, AccountStore } from '../accounts/account-store.ts'; import { userIdFromToken } from '../login/session-credentials.ts'; import type { PlayerProfiles } from '../profile/player-profiles.ts'; import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts'; import { signedInventoryJsonResponse } from './content-sign/content-signature.ts'; import { exchangeInventoryItems, type ExchangeItemDelta } from './inventory-rules.ts'; import { deltaToInventoryJson, parseExchangeItemsRequest, toInventoryJsonList } from './inventory-wire.ts'; import type { InventoryCatalogue } from './itemdef-catalogue.ts'; const INVENTORY_HOST = /^inventory-proxy-[a-z0-9-]+\.gaijin\.net$/; const TEXT_HEADERS = { 'content-type': 'text/plain; charset=utf-8' }; export class InventoryService implements Service { readonly name = 'inventory'; readonly #accounts: AccountStore; readonly #profiles: PlayerProfiles; readonly #catalogue: InventoryCatalogue; constructor(accounts: AccountStore, profiles: PlayerProfiles, catalogue: InventoryCatalogue) { this.#accounts = accounts; this.#profiles = profiles; this.#catalogue = catalogue; } accepts(request: ServiceRequest): boolean { return request.originalHost !== undefined && INVENTORY_HOST.test(request.originalHost); } handle(request: ServiceRequest): ServiceResponse { const action = headerOf(request, 'action') ?? ''; switch (action) { case 'GetInventory': return this.#getInventory(request); case 'GetItemDefsClient': return this.#getItemDefs(request); case 'GetItemPrices': return this.#getItemPrices(request); case 'GetItemDefChances': return this.#getItemDefChances(request); case 'ExchangeItems': return this.#exchangeItems(request); case 'CancelDelayedExchange': return signedInventoryJsonResponse({ response: { item_json: [] } }, 'CancelDelayedExchange -> 0 items'); default: return signedInventoryJsonResponse({ response: {} }, `${action || '(no action)'} -> empty response`); } } #getInventory(request: ServiceRequest): ServiceResponse { const account = this.#resolveAccount(request); if (!account) return errorResponse('UNAUTHORIZED', 'GetInventory: unknown account'); const items = toInventoryJsonList(this.#profiles.profileOf(account.userId), account.userId); return signedInventoryJsonResponse({ response: { item_json: items } }, `GetInventory -> ${items.length} stack(s)`); } #getItemDefs(request: ServiceRequest): ServiceResponse { const rawIds = headerOf(request, 'itemdefids') ?? ''; const language = headerOf(request, 'language') ?? 'english'; const ids = rawIds.split(',').map((part) => Number(part.trim())).filter((n) => Number.isSafeInteger(n) && n > 0); const defs = this.#catalogue.itemDefs(ids, language); return signedInventoryJsonResponse({ response: { itemdef_json: defs } }, `GetItemDefsClient (${defs.length} defs, lang=${language})`); } #getItemPrices(request: ServiceRequest): ServiceResponse { const currency = headerOf(request, 'currency') === 'WTE' ? 'WTE' : 'WTS'; const itemPrices = this.#catalogue.pricesForCurrency(currency); return signedInventoryJsonResponse({ response: { itemPrices } }, `GetItemPrices (${currency}) -> ${itemPrices.length} item(s)`); } #getItemDefChances(request: ServiceRequest): ServiceResponse { const rawId = headerOf(request, 'itemdefs') ?? ''; const generatorId = Number(rawId.trim()); const chances = Number.isSafeInteger(generatorId) ? this.#catalogue.chancesForGenerator(generatorId) : undefined; const response: Record = chances ? { [String(generatorId)]: chances } : {}; return signedInventoryJsonResponse({ response }, `GetItemDefChances (${generatorId}) -> ${chances?.length ?? 0} drop(s)`); } #exchangeItems(request: ServiceRequest): ServiceResponse { const account = this.#resolveAccount(request); if (!account) return errorResponse('UNAUTHORIZED', 'ExchangeItems: unknown account'); const parsed = parseExchangeItemsRequest(request.body.toString('utf8')); if (!parsed) return errorResponse('BAD_JSON', 'ExchangeItems: invalid JSON'); let delta: ExchangeItemDelta[] | undefined; let errorCode = 'EXCHANGE_FAILED'; this.#profiles.updateWhen(account.userId, (saved) => { const res = exchangeInventoryItems(saved, this.#catalogue, parsed.outputItemDefId, parsed.quantity, parsed.materials); if (!res.ok) { errorCode = res.code; return false; } delta = res.delta; return true; }); if (!delta) return errorResponse(errorCode, `ExchangeItems (${parsed.outputItemDefId}) -> ${errorCode}`); const jsonDelta = deltaToInventoryJson(delta, account.userId); return signedInventoryJsonResponse({ response: { item_json: jsonDelta } }, `ExchangeItems (${parsed.outputItemDefId} x${parsed.quantity}) -> ${jsonDelta.length} delta item(s)`); } #resolveAccount(request: ServiceRequest): Account | undefined { const uidHint = headerOf(request, 'uidhint'); if (uidHint) return this.#accounts.byUserId(uidHint); const token = headerOf(request, 'token'); const tokenUid = token ? userIdFromToken(token) : undefined; return tokenUid ? this.#accounts.byUserId(tokenUid) : undefined; } } function headerOf(request: ServiceRequest, name: string): string | undefined { const value = request.headers[name]; const text = Array.isArray(value) ? value[0] : value; return text ? text : undefined; } function errorResponse(code: string, summary: string): ServiceResponse { return { status: 200, headers: TEXT_HEADERS, body: `!ERROR:${code}`, logNotes: { summary } }; }