# Technical Documentation: daijro/camoufox

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/daijro/camoufox)

### Overview (`README.md`)

<p align="center">
  <img src="browser/assets/CamoufoxLogo.svg" alt="Camoufox" width="160">
</p>

<h1 align="center">Camoufox</h1>

<h4 align="center">Camoufox is an open source anti-detect browser built for webscraping & AI agents. 🦊</h4>

<div align="center">
  <a href="https://trendshift.io/repositories/12224" target="_blank">
    <img src="https://trendshift.io/api/badge/repositories/12224" alt="daijro%2Fcamoufox | Trendshift" width="250" height="55"/>
  </a><br>
  <a href="https://pepy.tech/projects/camoufox"><img src="https://static.pepy.tech/personalized-badge/camoufox?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads" alt="Total Downloads"</a>
  <a href="https://pepy.tech/projects/camoufox"><img src="https://static.pepy.tech/personalized-badge/camoufox?period=monthly&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads%2Fmonth" alt="Monthly Downloads"></a>
    <a href="https://pepy.tech/projects/camoufox"><img src="https://static.pepy.tech/personalized-badge/camoufox?period=weekly&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads%2Fweek" alt="Weekly Downloads"></a>
</div>

---

> [!NOTE]
> **All of the latest documentation is available at [camoufox.com](https://camoufox.com).**

---

# Sponsors

<details open id="sponsors">
<summary>View/Collapse All</summary>

## Premium

<table>
  <tr>
    <td width="25%" align="center" valign="middle">
      <a href="https://go.nodemaven.com/camoufoxreadmeoctober" target="_blank">
        <img width="380" alt="nodemaven" src="https://github.com/user-attachments/assets/3bc942c9-c031-466c-a2a4-3859c3e54721"/>
      </a>
    </td>
    <td valign="middle">
      <a href="https://go.nodemaven.com/camoufoxreadmeoctober">NodeMaven</a>: The most efficient proxy provider for Web Scrapping and Automation with the Highest Quality IP on the market.<br>
      <strong>Why <a href="https://go.nodemaven.com/camoufoxreadmeoctober">NodeMaven</a>?</strong><br>
      • 99.9% uptime<br>
      • ZIP Targeting<br>
      • IP filtering: all proxies have fraud score <97%<br>
      • No KYC required<br>
      • Unique free tools: Proxy Bandwidth Checker, Meta Tag Checker, IP Lookup and others!<br>
      <strong>Special codes for Camoufox users:</strong><br>
      • <code>CAMOUFOX35</code> - 35% off to Mobile and Residential Proxies<br>
      • <code>CAMOUFOX40</code> - 40% off to ISP (Static) Proxies<br>
      • <code>CAMOUFOX2X</code> - 2X traffic for Black Friday<br>
      Check Nodemaven's new GitHub for more web scraping and automation solutions - https://github.com/nodemaven
    </td>
  </tr>
  <tr>
    <td width="25%" align="center" valign="middle">
      <a href="https://node-proxy.com/?c=6P8Z23" target="_blank">
        <img width="380" alt="nodeproxy" src="https://github.com/user-attachments/assets/c25b50a7-cd7d-49ee-bfc1-3b3671ff55ed" />
      </a>
    </td>
    <td valign="middle">
      <strong>Need proxies for Camoufox?</strong><br>
      Use <strong><a href="https://node-proxy.com/?c=6P8Z23">Node Proxy</a></strong> — a provider of <strong>datacenter, residential and mobile proxies</strong> offering high speed, security and near-100% uptime. <strong>Fully tested and supported in Camoufox.</strong><br>
      <strong>What sets them apart from other providers</strong><br>
      • 90+ IP score<br>
      • HTTP + SOCKS5 — multiprotocol support<br>
      • Discounts for retail customers<br>
      • Full B2B support<br>
      • Ethically sourced IP addresses<br>
      • Special terms for Enterprise clients<br>
     <strong>Want to support Camoufox?</strong><br>
     Just use my promo code <strong><code>CAMOUFOX</code></strong> — it gets you a <strong>30% discount</strong> and supports the developer at the same time.<br>
     <strong><a href="https://node-proxy.com/?c=6P8Z23">Get started at node-proxy.com →</a></strong>
    </td>
  </tr>
  <tr>
    <td width="25%" align="center" valign="middle">
      <a href="https://byteful.com/?utm_source=github&utm_medium=github-sponsor&utm_campaign=camoufox_github_website_sponsor" target="_blank">
        <img width="380" alt="byteful" src="https://github.com/user-attachments/assets/33ae9e58-7c6d-44e9-a898-8baa1987df3b"/>
      </a>
    </td>
    <td valign="middle">
      <a href="https://byteful.com/?utm_source=github&utm_medium=github-sponsor&utm_campaign=camoufox_github_website_sponsor">Byteful</a> is a UK-based web data infrastructure platform that provides ethically sourced residential, mobile, static residential (ISP) and datacenter proxies alongside API-first tools for web scraping, data collection, and AI-driven automation.

Processing tens of billions of requests per month for thousands of customers, Byteful powers browser-based AI agents, automation systems, and data workflows. It is a member of the Internet Watch Foundation and the Ethical Web Data Collection Initiative.

Get 10% off Byteful Residential Bandwidth with the code: CAMOUFOX10
    </td>
  </tr>
  <tr>
    <td width="25%" align="center" valign="middle">
      <a href="https://layer3intel.com/?utm_source=github&utm_medium=sponsoring&utm_campaign=camoufox" target="_blank">
        <img width="380" alt="layer3" src="https://github.com/user-attachments/assets/891ca706-f3a6-4583-81c9-a5e4f6fef80d"/>
      </a>
    </td>
    <td valign="middle">
      <strong><a href="https://layer3intel.com/?utm_source=github&utm_medium=sponsoring&utm_campaign=camoufox">Layer3 Intel</a> | See your proxies the way anti-bots see them</strong><br>
      Camoufox hides your browser. Your proxy IP is the part it can't hide. Layer3 Intel is the residential proxy detection engine used to catch proxy traffic — check whether the IPs your provider sells you are clean, or already known and flagged.<br>
      • 🔍 Live threat score for any IP<br>
      • 🗂️ Proxy pool membership - identify IP resellers<br>
      • 📡 70M+ residential, mobile & ISP proxy IPs tracked across 200+ providers<br>
      • ⚡ <40ms API responses — vet IPs inline before your scraper uses them<br>
      Check your IPs: <a href="https://layer3intel.com/?utm_source=github&utm_medium=sponsoring&utm_campaign=camoufox">https://layer3intel.com</a>
    </td>
  </tr>
  <tr>
    <td width="25%" align="center" valign="middle">
      <a href="https://niuproxy.com/?utm_source=camoufox&utm_medium=camoufox&ref=camoufox" target="_blank">
        <img width="380" alt="NiuProxy" src="https://github.com/user-attachments/assets/85dc8020-af1b-4c5d-82a0-6024ce54903b"/>
      </a>
    </td>
    <td valign="middle">
      🚀 <strong>NiuProxy — Exclusive Camoufox Offer | 20% OFF</strong><br>
      🔥 Special Prices with Code camoufox80:<br>
      • Static Native ISP — $4.80/IP<br>
      • Residential 1TB — $0.44/GB<br>
      • Residential 10TB — $0.30/GB<br>
      🎁 <strong>Use camoufox80 for 20% OFF all recharges!</strong><br>
      👉 <a href="https://niuproxy.com/?utm_source=camoufox&utm_medium=camoufox&ref=camoufox">Visit NiuProxy<a>
    </td>
  </tr>
</table>

## Tools & Services
  
<table>
  <tr>
    <td width="25%" align="center" valign="middle">
      <a href="https://scrapfly.io/?utm_source=github&utm_medium=sponsoring&utm_campaign=camoufox" target="_blank">
        <img src="https://raw.githubusercontent.com/daijro/camoufox/main/browser/assets/scrapfly.png" alt="Scrapfly.io" width="200">
      </a>
    </td>
    <td valign="middle">
      <a href="https://scrapfly.io/?utm_source=github&utm_medium=sponsoring&utm_campaign=camoufox">Scrapfly</a> is an enterprise-grade solution providing Web Scraping API that aims to simplify the scraping process by managing everything: real browser rendering, rotating proxies, and fingerprints (TLS, HTTP, browser) to bypass all major anti-bots. Scrapfly also unlocks the observability by providing an analytical dashboard and measuring the success rate/block rate in detail.
    </td>
  </tr>
  <tr>
    <td width="25%" align="center" valign="middle">
      <a href="https://cloverlabs.ai/?utm_source=github&utm_medium=sponsoring&utm_campaign=camoufox" target="_blank">
        <img src="https://i.imgur.com/I3oe7xG.jpeg" alt="cloverlabs.ai" width="300">
      </a>
    </td>
    <td valign="middle">
      <a href="https://cloverlabs.ai/?utm_source=github&utm_medium=sponsoring&utm_campaign=camoufox">Clover Labs</a> is a Toronto based venture studio building AI agents for growth and distribution.
    </td>
  </tr>
  <tr>
    <td width="25%" align="center" valign="middle" height="100">
      <a href="https://serpapi.com/use-cases/web-search-api?utm_source=camoufox" target="_blank">
        <img width="350" alt="color horizontal" src="https://github.com/user-attachments/assets/cdf90178-869e-4f85-8288-3fe32da319d9"/>
      </a>
    </td>
    <td valign="middle">
      <a href="https://serpapi.com/use-cases/web-search-api?utm_source=camoufox">SerpApi, a web search API</a> to scrape Google and other search engines with a simple API.
    </td>
  </tr>
  <tr>
    <td width="25%" align="center" valign="middle" height="100">
      <a href="https://crawlbase.com/?utm_source=github&utm_medium=sponsorship&utm_campaign=camoufox" target="_blank">
        <img width="350" alt="color horizontal" src="https://github.com/user-attachments/assets/5c515090-86c2-4c76-b7b2-6e0b393594d5"/>
      </a>
    </td>
    <td valign="middle">
      <strong>Web data that survives the anti-bots.</strong><br>
      <a href="https://crawlbase.com/?utm_source=github&utm_medium=sponsorship&utm_campaign=camoufox">Crawlbase</a> gives developers and AI teams reliable data at scale: a 99% success-rate Crawler, Crawling API, Smart AI Proxies, and Web MCP Server that get through, so your scrapers and agents don't break. You build, we handle the infrastructure.

<strong>Get 15% off your first 3 months with code CAMOUFOX</strong> → <a href="https://crawlbase.com/?utm_source=github&utm_medium=sponsorship&utm_campaign=camoufox">crawlbase.com</a>
    </td>
  </tr>
  <tr>
    <td width="25%" align="center" valign="middle">
      <a href="https://scrappey.com/?utm_source=camoufox&utm_medium=sponsorship&utm_campaign=camoufox_sponsorship" target="_blank">
        <img width="380" alt="scrappey" src="https://github.com/user-attachments/assets/11b51db9-29c2-4ae9-a568-7466a5941c96"/>
      </a>
    </td>
    <td valign="middle">
      <a href="https://scrappey.com/?utm_source=camoufox&utm_medium=sponsorship&utm_campaign=camoufox_sponsorship">Scrappey</a> is a Web Scraping API that only charges successful scrapes with pay as you go - no subscriptions. Scrape complex sites. Residential proxies included, no hidden proxy fees, or expiring balances. One API for direct HTTP, full-browser rendering, JavaScript-heavy pages, screenshots, sessions, 30+ browser actions and 200+ concurrent sessions at a time - trusted by 1000+ developers and AI agents. Get 10% off with code CAMOUFOX.
    </td>
  </tr>
  <tr>
    <td width="25%" align="center" valign="middle">
      <a href="https://cloro.dev/?utm_source=referral&utm_medium=camoufox" target="_blank">
        <img width="380" alt="Cloro" src="https://github.com/user-attachments/assets/6dce6615-9733-43e3-8c6d-8d3bfb1aa7c7" />
      </a>
    </td>
    <td valign="middle">
      <a href="https://cloro.dev/?utm_source=referral&utm_medium=camoufox">Cloro</a> is a SERP and AI search API. Get structured results from Google, ChatGPT, Perplexity, Gemini, Copilot and Grok.
    </td>
  </tr>
</table>

## Proxy Providers

Camoufox is intended to be used with rotating proxies (preferably residential IPs). Check out these providers:

<table>
  <tr>
    <td width="25%" align="center" valign="middle">
      <a href="https://www.rapidproxy.io/?ref=daijro" target="_blank">
        <img width="380" alt="rapidproxy" src="https://github.com/user-attachments/assets/140337e0-50d5-452d-8a31-86c6b1761e47"/>
      </a>
    </td>
    <td valign="middle">
      <a href="https://www.rapidproxy.io/?ref=daijro">RapidProxy</a> - Power Your Data with Premium Proxies.<br>
      🎁 Try proxies for free  + Use code <strong>RAPID10</strong> for <strong>10% OFF</strong>
      <br>
      <strong>Why Choose RapidProxy?</strong><br>
      • 🌍 90M+ IPs in 200+ countries & regions<br>
      • ♾️ No expiration on traffic — use anytime, no pressure<br>
      • 🔥 Unlimited concurrency for maximum performance<br>
      • 💰 Starting from just &#36;0.65/GB — built for scale<br>
      • 📍 City-level targeting for precise geo access<br>
      • 🔄 Flexible session control tailored to your needs<br>
      Don’t miss out — start your free trial today and experience fast, stable, and scalable proxy performance with <a href="https://www.rapidproxy.io/?ref=daijro">RapidProxy</a>.
    </td>
  </tr>
  <tr>
    <td width="25%" align="center" valign="middle">
      <a href="https://www.swiftproxy.net/?ref=daijro" target="_blank">
        <img width="380" alt="swiftproxy" src="https://github.com/user-attachments/assets/2f351c5e-f128-4478-83ff-46a261bea221"/>
      </a>
    </td>
    <td valign="middle">
      <a href="https://www.swiftproxy.net/?ref=daijro">Swiftproxy</a> - <strong>High-Performance Residential Proxies for Scalable Data Collection</strong><br>
      Built for developers who need <strong>reliable</strong>, anti-detection proxy infrastructure. Swiftproxy delivers stable connections, high success rates, and flexible control for large-scale scraping and automation.<br>
      • 🌍 195+ locations with ethically sourced residential IPs<br>
      • 🔄 <strong>Rotating</strong> & <strong>sticky</strong> sessions with precise geo-targeting<br>
      • ⚡ Optimized for <strong>anti-ban</strong> & <strong>high success rate</strong><br>
      • 🔌 HTTP / HTTPS / SOCKS5 support<br>
      • 🧪 <strong>Free 500MB trial</strong> for testing<br>
      • 💸 <strong>Special discount</strong> code for Camoufox users: <strong>PROXY90 - 10%</strong><br>
      Best for: Web scraping, automation, multi-accounting, and large-scale data extraction
    </td>
  </tr>     
  <tr>
    <td width="25%" align="center" valign="middle">
      <a href="https://mangoproxy.com/prod-isp-static/?utm_source=daijro&utm_medium=partner&utm_campaign=daijro_github" target="_blank">
        <img width="380" alt="mangoproxy" src="https://github.com/user-attachments/assets/c2cd3ddf-c940-4906-be1b-5505dcdb6e06"/>
      </a>
    </td>
    <td valign="middle">
      <a href="https://mangoproxy.com/prod-isp-static/?utm_source=daijro&utm_medium=partner&utm_campaign=daijro_github">MangoProxy</a> is a Residential, ISP, Mobile and Datacenter proxy service designed for professional tasks where stability, speed, and anonymity matter.<br>
      Use code DAIJRO for 8% OFF ISP Static Proxies
    </td>
  </tr>
  <tr>
    <td width="25%" align="center" valign="middle">
      <a href="https://proxidize.com/?utm_source=github&utm_medium=sponsorship&utm_campaign=camoufox&utm_content=daijro" target="_blank">
        <img width="380" alt="proxidize" src="https://imagedelivery.net/r4caA8hJ3Ww3j8uyC_NNCA/95a9137a-43fd-48d4-7243-983f3f4a3d00/public"/>
      </a>
    </td>
    <td valign="middle">
      <strong><a href="https://proxidize.com/?utm_source=github&utm_medium=sponsorship&utm_campaign=camoufox&utm_content=daijro">Proxidize</a> | Mobile and Residential Proxies for Camoufox</strong><br>
      Running Camoufox at scale? Your browser setup is only half the stack. Your proxy layer matters too.<br>
      Proxidize provides mobile and residential proxies built for scraping, browser automation, SEO monitoring, AI agents, and data collection workflows.<br>
      <strong>Why Proxidize?</strong><br>
      • Real 4G and 5G mobile proxies<br>
      • Residential proxies in 195+ countries<br>
      • Rotating and sticky sessions<br>
      • City-level and carrier targeting<br>
      • Unlimited concurrency<br>
      • HTTP(S), SOCKS5, and UDP over SOCKS support<br>
      • No hardware or DIY setup required<br>
      Built for teams that need reliable proxy infrastructure without managing devices, servers, or proxy rotation themselves.<br>
      <strong>Special offer for Camoufox users</strong>: Use code <strong>CAMOUFOX20</strong> for <strong>20% off</strong>.<br>
      Start now: <a href="https://proxidize.com/?utm_source=github&utm_medium=sponsorship&utm_campaign=camoufox&utm_content=daijro">https://proxidize.com</a>
    </td>
  </tr>
  <tr>
    <td width="25%" align="center" valign="middle">
      <a href="https://www.thordata.com/?ls=dcx&lk=dcx" target="_blank">
        <img width="380" alt="Thordata" src="https://github.com/user-attachments/assets/0476bd5a-0063-4c31-8dc2-d3f982d58e6c"/>
      </a>
    </td>
    <td valign="middle">
      <b>Camoufox × Thordata</b><br>
      <b>Real Residential IPs and Web Data APIs for AI Agents and Automation</b><br>
      Power your Camoufox workflows with <strong>100M+ residential IPs across 190+ countries</strong>. Use precise geo and network targeting to run scraping, testing, and browser automation from the locations you need.<br>
      • 🔄 <strong>Rotating and sticky sessions</strong><br>
      • ⚡ <strong>Unlimited concurrent sessions</strong> for large-scale crawling<br>
      • 🌍 <strong>Location and network targeting</strong> for reliable regional access<br>
      • 🖥️ <strong>Web Data APIs:</strong> Use Webpage for rendered page access, Web Scraper API for structured extraction, or SERP API for real-time search results<br>
      <b>Exclusive offer for Camoufox users<br>
      Get free trial traffic after signup and use code <strong><code>CAMOUFOX</code></strong> for <strong>10% off</strong>.<br>
      <strong><a href="https://www.thordata.com/?ls=dcx&lk=dcx" target="_blank">Start your free trial with Thordata →</a></strong>
    </td>
  </tr>
  <tr>
    <td width="25%" align="center" valign="middle">
      <a href="https://www.webshare.io/" target="_blank">
        <img width="380" alt="Webshare" src="https://github.com/user-attachments/assets/b2af0630-bfa9-4f59-a074-d2162a2c8913"/>
      </a>
    </td>
    <td valign="middle">
      <strong><a href="https://www.webshare.io/">Webshare</a></strong> gives you instant access to a proxy pool of 80M+ ethically-sourced IPs across 195+ countries, with rotating residential, static ISP, and datacenter options plus a full API. It includes a 100+ Gbps backbone, country/city/state/ZIP/ASN-level targeting, and requires no credit card to start.<br>
      🏷️ Get <strong>20% OFF your first purchase</strong> with promo code <strong><code>CAMOUFOX20</code></strong>
  </tr>
  <tr>
    <td width="25%" align="center" valign="middle">
      <a href="https://okkproxy.com/?utm_source=camoufox&utm_medium=camoufox&ref=camoufox" target="_blank">
        <img width="380" alt="OkkProxy" src="https://github.com/user-attachments/assets/15df1ca6-bd84-4eee-9ed3-963bf343a021"/>
      </a>
    </td>
    <td valign="middle">
      👉 <strong><a href="https://okkproxy.com/?utm_source=camoufox&utm_medium=camoufox&ref=camoufox">Get Started with OkkProxy</a></strong><br>
      🚀 <strong>🔥 Static ISP Proxy Deals</strong><br>
      • Broadcast IP — from $1.50/IP<br>
      • Premium Native IP — from $4.50/IP<br>
      🔥 <strong>Unlimited Residential Proxies — from $58/day</strong><br>
      <strong>🎁 Use PAY2 for 10% OFF all recharges!</strong><br>
      Also available: Rotating Residential and Mobile Proxies.<br>
      👉 <a href="https://okkproxy.com/?utm_source=camoufox&utm_medium=camoufox&ref=camoufox">Visit OkkProxy<a>
    </td>
  </tr>
</table>
</details>

---

# Introduction

Camoufox is a Firefox build for web scraping and AI agents. Every launch gets a
fresh, internally consistent device identity drawn from the real-world
distribution of devices, and the browser reports it from C++, so a page sees
native values rather than JavaScript overrides. Playwright drives it, through
an automation layer the page cannot see.

| Package | Install | Docs |
|---|---|---|
| Python ([PyPI](https://pypi.org/project/camoufox/)) | `pip install -U "camoufox[geoip]"` | [Python driver README](https://github.com/CamouBrowser/camoucore/blob/main/python/camoufox/docs/README.md) |
| TypeScript / Node.js ([npm](https://www.npmjs.com/package/camoufox)) | `npm install camoufox playwright-core` | [TypeScript driver README](https://github.com/CamouBrowser/camoucore/blob/main/typescript/camoufox/docs/README.md) |
| AI coding agents | | [`AGENTS.md`](AGENTS.md#using-camoufox) |

This repository builds the browser. The drivers that launch it, the Python
and TypeScript launchers, are developed in
[CamouBrowser/camoucore](https://github.com/CamouBrowser/camoucore) and
published there in the one `camoucore` package, as `camoucore.camoufox` (npm:
`camoucore/camoufox`); report driver bugs
[there](https://github.com/CamouBrowser/camoucore/issues). The `camoufox`
packages on PyPI and npm are released from this repository: each is that
launcher under the `camoufox` name, pins one exact `camoucore` and records the
browser release it was tested with (`camoufox_pin/browser-pin.json`), so
`import camoufox` and the `camoufox` command are camoucore's, and `camoufox
fetch` installs that browser.

## Quick start

```bash
pip install -U "camoufox[geoip]"
camoufox fetch
```

```python
from camoufox.sync_api import Camoufox

with Camoufox(headless=True) as browser:
    page = browser.new_page()
    page.goto("https://example.com")
```

```python
import asyncio
from camoufox.async_api import AsyncCamoufox

async def main():
    async with AsyncCamoufox(headless=True) as browser:
        page = await browser.new_page()
        await page.goto("https://example.com")

asyncio.run(main())
```

```javascript
// npm install camoufox playwright-core && npx camoufox fetch
import { Camoufox } from "camoufox";

const browser = await Camoufox({ headless: true });
const page = await browser.newPage();
await page.goto("https://example.com");
await browser.close();
```

What you get back is a normal Playwright `Browser`. Behind a proxy, add
`proxy=...` and `geoip=True` so timezone, locale, geolocation and the WebRTC IP
match the exit IP. For many identities in one browser, use `NewContext()`.

## How it fits together

```mermaid
flowchart TB
    YOU(["Your Playwright code"])

    subgraph L["Launcher: the camoufox driver (camoucore)"]
        FP["fpgen<br/>draws a real device"] --> CO["coherence.py<br/>rejects impossible combinations"]
        CO --> ID[["Identity"]]
        GEO["geoip<br/>timezone, locale, WebRTC IP"] --> ID
    end

    subgraph B["Patched Firefox: browser/"]
        MC["MaskConfig<br/>reads CAMOU_CONFIG"] --> API["Web APIs answered in C++<br/>navigator, screen, WebGL,<br/>fonts, audio, WebRTC"]
        SET["Per-context setters<br/>sealed before page script"] --> API
        JG["Juggler<br/>isolated world"]
    end

    PAGE(["The web page"])

    YOU -- "1 launch options" --> L
    ID == "2 CAMOU_CONFIG + prefs" ==> MC
    ID -- "3 NewContext()" --> SET
    YOU <-- "4 Juggler protocol" --> JG
    API -- "native values" --> PAGE
    JG -. "trusted input, DOM reads;<br/>no code in the page" .-> PAGE

    classDef you fill:#eef2f6,stroke:#57606a,color:#1f2328
    classDef launcher fill:#ddf4ff,stroke:#0969da,color:#0a3069
    classDef browser fill:#fff1e5,stroke:#bc4c00,color:#4a1c00
    classDef page fill:#dafbe1,stroke:#1a7f37,color:#0f3d1c
    class YOU you
    class FP,CO,ID,GEO launcher
    class MC,API,SET,JG browser
    class PAGE page
    style L fill:none,stroke:#0969da,stroke-dasharray:4 3,color:#0969da
    style B fill:none,stroke:#bc4c00,stroke-dasharray:4 3,color:#bc4c00
```

1. The launcher draws a device from [fpgen](https://github.com/scrapfly/fingerprint-generator)
   (a model of real traffic), then adds fonts, voices, a GPU and media devices
   seeded by that identity. `coherence.py` rejects combinations no real machine
   produces.
2. The identity goes to the browser as the `CAMOU_CONFIG` environment variable
   (keys declared in [`browser/settings/properties.json`](browser/settings/properties.json)).
   The patches read it through `MaskConfig` and answer from C++.
3. `NewContext()` gives one context its own identity through setters that the
   per-context patches add to `window`. They are sealed before page script runs.
4. Playwright talks to Juggler. Camoufox's Juggler runs its page agent in an
   isolated world, so the page never sees automation code.

# Features

Each row says where it is implemented. A **patch** is a file in
[`browser/patches/`](browser/patches); **Juggler** is
[`browser/additions/juggler/`](browser/additions/juggler); the **launcher** is
the Python and TypeScript packages.

### Fingerprint spoofing

The goal is a browser that behaves exactly like stock Firefox, except that it
reports a different machine. A value is spoofed when it identifies the host
machine or the network. Anything else stays as Firefox has it, because
something stock Firefox never does, such as noise, is a fingerprint in its own
right.

| Trait | What a page sees | Why it is spoofed | Where |
|---|---|---|---|
| Navigator: User-Agent, platform, oscpu, hardware concurrency, language, appVersion | The drawn device's values, per launch or per context, in workers too | They name the OS and hardware directly, and every other value is checked against them | `navigator-spoofing`, `fingerprint-injection` patches |
| HTTP headers: User-Agent, Accept-Language | The navigator values | Servers compare the headers with what script reports | `network-patches` patch |
| Screen and window sizes, color depth, CSS media features | The drawn device's display, the same in JS and CSS | Screen size is among the most identifying values, and CSS media queries read it without script | `screen-spoofing`, `fingerprint-injection` patches |
| WebGL and WebGL2: vendor, renderer, parameters, extensions, shader precision, context attributes | One GPU fpgen recorded for Firefox on that OS. Values Firefox decides rather than the GPU follow the shipped Firefox ([`webgl-browser-owned-values-follow-firefox`](ci/tribal-rules.yml)) | The renderer string names the host's GPU, and its limits must agree with it | `webgl-spoofing` patch, `webgl.py` |
| WebGPU: `navigator.gpu` and its adapter | `navigator.gpu` only where Firefox on the claimed device has it: Windows and Apple Silicon Macs. The adapter is the host's only when the identity claims the host's GPU; otherwise `requestAdapter()` returns `null`, as for a blocked or software GPU | The adapter's limits and features come from the real GPU | launcher, `host_rendering.py` |
| Canvas, Web Audio, Opus, VP9, relaxed-SIMD wasm and NaN bits | The claimed CPU's arithmetic. Intel and AMD implement Skia's and Opus's estimate instructions RCPPS/RSQRTPS with different tables, so on an AMD host a canvas drawn with `color-dodge`, `color-burn`, `hue`, `saturation`, `color` or `luminosity` reads back other pixels than on Intel; an ARM64 CPU differs in far more (every Web Audio node and composite operation, Opus, VP9, NaN signs, relaxed SIMD). An x86-64 build computes as Intel, AMD or ARM64. `cpu` picks one; by default it follows the GPU (an Apple GPU is ARM, an Intel iGPU or Intel Mac is Intel, a Radeon iGPU is AMD) and otherwise is x86, 81% Intel as among Firefox's x86 users | The results split by CPU, not by OS or CPU generation, so they show the host's CPU | `cpu-vendor-estimates` patch, launcher |
| Audio: sample rate, output latency, max channels | The identity's values | They follow the claimed device's audio hardware | `audio-context-spoofing` patch |
| Fonts: installed list, `system-ui`, CSS2 system fonts | The claimed OS's fonts, from a bundled set; see [docs/FONTS.md](docs/FONTS.md) | Installed fonts reveal the OS and the software on it | `font-list-spoofing`, `font-hijacker`, `system-ui-font-spoofing` patches |
| Speech voices | The claimed OS's voices, which actually speak | The voice list is specific to each OS, and a voice that cannot speak is a tell | `voice-spoofing`, `speech-voices-spoofing` patches |
| Microphones, cameras, speakers | OS-style labels and groups; see [docs/MEDIA-DEVICES.md](docs/MEDIA-DEVICES.md) | Device count and labels differ per machine and per OS | `media-device-spoofing` patch |
| Media codecs (`canPlayType`, `isTypeSupported`) | Not the host's codec libraries | On Linux the answer depends on the host's installed codec libraries | `media-codec-spoofing` patch |
| Timezone, locale and `Intl` | The identity's, per realm, workers included | They must agree with the IP's country | `timezone-spoofing`, `locale-spoofing` patches |
| Geolocation | Coordinates from GeoIP, permission granted | They must agree with the IP | `geolocation-spoofing` patch, launcher |
| WebRTC IP | ICE candidates, SDP and `getStats()` rewritten to the proxy IP | WebRTC otherwise reveals the real IP behind a proxy | `webrtc-ip-spoofing` patch |
| WebRTC UDP behind a SOCKS5 proxy | STUN, TURN and peer-to-peer UDP go through the proxy's UDP relay (UDP ASSOCIATE), so the srflx candidate is the address the page's STUN server really saw; the local network gets no exception, and mDNS names stay in the browser. Without a relay, no UDP leaves the host and the srflx carries the proxy IP. Only a page's own loopback connection stays direct | Stock Firefox on the exit machine gathers a real srflx and connects peer to peer | `webrtc-socks5-udp` patch |
| Touchscreen | A touchscreen laptop, not a phone | Touch points and pointer media must agree with the claimed device | `touchscreen-fingerprint-spoofing`, `force-default-pointer` patches |

Left as stock Firefox has it, on purpose:

| Trait | What a page sees | Why it is not spoofed |
|---|---|---|
| Canvas pixels | What the GPU and fonts produce. As in stock Firefox, each context's PNG exports (`toDataURL`, `toBlob`) carry a per-session `deBG` chunk; the pixels themselves are untouched. On the host's OS the identity claims the host's GPU, so the pixels agree with it; on another OS readback returns random data, as `privacy.resistFingerprinting` does in LibreWolf ([the canvas on another OS](https://github.com/CamouBrowser/camoucore/blob/main/python/camoufox/docs/README.md#the-canvas-on-another-os)) | Stock Firefox does not perturb pixels in its default configuration, so noise would only mark the browser as a spoofer ([`canvas-is-not-noised`](ci/tribal-rules.yml)) |
| Text widths | What the font really measures | The same font on the same OS measures the same everywhere; widths no real machine produces are a fingerprint ([`no-glyph-spacing-noise`](ci/tribal-rules.yml)) |
| Audio render (`OfflineAudioContext`, `AnalyserNode`) | What the host CPU computes, the same in every context and every launch | Stock Firefox renders one value per CPU architecture, whatever the OS, sound card or sample rate, so a noised value is one no real machine produces ([`audio-is-not-noised`](ci/tribal-rules.yml)) |

Each context of one browser can carry its own identity:
[docs/per-context-patches.md](docs/per-context-patches.md).

### Canvas

Canvas and WebGL pixels come from the real OS, driver and GPU, whatever the
identity claims. The launcher chooses the canvas behaviour from two facts: does
the identity claim the host's OS, and does the host render on a GPU?

| | Identity on the host's OS | Identity on another OS |
|---|---|---|
| **GPU rendering** | 🟢 <ins><b>Most stealthy</b></ins><br/>&nbsp;&nbsp;&nbsp;&nbsp;✅ No canvas noise: looks like stock Firefox<br/>&nbsp;&nbsp;&nbsp;&nbsp;✅ The claimed GPU is the host's, so the pixels agree with it<br/>&nbsp;&nbsp;&nbsp;&nbsp;⛔ Every identity on this machine claims the same GPU, so there is less fingerprint diversity | 🟡 <ins><b>Less stealthy</b></ins><br/>&nbsp;&nbsp;&nbsp;&nbsp;✅ Readback is random, so the real OS does not show<br/>&nbsp;&nbsp;&nbsp;&nbsp;✅ A GPU is drawn per identity, so identities differ<br/>&nbsp;&nbsp;&nbsp;&nbsp;⛔ Canvas noise: looks like LibreWolf, Tor Browser or Mullvad Browser, which are rarer than stock Firefox |
| **Software rendering**<br/>(no working GPU driver, as on most servers) | 🟡 <ins><b>Less stealthy</b></ins><br/>&nbsp;&nbsp;&nbsp;&nbsp;✅ No canvas noise: looks like stock Firefox<br/>&nbsp;&nbsp;&nbsp;&nbsp;✅ Claims the software renderer (`llvmpipe` on Linux), so the pixels agree with it<br/>&nbsp;&nbsp;&nbsp;&nbsp;⛔ Reads as a server or a broken driver, and every identity on this machine claims the same renderer | 🟡 <ins><b>Less stealthy</b></ins><br/>&nbsp;&nbsp;&nbsp;&nbsp;✅ Readback is random, so the real OS does not show<br/>&nbsp;&nbsp;&nbsp;&nbsp;✅ A GPU is drawn per identity, so identities differ<br/>&nbsp;&nbsp;&nbsp;&nbsp;⛔ Canvas noise: looks like LibreWolf, Tor Browser or Mullvad Browser, which are rarer than stock Firefox |

A software-rendering host never claims a GPU. Firefox reads the name and the
pixels from one GL context, so a GPU name over software pixels never happens on
a real machine: with a broken GPU driver, Firefox reports `llvmpipe` too. To
report a GPU, render on one with `headless="virtual-gpu"`.

That is the default. These options override it:

| Override | Result |
|---|---|
| `canvas_noise=False` on another OS | 🔴 Stock Firefox, but the pixels show the real OS |
| `canvas_noise=True` on the host's OS | 🟡 Looks like LibreWolf with no need to |
| `webgl_config` naming a GPU other than the host's | 🟡 Canvas noise is turned on, as on another OS; with `canvas_noise=False`, 🔴 WebGL reports one GPU while the pixels come from another |

Noise is set per browser, not per context. Without it, every `NewContext()`
claims the host's OS. Details are in
[the canvas on another OS](https://github.com/CamouBrowser/camoucore/blob/main/python/camoufox/docs/README.md#the-canvas-on-another-os).

### Hiding automation

| What | Where |
|---|---|
| Playwright's `evaluate`, selectors and init scripts run in an isolated world the page cannot see | Juggler |
| `navigator.webdriver` is `false` | `playwright/1-leak-fixes` patch |
| `select_option`, `fill` on date and colour inputs, and `set_input_files` fire trusted events | `trusted-automation-events` patch |
| `fill` and `keyboard.insert_text` paste the text as a person does: the paste shortcut and Firefox's own paste, without the system clipboard | Juggler |
| Screenshots leave the page's DOM alone (no caret-hiding style writes) | Launcher |
| Mouse moves coalesce per frame as a real mouse's do, spaced as a 125 Hz mouse's | Juggler, `input-coalescing-parity` patch |
| A drag fires `drag` at its source with each motion, as GTK does | Juggler, `drag-source-events` patch |
| Driver calls define no interfaces on the page's window | `isolated-world-global-order` patch |
| A SOCKS5 proxy with a username and password works, for the launch and per context: the launcher hands the credentials to Juggler, which Playwright alone refuses | Launcher, Juggler |
| Headless reports a fine pointer, like a desktop | `force-default-pointer` patch |
| `mouse.wheel()` turns notches, as a physical wheel does: 100 px is one notch, each its own event with a native tick | Juggler, `wheel-native-ticks` patch |
| A press's click count is the identity's OS's, counted from the presses before it; Playwright's `click_count` is ignored. A held key repeats with that OS's delay and interval | Juggler |
| Juggler's debugger leaves no side effects content can observe | `debugger-invisible-to-content` patch |
| A stack the page captures while a driver call runs its code (`focus`, `dispatch_event`, an `mw:` evaluate) holds only the page's frames, never Juggler's, the isolated world's or the code the `mw:` evaluate compiled; a page function's `caller` is never driver code | Juggler, `debugger-invisible-to-content` patch |
| Code an `mw:` evaluate runs is named after the document, as an inline script is, never `debugger eval code` | Juggler, `debugger-invisible-to-content` patch |
| Per-context fingerprint setters are gone before page script runs | `window-setter-seal` patch |
| Popup blocker on, as in stock Firefox | `popup-blocker-parity` patch |
| On X11, a pointer-locked window partly off the top or left of the screen keeps running (stock Firefox can crash: the X server refuses the cursor barrier and GDK aborts) | `pointer-lock-offscreen` patch |
| Content-accessible chrome files match stock Firefox | `contentaccessible-parity` patch |
| Viewports never enter Responsive Design Mode; containers show no automation label | Juggler |

### Automation

| Feature | How to use it | Where |
|---|---|---|
| Human input: none in the browser. Each Playwright input call is one native event of the identity's OS; humanization is the driver's | `humanize=True` runs myuri in the driver; `myuri(part=fn)` replaces any of its parts | [Human input](#human-input) |
| Run code in the page's own world | `main_world_eval=True`, then `page.evaluate("mw:...")` | Juggler |
| Finish animations at once so Playwright never waits | `config={"instantAnimations": True}` (detectable; warns) | `no-css-animations` patch |
| Read closed shadow roots | `config={"forceScopeAccess": True}` | `shadow-root-bypass` patch |
| Many identities in one browser | `NewContext(browser, os=..., proxy=...)` | per-context patches, launcher |

### Addons

| Feature | Where |
|---|---|
| Load extracted addons without a debug server: `addons=["/path/to/addon"]` | launcher, `camoufox-window-module` patch |
| uBlock Origin installed by default: each browser release bundles the uBO release pinned in `browser/scripts/data/ubo.json` (`browser/scripts/fetch-ubo.py`), blocking with the default filter lists packaged in it, never downloaded at launch (`exclude_addons=[DefaultAddons.UBO]` to drop it) | packaging (`fetch-ubo.py` freeze_lists), launcher |
| Addons cannot open tabs unless `allow_addon_new_tab=True` | `disable-extension-newtab` patch |
| Addons run in private browsing | `all-addons-private-mode` patch |

### Launcher

| Feature | Option or command |
|---|---|
| Identity drawn from fpgen's real-world distribution, checked for coherence | default |
| Recorded real-device presets instead of fpgen | `fingerprint_preset=True` |
| Timezone, locale, geolocation and WebRTC IP from the proxy's exit IP | `proxy=..., geoip=True` |
| Locale chosen by the languages spoken in the IP's region | `geoip=True` without `locale` |
| Headed browser on a private Xvfb display (Linux) | `headless="virtual"` |
| Headed browser on a private Xorg display that renders on a named GPU (Linux) | `headless="virtual-gpu"` |
| Remote Playwright server for other languages | `launch_server()`, `camoufox server` |
| Install, pin and switch browser builds | `camoufox fetch`, `set`, `list`, `remove` |
| Core count that a page can measure | `pin_cpu_cores=True` |
| Block images, WebRTC or WebGL | `block_images`, `block_webrtc`, `block_webgl` |
| The host's GPU on the host's OS; random canvas readback, as in LibreWolf, on another OS | default; `canvas_noise=True` or `False` to choose |

The full option list is in the [Python driver README](https://github.com/CamouBrowser/camoucore/blob/main/python/camoufox/docs/README.md#launch-options).

### Debloat

| What | Where |
|---|---|
| Telemetry and data reporting removed at compile time | `librewolf/` patches |
| Onboarding messages disabled | `ghostery/` patch |
| Mozilla services and background traffic turned off | [`browser/settings/camoufox.cfg`](browser/settings/camoufox.cfg) |
| Firefox's bundled certificate revocations (OneCRL) enforced in every profile, with no network fetch | Stock Firefox since 159 |
| Stock browser UI: no theme, toolbar or dialog changes | |

> [!NOTE]
> Camoufox presents Firefox identities only. Some WAFs test SpiderMonkey engine
> behaviour, which no amount of spoofing turns into Chromium.

# How Camoufox compares

| | JavaScript injection | CDP-based (Chromium) | Camoufox |
|---|---|---|---|
| Where values are spoofed | Page-world overrides | Page-world overrides or flags | Browser C++ |
| `toString()`, property descriptors | Show the override | Show the override | Native |
| Workers and iframes | Often missed | Often missed | Same value everywhere |
| Headers agree with navigator | Only if set separately | Only if set separately | Always |
| Automation code in the page | Yes | Yes (bindings, `navigator.webdriver`) | No: isolated world |
| Identity source | Hand-picked or random | Hand-picked or random | fpgen's real-world distribution, coherence-checked |

Playwright drives Chromium over CDP but Firefox over Juggler, a protocol that is
a separate module inside Firefox. That makes it possible to give Juggler its
own copy of the page: Playwright reads and edits that copy, and the real page
never sees a getter fire or a listener appear. Input goes through Firefox's own
input handlers, so it is handled as a user's would be.

Camoufox can still be detected. Thousands of values must agree with each other,
and anti-bot vendors look for the one that does not. File a
[detection report](https://github.com/daijro/camoufox/issues/new?template=camoufox-detected.md)
when you find one.

## Human input

The browser does not humanize input. Each Playwright input call reaches the page
as one event of the shape a real device gives stock Firefox: a `mouse.move` is
one move, a click is a press and a release, `mouse.wheel(dx, dy)` is one wheel
event in whole notches (Linux and Windows: 100 px a notch, carried in that one
event as a fast spin of a notched wheel can be; macOS: one event of 16 px lines),
and `fill()` is Firefox's own paste. The browser adds no timing, paths, pacing or
randomness of its own, so how human the input looks is up to the driver: send the
moves, notches and keys a person would, at a person's times
([docs/input-dispatch.md](docs/input-dispatch.md) has each event's shape per OS).

The `humanize` option picks an engine per channel, run in your own process:

```python
from camoufox.humanize import myuri, raw

Camoufox(humanize=True)   # myuri() on every channel
Camoufox(humanize={"scroll": raw(), "seed": 1234})
Camoufox(humanize={"settings": {"mouse": {"speed_factor": 2}, "typing": {"wpm": 90}}})
```



<sub>A Linux identity with `humanize={"seed": 7}`, recorded at real speed. The red trail and the rings are drawn by the page from the mouse events it received.</sub>

- `myuri()` is [myuri](https://github.com/JWriter20/Myuri)'s smart actions, fitted
  to recordings of people on each OS and drawn for the launch identity's OS: the
  path, the press, the typing and the wheel turns, and the decisions around a
  click (scroll the element into view, choose the point, check that the press
  lands, try again when it does not). Both packages depend on it, pinned to the
  release they were tested with.
- `cursory()` is another name for `myuri()`: myuri runs cursory's paths.
- `raw()` is Playwright as it is.
- A channel a dict leaves out is `myuri()`. `humanize=None` or `False`, the
  default, is `raw()` everywhere.
- `settings` are [myuri's settings](https://github.com/JWriter20/Myuri#settings): mouse, scroll and typing speed,
  overshoot, typing mistakes and pauses. Pass any subset; the rest keep myuri's
  defaults, and an unknown key raises `ValueError` before launch. The `seed`
  draws one person around them, each speed within ±`variation` (0.2) of the
  value set; `{"variation": 0}` plays them exactly.

The engine decides when each event happens; the browser decides what each event
looks like for the identity's OS ([docs/humanize.md](docs/humanize.md)).

### Replacing a part: `myuri(part=fn)`

Each piece of myuri is a part you can replace with a function of yours, in your own process (Python below; TypeScript in [its README](https://github.com/CamouBrowser/camoucore/blob/main/typescript/camoufox/docs/README.md#replacing-a-part)). The rest stay myuri's, so a scroll of your own still serves myuri's clicks, and your move still ends where myuri presses.

```python
import asyncio

from camoufox.async_api import AsyncCamoufox
from camoufox.humanize import myuri

async def my_move(page, x, y, *, default, rng, play):
    await asyncio.sleep(0.1 + 0.2 * rng())            # a pause to look, then myuri's path
    await default()

async def my_into_view(page, locator, *, default, rng, play):
    await locator.scroll_into_view_if_needed()        # Playwright's own scroll
    # or: await default() for myuri's wheel turns

async with AsyncCamoufox(humanize={
    "mouse": myuri(move=my_move),
    "scroll": myuri(into_view=my_into_view),
    "settings": {"typing": {"wpm": 70}},
    "seed": 1234,
}) as browser:
    page = await browser.new_page()
    await page.set_content('<button id="submit" style="margin-top:3000px">Send</button>')
    await page.locator("#submit").click()             # my_into_view, then myuri's click after my pause
```

| Channel | Part | Called as | myuri's part |
|---|---|---|---|
| `mouse` | `move` | `fn(page, x, y, ...)` | a path from the cursor to (x, y) |
| | `press` | `fn(page, button, click_count, ...)` | the dwell, then each press and its hold |
| | `point` | `fn(page, box, attempt, ...)`, returns `(x, y)` | where in the element's visible box to aim; `attempt` counts the misses |
| | `reaches` | `fn(page, locator, x, y, pressing, ...)`, returns `None` or why it misses | whether a press at (x, y) lands on the element: not covered, enabled |
| `scroll` | `into_view` | `fn(page, locator, ...)` | wheel turns until the element is in view, waiting for each scroll to land |
| | `wheel` | `fn(page, dx, dy, ...)` | one scroll split into wheel notches |
| `keyboard` | `type` | `fn(page, text, ...)` | keys at a person's rhythm, with the mistakes they make |
| | `key` | `fn(page, key, ...)` | one key or chord (`"Enter"`, `"Control+a"`) |

Every part is also called with `default`, `rng` and `play`, as keywords:

- `default(*args)` runs myuri's part, with the same arguments when given none. A part that only adjusts myuri wraps it.
- `rng()` returns a float in [0, 1) from the humanize seed's stream: one stream per browser, the same numbers in Python and TypeScript.
- `play(steps)` dispatches steps at their times, in ms from the start of the call: `("move", x, y, t)`, `("down" | "up", button, t)`, `("wheel", dx, dy, t)` (one wheel event each), `("key", key, "down" | "up", t)`, `("text", text, t)` (pasted, as `keyboard.insert_text` is). It waits until each step is due on a monotonic clock rather than sleeping between steps, so a slow round trip delays one step and never adds up. Bad steps raise `ValueError` before anything is sent.
- Playwright calls inside a part are Playwright's own: `page.mouse.move` in a move part moves the mouse once.
- With the sync API a part is a plain function, and `default` and `play` return their result; with the async API they return awaitables, and the part may be `async`. Exceptions reach the caller unchanged.

What each channel drives:

| Channel | For |
|---|---|
| `mouse` | `Mouse.move`/`click`/`dblclick`; `click`, `dblclick`, `hover`, `check`, `uncheck` on a `Page`, `Frame` or `Locator`, and the click that focuses a field before `fill` |
| `keyboard` | `Keyboard.type`/`press`; `fill`, `type`, `press` on a `Page`, `Frame` or `Locator`, and `Locator.press_sequentially` |
| `scroll` | `Mouse.wheel`, `Locator.scroll_into_view_if_needed`, and bringing an element into view before a pointer action, fill or typing |

- A click that never reaches its element raises Playwright's `TimeoutError` at the call's timeout, naming what covers the point. `trial=True` goes to Playwright alone, and `force=True` skips the reach check.
- `ElementHandle` methods, `tap`, `drag_and_drop` and `drag_to` are Playwright's own.
- The wrappers belong to the browser `Camoufox()` launched: other browsers in the same process are untouched. For a browser from `connect()`, launch it without humanize and call `camoufox.humanize.attach(browser, humanize, os)` with its identity's OS. Over a network each event is a round trip, so the launcher warns (`humanize_remote`). `launch_server()` refuses any engine but `raw()`.

# Building the browser

This repository is not the Firefox source. It fetches Firefox, copies in
[`browser/additions/`](browser/additions), applies
[`browser/patches/`](browser/patches) and builds. The build runs on Linux; the
Windows and macOS binaries are cross-compiled. WSL does not work.

```mermaid
flowchart TB
    subgraph IN["From this repository"]
        direction LR
        UP["upstream.sh<br/>Firefox version"]
        ADD["additions/ + settings/<br/>files copied in"]
        PAT["patches/<br/>diffs applied"]
    end

    S1["<b>1. make dir</b><br/>download Firefox, copy additions,<br/>apply every patch"]
    S2["<b>2. make bootstrap</b><br/>toolchains, once per machine"]
    S3["<b>3. make build</b><br/>./mach build"]
    S4["<b>4. make package-linux</b><br/>or package-macos, package-windows"]
    FONTS["font bundle + fontconfig"]
    OUT[("Release archive")]

    IN --> S1 --> S2 --> S3 --> S4 --> OUT
    FONTS --> S4

    classDef input fill:#ddf4ff,stroke:#0969da,color:#0a3069
    classDef step fill:#fff1e5,stroke:#bc4c00,color:#4a1c00
    classDef out fill:#dafbe1,stroke:#1a7f37,color:#0f3d1c
    class UP,ADD,PAT,FONTS input
    class S1,S2,S3,S4 step
    class OUT out
    style IN fill:none,stroke:#0969da,stroke-dasharray:4 3,color:#0969da
```

```bash
git clone --depth 1 https://github.com/daijro/camoufox
cd camoufox/browser
make dir                        # fetch Firefox, copy additions, apply every patch
make bootstrap                  # one time: host packages and mach bootstrap
make build                      # ./mach build
make run                        # run the build
make package-linux arch=x86_64  # or package-macos / package-windows
```

`make help` lists every target. Install `ccache`. Every build is optimized as
stock Firefox's releases are, with Mozilla's PGO profile for the same Firefox
and cross-language LTO, and ccache cannot cache the LTO link, so an incremental
build still relinks libxul.

To build and package several targets in one go:

```bash
python3 multibuild.py --target linux windows macos --arch x86_64 arm64
```

| `multibuild.py` flag | Values |
|---|---|
| `--target` | `linux`, `windows`, `macos` (one or more) |
| `--arch` | `x86_64`, `arm64`, `i686` (one or more; `i686` builds Windows only) |
| `--bootstrap` | Bootstrap the build system first |
| `--clean` | Clean the build directory first |
| `--preflight` | Check that each target builds without building it: configure, the export tiers, and every patched source file (minutes, not hours) |

Artifacts are written to `browser/dist/`.

### With Docker

```bash
cd browser
docker build -t camoufox-builder .
docker run -v "$(pwd)/dist:/app/dist" camoufox-builder --target linux --arch x86_64
docker run -v "$(pwd)/dist:/app/dist" camoufox-builder --target windows --arch x86_64
```

The container takes the `multibuild.py` flags. Add
`-v "$HOME/.mozbuild":/root/.mozbuild:rw,z` to reuse the host's toolchains.

### Changing patches and running tests

| Task | Where |
|---|---|
| Write or edit a patch | [`AGENTS.md`](AGENTS.md#changing-a-patch) |
| Port patches to a new Firefox | [`docs/patch-upgrading-guide.md`](docs/patch-upgrading-guide.md) |
| Which suite to run for a change | [`AGENTS.md`](AGENTS.md#testing) |
| The CI pipeline and running any job locally | [`ci/README.md`](ci/README.md) |
| Contributing | [`CONTRIBUTING.md`](CONTRIBUTING.md) |

## Leak debugging

A way to find what a site detects without deobfuscating its JavaScript: start
from stock Firefox and add Camoufox's changes back until the site flags.

<details>
<summary>Leak debugging flow chart</summary>

```mermaid
flowchart TD
    START(["A site flags Camoufox"]) --> Q1{"Does it flag<br/>stock Firefox?"}
    Q1 -- yes --> NB["Not the browser:<br/>a bad IP or rate limiting"]
    Q1 -- no --> BASE["Build the debug baseline<br/>make ff-dbg (1), make build (2)"]
    BASE --> Q2{"Does it flag the<br/>baseline headless (4)?"}

    Q2 -- yes --> Q3{"Headed (3)<br/>as well?"}
    Q3 -- yes --> NB
    Q3 -- no --> Q4{"Still flagged with<br/>privacy.resistFingerprinting (6)?"}
    Q4 -- no --> FPP["Enable FPP and drop overrides<br/>until the leak returns"]
    Q4 -- yes --> DEOB["Deobfuscate the site's script<br/>to see what it tests"]

    Q2 -- no --> CFG["Apply config.patch (5)<br/>and rebuild (2)"]
    CFG --> Q5{"Still passes (3)?"}
    Q5 -- no --> PREFS["Remove prefs from camoufox.cfg (6)<br/>until it passes"]
    Q5 -- yes --> PW["Apply playwright/0-playwright.patch (5)<br/>and rebuild (2)"]
    PW --> Q6{"Still passes (3)?"}
    Q6 -- no --> JUG["Debug Juggler"]
    Q6 -- yes --> REST["Apply the other patches one at a time<br/>until it flags"]
    JUG -. "if Juggler looks clean" .-> DEOB

    classDef start fill:#eef2f6,stroke:#57606a,color:#1f2328
    classDef ask fill:#ddf4ff,stroke:#0969da,color:#0a3069
    classDef step fill:#fff1e5,stroke:#bc4c00,color:#4a1c00
    classDef found fill:#dafbe1,stroke:#1a7f37,color:#0f3d1c
    class START start
    class Q1,Q2,Q3,Q4,Q5,Q6 ask
    class BASE,CFG,PW step
    class NB,FPP,DEOB,PREFS,JUG,REST found
```

| # | Command | What it does |
|---|---|---|
| 1 | `make ff-dbg` | Stock Firefox with the minimum Camoufox needs |
| 2 | `make build` | Build |
| 3 | `make run` | Run the build |
| 4 | `make run args="--headless https://example.com"` | Run headless |
| 5 | `make patch ./patches/<name>.patch` | Apply one patch (`make unpatch` reverses it) |
| 6 | `make edit-cfg` | Edit `camoufox.cfg` |

</details>

---

## Licensing

| Part | Licence |
|---|---|
| The browser (`browser/`: patches, additions, settings, build system) | [MPL-2.0](LICENSE), the licence of the Firefox source it modifies |
| The `camoufox` release wrapper (`pyproject.toml`, `camoufox/`, `camoufox_pin/`, `npm/`) | MIT, like the driver it installs ([`camoufox/LICENSE`](camoufox/LICENSE), shipped in both packages); it adds no code to that driver |
| Python driver | MIT ([camoucore](https://github.com/CamouBrowser/camoucore/blob/main/python/LICENSE)) |
| TypeScript driver | MIT ([camoucore](https://github.com/CamouBrowser/camoucore/blob/main/typescript/LICENSE)); depends on [`camoucore`](https://github.com/CamouBrowser/camoucore) (MIT; carries a port of NumPy's pairwise summation, with its notice), [`fpgen-js`](https://www.npmjs.com/package/fpgen-js) (Apache-2.0) and [`python-random`](https://www.npmjs.com/package/python-random) |

## Thanks

| Project | Used for |
|---|---|
| [LibreWolf](https://gitlab.com/librewolf-community/browser/source) | Debloat patches and the original build system |
| [BetterFox](https://github.com/yokoffing/BetterFox) | Speed and debloat preferences |
| [Ghostery](https://github.com/ghostery/user-agent-desktop) | Debloat reference ([disable onboarding](browser/patches/ghostery/Disable-Onboarding-Messages.patch)) |
| [Vinyzu/cursory](https://github.com/Vinyzu/cursory) | The recorded human mouse movements behind `humanize=True`, which [myuri](https://github.com/JWriter20/Myuri) replays (via [cursory-js](https://github.com/JWriter20/cursory-js) in TypeScript) |
| [riflosnake/HumanCursor](https://github.com/riflosnake/HumanCursor) | The Bézier cursor Camoufox used before Cursory |
| [scrapfly/fingerprint-generator](https://github.com/scrapfly/fingerprint-generator) (fpgen) | The device distribution identities are drawn from |
| [CreepJS](https://github.com/abrahamjuliot/creepjs), [Browserleaks](https://browserleaks.com), [BrowserScan](https://www.browserscan.net/) | Leak testing |

---

### Overview (`ci/README.md`)

# The test pipeline

Everything that runs a suite against Camoufox. The same definition runs on a
pull request, on a push to `main`, before every release (through
`release.yml`), and for any caller of the `workflow_call` trigger that wants a
specific browser version, so there is one meaning of "the tests pass". Every job can be run locally
([Running a piece by hand](#running-a-piece-by-hand)).

```
resolve ── static ─────────────── lint, tribal rules, skiplist, self-tests  (seconds)
             └─ build or fetch ─┬─ patch guards × 3 + skiplist audit
                                ├─ build-tester ─────── 8 fingerprint profiles
                                └─ once guards and build-tester pass:
                                     ├─ playwright × 6 shards   (upstream suite + our own)
                                     ├─ native ───────── leaks, contexts, crash recovery
                                     ├─ sundial ──────── stealth grade
                                     └─ growth × 7 shards  memory growth, one test per runner
                             │
                          summary ──► one comment on the PR ──► gate: "All tests passed"
```

A push to `main` whose tree a passing pull request run already tested (nothing
else merged in between) runs none of that again. `resolve` finds the run
(`ci.carry`), `carry-browser` takes over the browser it tested, `sundial` runs
against it, since a pull request from a fork has no credential for it, and
`summary` reports the carried results with this run's grade. Each pull request
run records the tree it tested as a `tested-tree-<tree>` artifact. A push that
lands any other tree, or whose run's browser has expired (three days), is tested
in full.

## Jobs

| Job | Runner | What it proves |
|---|---|---|
| `static` | `ci.run_native --subset rules`, `pytest ci/tests`, `browser/scripts/check-input-dispatch.py` | Settled decisions still hold, the skiplist is valid, input goes through one chokepoint, the pipeline reports honestly |
| `build` / `fetch-browser` | `ci.run_prepare`, `ci.run_build` | The browser under test: built and packaged from this branch by the command a release's build runs, or the published release built from the same sources |
| `preflight` | `ci.run_prepare`, `ci.run_build --preflight` | Each target only a release builds (linux arm64, windows x86_64 and i686, macos x86_64 and arm64) configures, passes the export tiers, and compiles every source file a patch or an addition touches ([below](#what-a-release-builds)) |
| `patch-guards` | `ci.run_patch_guards --group spoofing\|automation\|parity`, `ci.run_skiplist_audit` | One guard per shipped behaviour ([`browser/tests/playwright/`](../browser/tests/playwright/README.md)); every skiplist entry still fails |
| `build-tester` | `ci.run_build_tester` | The raw binary against the anti-detect checks ([README](../browser/tests/build-tester/README.md)) |
| `playwright` | `ci.run_playwright --shard i/6` | Upstream playwright-python's suite, plus [`browser/tests/playwright/camoufox/`](../browser/tests/playwright/camoufox/README.md) |
| `native` | `ci.run_native --subset browser` | Leaks, context isolation, crash recovery ([below](#camoufoxs-own-suite)) |
| `growth` | `ci.run_native --subset growth --shard i/7` | Memory growth, one test per runner |
| `carry-browser` | | A carried push to `main`: the pull request run's browser, cached for `main` when it was built |
| `sundial` | `ci.run_sundial` | The stealth grade ([below](#stealth-grade)) |
| `summary` | `ci.summarize` | Folds every result into one table and a pull request comment |
| `gate` | | The required check, **`All tests passed`** |

## The driver

This repository builds the browser. The drivers that launch it, the Python and
TypeScript launchers, are developed in
[CamouBrowser/camoucore](https://github.com/CamouBrowser/camoucore) and
published there in the one `camoucore` package (PyPI and npm), as
`camoucore.camoufox` (npm: `camoucore/camoufox`). Driver and launcher changes
(Python and TypeScript, fingerprints, the CLI, the MCP server) go to camoucore:
the static job's `python3 -m ci.check_no_driver` fails a pull request that adds
`python/`, `typescript/`, a `camoufox/` module that is more than an alias stub,
or Python or TypeScript outside `browser/`, `ci/` and `.github/`. It also fails
a test that imports `camoufox.<module>` for a module the wrapper does not alias:
core modules such as `virtdisplay`, `fpgen_model` and `_warnings` are
`camoucore.<module>`.

What this repository still releases is the `camoufox` package on PyPI and npm,
a **release wrapper** with no launcher code of its own, laid out as camoucore's
[RELEASING.md](https://github.com/CamouBrowser/camoucore/blob/main/RELEASING.md)
("The wrapper packages") says:

| File | What it is |
|---|---|
| [`pyproject.toml`](../pyproject.toml) | `camoufox` on PyPI: depends on `camoucore==X.Y.Z` (and `camoucore[geoip]==X.Y.Z` for the `geoip` extra); the `camoufox` console script is `camoucore.camoufox.__main__:cli` |
| [`camoufox/`](../camoufox) | `import camoufox` re-exports `camoucore.camoufox`; one stub per public submodule makes `camoufox.<m>` the same module as `camoucore.camoufox.<m>`; `__main__.py` makes `python -m camoufox` the CLI. A new camoucore module needs a stub here (`ci/check_wrapper.py` fails without one) |
| [`npm/`](../npm) | `camoufox` on npm (packed from `npm/`, so its LICENSE is the wrapper's): depends on `camoucore` `X.Y.Z` with a `playwright-core` peer; `index.js` re-exports `camoucore/camoufox` and the `camoufox` bin imports `camoucore/camoufox/cli.js` |
| [`camoufox_pin/browser-pin.json`](../camoufox_pin/browser-pin.json) and `npm/camoufox_pin/browser-pin.json` | The browser release this wrapper was tested with, byte-identical copies. `{}` in the checkout; `release.yml` stamps both. The launcher reads it before its own as `importlib.resources.files("camoufox_pin") / "browser-pin.json"` (Python) or `camoufox/camoufox_pin/browser-pin.json` (npm) |
| `camoufox/LICENSE`, `npm/LICENSE` | MIT, the wrapper's licence (camoucore's too). The browser sources stay under the root [LICENSE](../LICENSE) (MPL-2.0), which neither package ships |

Both manifests must pin the same exact camoucore version, and the two pin
copies must agree; `python3 -m ci.release driver` prints the version and fails
otherwise. `ci/check_wrapper.py` checks an installed wrapper against the
contract (every module aliased, the pin read is the wrapper's, both commands
run); `.github/actions/driver` and `release.yml` run it. Raising the pin
is a pull request here, after camoucore has published that version.

Every job that drives the browser installs the driver the same way, through
[`.github/actions/driver`](../.github/actions/driver/action.yml):

| `ci/driver-ref` | What the jobs install |
|---|---|
| missing or empty (the default) | The wrapper from this checkout, `pip install ".[<extras>]"`, which resolves the pinned `camoucore` from PyPI; where a job asks for npm, `npm/` packed and installed with its pinned camoucore |
| a camoucore branch, tag or commit | That camoucore commit, checked out into `.ci-work/camoucore` and installed by its `scripts/install-driver.sh camoufox <venv> <npm-dir>`, then this checkout's wrapper on top without dependencies (`pip install --no-deps`, and `npm/` packed and installed), so `camoufox` is that commit's launcher with this repository's pin |

The file holds one ref; lines starting with `#` are ignored. Set it on a branch
that needs unreleased driver code, and empty it again once that driver is
published and pinned. While it is set, `release.yml` publishes no wrapper (a
prerelease skips the libraries, a stable tag fails).

The generators that write driver data (`browser/scripts/gen-fonts-json.py`,
`gen-font-groups.py`) write into a camoucore checkout: `--camoucore <dir>`,
`CAMOUCORE_DIR`, or a `camoucore` directory next to this checkout. Their output
lands through a camoucore pull request. The drift checks here
(`verify-fonts.py`, `ci/tests/test_essential_aliases.py`,
`test_cpu_estimates.py`) compare the browser with the installed driver.

**The browser ships first, then the driver.** A driver checks the interface a
browser declares ([`browser/INTERFACE`](../browser/INTERFACE), copied into each
release's `manifest.json`) and launches only builds inside its own
`MIN_INTERFACE`..`INTERFACE` range. A change to what the browser reads or
accepts from a launcher therefore lands in this order:

1. Bump `browser/INTERFACE` here, with the browser change, in a pull request
   whose `ci/driver-ref` names the camoucore branch that speaks the new
   interface. CI tests the browser against that driver.
2. Release the browser (`release.yml`). Published drivers keep launching the
   builds they already accept.
3. Merge and release the driver in camoucore, raising its `INTERFACE`.
4. Empty `ci/driver-ref` here, so CI follows the published driver again.

A change that neither side reads (a patch fix, a new spoofed value inside an
existing key) keeps the interface and needs no driver change.

## Which browser, which suite

`ci/versions.py` answers both, and every entry point uses it:

| Question | Answer |
|---|---|
| Browser | `browser/upstream.sh`, or the version a caller passes |
| Suite | The newest released playwright-python tag whose pinned Firefox is not ahead of that browser, and which is below the Playwright ceiling the installed driver declares (its `playwright<X` requirement) |

Playwright trails Firefox and skips versions, so the suite's Firefox is often a
release or two behind the browser. That is the normal case; the summary says
which rule picked the tag. The ceiling exists because `camoufox.server` imports
a private Playwright API and every Playwright minor may change Juggler.

```bash
python3 -m ci.versions --json
python3 -m ci.versions --browser-version 153.0.4 --json
```

Only suite selection follows `--browser-version`; the build always reads
`upstream.sh`. `--check-upstream`, which the workflow passes, refuses a version
the branch does not pin, so an old browser is never judged against a new suite.
An upgrade to a new Firefox is therefore a branch that edits `upstream.sh`.

## The Playwright suite

Upstream playwright-python at the resolved tag, fetched fresh every run and run
unmodified. `ci/pw_camoufox_plugin.py` adapts the environment around it, and
`ci/suite.py` overlays [`browser/tests/playwright/camoufox/`](../browser/tests/playwright/camoufox/README.md).
Why there is no vendored copy: [`browser/tests/playwright/README.md`](../browser/tests/playwright/README.md#why-there-is-no-vendored-suite).

`ci/run_playwright.py` names its targets explicitly, so nothing is left out
silently:

| Targets | How they run |
|---|---|
| `tests/async/`, `tests/sync/` | One pytest process |
| `tests/common/`, `tests/test_reference_count_async.py` | Their own process: they start their own event loop |
| `tests/test_installation.py` | Excluded, with a reason |

`unclaimed()` fails the run if upstream adds a test path that is neither in
`TARGETS` nor in `EXCLUDED`.

### Isolated world first

Camoufox ships with Playwright's code in an isolated world, but upstream's tests
assume the main world (they read globals their own page scripts defined). Each
group therefore runs in up to three passes:

| Pass | `CI_WORLD` | What it establishes |
|---|---|---|
| 1 | `isolated` | The browser as users run it |
| 2 | `main` | The pass-1 failures again, isolation off |
| 3 | `main` | What failed in both, once more; normally empty |

A test that passes only in pass 2 is a **main-world fallback**: it counts as a
pass, and the summary reports `main_world_fallback_count`. That number is the
isolated-world conformance gap; a jump means the isolation boundary moved. Both
rerun passes run only when the failure set is non-empty, because pytest's
`--last-failed` with nothing to filter reruns the whole group.

Pass 1 is cost-bounded: a 90 s per-test timeout, and upstream's own reruns off
(`CI=""`, because upstream's conftest overrides `--reruns`).

Some modules **hang** rather than fail under isolation. A Playwright feature
that works by replacing a page global, such as `route_web_socket` (which
replaces `window.WebSocket`) or a binding the page calls, lands in the isolated
world, so anything the page itself does never reaches it. In the sync API no
timeout can stop such a hang cleanly. Those modules are listed in
`ISOLATION_HANGS` in `ci/run_playwright.py` and run directly in the main world,
counted as fallbacks. The `route_web_socket` gap is real for users too:
[#775](https://github.com/daijro/camoufox/issues/775).

### The skiplist

[`ci/skiplist.yml`](skiplist.yml) deselects the upstream tests Camoufox fails on
purpose, each with a reason (`ci/summarize.py` rejects an entry without one).
A reason is not evidence, so `ci/run_skiplist_audit.py` runs every entry in the
main world with the skiplist off and **fails the build if a skipped test
passes**. An entry whose test passes or fails with machine speed names, in
`checked_by`, the patch guard that checks its reason instead.
`ISOLATION_HANGS` is a different list: those tests pass in the main
world, so they would fail the audit, and `test_isolation_hangs_are_not_in_the_skiplist`
keeps the two apart.

The entries cover keyboard input Camoufox presses as a real keyboard would,
client certificates the browser must present during the TLS handshake,
HTTPS-First through upstream's GET-only test proxy, the popup blocker Camoufox
keeps on, and scrollbars Camoufox does not hide in headless mode. CI is the
authority on what fails; a local run is a hypothesis.

## Camoufox's own suite

`browser/tests/native/` covers what the Playwright suite cannot ask about:

| Area | What it checks |
|---|---|
| Leaks | Launching and killing browsers leaves no file descriptors, sockets, child processes or X11 lock files, and the cost does not grow with launch count |
| Contexts versus browsers | Two contexts in one browser get different fingerprints; two pages in one context get the same one |
| Crashes | Killing the browser, the X server, a content process or the driver mid-run leaves nothing behind, and the next launch works (`test_crash_recovery.py`) |
| Memory growth | One mechanism (iframes, canvas readback, WebGL contexts, workers, script compilation, font measurement) driven N and 4N times grows by a bounded amount (`test_memory_growth.py`, the `growth` job) |
| Settled decisions | Every mechanically checkable rule in [`ci/tribal-rules.yml`](tribal-rules.yml) (`test_tribal_rules.py`) |
| GPU display | `headless="virtual-gpu"` renders on the card `CAMOUFOX_GPU` names, the identity claims that card, and the Xorg server exits with the browser (`test_gpu_display.py`). No runner has a GPU, so the `gpu` subset is run by hand and is not part of `all` |

## Stealth grade

`ci/run_sundial.py` reports **a letter grade and a count**, nothing else: no
vector name, value or source, and no per-category breakdown. Everything that
leaves `redact()` is checked against a whitelist (`_PUBLISHABLE`), so adding a
field fails the run. The request asks for the score only (`?auto=1&score=1`),
and a full report arriving anyway fails the run.

```json
{ "grade": "A", "checks_total": 412, "checks_passed": 403, "pass_rate": 0.978,
  "out_of_scope_failed": 6, "cross_os_total": 24, "cross_os_passed": 5,
  "os": "linux", "sundial_version": "0.3.1", "schema_version": 1 }
```

| Setting | Where |
|---|---|
| On/off switch, gated categories, `min_pass_rate` | [`ci/sundial.yml`](sundial.yml) |
| Credential | `SUNDIAL_AUTOMATION_KEY` secret; `SUNDIAL_USERNAME` is optional |
| Keep an encrypted full report for yourself | `SUNDIAL_REPORT_AGE_RECIPIENT` (an `age` public key) |

Cross-OS checks read the host rather than the disguise, so they are counted
separately and never scored. Without a credential (a fork pull request) the job
is skipped and the summary says so.

To see which category fails, run locally; `--explain` is refused under GitHub
Actions:

```bash
python3 -m ci.run_sundial --explain --binary /path/to/camoufox-bin
```

## Blocking a merge

Branch protection on `main` requires one check, **`All tests passed`** (the
`gate` job), so the list does not change when a suite is added or resharded.
Anything that is not `success` fails it, including `skipped`, except:

| May be skipped | When |
|---|---|
| `build`, `preflight` | The browser was fetched, not compiled |
| `fetch-browser` | The browser was compiled, not fetched |
| `sundial` | Disabled in `ci/sundial.yml`, or no credential |
| `carry-browser` | The push to `main` was not carried |
| every suite but `sundial` | The push to `main` was carried; `summary` requires their results from the pull request run |

`sundial` may also record a `skip` result when the sundial service is
unreachable. A rejected credential, a full report, or a score under the floor
still fails.

The settings are in [`ci/branch-protection.json`](branch-protection.json). To
apply them (needs admin):

```bash
gh api -X PUT repos/<owner>/<repo>/branches/main/protection --input ci/branch-protection.json
```

| Setting | Why |
|---|---|
| `enforce_admins: false` | A maintainer can still merge when CI itself is broken |
| `strict: false` | A pull request need not be rebased onto `main` before merging; otherwise every push to `main` would force a rebuild of every open pull request |
| No required reviews | A solo maintainer cannot approve their own pull request |

## Cost control

Each tier gates the next, so a lint failure never reaches the build:

| Tier | Jobs | Time |
|---|---|---|
| 0 static | lint, self-tests, settled decisions | seconds |
| 1 browser | build and five preflights (browser sources changed) or fetch (they did not) | minutes to hours |
| 2a smoke | patch guards, skiplist audit, build-tester | about 15 min |
| 2b full | Playwright × 6, native, growth × 7, stealth | about 40 min |
| 3 gate | the required check | seconds |

| Mechanism | Effect |
|---|---|
| **Fetch instead of build** | A pull request that does not touch browser sources tests the published release built from exactly this tree's sources (`ci.release paired`). With no such release, it builds. |
| **Compiled-input cache** | The build cache is keyed on a hash of the compiled inputs only (`ci/browser_inputs.py`). On a hit the browser is restored and this branch's Juggler JavaScript and other resources, the files Juggler's `moz.build` lists in `FINAL_TARGET_FILES`, are laid over it. Everything else, including any new file type, counts as native and forces a build. |
| **No partial restore** | That cache has no `restore-keys`: a partial match would hand the tests a browser built from different sources. A self-test checks the key covers every browser-affecting path. |
| **Warm ccache** | Pushes to `main` that build, and a twice-weekly schedule, keep the ccache from being evicted; pull requests restore it. A carried push builds nothing, so it caches the pull request's browser under the compiled-input key instead. |
| **Carried pushes** | A push to `main` that lands the tree its pull request run tested reuses that run's results ([above](#the-test-pipeline)). |
| **PGO and LTO** | Every build uses Mozilla's PGO profile for the same Firefox and links libxul with cross-language LTO, as a release does ([`builds-are-optimized-like-stock`](tribal-rules.yml)). ccache caches the compiles, not that link, so a warm build still pays for it. |
| **Network retries only** | `ci.run_prepare` (`setup-minimal`, `dir`, `mozbootstrap`) retries only failures that read as transient network errors. A failed hunk or compile error fails at once. |

Pushing to a branch cancels its running build (`cancel-in-progress`).

## What a release builds

A release builds six targets and a pull request builds one. Every step of a
release's build therefore also runs on a pull request
([`one-build-entry-point`](tribal-rules.yml)):

| | Pull request | Release |
|---|---|---|
| Runner setup | [`build-host`](../.github/actions/build-host/action.yml) | the same action |
| Source tree | `ci.run_prepare` | the same |
| linux x86_64 | `ci.run_build`: `multibuild.py` retargets, builds and packages | the same command |
| The other five targets | `ci.run_build --preflight`: `multibuild.py` retargets, then [`preflight.py`](../browser/scripts/preflight.py) configures, runs the `pre-export`, `export` and `pre-compile` tiers and compiles the objects of every patched or added source file | `ci.run_build`: the full build |

A preflight does not link or package, so a link error on a cross-compiled
target is still found by a release. Its compiles are cached per target, and a
target that passed is not preflighted again until the browser's compiled
inputs, `build-host` or the runner scripts change; the twice-weekly scheduled
run preflights every target regardless.

## Releases

One workflow, [`release.yml`](../.github/workflows/release.yml), makes every
browser release, on a **train**: on the 1st and 15th of each month the newest
browser **prerelease** is promoted to **stable**, and a new prerelease is cut
from `main`. Merges are tested by `tests.yml` but not released, so users see two
releases a month rather than one per merge. The same run publishes the
`camoufox` wrapper ([The driver](#the-driver)) when anything it ships changed:
`<next>bN` to PyPI and `<next>-beta.N` to npm `next` on a cut, `X.Y.Z` to PyPI
and npm `latest` on a `vX.Y.Z` tag. The driver itself is released from
camoucore, after the browser it needs.

```
1st and 15th ─► plan ─────────────────► promote-browser ─► cut
 (schedule)    (newest browser          v156.0.1-beta.N     │
                prerelease, no open     → stable, latest    │
                regression)                                 │
     ┌──────────────────────────────────────────────────────┘
     ▼
dispatch on main ─► ubo ─► tests ─► plan ─► build-browser ─► publish-browser
                  (AMO's  (tests.yml,       (only if its      v156.0.1-beta.N
                   newest) unless main's     sources changed)  (prerelease)
                           run passed it)

dispatch with promote ─► plan ─► promote-browser
```

| Rule | Detail |
|---|---|
| The train | The scheduled run promotes the newest browser release if it is still a prerelease, then its `cut` job dispatches `release.yml` on `main`. With nothing new since the last promotion it promotes nothing; a cut whose browser sources did not change publishes nothing. |
| A regression holds the train | While an issue labelled `regression` is open, the promotion fails and says which issues hold it; the cut still runs. The label must exist, so an empty answer means "none open", not "nobody could mark one". |
| Out of cycle | Run the Release workflow by hand on `main` (`gh workflow run release.yml --ref main`) to cut a prerelease now, or with `-f promote=true` to promote the newest prerelease now. |
| Only a tested commit is released | A cut calls `tests.yml` on its commit and continues only if it passes. A promotion requires `All tests passed` on the commit its release was built from, and that commit on `main`. |
| The browser is built only when its sources changed | `ci.browser_inputs.source_digest()` hashes the browser's sources. Each browser release carries a `manifest.json` with that digest, its commit, and the interface it speaks (`browser/INTERFACE`). A matching release is reused; otherwise `plan` takes the next unused `beta.N`. Nothing is committed: `ci.release set-build` writes the number into the build's tree. |
| uBlock Origin | Every browser package bundles the uBO release pinned in [`browser/scripts/data/ubo.json`](../browser/scripts/data/ubo.json) under `addons/UBO/` ([`browser/scripts/fetch-ubo.py`](../browser/scripts/fetch-ubo.py)), and the drivers load it from there. A cut reads the pin once, in the `ubo` job before `tests`, and hands it to the tests and every build, so the browser ships the uBO it was tested with. A bump is a reviewed commit (`fetch-ubo.py newest` prints the candidate). Its `manifest.json` (`ubo`) and release notes name it. A reused browser keeps the uBO it was built with. |
| Builds are attested | `gh attestation verify <file> --repo daijro/camoufox` |
| The pairing | `build-library` stamps the browser release built from the same sources into both copies of `browser-pin.json` and the wrapper versions into both manifests (`ci.release stamp --browser-tag <tag> --py-version <v> --npm-version <v>`), builds the wheel, sdist and npm tarball once, and checks that each installs and exposes the pin. To test a branch against a browser release, `ci.release stamp --browser-tag <tag>` without versions writes the pin into the installed packages, as `fetch-browser` does. |
| What publishes a wrapper | `ci.release lib-plan` publishes when anything the wrapper ships changed (`pyproject.toml`, `camoufox/`, `camoufox_pin/`, `npm/`, or the browser), each registry only if its package differs from the newest one there (`lib-diff`). It refuses a wrapper while `ci/driver-ref` is set or the pinned `camoucore` is missing from PyPI or npm: a stable tag fails, a prerelease publishes the browser alone. |
| Promotion | Refused unless the tag is a browser release, its commit is on `main`, and `All tests passed` succeeded on it. The release becomes stable and latest without a rebuild. |
| Failed publish | Re-run the failed jobs; every tag comes from `plan`. |
| Credentials | None stored. |

Releases cut before manifests existed (up to `v156.0.1-beta.32`) pair by the tag
`upstream.sh` names.

## Running a piece by hand

| Command | Needs a browser | What it runs |
|---|---|---|
| `python3 -m ci.run_prepare` | | `make setup-minimal`, `dir`, `mozbootstrap` |
| `python3 -m ci.run_build` | | The browser build and package for linux x86_64; `--target`, `--arch` for another |
| `python3 -m ci.run_build --target windows --arch x86_64 --preflight` | | Preflight one target |
| `python3 -m ci.run_patch_guards --binary <bin>` | yes | Patch guards; `--group spoofing\|automation\|parity`, `--only <name>` |
| `python3 -m ci.run_patch_guards --binary <bin> --only stock-gpu-parity` | yes | WebGL and WebGPU against stock Firefox of the same version, downloaded into `.ci-work` ([upgrade step](../docs/patch-upgrading-guide.md#browser-owned-gpu-values)) |
| `python3 -m ci.run_build_tester --binary <bin>` | yes | build-tester |
| `python3 -m ci.run_skiplist_audit --binary <bin>` | yes | Every skiplist entry still fails |
| `python3 -m ci.run_playwright --binary <bin>` | yes | The Playwright suite; `--shard 3/6` for one shard |
| `python3 -m ci.run_native --subset rules` | | Settled decisions |
| `python3 -m ci.run_native --subset browser --binary <bin>` | yes | Leaks, contexts, crashes |
| `python3 -m ci.run_native --subset growth --binary <bin>` | yes | Memory growth; `--shard 3/7` for one test |
| `CAMOUFOX_GPU=<pci> python3 -m ci.run_native --subset gpu --binary <bin>` | yes | `headless="virtual-gpu"` on a real GPU |
| `python3 -m ci.run_sundial --binary <bin>` | yes | The stealth grade (needs the credential) |
| `python3 -m ci.summarize --results-dir .ci-work/results` | | The summary table |
| `GITHUB_EVENT_NAME=schedule python3 -m ci.release target` | | What the train would promote |
| `python3 -m ci.release browser-plan` | | Whether a browser would be built or reused |
| `python3 -m ci.release paired` | | The release built from this tree |
| `python3 -m ci.release driver` | | The `camoucore` version the wrapper pins |
| `<venv>/bin/python ci/check_wrapper.py [--npm-dir DIR]` | | An installed wrapper is camoucore's launcher (run outside the checkout) |
| `python3 -m ci.check_no_driver` | | No launcher code in this repository, and no import of an unaliased `camoufox.<module>` |
| `python3 browser/scripts/fetch-ubo.py resolve` | | The uBlock Origin release a cut would bundle |
| `make -C browser stage-ubo` | | Bundle it into your build tree's `dist/bin`, as packaging does |
| `python3 -m pytest ci/tests -q` | | The pipeline's own tests |

`<bin>` is a `camoufox-bin`; `make -C browser path` prints the one in your
build tree. Each runner writes one result file to `.ci-work/results/`
(`run_prepare` writes none). A required suite with no result file is a
**failure**, never a skip.

The runners, and `ci/tests`, import the `camoufox` driver: install it first,
through the wrapper (`pip install ".[geoip]"` at the root) or from a camoucore
checkout (`scripts/install-driver.sh camoufox <venv> -`).

## Self-tests

`ci/tests/` asserts the pipeline reports honestly: redaction leaks nothing,
skips carry reasons, shards partition exactly once, and version resolution never
picks a suite newer than the browser. They run in the `static` job.

---

### Overview (`npm/README.md`)

# camoufox

The Node.js launcher for [Camoufox](https://camoufox.com), the anti-detect
Firefox build.

```sh
npm install camoufox playwright-core
npx camoufox fetch
```

```js
import { Camoufox } from "camoufox";
```

This package is the `camoucore/camoufox` launcher from
[camoucore](https://github.com/CamouBrowser/camoucore) under its own name, at
one exact camoucore version, plus the browser release it was tested with
(`camoufox/camoufox_pin/browser-pin.json`). `npx camoufox mcp` serves the
browser over MCP.

- Usage and launch options: [camoucore's camoufox docs](https://github.com/CamouBrowser/camoucore/blob/main/typescript/camoufox/docs/README.md)
- MCP server: [docs/mcp.md](https://github.com/CamouBrowser/camoucore/blob/main/typescript/core/docs/mcp.md)
- The browser: [daijro/camoufox](https://github.com/daijro/camoufox)

Launcher bugs and pull requests go to camoucore; browser ones to
daijro/camoufox. This package is MIT licensed (LICENSE); the browser it
downloads is under the Mozilla Public License 2.0.

---

### Overview (`browser/patches/playwright/README.md`)

# Playwright Patches

| File                 | Purpose                                                                                                                                                                                                                                                       |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `0-playwright.patch` | Playwright's Firefox patch ([`bootstrap.diff`](https://github.com/microsoft/playwright/blob/main/browser_patches/firefox/patches/bootstrap.diff)), ported to this Firefox version and carrying Camoufox's own changes to the same files. It is not a verbatim copy. |
| `1-leak-fixes.patch` | Reverts the part of `0-playwright.patch` a page can read: `navigator.webdriver` is `false`, as in a Firefox nobody is driving.                                                                                                                               |

---

### Overview (`browser/tests/build-tester/README.md`)

# Camoufox Build Tester

Tests a raw Camoufox binary (Firefox) directly against the same antibot-detection checks used in the service tests. Use this to validate a binary before packaging/releasing — it bypasses the Python package entirely.

To test against unreleased driver code, install it into `.venv/` first from a
[camoucore](https://github.com/CamouBrowser/camoucore) checkout
(`pip install -e <camoucore>/python`); `run_tests.sh` keeps it and
installs this repository's `camoufox` wrapper on top without dependencies.

## Prerequisites

- Python 3.10+ (what the `camoufox` driver requires)
- Node.js (for building the TypeScript checks bundle via `esbuild`)

## Setup

```bash
# Install npm deps (once — needed to build the checks bundle)
npm install

# Install Python deps
pip install -r requirements.txt   # the camoufox driver from PyPI, unless one is installed
```

## Usage

```bash
python scripts/run_tests.py <binary_path> [options]
```

**Example:**
```bash
python scripts/run_tests.py /path/to/camoufox-bin/camoufox
```

`./run_tests.sh <binary_path> [options]` does the setup for you: it installs the
npm dependencies and creates `.venv/` with the `camoufox` driver on first
run, then calls `run_tests.py`. It forwards every option below except `--json`.

In CI the suite runs through `python3 -m ci.run_build_tester --binary <path>`
from the repository root (see [`ci/README.md`](../../../ci/README.md)).

## Options

```
  binary_path           Path to the Camoufox (Firefox) binary
  --profile-count N     Number of profiles to test (1-8, default: 8)
  --secret KEY          HMAC signing key for certificate
  --save-cert PATH      Save certificate text to a file
  --no-cert             Skip certificate generation
  --json PATH           Write the full machine-readable result tree to PATH
```

## What It Tests

8 profiles total, run in two phases:

**Per-context phase (6 profiles)** — 3 macOS + 3 Linux profiles open simultaneously in a single browser instance, each with an isolated fingerprint injected via `addInitScript`. Tests that fingerprints are unique and don't leak between contexts.

**Global phase (2 profiles)** — 1 macOS + 1 Linux profile launched with fingerprint config passed via the `CAMOU_CONFIG` environment variable. Tests that browser-level fingerprint injection works correctly.

Each profile is scored across:

| Category | What it checks |
|---|---|
| Automation Detection | Playwright/CDP artefacts |
| JS Engine | V8 vs SpiderMonkey signals |
| Lie Detection | Inconsistent property overrides |
| Firefox APIs | Firefox-specific API presence |
| Cross-Signal | Consistency across navigator, screen, etc. |
| CSS Fingerprint | CSS rendering fingerprint |
| Canvas Noise | Canvas output is identical across renders (no random noise) |
| WebGL Render | WebGL rendering hash |
| Audio Integrity | AudioContext fingerprint |
| Font Platform | OS-consistent font availability |
| Speech Voices | Voice list matches declared OS |
| WebRTC | IP spoofing (test IP injected) |
| Stability | Fingerprint stable over time |
| Headless Detection | No headless mode signals |
| Match Results | Injected values actually appear in page |

A profile's grade is the share of its checks that pass: **A** 95% or more,
**B** 85%, **C** 75%, otherwise **F** (`scripts/grading.py`, shared with the
service tests).

## How It Differs from the Service Tests

| | Build Tester | Service Tests |
|---|---|---|
| Entry point | Raw binary path | `pip install camoufox` |
| Fingerprint injection | Manual (`generate_context_fingerprint` + init script) | Via `AsyncNewContext` API |
| Global mode | Yes (`CAMOU_CONFIG` env var) | No |
| Match validation | Yes (checks injected values match page) | No |
| Proxy support | No | Yes |
| Profile count | 8 (6 per-context + 2 global) | 6 (per-context only) |

## The Checks Bundle

`scripts/checks-bundle.js` is a compiled artifact built from the TypeScript sources in `src/`. A run rebuilds it whenever it is missing or older than any of them, so an edited check always takes effect.

Source files:
- `src/lib/checks/index.ts` — entry point
- `src/lib/checks/core.ts` — automation, JS engine, lie detection, etc.
- `src/lib/checks/extended.ts` — canvas, WebGL, fonts, audio, etc.
- `src/lib/checks/workers.ts` — worker thread consistency
- `src/lib/checks/collectors.ts` — fingerprint data collectors (hashes, WebRTC, stability)

---

### Overview (`browser/tests/cpu-probe/README.md`)

# CPU probe

What a page can compute that differs between CPUs, measured on stock Firefox.
`page.html` runs each test, hashes the result (FNV-1a) and POSTs the hashes;
`probe.py` serves it, launches a Firefox headless with a fresh profile and
prints the JSON. `compare.py` groups each key's values across result files.

    python3 -I probe.py <firefox binary> [pref=value ...] > result.json
    python3 compare.py results/*.json

Tests: Math functions (NaN results hashed as one value; NaN's bits are the
`nan` key), DOMMatrix, layout and SVG geometry with two webfonts, canvas (18
composite operations, gradients, paths, filter, drawImage, text), a WebGL
shader, WebAssembly relaxed SIMD (`relaxed.b64`), Web Audio nodes rendered
offline, and WebCodecs encoders.

The two webfonts come from Firefox's `layout/reftests/fonts`:
`DejaVuSansMono.woff` (Bitstream Vera license, DejaVu changes public domain)
and `VotoSerifGX.latin1.ttf` (SIL Open Font License 1.1). Each carries its
license in its `name` table.

`Dockerfile` (`--build-arg FFARCH=linux-x86_64` or `linux-aarch64`) runs the
same Firefox 159.0 on Linux for another architecture, with the same fonts, so
an ARM64 host's Linux values can be compared with x86-64's. WebGL is
unavailable in it.

## Results, stock Firefox 159.0 (`results/`)

| File | CPU | OS |
| --- | --- | --- |
| `linux-x86_64-i7-12700h` | Intel Core i7-12700H | Ubuntu |
| `windows-x86_64-i9-11900h` | Intel Core i9-11900H | Windows 11 26200 |
| `linux-x86_64-ryzen-9850x3d` | AMD Ryzen 7 9850X3D (Zen 5) | Ubuntu 26.04 |
| `linux-x86_64-threadripper-7970x-ff158` | AMD Threadripper 7970X (Zen 4) | Ubuntu, Firefox 158 (snap) |
| `linux-x86_64-docker-ryzen-9850x3d` | AMD Ryzen 7 9850X3D | Debian trixie container |
| `linux-arm64-docker-apple-m4` | Apple M4 | Debian trixie container (arm64) |
| `macos-arm64-apple-m4` | Apple M4 | macOS 27.0 |

What they show:

- Intel vs AMD: only the six estimate-based composite operations (`color`,
  `color-burn`, `color-dodge`, `hue`, `luminosity`, `saturation`) and the Opus
  encoder. Both are RCPPS/RSQRTPS, reproduced by `cpu-vendor-estimates.patch`
  (`docs/HOST-PARITY.md`).
- x86-64 vs ARM64 (same OS, same fonts, in the containers): every Web Audio
  node, every canvas composite operation, drawImage, filter and paths, Opus,
  VP9, 9 of 11 relaxed SIMD operations, and the sign of the default NaN.
  Layout, DOMMatrix, Math and text measurement agree. `cpu-vendor-estimates.patch`
  computes all of it on x86-64 when `general.cpu_identity` is 3, and the x86
  values on ARM64 when it is 1 or 2; the guard `cpu-vendor-estimates` checks
  it against `linux-arm64-docker-apple-m4`, `linux-x86_64-i7-12700h` and
  `linux-x86_64-docker-ryzen-9850x3d`.
- OS, not CPU: Windows differs in Math sin/cos/tan/pow, layout, DOMMatrix,
  text and Vorbis; macOS in pow, layout, DOMMatrix and text.
- Host-dependent rather than CPU-dependent: H.264 encoder availability,
  WebGL renderer and shader, hardwareConcurrency. The Firefox 158 run also
  differs in canvas paths and AV1.

---

### Overview (`browser/tests/playwright/README.md`)

# Tests

Three things live here, and none is a copy of anyone else's suite.

### `patches/` — patch guards

One standalone script per shipped behaviour. Each exits 0 or 1 and drives the
browser through the Python package. Whether the patches *apply* is the build's
check; these are the most direct evidence that a Firefox bump did not quietly
neuter a patch that still applies cleanly — the failure a compile check cannot
catch.

Each guard belongs to one of three groups (`GROUPS` in
`ci/run_patch_guards.py`), and CI runs each group as its own job:

- **spoofing**: a spoofed value still reaches the page and holds together (media devices, voices, fonts, the touchscreen digitizer, the sealed setters, …);
- **automation**: Playwright stays invisible to the page and never deadlocks it (isolated evaluate, trusted events, edge-case mouse input, …);
- **parity**: what a page or the OS can observe matches stock Firefox (content-accessible files, GPU probes, browser-owned WebGL and WebGPU values against stock Firefox of the same version, the popup blocker, the Windows manifest, …).

A new guard must be added to a group; `ci/tests` fails until it is.

```bash
python3 -m ci.run_patch_guards --binary /path/to/camoufox-bin
python3 -m ci.run_patch_guards --binary /path/to/camoufox-bin --group automation
python3 -m ci.run_patch_guards --binary /path/to/camoufox-bin --only isolated-evaluate
```

### `juggler/` — unit tests for Juggler's input modules

The browser plans no input of its own: each Playwright call is one event, and
humanization is the driver's (docs/humanize.md). What is left to test without a
build is `browser/additions/juggler/input/HumanDelay.js`, the draw behind the
paste and auto-Shift modifier timing, a plain ES module that runs under Node.
`gecko.mjs` supplies the Gecko global it is loaded through.

```bash
node --test browser/tests/juggler/*.test.mjs
```

### `camoufox/` — Camoufox's own Playwright tests

Tests for behaviour upstream Playwright has no equivalent for, or asserts the
opposite of on purpose. `ci/suite.py` overlays them onto the upstream checkout
so they run against its harness. See `camoufox/README.md` for when to add one.

---

## Why there is no vendored suite

This directory used to hold a fork of a v1.55-era playwright-python suite. It
was deleted because it was weaker than upstream's own: 73 of the 74 tests it
skipped as "Not supported by Camoufox" passed in upstream's copy, and only eight
of its passing tests had no upstream counterpart (six now live in `camoufox/`,
the other two had been renamed upstream).

`ci/run_playwright.py` instead fetches playwright-python at the tag
`ci/versions.py` resolves, applies `ci/skiplist.yml` and overlays `camoufox/`.
A suite fetched every run cannot go stale, and a deliberate difference from
upstream has to be written in the skiplist with a reason. How the suite runs:
[`ci/README.md`](../../../ci/README.md#the-playwright-suite).

```bash
make -C browser tests                  # the whole suite
make -C browser tests headful=true     # ... headed
python3 -m ci.run_playwright --binary /path/to/camoufox-bin --shard 3/6
```

---

### Overview (`browser/tests/service/README.md`)

# Camoufox Service Tests

End-to-end antibot-detection tests that verify a pip-installed camoufox release works correctly — both the Firefox binary and the Python package — using real proxies for each browser context.

## Prerequisites

- Python 3.10+ (what the `camoufox` driver requires)
- Node.js (for building the TypeScript checks bundle via `esbuild`)
- At least one proxy in `proxies.txt`

## Quick Start

```bash
# 1. Add your proxies (see format below)
# 2. Run the test script — it handles everything else automatically
./run_tests.sh
```

`run_tests.sh` will:
1. Install npm deps in `../build-tester/` (for `esbuild`, first run only)
2. Create a `.venv` virtualenv (first run only)
3. Install the `camoufox` driver from PyPI (tests the actual published package). Set `CAMOUFOX_DRIVER` to install another: a pinned version (`camoufox==0.6.0`) or a [camoucore](https://github.com/CamouBrowser/camoucore) checkout (`<camoucore>/python`, which gets this repository's `camoufox` wrapper on top)
4. **Phase 1** — run the suite against the locally compiled binary, auto-detected from:
   - macOS: `../../camoufox-*/obj-*-apple-darwin/dist/Camoufox.app/Contents/MacOS/camoufox`
   - Linux: `../../camoufox-*/obj-*-linux-*/dist/bin/camoufox-bin`

   Skipped (with a notice) if no local build is found. On macOS, the script also copies `properties.json` from `Camoufox.app/Contents/Resources/` into `MacOS/` so the driver can locate it next to the binary.
5. **Phase 2** — download the official binary (`--browser-version`, default `official/stable`) and run the suite against it
6. Exit `0` only if both phases pass

Use `--binary local` or `--binary fetched` to run only one phase.

On Windows, `.\run_tests.ps1` does the same in PowerShell, with the local build
looked up at `..\..\camoufox-*\obj-*-windows-msvc\dist\bin\camoufox.exe`. Its
options are the ones below in PowerShell form (`-BrowserVersion`,
`-ProfileCount`, `-Proxies`, `-Headful`, `-NoCert`, `-SaveCert`, `-Binary`).

> **Heads-up on Phase 2:** if the latest `official/stable` is older than the Firefox version the installed driver targets, the binary may not understand newer fingerprint patches and the test page can fail to produce results. Pin a newer binary with `--browser-version` to avoid this.

## Proxies

Tests require real proxies. Each context gets its own proxy, and `AsyncNewContext` takes its WebRTC IP, timezone, locale and geolocation from the proxy's exit IP.

Create `proxies.txt` in this directory with one proxy per line:

```
user:pass@domain:port
```

Example:
```
alice:secret123@proxy1.example.com:10000
bob:hunter2@proxy2.example.com:10000
alice:secret123@proxy1.example.com:10001
```

- Blank lines and lines starting with `#` are ignored
- Proxies are assigned round-robin across the 6 test profiles
- Fewer proxies than profiles is fine — they cycle
- `127.0.0.1` and `localhost` are bypassed automatically so the local test-page server stays reachable

## Manual Setup

If you prefer to run steps individually:

```bash
# Install build-tester deps (once)
cd ../build-tester && npm install && cd ../service

# Create and activate virtualenv
python3 -m venv .venv
source .venv/bin/activate

# Install the driver (or a camoucore checkout's python/ folder, then
# `pip install --no-deps` this repository's root for the camoufox wrapper)
pip install camoufox

# Download the browser binary
python -m camoufox fetch

# Run tests
python run_tests.py
```

## Options

```
./run_tests.sh [options]
python run_tests.py [options]

  --browser-version VER   Camoufox version specifier (default: official/stable)
                          e.g. official/prerelease/<version>-<release>
  --profile-count N       Number of profiles to test (1-6, default: 6)
  --proxies PATH          Path to proxies file (default: proxies.txt)
  --headful               Run with visible browser window
  --no-cert               Skip certificate generation
  --save-cert PATH        Save certificate text to a file
  --secret KEY            HMAC signing key for the certificate
                          (run_tests.py only)
  --binary MODE           Which binary to test: local | fetched | both (default: both)
                          (run_tests.sh only — orchestrates the two phases)
  --executable-path PATH  Run against a specific binary path
                          (run_tests.py only — used internally by phase 1)
```

## What It Tests

6 browser contexts run simultaneously — 3 macOS profiles and 3 Linux profiles — each with:

- A unique fingerprint generated by camoufox via fpgen (navigator, screen, WebGL, fonts, voices)
- A distinct timezone
- Its own proxy, with WebRTC ICE candidates spoofed to the proxy's exit IP

Each context is scored across the same categories as
[build-tester](../build-tester/README.md#what-it-tests), except Match Results.
How the two suites differ is in
[build-tester's README](../build-tester/README.md#how-it-differs-from-the-service-tests).

## Interpreting Results

Grading is shared with build-tester (`../build-tester/scripts/grading.py`): a
profile's grade, and the overall grade, come from the share of checks passed.

| Grade | Checks passed |
|---|---|
| **A** | 95% or more |
| **B** | 85% or more |
| **C** | 75% or more |
| **F** | less than 75% |

A grade of **A or B** exits with code `0`. Anything worse exits with code `1`.

The run ends with a **SERVICE VERIFICATION CERTIFICATE** (unless `--no-cert`),
followed by the list of proxies used. Its cross-profile uniqueness section
confirms each context has distinct audio, canvas, timezone, and screen
fingerprints.

## Failure Triage

If a check fails, **fix it in the Python package** (`python/camoufox/src/` in [camoucore](https://github.com/CamouBrowser/camoucore)), not in the test. The test is intentionally a black-box validator — it only uses the public `AsyncNewContext` API and trusts camoufox to produce correct fingerprints.

---

### Overview (`browser/tests/playwright/camoufox/README.md`)

# Camoufox's own Playwright tests

Tests for behaviour that is **specific to Camoufox** and therefore has no
upstream equivalent -- either because upstream never tested it, or because
upstream tests for the stock-Firefox behaviour that this fork deliberately does
not have.

These are not a fork of anything. `ci/suite.py` copies them into the upstream
playwright-python checkout it prepares for each run (`tests/async/`), so they
execute against **upstream's current harness** -- its `conftest.py`, its
`server.py`, its fixtures -- at whatever tag `ci/versions.py` resolved. Nothing
here is frozen, so nothing here goes stale the way a vendored suite does.

Write a test here when, and only when, one of these is true:

- **Camoufox has a behaviour upstream has no test for.** `test_route_request_fingerprint.py`
  is the example: enabling request interception must not change what a request
  looks like on the wire (daijro/camoufox#428, #271). Stock Playwright does not
  care, so upstream has nothing to say about it.

- **Upstream asserts the stock-Firefox behaviour and Camoufox is right not to
  match it.** The upstream test is skiplisted in `ci/skiplist.yml` and the
  version here takes over guarding the behaviour.

In the second case the `ci/skiplist.yml` entry must name the test that replaces
it, so a skip can never quietly mean "nothing checks this any more".

Everything else belongs upstream, where it is maintained for free.

---

### FONTS (`docs/FONTS.md`)

# Bundled fonts: what ships, what is reported, how to verify

Camoufox ships its own fonts so that font enumeration and text rendering are a
property of the *claimed* OS rather than of the host. There are two halves: a
font bundle (`browser/bundle/fonts/`) and one fontconfig per OS
(`browser/bundle/fontconfig/<os>/fonts.conf`). The data the launcher draws from
(`fonts.json`, `font-bases.json`, `font-groups.json` and `essential-fonts.json`
in the driver's [`camoucore/camoufox/`](https://github.com/CamouBrowser/camoucore/blob/main/python/camoufox/src), in
camoucore) is generated against that bundle and must be regenerated
with it. The marker fonts and Windows 11 marker fonts, in `markerFonts` and
`windows11MarkerFonts` of the driver's `launcher-constants.json`, are
kept by hand and must name fonts the bundle has.

## Getting the bundle

The bundle is **a release asset, not repo content** — 1513 faces, 2.16 GB
extracted, 843 MB as `.tar.xz`. It cannot live in git: GitHub caps a tracked
file at 100 MiB (`Apple Color Emoji.ttc` alone is 183 MiB) and an `.xz` archive
cannot be delta-compressed, so every font update would append another ~843 MB
blob to history forever. Release assets allow 2 GB per file, which fits the
whole bundle with no splitting and no LFS. It is the same trust model the build
already uses for the Firefox source itself.

```
make -C browser fetch-fonts     # download + verify the archive (browser/bundle/fonts-bundle-*.tar.xz)
make -C browser fonts-extract   # ...and unpack it to browser/bundle/fonts/   (gitignored)
make -C browser fonts-check     # verify the archive against the pin; non-zero if absent
make -C browser fonts-clean     # drop the extracted tree
```

`browser/scripts/data/font-bundle.json` pins the tag, asset name, size and **sha256**,
so a given commit expects one exact bundle and a truncated or substituted
download fails loudly instead of silently producing a browser that reports fonts
it cannot draw. `make fonts-extract` stamps the unpacked tree with that sha256
(`browser/bundle/fonts/.bundle-sha256`), so re-running it is free — which is what lets
`package-*` and `stage-fonts` depend on it unconditionally.

The asset is hosted by this repository, never by a fork: a build input that
lives in someone's personal account breaks the moment that account renames the
repo or deletes the release.

Publishing a new bundle: rebuild the archive, `python3 browser/scripts/fetch-fonts.py
--write-spec <archive> --tag font-bundle-vN`, then upload it under that tag.
Font-bundle tags do not match `release.yml`'s `vX.Y.Z` trigger, so they do not
start a release, and they carry no `manifest.json`, so no library pairs with them.

## Layout: each face stored once

A face used by several OSes is stored **once**, in a directory named for the set
of OSes that use it. `browser/bundle/fonts/groups.json` records which groups each OS
reads.

| group | faces | read by |
|-------|------:|---------|
| `LMW` | 328 | all three |
| `LM`  |  92 | Linux + macOS |
| `LW`  |  71 | Linux + Windows |
| `MW`  |  48 | macOS + Windows |
| `L`   | 301 | Linux only |
| `M`   | 311 | macOS only |
| `W`   | 362 | Windows only |

An OS reads the four groups its letter appears in: Linux `L+LM+LMW+LW` (792
faces), macOS `LM+LMW+M+MW` (779), Windows `LMW+LW+MW+W` (809). Storing a full
copy per OS instead made 41% of the bundle byte-identical duplicates (2955 files
/ 3.96 GB became 1513 / 2.16 GB) while leaving every OS's set unchanged.

Every package ships **all seven groups**, so the fingerprint is built from the
fonts actually available. What differs is how they are gated:

- **Linux packages** keep the group subdirectories and `groups.json`.
  `utils._generate_fontconfig` reads it at launch and hands fontconfig one
  `<dir>` per group the claimed OS reads. The parent is never named, because
  fontconfig scans `<dir>` **recursively** — naming it would put every other
  OS's faces on the search path.
- **macOS and Windows packages** flatten the groups into one directory: CoreText
  and DirectWrite activate a single directory and cannot read subfolders. There
  is no directory gate on those hosts; the allowlist in
  `browser/patches/font-hijacker.patch` is what restricts a lookup. Basenames therefore
  must not collide within a package's group set, which `verify-fonts.py` checks.
- **On Linux, a launch without the launcher's config gets the host's fonts.**
  It claims no OS, fontconfig uses the host's own configuration, and
  `font-hijacker.patch` adds only the files directly in `fonts/` (Firefox's
  `TwemojiMozilla.ttf`), as stock does, never the group subdirectories.
  `browser/tests/playwright/patches/bare-launch-host-fonts.py` checks it.
- **On a macOS host, a file holding a hidden system face (a PostScript name
  starting with `.`) is never activated.** WebRender loads those by name and gets
  the host's copy, so the UI drew wrong glyphs (#918). Check it on a Mac with
  `browser/scripts/check-macos-hidden-fonts.py`.

This replaced the 455 `<glob>` duplicate-face rejects the Windows fontconfig used
to carry. They were redundant under grouping and also unsound: 114 bundled
filenames contain `[ ]` (e.g. `ReemKufi[wght].ttf`), which fontconfig parses as a
character class, so those rejects silently matched nothing.

## The two invariants

**1. Everything reported must be renderable.** Every family the launcher may
report for an OS must be one the packaged browser can draw under that OS's
bundled fontconfig. `font-hijacker.patch` prunes lookups by family name *after*
fontconfig substitution, so a reported name fontconfig cannot resolve measures
as the fallback — a **reverse leak**. The old `fonts.json[mac]` carried 70 such
names (Hiragino etc.); the current lists carry none.

**2. Nothing outside an OS's groups may be reachable.** The converse, and the
one the group layout exists to enforce: a Windows identity must not be able to
render a macOS-only face, or an emoji/CJK glyph can fall back to Segoe UI Emoji
or PingFang on a machine claiming Linux. No reported name reveals this, and no
draw test can see it — it is checked directly, by asking fontconfig for every
file it can reach under each OS's conf and requiring all of them to sit inside
that OS's own groups (810 / 780 / 793 faces, including browser-shipped
`TwemojiMozilla.ttf`).

The reverse direction of invariant 1 is deliberately loose: an OS renders more
families than it ever reports (529 published vs 335 reported on Windows, 872 vs
567 on macOS, 583 vs 358 on Linux; `gen-fonts-json.py --dump-union` lists the
gap). Those are names a real OS never presents as a family — weight-variant
subfamilies DirectWrite folds into their parent ("Barlow Black"), the bare
`Sitka` / `Segoe UI Variable` umbrella names, and CJK families a stock install
does not report. They stay renderable but unreported.

## How `fonts.json` is derived (`browser/scripts/gen-fonts-json.py`)

```
reportable[os] = fc-scan(the groups <os> reads)          families fontconfig publishes
               + SCAN_FAMILIES                           Sitka * / Segoe UI Variable * (scan-time matches)
               + ALIASES                                 names fonts.conf rewrites to a bundled target
               + SHIPPED_BY_BROWSER                      Twemoji Mozilla (from the Firefox build)
               ∩ names(browser/scripts/data/font-manifests.json) bases + additions + marker fonts for that OS
               + ALIASES, REPORTABLE_EXTRA               forced in
```

Namespace matters here and is easy to get wrong: Windows and macOS enumerate the
**legacy family** (nameID 1), while Linux enumerates through **fontconfig**.
`system_profiler` and WPF report *typographic* families (nameID 16), a different
namespace — a list gathered that way will disagree with what a browser sees.

`--print-bases` prints the OS base lists intersected with the result and writes
them to `essential-fonts.json`. Each OS's list there is the
**intersection** of an OS's bases, never a superset: a name present in only one
version's base must not be forced onto every identity, or that version's base
becomes a no-op.

Regenerate together whenever the bundle changes:

```
python3 browser/scripts/gen-font-groups.py          # font-groups.json + font-bases.json
python3 browser/scripts/gen-fonts-json.py           # fonts.json
python3 browser/scripts/gen-fonts-json.py --print-bases   # essential-fonts.json
python3 browser/scripts/verify-fonts.py             # must pass before committing
```

Deliberate choices:

- **Windows aliases are unconditional and always reported.** The 13
  GDI-substitution / Light-Semilight rules (`Courier -> Courier New`,
  `Helvetica -> Arial`, `Calibri Light -> Calibri`, ...) are unconditional in
  `browser/bundle/fontconfig/windows/fonts.conf` because there is no per-launch
  fontconfig hook, and the names are in `essential-fonts.json`'s Windows list. That matches
  reality: every Windows install resolves all of them.
- **macOS TTC weight names are reported.** The confs rewrite `American
  Typewriter Semibold`, `Futura Bold`, `STIX Two Math Regular`, ... to their base
  family. A real Mac registers those as families but `fc-scan` cannot see them,
  so the ones whose target is bundled are forced in.
- **An alias name is essential only where its target is in every base.** A
  name fonts.conf rewrites renders only through its target, so it joins a base
  only with it. On Linux, `Calibri` and `Cambria` resolve to Carlito and
  Caladea, which come with LibreOffice (the `libreoffice` addition) and are in
  neither Ubuntu base: a draw without that bundle does not have them, as a
  stock Ubuntu without it does not. Every Linux identity used to claim both,
  and they rendered only because the bundled-font activation leaked Windows'
  own Calibri and Cambria to every OS. macOS's `Noto Sans Canadian Aboriginal
  Regular` left the floor for the same reason (its family is not in every
  macOS base).
- **`Twemoji Mozilla` is reportable on Linux** (a CreepJS Linux marker, and
  Firefox exposes its bundled font to content). Not reported on macOS.
- One name renders for every Linux identity but is not always reported
  (`Noto Sans Canadian Aboriginal Regular`) because a real Ubuntu does not report
  it. `verify-fonts.py` warns rather than fails.

## The per-launch draw (`fingerprints._generate_random_font_subset`)

Modelled on how real machines actually differ: one OS-version base, always whole,
plus independent per-unit draws. Not a uniform percentage of a pool.

1. **One base, drawn by weight, always complete.** A real machine has all of its
   OS defaults, so a base is never sampled.

   | OS | bases (weight / families) |
   |----|---------------------------|
   | Windows | `win11` 1.00 / 125 |
   | macOS | `sonoma` 0.20 / 499 · `tahoe26` 0.65 / 364 · `macos27` 0.15 / 361 |
   | Linux | `ubuntu2404` 0.45 / 257 · `ubuntu2604` 0.55 / 266 |

   Windows 10 was dropped entirely. macOS 27 differs from 26.6.2 by only three
   families and is identified by the *absence* of `Noto Sans Brahmi` /
   `Noto Sans CanAborig`.

2. **The essential floor** (`essential-fonts.json`: 125 / 368 / 272) — the
   intersection of that OS's bases, so it holds whichever base was drawn.

3. **Per-unit Bernoulli draws, per OS.** Each addition is one independent
   decision at its own measured probability. `kind: bundle` is atomic — it
   installs whole or not at all. `kind: alacarte` is piecemeal: on a hit, a
   size is drawn from its `sizes` distribution and that many families are taken.
   `requiresLocale` gates a unit on the identity's locale (e.g. `cjk-tc` on
   `zh-TW`).

   | unit | kind | Windows | macOS | Linux |
   |------|------|--------:|------:|------:|
   | `office` | bundle | 0.602 | — | — |
   | `apple-optional` | bundle | — | 0.818 | — |
   | `hololens` | bundle | 0.592 | — | — |
   | `distro-i18n` | bundle | — | — | 0.372 |
   | `libreoffice` | bundle | 0.066 | — | 0.112 |
   | `pan-euro` | bundle | 0.028 | — | — |
   | `cascadia` | bundle | 0.100 | 0.060 | 0.080 |
   | `meslo` | bundle | 0.040 | 0.040 | 0.060 |
   | `cjk-tc` | bundle (`zh-TW`) | 0.900 | — | — |
   | `dev` | à la carte | 0.038 | 0.070 | 0.174 |
   | `web` | à la carte | 0.088 | 0.270 | 0.195 |

   `apple-optional` is one atomic unit rather than base because Apple ships those
   57 faces as optional Font Book downloads, and the fpgen corpus puts all of
   them on exactly 81.8% of Macs.

4. **Marker fonts** appended if missing (`_ensure_marker_fonts`).

Resulting list sizes over 20 draws: 125–281 of 335 (Windows), 369–526 of 567
(macOS), 278–319 of 358 (Linux).

For a **native** identity — the host's own OS — on macOS and Windows the draw
claims the OS base only, because the real system fonts are the right ones there
and `font-hijacker.patch` does not activate the bundle. On a Windows host the
Win11 marker families are *subtracted* when the host cannot render them, rather
than added when it can; claiming a marker the host lacks is the leak.

The driver's `tests/test_font_distribution.py` covers this: base
completeness and weights, per-unit probability, bundle atomicity, à-la-carte
sizing, locale gating, determinism, renderable-only, and that the draw actually
varies (distinct lists, no single list dominating). Tolerances are binomial, at
5σ, so they fail on a real shift rather than on noise.

## fontconfig parity

Linux: generics resolve as a stock Ubuntu does (`sans-serif` → Noto Sans,
`serif` → Noto Serif, `monospace` → DejaVu Sans Mono, `cursive` → Z003),
`hintstyle` is `hintslight`, and the stock metric aliases (30-metric-aliases),
49-sansserif, urw-base35 and the non-Latin rule files are merged in stock
`conf.d` order. Windows: `sans-serif` → Arial, `serif` → Times New Roman,
`monospace` → Consolas, `cursive` → Comic Sans MS, plus `MS Shell Dlg 2 ->
Tahoma`, the `Sitka` / `Segoe UI Variable` scan-time instance families and the
alias block above. macOS: Helvetica / Times / Menlo / Apple Chancery / Zapfino.
`system-ui` is left to Gecko, which resolves it itself. The
`<dir prefix="cwd">fonts</dir>` line that `utils.py` rewrites is kept in all
three — `verify-fonts.py` fails if it is missing.

## Verifying

```
python3 browser/scripts/verify-fonts.py          # full: builds a fontconfig cache over the bundle, minutes on first run
python3 browser/scripts/verify-fonts.py --quick  # constants, draws and layout only
cd python && python3 -m pytest -q -k "font or humanize or launch_environment"
```

The full run checks, per OS: `fonts.json[os]` ⊆ what `fc-list` publishes (aliases
resolved via `fc-match`), no file reachable outside that OS's groups, generics
resolve to a reportable family, essential / variant / marker ⊆ `fonts.json`,
every OS version that reports an alias's target reports the alias, 20 draws stay
inside `fonts.json`, each face stored exactly once, no subfolders, and no
basename collisions within a package's group set. The release runs the full
check; every pull request runs `--quick` on the fonts its build carries.

## Known residue

- **The Linux base over-claims against the recorded corpus.** A draw reports a
  median ~287 families where real Linux machines in the corpus report ~100. The
  cause is that the bundle ships fontconfig's `30-metric-aliases`, so
  Arial/Times/Courier always resolve and must therefore always be reported.
  Closing it needs either distro base variants or a change to which aliases ship.
- **The macOS base weights (0.20 / 0.65 / 0.15) are estimates.** There is no
  version-share data source behind them, unlike the addition probabilities,
  which are measured. Sonoma's base is inherited and not re-verifiable on
  current hardware.
- **Nothing has been checked in a running browser.** Both invariants above are
  verified at the fontconfig layer, which is the gate on Linux packages. On
  macOS and Windows hosts the gate is the allowlist patch instead, and that has
  not been exercised against the flattened group layout.

---

### HOST PARITY (`docs/HOST-PARITY.md`)

# Host parity: a Windows identity on a Linux host

The Linux build is meant to pass for Firefox on the OS it claims. Measured
against stock Firefox on Windows 10, Windows 11 and Linux, some answers still came from
the host. This lists each one, what a page reads, and how it is closed.

| Tell (before) | What the page read | Fix | Where |
|---|---|---|---|
| Math from the host's libm | `Math.sin/cos/tan/pow` differ from Windows 11 in the last bit (beta.40 against stock Firefox 158 on Windows 11 25H2: sin 345, cos 458, tan 753 of 33,386 inputs, about 1% of a million random ones; pow 10 of 27,249 and 398 of a million random) | the algorithms the Windows CRT uses (`javascript.options.use_ucrt_math`): for pow, Arm's optimized-routines pow (128-entry log table, 256-entry exp table, FMA in the log step), which Windows 11 24H2 and later ship; for sin/cos/tan, Cody-Waite and Payne-Hanek reduction with AMD LibM's kernels, and the CRT's NaN for an infinite argument. Tables generated from their definitions (`browser/scripts/gen-ucrt-math-tables.py`); checked bit for bit against outputs recorded from `ucrtbase.dll` (`browser/tests/ucrt-math/`) and from Windows Firefox | `windows-crt-math.patch`, launcher |
| GTK keyboard | Ctrl+Up in `<textarea>` moved up a line (Windows: line start); Alt+Backspace no undo; Shift+Delete with nothing selected did nothing; Ctrl+/ selected all; AltGr `keyCode` 225 (Windows: 18); Ctrl+Backspace on a rich-text selection deleted only the selection | `input:windowsKeyboard`: Windows' shortcut tables replace GTK's text bindings (native and the ones synthesized events get), AltGr reports Alt, Windows' caret style in HTML editors. Launch-wide; set it `false` to keep Linux behaviour. The tables, text bindings and AltGr are GTK code, so on a macOS host only the caret style changes | `windows-keyboard.patch`, launcher |
| Linux behaviour defaults | middle click pastes the primary selection, double-click selects no trailing space, instant fullscreen, GTK scrollbar clicks | Windows' defaults (`windowsBehaviourPrefs` in `launcher-constants.json`). Measured on stock Windows: `middlemouse.paste`, `general.autoScroll`, `eat_space_to_next_word`, the fullscreen transition. From Firefox 158's `all.js`, `firefox.js` and `StaticPrefList.yaml` only: `middlemouse.scrollbarPosition`, `ui.scrollToClick`, `slider.snapMultiplier`, `click_and_hold_track` | launcher |
| Scrollbars from the host theme | a Windows 10 identity's classic scrollbars 12 px (GTK's); stock Windows 17 px | Windows' non-native scrollbars (`widget.non-native-theme.scrollbar.style` 4 or 5, following `ui.useOverlayScrollbars`) at Windows' size | launcher |
| Native line endings from the build | `new Blob(["a\nb"], {endings: "native"}).size` was 3 on the Linux build claiming Windows (stock Windows 159: 4, i.e. `"a\r\nb"`); `Selection.toString()` across `<p>x</p><p>y</p>` gave `"x\n\ny"` where Windows gives `"x\r\n\r\ny"` | both answered from the presented OS by `MaskConfig::NativeLineBreakIsCRLF()` instead of `#ifdef XP_WIN` / `NS_ULINEBREAK`; a Linux build claiming Windows reports CRLF, and a Windows build claiming macOS or Linux reports LF | `native-line-break.patch` |

These apply only when the identity claims Windows and the host is not Windows;
on a Windows host the build already behaves this way. Every default yields to a
value the caller sets. Native line endings are the exception in that they are
answered from the presented OS in both directions: a macOS or Linux identity
reports LF even on a Windows host.

They are the browser's, not a context's: prefs and launch config set from the
OS the browser was launched with. On a browser launched as Windows, a context
created with `NewContext(os="macos")` still has Windows' math, keyboard,
behaviour and native line endings; on a browser launched as Linux, a Windows
context has Linux's.
`NewContext` does not refuse that, because a launch without `os` draws its OS
from fpgen's mix, and a refusal would then come and go with the draw. Launch
with the `os` whose behaviour the contexts need, or one browser per OS.

## AltGr: what is left

On Windows, AltGr is Ctrl+Alt to the OS. Pressing it sends a ControlLeft
`WM_KEYDOWN` before the AltRight one (Firefox's `widget/windows/KeyboardLayout.cpp`
says so), so stock Firefox on Windows fires a `keydown` with `code`
`ControlLeft`, `key` `Control` and `ctrlKey` true, then one with `code`
`AltRight`, `key` `AltGraph` and `keyCode` 18. While AltGr is down on a layout
that has it, Firefox's `ModifierKeyState` sets only the AltGraph modifier, so
the AltGraph events and the characters typed with it carry `ctrlKey` and
`altKey` false, as they do here. (Chromium on Windows reports them true; Firefox
does not.)

This build fires the AltRight event with Windows' `keyCode` (18) but not the
ControlLeft events before and after it. Adding them means dispatching extra key
events from GTK's `KeymapWrapper`, which `GetDOMKeyCodeFromKeyPairs` cannot do,
and their order on release (ControlLeft before or after AltRight) has to be
recorded on Windows first. So a page that listens for the ControlLeft keydown
around AltGr can still tell. Pages see this only from a keyboard layout with
AltGr; a US layout has none.

## Reference data for the math

Both references were recorded on Windows; neither can be produced on Linux.
They come from one machine: Windows 11 25H2 (build 26200.9711) on an Intel
i9-11900H, which has FMA3, so the CRT takes its FMA3 paths.

- `browser/tests/ucrt-math/expected.u64.xz` is what `ucrtbase.dll`
  10.0.26100.9711 returns for every input in `inputs.py`, written by
  `record.py` with its provenance in `provenance.json`. It depends only on the
  CRT, not on Firefox.
- `browser/tests/playwright/patches/assets/windows-crt-math.json` is what stock
  Firefox 158.0 (the release build from archive.mozilla.org) returned on that
  machine for a sample of those inputs, cold, JIT-hot and constant-folded,
  written by `record_firefox.py`. The three paths agreed on every input;
  `check.py` checks that the sample is the one `record_firefox.py` draws and
  that each result there that comes from the CRT equals `expected.u64.xz`'s.

Every other `Math` function (exp, log and their variants, the inverse and
hyperbolic trig functions, cbrt, sqrt, atan2, hypot) uses fdlibm on Windows as
it does here; on 200,000 random inputs each, and on all three paths, they
matched stock Windows Firefox 158 bit for bit without any change.

Windows 10 and Windows 11 before 24H2 ship an older `ucrtbase.dll` (10.0.22621
and earlier) whose pow is AMD LibM's, not Arm's. Its results differ from the
24H2 pow in about 0.2% of the inputs in `inputs.py` (52 of 27,249). This build
returns the 24H2 results, so against a Windows 10 identity those pow results
are the newer Windows'. sin, cos and tan are the same in both.

Re-record on the pinned Firefox version when an update touches SpiderMonkey's
sin, cos, tan or `ecmaPow`, the JIT's paths to them, or constant folding, and
on a new Windows build when its `ucrtbase.dll` changes.

## CPU vendor: the estimate instructions in Skia and libopus

Unlike the rows above, this one is about the CPU, not the OS, and applies on
every host OS. Skia's raster pipeline uses RCPPS and RSQRTPS, x86's
reciprocal and reciprocal-square-root estimates, for the non-separable and
dodge/burn blend modes, perspective and matrix inversion. Both are specified
only to a relative error of 1.5 * 2^-12, and Intel and AMD meet that with
different tables, so a canvas drawn with those operations reads back
differently on the two vendors.

Measured over all 2^32 inputs (`browser/tests/cpu-estimates/`): an Intel Core
i7-12700H (Linux) and an i9-11900H (Windows 11) give the same bits; a Ryzen 7
9850X3D (Zen 5) and a Threadripper 7970X (Zen 4), both Linux, give the same
bits; Intel and AMD differ. Intel's rcp depends on the top 11 mantissa bits and
its rsqrt on the top 10, AMD's on 12 for both.

Stock Firefox 159.0, a 96x64 canvas with a gradient over a gradient, hashed
from `getImageData`: on the i9-11900H (Windows) and the Ryzen 9850X3D (Linux),
`source-over`, `multiply`, `screen` and `soft-light` agree, while `color-dodge`,
`color-burn`, `hue`, `saturation`, `color` and `luminosity` differ. The guard
`browser/tests/playwright/patches/cpu-vendor-estimates.py` carries this probe
and both vendors' values.

libopus's PVQ search (`celt/x86/vq_sse2.c`, the encoder) uses the same two
instructions, so an Opus stream encoded by the page also names the vendor:
WebCodecs' `AudioEncoder` (Opus, 64 kbit/s, mono, one second of a fixed
signal) gives one byte stream on the i7-12700H and the i9-11900H and another on
the Ryzen 9850X3D and the Threadripper 7970X (Firefox 158). MediaRecorder and
WebRTC encode with the same code. Decoding does not use the estimates.

`cpu-vendor-estimates.patch` adds `general.cpu_identity` (0 host, 1 Intel,
2 AMD, 3 ARM64). When it names the other x86 vendor, the two Skia functions compute
the estimate from the recorded table (`SkCpuEstimates.h`,
`SkCpuEstimateTables.h`, generated by `browser/scripts/gen-cpu-estimate-tables.py`)
lane by lane instead of with the instruction. libopus is linked into
libgkcodecs, which cannot read prefs, so Gecko hands it the same table
(`opus_mozilla_set_cpu_estimates`, `media/libopus/include/opus_cpu_estimates.h`)
just before it creates an encoder, in `OpusTrackEncoder` (MediaRecorder),
`FFmpegAudioEncoder` (WebCodecs) and WebRTC's `opus_interface.cc`. The emulation gives the other
vendor's bits for every input, special values included; `check.py` proves it
against the native instruction on the host's vendor and against the recorded
hashes for the other. When it names the host's
vendor, or is 0, Skia runs unchanged.

The launcher sets the pref from `cpu:arch` and `cpu:manufacturer`, which the
`cpu` option sets and the identity otherwise draws: ARM for an Apple GPU,
Intel for an Intel iGPU or any x86 Mac, AMD for a
Radeon APU's graphics, Intel for a hardwareConcurrency of 10, 14, 18, 22 or 28
(no AMD CPU reports those; Intel's hybrids do, e.g. the Core Ultra 5 125H's
18), and otherwise 81.4% Intel, the Intel share among x86
CPUs in Firefox's hardware report (data.firefox.com, week of 2026-11-02:
Intel 76.86%, AMD 17.61%, Apple 5.04%). The report has no per-OS split;
Steam's survey puts AMD far higher, so the share is a choice, kept in
`launcher-constants.json` as `x86IntelShare`.

On an Apple M4, stock Firefox 159 gives other values than x86-64 for every
Web Audio node, every canvas composite operation (source-over included, not
only the estimate-based ones), drawImage, filters and paths, the Opus and VP9
streams, the default NaN's sign bit (ARM's is positive), and 9 of 11
WebAssembly relaxed SIMD operations, under macOS and under Linux alike; Math,
DOMMatrix and layout agree with x86 on the same OS. With
`general.cpu_identity` 3 an x86-64 build computes what Firefox's aarch64 build
computes:

- Skia runs its NEON raster pipeline and blend kernels, executed lane for lane
  in C++ (`SkOpts_neonemu.cpp`, `SkNeonEmu.h`, `SkArmEstimates.h`).
- Web Audio mixes with the NEON engine (`AudioNodeEngineNeonEmu.cpp`), and its
  FFT runs ffvpx's aarch64 transform codelets (`tx_float_neonemu.c`).
- libopus runs its aarch64 CELT kernels and NEON inverse MDCT
  (`celt_neonemu.c`, `celt_tx_neonemu.c`), for encoding and decoding.
- The JIT and the interpreter make positive NaNs, and wasm relaxed SIMD gives
  ARMv8's lanes (`JS::SetEmulateArm64`).
- libvpx is built realtime-only for Linux and Windows arm64 (not macOS), which
  gives VP9 another bitstream and rejects VP8 with lookahead.
  `media.libvpx.realtime_only` makes that a runtime switch; the launcher sets
  it for an ARM Windows or Linux identity. libvpx's NEON code is otherwise
  bit-exact with x86.

The two translated ARM sources are generated from Firefox's aarch64 assembly by
`browser/scripts/a64toc.py`. The guard `cpu-vendor-estimates` runs the CPU probe
(`browser/tests/cpu-probe/`) with an ARM identity and compares every key on
which stock x86-64 and ARM64 Linux differ.

With `general.cpu_identity` 1 or 2, an aarch64 build computes what the
x86-64 build computes on an AVX2 and FMA core of that vendor:

- The x86 code paths are compiled for aarch64 against
  `third_party/simde/x86emu`, which stands in for `<immintrin.h>`: SIMDe's
  SSE, AVX2 and FMA intrinsics, with x86's negative default NaN, its NaN
  operand order and its out-of-range conversions (`x86emu.h`). Skia runs its
  SSE2, SSSE3 and AVX2 raster pipeline and blend kernels
  (`SkOpts_X86EmuTarget.h`, the `*_x86emu.cpp` files), with the vendor's
  estimate tables as on x86-64.
- Web Audio mixes as its SSE4.2 engine does, on NEON registers with the
  product rounded before each add (`AudioNodeEngineX86Emu.cpp`); the speex
  resampler runs its SSE path, and libopus its SSE CELT float kernels
  (`celt_x86emu.c`).
- ffvpx's FFT runs its x86-64 AVX2 and FMA3 assembly, translated to C
  (`tx_float_x86emu.c`) by `browser/scripts/x86toc.py`.
- The JIT and the interpreter make x86's negative default NaN (Math
  functions and constant folding included), and wasm relaxed SIMD gives the
  lanes SpiderMonkey's x64 backend gives (`JS::SetEmulateX86`).

What this does not cover:

- WebGL. Shaders run on the host's GPU or llvmpipe; an ARM identity on Linux
  claims llvmpipe, since no Linux ARM GPU is recorded yet.
- hardwareConcurrency and other CPU-shaped values do not yet follow the vendor.

---

### MEDIA DEVICES (`docs/MEDIA-DEVICES.md`)

# Media devices

How Camoufox presents `navigator.mediaDevices` (`media-device-spoofing.patch`,
the driver's `media-devices.json` and `draw_media_devices()` in
[camoucore](https://github.com/CamouBrowser/camoucore)).

## What a page can see

Stock Firefox exposes, **before** any `getUserMedia` grant, at most one device
per input kind with empty `label`/`deviceId`/`groupId` and no `audiooutput`.
**After** a grant (or while capturing) it lists every device with the OS's own
names, per-origin hashed ids, and shared `groupId`s for devices of the same
hardware. The captured track's `label` and `getSettings().deviceId/groupId`
are those of one listed device.

Camoufox reproduces exactly that for a spoofed machine:

- The fake media engine (`MediaEngineFake::EnumerateDevices`) emits the
  identity's microphones, cameras and speakers, with labels, raw ids and
  groups from the config, and `MediaManager` uses it for mics/cams and for the
  outputs whenever `mediaDevices:enabled` is set. `MediaDevices.cpp` is stock,
  so the pre-/post-grant rules, feature policy, permission prompts, the
  capture indicator and the camera/microphone `groupId` correlation all run
  unchanged.
- `getUserMedia()` therefore succeeds iff the identity has the requested
  device kind (a claimed camera captures the fake engine's test pattern; a
  camera-less identity gets `NotFoundError`, like a real machine without one).
- The patch treats the identity's devices (`LocalMediaDevice::IsIdentityDevice()`)
  as real hardware, so they get the permission prompt, count as capturing
  and expose their labels after a grant. `media.navigator.permission.fake`
  stays off, as in stock Firefox, because a page can detect it.

## Config keys

| key | meaning |
| --- | --- |
| `mediaDevices:enabled` | use the identity's devices instead of the host's |
| `mediaDevices:micros` / `webcams` / `speakers` | counts |
| `mediaDevices:microphoneLabels` / `webcamLabels` / `speakerLabels` | labels, aligned with the counts |
| `mediaDevices:microphoneGroups` / `webcamGroups` / `speakerGroups` | raw group ids (same string = same `groupId`) |

The Python package draws all of them from `media-devices.json`, seeded by the
identity, unless the caller set any `mediaDevices:` key. Label styles follow
the OS: Windows WASAPI friendly names (`Microphone Array (Realtek(R) Audio)`),
macOS CoreAudio names (`MacBook Pro Microphone`, `FaceTime HD Camera`), Linux
PulseAudio/PipeWire descriptions plus v4l2 card names with the USB id, and a
`Monitor of …` source per output as PulseAudio exposes.

## Guard

`browser/tests/playwright/patches/media-devices-coherence.py` checks the
pre-grant shape, that capture succeeds exactly for listed kinds, that captured
tracks match listed devices, that labels are never the fake engine's, and that a
camera-only identity does not crash the content process (it did, before
build12).

---

### Humanize (`docs/humanize.md`)

# Humanized input lives in the driver

The browser does not humanize input. Each Juggler input command Playwright sends
becomes one event of the shape a real device gives stock Firefox
([input-dispatch.md](input-dispatch.md) has each shape per OS), and the browser adds
no paths, pacing, splitting or randomness of its own. Whatever makes input look
human (the path a cursor takes, the times between keys, how a wheel turn is
broken into strokes) is planned in the process that drives the browser and sent as
ordinary Playwright calls.

This keeps the two jobs apart. The browser's job is that one call looks like one
real event; the driver's job is that the sequence of events looks like a person.
A driver that humanizes on its own (a cursor or typing library) gets exactly the
events it sends, never a second layer of delays on top of its own.

## The engines

`humanize` is a launch option in both launchers. Each channel (`mouse`,
`keyboard`, `scroll`) runs one engine in the driver process:

```python
from camoufox.humanize import myuri, raw

humanize = {"mouse": myuri(), "scroll": raw(), "seed": 1234, "settings": {"typing": {"wpm": 70}}}
```

- `myuri()` is [myuri](https://github.com/JWriter20/Myuri)'s smart actions, fitted
  to recordings of people on each OS ([`ci/tribal-rules.yml`](../ci/tribal-rules.yml), the
  `human-*` rules). It plans for the launch identity's OS, since input behaviour
  belongs to the browser, not the context. Both packages depend on it (PyPI
  `myuri`, npm `@jwriter20/myuri`), pinned to one release so a seed plans the
  same input in Python and TypeScript.
- `myuri(part=fn)` replaces one of myuri's parts (`move`, `press`, `point`,
  `reaches`, `into_view`, `wheel`, `type`, `key`) with your function and keeps
  the rest; the README's "Replacing a part" has the call signatures. myuri is
  the one implementation of the smart actions: Camoufox adapts Playwright to
  it and adds none of its own.
- `cursory()` is another name for `myuri()`: myuri runs cursory's paths.
- `raw()` is Playwright as it is.
- `humanize=True` is `myuri()` on every channel, and a channel a dict leaves out
  is `myuri()`. `humanize=None` or `False` (the default) is `raw()` everywhere.
- `settings` are [myuri's](https://github.com/JWriter20/Myuri#settings), checked by myuri before launch. The seed
  draws one person around them for the whole browser (myuri's
  `profile_from_seed(seed, settings, os)`), so one seed types, moves and
  scrolls at one speed. A Camoufox identity points with a mouse unless
  `settings["scroll"]["device"]` says otherwise.
- Nothing about humanize reaches the browser's config. The `humanize*` keys are
  marked `removed` in `browser/settings/properties.json`.

The engine owns timing and motion: the path, the dwell before a press, the hold,
the gaps between keys, Shift's lead and trail, and how a scroll is split into
wheel notches. The browser owns the shape of each event (deltaMode, wheelDelta,
coalescing, fractional coordinates), which a driver cannot set
([`humanize-timing-is-the-engine-and-shape-is-the-browser`](../ci/tribal-rules.yml)).

The engines wrap Playwright's input methods on the client
(`_humanize_playwright.py` in the Python driver and its TypeScript counterpart, in
[camoucore](https://github.com/CamouBrowser/camoucore)).
Each page gets one `myuri.Actions`, whose host sends every event through
Playwright's own input methods. A `raw()` channel's parts are Playwright's: its
move is one event and its scroll into view is Playwright's. User code never runs
in the browser. The browser guard is `browser/tests/playwright/patches/humanize.py`.

A humanized click is myuri's, not Playwright's. myuri wheels the element into
view, waiting for each scroll to land, chooses a point in the element's visible
part, moves there and waits its dwell, then presses where the cursor is, held for
its drawn hold. Playwright's click would move again first, and the browser counts
that move against the next press's click count
([Click count](input-dispatch.md#click-count)). Before pressing, myuri checks in
the page's isolated world that the point reaches the element: nothing covers it,
and the element is enabled. A press that would miss is aimed again elsewhere, on
Playwright's retry schedule until the call's timeout. It then raises Playwright's
`TimeoutError`, naming what covers the point. `trial=True` and `force=True` work
as they do in Playwright: a trial click goes to Playwright alone, and a forced
click skips the check.

## Seeds

`seed` (an integer in [0, 2^32)) seeds one stream for the browser, which every
page and part draws from, so two pages never replay the same draws. It is
myuri's `make_rng`, which draws the same numbers in Python and TypeScript;
`browser/tests/humanize/sequence.json` pins the input one seeded scenario plays,
and both launchers are tested against it. Without a seed, each launch draws a
random one.

## What the browser still times

Some single commands still carry timing inside the browser, because without it
one Playwright call would produce events no keyboard can:

- **Paste.** `fill()` and `keyboard.insert_text()` send `Page.insertText`, which
  Juggler turns into Ctrl+V (Cmd+V on a Mac identity) around Firefox's own paste.
  The modifier leads V by about 60 ms, V is held about 116 ms, and the modifier
  trails by about 40 ms. Without them the shortcut would go down and up in the
  same millisecond.
- **Shift for a shifted character.** A `keyboard.press("A")` or a typed `!` holds
  Shift around the key, with the same lead and trail.
- **A refused paste.** A page that cancels the paste gets the text typed key by
  key at a person's rate, as a person types what they cannot paste.

They are for raw Playwright. An engine that holds Shift itself, as myuri does,
gets no second Shift: Juggler skips its own when a real Shift is down. These are
one command's own events, drawn in the content process from
`input/HumanDelay.js` with the figures input-dispatch.md cites; they never pace
one command against the next. Mouse moves are also sent at least 8 ms apart (a
125 Hz mouse's reports), which a driver pacing its moves at 8 ms or more never
sees.

---

### Input Dispatch (`docs/input-dispatch.md`)

# Synthesized input dispatch

Every synthesized mouse and wheel event in the parent process goes through
`browser/additions/juggler/input/MouseDispatch.js`.
`browser/scripts/check-input-dispatch.py` fails the build if anything else
dispatches input or does browser-relative coordinate arithmetic, and it runs on
every pull request.

## The invariant

> A synthesized input event whose ack we await must reach the content
> renderer — and when it does not, we must stop waiting.

## Why it is worth a module and a lint

Four deadlocks shipped between 2026-04 and 2026-09, all the same failure:

| Date | Commit | Trigger |
|---|---|---|
| 2026-06-04 | `9270618` | `x == width` / `y == height` — the far edges |
| 2026-07-18 | `541ffca` | trajectory points, which bypassed the endpoint's guard (#225, #677) |
| 2026-07-24 | `16e5a13` | a zero-displacement move |
| 2026-09-03 | `014cc65` | `y == 0` — the near edge (#751, #752) |

Each was fixed by adding one more coordinate guard at one more call site. That
does not converge, for two reasons.

**The trigger set is not enumerable.** Whether relative `y == 0` reaches the
renderer is decided by `Math.round(boundingBox.top) < boundingBox.top` — a
rounding accident in the fractional height of browser chrome, which varies with
the *spoofed OS*: windows `51.4` → `51` deadlocks, macos `53.1` → `53`
deadlocks, linux `56.5` → `57` is fine. No review catches that, and no
hand-written list of coordinates contains it.

**Every miss costs the whole process.** `activateAndRun()`
(`TargetRegistry.js`) serializes input on a promise chain shared by every tab in
the process. It swallows errors to keep the chain running, but it cannot swallow
a callback that never returns. One unbounded `await` for an ack that will never
arrive wedges every later input event, in every tab, permanently — at 0% CPU,
with nothing in flight and no diagnostic.

`#677` is why review is not enough: restoring the (since removed) in-browser trajectory meant
writing a bounds check, and the one written was a copy of the pre-`#225` form,
reintroducing a fixed deadlock one day before it was re-fixed.

## How it is enforced

**One chokepoint.** `MouseDispatch` owns the relative→absolute conversion (with
the boundary snap), the in-viewport predicate, and the ack wait. Callers pass
relative coordinates and never see a bounding box.

**A fresh rect.** The browser rect is measured *after* the last `await` before
the dispatch (`apz-repaints-flushed`), never before it. The chrome can change
height during that wait — measured 2026-09-14: the nav-bar grew from 40 to
41 px about a second after startup when the (then forced) built-in theme was
applied — and a rect taken before it put a relative `y == 0` one row above the
content: the event reached the renderer as an exit event at client `y == -1`,
produced no ack, and the page saw no mousemove (~1 in 25 runs of
`near-edge-mouse-deadlock.py`). Both dispatch sites (`Page.dispatchMouseEvent`,
`Page.dispatchWheelEvent`) measure synchronously before dispatching.
`MouseDispatch.sendAcked()` measures again before every event it sends, so each
event goes out against where the browser is then.
Measured 2026-10-31: in a window too small for the chrome plus the viewport
(a 1366x768 screen draw), Juggler's `.browserStack` scrolled the browser on a
wheel turn, and a move that kept its starting rect landed 13-84 px off. The stack
is `overflow: hidden` since, so only Juggler's own `scrollRectIntoViewIfNeeded`
scrolls it.

**Bounded waits.** `sendAcked()` waits at most `kAckDeadlineMs` (5s) and then
drops the event with a warning naming the type, coordinate and browser rect. The
deadline is sized above the slowest *legitimate* ack, not near the typical one:
acks are p99 1ms on an idle page, but they are delivered from the content main
thread and inherit any block on it — a 3s synchronous script delayed one by
2849ms. One command holds at most one such wait per event it sends, and the
browser sends no events a command did not ask for. A zero-displacement move
produces no `eMouseMove`, so it is never acked; `Page.dispatchMouseEvent` does
not send one (`noop-mousemove-deadlock.py`, [Device pixels](#device-pixels)).
`apz-repaints-flushed` waits at most `kAckDeadlineMs` too: a flush sent to a
GPU process that dies never comes back, and stalled every such dispatch until
the backstop. So does the drag path's `juggler-drag-finalized`, per input
event: an answer a busy page gives later still decides the next event, so the
drag drops, and mouseup ends the wait. `activateAndRun()` bounds the whole
slot, tab switch included, at 30s, a backstop for the waits still unbounded in
it (`TabSwitchDone`, the drag path's `dragover` and cross-process sends). A
slot that expires before its tab switch completes fails its command with "Tab
switch did not complete within 30000ms"; the chain advances either way.

**The static check.** `browser/scripts/check-input-dispatch.py`, wired into the
`static` job of `.github/workflows/tests.yml`. Two exemptions, both
content-process: `PageAgent.js` (drag events, already content-relative, no ack)
and `FrameTree.js` (the ack *producer*).

**Boundary coverage.**
`browser/tests/playwright/patches/mouse-boundary-sweep.py` sweeps the whole
viewport ring across every spoofed OS, asserting each
point is acked *and observed by the page*. Hand-picked coordinate lists are what
let each of the four bugs through: the far-edge test probed only the far edges,
and the in-browser trajectory test (both removed with the trajectory) pinned
`os="linux"` — the one fingerprint immune to `#751`.
`browser/tests/playwright/patches/input-ack-backstop.py` covers the bounded waits
themselves: a late renderer ack, and a drag whose page answers late.

## Focus

A driven page stays focused and active, deliberately not stock. Upstream
Playwright's Juggler set `docShell.overrideHasFocus` and `forceActiveState` on
every top-level document so parallel pages behave as if each is in front;
Camoufox keeps that for the product (`content/main.js`). Stock gives a page
behind another window `hasFocus()` false, a window `blur`, and a hidden,
throttled state behind a foreground tab. The difference is page-visible
(`ci/tribal-rules.yml`, `driven-pages-stay-focused`).
Keyboard input therefore does not raise the page first; `Page.bringToFront`
still does that when a caller asks.

## The input gate

Firefox's content process drops user input that reaches a document before its
input gate opens: `dom.input_events.security.minTimeElapsedInMS` (100 ms) after
`readyState` became `"loading"`, then `minNumTicks` refresh ticks
(`PresShell::CanHandleUserInputEvents`). Juggler's mouse and key events are
synthesized for tests, which the gate exempts, so they reached a page earlier
than any person's could; its wheel is not exempt, so a wheel straight after
`goto` lost notches. Every input command now waits for the gate once per
document (`PageHandler._awaitUserInputGate`). Guard: `juggler-input-gate.py`.

## Move coalescing

A real mouse reports moves faster than the refresh driver ticks. The content
process queues them (`CoalescedMouseData`) and, at the next tick, dispatches
one `pointermove`/`mousemove` that carries the queued moves in
`getCoalescedEvents()`. A `pointerrawupdate` is dispatched for each move as it
arrives. Juggler's moves used to skip that queue, so each one reached the page
by itself: one `pointermove` per move, a coalesced list of length 1, and as
many `pointermove`s as `pointerrawupdate`s.

`input-coalescing-parity.patch` queues juggler moves the way real ones are
queued, and `BrowserChild::RecvRealMouseMoveEvent` acks each one with
`mousequeued <id>` when the renderer has it. A move returns at that ack
(`MouseDispatch.sendQueuedMove`). Sends are spaced at least 8 ms apart, the
reports of a 125 Hz mouse, the common rate. The clock starts when the move is
sent, not when its ack returns: the next move cannot start until this one
returns, so counting the ack into the gap stretched a 125 Hz path out to about
one move per frame. A path given as steps
(`page.mouse.move(x, y, steps=n)`, which Playwright sends as n moves) then
reaches the page as a real mouse's motion does. Measured with a 125 Hz XTest
sweep on Xvfb against stock 158.0.1: one
`pointermove` per frame carrying 2 to 4 moves, and a `pointerrawupdate` for
every move.

The queue is flushed once per frame on every OS, so how many moves a
`pointermove` carries is the pointer's report rate over the display's refresh
rate. A 100 Hz mouse on a 100 Hz display, or an 8 ms trackpad on a 120 Hz one,
gives one `pointermove` per report with a coalesced list of length 1; a
high-rate mouse on a 60 Hz display gives a median of 8. The frame rate is the
host's, so the page sees the host display's ratio whatever the identity's OS.

The coalesced move reaches the page at the refresh tick and is acked as
`mousemove <id>`, with the id of the newest move it carries. Any command of the
page other than another move waits for that ack first (`PageHandler
.beforeDispatch`, called by the protocol session). So whatever a caller does
after `page.mouse.move()` returns sees the move, whether that is an evaluate, a
click or a key. A move with a button held also waits for it before returning,
because the page decides at that tick whether the move starts a drag.

Both waits are bounded by `kAckDeadlineMs`. A page that blocks its main thread
past the deadline only ends the wait; the move stays queued and still reaches
the page. `browser/tests/playwright/patches/driven-move-coalescing.py` checks
the page's counts.

## Device pixels

Playwright floors every Firefox mouse coordinate to a whole CSS pixel before
sending it, so a driver cannot ask for a sub-pixel point. A Windows mouse at a
display scale above 1 moves in device pixels. PointerEvents report the point as
a fractional `clientX` (78% of moves at 2.5, in a recording on stock 159.0).
A step that stays inside one CSS pixel reaches the page as a `mousemove` with
no movement (10.7%). At scale 1 neither happens, and Windows never repeats a
position. A macOS mouse reports whole CSS pixels at scale 2, and repeats them:
19% of its `pointermove`s and `mousemove`s are at the position before, with no
movement.

So under a Windows identity, `PageHandler._placeMove` puts each move on one of
the device pixels inside the CSS pixel asked for
(`MouseDispatch.devicePointsIn`). A move to the pixel the pointer is already
in goes to another device pixel there, or is dropped when the pixel holds only
one. A press or release in that pixel lands where the pointer is. The content
area starts on the device pixel nearest its CSS origin, so the points are
counted from there. A macOS identity sends every move, a repeat of the
position included; a Linux identity drops a move to the pixel the pointer is on.
Both keep the whole pixels Playwright sends.
`browser/tests/playwright/patches/driven-move-device-pixels.py` checks the
Windows and macOS shapes.

## Timestamps

Windows stamps an input message with its tick count (`GetMessageTime`): whole
milliseconds that advance 15.625 ms at a time. In recordings on stock 159.0,
every gap between `pointermove`s, `keydown`s and mouse `wheel` events is a run
of those ticks (15, 16, 31, 32, 47 ms and so on), from a mouse and a touchpad
alike, and coalesced moves that arrive within one tick share its stamp. macOS
stamps input at high resolution. On Windows only a precision touchpad's scroll
is off the grid, because Firefox makes those `wheel` events itself, once per
frame.

`input-timestamp-tick.patch` stamps the events juggler synthesizes with
`MaskConfig::InputTimeStamp()`: mouse (`nsContentUtils::SynthesizeMouseEvent`),
wheel (`nsDOMWindowUtils::SendWheelEvent`) and keys
(`TextInputProcessor::PrepareKeyboardEventToDispatch`). Under a Windows launch
that is the latest tick, read off `steady_clock`, which every process shares,
so mouse events from the parent process and keys from the content process fall
on one grid. Under any other launch it is the current time, as before. Events a
page creates itself (`new Event()`) keep their high-resolution stamp, as they
do on Windows. `browser/tests/playwright/patches/driven-input-timestamp-grid.py`
checks both.

## Click count

The OS decides a press's click count (`detail`), so juggler counts driven
presses as the claimed OS would and ignores the `clickCount` the client sends.
The mouseup and the click take their press's count.

- **Windows.** Firefox (`nsWindow.cpp`) counts up a press on the same button
  within 500 ms of the last press, unless the pointer has moved 4 device pixels
  from the last release; such a move resets the count. Windows sends its own
  double click for a press within 500 ms and 1 device pixel of the last single
  press, which sets the count to 2. Quick presses in place count
  1, 2, 3, 2, 3, ...
- **macOS.** `NSEvent.clickCount`: within 500 ms and 3 points of the last
  press, without bound.
- **GTK.** 1, 2, 3 and then 1 again, within GTK's default 400 ms and 5 pixels.

`browser/tests/playwright/patches/driven-click-count.py` checks each.

## Key repeat

The OS repeats a held key, and only the last key pressed. Juggler repeats a
held driven key with the claimed OS's delay and interval, as keydowns with
`repeat` set; pressing another key moves the repeat to it, and releasing the
key stops it. A repeat the client sends for the held key is dispatched as sent
and does not restart the browser's. A repeat that comes due while the page is
still handling the last is skipped, as Firefox skips an OS repeat that arrives
while the page is busy (`BrowserChild::SkipRepeatedKeyEvent`): a busy page gets
the next repeat on the OS's schedule, never a burst of the ones it missed.

| OS | Delay | Interval | Modifiers |
|---|---|---|---|
| Windows | 500 ms | 31.25 ms | repeat |
| macOS | 500 ms | 83.3 ms | do not repeat |
| Linux | 500 ms | 30 ms | do not repeat |

The Linux values are GNOME's defaults, and its XKB keymap marks the modifiers
as not repeating. `browser/tests/playwright/patches/driven-key-repeat.py`
checks each.

## Drags

On GTK a drag's motion fires `drag` at the source and then `dragover` at the
target (`nsDragSession::DispatchMotionEvents`). The `drag` has `buttons` 0.
The `dragover` GTK sends before a drop is not a motion, so it has no `drag`.
Juggler sends `drag` ahead of each motion's `dragover`.
`drag-source-events.patch` adds the `"drag"` type to `jugglerSendMouseEvent`,
which fires it at the drag session's source. The `pointercancel` that ends the
pointer stream at `dragstart` carries one coalesced event, the move that
started the drag, now that the move reaches the page coalesced.
`browser/tests/playwright/patches/driven-drag-gtk.py` compares the stream
with stock's.

## Wheel notches

A mouse wheel turns in notches. On Linux (GTK, X11) stock 158.0.1 gives a notch
`deltaMode` 1, `deltaY` 6, `wheelDeltaY` -120, a `DOMMouseScroll` with
`detail` 3 and a `MozMousePixelScroll` of three lines, and scrolls 120 px
(measured with XTest button 5). On Windows, stock 159.0 has the same shape
(measured with `SendInput` at a device pixel ratio of 2.5, 45 runs identical):
`deltaMode` 1, `deltaY` 6, `wheelDeltaY` -120, `detail` 3, no acceleration. Its
pixels differ only because line height does, so three native lines need no
per-OS constant. macOS differs: with a person turning a notched USB mouse on
stock 159.0, a slow notch is `deltaMode` 1, `deltaY` 1, `wheelDeltaY` -48,
`detail` 1 and a `MozMousePixelScroll` of 16, and the OS accelerates a faster
turn into single events of more lines.

**One call is one event.** `Page.dispatchWheelEvent` (`mouse.wheel(dx, dy)`)
sends exactly one wheel event and returns; the browser does not split a call
into notches, space them or move the cursor for it. The driver decides how a
turn is broken up, by sending one call per event it wants, at its own times.

- **Linux and Windows identities.** Each axis maps to notches: 100 px is one
  notch, rounded to the nearest, at least one on an axis that moves. The event
  carries three lines per notch and is flagged as native ticks
  (`wheel-native-ticks.patch`), so Gecko applies the same system scroll speed and
  gives `wheelDeltaY` -120 per notch. `mouse.wheel(0, 300)` is one event of
  three notches: `deltaY` 18, `wheelDeltaY` -360, `detail` 9, 360 px. That is a
  shape stock produces: `WinMouseScrollHandler` turns a `WM_MOUSEWHEEL` of
  N x 120 into one event of N ticks (a fast spin the OS batched, or a wheel
  driver that sends multiples), and GTK turns a smooth-scroll delta of N into
  one event of N notches. Most notched mice on stock drivers send one notch an
  event, so a driver imitating one sends one call per 100 px.
- **macOS identities.** The call is one event of `round(px / 16)` lines, at
  least one, without the native-tick flag; the launcher turns
  `mousewheel.system_scroll_override.enabled` off, as stock has it on macOS. In
  the one macOS recording of a person's notched mouse
  (`human-input-recordings/mac-mini`, a Keychron M6, 1666 wheel events), every
  event is a single line-mode event of 1 to 13 lines, `wheelDeltaY` -48 a line;
  a turn starts at one line an event and climbs.

The page scrolls a whole number of notches or lines, not the exact pixels asked
for, and `mouse.wheel(0, 0)` sends nothing. There is no recording of a notched
mouse on Linux or Windows here; the Windows recordings (`win-i9-intel`,
`win-i9-intel-dpr1`) and the MacBook one are touchpads, which scroll in pixels
(`deltaMode` 0), a shape `mouse.wheel` does not produce.
`browser/tests/playwright/patches/driven-wheel-notches.py` checks each shape.

## Pasted text

Playwright's `fill()` and `keyboard.insert_text()` send `Page.insertText`. A
person enters a whole string by pasting it, so Juggler pastes: the paste
shortcut goes down (Ctrl+V, or Cmd+V when the page's `navigator.platform` is
a Mac), Firefox's own paste runs with the text (`nsIEditor.pasteTransferable`:
a trusted `paste` event whose `clipboardData` holds the text as `text/plain`,
then `beforeinput` and `input` with `insertFromPaste`), and the shortcut comes
up. The shortcut's `keypress`, where Firefox would paste from the system
clipboard, is cancelled in the system group; content never receives a
`keypress` for a shortcut, so that is not observable. The text never goes
through the system clipboard. The modifier leads V by about 60 ms and trails
it by about 40 ms, as Shift does a key, and V is held 116.25 ms (SD 23.88;
Dhakal et al., "Observations on Typing from 136 Million Keystrokes", CHI 2018).
Each of these delays is a normal draw from `input/HumanDelay.js`
(`normalDelay(mean, sd, min, max)`) with the figures its caller cites. They are the paste's own events, one command's
worth; the browser never paces one command against another (docs/humanize.md).

A page that cancels the paste, or the shortcut's `keydown`, and leaves the field
as it was gets the text typed instead, as a person types what they cannot paste:
key by key on a US keyboard, 238.66 ms press to press (SD 111.60, the same study).
A character with no US key arrives as an input method commits it. Typing stops
with an error if the focus leaves the field, and a read-only field takes nothing,
without error. A page that writes the pasted text in later than the shortcut's
release (about 160 ms) has it typed as well. A page that
handled the paste itself keeps what it wrote, and `fill()` fails only if the keys
change nothing either. Nothing focused that takes text gets the shortcut and no
paste. Playwright documents `insert_text()` as sending no key events; here it
sends the shortcut's.

A person clicks a field before pasting into it, while Playwright's `fill()`
focuses it from script: the page would get `focus` with no pointer or mouse
event before it. The Python launcher clicks a text field that does not have
focus before the fill (`camoufox/driver_defaults.py`), and so does the TypeScript
launcher (`driver_defaults.ts`). The click is Playwright's own, so the mouse moves
there and presses through the OS-path dispatch. A field that has focus is pasted
into as it is. Fields `fill()` sets without pasting (date, color, range and the
like) are not clicked, and neither is a field another element covers, which a
person could not click either: `fill()` works on it as Playwright's does.
`fill()` still selects the field's text with `select()` first.
`browser/tests/playwright/patches/driven-fill-paste.py` checks the events.

## Screenshots

Unless told `caret: "initial"`, Playwright hides the text caret for a
screenshot: from its utility world it sets `caret-color: transparent
!important` in the style attribute of every input, textarea and
contenteditable element, and puts the old value back after the capture. The
page can see all of it. A MutationObserver gets a `style` mutation for each
element, twice per screenshot. `getComputedStyle` reads the transparent caret
while the capture runs. Every element that had no inline style is left with an
empty `style=""` attribute.

Juggler captures with `drawSnapshot`, which never paints the caret, so hiding
it changes no pixel. The launchers therefore default screenshots of pages they
launched to `caret: "initial"`. Page, element and locator screenshots all get
it. Python wraps the client's `Page.screenshot` and `ElementHandle.screenshot`
(`camoufox/driver_defaults.py`). TypeScript fills the option in where the client
sends the request (`attachDriverDefaults` in `driver_defaults.ts`). Each checks that
the page belongs to a Camoufox launch, so other browsers in the same process
keep Playwright's behaviour. A caller who passes `caret` gets what they ask
for, and `caret: "hide"` writes the page's style attributes as before. A
client that connects through `launch_server` is not a launcher, so it should
pass `caret: "initial"` itself. The `@playwright/test` `toHaveScreenshot`
assertion passes `caret: "hide"` explicitly, so it also hides the caret.

The guard `screenshot-leaves-page` takes page, element and locator screenshots
with a focused caret. It checks that the page observes no change and is left
with no new attribute, and that each capture is byte-identical to one taken
with `caret: "hide"`.

## The page's globals

A window defines a WebIDL interface's name on itself the first time anything
needs the interface, so `Object.getOwnPropertyNames(window)` lists the
interfaces in the order they were first used, followed by the unused ones.
A driver's work used to show up in that list. Wrapping the page's nodes for
an isolated world, a locator's reads and an `evaluate` all create interfaces
in the page's window, and creating one defined its name there:
HTMLDivElement, CSSStyleDeclaration, DOMRect, MutationObserver, AbortSignal
and some 30 others moved up the list of a page that had never used them.

`isolated-world-global-order.patch` creates an interface Juggler needs
without defining its name, and marks it and its prototype in the window's
`ProtoAndIfaceCache`. The window keeps listing it as unused. The page defines
it, with its legacy aliases and factory functions in creation order, when it
first uses it, as stock does:

- by name (`WebIDLGlobalNameHash::DefineIfEnabled`);
- by creating an object of it or of an interface that inherits from it
  (`GetPerInterfaceObjectHandle`);
- by getting an object Juggler had already wrapped, such as an input a
  browser actor reads on focus (`MaybeDefineForCachedReflector`). The check
  costs one array read per cached reflector handed out
  (`DoGetOrCreateDOMReflector`): a count, per interface prototype, of the
  windows holding it created for Juggler and not yet defined, so a
  reflector of any other interface costs what it does in stock. An object the page creates is
  checked against its own interface's mark the same way.

An Xray of a window first resolves a name on the window itself (the
generated `ResolveOwnPropertyViaResolve`), which defines it there. For
Juggler that resolve now only creates the interface, and the Xray resolve
that follows hands it over: Playwright's utility script reads `AbortSignal`
this way.

Juggler is the caller when the innermost script is one of its
`resource://gre/modules/juggler/` modules, described from the module's own
realm because the page's principal does not see system frames, or runs in a
sandbox one of them created. A callback hides the caller; its incumbent global
decides then, so a listener in one of Juggler's isolated worlds (Playwright's
hit target check) is Juggler's, and a page's or a browser actor's is not. The
entry global is no guide: Juggler's actor messages enter the page's window.

`browser/tests/playwright/patches/driven-evaluate-globals.py` lists a page's
globals after driver work and after only the input that work causes (a click
on a field and a key, which Firefox's own actors wrap in the page's window as
they do for a person's input), and compares the two.

---

### Patch Upgrading Guide (`docs/patch-upgrading-guide.md`)

# Firefox Patch Upgrading Guide

How to update Camoufox's patches when `browser/upstream.sh` moves to a new Firefox
version. Patches break because Firefox renames APIs, moves code and shifts line
numbers; this guide covers finding and fixing those rejects.

## Table of Contents

1. [Understanding the Patch System](#understanding-the-patch-system)
2. [The Source Tree and Its Make Targets](#the-source-tree-and-its-make-targets)
3. [General Workflow](#general-workflow)
4. [Fixing Common Reject Types](#fixing-common-reject-types)
5. [Per-Context Machinery](#per-context-machinery)
6. [Porting Playwright](#porting-playwright)
7. [Testing and Validation](#testing-and-validation)
8. [Pitfalls](#pitfalls)

---

## Understanding the Patch System

### Patch Categories

All patches live under `browser/patches/`, and `browser/scripts/patch.py` applies every
`*.patch` in it (subdirectories included), sorted by file name:

- **Playwright**: `playwright/0-playwright.patch` (Juggler integration) and
  `playwright/1-leak-fixes.patch`. Their names sort first, and every other
  patch is written against a tree that already has them.
- **Feature patches**: `webrtc-ip-spoofing.patch`,
  `anti-font-fingerprinting.patch`, etc. Per-user-context (per-Playwright-context)
  support is built into each one.
- **`librewolf/`, `ghostery/`**: patches taken from those projects.

Compile-time dependencies between patches (MaskConfig, RoverfoxStorageManager)
are listed in [`browser/patches/patch-dependencies.md`](../browser/patches/patch-dependencies.md).

### Key Infrastructure Files

- **RoverfoxStorageManager.cpp/h**: Thread-safe key-value storage for per-context data
- **Manager Classes**: FontListManager, WebRTCIPManager, etc.
- **Window.webidl**: Exposes the per-context setters to Playwright

---

## The Source Tree and Its Make Targets

The Firefox tree is `browser/camoufox-<version>-<release>/` (from
`browser/upstream.sh`). It is a git repository whose `unpatched` tag is plain
Firefox plus `browser/additions/` and `browser/settings/`. Run every target, and
every command in this guide that does not say otherwise, from `browser/`:

| Target | What it does |
|---|---|
| `make dir` | Fetches and extracts Firefox if the tree is missing. Otherwise resets it to `unpatched`, runs `mach clobber` and `git clean -fdx` (the object directory goes too), re-copies additions, then applies every patch and lists the ones that left rejects. |
| `make revert` | `git reset --hard unpatched`. Untracked files stay, including new files that patches created. |
| `make clean` | `mach clobber`, `git clean -fdx`, then `make revert`: unpatched Firefox with nothing left over, without re-fetching. |
| `make patch ./patches/x.patch` | Applies one patch (`patch -p1`). |
| `make unpatch ./patches/x.patch` | Reverses one patch. |
| `make first-checkpoint` | Commits the current tree and tags it `first-checkpoint`. |
| `make workspace ./patches/x.patch` | Unapplies `x` if it is applied, runs `first-checkpoint`, then applies `x` again, so the working tree differs from the checkpoint by exactly that patch. |
| `make diff` | `git diff first-checkpoint`. Redirect it into the patch file. |
| `make checkpoint` | Commits tracked changes, keeping the `first-checkpoint` tag where it is. |
| `make grep <text>` | Searches the top-level patches for a string. |
| `make build` | `./mach build` (runs `make dir` first if the tree was never prepared). |
| `make set-target` | Rewrites the mozconfig for `BUILD_TARGET`. The sources and every object directory are left as they are. |
| `make preflight` | Checks that `BUILD_TARGET` builds without building it: configure, the export tiers, and the object of every source file a patch or an addition touches. |
| `make run` | Runs the build with `debug` on in `CAMOU_CONFIG`; wipes `~/.camoufox`. `args="..."` passes arguments. |
| `make path` | Prints the built `camoufox-bin`. |
| `make stage-fonts` | Stages the font bundle into the unpackaged build, which tests through the launchers need. |
| `make tests` | The Playwright suite against the build (`headful=true` for headed). |
| `make help` | Lists every target. |

`git diff` does not show untracked files. Before `make diff`, mark new files
with `git add -N <file>` inside the source tree, or they will be missing from
the patch.

---

## General Workflow

### Step 1: Bump the Version and Find the Broken Patches

Update `version` and `release` in `browser/upstream.sh`, pin the PGO profiles
Mozilla trained for that release and the Remote Settings collections a page can
see of it, then:

```bash
python3 scripts/pgo.py pin
python3 scripts/remote_settings.py pin
make dir
```

`patch.py` applies every patch and ends with a list of the ones that failed and
their reject files. It deletes the `.rej` files after listing them, so reproduce
each failure one patch at a time (Step 2).

### Step 2: Set Up One Patch

Start from a clean unpatched tree, apply what the patch builds on (at least the
Playwright patches, plus anything from `browser/patches/patch-dependencies.md`),
checkpoint, then apply the broken patch. Use `make clean` rather than
`make revert` here: files that other patches created survive a revert and make
`patch` stop on "previously applied" prompts.

```bash
make clean
make patch ./patches/playwright/0-playwright.patch
make patch ./patches/playwright/1-leak-fixes.patch
make first-checkpoint
make patch ./patches/patch-name.patch     # fails, leaving .rej files
```

Find the reject files:

```bash
cd camoufox-<version>-<release>
find . -name '*.rej' -type f
```

### Step 3: Analyze Each Reject File

Read the reject file to understand what failed:

```bash
cat path/to/file.cpp.rej
```

Reject files show:
- `@@` lines: Line numbers where patch expected to apply
- `-` lines: What the patch expected to find (old code)
- `+` lines: What the patch wanted to add (new code)

### Step 4: Locate the Correct Position in Firefox Code

The line numbers in rejects are usually wrong for the new Firefox version. You need to:

1. **Search for unique context** around the reject
2. **Understand what the patch is doing**
3. **Find equivalent location** in new Firefox code

### Step 5: Apply Changes Manually

Edit the file to make the rejected change at the correct location.

### Step 6: Remove Reject Files

After fixing all rejects, delete the `.rej` files and any `.orig` backups
`patch` left, so they do not end up in the diff:

```bash
find . -name '*.rej' -o -name '*.orig' | xargs rm -f
```

### Step 7: Write the Updated Patch

From `browser/`:

```bash
(cd camoufox-<version>-<release> && git add -N path/to/new/file.cpp)   # new files only
make diff > patches/patch-name.patch
```

### Step 8: Verify

Run `make dir` again. The patch should no longer be listed as failing.

---

## Fixing Common Reject Types

### Type 1: Include Directive Rejects

**Symptom**: Reject shows failed `#include` additions

**Example Reject**:
```
@@ -325,6 +325,7 @@
 #include "xpcpublic.h"

+#include "WebRTCIPManager.h"
 #include "nsDocShell.h"
```

**How to Fix**:

1. Read the actual file to find the includes section
2. Search for nearby includes (e.g., `xpcpublic.h`)
3. Add the new include in the appropriate location
4. Firefox include order: system headers, then Mozilla headers, alphabetically within groups

**Example**:

```cpp
// Find this in the actual file:
#include "xpcpublic.h"

// Add the missing includes after it:
#include "xpcpublic.h"

#include "WebRTCIPManager.h"
#include "nsDocShell.h"
#include "mozilla/OriginAttributes.h"
```

### Type 2: Function Signature Changes

**Symptom**: Reject shows function call with changed parameters

**Example Reject**:
```
-  mouseOrPointerEvent.mButton = aButton;
+  mouseOrPointerEvent.mJugglerEventId = aMouseEventData.mJugglerEventId;
```

**Common Causes**:
- Firefox refactored the API
- Parameters moved from individual args to struct/data object
- Parameter order changed

**How to Fix**:

1. Search for the function definition in Firefox source
2. Understand the new API structure
3. Port the patch logic to the new API

**Example - Firefox 146 Mouse Event Refactoring**:

Old Firefox 144 API (individual parameters):
```cpp
void SynthesizeMouseEvent(int x, int y, int button, ...)
```

New Firefox 146 API (structured data):
```cpp
void SynthesizeMouseEvent(SynthesizeMouseEventData& aData,
                         SynthesizeMouseEventOptions& aOptions)
```

Port the patch:
```cpp
// Old patch code:
mouseEvent.mButton = aButton;
mouseEvent.jugglerEventId = aJugglerEventId;

// New patch code for Firefox 146:
mouseOrPointerEvent.mButton = aMouseEventData.mButton;
mouseOrPointerEvent.mJugglerEventId = aMouseEventData.mJugglerEventId;
mouseOrPointerEvent.convertToPointer = aOptions.mConvertToPointer;
```

### Type 3: Missing Context - Code Moved

**Symptom**: Reject shows context that doesn't exist in the file

**How to Fix**:

1. Use grep to search for unique function names or variables in the reject
2. Find where Firefox moved the code
3. Apply the patch to the new location

```bash
# Search across the codebase
grep -r "FunctionName" camoufox-<version>/ --include="*.cpp"
```

### Type 4: New Parameter Added to Function Calls

**Symptom**: Reject shows function call, but Firefox added/removed parameters

**Example - MakeTextRun userContextId**:

Old call:
```cpp
MakeTextRun(text, len, drawTarget, appUnitsPerDevPixel, flags, recorder);
```

New Firefox expects:
```cpp
MakeTextRun(text, len, drawTarget, appUnitsPerDevPixel, flags, recorder, userContextId);
```

**How to Fix**:

1. Extract userContextId from available context (Document, PresContext, etc.)
2. Add proper extraction code before the call
3. Pass userContextId as the last parameter

**userContextId extraction**: the per-context patches resolve it from the
`BrowsingContext`, which exists before the document's attributes are set:

```cpp
uint32_t userContextId = 0;
if (BrowsingContext* bc = win->GetBrowsingContext()) {
  userContextId = bc->OriginAttributesRef().mUserContextId;
}
MakeTextRun(..., userContextId);
```

Workers use `WorkerPrivate::GetOriginAttributes()` instead.

### Type 5: Line Number Shifts (No Code Changes)

**Symptom**: Reject shows patch tried to apply at wrong line number, but code is identical

**How to Fix**:

Simply apply the patch manually at the correct line number. The code hasn't changed, just the location.

---

## Per-Context Machinery

Most spoofing patches carry per-context support. When porting one, expect these
pieces:

1. **Manager classes** (e.g., FontListManager, WebRTCIPManager):
   - Store per-context settings using RoverfoxStorageManager
   - Gate their setter with `RoverfoxStorageManager::IsSetterOffered` and
     `MarkSetterUsed`

2. **Window.webidl functions**:
   - JavaScript APIs exposed to Playwright
   - Examples: `setFontList()`, `setWebRTCIPv4()`

3. **nsGlobalWindowInner.cpp implementations**:
   - Extract userContextId from window/document/docshell
   - Call manager classes
   - Remove the setter after use with `RoverfoxStorageManager::RemoveSetter`

4. **Core logic changes**:
   - Consult the per-context manager before the global config (MaskConfig)
   - Pass userContextId through call chains

See [`per-context-patches.md`](per-context-patches.md) for the full list.

---

## Porting Playwright

The two Playwright patches ([`browser/patches/playwright/`](../browser/patches/playwright/README.md))
and Camoufox's Juggler (`browser/additions/juggler/`) both started from upstream
Playwright and both carry Camoufox changes: fixes to Juggler's input and
navigation paths, the isolated-world page agent, and the human cursor
(`input/`). Port upstream changes into them; never copy upstream over them.

### The Bootstrap Patch

Compare what changed in Playwright's
[bootstrap.diff](https://github.com/microsoft/playwright/blob/main/browser_patches/firefox/patches/bootstrap.diff)
since the last sync, then port it like any other patch:

```bash
make dir
make workspace ./patches/playwright/0-playwright.patch
# port the upstream changes into camoufox-<version>-<release>/
make diff > patches/playwright/0-playwright.patch
```

### Juggler

```bash
git clone https://github.com/microsoft/playwright.git /tmp/playwright
diff -r additions/juggler/ /tmp/playwright/browser_patches/firefox/juggler/
```

Port the upstream hunks one by one, keeping the Camoufox changes. Then check:

1. `components/Juggler.js` still exports `JugglerFactory`.
2. `components/components.conf` registers it with `esModule` (Firefox no longer
   supports `jsm`) and `"constructor": "JugglerFactory"`:

   ```python
   {
       "esModule": "resource://gre/modules/juggler/components/Juggler.js",
       "constructor": "JugglerFactory",
   }
   ```

3. Every file upstream added or renamed is listed in `FINAL_TARGET_FILES` in
   `juggler/moz.build`, and every `ChromeUtils.importESModule()` path still
   exists. Upstream registers a `juggler` chrome package in `jar.mn`; Camoufox
   does not, because a page can detect one (see `juggler/moz.build`), so
   upstream's `chrome://juggler/content/` paths become
   `resource://gre/modules/juggler/`.

Then `make dir && make build && make tests`. A wrong `components.conf` shows up
as one of these:

| Error | Cause |
|---|---|
| `undefined symbol: ... mozCreateComponent<nsICommandLineHandler>()` at link time | `components.conf` is not an ESM component |
| `Externally-constructed components may not specify 'constructor' or 'legacy_constructor' properties` | It uses `jsm` instead of `esModule` |
| `Externally-constructed components must specify a type other than nsISupports` | It is an external component with no type; make it an ESM component |
| `JavaScript components must specify a constructor` | The `constructor` field is missing |

---

## Testing and Validation

### Minimal Verification

After updating a patch, always verify:

1. **Every patch applies cleanly**: `make dir` lists no failures.

2. **Build compiles** (if feasible):
   ```bash
   make build
   ```

### Full Testing

Run the suites that cover the patch (see [`ci/README.md`](../ci/README.md)).
From the repository root,
`python3 -m ci.run_patch_guards --binary <camoufox-bin>` is the most direct
evidence that a patch which still applies was not neutered by the upgrade.

### Browser-Owned GPU Values

The launchers build WebGL from fpgen's recordings, which an older Firefox made.
Some values are the browser's rather than the GPU's, and an upgrade can change
them on every device: Firefox 156 added `EXT_depth_clamp` on Windows and fixed
WebGL1's `ALIASED_LINE_WIDTH_RANGE` at `[1, 1]` on Linux
([`webgl-browser-owned-values-follow-firefox`](../ci/tribal-rules.yml)).
Firefox 158 added `EXT_polygon_offset_clamp` on Windows devices with WebGL2
(ANGLE's D3D11 backend at feature level 10_0 and above) and on Linux desktop GL,
but not on macOS, where release builds use CGL's GL 4.1. Firefox 159 exposes
`EXT_texture_norm16` on WebGL2 wherever the GL has 16-bit normalized textures,
which is every macOS and x86_64 Linux WebGL2 context; on Windows, ANGLE decides
per device. It also adds `EXT_clip_control` and `EXT_texture_mirror_clamp_to_edge`
to both contexts on Linux desktop GL and on Windows (clip control from feature
level 10_0), but not on macOS.
The `stock-gpu-parity` guard finds them. It runs stock Firefox of the new version,
stock Firefox of the release fpgen's model recorded, and Camoufox claiming the
machine's GPU, and fails where the two stock releases differ and Camoufox does
not follow the new one. From the repository root:

```bash
python3 -m ci.run_patch_guards --binary <camoufox-bin> --only stock-gpu-parity
```

CI runs it on Linux with a software renderer. Run it on Windows and macOS too,
passing the stock binaries by hand, because each OS has its own graphics
backend. From the repository root:

```bash
python3 browser/tests/playwright/patches/stock-gpu-parity.py --binary <camoufox-bin> \
    --stock <Firefox of upstream.sh's version> --recorded-stock <Firefox of fpgen's release>
```

For each failure, find in the Firefox source why the value changed and whether
it holds on every device of that backend, then follow it where the launchers
convert a recording (`to_config` in camoucore's
`python/camoufox/src/webgl.py` and `typescript/camoufox/src/webgl.ts`).

---

## Pitfalls

| Pitfall | Avoid it by |
|---|---|
| Trusting reject line numbers | Searching for the context lines instead |
| Hand-editing a `.patch` file | Editing the tree and running `make diff` |
| Missing new files in the patch | `git add -N` them before `make diff` |
| A diff that includes the patch's dependencies | Running `make first-checkpoint` after applying them and before the patch being fixed |
| `.rej` and `.orig` files in the diff | Deleting them first (Step 6) |
| Guessing a value a refactored API now needs | Reading the new Firefox code, or the release notes |
| Fixing several patches in one pass | One patch at a time, each from `make clean` |

## Appendix: Firefox Source Navigation

### Finding Files

```bash
# Find files by name
find . -name "Navigator.cpp" -type f

# Find files containing a symbol
grep -r "GetAcceptLanguages" . --include="*.cpp"

# Find class definitions
grep -r "class Navigator" . --include="*.h"
```

### Understanding Firefox Code Structure

- `dom/`: DOM implementation
  - `dom/base/`: Core DOM classes (Window, Document, Navigator, etc.)
  - `dom/webidl/`: WebIDL interface definitions
  - `dom/media/webrtc/`: WebRTC implementation
- `gfx/`: Graphics and font rendering
  - `gfx/thebes/`: Text rendering (fonts, glyphs, shaping)
- `layout/`: Layout engine
  - `layout/generic/`: Text frames
  - `layout/mathml/`: MathML rendering

---

## Checklist

- [ ] Bump `browser/upstream.sh`, run `python3 scripts/pgo.py pin` and `python3 scripts/remote_settings.py pin`, and run `make dir` to list the failing patches
- [ ] Delete the [backports](../browser/patches/patch-dependencies.md#backports) the new Firefox ships
- [ ] For each: `make clean`, apply its dependencies, `make first-checkpoint`, `make patch` it
- [ ] Port each reject to the new Firefox code
- [ ] Remove `.rej` and `.orig` files, `git add -N` new files
- [ ] `make diff > patches/<name>.patch`
- [ ] `make dir` applies the whole stack cleanly, with no fuzz
- [ ] `make build`, then run the patch guards; `firefox-version-pin` checks that the build and every identity are the new Firefox
- [ ] Run `stock-gpu-parity` on Linux, Windows and macOS ([Browser-Owned GPU Values](#browser-owned-gpu-values))

---

## Additional Resources

- Firefox source: https://searchfox.org/
- Firefox API documentation: https://firefox-source-docs.mozilla.org/
- Mercurial repository: https://hg.mozilla.org/mozilla-central/

---

### Per Context Patches (`docs/per-context-patches.md`)

# Per-context fingerprint patches

`CAMOU_CONFIG` sets one identity for the whole browser. The per-context patches
let each Playwright context carry its own, so one Camoufox process can run many
sessions that do not correlate. The launchers use them through `NewContext()`
([Python](https://github.com/CamouBrowser/camoucore/blob/main/python/camoufox/docs/README.md#one-browser-many-identities),
[TypeScript](https://github.com/CamouBrowser/camoucore/blob/main/typescript/camoufox/docs/README.md#one-browser-many-identities)); this page is
for people working on the patches or driving the browser without a launcher.

## The setters

Each per-context patch adds a function to `window`. A setter stores its value
for the calling window's context, and is gone before any page script runs
(`window-setter-seal.patch`).

| Function | Patch | What a page sees |
|---|---|---|
| `setTimezone(tz)` | `timezone-spoofing.patch` | `Date`, `Intl.DateTimeFormat` and every other time API |
| `setScreenDimensions(w, h)` | `screen-spoofing.patch` | `screen.width`, `screen.height`, matching CSS media features |
| `setScreenColorDepth(depth)` | `screen-spoofing.patch` | `screen.colorDepth` |
| `setNavigatorPlatform(platform)` | `navigator-spoofing.patch` | `navigator.platform` |
| `setNavigatorOscpu(oscpu)` | `navigator-spoofing.patch` | `navigator.oscpu` |
| `setNavigatorHardwareConcurrency(cores)` | `navigator-spoofing.patch` | `navigator.hardwareConcurrency` |
| `setNavigatorAppVersion(appVersion)` | `navigator-spoofing.patch` | `navigator.appVersion`, in workers too |
| `setNavigatorUserAgent(ua)` | `navigator-spoofing.patch` | `navigator.userAgent`, in workers too |
| `setWebRTCIPv4(ip)` | `webrtc-ip-spoofing.patch` | ICE candidates, SDP, `getStats()` |
| `setWebRTCIPv6(ip)` | `webrtc-ip-spoofing.patch` | The same, for IPv6 |
| `setWebGLVendor(vendor)` | `webgl-spoofing.patch` | `UNMASKED_VENDOR_WEBGL` |
| `setWebGLRenderer(renderer)` | `webgl-spoofing.patch` | `UNMASKED_RENDERER_WEBGL` |
| `setFontList(fonts)` | `font-list-spoofing.patch` | Which fonts exist (comma-separated, case-insensitive) |
| `setSpeechVoices(voices)` | `speech-voices-spoofing.patch` | `speechSynthesis.getVoices()` (comma-separated names, or a JSON `{"speechd": grid}` for a Linux identity) |

Supporting patches, with no setter of their own:

| Patch | Provides |
|---|---|
| `anti-font-fingerprinting.patch` | The context id on each font group |
| `cross-process-storage.patch` | `RoverfoxStorageManager`, the per-context store, with the IPC that makes a value set in one process readable in every other, and the guard and removal every setter uses |

There is no canvas pixel noise, no audio noise and no glyph-spacing noise: each
produces output no real machine does ([`ci/tribal-rules.yml`](../ci/tribal-rules.yml)). A
browser launched with `canvas_noise=True` returns random canvas readback, as
`privacy.resistFingerprinting` does, for every context.

## Using the setters

Call them from `addInitScript`, which runs before page scripts on every new
page, frame and navigation. The `typeof` guards keep the script harmless on a
build without the patches.

```javascript
import { firefox } from "playwright-core";

const browser = await firefox.launch({ executablePath: "/path/to/camoufox-bin" });
const context = await browser.newContext();
await context.addInitScript((v) => {
  const w = window;
  if (typeof w.setTimezone === "function") w.setTimezone(v.timezone);
  if (typeof w.setScreenDimensions === "function") w.setScreenDimensions(v.width, v.height);
  if (typeof w.setNavigatorPlatform === "function") w.setNavigatorPlatform(v.platform);
  if (typeof w.setWebRTCIPv4 === "function") w.setWebRTCIPv4(v.webrtcIp);
}, {
  timezone: "America/New_York",
  width: 1920,
  height: 1080,
  platform: "Win32",
  webrtcIp: "203.0.113.1",
});
const page = await context.newPage();
await page.goto("https://example.com");
await browser.close();
```

Values set this way must still describe one plausible machine. The launchers'
`generate_context_fingerprint()` (`fingerprints.py`) draws them together and
builds this script; prefer it to hand-picked values.

## Architecture

### Storage

All setters share `RoverfoxStorageManager`, a mutex-protected key-value store
keyed by `userContextId` (each Playwright context is a Firefox container with
its own id).

| Step | Write path |
|---|---|
| 1 | The setter resolves `userContextId` from the window's `BrowsingContext`. |
| 2 | The value goes into the in-process cache. |
| 3 | It is also written as a pref with the `roverfox.s.` prefix (every type serialized as a string). |
| 4 | In a content process, it is sent to the parent with sync IPC (`SendRoverfoxStoragePut`). |
| 5 | Navigator, screen, timezone and WebGL also store it under id 0, for workers that cannot resolve their context. Fonts, voices and WebRTC do not. |

| Tier | Read path |
|---|---|
| 1 | The in-process cache |
| 2 | Firefox prefs, which Firefox syncs to every content process (main thread only) |

Off the main thread (workers, HarfBuzz, the compositor) only tier 1 is read;
the main thread keeps it a mirror of every `roverfox.s.` pref. There is no
read from the parent: a put reaches the parent synchronously, and the pref
update it sends each content process is queued ahead of any later document
load there, so a document never needs it. Asking the parent cost the first
read of each unset key 16-54 ms, which a page can time.

Getters a page can call in a loop (navigator, screen, timezone, WebGL vendor
and renderer) read through `GetUint`, `GetBool` and `GetString`
taking a prefix literal and the id (`"nav_hwc_", id`). Each thread memoizes
those answers, keyed by prefix and id, until any write in the process bumps a
generation counter, so a repeat read builds no key and takes no lock and costs
what the stock getter does.

### Cross-process storage

`cross-process-storage.patch` adds a sync message to `PContent.ipdl`,
`RoverfoxStoragePut`. The parent accepts only pref names starting with
`roverfox.s.`. Put is synchronous so the value is in the
parent before any worker process starts. The patch also adds `roverfox.s.` to
`sDynamicPrefOverrideList` in `Preferences.cpp`, because Firefox otherwise
strips dynamically created string prefs from content processes.

Files: `dom/base/RoverfoxStorageManager.cpp/h`, `ContentParent.cpp/h`,
`PContent.ipdl`, `ipc/ipdl/sync-messages.ini`, `modules/libpref/Preferences.cpp`.

### Setter guard and removal

Every setter uses the same three `RoverfoxStorageManager` helpers:

| Helper | Used by | Does |
|---|---|---|
| `IsSetterOffered` | The setter's WebIDL `Func=` guard | False once the window is sealed or the context has used the setter |
| `MarkSetterUsed` | The setter, or its manager's `Set*` | Records the use in the shared store, so later documents of the context, in any process, are never offered it |
| `RemoveSetter` | The setter, after it runs | Deletes the name from the calling global |

### Context resolution and lookup order

Windows resolve the id from `BrowsingContext`, which exists before the
DocShell or Document attributes are populated:

```cpp
if (BrowsingContext* bc = win->GetBrowsingContext()) {
  userContextId = bc->OriginAttributesRef().mUserContextId;
}
```

Workers use `WorkerPrivate::GetOriginAttributes()`. A spoofed getter checks the
per-context value first, then `CAMOU_CONFIG` through `MaskConfig`, then the
real value.

### Prefs that make it work

[`browser/settings/camoufox.cfg`](../browser/settings/camoufox.cfg):

| Pref | Why |
|---|---|
| `fission.autostart = true` | Disabled Fission is detectable; cross-process storage makes per-context values work with it |
| `fission.webContentIsolationStrategy = 0` | Cross-site iframes stay in their parent's process. Set by Juggler when a driver is attached; otherwise Firefox's default |

`dom.ipc.processCount` and `dom.ipc.processPrelaunch.enabled` are not overridden: a prelaunched process takes its context's values like any other (measured 2026-10-26, 3 contexts x 3 rounds).

## Patch details

| Patch | Hooks | Notes |
|---|---|---|
| `timezone-spoofing.patch` | SpiderMonkey `DateTimeInfo` per realm (`JS::SetRealmTimeZoneOverride`), `nsGlobalWindowOuter::SetNewDocument`, `WorkerPrivate::GetOrCreateGlobalScope` | The only patch inside SpiderMonkey. Re-applied on navigation and in dedicated, shared and service workers; also sets a process-wide override. Invalid IDs throw `TypeError`. |
| `screen-spoofing.patch` | `nsScreen::GetRect`, `nsDeviceContext`, `nsMediaFeatures.cpp` | CSS `device-width` and `color` agree with `screen.*`. |
| `navigator-spoofing.patch` | `Navigator::GetPlatform`, `GetOscpu`, `HardwareConcurrency`, `GetUserAgent`, `GetAppVersion`; the `WorkerNavigator` versions of platform, cores, UA and appVersion | Falls back to `navigator.*` in `CAMOU_CONFIG`. |
| `webrtc-ip-spoofing.patch` | `SanitizeSDPForIPLeak`, `CandidateReady`, candidate `.address`/`.relatedAddress`, `getStats()`, `UpdateDefaultCandidate`, `NrSocketBase::CreateSocket` | Forces `default_address_only` while spoofing; loopback, link-local and private addresses are left alone. UDP candidate ports come from the ephemeral range of the identity's OS (`MaskConfig::SpoofedEphemeralPorts()`), so a Windows identity on Linux never shows a Linux port. |
| `webgl-spoofing.patch` | `ClientWebGLContext::GetParameter` | Per context: vendor and renderer. Global only (`CAMOU_CONFIG`): parameters, extensions, shader precision. Works from `OffscreenCanvas` in workers. |
| `font-list-spoofing.patch` | `gfxPlatformFontList::FindAndAddFamiliesLocked` | A thread-local context id, set by an RAII guard in `FontFaceSet::Check/Load` and `gfxFontGroup::EnsureFontList`, avoids changing ~50 signatures. The list is in the shared store, so it holds in every content process. An `OffscreenCanvas` in a worker takes the worker's context (`anti-font-fingerprinting.patch`); other worker lookups are not filtered. |
| `speech-voices-spoofing.patch` | `SpeechSynthesis::GetVoices` | Filters the real list by name; a listed voice that is not installed is left out. |

Global-only patches (no setter) read `CAMOU_CONFIG` at startup:

| Patch | Config keys | Effect |
|---|---|---|
| `geolocation-spoofing.patch` | `geolocation:latitude`, `geolocation:longitude`, `geolocation:accuracy` | Returns these coordinates and grants the permission. Per context, use Playwright's `geolocation` option. |
| `locale-spoofing.patch` | `locale:*`, `navigator.language` | `navigator.language`, `Accept-Language`, `Intl`, the OS locale. |
| `force-default-pointer.patch` | `navigator.maxTouchPoints` | CSS `pointer` reports a fine pointer on desktop. |

Every patch that reads `CAMOU_CONFIG` is listed in
[`browser/patches/patch-dependencies.md`](../browser/patches/patch-dependencies.md).

## Build notes

| Topic | Rule |
|---|---|
| `SOURCES` vs `UNIFIED_SOURCES` | Manager `.cpp` files go in `SOURCES`, because unified builds that include `RoverfoxStorageManager.h` hit `mozilla::dom::mozilla::dom::`. `RoverfoxStorageManager.cpp` and `TimezoneManager.cpp` compile unified. |
| `EXPORTS` | Each patch adds its own `EXPORTS.mozilla.dom += [...]` next to its `SOURCES`, to avoid conflicts in the sorted list. |
| WebIDL | Each setter has its own `partial interface Window` block. |

## Where the launcher's values come from

`NewBrowser` puts one identity in `CAMOU_CONFIG`; `NewContext` builds a
per-context init script. fpgen draws both by default.
`fingerprint_preset=True` (or `preset=` for `NewContext`) opts into recorded
real-device presets instead:

| Bundle | Firefox | Presets (macOS / Windows / Linux) |
|---|---|---|
| `fingerprint-presets-v150.json` | 149 and newer (`PRESETS_V150_MIN_FF`) | 285 (58 / 168 / 59) |
| `fingerprint-presets.json` | older | 113 (25 / 71 / 17) |

The User-Agent's version is rewritten to the running browser's.

| Value | Source |
|---|---|
| UA, platform, cores, oscpu | fpgen or the preset; UA version set to the browser's |
| Screen, color depth | fpgen or the preset |
| WebGL | One GPU fpgen recorded for Firefox on that OS, weighted by its share and checked against the machine (`coherence.gpu_fits_machine()`); `webgl_for_gpu()` adds its parameters, extensions and shader precisions |
| Fonts | `_generate_random_font_subset()`: one OS-version base plus measured additions ([FONTS.md](FONTS.md)); never from presets |
| Voices | `draw_voice_config()`, from `voice-manifests.json`, seeded by the identity; never from presets. A Linux identity's voices come from the same Ubuntu release as its fonts, sent as a `voices:speechd` grid (languages x variants) that `MaskConfig::ExpandSpeechdGrid` expands: ~14000 voice objects do not fit in the environment. macOS uses the list measured on macOS 27 with its system voice default; Windows its OneCore packs |
| Timezone | The preset, or `timezone` in `CAMOU_CONFIG` (from geoip); with a proxy, `NewContext` looks it up from the exit IP |
| WebRTC IP | `NewContext`'s `webrtc_ip` or the proxy's exit IP, to the IPv4 or IPv6 setter; an invalid address raises `InvalidIP` |
| Geolocation | The `geolocation` argument, via Playwright |

## Known limitations

These patches control what APIs report. They cannot change how the host OS
renders, so some signals still show the real OS:

| Signal | Why |
|---|---|
| Text rendering | Core Text, DirectWrite and FreeType rasterize the same font differently, which shows in canvas hashes |
| GPU rasterization | Canvas and WebGL output carry the host GPU driver's rasterization |
| System colors | `AccentColor` and system colors differ by OS and desktop |
| Shader precision behaviour | Actual precision follows the real driver even when the reported formats are spoofed |

Run each identity on the OS it claims. The per-context patches make each
context a different person on the same OS, not a different OS. Where that is
not possible, launch with `canvas_noise=True`: canvas and WebGL readback then
return random data, which covers the two rasterization rows above. A browser
launched without it gives its contexts the host's OS and GPU, and `NewContext`
raises for another OS or GPU.

The settings that make a Windows identity on another host behave as Windows
([HOST-PARITY.md](HOST-PARITY.md): CRT math, keyboard, behaviour prefs,
scrollbars) are prefs and launch config, not per-context setters. They follow
the OS the browser was launched with: every context on a browser launched as
Windows gets them, and no context on a browser launched as another OS does.
`NewContext` does not refuse the mix, since a launch without `os` draws its OS
and the refusal would depend on the draw.

---

--- METRICS ---
- Files Extracted: 16
- Estimated Token Budget: ~50544 tokens
- Canonical Reference: https://codewiki.google/github.com/daijro/camoufox
