# 🧩 Paletools, Web App Extensions & Chrome MV3 Architecture Report

> **Target Scope:** EA Sports FC Web App (FC 24, FC 25, FC 26, FC 27)  
> **Status:** Canonical reference report for `@aphrody/fut` Extension & Injection Engineering  
> **Classification:** Browser Extensions, DOM Injection, Angular Hooking, Chrome Manifest V3, Anti-Detection  

---

## 1. Executive Summary & Ecosystem Anatomy

Third-party automation and enhancement on the official **EA Sports FC Ultimate Team Web App** is dominated by client-side browser extensions and userscripts. Unlike standalone backend bots that must independently solve EA's multi-layered CAS/SSO authentication, Cloudflare Turnstile challenges, and Arkose Labs FunCaptchas, **in-browser extensions** operate entirely inside an authenticated user session. By leveraging the existing session cookies, TLS fingerprints, and pre-loaded JavaScript runtime of the official web client, these tools achieve near-zero authentication overhead.

The open-source and community ecosystem is categorized into four architectural archetypes:

```
┌─────────────────────────────────────────────────────────────────────────────────────────────┐
│                            EA Web App Extension Archetypes                                  │
├──────────────────────┬──────────────────────┬──────────────────────┬────────────────────────┤
│ 1. Injected Suites   │ 2. Task Extensions   │ 3. Userscripts       │ 4. Off-Page Solvers    │
│    (Paletools)       │    (AutoPilot-SBC)   │    (FUT Enhancer)    │    (SbcCruncher)       │
├──────────────────────┼──────────────────────┼──────────────────────┼────────────────────────┤
│ - Dynamic Bookmarklet│ - Chrome MV3 Ext     │ - Tampermonkey / GM  │ - Next.js / Wasm       │
│ - Android Paledroid  │ - Side Panel / Popup │ - Direct DOM hooks   │ - Web Workers          │
│ - Global monkeypatch │ - Isolated + Main    │ - Legacy @grant none │ - Standalone Fodder    │
└──────────────────────┴──────────────────────┴──────────────────────┴────────────────────────┘
```

### Key Tools Profiled

1. **Paletools (by Paleta - `pale.tools`):**
   - **Market Position:** The most widely used FC Web App suite in the world (millions of active users).
   - **Distribution:** Dynamic bookmarklet (`javascript:(...)`), Tampermonkey userscript (`paletools.user.js`), and **Paledroid** (a modified Android APK patching the native WebView of the official Companion App).
   - **Capabilities:** Instant SBC template auto-filling, soft-ban mitigation, duplicate recycling, rapid sniping keyboard shortcuts, and FUTBIN price overlays.
2. **AutoPilot-SBC (`icysymmetra/AutoPilot-SBC`):**
   - **Architecture:** Clean Google Chrome Manifest V3 extension.
   - **Capabilities:** Automated multi-solve and sequence-based SBC execution using in-page data bridges.
3. **FUT Trade Enhancer (`ckalgos/fut-trade-enhancer`):**
   - **Architecture:** Historical reference userscript (1.5k+ stars) that established the baseline patterns for hooking EA's internal Angular controllers and injecting UI controls.
4. **SbcCruncher (`mabenj/SbcCruncher`):**
   - **Architecture:** Standalone web application (TypeScript / Next.js) executing combinatorial optimization algorithms in Web Workers to compute mathematically optimal squad rating matrices.

---

## 2. Injection Mechanisms & Execution Contexts

Interacting with the EA Web App requires code to read and manipulate internal JavaScript objects that only exist in the page's execution context.

```
┌────────────────────────────────────────────────────────────────────────────────┐
│                             Browser Execution Contexts                         │
│                                                                                │
│   ┌────────────────────────────────────────┐   ┌───────────────────────────┐   │
│   │          PAGE CONTEXT ("MAIN")         │   │   EXTENSION CONTEXT       │   │
│   │                                        │   │   ("ISOLATED WORLD")      │   │
│   │  window.services.Item                  │   │                           │   │
│   │  window.services.Club                  │   │  content-script.js        │   │
│   │  window.services.SBC                   │   │  chrome.runtime APIs      │   │
│   │  window.gAuthenticationModel           │   │  DOM access (shared)      │   │
│   │  Angular Components & ViewControllers  │   │  No window.services access│   │
│   └───────────────────▲────────────────────┘   └─────────────▲─────────────┘   │
│                       │                                      │                 │
│                       │   window.postMessage / CustomEvent   │                 │
│                       └──────────────────────────────────────┘                 │
└────────────────────────────────────────────────────────────────────────────────┘
```

