/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { ImpersonatedClient } from "../../../../src/ffi/curl-impersonate.ts"; import type { UtAuctionItem, UtClubInventoryStats, UtClubPlayerItem, UtMarketSearchParams, UtasSessionConfig, } from "./types.ts"; export class EaUtasClient { private client: ImpersonatedClient; private config: UtasSessionConfig; private baseUtasUrl: string; constructor(config: UtasSessionConfig = {}) { this.config = config; const gameYear = config.gameYear ?? "27"; this.baseUtasUrl = `https://utas.mob.v2.prd.futc-ext.gcp.ea.com/ut/game/fc${gameYear}`; this.client = new ImpersonatedClient({ profile: "chrome131" }); this.loadStoredSession(); } private loadStoredSession(): void { const cookiePath = this.config.cookiesPath ?? join(import.meta.dir, "../cookies/ea.json"); if (existsSync(cookiePath)) { try { const raw = readFileSync(cookiePath, "utf-8"); const cookies = JSON.parse(raw); // Look for PLAY_SESSION and auth tokens const playSession = cookies.find( (c: any) => c.name === "PLAY_SESSION", )?.value; if (playSession && !this.config.sid) { // Session JWT present this.config.sid = playSession; } } catch { // Cookie loading fallback } } // Fallback to Rust FFI Chromium cookie harvest if session still not set if (!this.config.sid) { try { const { harvestEaChromiumCookies } = require("../recon/network.ts"); const harvested = harvestEaChromiumCookies(); if (harvested["PLAY_SESSION"]) { this.config.sid = harvested["PLAY_SESSION"]; } } catch { // Silent fallback } } } private getHeaders(): Record { const headers: Record = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", Origin: "https://www.ea.com", Referer: "https://www.ea.com/ea-sports-fc/ultimate-team/web-app/", Accept: "application/json", "Accept-Language": "en-US,en;q=0.9", }; if (this.config.sid) { headers["X-UT-SID"] = this.config.sid; } if (this.config.phishingToken) { headers["X-UT-PHISHING-TOKEN"] = this.config.phishingToken; } return headers; } /** * Direct Transfer Market Search against UTAS shard */ public async searchMarket( params: UtMarketSearchParams = {}, ): Promise { const query = new URLSearchParams(); query.set("type", params.type ?? "player"); if (params.defId) query.set("defId", String(params.defId)); if (params.maskedDefId) query.set("maskedDefId", String(params.maskedDefId)); if (params.lev) query.set("lev", params.lev); if (params.pos) query.set("pos", params.pos); if (params.nat) query.set("nat", String(params.nat)); if (params.leag) query.set("leag", String(params.leag)); if (params.team) query.set("team", String(params.team)); if (params.micr) query.set("micr", String(params.micr)); if (params.macr) query.set("macr", String(params.macr)); if (params.minb) query.set("minb", String(params.minb)); if (params.maxb) query.set("maxb", String(params.maxb)); query.set("num", String(params.num ?? 21)); query.set("start", String(params.start ?? 0)); const url = `${this.baseUtasUrl}/transfermarket?${query.toString()}`; const res = await this.client.fetch(url, { headers: this.getHeaders() }); if (res.status === 401 || res.status === 403) { throw new Error( `UTAS Authentication required (HTTP ${res.status}). Session token expired or not established.`, ); } if (res.status !== 200) { throw new Error(`UTAS transfermarket request failed: HTTP ${res.status}`); } const data = await res.json(); return (data.auctionInfo ?? []).map((a: any) => ({ tradeId: a.tradeId, assetId: a.itemData?.assetId ?? 0, rating: a.itemData?.rating ?? 0, itemType: a.itemData?.itemType ?? "player", rareflag: a.itemData?.rareflag ?? 0, preferredPosition: a.itemData?.preferredPosition ?? "", startingBid: a.startingBid ?? 0, currentBid: a.currentBid ?? 0, buyNowPrice: a.buyNowPrice ?? 0, expires: a.expires ?? 0, tradeState: a.tradeState ?? "active", })); } /** * Queries current user credit balance from UTAS */ public async getUserCredits(): Promise { const url = `${this.baseUtasUrl}/user/credits`; const res = await this.client.fetch(url, { headers: this.getHeaders() }); if (res.status === 401 || res.status === 403) { throw new Error("UTAS Authentication required. Valid X-UT-SID is needed."); } const data = await res.json(); return data.credits ?? 0; } /** * Ingests and inspects club status */ public async getClubInventoryStats(): Promise { const credits = await this.getUserCredits().catch(() => 0); return { totalItems: 0, credits, tradepileCount: 0, watchlistCount: 0, }; } /** * Public CDN Static Dictionary fetch (No Auth Required) */ public async fetchPublicCdnDictionary( dictionaryType: "players" | "teams" | "nations" | "leagues", buildGuid: string = "FFA27PCC", ): Promise { const url = `https://fifa21.content.easports.com/fifa/fltOnlineAssets/${buildGuid}/2027/fut/items/web/${dictionaryType}.json`; const res = await this.client.fetch(url); if (res.status !== 200) { throw new Error(`Failed to fetch EA CDN ${dictionaryType}.json: HTTP ${res.status}`); } return await res.json(); } /** * Paginates through club players from UTAS */ public async getClubPlayers( offset: number = 0, count: number = 50, ): Promise { const url = `${this.baseUtasUrl}/club?count=${count}&offset=${offset}&type=player`; const res = await this.client.fetch(url, { headers: this.getHeaders() }); if (res.status === 401 || res.status === 403) { throw new Error( `UTAS Authentication required (HTTP ${res.status}). Session token expired or not established.`, ); } if (res.status !== 200) { throw new Error(`UTAS club request failed: HTTP ${res.status}`); } const data = await res.json(); return (data.itemData ?? []).map((it: any) => ({ id: it.id, assetId: it.assetId, resourceId: it.resourceId, rating: it.rating, itemType: it.itemType ?? "player", rareflag: it.rareflag ?? 0, preferredPosition: it.preferredPosition ?? "", possiblePositions: it.possiblePositions ?? [], nation: it.nation ?? 0, leagueId: it.leagueId ?? 0, teamid: it.teamid ?? 0, untradeable: it.untradeable ?? false, discardValue: it.discardValue ?? 0, owners: it.owners ?? 1, playStyle: it.playStyle, cardsubtypeid: it.cardsubtypeid, })); } /** * Fetches full club by paginating until empty */ public async getClubAllPlayers(maxCount: number = 2000): Promise { const allPlayers: UtClubPlayerItem[] = []; let offset = 0; const pageSize = 90; while (offset < maxCount) { const batch = await this.getClubPlayers(offset, pageSize); if (batch.length === 0) break; allPlayers.push(...batch); if (batch.length < pageSize) break; offset += pageSize; } return allPlayers; } }