# EA Sports FC OAuth2 & Club Linking Architecture: FUTBIN, FUT.GG & BXC

> **Scope:** EA Sports FC (FC 25, FC 26, FC 27) Ultimate Team Authentication, Third-Party Account Linking, and Club Inventory Ingestion  
> **Package:** `@aphrody/fut` & Bxc Engine  
> **Status:** Production Architecture Specification

---

## 1. Executive Summary

A core feature of community platforms like **FUTBIN** and **FUT.GG** is the ability for players to **link their Ultimate Team club** to calculate:
- Total club coin value (Console & PC).
- Untradeable card inventory and fodder distribution (83, 84, 85, 86, 87, 88, 89, 90+).
- **0-Coin SBC Solver**: Automatically computing which active Squad Building Challenges (Icons, Heroes, Upgrades) the user can complete for free using cards already sitting in their club.
- Evolutions tracker: Tracking which club players fit active or leaked Evolutions.

This document breaks down the **two official architectures** used by FUTBIN and FUT.GG, and details how `@aphrody/fut` implements an equivalent, sovereign solution.

```mermaid
flowchart TD
    subgraph EA Infrastructure
        AUTH["EA Identity OAuth2 (accounts.ea.com)"]
        COMM_API["EA FC Community API (Partner Program)"]
        WEB_APP["EA FC Web App (ea.com/ea-sports-fc/.../web-app/)"]
        UTAS["UTAS Game Server (utas.mob.v2.prd.futc-ext.gcp.ea.com)"]
    end

    subgraph Third-Party Approaches
        FUTGG["FUT.GG (GG Club)"]
        FUTBIN["FUTBIN (Club Import Extension)"]
        PALE["Paletools / Userscript"]
    end

    subgraph BXC Native Solution
        BXC_HARVEST["BXC Cookie Harvester (Chromium SQLite)"]
        BXC_UTAS["EaUtasClient (Direct /ut/game/fc27/club)"]
        BXC_BM["BXC 1-Click Bookmarklet"]
        BXC_DB["FutDatabaseRepository (Local Club Inventory)"]
        BXC_SOLVER["SquadSolver (0-Coin SBC Auto-Craft)"]
    end

    AUTH -->|Partner OAuth 2.0| FUTGG
    COMM_API -->|Read-only Club Data| FUTGG

    WEB_APP -->|Injected Content Script| FUTBIN
    FUTBIN -->|Serialized Player IDs| FUTBIN_SRV["FUTBIN Backend"]

    WEB_APP -->|Active Session Hook| PALE

    BXC_HARVEST -->|X-UT-SID + PLAY_SESSION| BXC_UTAS
    BXC_BM -->|Export Club JSON| BXC_DB
    BXC_UTAS -->|Paging /club?count=50| BXC_DB
    BXC_DB --> BXC_SOLVER
```

---

## 2. Approach 1: The Official EA FC Community API (Used by FUT.GG)

### 2.1 The Mechanism
In mid-2024 (and expanded for FC 25–FC 27), EA Sports introduced the official **EA SPORTS FC Community API**. This program allows approved commercial partners (**FUT.GG**, **FUTBIN**, and **FUTWIZ**) to request read-only permissions on behalf of players.

### 2.2 The OAuth 2.0 Authorization Code Flow
```
User (Browser)               FUT.GG                       EA Identity (accounts.ea.com)
     │                           │                                      │
     │ 1. Click "Connect EA"     │                                      │
     │──────────────────────────>│                                      │
     │                           │ 2. Redirect to EA OAuth Login        │
     │<──────────────────────────│ (client_id=FUTGG_PARTNER&scope=...)  │
     │                                                                  │
     │ 3. User logs in & approves read consent on accounts.ea.com       │
     │─────────────────────────────────────────────────────────────────>│
     │                                                                  │
     │ 4. 302 Redirect with ?code=AUTHORIZATION_CODE                    │
     │<─────────────────────────────────────────────────────────────────│
     │                                                                  │
     │ 5. Forward auth code to callback URL                             │
     │──────────────────────────>│                                      │
     │                           │ 6. Exchange code for Access Token    │
     │                           │─────────────────────────────────────>│
     │                           │<─────────────────────────────────────│
     │                           │    { access_token, refresh_token }   │
     │                           │                                      │
     │                           │ 7. Query EA Community API            │
     │                           │    GET /community/v1/user/club       │
     │                           │    Header: Authorization: Bearer ... │
     │                           │─────────────────────────────────────>│
```