### 2.1 The Isolated World Problem & Manifest V3 `"world": "MAIN"`

In Google Chrome's standard extension architecture, content scripts run in an **isolated world**. While they share the raw HTML DOM with the page, they maintain an entirely separate `window` global scope. Consequently:
* `window.services` is `undefined` inside standard content scripts.
* Directly calling EA service methods from an isolated content script fails.

#### The Modern Solution (Manifest V3 2024–2026):
Chrome 111+ introduced native declarative support for the main world in `manifest.json`:

```json
{
  "manifest_version": 3,
  "name": "Bxc FC Companion Engine",
  "version": "1.0.0",
  "content_scripts": [
    {
      "matches": ["https://www.ea.com/ea-sports-fc/ultimate-team/web-app/*"],
      "js": ["src/injected/bridge.js"],
      "run_at": "document_start",
      "world": "MAIN"
    },
    {
      "matches": ["https://www.ea.com/ea-sports-fc/ultimate-team/web-app/*"],
      "js": ["src/content/isolated-controller.js"],
      "run_at": "document_idle",
      "world": "ISOLATED"
    }
  ]
}
```

Alternatively, scripts can be dynamically registered or executed via the `chrome.scripting` API from a background Service Worker:

```javascript
// background.js (MV3 Service Worker)
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
  if (changeInfo.status === "complete" && tab.url?.includes("ultimate-team/web-app")) {
    await chrome.scripting.executeScript({
      target: { tabId },
      world: "MAIN",
      files: ["src/injected/ea-hooks.js"]
    });
  }
});
```

### 2.2 Content Security Policy (CSP) Bypass

The official EA Web App delivers restrictive HTTP security headers:
```http
Content-Security-Policy: default-src 'self' https://*.ea.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://*.ea.com https://*.google.com; connect-src 'self' https://*.ea.com https://*.futbin.com ...
```

This policy prevents bookmarklets or untrusted extensions from fetching remote scripts or contacting external APIs.

#### MV3 Solution: `declarativeNetRequest` Header Modification
In Chrome MV3, extensions bypass CSP by stripping or loosening response headers before the document is parsed by the browser:

```json
// manifest.json
{
  "permissions": ["declarativeNetRequest", "declarativeNetRequestWithHostAccess"],
  "host_permissions": ["*://*.ea.com/*"],
  "declarative_net_request": {
    "rule_resources": [
      {
        "id": "strip_csp_rules",
        "enabled": true,
        "path": "rules/csp-rules.json"
      }
    ]
  }
}
```

```json
// rules/csp-rules.json
[
  {
    "id": 1,
    "priority": 1,
    "action": {
      "type": "modifyHeaders",
      "responseHeaders": [
        { "header": "content-security-policy", "operation": "remove" },
        { "header": "content-security-policy-report-only", "operation": "remove" },
        { "header": "x-content-security-policy", "operation": "remove" }
      ]
    },
    "condition": {
      "urlFilter": "||ea.com/ea-sports-fc/ultimate-team/web-app/*",
      "resourceTypes": ["main_frame", "sub_frame"]
    }
  }
]
```

---

## 3. EA Web App Internal Hooks (`window.services`)

The EA FC Web App is a complex Single Page Application (built historically on AngularJS and updated into modern component-driven architectures). During bootstrapping, the application instantiates a singleton service container exposed globally on `window.services`.

Hooking into these services allows extensions to bypass DOM scraping entirely and directly execute business logic.

```
                                  ┌───────────────────────────┐
                                  │      window.services      │
                                  └─────────────┬─────────────┘
                                                │
         ┌───────────────────┬──────────────────┼───────────────────┬───────────────────┐
         ▼                   ▼                  ▼                   ▼                   ▼
   services.Item       services.Club      services.SBC        services.Store      services.PIN
   - searchMarket()    - search()         - loadSets()        - getPacks()        - sendEvent()
   - move()            - getStats()       - loadChallenge()   - openPack()        - (telemetry)
   - quickSell()       - clubDao          - submitChallenge() - unassigned
```