### 2.3 Key Technical Realities & Constraints
1. **Approval Process**: EA requires an enterprise legal contract, compliance review, and NDA to grant a `client_id` for the Community API. Unregistered developers cannot generate partner credentials.
2. **Strict Read-Only Scope**: The Community API permits reading club cards, active squads, and Evolutions. It **strictly forbids** transfer market operations (bidding, listing, buying).
3. **Privacy Advantage**: The user enters their EA password exclusively on `accounts.ea.com`. FUT.GG never sees or stores EA credentials.

---

## 3. Approach 2: Browser Extension & DOM Hooking (Used by FUTBIN)

### 3.1 The Mechanism ("FUTBIN Club Import")
Because the Community API was only recently introduced, FUTBIN historically built—and continues to offer—the **FUTBIN Club Import Extension** (available on the Chrome Web Store and Firefox Add-ons).

### 3.2 How the Extension Operates Inside the EA Web App
1. **Manifest Permissions**:
   ```json
   {
     "name": "FUTBIN Club Import",
     "permissions": ["storage"],
     "host_permissions": [
       "https://www.ea.com/ea-sports-fc/ultimate-team/web-app/*",
       "https://*.futbin.com/*"
     ]
   }
   ```
2. **Context Injection**:
   The extension injects a content script into the execution environment of `https://www.ea.com/ea-sports-fc/ultimate-team/web-app/`.
3. **Session Interception**:
   The EA Web App is an Angular application that keeps its active session in `sessionStorage` and global service singletons:
   ```javascript
   // Injected content script accesses the Web App's internal services
   const userClub = window.services.User.getUser().getClub();
   const authToken = window.sessionStorage.getItem("ut_session");
   ```
4. **Automated Pagination of Club Cards**:
   The script invokes the internal club service or issues requests with the active `X-UT-SID`:
   ```http
   GET /ut/game/fc27/club?count=90&offset=0&type=player HTTP/1.1
   Host: utas.mob.v2.prd.futc-ext.gcp.ea.com
   X-UT-SID: 98e4d3a2-11bc-4952-b1e0-67c2935401af
   ```
5. **Sync to FUTBIN**:
   Once all pages are collected, the extension strips unnecessary metadata (contracts, fitness) and sends a lightweight array of player IDs:
   ```json
   POST https://import.futbin.com/api/v1/club/sync
   Content-Type: application/json
   Authorization: Bearer <FUTBIN_USER_TOKEN>

   {
     "platform": "console",
     "items": [
       { "resourceId": 231747, "rating": 91, "untradeable": true },
       { "resourceId": 20801, "rating": 86, "untradeable": false }
     ]
   }
   ```

---

## 4. How BXC (`@aphrody/fut`) Implements Club Linking

`@aphrody/fut` provides a **triple-pipeline** offering complete autonomy without requiring proprietary EA partner credentials:

```
┌────────────────────────────────────────────────────────────────────────┐
│                      BXC Club Ingestion Tri-Mode                       │
├──────────────────────┬──────────────────────────┬──────────────────────┤
│ Mode 1: BXC Browser  │ Mode 2: 1-Click          │ Mode 3: Direct UTAS  │
│ Automation (CDP)     │ Bookmarklet / Script     │ Harvester            │
│ (Stealth Web App)    │ (No extension needed)    │ (Chromium Profile)   │
└──────────────────────┴──────────────────────────┴──────────────────────┘
```