### 3.1 `services.Item` (Inventory & Market Operations)

Handles individual item lifecycles, player cards, consumables, and transfer market queries.

* **`services.Item.searchTransferMarket(filter, page)`**:
  Executes an authenticated transfer market query against the UTAS shard. Returns a `Promise` resolving to an array of auction items.
* **`services.Item.move(item, targetPile)`**:
  Moves an item between inventory piles:
  * `ItemPile.CLUB` (1)
  * `ItemPile.TRANSFER` (2)
  * `ItemPile.FREE_AGENT` (quick-sell/discard)
* **`services.Item.quickSell(item)`**:
  Discards an item for its base discard value in coins.
* **`services.Item.list(item, startingBid, buyNowPrice, duration)`**:
  Puts an item up for auction on the Transfer Market.
* **`services.Item.applyConsumable(playerItem, consumableItem)`**:
  Applies contracts, chemistry styles, or position modifiers.

#### Implementation Hook Example:
```javascript
// Hooking transfer market search to log or transform results
const originalSearch = window.services.Item.searchTransferMarket;
window.services.Item.searchTransferMarket = async function (filter, page) {
  console.log("[BXC-FUT] Market search intercepted:", filter);
  const result = await originalSearch.apply(this, arguments);
  // Post-process auctions: enrich with local price index or chemistry score
  window.dispatchEvent(new CustomEvent("bxc:market:results", { detail: result }));
  return result;
};
```

### 3.2 `services.Club` (Club Inventory & Storage)

Used to search and inspect players already owned by the user.

* **`services.Club.search(filter)`**:
  Searches the club's storage. Accepts criteria including `level` (gold, silver), `rarity`, `position`, `league`, `nation`, `club`, `untradeablesOnly`, `minRating`, `maxRating`.
* **`services.Club.getStats()`**:
  Returns total player counts, untradeable counts, and squad counts.
* **`services.Club.clubDao.resetStatsCache()`**:
  Flushes local memory caches, forcing fresh synchronization with the server.

### 3.3 `services.SBC` (Squad Building Challenges)

The core service powering SBC automation tools (Paletools, AutoPilot-SBC).

* **`services.SBC.loadSets()`**:
  Fetches all active SBC categories and sets (e.g. Live, Foundations, Upgrades).
* **`services.SBC.loadChallenges(setId)`**:
  Retrieves specific challenges within a set.
* **`services.SBC.loadChallenge(challengeId)`**:
  Retrieves challenge criteria (minimum rating, required chemistry, exact formations, nation/league restrictions) and current squad slot allocations.
* **`services.SBC.saveSquad(challengeId, squad)`**:
  Persists candidate player assignments to the server.
* **`services.SBC.submitChallenge(challengeId)`**:
  Finalizes and submits the squad, claiming the rewards pack or player pick.

### 3.4 `services.Store` (Packs & Unassigned Items)

* **`services.Store.requestUnassignedItems()`**:
  Returns cards currently in the "unassigned" limbo pile (e.g. after opening packs or buying items without sending them to the club).
* **`services.Store.openPack(packId)`**:
  Opens an existing pack and transitions to the pack animation screen.

### 3.5 `services.PIN` (Telemetry & Anti-Fraud Tracking)

EA tracks user interactions through the **PIN (Player Interface Network)** system.
* The Web App periodically sends telemetry batches (`page_view`, `search`, `click`, `drag_and_drop`, `duration`) to `https://pin-river.data.ea.com/pinEvents`.
* **Critical Finding:** Completely blocking or breaking `services.PIN` triggers backend fraud flags because legitimate players generate dozens of PIN events per minute.
* **Best Practice:** Ensure automated operations trigger standard UI events or leave `services.PIN.sendEvent` functional while executing automated tasks.

---

## 4. Chrome Extension Manifest V3 (MV3) Standards in 2026

Building a production-grade extension for EA FC in 2026 requires adhering to Google Chrome's strict Manifest V3 specifications.

```
┌────────────────────────────────────────────────────────────────────────────────────────┐
│                          Manifest V3 Architecture (2026)                               │
├────────────────────────────────────────────────────────────────────────────────────────┤
│                                                                                        │
│   ┌────────────────────────┐         WebSocket / Fetch        ┌────────────────────┐   │
│   │   Background Worker    │◄────────────────────────────────►│  External Engine   │   │
│   │   (service-worker.js)  │                                  │  (Bxc / Localhost) │   │
│   └───────────┬────────────┘                                  └────────────────────┘   │
│               │                                                                        │
│               │ chrome.runtime.connect (Keepalive Port)                                │
│               ▼                                                                        │
│   ┌────────────────────────┐         postMessage / Event      ┌────────────────────┐   │
│   │     Content Script     │◄────────────────────────────────►│   Page Context     │   │
│   │     (world: ISOLATED)  │                                  │   (world: MAIN)    │   │
│   └───────────┬────────────┘                                  └────────────────────┘   │
│               │                                                                        │
│               ▼                                                                        │
│   ┌────────────────────────┐                                                           │
│   │    Chrome Side Panel   │                                                           │
│   │   (chrome.sidePanel)   │                                                           │
│   └────────────────────────┘                                                           │
└────────────────────────────────────────────────────────────────────────────────────────┘
```

### 4.1 Side Panel API (`chrome.sidePanel`)

Rather than injecting intrusive floating modals into EA's complex CSS layout, modern extensions use Chrome's native **Side Panel API**.

```json
// manifest.json
{
  "permissions": ["sidePanel"],
  "side_panel": {
    "default_path": "sidepanel/index.html"
  }
}
```

```javascript
// background.js: open side panel automatically on EA Web App
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
  if (tab.url?.includes("ea.com/ea-sports-fc/ultimate-team/web-app")) {
    await chrome.sidePanel.setOptions({
      tabId,
      path: "sidepanel/index.html",
      enabled: true
    });
  }
});
```

### 4.2 Background Service Worker Keepalive Strategy

MV3 service workers terminate automatically after **30 seconds of inactivity**. Long-running market monitors or batch SBC solvers must prevent premature suspension.

#### Proven 2026 Keepalive Patterns:
1. **Long-Lived `chrome.runtime.connect` Port:**
   Maintaining an open message channel from an active Web App content script to the Service Worker resets the idle timer:
   ```javascript
   // content-script.js
   let port = chrome.runtime.connect({ name: "bxc-keepalive" });
   setInterval(() => {
     try {
       port.postMessage({ type: "PING" });
     } catch {
       port = chrome.runtime.connect({ name: "bxc-keepalive" });
     }
   }, 25000);
   ```
2. **Offscreen Documents API (`chrome.offscreen`):**
   If continuous background network connectivity (e.g. WebSocket to Bxc Engine) is required without any active tabs:
   ```javascript
   await chrome.offscreen.createDocument({
     url: "offscreen.html",
     reasons: [chrome.offscreen.Reason.WEB_SOCKETS],
     justification: "Maintain real-time market price feed connection"
   });
   ```

### 4.3 Direct Cookie Harvesting (`chrome.cookies.getAll`)

Instead of parsing browser storage via JavaScript, extensions with `cookies` permissions can query authentication tokens directly:

```javascript
// background.js
async function getEaAuthCookies() {
  const cookies = await chrome.cookies.getAll({ domain: "ea.com" });
  const playSession = cookies.find(c => c.name === "PLAY_SESSION")?.value;
  return { playSession, all: cookies };
}
```

---

## 5. EA Anti-Detection & Evasion Engineering

EA Sports deploys multi-tiered heuristics to detect non-human behavior on the Web App. Bypassing these filters requires strict behavioral engineering.

### 5.1 Throttling & Gaussian Jitter

Automated actions (such as searching the transfer market or moving cards) must never use constant intervals (e.g. exactly 1000ms). Fixed intervals are trivial to detect using standard time-series deviation analysis.

#### Gaussian Jitter Implementation:
```typescript
function gaussianRandom(mean: number, stdDev: number): number {
  let u = 0, v = 0;
  while (u === 0) u = Math.random();
  while (v === 0) v = Math.random();
  const z = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
  return Math.max(0, mean + z * stdDev);
}

export async function humanDelay(baseMs = 1500, stdDevMs = 350): Promise<void> {
  const delay = gaussianRandom(baseMs, stdDevMs);
  await new Promise((resolve) => setTimeout(resolve, delay));
}
```