### 4.1 Mode 1: 1-Click Bookmarklet / Userscript (`bxc fut ea bookmarklet`)
For users playing on standard Chrome/Edge/Firefox, BXC generates a portable JavaScript snippet that can be pasted into the browser address bar or console on the Web App:

```javascript
// BXC 1-Click Club Export Snippet
(async () => {
  const sid = sessionStorage.getItem("ut_session") || window.services?.User?.getUser()?._accessToken;
  const year = "27";
  const baseUrl = `https://utas.mob.v2.prd.futc-ext.gcp.ea.com/ut/game/fc${year}`;
  
  let offset = 0;
  const count = 90;
  const players = [];
  
  while (true) {
    const res = await fetch(`${baseUrl}/club?count=${count}&offset=${offset}&type=player`, {
      headers: { "X-UT-SID": sid, "Accept": "application/json" }
    });
    if (!res.ok) break;
    const data = await res.json();
    const items = data.itemData || [];
    if (items.length === 0) break;
    players.push(...items);
    offset += count;
  }
  
  const payload = JSON.stringify({ syncedAt: new Date().toISOString(), total: players.length, items: players });
  
  // Option A: Save to file club_inventory.json
  const blob = new Blob([payload], { type: "application/json" });
  const a = document.createElement("a");
  a.href = URL.createObjectURL(blob);
  a.download = "bxc_club_fc27.json";
  a.click();
})();
```

### 4.2 Mode 2: Native Chromium Cookie Harvester (`bxc fut native cookies`)
When the user has previously logged into the EA Web App in their local Chromium or Google Chrome browser:
1. `bxc` uses native Rust FFI (`bxc_harvest_chromium_cookies`) to decrypt the `PLAY_SESSION` and `osc` tokens from the local Chrome SQLite cookie store.
2. `EaUtasClient` loads these cookies and issues requests directly against `utas.mob.v2.prd.futc-ext.gcp.ea.com`.

### 4.3 Mode 3: Direct Ingestion & Local Database Synchronization
Once the club JSON is loaded:
- Ingested into SQLite (`packages/fut/src/data/fut_extracted_database.sqlite`) under the `user_club_inventory` table.
- Instantly cross-referenced with `SquadSolver`:
  ```bash
  bxc fut sbc list --my-club
  bxc fut sbc detail mbappe-potm --auto-solve-club
  ```
  Returns exact completion cost: e.g. **"Requires 45,000 coins (8 out of 9 squads completed with 100% untradeable club fodder!)"**.

---

## 5. Security & Risk Analysis

| Risk Vector | Browser Extension / Bookmarklet | Headless Botting (Password Prompt) | Official Community API |
| :--- | :--- | :--- | :--- |
| **Credential Safety** | 100% Safe (Password never handled) | High Risk (Password stored in plaintext) | 100% Safe (Handled by EA Identity) |
| **Account Ban Risk** | Near Zero (Passive read of club items) | Elevated if market botting / sniping | Zero (Authorized by EA) |
| **Maintenance Need** | Low (UTAS `/club` route is stable) | High (Akamai bot manager updates) | Low (Maintained by EA API team) |
| **Setup Friction** | Single drag-and-drop bookmarklet | Requires entering email, password & 2FA | One-click OAuth login |

---

## 6. Implementation Checklist for `@aphrody/fut`

- [x] Reverse-engineer EA OAuth & UTAS authentication specification.
- [x] Implement `EaUtasClient.getClubPlayers()` and `getClubAllPlayers()`.
- [x] Create `UtClubPlayerItem` and `ClubSyncSummary` types.
- [x] Create 1-click Web App export bookmarklet generator (`bxc fut ea bookmarklet`).
- [x] Add CLI commands: `bxc fut ea club` and `bxc fut ea sync <file.json>`.
- [x] Connect club inventory to `SquadSolver` for 0-coin SBC recommendations.