### 5.2 Realistic Human Input Simulation

When interacting with DOM buttons (e.g., clicking "Search", "Buy Now", or "Confirm"):
* Never use raw `element.click()`. Many bot detectors check `event.isTrusted`.
* Generate sequential mouse events: `pointerdown` $\rightarrow$ `mousedown` $\rightarrow$ `pointerup` $\rightarrow$ `mouseup` $\rightarrow$ `click`.
* Displace the click coordinates randomly within the element's bounding rectangle rather than clicking $(0, 0)$ or the exact center:
  ```javascript
  function simulateRealisticClick(element) {
    const rect = element.getBoundingClientRect();
    const offsetX = rect.width * (0.2 + Math.random() * 0.6);
    const offsetY = rect.height * (0.2 + Math.random() * 0.6);
    const clientX = rect.left + offsetX;
    const clientY = rect.top + offsetY;

    const eventProps = { bubbles: true, cancelable: true, view: window, clientX, clientY };
    element.dispatchEvent(new MouseEvent("mousedown", eventProps));
    setTimeout(() => {
      element.dispatchEvent(new MouseEvent("mouseup", eventProps));
      element.dispatchEvent(new MouseEvent("click", eventProps));
    }, 40 + Math.random() * 80);
  }
  ```

### 5.3 Transfer Market Cache-Busting

When repeatedly checking prices for a player, querying the exact same filter (`maxb=15000`) repeatedly causes UTAS proxies to serve cached responses or flag query repetition.
* **Tactic:** Step the `minb` (minimum bid) back and forth between 150 and 200 on every search.
* This changes the query string hash, forcing fresh database evaluation without altering the target player pool.

### 5.4 Soft-Ban Handling & Arkose Labs Captcha Detection

* **Search Caps:** Enforce a maximum of 25 transfer market queries per 3-minute rolling window, followed by a mandatory 45-second idle cooldown.
* **Error Interception:** Intercept all UTAS HTTP responses:
  * **HTTP 429 / Error 458/512:** Soft-ban detected. Immediately suspend all automated queues, notify the user, and enforce an exponential backoff (starting at 15 minutes).
  * **Arkose Labs FunCaptcha:** If the Web App renders the FunCaptcha modal iframe, halt the extension immediately to allow manual human resolution.

---

## 6. Integration Architecture for `@aphrody/fut`

To unify these patterns into the `@aphrody/fut` monorepo, the following architecture is established:

```
┌─────────────────────────────────────────────────────────────────────────────────────────────┐
│                              @aphrody/fut Extension Bridge                                  │
├─────────────────────────────────────────────────────────────────────────────────────────────┤
│                                                                                             │
│  [ Web App (DOM & window.services) ]                                                        │
│           ▲                                                                                 │
│           │ Injected Hook Bridge (world: MAIN)                                              │
│           ▼                                                                                 │
│  [ Chrome Extension MV3 Content Script ]                                                    │
│           ▲                                                                                 │
│           │ Side Panel / Web Worker Keepalive                                               │
│           ▼                                                                                 │
│  [ Local Bxc Agent Engine (Bun / Rust Bridge) ]                                             │
│     ├── Exact SBC Solver (HiGHS Wasm / ILP)                                                 │
│     ├── Real-Time Market Valuation Index (SQLite / FTS5)                                    │
│     └── MCP Agent Interface (Natural Language Squad Building)                               │
└─────────────────────────────────────────────────────────────────────────────────────────────┘
```

1. **Manifest V3 Package (`packages/fut-extension`):**
   - Implements `declarativeNetRequest` for transparent CSP header removal.
   - Embeds content scripts targeting `"world": "MAIN"` to expose a standardized event bridge over `window.services`.
   - Uses Chrome's `sidePanel` API to render the `@aphrody/fut` companion UI directly beside the Web App.
2. **Event Bridge Protocol:**
   - Communication between the Web App and the Bxc Engine is routed through structured JSON messages (`BXC_SBC_SOLVE_REQUEST`, `BXC_MARKET_QUERY`).
3. **Hybrid Execution:**
   - Lightweight actions (squad slot assignments, quick listings) execute client-side via `window.services`.
   - Heavy computational workloads (MILP squad optimization, multi-league chemistry trees) offload to the local Bun/Rust engine via local WebSocket/HTTP.
