Stealth Chromium that passes every bot detection test. Drop-in Playwright replacement with source-level fingerprint patches. 50+ tests passed.
Python ai-agentsanti-detectantidetect-browserbot-detectionbrowser-automationcaptcha-bypasschromiumcloudflarecloudflare-bypassfingerprintheadless-browserplaywrightpuppeteerpythonrecaptchaseleniumstealth-browserundetectedweb-scrapingwebscraping
feat!: free key by email, keyless mode removed
CloakHQ55596c8a1192
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 872040f..1ba0f35 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -36,14 +36,26 @@ jobs:javascript-browser:# Humanize engine + Puppeteer tests against the real CloakBrowser binary.runs-on: ubuntu-latest+ # A launch needs a key: it downloads the binary and the binary checks it at start.+ env:+ CLOAKBROWSER_LICENSE_KEY: ${{ secrets.CLOAKBROWSER_CI_KEY }}steps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0with:node-version: 22+ - name: Check for a license key+ id: key+ # GitHub never gives secrets to PRs from forks (a PR's code could read+ # and leak them), so the key is empty there: skip instead of failing.+ run: |+ if [ -n "$CLOAKBROWSER_LICENSE_KEY" ]; then echo "present=true" >> "$GITHUB_OUTPUT"+ else echo "::notice::Real-browser tests skipped: no license key (PRs from forks get no secrets)."; fi- name: Install and build+ if: steps.key.outputs.present == 'true'run: cd js && npm install && npm run build- name: Download the binary+ if: steps.key.outputs.present == 'true'run: |set -o pipefailcd js@@ -52,8 +64,11 @@ jobs:test -x "$path" || { echo "::error::binary download failed (got: '$path')"; exit 1; }echo "CLOAKBROWSER_BINARY_PATH=$path" >> "$GITHUB_ENV"- name: Install browser system deps+ if: steps.key.outputs.present == 'true'run: cd js && npx playwright-core install-deps chromium- name: Run real-browser tests+ if: steps.key.outputs.present == 'true'+ # Up to 4 browsers at once (2 files, 2 each): the key needs that many sessions.run: cd js && xvfb-run -a npx vitest run tests/humanizeEngine.test.ts tests/humanizePuppeteer.test.tsdotnet:diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8878c92..7820018 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,21 @@ Changes are tagged: **[wrapper]** for Python/JS wrapper, **[binary]** for Chromi---+## [0.7.0] — unreleased++**Breaking: every launch now needs a license key.** A free key takes one email and gets the latest build (1 concurrent session). The old keyless v146 build is no longer downloaded. To keep running it without a key, stay on the 0.6 wrapper: `pip install "cloakbrowser<0.7"`, `npm install [email protected]`, `dotnet add package CloakBrowser --version 0.6.5`, or the Docker image `cloakhq/cloakbrowser:0.6.5`.++- **[wrapper]** A launch with no key (no `license_key=`, no `CLOAKBROWSER_LICENSE_KEY`, no saved `~/.cloakbrowser/license.key`) shows a short menu in a terminal: **1)** get a free key (prints a signup link, opens it in your browser and continues once you confirm your email) or **2)** paste a key you have. The key is saved and the launch continues on the latest build. If the email already has a free key, the menu says so and asks you to paste it. Ctrl+C at the menu quits without a traceback. Python, JavaScript, and .NET+- **[wrapper]** Without a terminal (CI, Docker without `-it`, MCP servers, `launch_async` on a worker thread) the launch raises `CloakBrowserLicenseError` with the signup link instead of waiting. After you confirm, the key is also emailed to you; a long-running process that keeps going picks it up if you confirm within 10 minutes and uses it on its next launch, and the next run on the same machine finds it on its own. Python, JavaScript, and .NET+- **[wrapper]** `cloakbrowser login` with no argument shows the same menu. It now requires both stdin and stderr to be a terminal; otherwise it prints the usage and exits 2. `logout` also drops a pending signup. GitHub sign-in is gone from the CLI. Python, JavaScript, and .NET+- **[wrapper]** The saved key file is created readable by its owner only (`0600`) on Linux and macOS, also from .NET, which did not restrict it before. Only `cb_…` keys are accepted. Python, JavaScript, and .NET+- **[wrapper]** Docker: the image no longer contains a binary. The latest build downloads on the first launch with your key: pass `-e CLOAKBROWSER_LICENSE_KEY`, or run with `-it` to be asked for one. `cloaktest` prints a short message instead of a traceback when there is no key, and Ctrl+C in `docker run -it` no longer prints an X server error+- **[wrapper]** Headless launches no longer emulate a fixed 1920x947 viewport: pages track the window the binary reports, as headed launches already did. `--start-maximized` is added whenever no window size or viewport is given, and credentialed HTTP proxies always go inline through `--proxy-server`. These used to depend on the binary version; every build served today supports them, so a `CLOAKBROWSER_BINARY_PATH` binary no longer needs its version declared. Python, JavaScript, and .NET+- **[wrapper]** **Removed:** `CHROMIUM_VERSION` / `PLATFORM_CHROMIUM_VERSIONS` / `get_chromium_version`, `check_for_update` (JS `checkForUpdate`, .NET `Download.CheckForUpdateAsync`), the binary-version gate helpers, `DEFAULT_VIEWPORT`, the GitHub Releases download fallback, and the `CLOAKBROWSER_DOWNLOAD_URL` and `CLOAKBROWSER_SKIP_CHECKSUM` variables. `binary_info()` no longer has `tier` or `bundled_version`, and its `version` is empty until a build has been downloaded. `cloakbrowser info` reports the license tier as `none` without a key, and `cloakbrowser update` needs a key. Python, JavaScript, and .NET+- **[wrapper]** .NET: an invalid, expired, or unverifiable key now throws `CloakBrowserLicenseError` (was `InvalidOperationException`), like Python and JavaScript. `Humanize.Browser(browser, config, defaultNoViewport)` replaces the `headless` / `headlessNoViewport` parameters. .NET only+- **[wrapper]** The welcome banner no longer names a Chromium version, and links the docs and cloakbrowser.dev. A paid key sees it once per machine; a free key once a day. Python, JavaScript, and .NET+- **[wrapper]** The new-wrapper-version notice now also reaches users with a key (it only ran without one before). Python, JavaScript, and .NET+## [0.6.5] — 2026-10-31- **[wrapper]** `context.close(reason=...)` on a `launch_context()` / `launch_context_async()` context now passes the reason to Playwright. Python raised `TypeError` and left the browser running; JavaScript `launchContext()` dropped the reason. .NET handles gain `CloseAsync(options)`. The browser is now closed even when closing the context fails. Python, JavaScript, and .NET (#609, #633)diff --git a/Dockerfile b/Dockerfileindex b6cd95c..b3680bd 100644--- a/Dockerfile+++ b/Dockerfile@@ -32,10 +32,8 @@ RUN cd js && npm install && npm run build# ExamplesCOPY examples/ examples/-# Pre-download stealth Chromium binary during build (not at runtime)-# Remove welcome marker so users see it on first container run-RUN python -c "from cloakbrowser import ensure_binary; ensure_binary()" \- && rm -f ~/.cloakbrowser/.welcome_shown+# No binary in the image: it downloads on first launch with your license key+# (docker run -e CLOAKBROWSER_LICENSE_KEY=cb_...). Free key: cloakbrowser login.# CLI shortcutsCOPY bin/cloaktest /usr/local/bin/cloaktestdiff --git a/README.md b/README.mdindex bebb1aa..9302f15 100644--- a/README.md+++ b/README.md@@ -40,14 +40,14 @@ Same API, same code — just swap the import. <strong>3 lines of code, 30 second- **`humanize=True`** — human-like mouse curves, keyboard timing, and scroll patterns. One flag, behavioral detection passes- **Pro: 0.9 reCAPTCHA v3 score** — human-level, server-verified- **Passes Cloudflare Turnstile**, FingerprintJS, BrowserScan — tested against 50+ detection sites-- **Auto-downloads the right binary** — free or Pro based on your license+- **Auto-downloads the right binary** — the latest build for your platform- **`pip install cloakbrowser`** or **`npm install cloakbrowser`** — binary auto-downloads, zero config-- **Latest binary, free to try** — [sign in with GitHub](https://cloakbrowser.dev/free), point the newest build at your hardest target, scale to thousands of sessions on Pro+- **Latest binary, free to try** — [get a free key with your email](https://cloakbrowser.dev/free) (or just launch: the first run asks), point the newest build at your hardest target, scale to thousands of sessions on Pro-**Try it now** — no install needed:+**Try it now** — no install needed. The first run asks for a key: get one free with your email, or paste yours:```bash-docker run --rm cloakhq/cloakbrowser cloaktest+docker run --rm -it cloakhq/cloakbrowser cloaktest```**Python:**@@ -126,6 +126,8 @@ dotnet add package CloakBrowserOn first run, the stealth Chromium binary is automatically downloaded (~200MB, cached locally).+**License key:** every launch needs one, and a free key takes one email. The first launch in a terminal asks: get a free key (opens the signup page and continues once you confirm your email) or paste a key you have. In CI, Docker, or any run without a terminal, set `CLOAKBROWSER_LICENSE_KEY` (get one with `cloakbrowser login` or at [cloakbrowser.dev/free](https://cloakbrowser.dev/free)).+**Optional:** Auto-detect timezone/locale from proxy IP:```bash@@ -186,12 +188,11 @@ CloakBrowser doesn't solve CAPTCHAs — it prevents them from appearing. No CAPTAnti-bot systems change every week and an older binary quietly degrades. The latest build is the one that keeps passing. **Try it free, then upgrade when you're running for real.**-- **Free, latest build (Chromium 156)** — the newest binary, the exact one that stays [green against live detection](#test-results). Free with a GitHub sign-in, one concurrent session. [Grab your key](https://cloakbrowser.dev/free) or run `cloakbrowser login`, then throw it at your hardest target.+- **Free, latest build (Chromium 156)** — the newest binary, the exact one that stays [green against live detection](#test-results). Free with your email, one concurrent session. Just launch (the first run asks), run `cloakbrowser login`, or [grab your key](https://cloakbrowser.dev/free), then throw it at your hardest target.- **Pro** — when it's part of production scraping, QA, monitoring, or automation: scale to **5, 20, 200, 2,000, or more concurrent sessions**, always first on the newest patches, with hands-on support. Linux, Windows, macOS. **[See plans and pricing →](https://cloakbrowser.dev)**-- **v146** — the older build stays free on [GitHub Releases](https://github.com/CloakHQ/cloakbrowser/releases). A quick first look, but it ages fast as detection evolves.```bash-cloakbrowser login # GitHub sign-in for a free key, or paste a paid key+cloakbrowser login # get a free key by email, or paste a key you have# ...or set it directly (env var, license_key= param, or ~/.cloakbrowser/license.key):export CLOAKBROWSER_LICENSE_KEY=cb_xxxxxxxx```@@ -208,7 +209,7 @@ Every profile is a genuinely separate computer: its own fingerprint, GPU, screen- **Native desktop app** — profiles open as normal windows on Windows and macOS. On a Linux server they run in Docker and stream to your browser.- **The real engine** — most profile managers inject JavaScript into a stock browser. Every profile here runs the patched Chromium binary this repo ships.- **Automate what you can see** — every running profile exposes a CDP endpoint. Drive it with Playwright or Puppeteer while you watch the exact same window live.-- **One key, both products** — your CloakBrowser key works in the Manager too. Free with a GitHub sign-in for one profile at a time.+- **One key, both products** — your CloakBrowser key works in the Manager too. Free with your email for one profile at a time.It's also the fastest way to try the browser without writing any code: download, create a profile, click **Launch**.@@ -281,7 +282,7 @@ All tests verified against live detection services. Results below are for the laCloakBrowser is a thin wrapper (Python + JavaScript) around a custom-built Chromium binary:1. **You install** → `pip install cloakbrowser` or `npm install cloakbrowser`-2. **First launch** → binary auto-downloads for your platform (latest build with a free or Pro key, the older v146 without one)+2. **First launch** → asks for a license key if you have none (free by email), then the latest build auto-downloads for your platform3. **Every launch** → Playwright or Puppeteer starts with our binary + stealth args4. **You write code** → standard Playwright/Puppeteer API, nothing new to learn@@ -304,7 +305,7 @@ browser = launch()# Headed mode (see the browser window)browser = launch(headless=False)-# Latest binary — pass a key (free via `cloakbrowser login`, or paid) or set CLOAKBROWSER_LICENSE_KEY+# Pass a key explicitly (free via `cloakbrowser login`, or paid); otherwise the env var or saved key is usedbrowser = launch(license_key="cb_xxxxxxxx")# With proxy (HTTP or SOCKS5)@@ -447,15 +448,15 @@ Async version: `launch_persistent_context_async()`.Pre-download the binary, diagnose your setup, or manage the cache from the command line:```bash-python -m cloakbrowser login # Get a free key via GitHub, or save a paid key-python -m cloakbrowser logout # Remove the saved key (revert to the free binary)+python -m cloakbrowser login # Get a free key by email, or save a key you have+python -m cloakbrowser logout # Remove the saved keypython -m cloakbrowser install # Download binary with progress outputpython -m cloakbrowser info # Diagnostics: binary that will launch, license tier, env checkspython -m cloakbrowser update # Check for and download newer binarypython -m cloakbrowser clear-cache # Remove cached binaries```-`login` with no argument prompts you to paste a license key or press Enter to get a free key via a GitHub sign-in; `login <key>` saves a key directly. Both validate the key, then store it at `~/.cloakbrowser/license.key` so every launch picks it up.+`login` with no argument shows the same menu as a first launch without a key: **1)** get a free key (opens the signup page in your browser, then waits until you confirm your email) or **2)** paste a key you have. `login <key>` saves a key directly. Keys are validated, then stored at `~/.cloakbrowser/license.key` (readable by you only) so every launch picks them up.`info` reports the binary that will actually launch given your license, runs a quick launch test (and flags missing system libraries on Linux), shows your license tier, and checks fonts, GeoIP, and optional dependencies. Add `--quick` to skip the launch test or `--json` for machine-readable output. Add `--proxy <url>` to resolve the exit IP, timezone, and locale a launch would apply through that proxy (the same `geoip=True` resolution; downloads the GeoIP DB if not cached) — useful for confirming a proxy hands you a timezone/locale that matches its exit IP.@@ -470,12 +471,13 @@ from cloakbrowser import binary_info, clear_cache, ensure_binary# Check binary installation statusprint(binary_info())-# {'version': '146.0.7680.177.5', 'platform': 'linux-x64', 'installed': True, ...}+# {'version': '155.0.8059.39.2', 'platform': 'linux-x64', 'installed': True, ...}+# ('version' is None until a build has been downloaded)# Force re-downloadclear_cache()-# Pre-download binary (e.g., during Docker build)+# Pre-download binary (e.g., during Docker build; needs CLOAKBROWSER_LICENSE_KEY set)ensure_binary()```@@ -642,11 +644,10 @@ For an arbitrary expression, `page._stealth_world.evaluate("…")` evaluates it| Env Variable | Default | Description ||---|---|---|-| `CLOAKBROWSER_BINARY_PATH` | — | Skip download, use a local Chromium binary. Set `CLOAKBROWSER_VERSION` (or `browser_version=`) to that binary's exact version too, or proxy auth and headless viewport fall back to safe defaults |+| `CLOAKBROWSER_LICENSE_KEY` | — | Your license key (free or paid). Overrides `~/.cloakbrowser/license.key`. Required wherever there is no terminal to ask (CI, Docker) |+| `CLOAKBROWSER_BINARY_PATH` | — | Skip download, use a local Chromium binary || `CLOAKBROWSER_CACHE_DIR` | `~/.cloakbrowser` | Binary cache directory |-| `CLOAKBROWSER_DOWNLOAD_URL` | `cloakbrowser.dev` | Custom download URL for binary |-| `CLOAKBROWSER_AUTO_UPDATE` | `true` | Set to `false` to disable background update checks |-| `CLOAKBROWSER_SKIP_CHECKSUM` | `false` | Only applies to a custom `CLOAKBROWSER_DOWNLOAD_URL`: set to `true` to skip its checksum check. Signature verification on the official download path is mandatory and cannot be skipped. |+| `CLOAKBROWSER_AUTO_UPDATE` | `true` | Set to `false` to keep the cached build and skip update checks || `CLOAKBROWSER_GEOIP_TIMEOUT_SECONDS` | `5` | Max seconds for GeoIP resolution before continuing without it || `CLOAKBROWSER_VERSION` | — | Pin to an exact Chromium version for rollback (e.g. `154.0.8037.57.1`). Paid Pro key only || `CLOAKBROWSER_RELEASE_CHANNEL` | `stable` | Set to `preview` to opt into the Preview binary channel |@@ -706,14 +707,14 @@ Supported by the binary but **not set by default** — pass via `args` to custom| `--fingerprint-taskbar-height` | Override taskbar height (binary defaults: Win=48, Mac=95, Linux=0) || `--fingerprint-webrtc-ip` | WebRTC ICE candidate IP replacement. Use `auto` to resolve from proxy exit IP (makes an HTTP call through the proxy), or pass an explicit IP. Auto-injected when `geoip=True` || `--fingerprint-noise=false` | Disable noise injection (canvas, WebGL, audio) while keeping the deterministic fingerprint seed active |-| `--fingerprint=off` | **Chromium 148+ binary only.** Pass-through debug mode — turns spoofing off and presents the machine's **real native fingerprint** (keeps only the baseline any Chrome needs). The binary strips the injected seed *and* `--fingerprint-platform`, so there's no mixed OS profile. Most useful on a genuine Windows machine to check whether an issue is our spoofing or the environment. Accepts `off`/`false`/`0`/`disable`/`disabled`. For a *pure* pass-through don't combine it with `geoip=True` / explicit timezone / locale — those stay applied. |-| `--fingerprint-allow-3p-cookies` | **Chromium 148+ binary only.** Re-enable third-party cookies for embedded flows that need them (reCAPTCHA v3, SSO, some payment challenges). Off by default; turn on only where a login/payment/embedded challenge loads but never finishes. |-| `--fingerprint-sapi-voices=false` | **Chromium 150+ binary only.** Opt out of the Windows speech-voice tables when spoofing Windows. On by default (the voice set matches a real Chrome install); turn off only if a target reacts badly to the Windows voice list. |-| `--license-route=auto\|direct\|proxy` | **Chromium 154.0.8037.57.2+ on Linux, 155+ on all platforms.** How the Pro license and session calls leave the browser. `auto` (default): direct to cloakbrowser.dev first, and one retry through your `--proxy-server` if direct can't reach it. `direct`: never through the proxy. `proxy`: only through the proxy (needs `--proxy-server`). |-| `--license-through-proxy` | **Chromium 148+ binary only (all platforms).** Route the Pro license/session calls through your `--proxy-server` instead of direct to cloakbrowser.dev. Off by default (these calls go direct, so they never spend proxy bandwidth or touch your scraping session). On `154.0.8037.57.2` and newer, use `--license-route=proxy`; this older spelling still works. |-| `--fingerprint-transparent-proxy` | **Chromium 151+ binary only.** A stronger way of connecting through your `--proxy-server`, for sites and providers that block every proxy you try. Off by default; enable it alongside `--proxy-server`. |-| `--fingerprint-transparent-proxy-dns=<url>\|local` | **Chromium 155.0.8059.39.1+ binary only, Linux and Windows.** DNS for `--fingerprint-transparent-proxy` mode. By default sites are resolved with Cloudflare's DNS over HTTPS, sent through your proxy. Pass your own DNS over HTTPS address, or `local` to resolve on your own machine as before. |-| `--fingerprint-portable-cookies` | **Chromium 151+ binary only.** Encrypt cookies with a machine-independent key so a copied profile keeps its logins across machines. Turn it on from the first launch — it changes how cookies are written, so a cookie is only portable if this was set when it was saved. |+| `--fingerprint=off` | Pass-through debug mode — turns spoofing off and presents the machine's **real native fingerprint** (keeps only the baseline any Chrome needs). The binary strips the injected seed *and* `--fingerprint-platform`, so there's no mixed OS profile. Most useful on a genuine Windows machine to check whether an issue is our spoofing or the environment. Accepts `off`/`false`/`0`/`disable`/`disabled`. For a *pure* pass-through don't combine it with `geoip=True` / explicit timezone / locale — those stay applied. |+| `--fingerprint-allow-3p-cookies` | Re-enable third-party cookies for embedded flows that need them (reCAPTCHA v3, SSO, some payment challenges). Off by default; turn on only where a login/payment/embedded challenge loads but never finishes. |+| `--fingerprint-sapi-voices=false` | Opt out of the Windows speech-voice tables when spoofing Windows. On by default (the voice set matches a real Chrome install); turn off only if a target reacts badly to the Windows voice list. |+| `--license-route=auto\|direct\|proxy` | How the Pro license and session calls leave the browser. `auto` (default): direct to cloakbrowser.dev first, and one retry through your `--proxy-server` if direct can't reach it. `direct`: never through the proxy. `proxy`: only through the proxy (needs `--proxy-server`). |+| `--license-through-proxy` | Older spelling of `--license-route=proxy`: route the Pro license/session calls through your `--proxy-server` instead of direct to cloakbrowser.dev. Still works; prefer `--license-route=proxy`. |+| `--fingerprint-transparent-proxy` | A stronger way of connecting through your `--proxy-server`, for sites and providers that block every proxy you try. Off by default; enable it alongside `--proxy-server`. |+| `--fingerprint-transparent-proxy-dns=<url>\|local` | **Linux and Windows.** DNS for `--fingerprint-transparent-proxy` mode. By default sites are resolved with Cloudflare's DNS over HTTPS, sent through your proxy. Pass your own DNS over HTTPS address, or `local` to resolve on your own machine as before. |+| `--fingerprint-portable-cookies` | Encrypt cookies with a machine-independent key so a copied profile keeps its logins across machines. Turn it on from the first launch — it changes how cookies are written, so a cookie is only portable if this was set when it was saved. || `--enable-blink-features=FakeShadowRoot` | Access closed shadow DOM elements |> **Note:** All stealth tests were verified with the default fingerprint config above. Changing these flags may affect detection results — test your configuration before using in production.@@ -793,7 +794,7 @@ browser = launch(args=[- [`basic.py`](examples/basic.py) — Launch and load a page- [`persistent_context.py`](examples/persistent_context.py) — Persistent profile with cookie/localStorage persistence- [`recaptcha_score.py`](examples/recaptcha_score.py) — Check your reCAPTCHA v3 score-- [`stealth_test.py`](examples/stealth_test.py) — Run against 6 detection sites+- [`stealth_test.py`](examples/stealth_test.py) — Run against 7 detection sites- [`fingerprint_scan_test.py`](examples/fingerprint_scan_test.py) — Test against fingerprint-scan.com and CreepJS**JavaScript** — see [`js/examples/`](js/examples/):@@ -847,15 +848,15 @@ browser = await launch_async(args=["--remote-debugging-port=9242"])## Platforms-| Platform | Free | Pro | Status |-|---|---|---|---|-| Linux x86_64 | Chromium 146 (58 patches) | Chromium 155 (87 patches) | ✅ |-| Linux arm64 (RPi, Graviton) | Chromium 146 (58 patches) | Chromium 155 (87 patches) | ✅ |-| macOS arm64 (Apple Silicon) | Chromium 145 (26 patches) | Chromium 155 (87 patches) | ✅ |-| macOS x86_64 (Intel) | Chromium 145 (26 patches) | Chromium 155 (87 patches) | ✅ |-| Windows x86_64 | Chromium 146 (58 patches) | Chromium 155 (87 patches) | ✅ |+| Platform | Binary | Status |+|---|---|---|+| Linux x86_64 | Chromium 155 (87 patches) | ✅ |+| Linux arm64 (RPi, Graviton) | Chromium 155 (87 patches) | ✅ |+| macOS arm64 (Apple Silicon) | Chromium 155 (87 patches) | ✅ |+| macOS x86_64 (Intel) | Chromium 155 (87 patches) | ✅ |+| Windows x86_64 | Chromium 155 (87 patches) | ✅ |-The wrapper auto-downloads the correct binary for your platform.+The wrapper auto-downloads the correct binary for your platform. Free and Pro keys get the same build; Pro raises the number of concurrent sessions.**macOS first launch:** The binary is ad-hoc signed. On first run, macOS Gatekeeper will block it. Right-click the app → **Open** → click **Open** in the dialog. This is only needed once.@@ -863,19 +864,23 @@ The wrapper auto-downloads the correct binary for your platform.Pre-built image on Docker Hub — no install, no setup.-> **Pro:** the image ships with the free binary. Set `CLOAKBROWSER_LICENSE_KEY` (e.g. `-e CLOAKBROWSER_LICENSE_KEY=cb_xxx`, or in Compose) and the latest binary downloads at runtime.+> **License key:** the image has no binary inside; the latest build downloads on the first launch with your key. Run with `-it` and the first launch asks for one, as in the quick test below (the key and binary live in the container, so `--rm` discards them). For scripts, servers and Compose, pass the key instead: `export CLOAKBROWSER_LICENSE_KEY=cb_xxx` on the host, then `-e CLOAKBROWSER_LICENSE_KEY` (as below), or set it in Compose. A free key takes one email: `cloakbrowser login` or [cloakbrowser.dev/free](https://cloakbrowser.dev/free).### Quick test```bash-docker run --rm cloakhq/cloakbrowser cloaktest+# Interactive: asks for a key (free by email, or paste yours)+docker run --rm -it cloakhq/cloakbrowser cloaktest++# With your key in the environment (scripts, CI)+docker run --rm -e CLOAKBROWSER_LICENSE_KEY cloakhq/cloakbrowser cloaktest```### Run a script```bash# Inline script-docker run --rm cloakhq/cloakbrowser python -c "+docker run --rm -e CLOAKBROWSER_LICENSE_KEY cloakhq/cloakbrowser python -c "from cloakbrowser import launchbrowser = launch()page = browser.new_page()@@ -885,10 +890,10 @@ browser.close()"# Mount your own script-docker run --rm -v ./my_script.py:/app/my_script.py cloakhq/cloakbrowser python my_script.py+docker run --rm -e CLOAKBROWSER_LICENSE_KEY -v ./my_script.py:/app/my_script.py cloakhq/cloakbrowser python my_script.py# With a proxy-docker run --rm cloakhq/cloakbrowser python -c "+docker run --rm -e CLOAKBROWSER_LICENSE_KEY cloakhq/cloakbrowser python -c "from cloakbrowser import launchbrowser = launch(proxy='http://user:pass@proxy:8080', geoip=True)page = browser.new_page()@@ -903,7 +908,7 @@ browser.close()Start a persistent stealth browser and connect to it remotely via Chrome DevTools Protocol:```bash-docker run -d --name cloak -p 127.0.0.1:9222:9222 cloakhq/cloakbrowser cloakserve+docker run -d --name cloak -e CLOAKBROWSER_LICENSE_KEY -p 127.0.0.1:9222:9222 cloakhq/cloakbrowser cloakserve```Then connect from your host machine:@@ -949,23 +954,23 @@ Pass extra flags to the browser:```bash# With proxy-docker run -d --name cloak -p 127.0.0.1:9222:9222 cloakhq/cloakbrowser \+docker run -d --name cloak -e CLOAKBROWSER_LICENSE_KEY -p 127.0.0.1:9222:9222 cloakhq/cloakbrowser \cloakserve --proxy-server=http://proxy:8080# Headed mode (renders to Xvfb inside container)-docker run -d --name cloak -p 127.0.0.1:9222:9222 cloakhq/cloakbrowser \+docker run -d --name cloak -e CLOAKBROWSER_LICENSE_KEY -p 127.0.0.1:9222:9222 cloakhq/cloakbrowser \cloakserve --headless=false# Reap disconnected per-seed browser processes after 5 minutes-docker run -d --name cloak -p 127.0.0.1:9222:9222 cloakhq/cloakbrowser \+docker run -d --name cloak -e CLOAKBROWSER_LICENSE_KEY -p 127.0.0.1:9222:9222 cloakhq/cloakbrowser \cloakserve --idle-timeout=300# Keep per-seed profiles (cookies, logins) across idle cleanup and container restarts-docker run -d --name cloak -p 127.0.0.1:9222:9222 -v ./cloak-profiles:/profiles cloakhq/cloakbrowser \+docker run -d --name cloak -e CLOAKBROWSER_LICENSE_KEY -p 127.0.0.1:9222:9222 -v ./cloak-profiles:/profiles cloakhq/cloakbrowser \cloakserve --idle-timeout=300 --data-dir=/profiles --keep-profiles# Per-job container: reap Chrome 60s after disconnect, exit (status 0) after 5 minutes with no connections-docker run --rm --name cloak -p 127.0.0.1:9222:9222 cloakhq/cloakbrowser \+docker run --rm --name cloak -e CLOAKBROWSER_LICENSE_KEY -p 127.0.0.1:9222:9222 cloakhq/cloakbrowser \cloakserve --idle-timeout=60 --exit-after-idle=300```@@ -987,6 +992,8 @@ services:image: cloakhq/cloakbrowsercommand: cloakserverestart: unless-stopped+ environment:+ - CLOAKBROWSER_LICENSE_KEY # passed through from the hostports:- "127.0.0.1:9222:9222"healthcheck:@@ -1020,7 +1027,7 @@ For a server that runs one job and goes away (e.g. a per-job container), set `--**Persistent profiles** — mount a volume to keep cookies and sessions across container restarts:```bash-docker run --rm -v ./my-profile:/profile cloakhq/cloakbrowser python -c "+docker run --rm -e CLOAKBROWSER_LICENSE_KEY -v ./my-profile:/profile cloakhq/cloakbrowser python -c "from cloakbrowser import launch_persistent_contextctx = launch_persistent_context('/profile')page = ctx.new_page()@@ -1199,7 +1206,7 @@ Preview availability is platform-specific. Preview always selects the newest buiTwo ways to go back to a working version:-**Pin the binary** (keep current wrapper, just use an older Chromium) — paid Pro key only. A free GitHub key cannot pin: it ignores the pin and always gets the latest build.+**Pin the binary** (keep current wrapper, just use an older Chromium) — paid Pro key only. A free key cannot pin: it ignores the pin and always gets the latest build.```pythonbrowser = launch(license_key="cb_xxxxxxxx", browser_version="154.0.8037.57.1")@@ -1229,7 +1236,6 @@ Use a local binary:```bashexport CLOAKBROWSER_BINARY_PATH=/path/to/your/chrome-export CLOAKBROWSER_VERSION=155.0.8059.39.2 # that binary's exact version```### macOS: "App is damaged" or Gatekeeper blocks launch@@ -1305,10 +1311,13 @@ Other tips for maximizing reCAPTCHA scores:A: CloakBrowser is a browser built on open-source Chromium. We do not condone illegal use. Automating systems without authorization, credential stuffing, and account creation abuse are expressly prohibited. See [BINARY-LICENSE.md](https://github.com/CloakHQ/CloakBrowser/blob/main/BINARY-LICENSE.md) for full terms.**Q: Is CloakBrowser free?**-A: Yes. The wrappers (Python, JS, .NET) are MIT and free forever. For the binary: the **latest build is free** with a GitHub sign-in at one concurrent session ([cloakbrowser.dev/free](https://cloakbrowser.dev/free)); **Pro** adds more concurrent sessions ([cloakbrowser.dev](https://cloakbrowser.dev)); and the older **v146** build stays free on [GitHub Releases](https://github.com/CloakHQ/cloakbrowser/releases). We refresh the free build from time to time as the project moves forward.+A: Yes. The wrappers (Python, JS, .NET) are MIT and free forever. For the binary: the **latest build is free** with your email at one concurrent session ([cloakbrowser.dev/free](https://cloakbrowser.dev/free)); **Pro** adds more concurrent sessions ([cloakbrowser.dev](https://cloakbrowser.dev)).**Q: Do I need a license key for the free version?**-A: For the latest build, a free key from a GitHub sign-in (`cloakbrowser login`, or [cloakbrowser.dev/free](https://cloakbrowser.dev/free)) gives you one concurrent session, and a paid key raises the limit. The older v146 build runs with no key.+A: Yes, a free one. The first launch in a terminal asks for it and gets it for you by email (or run `cloakbrowser login`, or visit [cloakbrowser.dev/free](https://cloakbrowser.dev/free)). It gives you one concurrent session; a paid key raises the limit.++**Q: Can I still use the old keyless v146 build?**+A: Yes, through the last wrapper release that runs without a key: `pip install "cloakbrowser<0.7"`, `npm install [email protected]`, or `dotnet add package CloakBrowser --version 0.6.5`, or the Docker image `cloakhq/cloakbrowser:0.6.5`. It downloads the old v146 build (v145 on macOS) from [GitHub Releases](https://github.com/CloakHQ/cloakbrowser/releases), with no key. It is no longer updated and ages fast as detection evolves, so the free key on the latest build is the better choice.**Q: Will detection sites eventually catch this?**A: Possibly. Bot detection is an arms race. Source-level patches are harder to detect than config-level patches, but not impossible. We actively monitor and update when detection evolves.@@ -1334,7 +1343,7 @@ The wrapper automatically verifies every binary download against a pinned Ed2551```bash# Verify GPG signature (binary release tag)gpg --keyserver keyserver.ubuntu.com --recv-keys C60C0DDC9D0DE2DD-git verify-tag chromium-v146.0.7680.177.5+git verify-tag chromium-v155.0.8059.39.2-pro# Verify GitHub binary attestation (Sigstore)gh attestation verify cloakbrowser-linux-x64.tar.gz --repo CloakHQ/cloakbrowser@@ -1349,10 +1358,7 @@ cosign verify \## License- **Wrapper code** (this repository) — MIT. See [LICENSE](https://github.com/CloakHQ/CloakBrowser/blob/main/LICENSE).-- **CloakBrowser binary** (compiled Chromium):- - **v146 and earlier** — free for personal and commercial use, no redistribution (OEM/SaaS license required to serve third parties).- - **v148 and later** — requires a license key: free with a GitHub sign-in (one concurrent session), or a paid [CloakBrowser Pro](https://cloakbrowser.dev) subscription.- - See [BINARY-LICENSE.md](https://github.com/CloakHQ/CloakBrowser/blob/main/BINARY-LICENSE.md) for full terms.+- **CloakBrowser binary** (compiled Chromium) — requires a license key: free with your email (one concurrent session), or a paid [CloakBrowser Pro](https://cloakbrowser.dev) subscription. Free for personal and commercial use, no redistribution (OEM/SaaS license required to serve third parties). See [BINARY-LICENSE.md](https://github.com/CloakHQ/CloakBrowser/blob/main/BINARY-LICENSE.md) for full terms.## Contributingdiff --git a/bin/docker-entrypoint.sh b/bin/docker-entrypoint.shindex feb1b55..9295cc2 100644--- a/bin/docker-entrypoint.sh+++ b/bin/docker-entrypoint.sh@@ -7,8 +7,10 @@# returning 502 forever. See CloakHQ/CloakBrowser#283.rm -f /tmp/.X99-lock /tmp/.X11-unix/X99-# Start Xvfb for headed mode (Turnstile, CAPTCHAs), then run user command-Xvfb :99 -screen 0 1920x1080x24 -nolisten tcp &+# Start Xvfb for headed mode (Turnstile, CAPTCHAs), then run user command.+# setsid: its own session, so Ctrl+C in `docker run -it` reaches only the user's+# command, not the X server (which otherwise dies printing "XIO: fatal IO error").+setsid Xvfb :99 -screen 0 1920x1080x24 -nolisten tcp &# Wait for the X server to actually accept connections before starting the WM.# A blind `sleep 1` races under a CPU-starved start: openbox can come up before@@ -22,7 +24,7 @@ done# Window manager so headed --start-maximized is honored (bare Xvfb has no WM;# without one the flag is a silent no-op and the window stays un-maximized).-DISPLAY=:99 openbox &+DISPLAY=:99 setsid openbox &# Opt-in: fetch the Widevine CDM so persistent contexts present as a real# Chrome (a DRM/EME probe is used by some bot detectors). Off by default — only@@ -40,7 +42,7 @@ case "${_fetch_widevine,,}" in# ~/.cloakbrowser/WidevineCdm). The wrapper's auto-detection# (cloakbrowser/widevine.py, js/src/widevine.ts) falls back to this path# after the per-binary dir, so the CDM is discoverable by ANY process (CMD- # or `docker exec`) and ANY binary (free or Pro, any version) with no env+ # or `docker exec`) and ANY binary version with no env# var. Best-effort: a failure must never block launch.python /usr/local/bin/fetch-widevine.py --quiet \|| echo "[cloakbrowser] Widevine fetch failed; continuing without it" >&2diff --git a/cloakbrowser/__init__.py b/cloakbrowser/__init__.pyindex bb8febf..d1c7ca4 100644--- a/cloakbrowser/__init__.py+++ b/cloakbrowser/__init__.py@@ -12,8 +12,8 @@ Usage:"""from .browser import launch, launch_async, launch_context, launch_context_async, launch_persistent_context, launch_persistent_context_async, ProxySettings, build_args, maybe_resolve_geoip-from .config import CHROMIUM_VERSION, get_default_stealth_args-from .download import binary_info, check_for_update, clear_cache, ensure_binary+from .config import get_default_stealth_args+from .download import binary_info, clear_cache, ensure_binaryfrom .license import CloakBrowserLicenseError, LicenseInfo, validate_licensefrom ._version import __version__@@ -39,8 +39,6 @@ __all__ = ["ensure_binary","clear_cache","binary_info",- "check_for_update",- "CHROMIUM_VERSION","get_default_stealth_args","build_args","maybe_resolve_geoip",diff --git a/cloakbrowser/__main__.py b/cloakbrowser/__main__.pyindex 7f2c0c9..7d60972 100644--- a/cloakbrowser/__main__.py+++ b/cloakbrowser/__main__.py@@ -40,10 +40,7 @@ ARROW = _console_glyph("→", "->")DASH = _console_glyph("—", "-")UPGRADE_HINT = f"For more than one concurrent session {ARROW} https://cloakbrowser.dev"-FREE_LATEST_HINT = (- f"Get the latest binary free {ARROW} run 'cloakbrowser login' "- "or https://cloakbrowser.dev/free"-)+NO_KEY_HINT = f"Get a free key {ARROW} run 'cloakbrowser login'"def _setup_logging() -> None:@@ -120,12 +117,8 @@ def _resolve_license() -> tuple[dict, bool]:from .license import resolve_license_key, validate_licensekey = resolve_license_key(None)- # ensure_binary disables Pro routing when a custom download URL is set, so the- # diagnostic must report free too (matches download.py).- if os.environ.get("CLOAKBROWSER_DOWNLOAD_URL"):- key = Noneif not key:- return {"tier": "free"}, False+ return {"tier": "none"}, Falsetry:lic = validate_license(key)except Exception as exc:@@ -140,13 +133,10 @@ def _resolve_license() -> tuple[dict, bool]:def _effective_binary(entitled_pro: bool, quick: bool = False) -> dict:"""Describe the binary ensure_binary would actually launch (no download).- Mirrors ensure_binary's resolution (override > version pin > license tier).- Unlike binary_info(), a Pro binary on disk is only reported when the license- entitles Pro — so a keyless run correctly shows the free binary even if a- Pro binary is cached.+ Mirrors ensure_binary's resolution (override > version pin > license).+ Without a valid key nothing launches, so only the cached build is reported."""from .config import (- CHROMIUM_VERSION,_version_newer,get_binary_dir,get_binary_path,@@ -163,7 +153,6 @@ def _effective_binary(entitled_pro: bool, quick: bool = False) -> dict:"latest_version": None,"pinned": False,"tier": "override",- "bundled_version": CHROMIUM_VERSION,"path": override,"installed": os.path.isfile(override),"cache_dir": None,@@ -195,9 +184,7 @@ def _effective_binary(entitled_pro: bool, quick: bool = False) -> dict:elif entitled_pro:# Mirror ensure_binary: Preview/Stable resolution picks what the next# launch will run, while AUTO_UPDATE=false keeps an installed channel build.- installed_version = get_effective_version(- pro=True, release_channel=requested_channel- )+ installed_version = get_effective_version(requested_channel)auto_update = os.environ.get("CLOAKBROWSER_AUTO_UPDATE", "true").lower()updates_enabled = auto_update != "false"if installed_version and not updates_enabled:@@ -209,10 +196,10 @@ def _effective_binary(entitled_pro: bool, quick: bool = False) -> dict:else:version = installed_version or latest_versionelse:- version = get_effective_version()+ version = get_effective_version(requested_channel)installed_version = version- path = get_binary_path(version, pro=entitled_pro) if version else None+ path = get_binary_path(version) if version else Nonereturn {"version": version,"latest_version": latest_version,@@ -221,11 +208,10 @@ def _effective_binary(entitled_pro: bool, quick: bool = False) -> dict:"channel_fallback": channel_fallback,"installed_version": installed_version,"pinned": bool(requested),- "tier": "pro" if entitled_pro else "free",- "bundled_version": CHROMIUM_VERSION,+ "tier": "pro" if entitled_pro else "none","path": str(path) if path else None,"installed": bool(path) and path.exists(),- "cache_dir": str(get_binary_dir(version, pro=entitled_pro)) if version else None,+ "cache_dir": str(get_binary_dir(version)) if version else None,"override": None,}@@ -500,14 +486,11 @@ def _print_diagnostics(diag: dict) -> None:lic = diag["license"]tier = lic["tier"]if tier == "free" and lic.get("valid"):- # Validated free-tier key (GitHub login): the latest binary, 1 session.print("License: Free (latest binary, 1 concurrent session)")print(f" {UPGRADE_HINT}")- elif tier == "free":- # Keyless: running the older free binary — invite the free-latest login.- print("License: Free (no key)")- print(f" {FREE_LATEST_HINT}")- print(f" {UPGRADE_HINT}")+ elif tier == "none":+ print("License: none (a launch needs a key)")+ print(f" {NO_KEY_HINT}")elif "error" in lic:print(f"License: {tier} ({lic['error']})")else:@@ -547,27 +530,19 @@ def cmd_info(args: argparse.Namespace) -> None:def cmd_update(args: argparse.Namespace) -> None:- from .download import check_for_pro_update, check_for_update-- logger = logging.getLogger("cloakbrowser")- logger.info("Checking for updates...")+ from .download import check_for_pro_update+ from .license import resolve_license_key- # A valid Pro license updates the Pro binary; everyone else updates free.- _, entitled_pro = _resolve_license()- if entitled_pro:- from .license import resolve_license_key-- key = resolve_license_key(None)- if not key:- raise RuntimeError("Pro license key disappeared during update")- new_version = check_for_pro_update(key)- label = "Pro Chromium"- else:- new_version = check_for_update()- label = "Chromium"+ _, entitled = _resolve_license()+ key = resolve_license_key(None)+ if not entitled or not key:+ print(f"No valid license key. {NO_KEY_HINT}", file=sys.stderr)+ sys.exit(1)+ logging.getLogger("cloakbrowser").info("Checking for updates...")+ new_version = check_for_pro_update(key)if new_version:- print(f"Updated to {label} {new_version}")+ print(f"Updated to Chromium {new_version}")else:print("Already up to date.")@@ -583,61 +558,27 @@ def cmd_clear_cache(args: argparse.Namespace) -> None:print("Cache cleared.")-FREE_LOGIN_URL = "https://cloakbrowser.dev/api/license/free/github/start"---def _save_license_key(key: str) -> None:- """Persist a validated key to ~/.cloakbrowser/license.key (0600)."""- from .config import get_cache_dir-- cache_dir = get_cache_dir()- cache_dir.mkdir(parents=True, exist_ok=True)- key_file = cache_dir / "license.key"- key_file.write_text(key.strip() + "\n")- try:- key_file.chmod(0o600)- except OSError:- pass---def _prompt_free_github_login() -> str:- """Open the GitHub free-key page and read back the emailed key."""- import webbrowser-- print(f"Opening GitHub sign-in: {FREE_LOGIN_URL}")- try:- webbrowser.open(FREE_LOGIN_URL)- except Exception:- pass- print("If your browser did not open, visit the URL above and authorize with GitHub.")- print("We'll email your free CloakBrowser key to your GitHub email.")- try:- return input("Paste the key from that email here: ").strip()- except EOFError:- return ""--def cmd_login(args: argparse.Namespace) -> None:- """Activate any key. `login <key>` saves a pasted key; bare `login` prompts- to paste a key or press ENTER to get a free key via GitHub."""- from .license import validate_license+ """Activate any key. `login <key>` saves a pasted key; bare `login` shows the+ same menu as a no-key launch: get a free key by email, or paste one."""+ from .download import can_prompt, prompt_license_key+ from .license import save_license_key, validate_licensekey = (getattr(args, "key", None) or "").strip()if not key:- if not sys.stdin.isatty():+ # The menu goes to stderr: both ends must be a terminal, or the prompt+ # lands somewhere invisible (`login 2>log`) and waits forever.+ if not can_prompt():print("Usage: cloakbrowser login <key> (or run it interactively for a free key).",file=sys.stderr,)sys.exit(2)try:- entered = input(- "Paste your license key, or press ENTER to get a free key via GitHub: "- ).strip()+ key = prompt_license_key()except EOFError:- entered = ""- key = entered or _prompt_free_github_login()+ key = ""if not key:print("No key entered. Nothing saved.", file=sys.stderr)@@ -654,7 +595,11 @@ def cmd_login(args: argparse.Namespace) -> None:print("That license key is invalid or expired. Nothing was saved.", file=sys.stderr)sys.exit(1)- _save_license_key(key)+ try:+ save_license_key(key)+ except ValueError:+ print("That is not a CloakBrowser license key (they start with cb_). Nothing was saved.", file=sys.stderr)+ sys.exit(1)if info.plan == "free":print("Saved. Free tier active: latest binary, 1 concurrent session (one browser at a time).")print("Need to run more at once? See the plans at https://cloakbrowser.dev")@@ -663,9 +608,11 @@ def cmd_login(args: argparse.Namespace) -> None:def cmd_logout(args: argparse.Namespace) -> None:- """Remove the saved license key (revert to the free v146 binary)."""+ """Remove the saved license key."""from .config import get_cache_dir+ # A pending claim code would otherwise hand the key back on the next launch.+ (get_cache_dir() / ".free_claim").unlink(missing_ok=True)key_file = get_cache_dir() / "license.key"if key_file.exists():try:@@ -673,7 +620,7 @@ def cmd_logout(args: argparse.Namespace) -> None:except OSError as e:print(f"Could not remove {key_file}: {e}", file=sys.stderr)sys.exit(1)- print("Logged out. Removed the saved key; launches revert to the free binary.")+ print("Logged out. Removed the saved key; launches need a key again.")else:print("No saved license key found.")@@ -711,12 +658,12 @@ def main() -> None:sub.add_parser("clear-cache", help="Remove all cached binaries")login_p = sub.add_parser(- "login", help="Save a license key (or get a free key via GitHub)"+ "login", help="Save a license key (or get a free key by email)")login_p.add_argument("key", nargs="?", help="License key to save. Omit to enter it interactively.")- sub.add_parser("logout", help="Remove the saved license key (revert to free binary)")+ sub.add_parser("logout", help="Remove the saved license key")args = parser.parse_args()if not args.command:diff --git a/cloakbrowser/browser.py b/cloakbrowser/browser.pyindex 0926976..3f2dc3e 100644--- a/cloakbrowser/browser.py+++ b/cloakbrowser/browser.py@@ -23,11 +23,7 @@ from typing import Any, Literal, TypedDictfrom urllib.parse import quote, unquote, urlparse, urlunparsefrom .config import (- DEFAULT_VIEWPORT,IGNORE_DEFAULT_ARGS,- binary_supports_headless_no_viewport,- binary_supports_http_proxy_inline_auth,- binary_supports_maximized_window,get_default_stealth_args,persistent_seed_args,)@@ -217,8 +213,7 @@ def _default_no_viewport(browser: Any) -> None:``outerWidth < innerWidth`` — a physically impossible window (bot tell). We wrapthe two factory methods so pages track the real OS window instead. ``setdefault``only: an explicit ``viewport`` or ``no_viewport`` from the caller is never- overridden (Playwright rejects passing both). Applied for headed launches only.- Composes under humanize's ``patch_browser`` (apply this first).+ overridden (Playwright rejects passing both). Composes under humanize's ``patch_browser`` (apply this first)."""orig_new_context = browser.new_contextorig_new_page = browser.new_page@@ -256,22 +251,14 @@ def _default_no_viewport_async(browser: Any) -> None:browser.new_page = _patched_new_page-def _resolve_context_viewport(- viewport: Any, headless: bool, headless_no_viewport: bool = False-) -> dict[str, Any]:+def _resolve_context_viewport(viewport: Any) -> dict[str, Any]:"""Return the viewport kwarg for a context.- Headed: no emulated viewport so the page tracks the real window. Headless on a- newer binary (``headless_no_viewport``): also ``no_viewport``, since it reports- coherent dimensions without emulation. Headless on an older binary: a fixed- ``DEFAULT_VIEWPORT`` keeps dimensions coherent and deterministic. Explicit- ``viewport`` / ``None`` honored.+ Default: no emulated viewport. Headed, the page tracks the real window;+ headless, the binary reports coherent dimensions itself. An explicit+ ``viewport`` is honored; ``None`` also means no viewport."""- if viewport is _VIEWPORT_UNSET:- if headless and not headless_no_viewport:- return {"viewport": DEFAULT_VIEWPORT}- return {"no_viewport": True}- if viewport is None:+ if viewport is _VIEWPORT_UNSET or viewport is None:return {"no_viewport": True}return {"viewport": viewport}@@ -376,11 +363,11 @@ def launch(binary_path = ensure_binary(license_key=license_key, browser_version=browser_version, release_channel=release_channel)timezone, locale, exit_ip = maybe_resolve_geoip(geoip, proxy, timezone, locale, args)- proxy_kwargs, proxy_extra_args = _resolve_proxy_config(proxy, browser_version, license_key, release_channel)+ proxy_kwargs, proxy_extra_args = _resolve_proxy_config(proxy)args = _resolve_webrtc_args(args, proxy)args = _append_webrtc_exit_ip(args, exit_ip)- chrome_args = build_args(stealth_args, (args or []) + proxy_extra_args, timezone=timezone, locale=locale, headless=headless, extension_paths=extension_paths, start_maximized=binary_supports_maximized_window(license_key, browser_version, release_channel) and not _suppress_maximize)+ chrome_args = build_args(stealth_args, (args or []) + proxy_extra_args, timezone=timezone, locale=locale, headless=headless, extension_paths=extension_paths, start_maximized=not _suppress_maximize)_maybe_warn_windows_fonts(chrome_args)logger.debug("Launching stealth Chromium (headless=%s, args=%d)", headless, len(chrome_args))@@ -437,12 +424,10 @@ def launch(if proxy_extra_args:browser._impl_obj.on("context", _warn_on_request_client_use)- # Default new_page()/new_context() to no_viewport for headed (page tracks the- # real window) and for headless on binaries that report coherent dimensions- # natively; older headless binaries keep Playwright's default viewport. Apply- # before humanize so the wraps compose.- if not headless or binary_supports_headless_no_viewport(license_key, browser_version, release_channel):- _default_no_viewport(browser)+ # Default new_page()/new_context() to no_viewport: headed, the page tracks the+ # real window; headless, the binary reports coherent dimensions natively.+ # Apply before humanize so the wraps compose.+ _default_no_viewport(browser)# Human-like behavioral patchingif humanize:@@ -512,10 +497,10 @@ async def launch_async( # noqa: C901# they don't freeze the caller's event loop.binary_path = await asyncio.to_thread(ensure_binary, license_key=license_key, browser_version=browser_version, release_channel=release_channel)timezone, locale, exit_ip = await asyncio.to_thread(maybe_resolve_geoip, geoip, proxy, timezone, locale, args)- proxy_kwargs, proxy_extra_args = _resolve_proxy_config(proxy, browser_version, license_key, release_channel)+ proxy_kwargs, proxy_extra_args = _resolve_proxy_config(proxy)args = await asyncio.to_thread(_resolve_webrtc_args, args, proxy)args = _append_webrtc_exit_ip(args, exit_ip)- chrome_args = build_args(stealth_args, (args or []) + proxy_extra_args, timezone=timezone, locale=locale, headless=headless, extension_paths=extension_paths, start_maximized=binary_supports_maximized_window(license_key, browser_version, release_channel) and not _suppress_maximize)+ chrome_args = build_args(stealth_args, (args or []) + proxy_extra_args, timezone=timezone, locale=locale, headless=headless, extension_paths=extension_paths, start_maximized=not _suppress_maximize)_maybe_warn_windows_fonts(chrome_args)logger.debug("Launching stealth Chromium async (headless=%s, args=%d)", headless, len(chrome_args))@@ -569,10 +554,8 @@ async def launch_async( # noqa: C901if proxy_extra_args:browser._impl_obj.on("context", _warn_on_request_client_use)- # Default new_page()/new_context() to no_viewport for headed and qualifying- # headless binaries (see launch()).- if not headless or binary_supports_headless_no_viewport(license_key, browser_version, release_channel):- _default_no_viewport_async(browser)+ # Default new_page()/new_context() to no_viewport (see launch()).+ _default_no_viewport_async(browser)# Human-like behavioral patching (async variant)if humanize:@@ -653,11 +636,11 @@ def launch_persistent_context(binary_path = ensure_binary(license_key=license_key, browser_version=browser_version, release_channel=release_channel)timezone, locale, exit_ip = maybe_resolve_geoip(geoip, proxy, timezone, locale, args)- proxy_kwargs, proxy_extra_args = _resolve_proxy_config(proxy, browser_version, license_key, release_channel)+ proxy_kwargs, proxy_extra_args = _resolve_proxy_config(proxy)args = _resolve_webrtc_args(args, proxy)args = _append_webrtc_exit_ip(args, exit_ip)args = persistent_seed_args(user_data_dir, stealth_args, args)- chrome_args = build_args(stealth_args, (args or []) + proxy_extra_args, timezone=timezone, locale=locale, headless=headless, extension_paths=extension_paths, start_maximized=binary_supports_maximized_window(license_key, browser_version, release_channel) and viewport is _VIEWPORT_UNSET and "viewport" not in kwargs and "no_viewport" not in kwargs)+ chrome_args = build_args(stealth_args, (args or []) + proxy_extra_args, timezone=timezone, locale=locale, headless=headless, extension_paths=extension_paths, start_maximized=viewport is _VIEWPORT_UNSET and "viewport" not in kwargs and "no_viewport" not in kwargs)_maybe_warn_windows_fonts(chrome_args)logger.debug(@@ -672,9 +655,7 @@ def launch_persistent_context(if user_agent:context_kwargs["user_agent"] = user_agentcontext_kwargs.update(- _resolve_context_viewport(- viewport, headless, binary_supports_headless_no_viewport(license_key, browser_version, release_channel)- )+ _resolve_context_viewport(viewport))if color_scheme:context_kwargs["color_scheme"] = color_scheme@@ -825,11 +806,11 @@ async def launch_persistent_context_async(# Blocking network calls run in a thread (see launch_async).binary_path = await asyncio.to_thread(ensure_binary, license_key=license_key, browser_version=browser_version, release_channel=release_channel)timezone, locale, exit_ip = await asyncio.to_thread(maybe_resolve_geoip, geoip, proxy, timezone, locale, args)- proxy_kwargs, proxy_extra_args = _resolve_proxy_config(proxy, browser_version, license_key, release_channel)+ proxy_kwargs, proxy_extra_args = _resolve_proxy_config(proxy)args = await asyncio.to_thread(_resolve_webrtc_args, args, proxy)args = _append_webrtc_exit_ip(args, exit_ip)args = persistent_seed_args(user_data_dir, stealth_args, args)- chrome_args = build_args(stealth_args, (args or []) + proxy_extra_args, timezone=timezone, locale=locale, headless=headless, extension_paths=extension_paths, start_maximized=binary_supports_maximized_window(license_key, browser_version, release_channel) and viewport is _VIEWPORT_UNSET and "viewport" not in kwargs and "no_viewport" not in kwargs)+ chrome_args = build_args(stealth_args, (args or []) + proxy_extra_args, timezone=timezone, locale=locale, headless=headless, extension_paths=extension_paths, start_maximized=viewport is _VIEWPORT_UNSET and "viewport" not in kwargs and "no_viewport" not in kwargs)_maybe_warn_windows_fonts(chrome_args)logger.debug(@@ -844,9 +825,7 @@ async def launch_persistent_context_async(if user_agent:context_kwargs["user_agent"] = user_agentcontext_kwargs.update(- _resolve_context_viewport(- viewport, headless, binary_supports_headless_no_viewport(license_key, browser_version, release_channel)- )+ _resolve_context_viewport(viewport))if color_scheme:context_kwargs["color_scheme"] = color_scheme@@ -994,9 +973,7 @@ def launch_context(if user_agent:context_kwargs["user_agent"] = user_agentcontext_kwargs.update(- _resolve_context_viewport(- viewport, headless, binary_supports_headless_no_viewport(license_key, browser_version, release_channel)- )+ _resolve_context_viewport(viewport))if color_scheme:context_kwargs["color_scheme"] = color_scheme@@ -1129,9 +1106,7 @@ async def launch_context_async(if user_agent:context_kwargs["user_agent"] = user_agentcontext_kwargs.update(- _resolve_context_viewport(- viewport, headless, binary_supports_headless_no_viewport(license_key, browser_version, release_channel)- )+ _resolve_context_viewport(viewport))if color_scheme:context_kwargs["color_scheme"] = color_scheme@@ -1490,9 +1465,7 @@ def build_args(# Open maximized (real Windows Chrome overwhelmingly runs maximized) so the# window fills the spoofed screen. Skipped if the caller already chose a- # window geometry. Gated to binaries where this stays coherent (see- # binary_supports_maximized_window) — below the gate it would create- # outerWidth < innerWidth.+ # window geometry.if start_maximized and not any(k in seen for k in ("--start-maximized", "--window-size", "--window-position")):@@ -1660,40 +1633,6 @@ def _maybe_warn_windows_fonts(chrome_args: list[str]) -> None:pass-def _parse_proxy_url(proxy: str) -> dict[str, Any]:- """Parse HTTP(S) proxy URL, extracting credentials into separate Playwright fields.-- Handles: http://user:pass@host:port -> {server: "http://host:port", username: "user", password: "pass"}- Also handles: no credentials, URL-encoded special chars, missing port,- and bare proxy strings without a scheme (e.g. 'user:pass@host:port' -> treated as http).-- SOCKS5 URLs are NOT handled here — they take a dedicated path via- ``_normalize_socks_string_url`` in ``_resolve_proxy_config``.- """- # Bare format: "user:pass@host:port" — urlparse needs a scheme to extract credentials.- normalized = proxy- if "@" in proxy and "://" not in proxy:- normalized = f"http://{proxy}"-- parsed = urlparse(normalized)-- if not parsed.username:- return {"server": proxy} # no creds — return original unchanged-- # Rebuild server URL without credentials- netloc = parsed.hostname or ""- if parsed.port:- netloc += f":{parsed.port}"-- server = urlunparse((parsed.scheme, netloc, parsed.path, "", "", ""))-- result: dict[str, Any] = {"server": server}- result["username"] = unquote(parsed.username)- if parsed.password:- result["password"] = unquote(parsed.password)-- return result-def _has_credentials(proxy: str | ProxySettings) -> bool:"""Check if the proxy has inline or dict-level credentials."""@@ -1803,17 +1742,12 @@ def _warn_on_request_client_use(impl_context: Any) -> None:def _resolve_proxy_config(proxy: str | ProxySettings | None,- browser_version: str | None = None,- license_key: str | None = None,- release_channel: str | None = None,) -> tuple[dict[str, Any], list[str]]:"""Resolve proxy into Playwright kwargs and Chrome args.- Proxies with credentials (SOCKS5 always; HTTP/HTTPS only on binaries that- support inline proxy auth) are passed via Chrome's --proxy-server flag with- inline credentials, bypassing Playwright's CDP auth interceptor which breaks- on some proxies and Google domains (#182). HTTP/HTTPS creds on older binaries- fall back to Playwright's proxy dict.+ Proxies with credentials (SOCKS5 and HTTP/HTTPS) are passed via Chrome's+ --proxy-server flag with inline credentials, bypassing Playwright's CDP auth+ interceptor which breaks on some proxies and Google domains (#182).Returns:(proxy_kwargs, extra_chrome_args) — one or both will be empty.@@ -1835,11 +1769,9 @@ def _resolve_proxy_config(# passwords at '=' and other special chars (#157).return {}, [f"--proxy-server={_normalize_socks_string_url(proxy)}"]- # HTTP/HTTPS with credentials, only on binaries that ship inline proxy auth:- # use Chrome's native proxy authentication path instead of Playwright's CDP- # auth interceptor (#182). Older binaries (free macOS/linux-arm64) can't parse- # inline credentials, so they fall through to the Playwright proxy dict below.- if _has_credentials(proxy) and binary_supports_http_proxy_inline_auth(license_key, browser_version, release_channel):+ # HTTP/HTTPS with credentials: use Chrome's native proxy authentication path+ # instead of Playwright's CDP auth interceptor (#182).+ if _has_credentials(proxy):if isinstance(proxy, dict):url = _reconstruct_http_url(proxy)extra_args = [f"--proxy-server={url}"]@@ -1852,4 +1784,4 @@ def _resolve_proxy_config(# HTTP/HTTPS without credentials: use Playwright's proxy dictif isinstance(proxy, dict):return {"proxy": proxy}, []- return {"proxy": _parse_proxy_url(proxy)}, []+ return {"proxy": {"server": proxy}}, []diff --git a/cloakbrowser/config.py b/cloakbrowser/config.pyindex 097aaec..c0616b2 100644--- a/cloakbrowser/config.py+++ b/cloakbrowser/config.py@@ -14,22 +14,6 @@ from pathlib import Pathlogger = logging.getLogger("cloakbrowser")-# ----------------------------------------------------------------------------# Chromium version shipped with this release.-# Different platforms may ship different versions during transition periods.-# CHROMIUM_VERSION is the latest across all platforms (for display/reference).-# Use get_chromium_version() for the current platform's actual version.-# ----------------------------------------------------------------------------CHROMIUM_VERSION = "146.0.7680.177.5"--PLATFORM_CHROMIUM_VERSIONS: dict[str, str] = {- "linux-x64": "146.0.7680.177.5",- "linux-arm64": "146.0.7680.177.3",- "darwin-arm64": "145.0.7632.109.2",- "darwin-x64": "145.0.7632.109.2",- "windows-x64": "146.0.7680.177.5",-}-# ---------------------------------------------------------------------------# Ed25519 public keys for verifying downloaded binaries.#@@ -177,15 +161,6 @@ def get_default_stealth_args() -> list[str]:return base + ["--fingerprint-platform=windows"]-# ----------------------------------------------------------------------------# Default viewport — used for HEADLESS only (headed launches use no_viewport so-# the page tracks the real window). Headless has no window chrome, so a fixed-# viewport stays coherent (outer == inner) and gives deterministic dimensions.-# Models a maximized Chrome on 1080p Windows: screen=1920x1080,-# innerHeight=947 (minus ~85px Chrome UI: tabs + address bar + bookmarks).-# ----------------------------------------------------------------------------DEFAULT_VIEWPORT = {"width": 1920, "height": 947}-# ---------------------------------------------------------------------------# Platform detection# ---------------------------------------------------------------------------@@ -198,9 +173,6 @@ SUPPORTED_PLATFORMS: dict[tuple[str, str], str] = {("Windows", "x86_64"): "windows-x64",}-# Platforms with pre-built binaries available for download (derived from version map).-AVAILABLE_PLATFORMS: set[str] = set(PLATFORM_CHROMIUM_VERSIONS.keys())-_VERSION_PIN_RE = re.compile(r"^[0-9]+(?:\.[0-9]+){3,4}$")@@ -236,12 +208,6 @@ def normalize_requested_version(version: str | None = None) -> str | None:return normalized-def get_chromium_version() -> str:- """Return the Chromium version for the current platform."""- tag = get_platform_tag()- return PLATFORM_CHROMIUM_VERSIONS.get(tag, CHROMIUM_VERSION)--def get_platform_tag() -> str:"""Return the platform tag for binary download (e.g. 'linux-x64', 'darwin-arm64')."""system = platform.system()@@ -270,16 +236,14 @@ def get_cache_dir() -> Path:return Path.home() / ".cloakbrowser"-def get_binary_dir(version: str | None = None, pro: bool = False) -> Path:- """Return the directory for a Chromium version binary."""- v = version or get_chromium_version()- suffix = "-pro" if pro else ""- return get_cache_dir() / f"chromium-{v}{suffix}"+def get_binary_dir(version: str) -> Path:+ """Return the cache directory for a Chromium build."""+ return get_cache_dir() / f"chromium-{version}-pro"-def get_binary_path(version: str | None = None, pro: bool = False) -> Path:+def get_binary_path(version: str) -> Path:"""Return the expected path to the chrome executable."""- binary_dir = get_binary_dir(version, pro=pro)+ binary_dir = get_binary_dir(version)if platform.system() == "Darwin":# macOS: Chromium.app bundle@@ -291,75 +255,28 @@ def get_binary_path(version: str | None = None, pro: bool = False) -> Path:return binary_dir / "chrome"-def check_platform_available() -> None:- """Raise a clear error if no pre-built binary exists for this platform.-- Skipped when CLOAKBROWSER_BINARY_PATH is set (user has their own build).- """- if get_local_binary_override():- return-- tag = get_platform_tag() # raises if platform unsupported entirely- if tag not in AVAILABLE_PLATFORMS:- available = ", ".join(sorted(AVAILABLE_PLATFORMS))- import sys-- sys.exit(- f"\n\033[1mCloakBrowser\033[0m — Pre-built binaries are currently only available for: {available}.\n\n"- f"To use CloakBrowser now, set CLOAKBROWSER_BINARY_PATH to a local Chromium binary."- )---def get_effective_version(- pro: bool = False, release_channel: str | None = None-) -> str | None:- """Return the best available version: auto-updated if available, else platform default.-- Reads a platform-scoped marker file from the cache directory.- Returns the platform's hardcoded version if no update has been downloaded.+def get_effective_version(release_channel: str | None = None) -> str | None:+ """Return the cached build the channel's marker names, or None.- When ``pro=True``, reads from the Pro-specific marker and returns ``None`` when- no cached Pro binary matches it. A valid Pro license must NEVER fall back to the- free binary, so there is deliberately no free-version fallback here — callers- treat ``None`` as "resolve the latest Pro version from the server" instead.+ None means nothing usable is cached: callers resolve the latest build from+ the server instead."""- base = get_chromium_version()- cache = get_cache_dir()-- if pro:- channel = normalize_release_channel(release_channel)- marker_prefix = (- "latest_pro_version_preview"- if channel == "preview"- else "latest_pro_version"- )- marker = cache / f"{marker_prefix}_{get_platform_tag()}"- if marker.exists():- try:- version = marker.read_text().strip()- if version:- binary = get_binary_path(version, pro=True)- # Match launch's _pro_binary_ready (exists AND executable) so- # `info` never reports a build that launch would reject.- if binary.exists() and os.access(binary, os.X_OK):- return version- except (ValueError, OSError):- pass+ channel = normalize_release_channel(release_channel)+ marker_prefix = (+ "latest_pro_version_preview" if channel == "preview" else "latest_pro_version"+ )+ marker = get_cache_dir() / f"{marker_prefix}_{get_platform_tag()}"+ try:+ version = marker.read_text().strip()+ except OSError:return None-- # Free tier: try platform-scoped marker first, fall back to legacy marker- for name in (f"latest_version_{get_platform_tag()}", "latest_version"):- marker = cache / name- if marker.exists():- try:- version = marker.read_text().strip()- if version and _version_newer(version, base):- binary = get_binary_path(version)- if binary.exists():- return version- except (ValueError, OSError):- pass- return base+ if version:+ binary = get_binary_path(version)+ # Match launch's _pro_binary_ready (exists AND executable) so+ # `info` never reports a build that launch would reject.+ if binary.exists() and os.access(binary, os.X_OK):+ return version+ return Nonedef _version_tuple(v: str) -> tuple[int, ...]:@@ -375,14 +292,7 @@ def _version_newer(a: str, b: str) -> bool:# ---------------------------------------------------------------------------# Download URL# ----------------------------------------------------------------------------DOWNLOAD_BASE_URL = os.environ.get(- "CLOAKBROWSER_DOWNLOAD_URL",- "https://cloakbrowser.dev",-)--GITHUB_API_URL = "https://api.github.com/repos/CloakHQ/cloakbrowser/releases"--GITHUB_DOWNLOAD_BASE_URL = "https://github.com/CloakHQ/cloakbrowser/releases/download"+DOWNLOAD_BASE_URL = "https://cloakbrowser.dev"def get_archive_ext() -> str:@@ -396,18 +306,6 @@ def get_archive_name(tag: str | None = None) -> str:return f"cloakbrowser-{t}{get_archive_ext()}"-def get_download_url(version: str | None = None) -> str:- """Return the full download URL for the current platform's binary archive."""- v = version or get_chromium_version()- return f"{DOWNLOAD_BASE_URL}/chromium-v{v}/{get_archive_name()}"---def get_fallback_download_url(version: str | None = None) -> str:- """Return the GitHub Releases fallback URL for the binary archive."""- v = version or get_chromium_version()- return f"{GITHUB_DOWNLOAD_BASE_URL}/chromium-v{v}/{get_archive_name()}"--# ---------------------------------------------------------------------------# Local binary override (skip download, use your own build)# ---------------------------------------------------------------------------@@ -417,137 +315,3 @@ def get_local_binary_override() -> str | None:Set CLOAKBROWSER_BINARY_PATH to use a locally built Chromium instead of downloading."""return os.environ.get("CLOAKBROWSER_BINARY_PATH")---# ----------------------------------------------------------------------------# Headless viewport handling by binary version-# ----------------------------------------------------------------------------# First Chromium build that reports coherent headless dimensions without an-# emulated viewport. On these binaries the wrapper launches headless with-# no_viewport; older binaries need a fixed DEFAULT_VIEWPORT to stay coherent.-# None => not shipped yet; feature off, behavior byte-identical to today.-# TODO: set to the chromium version string that first ships it.-HEADLESS_NO_VIEWPORT_MIN_VERSION: str | None = "148.0.7778.215.4"---def binary_supports_headless_no_viewport(- license_key: str | None = None,- browser_version: str | None = None,- release_channel: str | None = None,-) -> bool:- """Whether headless can launch with ``no_viewport`` on the resolved binary.-- Only binaries at or above ``HEADLESS_NO_VIEWPORT_MIN_VERSION`` qualify; older- ones keep ``DEFAULT_VIEWPORT``. A local override binary- (``CLOAKBROWSER_BINARY_PATH``) is unknown-version, so stay on the safe path.- """- if HEADLESS_NO_VIEWPORT_MIN_VERSION is None:- return False- # A declared version (browser_version arg OR CLOAKBROWSER_VERSION env) wins even- # under a local override — the caller is asserting the version (also how internal- # builds opt in). Only an override with no declared version stays on the safe path.- try:- declared = normalize_requested_version(browser_version)- except ValueError:- declared = None- if declared:- version = declared- elif get_local_binary_override():- return False- else:- from .license import resolve_license_key-- pro = bool(resolve_license_key(license_key))- version = get_effective_version(pro=pro, release_channel=release_channel)- if version is None:- return False- try:- return not _version_newer(HEADLESS_NO_VIEWPORT_MIN_VERSION, version)- except (ValueError, AttributeError):- return False---# ----------------------------------------------------------------------------# Inline HTTP proxy authentication by binary version-# ----------------------------------------------------------------------------# First Chromium build, per platform, whose binary can take inline HTTP proxy-# credentials (Chromium-native ``--proxy-server=http://user:pass@host``). Below-# the floor the wrapper MUST route credentialed HTTP/HTTPS proxies through-# Playwright's proxy dict instead — an older binary treats the ``user:pass@``-# authority as an invalid proxy host and drops proxy auth (#182).-#-# A single global threshold (like HEADLESS_NO_VIEWPORT_MIN_VERSION) can't model-# this: the capability landed in different build lineages at different points —-# linux-x64/windows-x64 have it at 146.0.7680.177.5, but the free macOS (145.x)-# and linux-arm64 (146.0.7680.177.3) floors predate it, so those only qualify-# once they resolve to a Pro/newer build (148+). Platforms absent from this map-# are treated as never-inline (unknown capability => safe fallback).-HTTP_PROXY_INLINE_AUTH_MIN_VERSION: dict[str, str] = {- "linux-x64": "146.0.7680.177.5",- "windows-x64": "146.0.7680.177.5",- "linux-arm64": "148.0.7778.215.3",- "darwin-arm64": "148.0.7778.215.3",- "darwin-x64": "148.0.7778.215.3",-}---def binary_supports_http_proxy_inline_auth(- license_key: str | None = None,- browser_version: str | None = None,- release_channel: str | None = None,-) -> bool:- """Whether the resolved binary accepts inline HTTP proxy credentials.-- The capability is a function of the binary version; ``license_key`` only- resolves *which* version launches (Pro build vs free default), exactly like- ``binary_supports_headless_no_viewport``. A declared pin wins, else a valid- Pro license resolves to the Pro build (which ships the patch), else the free- per-platform default — then it compares to this platform's floor. Below the- floor, credentialed HTTP proxies fall back to Playwright's proxy dict. A- local override with no declared version is unknown-version, so stay on the- safe fallback. Python, JS and .NET mirror this gate.- """- floor = HTTP_PROXY_INLINE_AUTH_MIN_VERSION.get(get_platform_tag())- if floor is None:- return False- try:- declared = normalize_requested_version(browser_version)- except ValueError:- declared = None- if declared:- version = declared- elif get_local_binary_override():- return False- else:- from .license import resolve_license_key-- pro = bool(resolve_license_key(license_key))- version = get_effective_version(pro=pro, release_channel=release_channel)- if version is None:- # Pro with no cached marker => resolve latest Pro from the server, which- # is >= the floor by construction and always ships the patch.- return True- try:- return not _version_newer(floor, version)- except (ValueError, AttributeError):- return False---def binary_supports_maximized_window(- license_key: str | None = None,- browser_version: str | None = None,- release_channel: str | None = None,-) -> bool:- """Whether the wrapper may auto-add ``--start-maximized``.-- Gated on the same threshold as the no_viewport shim: only binaries whose- headless surface-fix + headed screen-clamp make a maximized window coherent- (``outer == screen``). Below it, maximizing headless while the CDP viewport- stays at 1280x720 yields ``outerWidth < innerWidth`` — an impossible-window- bot tell — so the flag must NOT be added. Shares- ``HEADLESS_NO_VIEWPORT_MIN_VERSION``; kept as its own name so the two can- diverge later. Python, JS and .NET mirror this gate.- """- return binary_supports_headless_no_viewport(- license_key, browser_version, release_channel- )diff --git a/cloakbrowser/download.py b/cloakbrowser/download.pyindex 9f47b23..dd0776e 100644--- a/cloakbrowser/download.py+++ b/cloakbrowser/download.py@@ -26,21 +26,14 @@ import httpxfrom ._version import __version__ as _wrapper_versionfrom .config import (BINARY_SIGNING_PUBKEYS,- CHROMIUM_VERSION,DOWNLOAD_BASE_URL,- GITHUB_API_URL,- GITHUB_DOWNLOAD_BASE_URL,_version_newer,- check_platform_available,get_archive_ext,get_archive_name,get_binary_dir,get_binary_path,get_cache_dir,- get_chromium_version,- get_download_url,get_effective_version,- get_fallback_download_url,get_local_binary_override,get_platform_tag,normalize_release_channel,@@ -56,27 +49,19 @@ class BinaryVerificationError(RuntimeError):Distinct from transient download/network errors: a verification failure isa tampering signal and MUST surface, never silently fall back to another- binary. The Pro routing in ensure_binary re-raises this rather than- downgrading to the free tier.+ binary. The routing in ensure_binary re-raises this rather than falling+ back to a cached build."""# Timeout for download (large binary, allow 10 min)DOWNLOAD_TIMEOUT = httpx.Timeout(connect=10.0, read=60.0, write=10.0, pool=10.0)-# Auto-update check interval (1 hour)-UPDATE_CHECK_INTERVAL = 3600--# Free-tier welcome banner re-show interval (1 day). Free users see the-# "get the latest free" invite again after this gap; Pro users see it only once+# Free-key welcome banner re-show interval (1 day). Free users see the+# "more sessions" invite again after this gap; Pro users see it only once# (see _show_welcome).WELCOME_FREE_INTERVAL = 24 * 3600-# Pro Chromium major shown in the free-tier welcome banner. Bump at each Pro-# major release (there is no local constant to derive it from — the live Pro-# version comes from the network, which we don't call just to print a banner).-PRO_MAJOR = "155"-# Attempts to rename an extraction into place while concurrent callers are# replacing the same partial install (see _extract_archive).INSTALL_RENAME_ATTEMPTS = 5@@ -137,15 +122,13 @@ def _emit(text: str) -> None:pass-def _show_welcome(tier: str = "keyless") -> None:+def _show_welcome(tier: str) -> None:"""Show welcome message on launch. A marker file gates the cadence: a paid- (Pro) key shows once ever; free (keyless or a free GitHub key) re-shows every- WELCOME_FREE_INTERVAL.+ (Pro) key shows once ever; a free key re-shows every WELCOME_FREE_INTERVAL.tier:- "pro" — a paid license key (Pro banner + support address)- "free" — a free GitHub key (latest binary, one concurrent session)- "keyless" — no key, running the older free binary (invite the free login)+ "pro" — a paid license key (Pro banner + support address)+ "free" — a free key (latest binary, one concurrent session)"""marker = get_cache_dir() / ".welcome_shown"if not _welcome_due(marker, pro=(tier == "pro")):@@ -156,34 +139,21 @@ def _show_welcome(tier: str = "keyless") -> None:# cosmetic banner must never be able to kill a launch._emit("\n")_emit(" CloakBrowser - stealth Chromium for automation\n")- _emit(" https://github.com/CloakHQ/CloakBrowser\n")- _emit("\n")if tier == "pro":- _emit(- f" CloakBrowser Pro active (v{PRO_MAJOR}) - latest binary, newest patches.\n"- )+ _emit(" CloakBrowser Pro active.\n\n")_emit(" Pro support -> [email protected]\n")- elif tier == "free":- _emit(- f" CloakBrowser free (v{PRO_MAJOR}): the latest binary, 1 concurrent session.\n"- )- _emit(- " For more than one concurrent session -> https://cloakbrowser.dev\n"- )+ _emit(" Site -> https://cloakbrowser.dev\n")else:- free_major = CHROMIUM_VERSION.split(".")[0]- _emit(- f" Running the free binary (v{free_major}). "- f"The latest binary (v{PRO_MAJOR}) is free too, with 1 concurrent session.\n"- )- _emit(- " Get your key: run cloakbrowser login or visit https://cloakbrowser.dev/free\n"- )- _emit(- " For more than one concurrent session -> https://cloakbrowser.dev\n"- )+ _emit(" CloakBrowser free: 1 concurrent session.\n\n")+ _emit(" For more than one concurrent session -> https://cloakbrowser.dev\n")+ _emit(" Docs -> https://github.com/CloakHQ/CloakBrowser\n")_emit(" Star us if CloakBrowser helps your project!\n")_emit("\n")+ _mark_welcome_shown()+++def _mark_welcome_shown() -> None:+ marker = get_cache_dir() / ".welcome_shown"try:marker.parent.mkdir(parents=True, exist_ok=True)marker.write_text(str(int(time.time())))@@ -220,183 +190,249 @@ def ensure_binary(requested_version = normalize_requested_version(browser_version)- # Pro license key check (custom download URL overrides Pro path)- from .license import (- CloakBrowserLicenseError,- resolve_license_key,- validate_license,+ from .license import CloakBrowserLicenseError, resolve_license_key, validate_license++ # No key anywhere (param, env, license.key) -> get a free one first.+ key = resolve_license_key(license_key) or _claim_free_key()+ info = validate_license(key)+ if info and info.valid:+ _maybe_trigger_update_check()+ # A free key always gets the latest build. Drop any version pin: the+ # server force-serves latest to free keys, so fetching a pinned+ # version's signed manifest would mismatch the served bytes and fail+ # checksum verification. Paid keys keep pinning/rollback.+ if info.plan == "free":+ requested_version = None+ # (A blip during a routine update never reaches the error below:+ # _ensure_pro_binary returns the cached build and retries next launch.)+ try:+ return _ensure_pro_binary(+ key,+ requested_version=requested_version,+ plan=info.plan,+ release_channel=release_channel,+ )+ except BinaryVerificationError:+ # Authenticity could not be confirmed — surface verbatim.+ raise+ except Exception as e:+ raise RuntimeError(+ f"CloakBrowser binary unavailable: {e}. Your license is valid but "+ f"the binary could not be downloaded right now. Retry in a moment."+ ) from e+ if info:+ raise CloakBrowserLicenseError(+ f"CloakBrowser: license key is invalid or expired (plan={info.plan}). "+ f"Check CLOAKBROWSER_LICENSE_KEY or ~/.cloakbrowser/license.key, or get "+ f"a free key with: cloakbrowser login"+ )+ raise CloakBrowserLicenseError(+ "CloakBrowser: license could not be validated (server unreachable and "+ "no cached validation). Retry in a moment."+ )+++# How long a background claim poll keeps checking for the key (see _claim_free_key).+CLAIM_POLL_WINDOW = 600+_claim_poll_started = False+++def _isatty(stream) -> bool:+ try:+ return stream.isatty()+ except (AttributeError, ValueError, OSError): # None (pythonw) or closed+ return False+++def can_prompt() -> bool:+ """A person is at this terminal and Ctrl+C reaches us (main thread)."""+ return (+ threading.current_thread() is threading.main_thread()+ and _isatty(sys.stdin)+ and _isatty(sys.stderr))- key = resolve_license_key(license_key)- if os.environ.get("CLOAKBROWSER_DOWNLOAD_URL"):- key = None- if key:+def _ask(prompt: str) -> str:+ # Prompt on stderr: a script's stdout may be its data.+ _emit(prompt)+ return input().strip()+++def _emit_welcome() -> None:+ _emit("\n Welcome to CloakBrowser - stealth Chromium for automation\n")+ _emit(" https://github.com/CloakHQ/CloakBrowser\n\n")+ _emit(" CloakBrowser needs a license key.\n\n")+++def prompt_license_key() -> str:+ """Terminal menu shared by a no-key launch and `cloakbrowser login`: get a+ free key by email or paste one. Returns a valid key, already saved.++ Raises EOFError if stdin closes, KeyboardInterrupt on Ctrl+C."""+ _emit_welcome()+ _emit(" 1) Get a free key (by email: the latest build, 1 concurrent session)\n")+ _emit(" 2) Paste a key I already have\n\n")+ while True:+ choice = _ask(" Choose 1 or 2 [1]: ")+ if choice in ("", "1"):+ key = _get_free_key()+ if key:+ return key+ _emit(f"\n {HAS_KEY_MSG}\n")+ elif choice != "2":+ _emit(" Please type 1 or 2.\n")+ continue+ key = _paste_key()+ if key:+ return key+++HAS_KEY_MSG = (+ "This email already has a free key. It's in the email we sent when you "+ "first got it (search your mail for CloakBrowser)."+)+++def _paste_key() -> str | None:+ """Ask until a valid key is pasted (saved, returned) or the answer is empty."""+ from .license import _KEY_RE, save_license_key, validate_license++ while True:+ key = _ask(" Paste your key (empty to go back): ")+ if not key:+ return None+ if not _KEY_RE.fullmatch(key):+ _emit(" That is not a CloakBrowser key (they start with cb_).\n")+ continueinfo = validate_license(key)- if info and info.valid:- # Free tier always gets the latest build. Drop any version pin: the- # server force-serves latest to free keys, so fetching a pinned- # version's signed manifest would mismatch the served bytes and fail- # checksum verification. Paid keys keep pinning/rollback.- if info.plan == "free":- requested_version = None- # A valid license is entitled to Pro, so Pro failures surface loudly- # rather than silently substituting the older free binary. (A blip- # during a routine update never reaches here: _ensure_pro_binary- # returns the cached Pro binary and updates in the background.)- try:- return _ensure_pro_binary(- key,- requested_version=requested_version,- plan=info.plan,- release_channel=release_channel,- )- except BinaryVerificationError:- # Authenticity could not be confirmed — surface verbatim.- raise- except Exception as e:- # Transient failure with no cached Pro binary to use — surface a- # clear error rather than silently downloading the free binary.- raise RuntimeError(- f"Pro binary unavailable: {e}. Your license is valid but the "- f"Pro binary could not be downloaded right now. Retry in a "- f"moment. To use the free binary instead, unset "- f"CLOAKBROWSER_LICENSE_KEY."- ) from e- elif info:- # Key supplied but rejected — abort, never downgrade to free.- raise CloakBrowserLicenseError(- f"CloakBrowser Pro: license key is invalid or expired "- f"(plan={info.plan}). Check CLOAKBROWSER_LICENSE_KEY, or unset it "- f"to use the free binary."- )+ if info is None:+ _emit(" Could not reach the license server. Check your connection and retry.\n")+ elif not info.valid:+ _emit(" That key is invalid or expired.\n")else:- # Key supplied but unvalidatable (server down, no cache) — abort.- raise CloakBrowserLicenseError(- "CloakBrowser Pro: license could not be validated (server "- "unreachable and no cached validation). Retry in a moment, or "- "unset CLOAKBROWSER_LICENSE_KEY to use the free binary."- )+ save_license_key(key)+ _emit(" Key saved.\n\n")+ if info.plan == "free":+ _mark_welcome_shown() # the menu was the welcome; a paid key keeps its Pro banner+ return key- # Fail fast if no binary available for this platform- check_platform_available()- if requested_version:- binary_path = get_binary_path(requested_version)- if binary_path.exists() and _is_executable(binary_path):- logger.debug(- "Pinned binary found in cache: %s (version %s)",- binary_path,- requested_version,- )- _show_welcome()- return str(binary_path)+def _get_free_key() -> str | None:+ """Open the claim link and wait for the key (saved, returned). None if the+ email already has a key, which the server never sends to a claim."""+ from .license import FreeKeyAlreadyHeld, claim_link, get_claim_code, poll_claim- logger.info(- "Stealth Chromium %s not found. Downloading for %s...",- requested_version,- get_platform_tag(),- )- _download_and_extract(requested_version)+ code = get_claim_code()+ link = claim_link(code)+ _emit(f"\n Open this link and enter your email:\n {link}\n")+ if _has_display():+ import webbrowser- if not (binary_path.exists() and _is_executable(binary_path)):- raise RuntimeError(- f"Pinned download completed but binary not found at expected path: {binary_path}. "- f"This may indicate a packaging issue. Please report at "- f"https://github.com/CloakHQ/cloakbrowser/issues"- )- _show_welcome()- return str(binary_path)+ try:+ if webbrowser.open(link):+ _emit(" (opened in your browser)\n")+ except (webbrowser.Error, OSError) as e:+ logger.debug("Could not open a browser: %s", e)+ _emit("\n Waiting for you to confirm your email... (Ctrl+C to stop)\n")+ try:+ key = poll_claim(code, overwrite=True)+ except FreeKeyAlreadyHeld:+ return None+ _emit(" Free key saved.\n\n")+ _mark_welcome_shown() # the menu was the welcome: no second banner this launch+ return key- # Check for auto-updated version first, then fall back to hardcoded- effective = get_effective_version()- binary_path = get_binary_path(effective)- if binary_path.exists() and _is_executable(binary_path):- logger.debug("Binary found in cache: %s (version %s)", binary_path, effective)- _show_welcome()- _maybe_trigger_update_check()- return str(binary_path)+def _claim_free_key() -> str:+ """No key anywhere: get one before launching.- # Fall back to platform's hardcoded version if effective version binary doesn't exist- platform_version = get_chromium_version()- if effective != platform_version:- fallback_path = get_binary_path()- if fallback_path.exists() and _is_executable(fallback_path):- logger.debug("Binary found in cache: %s", fallback_path)- _maybe_trigger_update_check()- return str(fallback_path)-- # Download platform's hardcoded version- logger.info(- "Stealth Chromium %s not found. Downloading for %s...",- platform_version,- get_platform_tag(),+ A person at a terminal (main thread) gets the menu (prompt_license_key).+ Anything else (CI, Docker, an MCP server, launch_async's worker thread, where+ Ctrl+C can't reach) raises with the claim link and keeps polling in the+ background, so a long-lived process picks the key up and its next launch works."""+ from .license import (+ CloakBrowserLicenseError,+ FreeKeyAlreadyHeld,+ check_claim,+ claim_link,+ get_claim_code,+ save_license_key,)- _download_and_extract()- binary_path = get_binary_path()- if not binary_path.exists():- raise RuntimeError(- f"Download completed but binary not found at expected path: {binary_path}. "- f"This may indicate a packaging issue. Please report at "- f"https://github.com/CloakHQ/cloakbrowser/issues"- )+ code = get_claim_code()+ try:+ key = check_claim(code)+ except FreeKeyAlreadyHeld:+ if not can_prompt():+ raise CloakBrowserLicenseError(+ f"{HAS_KEY_MSG} Set CLOAKBROWSER_LICENSE_KEY or run: cloakbrowser login"+ ) from None+ key = None # the menu below starts over with a fresh code+ if key: # confirmed since an earlier launch printed the link+ save_license_key(key, overwrite=False)+ return key+ if can_prompt():+ try:+ return prompt_license_key()+ except EOFError:+ pass # stdin closed mid-menu: fall through to the link + error+ except KeyboardInterrupt:+ # The person at the menu chose to stop: exit quietly like the JS and+ # .NET wrappers (130 = Ctrl+C), not with a traceback.+ _emit("\n")+ raise SystemExit(130) from None+ code = get_claim_code() # fresh if the old one was retired+ link = claim_link(code)+ _emit_welcome()+ _emit(f" Get one free (the latest build, 1 concurrent session):\n {link}\n"+ " After you confirm, the key is also emailed to you.\n\n")+ _start_claim_poll(code)+ raise CloakBrowserLicenseError(+ f"No CloakBrowser license key. Get one free: {link} "+ "(or run: cloakbrowser login), then launch again."+ )- _maybe_trigger_update_check()- return str(binary_path)+def _has_display() -> bool:+ """Whether opening a browser can show a window. On Linux/BSD without a+ display (typically SSH), webbrowser falls back to a text browser (lynx,+ w3m) that takes over this terminal, so skip it: the link is printed anyway.+ The same reason gh and gcloud print the URL instead on remote hosts."""+ if sys.platform in ("darwin", "win32"):+ return True+ return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))-def _download_and_extract(version: str | None = None) -> None:- """Download the binary archive and extract to cache directory.- Tries the primary server (cloakbrowser.dev) first, falls back to- GitHub Releases if the primary is unreachable or returns an error.- Verifies SHA-256 checksum before extraction when available.- """- primary_url = get_download_url(version)- fallback_url = get_fallback_download_url(version)- binary_dir = get_binary_dir(version)- binary_path = get_binary_path(version)+_claim_poll_lock = threading.Lock()- # Create cache dir- binary_dir.parent.mkdir(parents=True, exist_ok=True)- # Download to temp file first (atomic — no partial downloads in cache)- with tempfile.NamedTemporaryFile(suffix=get_archive_ext(), delete=False) as tmp:- tmp_path = Path(tmp.name)+def _start_claim_poll(code: str) -> None:+ """Poll for the claimed key in a daemon thread, once per process."""+ global _claim_poll_started+ with _claim_poll_lock: # concurrent launch_async calls: one poller only+ if _claim_poll_started:+ return+ _claim_poll_started = True+ from .license import FreeKeyAlreadyHeld, poll_claim- try:- # Try primary, fall back to GitHub Releases (skip fallback if custom URL)+ def run() -> None:try:- _download_file(primary_url, tmp_path)- except Exception as primary_err:- if os.environ.get("CLOAKBROWSER_DOWNLOAD_URL"):- raise- logger.warning(- "Primary download failed (%s), trying GitHub Releases...",- primary_err,- )- _download_file(fallback_url, tmp_path)+ if poll_claim(code, deadline=time.time() + CLAIM_POLL_WINDOW):+ _emit("\n CloakBrowser: free key saved. The next launch uses it.\n")+ except FreeKeyAlreadyHeld:+ _emit(f"\n CloakBrowser: {HAS_KEY_MSG}\n Set CLOAKBROWSER_LICENSE_KEY or run: cloakbrowser login\n")+ except (OSError, ValueError) as e:+ logger.warning("Could not save the claimed free key: %s", e)- # Verify the download before extraction. On the official path this is a- # mandatory, non-bypassable Ed25519 signature check (see- # _verify_download_checksum); the skip flag only applies to custom- # self-hosted CLOAKBROWSER_DOWNLOAD_URL setups.- _verify_download_checksum(tmp_path, version)-- _extract_archive(tmp_path, binary_dir, binary_path)- _show_welcome()- finally:- # Clean up temp file- tmp_path.unlink(missing_ok=True)+ threading.Thread(target=run, daemon=True).start()def _pro_binary_ready(version: str | None) -> bool:"""True when a cached, executable Pro binary exists for ``version``."""if not version:return False- path = get_binary_path(version, pro=True)+ path = get_binary_path(version)return path.exists() and _is_executable(path)@@ -408,21 +444,20 @@ def _ensure_pro_binary() -> str:"""Ensure the latest (keyed) binary is downloaded and cached. Returns its path.- Used for both free-tier GitHub keys (plan="free") and paid keys — both fetch- the same latest build; the server enforces the concurrency cap. A valid key- NEVER falls back to the older free binary: if the latest build cannot be- resolved or downloaded and none is cached, the error is raised.+ Used for both free keys (plan="free") and paid keys — both fetch the same+ latest build; the server enforces the concurrency cap. If the latest build+ cannot be resolved or downloaded and none is cached, the error is raised."""from .license import get_pro_latest_release, get_pro_latest_version- # Banner tier: a free GitHub key gets the free banner, paid keys the Pro one.+ # Banner tier: a free key gets the free banner, paid keys the Pro one.welcome_tier = "free" if plan == "free" else "pro"# --- Pinned: launch the exact requested version, no server cross-check, no# marker write (a rollback pin must not stick future unpinned launches). ---if requested_version:if _pro_binary_ready(requested_version):- binary_path = get_binary_path(requested_version, pro=True)+ binary_path = get_binary_path(requested_version)logger.debug("Pinned Pro binary found in cache: %s (version %s)",binary_path,@@ -434,7 +469,7 @@ def _ensure_pro_binary("Downloading Pro Chromium %s for %s...", requested_version, get_platform_tag())_download_pro_binary(requested_version, license_key)- binary_path = get_binary_path(requested_version, pro=True)+ binary_path = get_binary_path(requested_version)if not binary_path.exists():raise RuntimeError(f"Pro download completed but binary not found at: {binary_path}"@@ -443,17 +478,16 @@ def _ensure_pro_binary(return str(binary_path)# --- Unpinned: track the server's latest selected channel. ---- effective = get_effective_version(pro=True, release_channel=release_channel)+ effective = get_effective_version(release_channel)- # Honor CLOAKBROWSER_AUTO_UPDATE=false the way the free path does: if the user- # froze updates AND a Pro build is already cached, keep it and skip the server- # check. With no cached build we must still fetch one — a valid Pro license can- # never launch the free binary. (The `update` CLI ignores this and always acts.)+ # Honor CLOAKBROWSER_AUTO_UPDATE=false: if the user froze updates AND a build+ # is already cached, keep it and skip the server check. With no cached build+ # we must still fetch one. (The `update` CLI ignores this and always acts.)frozen = os.environ.get("CLOAKBROWSER_AUTO_UPDATE", "").lower() == "false"if frozen and _pro_binary_ready(effective):logger.debug("Pro auto-update disabled; using cached %s", effective)_show_welcome(welcome_tier)- return str(get_binary_path(effective, pro=True))+ return str(get_binary_path(effective))# get_pro_latest_version() is rate-limited to one network call per hour and# returns a cached string in between, so this foreground check stays cheap on@@ -482,11 +516,11 @@ def _ensure_pro_binary(if version is None:# Valid Pro license but nothing resolvable (server unreachable AND no- # cached Pro build). Never downgrade to the free binary — fail loudly.+ # cached build) — fail loudly.raise RuntimeError("Could not determine latest Pro version from server")if _pro_binary_ready(version):- binary_path = get_binary_path(version, pro=True)+ binary_path = get_binary_path(version)# Advance the marker if this cached build is newer than what the marker names,# so `info` (and a later server-outage launch) reflect the build we actually# launch — never a stale marker.@@ -500,7 +534,7 @@ def _ensure_pro_binary(return str(binary_path)# `version` (the server latest) needs downloading. On failure, fall back to a- # cached Pro build if we have one — never the free binary.+ # cached build if we have one.try:logger.info("Downloading Pro Chromium %s for %s...", version, get_platform_tag()@@ -518,10 +552,10 @@ def _ensure_pro_binary(effective,)_show_welcome(welcome_tier)- return str(get_binary_path(effective, pro=True))+ return str(get_binary_path(effective))raise- binary_path = get_binary_path(version, pro=True)+ binary_path = get_binary_path(version)if not binary_path.exists():raise RuntimeError(f"Pro download completed but binary not found at: {binary_path}"@@ -544,8 +578,8 @@ def _download_pro_binary(version: str, license_key: str) -> None:manifest verified in _verify_pro_download."""download_url = f"{DOWNLOAD_BASE_URL}/api/download/{version}"- binary_dir = get_binary_dir(version, pro=True)- binary_path = get_binary_path(version, pro=True)+ binary_dir = get_binary_dir(version)+ binary_path = get_binary_path(version)platform_tag = get_platform_tag()binary_dir.parent.mkdir(parents=True, exist_ok=True)@@ -563,11 +597,7 @@ def _download_pro_binary(version: str, license_key: str) -> None:},)- # Pro binaries come from cloakbrowser.dev — the same origin as free- # downloads — so the M1 attack the Ed25519 signature defends against- # applies equally. Verify with the same non-bypassable signature check;- # CLOAKBROWSER_SKIP_CHECKSUM does NOT bypass it (parity with the- # official free path).+ # Non-bypassable Ed25519 signature check (M1 defense); no env var skips it._verify_pro_download(tmp_path, version)_extract_archive(tmp_path, binary_dir, binary_path)@@ -576,20 +606,17 @@ def _download_pro_binary(version: str, license_key: str) -> None:def _verify_pro_download(file_path: Path, version: str) -> None:- """Verify a Pro archive with the same non-bypassable Ed25519 signature check- as official free downloads.+ """Verify a downloaded archive with a non-bypassable Ed25519 signature check.- Pro binaries are served from cloakbrowser.dev (same origin as the free- tier), so a tampered same-origin SHA256SUMS could otherwise certify a- tampered binary (M1, #308). Fetch the Pro SHA256SUMS + detached+ A tampered same-origin SHA256SUMS could otherwise certify a tampered+ binary (M1, #308). Fetch the Pro SHA256SUMS + detachedSHA256SUMS.sig, verify the signature against the pinned keys FIRST, bind themanifest to the requested version, then verify the archive's SHA-256.An invalid signature, checksum, or version mismatch raisesBinaryVerificationError (a tampering signal the router surfaces verbatim);- CLOAKBROWSER_SKIP_CHECKSUM cannot bypass it. A failed manifest FETCH is- transient — nothing was validated — and raises a plain RuntimeError. A- valid-license user is never silently downgraded to the free binary.+ Nothing can bypass it. A failed manifest FETCH is+ transient — nothing was validated — and raises a plain RuntimeError."""base = f"{DOWNLOAD_BASE_URL}/releases/pro/chromium-v{version}"try:@@ -611,15 +638,17 @@ def _verify_pro_download(file_path: Path, version: str) -> None:manifest_bytes = manifest_resp.content# _verify_signature / _verify_checksum raise plain RuntimeError; convert to- # BinaryVerificationError so the Pro router treats them as tampering signals- # (re-raise) rather than transient failures (fall back to free).+ # BinaryVerificationError so the router treats them as tampering signals+ # (re-raise) rather than transient failures (fall back to a cached build).try:_verify_signature(manifest_bytes, sig_resp.content)except RuntimeError as exc:raise BinaryVerificationError(str(exc)) from excmanifest_text = manifest_bytes.decode("utf-8")- # Version binding: same forced-downgrade defense as the official path.+ # Version binding: the signature proves "we made this manifest", not "this+ # is the version you asked for" — without this a genuinely-signed older+ # release could be served in place of the requested one (forced downgrade).declared = _parse_manifest_version(manifest_text)if declared != version:raise BinaryVerificationError(@@ -640,79 +669,6 @@ def _verify_pro_download(file_path: Path, version: str) -> None:raise BinaryVerificationError(str(exc)) from exc-def _verify_download_checksum(file_path: Path, version: str | None = None) -> None:- """Verify the downloaded archive's integrity and authenticity.-- Official path (cloakbrowser.dev / GitHub Releases): fetch SHA256SUMS plus- its detached Ed25519 signature SHA256SUMS.sig, verify the signature against- the pinned public keys FIRST, then verify the archive's SHA-256 against the- now-authenticated manifest. Mandatory and non-bypassable — a same-origin- manifest can no longer certify a tampered binary (#308).-- Custom self-hosted path (CLOAKBROWSER_DOWNLOAD_URL set): the pinned keys do- not apply to a third-party server, so fall back to the plain same-origin- SHA256SUMS check, which CLOAKBROWSER_SKIP_CHECKSUM may bypass.- """- tarball_name = get_archive_name()-- if os.environ.get("CLOAKBROWSER_DOWNLOAD_URL"):- # Self-hosted mirror: signature scheme does not apply. Preserve the- # legacy same-origin checksum behavior, skippable as before.- if os.environ.get("CLOAKBROWSER_SKIP_CHECKSUM", "").lower() == "true":- logger.warning(- "CLOAKBROWSER_SKIP_CHECKSUM set — skipping verification for custom download URL"- )- return- checksums = _fetch_checksums(version)- if checksums is None:- logger.warning(- "SHA256SUMS not available from custom URL — skipping checksum verification"- )- return- expected = checksums.get(tarball_name)- if expected is None:- logger.warning(- "SHA256SUMS found but no entry for %s — skipping verification",- tarball_name,- )- return- _verify_checksum(file_path, expected)- return-- # Official path: signature is the trust root and is non-bypassable.- manifest = _fetch_signed_manifest(version)- if manifest is None:- raise RuntimeError(- "Could not fetch a signed SHA256SUMS (SHA256SUMS + SHA256SUMS.sig) "- "for this release — refusing to use an unverified binary. "- "Retry, or report at https://github.com/CloakHQ/cloakbrowser/issues"- )- manifest_bytes, sig_bytes = manifest- _verify_signature(manifest_bytes, sig_bytes)- manifest_text = manifest_bytes.decode("utf-8")-- # Version binding: the signed manifest must declare the version we asked for.- # The signature proves "we made this manifest", not "this is the version you- # requested" — without this check a mirror could serve a genuinely-signed- # older release in place of the requested one (forced downgrade).- requested = version or get_chromium_version()- declared = _parse_manifest_version(manifest_text)- if declared != requested:- raise RuntimeError(- f"Version mismatch in signed SHA256SUMS: requested {requested}, "- f"manifest declares {declared or 'none'}. Refusing (possible downgrade)."- )-- checksums = _parse_checksums(manifest_text)- expected = checksums.get(tarball_name)- if expected is None:- raise RuntimeError(- f"Signature-verified SHA256SUMS has no entry for {tarball_name} — "- f"cannot confirm binary integrity."- )- _verify_checksum(file_path, expected)--def _parse_manifest_version(text: str) -> str | None:"""Read the 'version=<v>' line from a signed manifest. None if absent.@@ -726,35 +682,6 @@ def _parse_manifest_version(text: str) -> str | None:return None-def _fetch_signed_manifest(version: str | None = None) -> tuple[bytes, bytes] | None:- """Fetch (SHA256SUMS, SHA256SUMS.sig) raw bytes for a version, or None.-- Both files are fetched from the SAME origin so the signature always matches- the exact manifest bytes it certifies. The primary origin is tried first,- then the GitHub Releases mirror. follow_redirects mirrors _fetch_checksums:- cloakbrowser.dev 301-redirects /chromium-v* to GitHub Releases.- """- v = version or get_chromium_version()- bases = [- f"{DOWNLOAD_BASE_URL}/chromium-v{v}",- f"{GITHUB_DOWNLOAD_BASE_URL}/chromium-v{v}",- ]- for base in bases:- try:- manifest_resp = httpx.get(- f"{base}/SHA256SUMS", follow_redirects=True, timeout=10.0- )- manifest_resp.raise_for_status()- sig_resp = httpx.get(- f"{base}/SHA256SUMS.sig", follow_redirects=True, timeout=10.0- )- sig_resp.raise_for_status()- return manifest_resp.content, sig_resp.content- except Exception:- continue- return None--def _verify_signature(manifest_bytes: bytes, sig_b64: bytes) -> None:"""Verify a detached Ed25519 signature over the raw manifest bytes.@@ -797,26 +724,6 @@ def _verify_signature(manifest_bytes: bytes, sig_b64: bytes) -> None:)-def _fetch_checksums(version: str | None = None) -> dict[str, str] | None:- """Fetch SHA256SUMS file for a version. Returns {filename: hash} or None."""- v = version or get_chromium_version()- has_custom_url = os.environ.get("CLOAKBROWSER_DOWNLOAD_URL")-- # Build URL list — respect custom URL contract (no GitHub fallback)- urls = [f"{DOWNLOAD_BASE_URL}/chromium-v{v}/SHA256SUMS"]- if not has_custom_url:- urls.append(f"{GITHUB_DOWNLOAD_BASE_URL}/chromium-v{v}/SHA256SUMS")-- for url in urls:- try:- resp = httpx.get(url, follow_redirects=True, timeout=10.0)- resp.raise_for_status()- return _parse_checksums(resp.text)- except Exception:- continue- return None--def _parse_checksums(text: str) -> dict[str, str]:"""Parse SHA256SUMS format: '<64-hex sha256> filename' per line.@@ -903,12 +810,10 @@ def _download_file(url: str, dest: Path, headers: dict[str, str] | None = None)logger.info("Download complete: %d MB", dest.stat().st_size // (1024 * 1024))-def _extract_archive(- archive_path: Path, dest_dir: Path, binary_path: Path | None = None-) -> None:+def _extract_archive(archive_path: Path, dest_dir: Path, binary_path: Path) -> None:"""Extract tar.gz or zip archive to destination directory."""logger.info("Extracting to %s", dest_dir)- bp = binary_path or get_binary_path()+ bp = binary_path# Extract into a private sibling dir, then rename it into place. Concurrent# first runs (in this process or others) each get their own staging dir, so@@ -1073,44 +978,24 @@ def binary_info(browser_version: str | None = None,release_channel: str | None = None,) -> dict:- """Return info about the current binary installation.-- tier reflects what is actually installed on disk, not merely whether a- license is cached — a cached license with no Pro binary downloaded yet is- still effectively running the free binary, and the active key may differ- from the cached one.+ """Return info about the cached binary installation.browser_version (or CLOAKBROWSER_VERSION) pins the reported version so the- info matches what a pinned launch actually runs, instead of latest.+ info matches what a pinned launch actually runs, instead of latest. version+ is None until a build has been downloaded."""- requested = normalize_requested_version(browser_version)- # Prefer Pro only if a Pro binary actually exists on disk. get_effective_version- # returns None for Pro when nothing is cached (it never falls back to free).- pro_version = requested or get_effective_version(- pro=True, release_channel=release_channel+ version = normalize_requested_version(browser_version) or get_effective_version(+ release_channel)- pro = _pro_binary_ready(pro_version) # already false for a None version-- if pro:- effective = pro_version- binary_path = get_binary_path(pro_version, pro=True)- else:- effective = requested or get_effective_version()- binary_path = get_binary_path(effective)- if pro:- download_url = f"{DOWNLOAD_BASE_URL}/api/download/latest"- if normalize_release_channel(release_channel) == "preview":- download_url += "?channel=preview"- else:- download_url = get_download_url(effective)+ download_url = f"{DOWNLOAD_BASE_URL}/api/download/latest"+ if normalize_release_channel(release_channel) == "preview":+ download_url += "?channel=preview"return {- "version": effective,- "tier": "pro" if pro else "free",- "bundled_version": CHROMIUM_VERSION,+ "version": version,"platform": get_platform_tag(),- "binary_path": str(binary_path),- "installed": binary_path.exists(),- "cache_dir": str(get_binary_dir(effective, pro=pro)),+ "binary_path": str(get_binary_path(version)) if version else None,+ "installed": _pro_binary_ready(version),+ "cache_dir": str(get_binary_dir(version)) if version else None,"download_url": download_url,}@@ -1120,30 +1005,6 @@ def binary_info(# ----------------------------------------------------------------------------def check_for_update() -> str | None:- """Manually check for a newer Chromium version. Returns new version or None.-- This is the public API for triggering an update check. Unlike the- background check in ensure_binary(), this blocks until complete.- """- latest = _get_latest_chromium_version()- if latest is None:- return None- if not _version_newer(latest, get_chromium_version()):- return None-- binary_dir = get_binary_dir(latest)- if binary_dir.exists():- # Already downloaded- _write_version_marker(latest)- return latest-- logger.info("Downloading Chromium %s...", latest)- _download_and_extract(version=latest)- _write_version_marker(latest)- return latest--def check_for_pro_update(license_key: str, release_channel: str | None = None) -> str | None:@@ -1159,7 +1020,7 @@ def check_for_pro_update(if not latest:return None- effective = get_effective_version(pro=True, release_channel=release_channel)+ effective = get_effective_version(release_channel)if effective and not _version_newer(latest, effective) and _pro_binary_ready(effective):@@ -1169,7 +1030,7 @@ def check_for_pro_update(if not _pro_binary_ready(latest):logger.info("Downloading Pro Chromium %s...", latest)_download_pro_binary(latest, license_key)- binary_path = get_binary_path(latest, pro=True)+ binary_path = get_binary_path(latest)if not binary_path.exists():raise RuntimeError(f"Pro download completed but binary not found at: {binary_path}"@@ -1179,59 +1040,6 @@ def check_for_pro_update(return latest-def _should_check_for_update() -> bool:- """Check if auto-update is enabled and rate limit hasn't been hit."""- if os.environ.get("CLOAKBROWSER_AUTO_UPDATE", "").lower() == "false":- return False- if get_local_binary_override():- return False- if os.environ.get("CLOAKBROWSER_DOWNLOAD_URL"):- return False-- check_file = get_cache_dir() / ".last_update_check"- if check_file.exists():- try:- last_check = float(check_file.read_text().strip())- if time.time() - last_check < UPDATE_CHECK_INTERVAL:- return False- except (ValueError, OSError):- pass- return True---def _get_latest_chromium_version() -> str | None:- """Hit GitHub Releases API, return latest chromium-v* version for this platform.-- Checks that the release has a binary asset for the current platform,- so Linux-only releases won't be offered to macOS users.- """- try:- resp = httpx.get(GITHUB_API_URL, params={"per_page": 10}, timeout=10.0)- resp.raise_for_status()- platform_tarball = get_archive_name()- for release in resp.json():- tag = release.get("tag_name", "")- if tag.startswith("chromium-v") and not release.get("draft"):- asset_names = {a["name"] for a in release.get("assets", [])}- if platform_tarball in asset_names:- return tag.removeprefix("chromium-v")- return None- except Exception:- logger.debug("Auto-update check failed", exc_info=True)- return None---def _write_version_marker(version: str) -> None:- """Write the latest version marker for this platform to cache dir."""- cache_dir = get_cache_dir()- cache_dir.mkdir(parents=True, exist_ok=True)- marker = cache_dir / f"latest_version_{get_platform_tag()}"- # Write to temp file then rename for atomicity- tmp = marker.with_suffix(".tmp")- tmp.write_text(version)- tmp.rename(marker)--def _write_pro_version_marker(version: str, release_channel: str | None = None) -> None:@@ -1261,8 +1069,6 @@ def _check_wrapper_update() -> None:_wrapper_update_checked = Trueif os.environ.get("CLOAKBROWSER_AUTO_UPDATE", "").lower() == "false":return- if os.environ.get("CLOAKBROWSER_DOWNLOAD_URL"):- returntry:resp = httpx.get("https://pypi.org/pypi/cloakbrowser/json",@@ -1281,50 +1087,9 @@ def _check_wrapper_update() -> None:logger.debug("Wrapper update check failed", exc_info=True)-def _check_and_download_update() -> None:- """Background task: check for newer binary, download if available."""- try:- # Record check timestamp first (rate limiting)- check_file = get_cache_dir() / ".last_update_check"- check_file.parent.mkdir(parents=True, exist_ok=True)- check_file.write_text(str(time.time()))-- platform_version = get_chromium_version()- latest = _get_latest_chromium_version()- if latest is None:- return- if not _version_newer(latest, platform_version):- return-- # Already downloaded?- if get_binary_dir(latest).exists():- _write_version_marker(latest)- return-- logger.info(- "Newer Chromium available: %s (current: %s). Downloading in background...",- latest,- platform_version,- )- _download_and_extract(version=latest)- _write_version_marker(latest)- logger.info(- "Background update complete: Chromium %s ready. Will use on next launch.",- latest,- )- except Exception:- logger.debug("Background update failed", exc_info=True)--def _maybe_trigger_update_check() -> None:- """Fire-and-forget update check in a daemon thread."""- # Wrapper update: once per process, not rate-limited- if not _wrapper_update_checked:- t = threading.Thread(target=_check_wrapper_update, daemon=True)- t.start()+ """Fire-and-forget wrapper update check (once per process) in a daemon thread.- # Binary update: rate-limited to once per hour- if not _should_check_for_update():- return- t = threading.Thread(target=_check_and_download_update, daemon=True)- t.start()+ The binary itself updates on the launch path (_ensure_pro_binary)."""+ if not _wrapper_update_checked:+ threading.Thread(target=_check_wrapper_update, daemon=True).start()diff --git a/cloakbrowser/license.py b/cloakbrowser/license.pyindex 7e437bf..f76e05e 100644--- a/cloakbrowser/license.py+++ b/cloakbrowser/license.py@@ -11,6 +11,7 @@ import jsonimport loggingimport osimport re+import secretsimport timeimport uuidfrom collections.abc import Mapping@@ -26,6 +27,10 @@ logger = logging.getLogger("cloakbrowser")VALIDATE_URL = "https://cloakbrowser.dev/api/license/validate"PRO_VERSION_URL = "https://cloakbrowser.dev/api/download/version"SESSION_COUNT_URL = "https://cloakbrowser.dev/api/license/session/count"+CLAIM_URL = "https://cloakbrowser.dev/api/license/free/claim"+# Fragment, not query: the claim code is a bearer secret and a fragment never+# reaches the server or CDN logs. The page reads it client-side.+FREE_CLAIM_LINK = "https://cloakbrowser.dev/#claim="LICENSE_CACHE_TTL = 86400 # 24 hoursPRO_VERSION_CHECK_INTERVAL = 3600 # 1 hour@@ -296,6 +301,127 @@ def resolve_license_key(license_key: str | None = None) -> str | None:return key+_KEY_RE = re.compile(r"cb_[A-Za-z0-9_-]+")+CLAIM_CODE_RE = re.compile(r"[A-Za-z0-9_-]{20,128}") # the server's format+CLAIM_MAX_AGE = 7 * 86400+++def _write_private(path: Path, text: str) -> None:+ """Write `text` to `path` readable by the owner only, from the first byte.++ The file is created 0600 before anything is written to it, then swapped into+ place, so neither the key nor the claim code is ever world-readable."""+ tmp = path.with_name(f"{path.name}.{secrets.token_hex(8)}.tmp")+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ with os.fdopen(fd, "w") as f:+ f.write(text)+ os.replace(tmp, path)+++def save_license_key(key: str, *, overwrite: bool = True) -> bool:+ """Save a key to <cache>/license.key (0600) and retire the claim code.++ `overwrite=False` (the background claim poll) leaves an existing key alone:+ the user may have run `cloakbrowser login` meanwhile. Returns True if saved."""+ key = key.strip()+ if not _KEY_RE.fullmatch(key):+ raise ValueError("not a CloakBrowser license key")+ cache_dir = get_cache_dir()+ cache_dir.mkdir(parents=True, exist_ok=True)+ key_file = cache_dir / "license.key"+ # The claim code keeps returning the key, so it is retired either way:+ # otherwise a later launch (say after `logout`) would silently re-save it.+ claim = cache_dir / ".free_claim"+ if not overwrite and key_file.exists():+ claim.unlink(missing_ok=True)+ return False+ _write_private(key_file, key + "\n")+ claim.unlink(missing_ok=True)+ return True+++def get_claim_code() -> str:+ """This install's claim code, from <cache>/.free_claim (made 0600, 7-day life).++ Workers launching at once must print the same link, so the file is created+ exclusively and a loser of the race reads the winner's code."""+ cache_dir = get_cache_dir()+ cache_dir.mkdir(parents=True, exist_ok=True)+ path = cache_dir / ".free_claim"+ try:+ if time.time() - path.stat().st_mtime < CLAIM_MAX_AGE:+ code = path.read_text().strip()+ if CLAIM_CODE_RE.fullmatch(code):+ return code+ path.unlink(missing_ok=True) # expired or garbage: start over+ except OSError:+ pass+ code = secrets.token_urlsafe(32)+ tmp = path.with_name(f"{path.name}.{secrets.token_hex(8)}.tmp")+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ with os.fdopen(fd, "w") as f:+ f.write(code)+ try:+ # Publish complete, without replacing: the first code wins and a reader+ # never sees a half-written file (same as the profile seed file).+ os.link(tmp, path)+ except FileExistsError:+ code = path.read_text().strip()+ except OSError:+ # ponytail: no hard links (FAT, some network mounts) -> plain replace;+ # a concurrent first launch there may print a different link.+ os.replace(tmp, path)+ finally:+ tmp.unlink(missing_ok=True)+ return code+++def claim_link(code: str) -> str:+ return f"{FREE_CLAIM_LINK}{code}"+++class FreeKeyAlreadyHeld(Exception):+ """The claim's email already has a free key. The server never sends an+ existing key to a claim (anyone can type anyone's email), so the person+ pastes it from the email they got it in."""+++def check_claim(code: str) -> str | None:+ """One poll: the key once the claim's email is confirmed, else None.+ Raises FreeKeyAlreadyHeld (and retires the code) if that email has a key.++ The code goes in the body, never the URL: it is a bearer secret and URLs+ land in server logs."""+ try:+ resp = httpx.post(CLAIM_URL, json={"code": code}, timeout=5.0)+ data = resp.json() if resp.status_code == 200 else {}+ except (httpx.HTTPError, ValueError) as e:+ logger.debug("Free-key claim check failed: %s", e)+ return None+ if not isinstance(data, dict): # e.g. a captive portal's JSON: just pending+ return None+ if data.get("status") == "has_key":+ # This code will only ever answer has_key: start fresh next time.+ (get_cache_dir() / ".free_claim").unlink(missing_ok=True)+ raise FreeKeyAlreadyHeld+ key = data.get("license_key") if data.get("status") == "ready" else None+ return key if isinstance(key, str) and _KEY_RE.fullmatch(key.strip()) else None+++def poll_claim(code: str, *, interval: float = 15.0, deadline: float | None = None,+ overwrite: bool = False) -> str | None:+ """Poll until the key arrives (saved, then returned) or `deadline` passes.+ None if the deadline passed, or the key arrived but an existing key was kept+ (overwrite=False)."""+ while True:+ key = check_claim(code)+ if key:+ return key.strip() if save_license_key(key, overwrite=overwrite) else None+ if deadline is not None and time.time() + interval > deadline:+ return None+ time.sleep(interval)++def build_launch_env(license_key: str | None = None,user_env: Mapping[str, str | None] | None = None,diff --git a/dotnet/README.md b/dotnet/README.mdindex 94a3ac8..5865988 100644--- a/dotnet/README.md+++ b/dotnet/README.md@@ -101,6 +101,13 @@ dotnet add package CloakBrowserThe patched Chromium binary downloads automatically on first launch, cached under`~/.cloakbrowser` (override with `CLOAKBROWSER_CACHE_DIR`).+**License key:** every launch needs one, and a free key takes one email. The first launch+in a console asks: get a free key (opens the signup page and continues once you confirm+your email) or paste a key you have. In CI, Docker, or any run with redirected+stdin/stderr, set `CLOAKBROWSER_LICENSE_KEY` (free key at+[cloakbrowser.dev/free](https://cloakbrowser.dev/free)); a missing key then throws+`CloakBrowserLicenseError` with the signup link.+---## Project layout@@ -355,10 +362,10 @@ var page = await ctx.NewPageAsync();| `Args` | `List<string>` | `[]` | extra Chromium flags (e.g. `--fingerprint-webrtc-ip=auto`) || `Locale` | `string` | `null` | BCP 47 locale -> `--lang`, `--fingerprint-locale` || `Timezone` | `string` | `null` | IANA timezone -> `--fingerprint-timezone` |-| `Viewport` | `(int,int)` | - | window size |+| `Viewport` | `(int,int)` | - | fixed viewport size; unset = no emulated viewport (tracks the real window) || `NoViewport` | `bool` | `false` | disable viewport emulation (track the real window) || `ColorScheme` | `string` | - | `light` / `dark` |-| `LicenseKey` | `string` | `null` | CloakBrowser Pro key (or `CLOAKBROWSER_LICENSE_KEY` env / `~/.cloakbrowser/license.key`) |+| `LicenseKey` | `string` | `null` | License key, free or paid (or `CLOAKBROWSER_LICENSE_KEY` env / `~/.cloakbrowser/license.key`) || `BrowserVersion` | `string` | `null` | Pin an exact Chromium version (e.g. `"154.0.8037.57.1"`). Also reads from `CLOAKBROWSER_VERSION` env var. Paid Pro key only. || `ReleaseChannel` | `string` | `null` (`stable`) | Set to `"preview"` to opt into the Pro Preview binary channel. Also reads from `CLOAKBROWSER_RELEASE_CHANNEL`. |@@ -366,13 +373,12 @@ var page = await ctx.NewPageAsync();The wrappers are MIT, free forever. The latest binary is **free to try**:-- **Free, latest build (Chromium 156)** — the newest binary. Free with a GitHub sign-in, one concurrent session. Run `cloakbrowser login` or [grab your key](https://cloakbrowser.dev/free).+- **Free, latest build (Chromium 156)** — the newest binary. Free with your email, one concurrent session. Just launch (the first run asks), run `cloakbrowser login`, or [grab your key](https://cloakbrowser.dev/free).- **Pro** — scale to **5, 20, 200, 2,000, or more concurrent sessions**, always first on the newest patches, with hands-on support. Linux, Windows, macOS. **[See plans and pricing →](https://cloakbrowser.dev)**-- **v146** — the older build stays free on [GitHub Releases](https://github.com/CloakHQ/cloakbrowser/releases). A quick first look, but it ages fast as detection evolves.Try the latest free → **[cloakbrowser.dev/free](https://cloakbrowser.dev/free)** · Scale up on Pro → **[cloakbrowser.dev](https://cloakbrowser.dev)**-Get a key: run `cloakbrowser login` (GitHub sign-in for a free key, or paste a paid key), or set it directly via the `LicenseKey` option, the `CLOAKBROWSER_LICENSE_KEY` env var, or `~/.cloakbrowser/license.key`:+Get a key: run `cloakbrowser login` (free key by email, or paste a key you have), or set it directly via the `LicenseKey` option, the `CLOAKBROWSER_LICENSE_KEY` env var, or `~/.cloakbrowser/license.key`:```csharpawait using var browser = await CloakLauncher.LaunchAsync(new LaunchOptions@@ -381,13 +387,11 @@ await using var browser = await CloakLauncher.LaunchAsync(new LaunchOptions});```-A valid key downloads the latest Pro binary from cloakbrowser.dev; without one, the-free binary downloads from GitHub Releases. Validation is cached locally for 24h, and-the Pro binary is authenticated with the **same pinned Ed25519 signature** as the free-binary — a key whose Pro download or signature check fails surfaces a clear error-rather than silently downgrading. `Download.BinaryInfo()` exposes a `Tier` field-(`"pro"` / `"free"`); `License.ValidateLicense` / `License.LicenseInfo` mirror the-Python `validate_license` / `LicenseInfo` exports.+A valid key downloads the latest binary from cloakbrowser.dev. Validation is cached+locally for 24h, and every download is authenticated with a **pinned Ed25519+signature**: a failed download or signature check surfaces a clear error. An invalid or+expired key throws `CloakBrowserLicenseError`. `License.ValidateLicense` /+`License.LicenseInfo` mirror the Python `validate_license` / `LicenseInfo` exports.### Preview release channel@@ -405,7 +409,7 @@ Or set `CLOAKBROWSER_RELEASE_CHANNEL=preview` for all launches and CLI commands.### Rolling back to a previous binary version-Pin an exact Chromium version without downgrading the wrapper — paid Pro key only. A free GitHub key cannot pin: it ignores the pin and always gets the latest build.+Pin an exact Chromium version without downgrading the wrapper — paid Pro key only. A free key cannot pin: it ignores the pin and always gets the latest build.```csharpawait using var browser = await CloakLauncher.LaunchAsync(new LaunchOptions@@ -424,6 +428,13 @@ Or downgrade the wrapper (if a new wrapper release broke something). With a licedotnet add package CloakBrowser --version 0.6.3```+**Can I still use the old keyless v146 build?** Yes, through the last wrapper release+that runs without a key: `dotnet add package CloakBrowser --version 0.6.5`. It downloads+the old v146 build (v145 on macOS) from+[GitHub Releases](https://github.com/CloakHQ/cloakbrowser/releases), with no key. It is no+longer updated and ages fast as detection evolves, so the free key on the latest build is+the better choice.+---## `HumanConfig` reference@@ -602,12 +613,14 @@ await using var browser = await CloakLauncher.LaunchAsync(new LaunchOptions## CLIInstalled via NuGet you don't need a CLI — the binary auto-downloads on first launch-and updates in the background, and `Download.BinaryInfo()` reports the installed-version, path, and tier (`Download.EnsureBinary()` pre-fetches it on demand).+and updates on launch, and `Download.BinaryInfo()` reports the installed+version and path (`Download.EnsureBinary()` pre-fetches it on demand).When running from a clone of the repo, a small CLI does the same:```bash+dotnet run --project src/CloakBrowser.Cli -- login # free key by email, or paste a key+dotnet run --project src/CloakBrowser.Cli -- logout # remove the saved keydotnet run --project src/CloakBrowser.Cli -- install # download the binarydotnet run --project src/CloakBrowser.Cli -- info # version / path / platformdotnet run --project src/CloakBrowser.Cli -- update # check + download newer@@ -622,11 +635,10 @@ Same set as the Python wrapper:| Variable | Purpose || --- | --- |-| `CLOAKBROWSER_BINARY_PATH` | Use a local binary, skip download. Set `CLOAKBROWSER_VERSION` (or `BrowserVersion`) to that binary's exact version too, or proxy auth and headless viewport fall back to safe defaults |+| `CLOAKBROWSER_LICENSE_KEY` | Your license key (free or paid). Required wherever there is no console to ask (CI, Docker) |+| `CLOAKBROWSER_BINARY_PATH` | Use a local binary, skip download || `CLOAKBROWSER_CACHE_DIR` | Override the cache directory |-| `CLOAKBROWSER_DOWNLOAD_URL` | Override the download URL |-| `CLOAKBROWSER_AUTO_UPDATE` | Enable/disable background auto-update |-| `CLOAKBROWSER_SKIP_CHECKSUM` | Skip SHA-256 verification |+| `CLOAKBROWSER_AUTO_UPDATE` | Set to `false` to keep the cached build and skip update checks || `CLOAKBROWSER_VERSION` | Pin to an exact Chromium version for rollback (e.g. `154.0.8037.57.1`). Paid Pro key only || `CLOAKBROWSER_RELEASE_CHANNEL` | Set to `preview` to opt into the Pro Preview binary channel (default: `stable`) || `CLOAKBROWSER_GEOIP_TIMEOUT_SECONDS` | GeoIP HTTP timeout |@@ -697,4 +709,4 @@ classes share one serial xunit collection (`RealBrowser`).## License- **Wrapper code** — MIT, same as the upstream CloakBrowser project.-- **CloakBrowser binary** (compiled Chromium) — no redistribution. v146 and earlier: free, no key. v148 and later: requires a license key, free with a GitHub sign-in (one concurrent session) or a paid [CloakBrowser Pro](https://cloakbrowser.dev) subscription. See [BINARY-LICENSE.md](https://github.com/CloakHQ/CloakBrowser/blob/main/BINARY-LICENSE.md).+- **CloakBrowser binary** (compiled Chromium) — requires a license key: free with your email (one concurrent session), or a paid [CloakBrowser Pro](https://cloakbrowser.dev) subscription. Free for personal and commercial use, no redistribution. See [BINARY-LICENSE.md](https://github.com/CloakHQ/CloakBrowser/blob/main/BINARY-LICENSE.md).diff --git a/dotnet/src/CloakBrowser.Cli/Program.cs b/dotnet/src/CloakBrowser.Cli/Program.csindex 624dad4..19953b7 100644--- a/dotnet/src/CloakBrowser.Cli/Program.cs+++ b/dotnet/src/CloakBrowser.Cli/Program.cs@@ -1,4 +1,3 @@-using System.Diagnostics;using System.Text.Json;using CloakBrowser;@@ -6,8 +5,8 @@ using CloakBrowser;// Direct port of Python cloakbrowser/__main__.py.//// Usage:-// cloakbrowser login # Save a license key (or get a free key via GitHub)-// cloakbrowser logout # Remove the saved license key (revert to free binary)+// cloakbrowser login # Save a license key (or get a free key by email)+// cloakbrowser logout # Remove the saved license key// cloakbrowser install # Download binary (with progress)// cloakbrowser info # Environment + binary diagnostics (--quick, --json)// cloakbrowser doctor # Alias for info@@ -15,9 +14,7 @@ using CloakBrowser;// cloakbrowser clear-cache # Remove cached binariesconst string UpgradeHint = "For more than one concurrent session → https://cloakbrowser.dev";-const string FreeLatestHint =- "Get the latest binary free → run 'cloakbrowser login' or https://cloakbrowser.dev/free";-const string FreeLoginUrl = "https://cloakbrowser.dev/api/license/free/github/start";+const string NoKeyHint = "Get a free key → run 'cloakbrowser login'";// Route CloakBrowser logs to stderr at Info level (clean output).CloakLog.MinLevel = CloakLogLevel.Info;@@ -43,8 +40,7 @@ tryCmdInfo(rest);break;case "update":- await CmdUpdate();- break;+ return await CmdUpdate();case "clear-cache":CmdClearCache();break;@@ -227,16 +223,13 @@ static void PrintDiagnostics(Dictionary<string, object?> diag)bool validated = lic.TryGetValue("valid", out var validObj) && validObj is true;if (tier == "free" && validated){- // Validated free-tier key (GitHub login): the latest binary, 1 session.Console.WriteLine("License: Free (latest binary, 1 concurrent session)");Console.WriteLine($" {UpgradeHint}");}- else if (tier == "free")+ else if (tier == "none"){- // Keyless: running the older free binary — invite the free-latest login.- Console.WriteLine("License: Free (no key)");- Console.WriteLine($" {FreeLatestHint}");- Console.WriteLine($" {UpgradeHint}");+ Console.WriteLine("License: none (a launch needs a key)");+ Console.WriteLine($" {NoKeyHint}");}else if (lic.ContainsKey("error")){@@ -280,36 +273,21 @@ static void PrintDiagnostics(Dictionary<string, object?> diag)}}-static async Task CmdUpdate()+static async Task<int> CmdUpdate(){- CloakLog.Info("Checking for updates...");-- // A valid Pro license updates the Pro binary; everyone else updates free.- // Mirrors Diagnostics.ResolveLicense: a custom download URL disables Pro routing.string? key = License.ResolveLicenseKey();- if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL"))) key = null;- bool entitledPro = false;- if (!string.IsNullOrEmpty(key))+ if (string.IsNullOrEmpty(key) || License.ValidateLicense(key)?.Valid != true){- try { entitledPro = License.ValidateLicense(key!)?.Valid == true; }- catch { entitledPro = false; }+ Console.Error.WriteLine($"No valid license key. {NoKeyHint}");+ return 1;}- string? newVersion;- string label;- if (entitledPro)- {- newVersion = await Download.CheckForProUpdateAsync(key!).ConfigureAwait(false);- label = "Pro Chromium";- }- else- {- newVersion = await Download.CheckForUpdateAsync().ConfigureAwait(false);- label = "Chromium";- }+ CloakLog.Info("Checking for updates...");+ string? newVersion = await Download.CheckForProUpdateAsync(key).ConfigureAwait(false);Console.WriteLine(newVersion != null- ? $"Updated to {label} {newVersion}"+ ? $"Updated to Chromium {newVersion}": "Already up to date.");+ return 0;}static void CmdClearCache()@@ -323,23 +301,29 @@ static void CmdClearCache()Console.WriteLine("Cache cleared.");}-// Activate any key. `login <key>` saves a pasted key; bare `login` prompts to-// paste a key or press ENTER to get a free key via GitHub. Mirrors Python cmd_login.+// Activate any key. `login <key>` saves a pasted key; bare `login` shows the same+// menu as a no-key launch: get a free key by email, or paste one. Mirrors Python cmd_login.static int CmdLogin(string[] flags){string key = (flags.Length > 0 ? flags[0] : "").Trim();if (string.IsNullOrEmpty(key)){- if (Console.IsInputRedirected)+ // Same check as a launch: the menu is written to stderr, so both must be a terminal.+ if (!Download.CanPrompt()){Console.Error.WriteLine("Usage: cloakbrowser login <key> (or run it interactively for a free key).");return 2;}- Console.Write("Paste your license key, or press ENTER to get a free key via GitHub: ");- string entered = (Console.ReadLine() ?? "").Trim();- key = string.IsNullOrEmpty(entered) ? PromptFreeGithubLogin() : entered;+ try+ {+ key = Download.PromptLicenseKey();+ }+ catch (EndOfStreamException)+ {+ key = "";+ }}if (string.IsNullOrEmpty(key))@@ -361,7 +345,15 @@ static int CmdLogin(string[] flags)return 1;}- SaveLicenseKey(key);+ try+ {+ License.SaveLicenseKey(key);+ }+ catch (ArgumentException)+ {+ Console.Error.WriteLine("That is not a CloakBrowser license key (they start with cb_). Nothing was saved.");+ return 1;+ }if (info.Plan == "free"){Console.WriteLine(@@ -375,9 +367,12 @@ static int CmdLogin(string[] flags)return 0;}-// Remove the saved license key (revert to the free binary). Mirrors Python cmd_logout.+// Remove the saved license key. Mirrors Python cmd_logout.static int CmdLogout(){+ // A pending claim code would quietly reinstall a key on the next launch.+ try { File.Delete(Path.Combine(Config.GetCacheDir(), ".free_claim")); }+ catch (IOException) { }string keyFile = Path.Combine(Config.GetCacheDir(), "license.key");if (File.Exists(keyFile)){@@ -390,7 +385,7 @@ static int CmdLogout()Console.Error.WriteLine($"Could not remove {keyFile}: {e.Message}");return 1;}- Console.WriteLine("Logged out. Removed the saved key; launches revert to the free binary.");+ Console.WriteLine("Logged out. Removed the saved key; launches need a key again.");}else{@@ -399,30 +394,6 @@ static int CmdLogout()return 0;}-// Persist a validated key to <cache_dir>/license.key.-static void SaveLicenseKey(string key)-{- string cacheDir = Config.GetCacheDir();- Directory.CreateDirectory(cacheDir);- string keyFile = Path.Combine(cacheDir, "license.key");- File.WriteAllText(keyFile, key.Trim() + "\n");-}--// Open the GitHub free-key page and read back the emailed key.-static string PromptFreeGithubLogin()-{- Console.WriteLine($"Opening GitHub sign-in: {FreeLoginUrl}");- try- {- Process.Start(new ProcessStartInfo(FreeLoginUrl) { UseShellExecute = true });- }- catch { /* best-effort — the URL is printed above for manual navigation */ }- Console.WriteLine("If your browser did not open, visit the URL above and authorize with GitHub.");- Console.WriteLine("We'll email your free CloakBrowser key to your GitHub email.");- Console.Write("Paste the key from that email here: ");- return (Console.ReadLine() ?? "").Trim();-}-static string TitleCase(string s) =>string.IsNullOrEmpty(s) ? s : char.ToUpperInvariant(s[0]) + s.Substring(1);@@ -433,8 +404,8 @@ static void PrintHelp()Console.WriteLine("Manage the CloakBrowser stealth Chromium binary.");Console.WriteLine();Console.WriteLine("commands:");- Console.WriteLine(" login Save a license key (or get a free key via GitHub)");- Console.WriteLine(" logout Remove the saved license key (revert to free binary)");+ Console.WriteLine(" login Save a license key (or get a free key by email)");+ Console.WriteLine(" logout Remove the saved license key");Console.WriteLine(" install Download the Chromium binary");Console.WriteLine(" info Environment + binary diagnostics (--quick, --json)");Console.WriteLine(" doctor Alias for info");diff --git a/dotnet/src/CloakBrowser/CloakLauncher.cs b/dotnet/src/CloakBrowser/CloakLauncher.csindex 0e009e8..8718c3f 100644--- a/dotnet/src/CloakBrowser/CloakLauncher.cs+++ b/dotnet/src/CloakBrowser/CloakLauncher.cs@@ -28,24 +28,21 @@ public static class CloakLauncherreleaseChannel: options.ReleaseChannel).ConfigureAwait(false);var (timezone, locale, exitIp) = await MaybeResolveGeoIpAsync(options.GeoIp, options.Proxy, options.Timezone, options.Locale, options.Args).ConfigureAwait(false);- var proxyResolution = ProxyResolver.Resolve(- options.Proxy, options.BrowserVersion, options.LicenseKey, options.ReleaseChannel);+ var proxyResolution = ProxyResolver.Resolve(options.Proxy);var args = await ResolveWebRtcArgsAsync(options.Args, options.Proxy).ConfigureAwait(false);args = MaybeAppendWebRtcExitIp(args, exitIp);var combined = new List<string>(args ?? new List<string>());combined.AddRange(proxyResolution.ExtraArgs);var chromeArgs = BuildArgs(options.StealthArgs, combined, timezone, locale, options.Headless, options.ExtensionPaths,- startMaximized: Config.BinarySupportsMaximizedWindow(- options.LicenseKey, options.BrowserVersion, options.ReleaseChannel)- && !options.SuppressMaximize);+ startMaximized: !options.SuppressMaximize);MaybeWarnWindowsFonts(chromeArgs);CloakLog.Debug($"Launching stealth Chromium (headless={options.Headless}, args={chromeArgs.Count})");// Per-launch denial file: the binary records a post-handshake license// denial here so NewPage/NewContext can surface it (see LicenseGuard).- // Only when a key is in play — keyless runs the unenforced free binary.+ // Only when a key is in play (none only with a CLOAKBROWSER_BINARY_PATH override).var denialPath = License.ResolveLicenseKey(options.LicenseKey) != null? License.MintDenialFile(): null;@@ -80,13 +77,10 @@ public static class CloakLaunchervar humanCfg = options.Humanize? HumanConfigFactory.Resolve(options.HumanPreset, options.HumanConfig): null;- // Pass headless so headed handles default new pages/contexts to NoViewport- // (track the real window - see CloakBrowserHandle.ApplyDefaultNoViewport).- // headlessNoViewport extends that default to headless on newer binaries.- bool headlessNoViewport = Config.BinarySupportsHeadlessNoViewport(- options.LicenseKey, options.BrowserVersion, options.ReleaseChannel);+ // New pages/contexts default to NoViewport: headed tracks the real window,+ // headless reports coherent dimensions natively (see ViewportDefaults).return new CloakBrowserHandle(- playwright, browser, options.Humanize, humanCfg, options.Headless, headlessNoViewport, denialPath);+ playwright, browser, options.Humanize, humanCfg, denialPath);}catch{@@ -171,8 +165,7 @@ public static class CloakLauncherreleaseChannel: options.ReleaseChannel).ConfigureAwait(false);var (timezone, locale, exitIp) = await MaybeResolveGeoIpAsync(options.GeoIp, options.Proxy, options.Timezone, options.Locale, options.Args).ConfigureAwait(false);- var proxyResolution = ProxyResolver.Resolve(- options.Proxy, options.BrowserVersion, options.LicenseKey, options.ReleaseChannel);+ var proxyResolution = ProxyResolver.Resolve(options.Proxy);var args = await ResolveWebRtcArgsAsync(options.Args, options.Proxy).ConfigureAwait(false);args = MaybeAppendWebRtcExitIp(args, exitIp);args = Config.PersistentSeedArgs(userDataDir, options.StealthArgs, args);@@ -180,9 +173,7 @@ public static class CloakLaunchervar combined = new List<string>(args ?? new List<string>());combined.AddRange(proxyResolution.ExtraArgs);var chromeArgs = BuildArgs(options.StealthArgs, combined, timezone, locale, options.Headless, options.ExtensionPaths,- startMaximized: Config.BinarySupportsMaximizedWindow(- options.LicenseKey, options.BrowserVersion, options.ReleaseChannel)- && !options.NoViewport && options.Viewport == null);+ startMaximized: !options.NoViewport && options.Viewport == null);MaybeWarnWindowsFonts(chromeArgs);CloakLog.Debug($"Launching persistent stealth Chromium (headless={options.Headless}, user_data_dir={userDataDir})");@@ -420,8 +411,6 @@ public static class CloakLauncher// Open maximized (real Chrome overwhelmingly runs maximized) so the window// fills the spoofed screen. Skipped if the caller chose a window geometry.- // Gated to binaries where this stays coherent (see BinarySupportsMaximizedWindow)- // — below the gate it would make outerWidth < innerWidth.if (startMaximized&& !seen.ContainsKey("--start-maximized")&& !seen.ContainsKey("--window-size")@@ -589,8 +578,8 @@ public static class CloakLauncher/// <summary>/// Resolve the viewport for a context. Headed: no emulated viewport so the page/// tracks the real window (CDP viewport emulation forces outerWidth < innerWidth =- /// a physically impossible window = bot tell). Headless: a fixed DEFAULT_VIEWPORT- /// stays coherent (outer == inner) and keeps dimensions deterministic. An explicit+ /// a physically impossible window = bot tell). Headless: the binary reports coherent+ /// dimensions natively, so no emulated viewport either. An explicit/// <see cref="LaunchContextOptions.NoViewport"/> or <see cref="LaunchContextOptions.Viewport"/>/// is always honored. Port of Python <c>_resolve_context_viewport</c>./// </summary>@@ -600,14 +589,9 @@ public static class CloakLauncherreturn ViewportSize.NoViewport;if (options.Viewport != null)return new ViewportSize { Width = options.Viewport.Value.Width, Height = options.Viewport.Value.Height };- // Viewport unset: headed tracks the real window; headless on a newer binary also- // tracks it (coherent dimensions natively), older headless gets the fixed default.- bool headlessNoViewport = options.Headless- && Config.BinarySupportsHeadlessNoViewport(- options.LicenseKey, options.BrowserVersion, options.ReleaseChannel);- return options.Headless && !headlessNoViewport- ? new ViewportSize { Width = Config.DefaultViewportWidth, Height = Config.DefaultViewportHeight }- : ViewportSize.NoViewport;+ // Viewport unset: headed tracks the real window; headless reports coherent+ // dimensions natively.+ return ViewportSize.NoViewport;}private static BrowserNewContextOptions BuildContextOptions(LaunchContextOptions options)diff --git a/dotnet/src/CloakBrowser/Config.cs b/dotnet/src/CloakBrowser/Config.csindex 07aed3c..43392e8 100644--- a/dotnet/src/CloakBrowser/Config.cs+++ b/dotnet/src/CloakBrowser/Config.cs@@ -9,24 +9,6 @@ namespace CloakBrowser;/// </summary>public static class Config{- // ------------------------------------------------------------------------ // Chromium version shipped with this release.- // Different platforms may ship different versions during transition periods.- // ChromiumVersion is the latest across all platforms (for display/reference).- // Use GetChromiumVersion() for the current platform's actual version.- // ------------------------------------------------------------------------ public const string ChromiumVersion = "146.0.7680.177.5";-- public static readonly IReadOnlyDictionary<string, string> PlatformChromiumVersions =- new Dictionary<string, string>- {- ["linux-x64"] = "146.0.7680.177.5",- ["linux-arm64"] = "146.0.7680.177.3",- ["darwin-arm64"] = "145.0.7632.109.2",- ["darwin-x64"] = "145.0.7632.109.2",- ["windows-x64"] = "146.0.7680.177.5",- };-// -----------------------------------------------------------------------// Ed25519 public keys for verifying downloaded binaries.//@@ -50,16 +32,6 @@ public static class Configpublic static readonly string[] IgnoreDefaultArgs ={ "--enable-automation", "--enable-unsafe-swiftshader" };- // ------------------------------------------------------------------------ // Default viewport - used for HEADLESS only (headed launches use no_viewport- // so the page tracks the real window). Headless has no window chrome, so a- // fixed viewport stays coherent (outer == inner) and gives deterministic- // dimensions. Models a maximized Chrome on 1080p Windows: screen=1920x1080,- // innerHeight=947 (minus ~85px Chrome UI: tabs + address bar + bookmarks).- // ------------------------------------------------------------------------ public const int DefaultViewportWidth = 1920;- public const int DefaultViewportHeight = 947;-private static readonly Random _rng = new();public const int SeedMin = 10000;@@ -117,7 +89,7 @@ public static class Config/// concurrent callers can replace each other (seen on macOS); POSIX link() fails/// atomically with EEXIST instead. Windows MoveFileEx without REPLACE_EXISTING is atomic./// </summary>- private static void PublishNoReplace(string tmp, string file, byte[] content)+ internal static void PublishNoReplace(string tmp, string file, byte[] content, bool ownerOnly = false){if (OperatingSystem.IsWindows()){@@ -134,14 +106,20 @@ public static class Config// never overwrites. ponytail: a concurrent reader can catch the file empty// here and regenerate; link() avoids that window.CloakLog.Debug("Hard link unsupported for {0} (errno {1}); using exclusive create", file, errno);- try { WriteSynced(file, content); }+ try { WriteSynced(file, content, ownerOnly); }catch (IOException) when (File.Exists(file)) { }}- /// <summary>Create <paramref name="file"/> exclusively (throws if present), write, flush to disk.</summary>- private static void WriteSynced(string file, byte[] content)+ /// <summary>+ /// Create <paramref name="file"/> exclusively (throws if present), write, flush to disk.+ /// <paramref name="ownerOnly"/> creates it 0600 (secrets such as the claim code).+ /// </summary>+ private static void WriteSynced(string file, byte[] content, bool ownerOnly = false){- using var fs = new FileStream(file, FileMode.CreateNew, FileAccess.Write);+ var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write };+ if (ownerOnly && !OperatingSystem.IsWindows())+ options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;+ using var fs = new FileStream(file, options);fs.Write(content, 0, content.Length);fs.Flush(flushToDisk: true);}@@ -223,21 +201,6 @@ public static class Configreturn baseArgs;}- // ------------------------------------------------------------------------ // Platform detection- // ------------------------------------------------------------------------- /// <summary>Platforms with pre-built binaries available for download.</summary>- public static IReadOnlySet<string> AvailablePlatforms =>- new HashSet<string>(PlatformChromiumVersions.Keys);-- /// <summary>Return the Chromium version for the current platform.</summary>- public static string GetChromiumVersion()- {- var tag = GetPlatformTag();- return PlatformChromiumVersions.TryGetValue(tag, out var v) ? v : ChromiumVersion;- }-// -----------------------------------------------------------------------// Version pinning// -----------------------------------------------------------------------@@ -340,20 +303,14 @@ public static class Configreturn Path.Combine(home, ".cloakbrowser");}- /// <summary>Return the directory for a Chromium version binary.</summary>- /// <param name="version">Version string, or null for the platform default.</param>- /// <param name="pro">When true, use the Pro-specific cache dir (<c>chromium-{v}-pro</c>).</param>- public static string GetBinaryDir(string? version = null, bool pro = false)- {- var v = version ?? GetChromiumVersion();- var suffix = pro ? "-pro" : "";- return Path.Combine(GetCacheDir(), $"chromium-{v}{suffix}");- }+ /// <summary>Return the cache directory for a Chromium build (kept as <c>chromium-{v}-pro</c> so existing caches stay valid).</summary>+ public static string GetBinaryDir(string version) =>+ Path.Combine(GetCacheDir(), $"chromium-{version}-pro");/// <summary>Return the expected path to the chrome executable.</summary>- public static string GetBinaryPath(string? version = null, bool pro = false)+ public static string GetBinaryPath(string version){- var binaryDir = GetBinaryDir(version, pro);+ var binaryDir = GetBinaryDir(version);if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))return Path.Combine(binaryDir, "Chromium.app", "Contents", "MacOS", "Chromium");@@ -363,77 +320,26 @@ public static class Config}/// <summary>- /// Raise a clear error if no pre-built binary exists for this platform.- /// Skipped when <c>CLOAKBROWSER_BINARY_PATH</c> is set (user has their own build).- /// </summary>- public static void CheckPlatformAvailable()- {- if (GetLocalBinaryOverride() != null)- return;-- var tag = GetPlatformTag(); // throws if platform unsupported entirely- if (!AvailablePlatforms.Contains(tag))- {- var available = string.Join(", ", AvailablePlatforms.OrderBy(x => x));- throw new PlatformNotSupportedException(- $"\nCloakBrowser - Pre-built binaries are currently only available for: {available}.\n\n" +- "To use CloakBrowser now, set CLOAKBROWSER_BINARY_PATH to a local Chromium binary.");- }- }-- /// <summary>- /// Return the best available version: auto-updated if available, else platform default.- /// Reads a platform-scoped marker file from the cache directory.- /// When <paramref name="pro"/> is true, reads from the Pro-specific marker and returns- /// <c>null</c> when no cached Pro binary matches it. A valid Pro license must NEVER fall- /// back to the free binary, so there is deliberately no free-version fallback for Pro —- /// callers treat <c>null</c> as "resolve the latest Pro version from the server".+ /// Return the cached build the channel's marker names, or null. Null means nothing+ /// usable is cached: callers resolve the latest build from the server instead./// </summary>- public static string? GetEffectiveVersion(bool pro = false, string? releaseChannel = null)+ public static string? GetEffectiveVersion(string? releaseChannel = null){- var baseVersion = GetChromiumVersion();- var cache = GetCacheDir();-- if (pro)+ var markerPrefix = NormalizeReleaseChannel(releaseChannel) == "preview"+ ? "latest_pro_version_preview"+ : "latest_pro_version";+ var marker = Path.Combine(GetCacheDir(), $"{markerPrefix}_{GetPlatformTag()}");+ try{- var markerPrefix = NormalizeReleaseChannel(releaseChannel) == "preview"- ? "latest_pro_version_preview"- : "latest_pro_version";- var proMarker = Path.Combine(cache, $"{markerPrefix}_{GetPlatformTag()}");- if (File.Exists(proMarker))- {- try- {- var version = File.ReadAllText(proMarker).Trim();- // Match launch's ProBinaryReady (exists AND executable) so `info`- // never reports a build that launch would reject.- if (!string.IsNullOrEmpty(version) && IsExecutableFile(GetBinaryPath(version, pro: true)))- return version;- }- catch (Exception ex) when (ex is FormatException or IOException) { }- }- return null;+ var version = File.ReadAllText(marker).Trim();+ // Match launch's ProBinaryReady (exists AND executable) so `info`+ // never reports a build that launch would reject.+ if (!string.IsNullOrEmpty(version) && IsExecutableFile(GetBinaryPath(version)))+ return version;}-- foreach (var name in new[] { $"latest_version_{GetPlatformTag()}", "latest_version" })- {- var marker = Path.Combine(cache, name);- if (File.Exists(marker))- {- try- {- var version = File.ReadAllText(marker).Trim();- if (!string.IsNullOrEmpty(version) && VersionNewer(version, baseVersion))- {- var binary = GetBinaryPath(version);- if (File.Exists(binary))- return version;- }- }- catch (Exception ex) when (ex is FormatException or IOException) { }- }- }- return baseVersion;+ catch (IOException) { }+ catch (UnauthorizedAccessException) { }+ return null;}/// <summary>True when a binary exists and is executable. Canonical check shared with Download.</summary>@@ -468,13 +374,7 @@ public static class Config// Download URL// ------------------------------------------------------------------------ public static string DownloadBaseUrl =>- Environment.GetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL") ?? "https://cloakbrowser.dev";-- public const string GitHubApiUrl = "https://api.github.com/repos/CloakHQ/cloakbrowser/releases";-- public const string GitHubDownloadBaseUrl =- "https://github.com/CloakHQ/cloakbrowser/releases/download";+ public const string DownloadBaseUrl = "https://cloakbrowser.dev";/// <summary>Return the archive extension for the current platform (.zip for Windows, .tar.gz otherwise).</summary>public static string GetArchiveExt() =>@@ -487,20 +387,6 @@ public static class Configreturn $"cloakbrowser-{t}{GetArchiveExt()}";}- /// <summary>Return the full download URL for the current platform's binary archive.</summary>- public static string GetDownloadUrl(string? version = null)- {- var v = version ?? GetChromiumVersion();- return $"{DownloadBaseUrl}/chromium-v{v}/{GetArchiveName()}";- }-- /// <summary>Return the GitHub Releases fallback URL for the binary archive.</summary>- public static string GetFallbackDownloadUrl(string? version = null)- {- var v = version ?? GetChromiumVersion();- return $"{GitHubDownloadBaseUrl}/chromium-v{v}/{GetArchiveName()}";- }-// -----------------------------------------------------------------------// CloakBrowser Pro download URLs (cloakbrowser.dev, license-key authed)// -----------------------------------------------------------------------@@ -531,151 +417,4 @@ public static class Config/// </summary>public static string? GetLocalBinaryOverride() =>Environment.GetEnvironmentVariable("CLOAKBROWSER_BINARY_PATH");-- // First Chromium build that reports coherent headless dimensions without an- // emulated viewport. On these binaries the wrapper launches headless with no- // viewport; older binaries need a fixed default viewport to stay coherent.- // null => not shipped yet; feature off, behavior byte-identical to today.- // TODO: set to the chromium version string that first ships it.- public static readonly string? HeadlessNoViewportMinVersion = "148.0.7778.215.4";-- /// <summary>- /// Whether headless can launch without an emulated viewport on the resolved binary.- /// Only binaries at or above <see cref="HeadlessNoViewportMinVersion"/> qualify; older- /// ones keep the fixed default viewport. A local override binary- /// (<c>CLOAKBROWSER_BINARY_PATH</c>) is unknown-version, so stay on the safe path.- /// </summary>- public static bool BinarySupportsHeadlessNoViewport(- string? licenseKey = null, string? browserVersion = null, string? releaseChannel = null)- {- if (HeadlessNoViewportMinVersion == null)- return false;- // A declared version (browserVersion arg OR CLOAKBROWSER_VERSION env) wins even- // under a local override — the caller asserts the version (also how internal builds- // opt in). Only an override with no declared version stays on the safe path.- string? declared;- try- {- declared = NormalizeRequestedVersion(browserVersion);- }- catch- {- declared = null;- }- string? version;- if (!string.IsNullOrEmpty(declared))- {- version = declared!;- }- else if (GetLocalBinaryOverride() != null)- {- return false;- }- else- {- bool pro = !string.IsNullOrEmpty(License.ResolveLicenseKey(licenseKey));- version = GetEffectiveVersion(pro, releaseChannel);- }- // No cached Pro build resolvable (GetEffectiveVersion returned null) → fail safe.- if (version == null) return false;- try- {- return !VersionNewer(HeadlessNoViewportMinVersion, version);- }- catch- {- return false;- }- }-- /// <summary>- /// Whether the wrapper may auto-add <c>--start-maximized</c>. Gated on the same- /// threshold as the no_viewport shim: only binaries whose headless surface-fix +- /// headed screen-clamp make a maximized window coherent (<c>outer == screen</c>).- /// Below it, maximizing headless while the CDP viewport stays at 1280x720 yields- /// <c>outerWidth < innerWidth</c> — a bot tell — so the flag must NOT be added.- /// Shares <see cref="HeadlessNoViewportMinVersion"/>; own name so the two can- /// diverge later. Python, JS and .NET mirror this gate.- /// </summary>- public static bool BinarySupportsMaximizedWindow(- string? licenseKey = null, string? browserVersion = null, string? releaseChannel = null)- => BinarySupportsHeadlessNoViewport(licenseKey, browserVersion, releaseChannel);-- // First Chromium build, per platform, whose binary can take inline HTTP proxy- // credentials (Chromium-native --proxy-server=http://user:pass@host). Below the- // floor the wrapper MUST route credentialed HTTP/HTTPS proxies through- // Playwright's proxy object — an older binary treats the user:pass@ authority as- // an invalid proxy host and drops proxy auth (#182). A single global threshold- // can't model this: the capability landed in different build lineages at different- // points (linux-x64/windows-x64 at 146.0.7680.177.5, but the free macOS 145.x and- // linux-arm64 146.0.7680.177.3 floors predate it, qualifying only once they resolve- // to a Pro/newer 148+ build). Platforms absent from this map are never-inline.- public static readonly IReadOnlyDictionary<string, string> HttpProxyInlineAuthMinVersion =- new Dictionary<string, string>- {- ["linux-x64"] = "146.0.7680.177.5",- ["windows-x64"] = "146.0.7680.177.5",- ["linux-arm64"] = "148.0.7778.215.3",- ["darwin-arm64"] = "148.0.7778.215.3",- ["darwin-x64"] = "148.0.7778.215.3",- };-- /// <summary>- /// Whether the resolved binary accepts inline HTTP proxy credentials. The- /// capability is a function of the binary version; <paramref name="licenseKey"/>- /// only resolves which version launches (Pro build vs free default), exactly like- /// <see cref="BinarySupportsHeadlessNoViewport"/>. A declared pin wins, else a valid- /// Pro license resolves to the Pro build (which ships the patch), else the free- /// per-platform default — then it compares to this platform's floor. Below the- /// floor, credentialed HTTP proxies fall back to Playwright's proxy object. A local- /// override with no declared version is unknown-version, so stay on the safe- /// fallback. Python, JS and .NET mirror this gate.- /// </summary>- public static bool BinarySupportsHttpProxyInlineAuth(- string? licenseKey = null, string? browserVersion = null, string? releaseChannel = null)- {- string tag;- try- {- tag = GetPlatformTag();- }- catch- {- return false;- }- if (!HttpProxyInlineAuthMinVersion.TryGetValue(tag, out var floor))- return false;- string? declared;- try- {- declared = NormalizeRequestedVersion(browserVersion);- }- catch- {- declared = null;- }- string? version;- if (!string.IsNullOrEmpty(declared))- {- version = declared!;- }- else if (GetLocalBinaryOverride() != null)- {- return false;- }- else- {- bool pro = !string.IsNullOrEmpty(License.ResolveLicenseKey(licenseKey));- version = GetEffectiveVersion(pro, releaseChannel);- }- if (version == null) return false;- try- {- return !VersionNewer(floor, version);- }- catch- {- return false;- }- }}diff --git a/dotnet/src/CloakBrowser/Diagnostics.cs b/dotnet/src/CloakBrowser/Diagnostics.csindex 57d45dd..1f1f158 100644--- a/dotnet/src/CloakBrowser/Diagnostics.cs+++ b/dotnet/src/CloakBrowser/Diagnostics.cs@@ -150,12 +150,8 @@ internal static class Diagnosticsprivate static (Dictionary<string, object?> license, bool entitledPro) ResolveLicense(){string? key = License.ResolveLicenseKey();- // EnsureBinary disables Pro routing when a custom download URL is set, so the- // diagnostic must report free too (matches Download.cs).- if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL")))- key = null;if (string.IsNullOrEmpty(key))- return (new Dictionary<string, object?> { ["tier"] = "free" }, false);+ return (new Dictionary<string, object?> { ["tier"] = "none" }, false);try{LicenseInfo? lic = License.ValidateLicense(key!);@@ -178,8 +174,7 @@ internal static class Diagnostics}// Describe the binary EnsureBinary would actually launch (no download).- // Unlike Download.BinaryInfo(), a Pro binary on disk is only reported when- // the license entitles Pro — so a keyless run shows the free binary.+ // Without a valid key nothing launches, so only the cached build is reported.private static Dictionary<string, object?> EffectiveBinary(bool entitledPro, bool quick = false){string? over = Config.GetLocalBinaryOverride();@@ -191,7 +186,6 @@ internal static class Diagnostics["latest_version"] = null,["pinned"] = false,["tier"] = "override",- ["bundled_version"] = Config.ChromiumVersion,["path"] = over,["installed"] = File.Exists(over),["cache_dir"] = null,@@ -218,7 +212,7 @@ internal static class Diagnostics{// Mirror EnsureBinary: report what the next launch resolves to, while// CLOAKBROWSER_AUTO_UPDATE=false retains an installed channel build.- installedVersion = Config.GetEffectiveVersion(true, requestedChannel);+ installedVersion = Config.GetEffectiveVersion(requestedChannel);var autoUpdate = (Environment.GetEnvironmentVariable("CLOAKBROWSER_AUTO_UPDATE") ?? "true").ToLowerInvariant();bool updatesEnabled = autoUpdate != "false";if (installedVersion != null && !updatesEnabled)@@ -230,10 +224,10 @@ internal static class Diagnostics}else{- version = Config.GetEffectiveVersion(false);+ version = Config.GetEffectiveVersion(requestedChannel);installedVersion = version;}- string? path = version != null ? Config.GetBinaryPath(version, entitledPro) : null;+ string? path = version != null ? Config.GetBinaryPath(version) : null;return new Dictionary<string, object?>{["version"] = version,@@ -243,11 +237,10 @@ internal static class Diagnostics["channel_fallback"] = latestRelease?.Fallback ?? false,["installed_version"] = installedVersion,["pinned"] = !string.IsNullOrEmpty(requested),- ["tier"] = entitledPro ? "pro" : "free",- ["bundled_version"] = Config.ChromiumVersion,+ ["tier"] = entitledPro ? "pro" : "none",["path"] = path,["installed"] = path != null && File.Exists(path),- ["cache_dir"] = version != null ? Config.GetBinaryDir(version, entitledPro) : null,+ ["cache_dir"] = version != null ? Config.GetBinaryDir(version) : null,["override"] = null,};}diff --git a/dotnet/src/CloakBrowser/Download.cs b/dotnet/src/CloakBrowser/Download.csindex eb92cff..a25a213 100644--- a/dotnet/src/CloakBrowser/Download.cs+++ b/dotnet/src/CloakBrowser/Download.cs@@ -9,13 +9,11 @@ namespace CloakBrowser;/// <summary>Info about the current binary installation (returned by <see cref="Download.BinaryInfo"/>).</summary>public sealed record CloakBinaryInfo(- string Version,- string Tier,- string BundledVersion,+ string? Version,string Platform,- string BinaryPath,+ string? BinaryPath,bool Installed,- string CacheDir,+ string? CacheDir,string DownloadUrl);/// <summary>@@ -24,8 +22,8 @@ public sealed record CloakBinaryInfo(////// Distinct from transient download/network errors: a verification failure is a/// tampering signal and MUST surface, never silently fall back to another binary.-/// The Pro routing in <see cref="Download.EnsureBinaryAsync"/> re-raises this rather-/// than downgrading to the free tier.+/// The routing in <see cref="Download.EnsureBinaryAsync"/> re-raises this rather+/// than falling back to a cached build./// </summary>public sealed class BinaryVerificationError : Exception{@@ -40,11 +38,8 @@ public sealed class BinaryVerificationError : Exception/// </summary>public static class Download{- // Auto-update check interval (1 hour).- private const int UpdateCheckInterval = 3600;-- // Free-tier welcome banner re-show interval (1 day, seconds). Free users see- // the "get the latest free" invite again after this gap; Pro users see it only+ // Free-key welcome banner re-show interval (1 day, seconds). Free users see+ // the "more sessions" invite again after this gap; Pro users see it only// once (see ShowWelcome).internal const long WelcomeFreeInterval = 24L * 3600;@@ -63,7 +58,8 @@ public static class Downloadprivate const int SharingViolationHResult = unchecked((int)0x80070020);private const int LockViolationHResult = unchecked((int)0x80070021);- private static readonly HttpClient Http = CreateHttpClient();+ // Not readonly so tests can swap in an HttpClient backed by a fake handler.+ internal static HttpClient Http = CreateHttpClient();private static HttpClient CreateHttpClient(){@@ -83,9 +79,6 @@ public static class Download/// <summary>Overrides the pinned signing keys for tests. Null -> use <see cref="Config.BinarySigningPubkeys"/>.</summary>internal static IReadOnlyList<string>? SigningPubkeysOverride;- /// <summary>Overrides the fetched (manifest, sig) pair for tests. Null -> fetch over HTTP.</summary>- internal static Func<string?, (byte[] Manifest, byte[] Sig)?>? SignedManifestOverride;-/// <summary>Overrides the fetched Pro (manifest, sig) pair for tests. Null -> fetch over HTTP.</summary>internal static Func<string, (byte[] Manifest, byte[] Sig)?>? ProSignedManifestOverride;@@ -94,10 +87,6 @@ public static class Download// ------------------------------------------------------------------------ // Pro Chromium major shown in the free-tier welcome banner. Bump at each Pro- // major release (there is no local constant to derive it from - the live Pro- // version comes from the network, which we don't call just to print a banner).- private const string ProMajor = "155";/// <summary>/// Whether the welcome banner should be shown now. Pro: once ever (only when@@ -141,15 +130,14 @@ public static class Download/// <summary>/// Show the launch welcome banner. A marker file gates the cadence: a paid- /// (Pro) key shows once ever; free (keyless or a free GitHub key) re-shows- /// every <see cref="WelcomeFreeInterval"/>. Mirrors Python <c>_show_welcome(tier)</c>.+ /// (Pro) key shows once ever; a free key re-shows every+ /// <see cref="WelcomeFreeInterval"/>. Mirrors Python <c>_show_welcome(tier)</c>.////// <paramref name="tier"/>:- /// "pro" — a paid license key (Pro banner + support address)- /// "free" — a free GitHub key (latest binary, one concurrent session)- /// "keyless" — no key, running the older free binary (invite the free login)+ /// "pro" — a paid license key (Pro banner + support address)+ /// "free" — a free key (latest binary, one concurrent session)/// </summary>- internal static void ShowWelcome(string tier = "keyless")+ internal static void ShowWelcome(string tier){var marker = Path.Combine(Config.GetCacheDir(), ".welcome_shown");if (!WelcomeDue(marker, tier == "pro")) return;@@ -160,48 +148,52 @@ public static class Downloadvar sb = new System.Text.StringBuilder();sb.Append('\n');sb.Append(" CloakBrowser - stealth Chromium for automation\n");- sb.Append(" https://github.com/CloakHQ/CloakBrowser\n");- sb.Append('\n');if (tier == "pro"){- sb.Append($" CloakBrowser Pro active (v{ProMajor}) - latest binary, newest patches.\n");+ sb.Append(" CloakBrowser Pro active.\n\n");sb.Append(" Pro support -> [email protected]\n");- }- else if (tier == "free")- {- sb.Append($" CloakBrowser free (v{ProMajor}): the latest binary, 1 concurrent session.\n");- sb.Append(" For more than one concurrent session -> https://cloakbrowser.dev\n");+ sb.Append(" Site -> https://cloakbrowser.dev\n");}else{- var freeMajor = Config.GetChromiumVersion().Split('.')[0];- sb.Append($" Running the free binary (v{freeMajor}). " +- $"The latest binary (v{ProMajor}) is free too, with 1 concurrent session.\n");- sb.Append(" Get your key: run cloakbrowser login or visit https://cloakbrowser.dev/free\n");+ sb.Append(" CloakBrowser free: 1 concurrent session.\n\n");sb.Append(" For more than one concurrent session -> https://cloakbrowser.dev\n");}+ sb.Append(" Docs -> https://github.com/CloakHQ/CloakBrowser\n");sb.Append(" Star us if CloakBrowser helps your project!\n");sb.Append('\n');- Console.Error.Write(sb.ToString());+ Emit(sb.ToString());+ MarkWelcomeShown();+ }+ private static void MarkWelcomeShown()+ {try{+ var marker = Path.Combine(Config.GetCacheDir(), ".welcome_shown");Directory.CreateDirectory(Path.GetDirectoryName(marker)!);File.WriteAllText(marker, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString());}catch { /* marker write is best-effort (IO, permissions, etc.) — never crash */ }}+ /// <summary>Write a cosmetic line to stderr, swallowing any error (a banner must never kill a launch).</summary>+ private static void Emit(string text)+ {+ try { Console.Error.Write(text); }+ catch { /* cosmetic */ }+ }+/// <summary>/// Ensure the stealth Chromium binary is available. Download if needed./// Returns the path to the chrome executable. Set <c>CLOAKBROWSER_BINARY_PATH</c>/// to skip download and use a local build./// </summary>/// <param name="licenseKey">- /// CloakBrowser Pro license key. Also read from the <c>CLOAKBROWSER_LICENSE_KEY</c>- /// env var or <c>~/.cloakbrowser/license.key</c>. With a valid key the latest Pro- /// binary is downloaded from cloakbrowser.dev; without one, the free binary- /// downloads from GitHub Releases exactly as before.+ /// CloakBrowser license key. Also read from the <c>CLOAKBROWSER_LICENSE_KEY</c>+ /// env var or <c>~/.cloakbrowser/license.key</c>. With no key anywhere, a terminal+ /// gets a menu to get a free key by email or paste one; otherwise this throws+ /// <see cref="CloakBrowserLicenseError"/> with the claim link./// </param>/// <param name="browserVersion">/// Exact Chromium version pin. Also read from the <c>CLOAKBROWSER_VERSION</c>@@ -227,179 +219,267 @@ public static class Downloadvar requestedVersion = Config.NormalizeRequestedVersion(browserVersion);- // Pro license key check (a custom CLOAKBROWSER_DOWNLOAD_URL overrides the Pro path).- // Treat an empty value as unset (falsy), matching Python/JS semantics.+ // No key anywhere (param, env, license.key) -> get a free one first.var key = License.ResolveLicenseKey(licenseKey);- if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL")))- key = null;+ if (string.IsNullOrEmpty(key))+ key = await Task.Run(ClaimFreeKey, ct).ConfigureAwait(false);- if (!string.IsNullOrEmpty(key))+ // Sync HTTP on a cache miss: run it off the caller's thread (e.g. a UI thread).+ var info = await Task.Run(() => License.ValidateLicense(key)).ConfigureAwait(false);+ if (info != null && info.Valid){- // Sync HTTP on a cache miss: run it off the caller's thread (e.g. a UI thread).- var info = await Task.Run(() => License.ValidateLicense(key)).ConfigureAwait(false);- if (info != null && info.Valid)+ MaybeTriggerUpdateCheck();+ // A free key always gets the latest build. Drop any version pin: the+ // server force-serves latest to free keys, so fetching a pinned+ // version's signed manifest would mismatch the served bytes and fail+ // checksum verification. Paid keys keep pinning/rollback.+ var proVersion = info.Plan == "free" ? null : requestedVersion;+ // (A blip during a routine update never reaches the error below:+ // EnsureProBinaryAsync returns the cached build and retries next launch.)+ try{- // Free tier always gets the latest build. Drop any version pin: the- // server force-serves latest to free keys, so fetching a pinned- // version's signed manifest would mismatch the served bytes and fail- // checksum verification. Paid keys keep pinning/rollback.- var proVersion = info.Plan == "free" ? null : requestedVersion;- // A valid license is entitled to Pro, so Pro failures surface loudly- // rather than silently substituting the older free binary. (A blip- // during a routine update never reaches here: EnsureProBinaryAsync- // returns the cached Pro binary and updates in the background.)- try- {- return await EnsureProBinaryAsync(- key, proVersion, info.Plan, ct, releaseChannel).ConfigureAwait(false);- }- catch (BinaryVerificationError)- {- // Authenticity could not be confirmed - surface verbatim.- throw;- }- catch (Exception e)- {- // Transient failure with no cached Pro binary to use - surface a- // clear error rather than silently downloading the free binary.- throw new InvalidOperationException(- $"Pro binary unavailable: {e.Message}. Your license is valid but the " +- "Pro binary could not be downloaded right now. Retry in a moment. " +- "To use the free binary instead, unset CLOAKBROWSER_LICENSE_KEY.", e);- }+ return await EnsureProBinaryAsync(+ key, proVersion, info.Plan, ct, releaseChannel).ConfigureAwait(false);}- else if (info != null)+ catch (BinaryVerificationError){- // Key supplied but rejected - abort, never downgrade to free.- throw new InvalidOperationException(- $"CloakBrowser Pro: license key is invalid or expired (plan={info.Plan}). " +- "Check CLOAKBROWSER_LICENSE_KEY, or unset it to use the free binary.");+ // Authenticity could not be confirmed - surface verbatim.+ throw;}- else+ catch (Exception e){- // Key supplied but unvalidatable (server down, no cache) - abort.throw new InvalidOperationException(- "CloakBrowser Pro: license could not be validated (server unreachable " +- "and no cached validation). Retry in a moment, or unset " +- "CLOAKBROWSER_LICENSE_KEY to use the free binary.");+ $"CloakBrowser binary unavailable: {e.Message}. Your license is valid but " ++ "the binary could not be downloaded right now. Retry in a moment.", e);}}+ if (info != null)+ throw new CloakBrowserLicenseError(+ $"CloakBrowser: license key is invalid or expired (plan={info.Plan}). " ++ "Check CLOAKBROWSER_LICENSE_KEY or ~/.cloakbrowser/license.key, or get " ++ "a free key with: cloakbrowser login");+ throw new CloakBrowserLicenseError(+ "CloakBrowser: license could not be validated (server unreachable and " ++ "no cached validation). Retry in a moment.");+ }- // Fail fast if no binary available for this platform.- Config.CheckPlatformAvailable();+ /// <summary>Synchronous convenience wrapper around <see cref="EnsureBinaryAsync"/>.</summary>+ public static string EnsureBinary(+ string? licenseKey = null, string? browserVersion = null, string? releaseChannel = null) =>+ EnsureBinaryAsync(licenseKey, browserVersion, releaseChannel: releaseChannel).GetAwaiter().GetResult();- if (requestedVersion != null)- {- var pinnedPath = Config.GetBinaryPath(requestedVersion);- if (File.Exists(pinnedPath) && IsExecutable(pinnedPath))- {- CloakLog.Debug("Pinned binary found in cache: {0} (version {1})", pinnedPath, requestedVersion);- ShowWelcome();- return pinnedPath;- }+ // -----------------------------------------------------------------------+ // No key: free key by email (claim link) or paste one. Mirrors Python+ // download.py prompt_license_key / _claim_free_key.+ // ------------------------------------------------------------------------ CloakLog.Info("Stealth Chromium {0} not found. Downloading for {1}...",- requestedVersion, Config.GetPlatformTag());- await DownloadAndExtractAsync(requestedVersion, ct).ConfigureAwait(false);+ /// <summary>How long a background claim poll keeps checking for the key (not readonly: test seam).</summary>+ internal static TimeSpan ClaimPollWindow = TimeSpan.FromMinutes(10);- if (!File.Exists(pinnedPath) || !IsExecutable(pinnedPath))- throw new InvalidOperationException(- $"Pinned download completed but binary not found at expected path: {pinnedPath}. " +- "This may indicate a packaging issue. Please report at " +- "https://github.com/CloakHQ/cloakbrowser/issues");- ShowWelcome();- return pinnedPath;- }+ private static int _claimPollStarted;- // Check for auto-updated version first, then fall back to hardcoded.- // Free tier never returns null (bundled base is the floor).- var effective = Config.GetEffectiveVersion()!;- var binaryPath = Config.GetBinaryPath(effective);+ /// <summary>The running background claim poll, if any. Test seam (await it instead of leaking it).</summary>+ internal static Task? ClaimPollTask;- if (File.Exists(binaryPath) && IsExecutable(binaryPath))- {- CloakLog.Debug("Binary found in cache: {0} (version {1})", binaryPath, effective);- ShowWelcome();- MaybeTriggerUpdateCheck();- return binaryPath;- }+ internal const string HasKeyMessage =+ "This email already has a free key. It's in the email we sent when you " ++ "first got it (search your mail for CloakBrowser).";- // Fall back to platform's hardcoded version if effective version binary doesn't exist.- var platformVersion = Config.GetChromiumVersion();- if (effective != platformVersion)- {- var fallbackPath = Config.GetBinaryPath();- if (File.Exists(fallbackPath) && IsExecutable(fallbackPath))- {- CloakLog.Debug("Binary found in cache: {0}", fallbackPath);- MaybeTriggerUpdateCheck();- return fallbackPath;- }- }+ // Test seams: null -> real console / browser.+ internal static Func<bool>? CanPromptOverride;+ internal static Func<string?>? ReadLineOverride;+ internal static Func<string, bool>? OpenBrowserOverride;- // Download platform's hardcoded version.- CloakLog.Info("Stealth Chromium {0} not found. Downloading for {1}...",- platformVersion, Config.GetPlatformTag());- await DownloadAndExtractAsync(null, ct).ConfigureAwait(false);+ /// <summary>Reset the once-per-process background claim poll. Test seam.</summary>+ internal static void ResetClaimPoll() => _claimPollStarted = 0;- binaryPath = Config.GetBinaryPath();- if (!File.Exists(binaryPath))- throw new InvalidOperationException(- $"Download completed but binary not found at expected path: {binaryPath}. " +- "This may indicate a packaging issue. Please report at " +- "https://github.com/CloakHQ/cloakbrowser/issues");+ /// <summary>A person is at this terminal: neither stdin nor stderr is redirected.</summary>+ public static bool CanPrompt() =>+ CanPromptOverride?.Invoke() ?? (!Console.IsInputRedirected && !Console.IsErrorRedirected);- MaybeTriggerUpdateCheck();- return binaryPath;+ /// <summary>Prompt on stderr (a program's stdout may be its data); EndOfStreamException if stdin closes.</summary>+ private static string Ask(string prompt)+ {+ Emit(prompt);+ var line = ReadLineOverride != null ? ReadLineOverride() : Console.ReadLine();+ return line?.Trim() ?? throw new EndOfStreamException("stdin closed");}- /// <summary>Synchronous convenience wrapper around <see cref="EnsureBinaryAsync"/>.</summary>- public static string EnsureBinary(- string? licenseKey = null, string? browserVersion = null, string? releaseChannel = null) =>- EnsureBinaryAsync(licenseKey, browserVersion, releaseChannel: releaseChannel).GetAwaiter().GetResult();-- private static async Task DownloadAndExtractAsync(string? version, CancellationToken ct)+ private static void EmitWelcome(){- var primaryUrl = Config.GetDownloadUrl(version);- var fallbackUrl = Config.GetFallbackDownloadUrl(version);- var binaryDir = Config.GetBinaryDir(version);- var binaryPath = Config.GetBinaryPath(version);-- Directory.CreateDirectory(Path.GetDirectoryName(binaryDir)!);+ Emit("\n Welcome to CloakBrowser - stealth Chromium for automation\n");+ Emit(" https://github.com/CloakHQ/CloakBrowser\n\n");+ Emit(" CloakBrowser needs a license key.\n\n");+ }- var tmpPath = Path.Combine(Path.GetTempPath(),- $"cloakbrowser-{Guid.NewGuid():N}{Config.GetArchiveExt()}");+ /// <summary>+ /// Terminal menu shared by a no-key launch and <c>cloakbrowser login</c>: get a free+ /// key by email or paste one. Returns a valid key, already saved. Throws+ /// <see cref="EndOfStreamException"/> if stdin closes.+ /// </summary>+ public static string PromptLicenseKey()+ {+ EmitWelcome();+ Emit(" 1) Get a free key (by email: the latest build, 1 concurrent session)\n");+ Emit(" 2) Paste a key I already have\n\n");+ while (true)+ {+ var choice = Ask(" Choose 1 or 2 [1]: ");+ if (choice is "" or "1")+ {+ var free = GetFreeKey();+ if (free != null) return free;+ Emit($"\n {HasKeyMessage}\n");+ }+ else if (choice != "2")+ {+ Emit(" Please type 1 or 2.\n");+ continue;+ }+ var pasted = PasteKey();+ if (pasted != null) return pasted;+ }+ }- try+ /// <summary>Ask until a valid key is pasted (saved, returned) or the answer is empty.</summary>+ private static string? PasteKey()+ {+ while (true){- // Try primary, fall back to GitHub Releases (skip fallback if custom URL).- try+ var key = Ask(" Paste your key (empty to go back): ");+ if (key.Length == 0) return null;+ if (!License.KeyRe.IsMatch(key)){- await DownloadFileAsync(primaryUrl, tmpPath, ct).ConfigureAwait(false);+ Emit(" That is not a CloakBrowser key (they start with cb_).\n");+ continue;}- catch (Exception primaryErr)+ var info = License.ValidateLicense(key);+ if (info == null)+ Emit(" Could not reach the license server. Check your connection and retry.\n");+ else if (!info.Valid)+ Emit(" That key is invalid or expired.\n");+ else{- if (Environment.GetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL") != null)- throw;- CloakLog.Warning("Primary download failed ({0}), trying GitHub Releases...", primaryErr.Message);- await DownloadFileAsync(fallbackUrl, tmpPath, ct).ConfigureAwait(false);+ License.SaveLicenseKey(key);+ Emit(" Key saved.\n\n");+ if (info.Plan == "free")+ MarkWelcomeShown(); // the menu was the welcome; a paid key keeps its Pro banner+ return key;}+ }+ }- // Verify the download before extraction. On the official path this is a- // mandatory, non-bypassable Ed25519 signature check (see- // VerifyDownloadChecksumAsync); the skip flag only applies to custom- // self-hosted CLOAKBROWSER_DOWNLOAD_URL setups.- await VerifyDownloadChecksumAsync(tmpPath, version, ct).ConfigureAwait(false);+ /// <summary>+ /// Open the claim link and wait for the key (saved, returned). Null if the email+ /// already has a key, which the server never sends to a claim.+ /// </summary>+ private static string? GetFreeKey()+ {+ var code = License.GetClaimCode();+ var link = License.ClaimLink(code);+ Emit($"\n Open this link and enter your email:\n {link}\n");+ if (OpenBrowser(link))+ Emit(" (opened in your browser)\n");+ Emit("\n Waiting for you to confirm your email... (Ctrl+C to stop)\n");+ string? key;+ try+ {+ key = License.PollClaim(code, overwrite: true);+ }+ catch (FreeKeyAlreadyHeldException)+ {+ return null;+ }+ Emit(" Free key saved.\n\n");+ MarkWelcomeShown(); // the menu was the welcome: no second banner this launch+ return key;+ }- ExtractArchive(tmpPath, binaryDir, binaryPath);- ShowWelcome();+ /// <summary>Open <paramref name="url"/> in the default browser. False if that failed.</summary>+ public static bool OpenBrowser(string url)+ {+ if (OpenBrowserOverride != null) return OpenBrowserOverride(url);+ try+ {+ using var p = Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });+ return true;}- finally+ catch (Exception e) when (e is System.ComponentModel.Win32Exception or InvalidOperationException+ or PlatformNotSupportedException){- try { if (File.Exists(tmpPath)) File.Delete(tmpPath); } catch (IOException) { }+ CloakLog.Debug("Could not open a browser: {0}", e.Message);+ return false;}}+ /// <summary>+ /// No key anywhere: get one before launching. A person at a terminal gets the menu+ /// (<see cref="PromptLicenseKey"/>). Anything else (CI, Docker, an MCP server) throws+ /// with the claim link and keeps polling in the background, so a long-lived process+ /// picks the key up and its next launch works.+ /// </summary>+ private static string ClaimFreeKey()+ {+ var code = License.GetClaimCode();+ string? key;+ try+ {+ key = License.CheckClaim(code);+ }+ catch (FreeKeyAlreadyHeldException)+ {+ if (!CanPrompt())+ throw new CloakBrowserLicenseError(+ $"{HasKeyMessage} Set CLOAKBROWSER_LICENSE_KEY or run: cloakbrowser login");+ key = null; // the menu below starts over with a fresh code+ }+ if (key != null) // confirmed since an earlier launch printed the link+ {+ License.SaveLicenseKey(key, overwrite: false);+ return key;+ }+ if (CanPrompt())+ {+ try+ {+ return PromptLicenseKey();+ }+ catch (EndOfStreamException) { /* stdin closed mid-menu: fall through to the link + error */ }+ }+ code = License.GetClaimCode(); // fresh if the old one was retired+ var link = License.ClaimLink(code);+ EmitWelcome();+ Emit($" Get one free (the latest build, 1 concurrent session):\n {link}\n" ++ " After you confirm, the key is also emailed to you.\n\n");+ StartClaimPoll(code);+ throw new CloakBrowserLicenseError(+ $"No CloakBrowser license key. Get one free: {link} " ++ "(or run: cloakbrowser login), then launch again.");+ }++ /// <summary>Poll for the claimed key in the background, once per process.</summary>+ private static void StartClaimPoll(string code)+ {+ if (Interlocked.Exchange(ref _claimPollStarted, 1) == 1) return;+ ClaimPollTask = Task.Run(() =>+ {+ try+ {+ // Saved, not merely received: an existing key is never overwritten here.+ if (License.PollClaimCore(code, deadline: DateTime.UtcNow + ClaimPollWindow).Saved)+ Emit("\n CloakBrowser: free key saved. The next launch uses it.\n");+ }+ catch (FreeKeyAlreadyHeldException)+ {+ Emit($"\n CloakBrowser: {HasKeyMessage}\n Set CLOAKBROWSER_LICENSE_KEY or run: cloakbrowser login\n");+ }+ catch (Exception e) when (e is IOException or UnauthorizedAccessException or ArgumentException)+ {+ CloakLog.Warning("Could not save the claimed free key: {0}", e.Message);+ }+ });+ }+// -----------------------------------------------------------------------// CloakBrowser Pro download path// -----------------------------------------------------------------------@@ -409,13 +489,13 @@ public static class Downloadstring licenseKey, string? requestedVersion, string? plan,CancellationToken ct, string? releaseChannel){- // A validated free GitHub key routes here too (it downloads the latest binary),+ // A validated free key routes here too (it downloads the latest binary),// but its welcome banner is the "free" one, not the paid Pro banner.var welcomeTier = plan == "free" ? "free" : "pro";if (requestedVersion != null){- var pinnedPath = Config.GetBinaryPath(requestedVersion, pro: true);+ var pinnedPath = Config.GetBinaryPath(requestedVersion);if (File.Exists(pinnedPath) && IsExecutable(pinnedPath)){CloakLog.Debug("Pinned Pro binary found in cache: {0} (version {1})", pinnedPath, requestedVersion);@@ -426,7 +506,7 @@ public static class DownloadCloakLog.Info("Downloading Pro Chromium {0} for {1}...", requestedVersion, Config.GetPlatformTag());await DownloadProBinaryAsync(requestedVersion, licenseKey, ct).ConfigureAwait(false);- pinnedPath = Config.GetBinaryPath(requestedVersion, pro: true);+ pinnedPath = Config.GetBinaryPath(requestedVersion);if (!File.Exists(pinnedPath) || !IsExecutable(pinnedPath))throw new InvalidOperationException($"Pro download completed but binary not found at: {pinnedPath}");@@ -438,11 +518,10 @@ public static class Download}// Unpinned: track the server's latest selected channel.- var effective = Config.GetEffectiveVersion(pro: true, releaseChannel: releaseChannel);+ var effective = Config.GetEffectiveVersion(releaseChannel);- // Honor CLOAKBROWSER_AUTO_UPDATE=false the way the free path does: frozen AND a- // cached Pro build present → keep it, skip the server check. With no cached build- // we must still fetch one — a valid Pro license never launches the free binary.+ // Honor CLOAKBROWSER_AUTO_UPDATE=false: frozen AND a cached build present → keep+ // it, skip the server check. With no cached build we must still fetch one.// (The `update` CLI ignores this and always acts.)var frozen = string.Equals(Environment.GetEnvironmentVariable("CLOAKBROWSER_AUTO_UPDATE"), "false",@@ -450,7 +529,7 @@ public static class Downloadif (frozen && ProBinaryReady(effective)){ShowWelcome(welcomeTier);- return Config.GetBinaryPath(effective, pro: true);+ return Config.GetBinaryPath(effective);}// GetProLatestVersion() is rate-limited to one network call per hour and returns a@@ -484,11 +563,11 @@ public static class Downloadif (version == null){// Valid Pro license but nothing resolvable (server unreachable AND no cached- // Pro build). Never downgrade to the free binary — fail loudly.+ // build) — fail loudly.throw new InvalidOperationException("Could not determine latest Pro version from server");}- var readyPath = Config.GetBinaryPath(version, pro: true);+ var readyPath = Config.GetBinaryPath(version);if (File.Exists(readyPath) && IsExecutable(readyPath)){// Advance the marker if this cached build is newer than what the marker names,@@ -502,7 +581,7 @@ public static class Download}// `version` (the server latest) needs downloading. On failure, fall back to a- // cached Pro build if we have one — never the free binary.+ // cached build if we have one.try{CloakLog.Info("Downloading Pro Chromium {0} for {1}...", version, Config.GetPlatformTag());@@ -520,12 +599,12 @@ public static class Download{CloakLog.Warning("Pro update to {0} failed; launching cached Pro binary {1}", version, effective);ShowWelcome(welcomeTier);- return Config.GetBinaryPath(effective, pro: true);+ return Config.GetBinaryPath(effective);}throw;}- var downloadedPath = Config.GetBinaryPath(version, pro: true);+ var downloadedPath = Config.GetBinaryPath(version);if (!File.Exists(downloadedPath))throw new InvalidOperationException($"Pro download completed but binary not found at: {downloadedPath}");@@ -543,8 +622,8 @@ public static class Downloadprivate static async Task DownloadProBinaryAsync(string version, string licenseKey, CancellationToken ct){var downloadUrl = Config.GetProDownloadUrl(version);- var binaryDir = Config.GetBinaryDir(version, pro: true);- var binaryPath = Config.GetBinaryPath(version, pro: true);+ var binaryDir = Config.GetBinaryDir(version);+ var binaryPath = Config.GetBinaryPath(version);var platformTag = Config.GetPlatformTag();Directory.CreateDirectory(Path.GetDirectoryName(binaryDir)!);@@ -560,10 +639,7 @@ public static class Download["X-Platform"] = platformTag,}).ConfigureAwait(false);- // Pro binaries come from cloakbrowser.dev - the same origin as free- // downloads - so the same attack the Ed25519 signature defends against- // applies equally. Verify with the same non-bypassable signature check;- // CLOAKBROWSER_SKIP_CHECKSUM does NOT bypass it (parity with the free path).+ // Non-bypassable Ed25519 signature check (M1 defense); no env var skips it.await VerifyProDownloadAsync(tmpPath, version, ct).ConfigureAwait(false);ExtractArchive(tmpPath, binaryDir, binaryPath);@@ -575,17 +651,15 @@ public static class Download}/// <summary>- /// Verify a Pro archive with the same non-bypassable Ed25519 signature check as- /// official free downloads.+ /// Verify a downloaded archive with a non-bypassable Ed25519 signature check.///- /// Pro binaries are served from cloakbrowser.dev (same origin as the free tier), so- /// a tampered same-origin SHA256SUMS could otherwise certify a tampered binary+ /// A tampered same-origin SHA256SUMS could otherwise certify a tampered binary/// (#308). Fetch the Pro SHA256SUMS + detached SHA256SUMS.sig, verify the signature/// against the pinned keys FIRST, bind the manifest to the requested version, then/// verify the archive's SHA-256. An invalid signature, checksum, or version mismatch/// throws <see cref="BinaryVerificationError"/> (a tampering signal the router surfaces/// verbatim); a failed manifest FETCH is transient and throws a plain- /// <see cref="InvalidOperationException"/>, never silently downgrading a valid-license user.+ /// <see cref="InvalidOperationException"/>./// </summary>internal static async Task VerifyProDownloadAsync(string filePath, string version, CancellationToken ct){@@ -625,8 +699,8 @@ public static class Downloadvar (manifestData, sigData) = manifest.Value;// VerifySignature / VerifyChecksum throw InvalidOperationException; convert to- // BinaryVerificationError so the Pro router treats them as tampering signals- // (re-raise) rather than transient failures (fall back to free).+ // BinaryVerificationError so the router treats them as tampering signals+ // (re-raise) rather than transient failures (fall back to a cached build).try{VerifySignature(manifestData, sigData);@@ -638,7 +712,9 @@ public static class Downloadvar manifestText = System.Text.Encoding.UTF8.GetString(manifestData);- // Version binding: same forced-downgrade defense as the official free path.+ // Version binding: the signature proves "we made this manifest", not "this is+ // the version you asked for" — without this a genuinely-signed older release+ // could be served in place of the requested one (forced downgrade).var declared = ParseManifestVersion(manifestText);if (declared != version)throw new BinaryVerificationError(@@ -677,88 +753,6 @@ public static class Downloadcatch (IOException) { }}- /// <summary>- /// Verify the downloaded archive's integrity and authenticity.- ///- /// Official path (cloakbrowser.dev / GitHub Releases): fetch SHA256SUMS plus- /// its detached Ed25519 signature SHA256SUMS.sig, verify the signature against- /// the pinned public keys FIRST, then verify the archive's SHA-256 against the- /// now-authenticated manifest. Mandatory and non-bypassable - a same-origin- /// manifest can no longer certify a tampered binary (#308).- ///- /// Custom self-hosted path (CLOAKBROWSER_DOWNLOAD_URL set): the pinned keys do- /// not apply to a third-party server, so fall back to the plain same-origin- /// SHA256SUMS check, which CLOAKBROWSER_SKIP_CHECKSUM may bypass.- /// </summary>- /// <summary>Synchronous wrapper around <see cref="VerifyDownloadChecksumAsync"/> for tests.</summary>- internal static void VerifyDownloadChecksum(string filePath, string? version = null) =>- VerifyDownloadChecksumAsync(filePath, version, default).GetAwaiter().GetResult();-- internal static async Task VerifyDownloadChecksumAsync(string filePath, string? version, CancellationToken ct)- {- var tarballName = Config.GetArchiveName();-- if (Environment.GetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL") != null)- {- // Self-hosted mirror: signature scheme does not apply. Preserve the- // legacy same-origin checksum behavior, skippable as before.- if ((Environment.GetEnvironmentVariable("CLOAKBROWSER_SKIP_CHECKSUM") ?? "")- .ToLowerInvariant() == "true")- {- CloakLog.Warning(- "CLOAKBROWSER_SKIP_CHECKSUM set - skipping verification for custom download URL");- return;- }- var checksums = await FetchChecksumsAsync(version, ct).ConfigureAwait(false);- if (checksums == null)- {- CloakLog.Warning(- "SHA256SUMS not available from custom URL - skipping checksum verification");- return;- }- if (!checksums.TryGetValue(tarballName, out var exp))- {- CloakLog.Warning(- "SHA256SUMS found but no entry for {0} - skipping verification", tarballName);- return;- }- VerifyChecksum(filePath, exp);- return;- }-- // Official path: signature is the trust root and is non-bypassable.- var manifest = SignedManifestOverride != null- ? SignedManifestOverride(version)- : await FetchSignedManifestAsync(version, ct).ConfigureAwait(false);- if (manifest == null)- throw new InvalidOperationException(- "Could not fetch a signed SHA256SUMS (SHA256SUMS + SHA256SUMS.sig) " +- "for this release - refusing to use an unverified binary. " +- "Retry, or report at https://github.com/CloakHQ/cloakbrowser/issues");-- var (manifestBytes, sigBytes) = manifest.Value;- VerifySignature(manifestBytes, sigBytes);- var manifestText = System.Text.Encoding.UTF8.GetString(manifestBytes);-- // Version binding: the signed manifest must declare the version we asked for.- // The signature proves "we made this manifest", not "this is the version you- // requested" - without this check a mirror could serve a genuinely-signed- // older release in place of the requested one (forced downgrade).- var requested = version ?? Config.GetChromiumVersion();- var declared = ParseManifestVersion(manifestText);- if (declared != requested)- throw new InvalidOperationException(- $"Version mismatch in signed SHA256SUMS: requested {requested}, " +- $"manifest declares {declared ?? "none"}. Refusing (possible downgrade).");-- var manifestChecksums = ParseChecksums(manifestText);- if (!manifestChecksums.TryGetValue(tarballName, out var expected))- throw new InvalidOperationException(- $"Signature-verified SHA256SUMS has no entry for {tarballName} - " +- "cannot confirm binary integrity.");- VerifyChecksum(filePath, expected);- }-/// <summary>/// Read the 'version=<v>' line from a signed manifest. Null if absent./// The line has no internal whitespace so older wrappers' SHA256SUMS parsers@@ -775,40 +769,6 @@ public static class Downloadreturn null;}- /// <summary>- /// Fetch (SHA256SUMS, SHA256SUMS.sig) raw bytes for a version, or null.- /// Both files are fetched from the SAME origin so the signature always matches- /// the exact manifest bytes it certifies. The primary origin is tried first,- /// then the GitHub Releases mirror.- /// </summary>- internal static async Task<(byte[] Manifest, byte[] Sig)?> FetchSignedManifestAsync(- string? version, CancellationToken ct)- {- var v = version ?? Config.GetChromiumVersion();- var bases = new[]- {- $"{Config.DownloadBaseUrl}/chromium-v{v}",- $"{Config.GitHubDownloadBaseUrl}/chromium-v{v}",- };- foreach (var b in bases)- {- try- {- using var manifestResp = await Http.GetAsync($"{b}/SHA256SUMS", ct).ConfigureAwait(false);- manifestResp.EnsureSuccessStatusCode();- var manifestBytes = await manifestResp.Content.ReadAsByteArrayAsync(ct).ConfigureAwait(false);-- using var sigResp = await Http.GetAsync($"{b}/SHA256SUMS.sig", ct).ConfigureAwait(false);- sigResp.EnsureSuccessStatusCode();- var sigBytes = await sigResp.Content.ReadAsByteArrayAsync(ct).ConfigureAwait(false);-- return (manifestBytes, sigBytes);- }- catch (Exception) { /* try next origin */ }- }- return null;- }-/// <summary>/// Verify a detached Ed25519 signature over the raw manifest bytes./// <paramref name="sigB64"/> is the base64 of the 64-byte raw signature. Tries@@ -870,29 +830,6 @@ public static class Download"Report at https://github.com/CloakHQ/cloakbrowser/issues");}- private static async Task<Dictionary<string, string>?> FetchChecksumsAsync(string? version, CancellationToken ct)- {- var v = version ?? Config.GetChromiumVersion();- var hasCustomUrl = Environment.GetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL") != null;-- var urls = new List<string> { $"{Config.DownloadBaseUrl}/chromium-v{v}/SHA256SUMS" };- if (!hasCustomUrl)- urls.Add($"{Config.GitHubDownloadBaseUrl}/chromium-v{v}/SHA256SUMS");-- foreach (var url in urls)- {- try- {- using var resp = await Http.GetAsync(url, ct).ConfigureAwait(false);- resp.EnsureSuccessStatusCode();- var text = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);- return ParseChecksums(text);- }- catch (Exception) { /* try next */ }- }- return null;- }-/// <summary>/// Parse SHA256SUMS format: '<64-hex sha256> filename' per line./// Only lines whose first token is a 64-character hex digest are accepted@@ -975,10 +912,10 @@ public static class DownloadCloakLog.Info("Download complete: {0} MB", new FileInfo(dest).Length / (1024 * 1024));}- private static void ExtractArchive(string archivePath, string destDir, string? binaryPath)+ private static void ExtractArchive(string archivePath, string destDir, string binaryPath){CloakLog.Info("Extracting to {0}", destDir);- var bp = binaryPath ?? Config.GetBinaryPath();+ var bp = binaryPath;// Extract into a private sibling dir, then rename it into place. Concurrent// first runs (in this process or others) each get their own staging dir, so@@ -1118,7 +1055,7 @@ public static class Downloadprivate static bool ProBinaryReady([NotNullWhen(true)] string? version){if (string.IsNullOrEmpty(version)) return false;- var p = Config.GetBinaryPath(version, pro: true);+ var p = Config.GetBinaryPath(version);return File.Exists(p) && IsExecutable(p);}@@ -1164,80 +1101,29 @@ public static class Download}/// <summary>- /// Return info about the current binary installation.- ///- /// <c>Tier</c> reflects what is actually installed on disk, not merely whether a- /// license is cached - a cached license with no Pro binary downloaded yet is still- /// effectively running the free binary, and the active key may differ from the- /// cached one.+ /// Return info about the cached binary installation. <paramref name="browserVersion"/>+ /// (or CLOAKBROWSER_VERSION) pins the reported version so the info matches what a+ /// pinned launch actually runs, instead of latest. Version is null until a build+ /// has been downloaded./// </summary>public static CloakBinaryInfo BinaryInfo(string? browserVersion = null, string? releaseChannel = null){- // browserVersion (or CLOAKBROWSER_VERSION) pins the reported version so the- // info matches what a pinned launch actually runs, instead of latest.- var requested = Config.NormalizeRequestedVersion(browserVersion);- // Prefer Pro only if a Pro binary actually exists on disk. GetEffectiveVersion- // returns null for Pro when nothing is cached (it never falls back to free).- var proVersion = requested ?? Config.GetEffectiveVersion(- pro: true, releaseChannel: releaseChannel);- var pro = ProBinaryReady(proVersion);-- string effective;- string binaryPath;- if (pro)- {- // pro == true implies proVersion is non-null (ProBinaryReady).- effective = proVersion!;- binaryPath = Config.GetBinaryPath(proVersion!, pro: true);- }- else- {- effective = requested ?? Config.GetEffectiveVersion()!;- binaryPath = Config.GetBinaryPath(effective);- }-+ var version = Config.NormalizeRequestedVersion(browserVersion)+ ?? Config.GetEffectiveVersion(releaseChannel);return new CloakBinaryInfo(- Version: effective,- Tier: pro ? "pro" : "free",- BundledVersion: Config.ChromiumVersion,+ Version: version,Platform: Config.GetPlatformTag(),- BinaryPath: binaryPath,- Installed: File.Exists(binaryPath),- CacheDir: Config.GetBinaryDir(effective, pro: pro),- DownloadUrl: pro ? Config.GetProLatestDownloadUrl(releaseChannel) : Config.GetDownloadUrl(effective));+ BinaryPath: version != null ? Config.GetBinaryPath(version) : null,+ Installed: ProBinaryReady(version),+ CacheDir: version != null ? Config.GetBinaryDir(version) : null,+ DownloadUrl: Config.GetProLatestDownloadUrl(releaseChannel));}// -----------------------------------------------------------------------// Auto-update// ------------------------------------------------------------------------ /// <summary>- /// Manually check for a newer Chromium version. Returns new version or null.- /// Unlike the background check in EnsureBinary, this blocks until complete.- /// </summary>- public static async Task<string?> CheckForUpdateAsync(CancellationToken ct = default)- {- var latest = await GetLatestChromiumVersionAsync(ct).ConfigureAwait(false);- if (latest == null) return null;- if (!Config.VersionNewer(latest, Config.GetChromiumVersion())) return null;-- var binaryDir = Config.GetBinaryDir(latest);- if (Directory.Exists(binaryDir))- {- WriteVersionMarker(latest);- return latest;- }-- CloakLog.Info("Downloading Chromium {0}...", latest);- await DownloadAndExtractAsync(latest, ct).ConfigureAwait(false);- WriteVersionMarker(latest);- return latest;- }-- /// <summary>Synchronous convenience wrapper around <see cref="CheckForUpdateAsync"/>.</summary>- public static string? CheckForUpdate() => CheckForUpdateAsync().GetAwaiter().GetResult();-/// <summary>/// Move a Pro install to the selected channel's latest. Blocks until complete. Returns the/// new version when a newer Pro build is downloaded or an already-cached newer build is@@ -1250,7 +1136,7 @@ public static class Downloadvar latest = await Task.Run(() => License.GetProLatestVersion(releaseChannel)).ConfigureAwait(false);if (string.IsNullOrEmpty(latest)) return null;- var effective = Config.GetEffectiveVersion(pro: true, releaseChannel: releaseChannel);+ var effective = Config.GetEffectiveVersion(releaseChannel);if (effective != null && !Config.VersionNewer(latest, effective) && ProBinaryReady(effective)){// Already on the latest cached Pro build.@@ -1261,7 +1147,7 @@ public static class Download{CloakLog.Info("Downloading Pro Chromium {0}...", latest);await DownloadProBinaryAsync(latest, licenseKey, ct).ConfigureAwait(false);- var p = Config.GetBinaryPath(latest, pro: true);+ var p = Config.GetBinaryPath(latest);if (!File.Exists(p))throw new InvalidOperationException($"Pro download completed but binary not found at: {p}");}@@ -1274,75 +1160,6 @@ public static class Downloadpublic static string? CheckForProUpdate(string licenseKey, string? releaseChannel = null) =>CheckForProUpdateAsync(licenseKey, releaseChannel: releaseChannel).GetAwaiter().GetResult();- private static bool ShouldCheckForUpdate()- {- if ((Environment.GetEnvironmentVariable("CLOAKBROWSER_AUTO_UPDATE") ?? "").ToLowerInvariant() == "false")- return false;- if (Config.GetLocalBinaryOverride() != null) return false;- if (Environment.GetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL") != null) return false;-- var checkFile = Path.Combine(Config.GetCacheDir(), ".last_update_check");- if (File.Exists(checkFile))- {- try- {- var lastCheck = double.Parse(File.ReadAllText(checkFile).Trim(),- System.Globalization.CultureInfo.InvariantCulture);- var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000.0;- if (now - lastCheck < UpdateCheckInterval)- return false;- }- catch (Exception ex) when (ex is FormatException or IOException) { }- }- return true;- }-- private static async Task<string?> GetLatestChromiumVersionAsync(CancellationToken ct)- {- try- {- var url = $"{Config.GitHubApiUrl}?per_page=10";- using var resp = await Http.GetAsync(url, ct).ConfigureAwait(false);- resp.EnsureSuccessStatusCode();- var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);- using var doc = System.Text.Json.JsonDocument.Parse(json);- var platformTarball = Config.GetArchiveName();- foreach (var release in doc.RootElement.EnumerateArray())- {- var tag = release.TryGetProperty("tag_name", out var t) ? t.GetString() ?? "" : "";- var draft = release.TryGetProperty("draft", out var d) && d.GetBoolean();- if (tag.StartsWith("chromium-v", StringComparison.Ordinal) && !draft)- {- if (release.TryGetProperty("assets", out var assets))- {- foreach (var asset in assets.EnumerateArray())- {- if (asset.TryGetProperty("name", out var n) && n.GetString() == platformTarball)- return tag["chromium-v".Length..];- }- }- }- }- return null;- }- catch (Exception)- {- CloakLog.Debug("Auto-update check failed");- return null;- }- }-- private static void WriteVersionMarker(string version)- {- var cacheDir = Config.GetCacheDir();- Directory.CreateDirectory(cacheDir);- var marker = Path.Combine(cacheDir, $"latest_version_{Config.GetPlatformTag()}");- var tmp = marker + ".tmp";- File.WriteAllText(tmp, version);- if (File.Exists(marker)) File.Delete(marker);- File.Move(tmp, marker);- }-/// <summary>/// Check NuGet for a newer wrapper version and log an upgrade hint. Runs once per/// process (gated by <see cref="_wrapperUpdateChecked"/> in MaybeTriggerUpdateCheck).@@ -1354,8 +1171,6 @@ public static class Download{if ((Environment.GetEnvironmentVariable("CLOAKBROWSER_AUTO_UPDATE") ?? "").ToLowerInvariant() == "false")return;- if (Environment.GetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL") != null)- return;try{using var resp = await Http.GetAsync(@@ -1405,49 +1220,16 @@ public static class Downloadreturn false;}- private static async Task CheckAndDownloadUpdateAsync()- {- try- {- var checkFile = Path.Combine(Config.GetCacheDir(), ".last_update_check");- Directory.CreateDirectory(Path.GetDirectoryName(checkFile)!);- var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000.0;- File.WriteAllText(checkFile, now.ToString(System.Globalization.CultureInfo.InvariantCulture));-- var platformVersion = Config.GetChromiumVersion();- var latest = await GetLatestChromiumVersionAsync(CancellationToken.None).ConfigureAwait(false);- if (latest == null) return;- if (!Config.VersionNewer(latest, platformVersion)) return;-- if (Directory.Exists(Config.GetBinaryDir(latest)))- {- WriteVersionMarker(latest);- return;- }-- CloakLog.Info("Newer Chromium available: {0} (current: {1}). Downloading in background...",- latest, platformVersion);- await DownloadAndExtractAsync(latest, CancellationToken.None).ConfigureAwait(false);- WriteVersionMarker(latest);- CloakLog.Info("Background update complete: Chromium {0} ready. Will use on next launch.", latest);- }- catch (Exception)- {- CloakLog.Debug("Background update failed");- }- }-+ /// <summary>+ /// Fire-and-forget wrapper update check (once per process). The binary itself+ /// updates on the launch path (<see cref="EnsureProBinaryAsync"/>).+ /// </summary>private static void MaybeTriggerUpdateCheck(){- // Wrapper update: once per process, not rate-limited.if (!_wrapperUpdateChecked){_wrapperUpdateChecked = true;_ = Task.Run(CheckWrapperUpdateAsync);}-- // Binary update: rate-limited to once per hour.- if (!ShouldCheckForUpdate()) return;- _ = Task.Run(CheckAndDownloadUpdateAsync);}}diff --git a/dotnet/src/CloakBrowser/Handles.cs b/dotnet/src/CloakBrowser/Handles.csindex 6ffac7b..5c03a3d 100644--- a/dotnet/src/CloakBrowser/Handles.cs+++ b/dotnet/src/CloakBrowser/Handles.cs@@ -16,8 +16,6 @@ public sealed class CloakBrowserHandle : IAsyncDisposableprivate readonly bool _humanize;private readonly HumanConfig? _humanCfg;private readonly IBrowser _rawBrowser;- private readonly bool _headless;- private readonly bool _headlessNoViewport;private readonly string? _denialPath;/// <summary>@@ -39,22 +37,20 @@ public sealed class CloakBrowserHandle : IAsyncDisposableinternal string? DenialPath => _denialPath;internal CloakBrowserHandle(IPlaywright playwright, IBrowser browser, bool humanize, HumanConfig? humanCfg,- bool headless = true, bool headlessNoViewport = false, string? denialPath = null)+ string? denialPath = null){_playwright = playwright;_rawBrowser = browser;_humanize = humanize;_humanCfg = humanCfg;- _headless = headless;- _headlessNoViewport = headlessNoViewport;_denialPath = denialPath;// Wrap the whole browser so the entire object graph (contexts, pages, mice,- // keyboards, locators, frames) is humanized transparently. The wrapper is- // headless-aware so the headed no-viewport default also applies when pages are- // created through the humanized browser (parity with Python's _default_no_viewport,- // which patches the raw browser so the default holds on every path).+ // keyboards, locators, frames) is humanized transparently. The wrapper also+ // applies the no-viewport default, so it holds when pages are created through+ // the humanized browser (parity with Python's _default_no_viewport, which+ // patches the raw browser so the default holds on every path).var visible = humanize- ? Wrappers.Humanize.Browser(browser, humanCfg ?? new HumanConfig(), headless, headlessNoViewport)+ ? Wrappers.Humanize.Browser(browser, humanCfg ?? new HumanConfig(), defaultNoViewport: true): browser;// Then wrap in the license guard so a post-handshake denial surfaces on the first// call through any page/context this browser produces (see LicenseGuard).@@ -62,16 +58,15 @@ public sealed class CloakBrowserHandle : IAsyncDisposable}/// <summary>- /// On headed launches, default a page/context that the caller didn't give an explicit- /// viewport to <c>NoViewport</c> so it tracks the real OS window. Delegates to the- /// shared <see cref="ViewportDefaults"/> (the single source of truth shared with the- /// humanize wrapper). Port of Python <c>_default_no_viewport</c>.+ /// Default a page/context that the caller didn't give an explicit viewport to+ /// <c>NoViewport</c>. Delegates to the shared <see cref="ViewportDefaults"/> (the single+ /// source of truth shared with the humanize wrapper). Port of Python <c>_default_no_viewport</c>./// </summary>- private BrowserNewPageOptions ApplyDefaultNoViewport(BrowserNewPageOptions? options) =>- ViewportDefaults.ApplyHeadedNoViewport(options, _headless, _headlessNoViewport);+ private static BrowserNewPageOptions ApplyDefaultNoViewport(BrowserNewPageOptions? options) =>+ ViewportDefaults.ApplyNoViewport(options);- private BrowserNewContextOptions ApplyDefaultNoViewport(BrowserNewContextOptions? options) =>- ViewportDefaults.ApplyHeadedNoViewport(options, _headless, _headlessNoViewport);+ private static BrowserNewContextOptions ApplyDefaultNoViewport(BrowserNewContextOptions? options) =>+ ViewportDefaults.ApplyNoViewport(options);/// <summary>/// Create a new browser context. On headed launches without an explicit viewport,@@ -142,7 +137,7 @@ internal static class LicenseGuard/// <summary>/// Run a factory op, surface a denial (whether it threw or succeeded), and wrap the/// returned page/context so its later calls are guarded too. When there is no denial- /// path (keyless), it is a pass-through.+ /// path (no key: a local binary override), it is a pass-through./// </summary>public static async Task<T> GuardAsync<T>(Func<Task<T>> op, string? denialPath) where T : class{diff --git a/dotnet/src/CloakBrowser/LaunchOptions.cs b/dotnet/src/CloakBrowser/LaunchOptions.csindex eedcf21..4489226 100644--- a/dotnet/src/CloakBrowser/LaunchOptions.cs+++ b/dotnet/src/CloakBrowser/LaunchOptions.cs@@ -43,8 +43,8 @@ public class LaunchOptions/// <summary>/// CloakBrowser Pro license key. Also read from the <c>CLOAKBROWSER_LICENSE_KEY</c>- /// env var or <c>~/.cloakbrowser/license.key</c>. With a valid key the latest Pro- /// binary is downloaded from cloakbrowser.dev; without one, the free binary is used.+ /// env var or <c>~/.cloakbrowser/license.key</c>. With no key anywhere, a launch from+ /// a terminal offers a free key by email; otherwise it throws with the claim link./// </summary>public string? LicenseKey { get; set; }@@ -77,7 +77,7 @@ public class LaunchContextOptions : LaunchOptions/// <summary>Custom user agent string.</summary>public string? UserAgent { get; set; }- /// <summary>Viewport size. Null means "use default 1920x947". Set <see cref="NoViewport"/> to disable.</summary>+ /// <summary>Viewport size. Null means no emulated viewport (headed tracks the real window; headless reports the binary's own dimensions).</summary>public (int Width, int Height)? Viewport { get; set; }/// <summary>Disable viewport emulation (use the OS window size).</summary>diff --git a/dotnet/src/CloakBrowser/License.cs b/dotnet/src/CloakBrowser/License.csindex 2e41100..959575c 100644--- a/dotnet/src/CloakBrowser/License.cs+++ b/dotnet/src/CloakBrowser/License.cs@@ -54,6 +54,16 @@ public sealed class CloakBrowserLicenseError : Exceptionpublic CloakBrowserLicenseError(string message, Exception inner) : base(message, inner) { }}+/// <summary>+/// The claim's email already has a free key. The server never sends an existing+/// key to a claim (anyone can type anyone's email), so the person pastes it from+/// the email they got it in.+/// </summary>+public sealed class FreeKeyAlreadyHeldException : Exception+{+ public FreeKeyAlreadyHeldException() : base("This email already has a free key.") { }+}+/// <summary>/// Source of a resolved license key. Determines whether env injection/// into the child browser process is needed.@@ -351,6 +361,170 @@ public static class Licensereturn ResolveLicenseKeyWithSource(licenseKey).Key;}+ // -----------------------------------------------------------------------+ // Free key by email: claim code + key save. Mirrors Python license.py.+ // -----------------------------------------------------------------------++ public const string ClaimUrl = "https://cloakbrowser.dev/api/license/free/claim";+ // Fragment form: the code after '#' never reaches server or CDN logs.+ public const string FreeClaimLink = "https://cloakbrowser.dev/#claim=";+ internal static readonly Regex KeyRe = new(@"^cb_[A-Za-z0-9_-]+$", RegexOptions.Compiled);+ internal static readonly Regex ClaimCodeRe = new(@"^[A-Za-z0-9_-]{20,128}$", RegexOptions.Compiled); // the server's format+ internal static readonly TimeSpan ClaimMaxAge = TimeSpan.FromDays(7);+ internal static TimeSpan ClaimPollInterval = TimeSpan.FromSeconds(15); // not readonly: test seam++ private static string ClaimFile => Path.Combine(Config.GetCacheDir(), ".free_claim");++ /// <summary>Create <paramref name="path"/> exclusively, readable by the owner only from the first byte.</summary>+ private static void WritePrivateNew(string path, string text)+ {+ var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write };+ if (!OperatingSystem.IsWindows())+ options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;+ using var fs = new FileStream(path, options);+ var bytes = Encoding.UTF8.GetBytes(text);+ fs.Write(bytes, 0, bytes.Length);+ fs.Flush(flushToDisk: true);+ }++ /// <summary>+ /// Save a key to <c><cache>/license.key</c> (0600) and retire the claim code.+ /// <paramref name="overwrite"/> false (the background claim poll) leaves an existing+ /// key alone: the user may have run <c>cloakbrowser login</c> meanwhile. Returns true if saved.+ /// </summary>+ public static bool SaveLicenseKey(string key, bool overwrite = true)+ {+ key = key.Trim();+ if (!KeyRe.IsMatch(key))+ throw new ArgumentException("not a CloakBrowser license key");+ var cacheDir = Config.GetCacheDir();+ Directory.CreateDirectory(cacheDir);+ var keyFile = Path.Combine(cacheDir, "license.key");+ if (!overwrite && File.Exists(keyFile))+ {+ // Not saved, but the claim is spent either way: left on disk it would+ // silently reinstall this key on the launch after a logout.+ File.Delete(ClaimFile);+ return false;+ }+ var tmp = Path.Combine(cacheDir, $"license.key.{Guid.NewGuid():N}.tmp");+ try+ {+ WritePrivateNew(tmp, key + "\n");+ File.Move(tmp, keyFile, overwrite: true);+ }+ finally+ {+ try { File.Delete(tmp); } catch (IOException) { }+ }+ // The claim code keeps returning the key, so it must not outlive the save.+ File.Delete(ClaimFile);+ return true;+ }++ /// <summary>+ /// This install's claim code, from <c><cache>/.free_claim</c> (0600, 7-day life).+ /// Workers launching at once must print the same link, so a new code is published+ /// without replacing and a loser of the race reads the winner's code.+ /// </summary>+ public static string GetClaimCode()+ {+ var cacheDir = Config.GetCacheDir();+ Directory.CreateDirectory(cacheDir);+ var path = ClaimFile;+ try+ {+ if (File.Exists(path))+ {+ if (DateTime.UtcNow - File.GetLastWriteTimeUtc(path) < ClaimMaxAge)+ {+ var existing = File.ReadAllText(path).Trim();+ if (ClaimCodeRe.IsMatch(existing))+ return existing;+ }+ File.Delete(path); // expired or garbage: start over+ }+ }+ catch (IOException) { }+ catch (UnauthorizedAccessException) { }++ var code = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))+ .TrimEnd('=').Replace('+', '-').Replace('/', '_');+ var tmp = Path.Combine(cacheDir, $".free_claim.{Guid.NewGuid():N}.tmp");+ try+ {+ WritePrivateNew(tmp, code);+ // Publish complete, without replacing: the first code wins and a reader+ // never sees a half-written file (same as the profile seed file).+ Config.PublishNoReplace(tmp, path, Encoding.UTF8.GetBytes(code), ownerOnly: true);+ }+ finally+ {+ try { File.Delete(tmp); } catch (IOException) { }+ }+ return File.ReadAllText(path).Trim();+ }++ /// <summary>The claim link printed for <paramref name="code"/>.</summary>+ public static string ClaimLink(string code) => FreeClaimLink + code;++ /// <summary>+ /// One poll: the key once the claim's email is confirmed, else null. Throws+ /// <see cref="FreeKeyAlreadyHeldException"/> (and retires the code) if that email+ /// already has a key. The code goes in the body, never the URL: it is a bearer+ /// secret and URLs land in server logs.+ /// </summary>+ public static string? CheckClaim(string code)+ {+ string? status, key;+ try+ {+ using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));+ var body = new StringContent(JsonSerializer.Serialize(new { code }), Encoding.UTF8, "application/json");+ using var resp = Http.PostAsync(ClaimUrl, body, cts.Token).GetAwaiter().GetResult();+ if (!resp.IsSuccessStatusCode) return null;+ using var doc = JsonDocument.Parse(resp.Content.ReadAsStringAsync(cts.Token).GetAwaiter().GetResult());+ var root = doc.RootElement;+ status = root.TryGetProperty("status", out var s) && s.ValueKind == JsonValueKind.String ? s.GetString() : null;+ key = root.TryGetProperty("license_key", out var k) && k.ValueKind == JsonValueKind.String ? k.GetString() : null;+ }+ // OperationCanceledException covers TaskCanceledException and a body-read+ // timeout; IOException a connection dropped mid-body. All mean "pending".+ catch (Exception e) when (e is HttpRequestException or OperationCanceledException or JsonException+ or InvalidOperationException or IOException)+ {+ CloakLog.Debug("Free-key claim check failed: {0}", e.Message);+ return null;+ }+ if (status == "has_key")+ {+ // This code will only ever answer has_key: start fresh next time.+ try { File.Delete(ClaimFile); } catch (IOException) { }+ throw new FreeKeyAlreadyHeldException();+ }+ return status == "ready" && key != null && KeyRe.IsMatch(key.Trim()) ? key.Trim() : null;+ }++ /// <summary>Poll until the key arrives (saved, then returned) or <paramref name="deadline"/> passes.</summary>+ public static string? PollClaim(string code, TimeSpan? interval = null, DateTime? deadline = null,+ bool overwrite = false, CancellationToken ct = default) =>+ PollClaimCore(code, interval, deadline, overwrite, ct).Key;++ /// <summary><see cref="PollClaim"/>, also reporting whether the key was actually saved.</summary>+ internal static (string? Key, bool Saved) PollClaimCore(string code, TimeSpan? interval = null,+ DateTime? deadline = null, bool overwrite = false, CancellationToken ct = default)+ {+ var wait = interval ?? ClaimPollInterval;+ while (true)+ {+ var key = CheckClaim(code);+ if (key != null)+ return (key, SaveLicenseKey(key, overwrite));+ if (deadline != null && DateTime.UtcNow + wait > deadline) return (null, false);+ if (ct.WaitHandle.WaitOne(wait)) ct.ThrowIfCancellationRequested();+ }+ }+/// <summary>/// Build a child-process env dict with any needed license key injection.///diff --git a/dotnet/src/CloakBrowser/ProxyResolver.cs b/dotnet/src/CloakBrowser/ProxyResolver.csindex 3b54f93..7bb94bd 100644--- a/dotnet/src/CloakBrowser/ProxyResolver.cs+++ b/dotnet/src/CloakBrowser/ProxyResolver.cs@@ -236,33 +236,6 @@ internal static class ProxyResolverreturn result;}- /// <summary>Parse an HTTP(S) proxy URL into a Playwright <see cref="Microsoft.Playwright.Proxy"/>.</summary>- private static Microsoft.Playwright.Proxy ParseProxyUrl(string proxy)- {- string normalized = proxy;- if (proxy.Contains('@') && !proxy.Contains("://"))- normalized = $"http://{proxy}";-- var parsed = ParseUrl(normalized);- if (string.IsNullOrEmpty(parsed.Username))- return new Microsoft.Playwright.Proxy { Server = proxy };-- string netloc = parsed.Host;- if (parsed.Port != null) netloc += $":{parsed.Port}";- var sb = new System.Text.StringBuilder();- if (!string.IsNullOrEmpty(parsed.Scheme)) sb.Append(parsed.Scheme).Append("://");- sb.Append(netloc).Append(parsed.Path);-- var result = new Microsoft.Playwright.Proxy- {- Server = sb.ToString(),- Username = Unquote(parsed.Username!),- };- if (!string.IsNullOrEmpty(parsed.Password))- result.Password = Unquote(parsed.Password!);- return result;- }-/// <summary>Extract a normalized proxy URL string from a string or dict proxy (for geoip / webrtc).</summary>public static string? ExtractProxyUrl(object? proxy){@@ -283,9 +256,7 @@ internal static class ProxyResolver}/// <summary>Resolve a proxy into Playwright options + extra Chrome args (one or both empty).</summary>- public static ProxyResolution Resolve(- object? proxy, string? browserVersion = null, string? licenseKey = null,- string? releaseChannel = null)+ public static ProxyResolution Resolve(object? proxy){if (proxy == null)return new ProxyResolution(null, new List<string>());@@ -311,17 +282,15 @@ internal static class ProxyResolverreturn new ProxyResolution(null, new List<string> { $"--proxy-server={NormalizeSocksStringUrl(sUrl)}" });}- // HTTP/HTTPS with credentials, only on binaries that ship inline proxy auth:- // inline creds via --proxy-server. Older binaries (free macOS/linux-arm64)- // can't parse inline credentials, so they fall through to Playwright's proxy.+ // HTTP/HTTPS with credentials: inline creds via --proxy-server (Chrome's native+ // proxy auth) instead of Playwright's CDP auth interceptor (#182).bool hasCreds = proxy switch{ProxySettings ps => HasCredentials(ps),string s => HasCredentials(s),_ => false,};- if (hasCreds && Config.BinarySupportsHttpProxyInlineAuth(- licenseKey, browserVersion, releaseChannel))+ if (hasCreds){if (proxy is ProxySettings psd){@@ -346,6 +315,6 @@ internal static class ProxyResolverPassword = dict.Password,}, new List<string>());}- return new ProxyResolution(ParseProxyUrl((string)proxy), new List<string>());+ return new ProxyResolution(new Microsoft.Playwright.Proxy { Server = (string)proxy }, new List<string>());}}diff --git a/dotnet/src/CloakBrowser/ViewportDefaults.cs b/dotnet/src/CloakBrowser/ViewportDefaults.csindex d0e4223..1365106 100644--- a/dotnet/src/CloakBrowser/ViewportDefaults.cs+++ b/dotnet/src/CloakBrowser/ViewportDefaults.cs@@ -3,33 +3,29 @@ using Microsoft.Playwright;namespace CloakBrowser;/// <summary>-/// Shared headed-launch viewport defaulting - the single source of truth behind both+/// Shared viewport defaulting - the single source of truth behind both/// <see cref="CloakBrowserHandle"/> and the humanize <c>HumanizedBrowser</c> wrapper, so/// the default applies no matter which path creates the page/context (mirrors Python's/// single <c>_default_no_viewport</c> that monkey-patches the raw browser).///-/// On a headed launch, a page/context the caller gave no explicit viewport defaults to-/// <see cref="ViewportSize.NoViewport"/> so it tracks the real OS window - a bare emulated-/// viewport on a headed window yields <c>outerWidth < innerWidth</c> (a physically-/// impossible window / bot tell). Headless keeps Playwright's default (coherent there).-/// An explicit viewport (including <see cref="ViewportSize.NoViewport"/>) is always honored.+/// A page/context the caller gave no explicit viewport defaults to+/// <see cref="ViewportSize.NoViewport"/>: headed, it tracks the real OS window (a bare+/// emulated viewport there yields <c>outerWidth < innerWidth</c>, an impossible window);+/// headless, the binary reports coherent dimensions itself. An explicit viewport+/// (including <see cref="ViewportSize.NoViewport"/>) is always honored./// </summary>internal static class ViewportDefaults{- public static BrowserNewPageOptions ApplyHeadedNoViewport(- BrowserNewPageOptions? options, bool headless, bool headlessNoViewport = false)+ public static BrowserNewPageOptions ApplyNoViewport(BrowserNewPageOptions? options){var o = options ?? new BrowserNewPageOptions();- if (headless && !headlessNoViewport) return o;o.ViewportSize ??= ViewportSize.NoViewport;return o;}- public static BrowserNewContextOptions ApplyHeadedNoViewport(- BrowserNewContextOptions? options, bool headless, bool headlessNoViewport = false)+ public static BrowserNewContextOptions ApplyNoViewport(BrowserNewContextOptions? options){var o = options ?? new BrowserNewContextOptions();- if (headless && !headlessNoViewport) return o;o.ViewportSize ??= ViewportSize.NoViewport;return o;}diff --git a/dotnet/src/CloakBrowser/Wrappers/Humanize.cs b/dotnet/src/CloakBrowser/Wrappers/Humanize.csindex 47704df..6d81bd5 100644--- a/dotnet/src/CloakBrowser/Wrappers/Humanize.cs+++ b/dotnet/src/CloakBrowser/Wrappers/Humanize.cs@@ -51,13 +51,14 @@ public static class Humanize/// <summary>/// Wrap a raw Playwright <see cref="IBrowser"/> so every context/page it produces- /// is humanized.+ /// is humanized. <paramref name="defaultNoViewport"/> (set by CloakBrowser's own+ /// launcher) defaults pages/contexts without an explicit viewport to no viewport./// </summary>public static IBrowser Browser(- IBrowser browser, HumanConfig? config = null, bool headless = true, bool headlessNoViewport = false)+ IBrowser browser, HumanConfig? config = null, bool defaultNoViewport = false){if (browser is HumanizedBrowser) return browser;- return new HumanizedBrowser(browser, config ?? new HumanConfig(), headless, headlessNoViewport);+ return new HumanizedBrowser(browser, config ?? new HumanConfig(), defaultNoViewport);}/// <summary>diff --git a/dotnet/src/CloakBrowser/Wrappers/HumanizedBrowser.cs b/dotnet/src/CloakBrowser/Wrappers/HumanizedBrowser.csindex a6ea43d..ced6449 100644--- a/dotnet/src/CloakBrowser/Wrappers/HumanizedBrowser.cs+++ b/dotnet/src/CloakBrowser/Wrappers/HumanizedBrowser.cs@@ -15,17 +15,21 @@ public sealed partial class HumanizedBrowser : IBrowser{private readonly IBrowser _inner;private readonly HumanConfig _cfg;- private readonly bool _headless;- private readonly bool _headlessNoViewport;+ private readonly bool _defaultNoViewport;- internal HumanizedBrowser(IBrowser inner, HumanConfig cfg, bool headless = true, bool headlessNoViewport = false)+ internal HumanizedBrowser(IBrowser inner, HumanConfig cfg, bool defaultNoViewport = false){_inner = inner;_cfg = cfg;- _headless = headless;- _headlessNoViewport = headlessNoViewport;+ _defaultNoViewport = defaultNoViewport;}+ private BrowserNewPageOptions? Viewport(BrowserNewPageOptions? o) =>+ _defaultNoViewport ? ViewportDefaults.ApplyNoViewport(o) : o;++ private BrowserNewContextOptions? Viewport(BrowserNewContextOptions? o) =>+ _defaultNoViewport ? ViewportDefaults.ApplyNoViewport(o) : o;+/// <summary>The original, un-humanized Playwright browser (escape hatch).</summary>public IBrowser Original => _inner;@@ -34,12 +38,12 @@ public sealed partial class HumanizedBrowser : IBrowserpublic async Task<IPage> NewPageAsync(BrowserNewPageOptions? options = null) =>await Humanize.WrapPageAsync(- await _inner.NewPageAsync(ViewportDefaults.ApplyHeadedNoViewport(options, _headless, _headlessNoViewport)).ConfigureAwait(false),+ await _inner.NewPageAsync(Viewport(options)).ConfigureAwait(false),_cfg).ConfigureAwait(false);public async Task<IBrowserContext> NewContextAsync(BrowserNewContextOptions? options = null) =>Humanize.Context(- await _inner.NewContextAsync(ViewportDefaults.ApplyHeadedNoViewport(options, _headless, _headlessNoViewport)).ConfigureAwait(false),+ await _inner.NewContextAsync(Viewport(options)).ConfigureAwait(false),_cfg);public IReadOnlyList<IBrowserContext> Contexts =>diff --git a/dotnet/tests/CloakBrowser.Tests/ClaimTests.cs b/dotnet/tests/CloakBrowser.Tests/ClaimTests.csnew file mode 100644index 0000000..0713da9--- /dev/null+++ b/dotnet/tests/CloakBrowser.Tests/ClaimTests.cs@@ -0,0 +1,332 @@+using System.Net;+using System.Runtime.InteropServices;+using System.Text;+using CloakBrowser;+using Xunit;++namespace CloakBrowser.Tests;++/// <summary>+/// Free key by email: claim code, key save, and the no-key launch path.+/// Port of Python <c>tests/test_free_claim.py</c>. Serialized: mutates env and static seams.+/// </summary>+[Collection("env-serial")]+public sealed class ClaimTests : IDisposable+{+ private readonly string _tmp;+ private readonly string? _prevCache;+ private readonly string? _prevKey;+ private readonly string? _prevBinary;+ private readonly HttpClient _prevHttp = License.Http;+ private readonly TimeSpan _prevInterval = License.ClaimPollInterval;+ private readonly List<string> _claimBodies = new();+ private readonly Queue<string> _claimAnswers = new();+ private readonly StringWriter _err = new();+ private readonly TextWriter _prevErr = Console.Error;++ private const string Version = "155.0.8059.39.2";++ public ClaimTests()+ {+ _tmp = Directory.CreateTempSubdirectory("cloak-claim-").FullName;+ _prevCache = Environment.GetEnvironmentVariable("CLOAKBROWSER_CACHE_DIR");+ _prevKey = Environment.GetEnvironmentVariable("CLOAKBROWSER_LICENSE_KEY");+ _prevBinary = Environment.GetEnvironmentVariable("CLOAKBROWSER_BINARY_PATH");+ Environment.SetEnvironmentVariable("CLOAKBROWSER_CACHE_DIR", _tmp);+ Environment.SetEnvironmentVariable("CLOAKBROWSER_LICENSE_KEY", null);+ Environment.SetEnvironmentVariable("CLOAKBROWSER_BINARY_PATH", null);+ License.ClaimPollInterval = TimeSpan.Zero;+ // Claim POSTs get the queued answers (pending once empty); record their bodies.+ License.Http = new HttpClient(new FakeHandler(async request =>+ {+ Assert.Equal(License.ClaimUrl, request.RequestUri!.ToString());+ _claimBodies.Add(await request.Content!.ReadAsStringAsync());+ var body = _claimAnswers.Count > 0 ? _claimAnswers.Dequeue() : "{\"status\":\"pending\"}";+ if (body == "network-error") throw new HttpRequestException("down");+ return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body) };+ }));+ Download.OpenBrowserOverride = _ => true;+ Download.ResetClaimPoll();+ Console.SetError(_err);+ }++ public void Dispose()+ {+ Console.SetError(_prevErr);+ License.Http = _prevHttp;+ License.ClaimPollInterval = _prevInterval;+ License.ValidateLicenseOverride = null;+ License.ProLatestVersionOverride = null;+ Download.CanPromptOverride = null;+ Download.ReadLineOverride = null;+ Download.OpenBrowserOverride = null;+ Download.ClaimPollTask = null;+ Download.ResetClaimPoll();+ Environment.SetEnvironmentVariable("CLOAKBROWSER_CACHE_DIR", _prevCache);+ Environment.SetEnvironmentVariable("CLOAKBROWSER_LICENSE_KEY", _prevKey);+ Environment.SetEnvironmentVariable("CLOAKBROWSER_BINARY_PATH", _prevBinary);+ try { Directory.Delete(_tmp, recursive: true); } catch (IOException) { }+ }++ private sealed class FakeHandler(Func<HttpRequestMessage, Task<HttpResponseMessage>> serve) : HttpMessageHandler+ {+ protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)+ => serve(request);+ }++ private string ClaimFile => Path.Combine(_tmp, ".free_claim");+ private string KeyFile => Path.Combine(_tmp, "license.key");++ private static void AssertOwnerOnly(string path)+ {+ if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return;+ Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(path));+ }++ private void Answer(params string[] bodies)+ {+ foreach (var b in bodies) _claimAnswers.Enqueue(b);+ }++ /// <summary>Valid license + a cached latest build, so a launch returns without downloading.</summary>+ private Dictionary<string, string> ValidLaunch()+ {+ var seen = new Dictionary<string, string>();+ License.ValidateLicenseOverride = key => { seen["key"] = key; return new LicenseInfo(true, "free", null); };+ License.ProLatestVersionOverride = () => Version;+ var bin = Config.GetBinaryPath(Version);+ Directory.CreateDirectory(Path.GetDirectoryName(bin)!);+ File.WriteAllText(bin, "binary");+ if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))+ File.SetUnixFileMode(bin, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);+ return seen;+ }++ private void Input(params string[] lines)+ {+ var q = new Queue<string>(lines);+ Download.CanPromptOverride = () => true;+ Download.ReadLineOverride = () => q.Count > 0 ? q.Dequeue() : null;+ }++ // ── claim code ─────────────────────────────────────────────────────────++ [Fact]+ public void ClaimCode_is_reused_and_private()+ {+ var code = License.GetClaimCode();+ Assert.Matches(License.ClaimCodeRe, code);+ Assert.Equal(code, License.GetClaimCode());+ AssertOwnerOnly(ClaimFile);+ }++ [Fact]+ public void ClaimCode_rotates_after_seven_days()+ {+ var old = License.GetClaimCode();+ File.SetLastWriteTimeUtc(ClaimFile, DateTime.UtcNow - License.ClaimMaxAge - TimeSpan.FromMinutes(1));+ Assert.NotEqual(old, License.GetClaimCode());+ }++ [Fact]+ public async Task Parallel_workers_share_one_code()+ {+ using var start = new Barrier(8);+ var codes = await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => Task.Run(() =>+ {+ start.SignalAndWait();+ return License.GetClaimCode();+ })));+ Assert.Single(codes.Distinct());+ }++ // ── key save ───────────────────────────────────────────────────────────++ [Fact]+ public void SaveKey_is_private_and_retires_claim()+ {+ License.GetClaimCode();+ Assert.True(License.SaveLicenseKey("cb_abc"));+ Assert.Equal("cb_abc\n", File.ReadAllText(KeyFile));+ AssertOwnerOnly(KeyFile);+ Assert.False(File.Exists(ClaimFile));+ }++ [Fact]+ public void SaveKey_rejects_non_keys()+ {+ Assert.Throws<ArgumentException>(() => License.SaveLicenseKey("<script>"));+ Assert.False(File.Exists(KeyFile));+ }++ [Fact]+ public void Poller_never_overwrites_an_existing_key()+ {+ License.SaveLicenseKey("cb_mine");+ Assert.False(License.SaveLicenseKey("cb_claimed", overwrite: false));+ Assert.Equal("cb_mine\n", File.ReadAllText(KeyFile));+ }++ [Fact]+ public void Ready_claim_with_an_existing_key_is_not_saved_but_is_retired()+ {+ // A login happened while the background poll ran: keep that key, report+ // "not saved" (no false "saved" message), and drop the spent claim so it+ // can't reinstall the key after a later logout.+ License.SaveLicenseKey("cb_mine");+ var code = License.GetClaimCode();+ Answer("{\"status\":\"ready\",\"license_key\":\"cb_claimed\"}");+ var (key, saved) = License.PollClaimCore(code);+ Assert.Equal("cb_claimed", key);+ Assert.False(saved);+ Assert.Equal("cb_mine\n", File.ReadAllText(KeyFile));+ Assert.False(File.Exists(ClaimFile));+ }++ // ── CheckClaim ─────────────────────────────────────────────────────────++ [Theory]+ [InlineData("{\"status\":\"pending\"}", null)]+ [InlineData("{\"status\":\"ready\",\"license_key\":\"cb_ok\"}", "cb_ok")]+ [InlineData("{\"status\":\"ready\",\"license_key\":\"bad key\"}", null)] // trust boundary+ public void CheckClaim_answers(string body, string? expected)+ {+ Answer(body);+ var code = new string('c', 32);+ Assert.Equal(expected, License.CheckClaim(code));+ // The code is a bearer secret: body, never the URL (the handler asserts the URL).+ Assert.Equal($"{{\"code\":\"{code}\"}}", Assert.Single(_claimBodies));+ }++ [Fact]+ public void CheckClaim_network_error_is_pending()+ {+ Answer("network-error");+ Assert.Null(License.CheckClaim(new string('c', 32)));+ }++ [Fact]+ public void CheckClaim_has_key_throws_and_retires_code()+ {+ License.GetClaimCode();+ Answer("{\"status\":\"has_key\"}");+ Assert.Throws<FreeKeyAlreadyHeldException>(() => License.CheckClaim(new string('c', 32)));+ Assert.False(File.Exists(ClaimFile));+ }++ // ── EnsureBinary with no key ───────────────────────────────────────────++ [Fact]+ public async Task No_key_without_terminal_throws_with_link_and_polls_once()+ {+ Download.CanPromptOverride = () => false;+ Download.ClaimPollWindow = TimeSpan.Zero; // one background check, then stop+ try+ {+ var ex = await Assert.ThrowsAsync<CloakBrowserLicenseError>(() => Download.EnsureBinaryAsync());+ Assert.Contains("cloakbrowser.dev/#claim=", ex.Message);+ Assert.NotNull(Download.ClaimPollTask);+ await Download.ClaimPollTask!;+ // A second no-key launch in the same process starts no second poll.+ var first = Download.ClaimPollTask;+ await Assert.ThrowsAsync<CloakBrowserLicenseError>(() => Download.EnsureBinaryAsync());+ Assert.Same(first, Download.ClaimPollTask);+ }+ finally+ {+ Download.ClaimPollWindow = TimeSpan.FromMinutes(10);+ }+ Assert.Contains("#claim=", _err.ToString()); // stderr only: stdout belongs to the app+ }++ [Fact]+ public async Task Menu_default_gets_free_key_then_launches()+ {+ var seen = ValidLaunch();+ Answer("{\"status\":\"pending\"}", "{\"status\":\"pending\"}",+ "{\"status\":\"ready\",\"license_key\":\"cb_claimed\"}"); // first check, then polls+ Input("");+ string? opened = null;+ Download.OpenBrowserOverride = url => { opened = url; return true; };++ Assert.Equal(Config.GetBinaryPath(Version), await Download.EnsureBinaryAsync());+ Assert.StartsWith(License.FreeClaimLink, opened);+ Assert.Equal("cb_claimed", seen["key"]);+ Assert.Equal("cb_claimed\n", File.ReadAllText(KeyFile));+ var err = _err.ToString();+ Assert.Contains("Welcome to CloakBrowser", err);+ Assert.Contains("1) Get a free key", err);+ // The menu was the welcome: the regular banner stays quiet this launch.+ Assert.DoesNotContain("Star us", err);+ }++ [Fact]+ public async Task Menu_paste_key_asks_again_until_valid()+ {+ var seen = ValidLaunch();+ Input("2", "hello", "cb_mine");+ Download.OpenBrowserOverride = _ => throw new InvalidOperationException("must not open a browser");++ Assert.Equal(Config.GetBinaryPath(Version), await Download.EnsureBinaryAsync());+ Assert.Equal("cb_mine", seen["key"]);+ Assert.Equal("cb_mine\n", File.ReadAllText(KeyFile));+ }++ [Fact]+ public void Menu_rejects_invalid_pasted_key()+ {+ License.ValidateLicenseOverride = key => new LicenseInfo(key == "cb_good", "free", null);+ Input("7", "2", "cb_bad", "cb_good");+ Assert.Equal("cb_good", Download.PromptLicenseKey());+ Assert.Equal("cb_good\n", File.ReadAllText(KeyFile));+ }++ [Fact]+ public void Menu_email_already_has_key_switches_to_paste()+ {+ License.ValidateLicenseOverride = _ => new LicenseInfo(true, "free", null);+ Answer("{\"status\":\"has_key\"}");+ Input("1", "cb_old");+ Assert.Equal("cb_old", Download.PromptLicenseKey());+ Assert.Contains("already has a free key", _err.ToString());+ Assert.Equal("cb_old\n", File.ReadAllText(KeyFile));+ }++ [Fact]+ public async Task No_terminal_email_already_has_key_says_so()+ {+ Download.CanPromptOverride = () => false;+ Answer("{\"status\":\"has_key\"}");+ var ex = await Assert.ThrowsAsync<CloakBrowserLicenseError>(() => Download.EnsureBinaryAsync());+ Assert.Contains("already has a free key", ex.Message);+ }++ [Fact]+ public async Task Stdin_closed_mid_menu_falls_back_to_link_error()+ {+ Input(); // EOF on the first read+ Download.ClaimPollWindow = TimeSpan.Zero;+ try+ {+ var ex = await Assert.ThrowsAsync<CloakBrowserLicenseError>(() => Download.EnsureBinaryAsync());+ Assert.Contains("#claim=", ex.Message);+ if (Download.ClaimPollTask != null) await Download.ClaimPollTask;+ }+ finally+ {+ Download.ClaimPollWindow = TimeSpan.FromMinutes(10);+ }+ }++ [Fact]+ public async Task Any_key_source_skips_the_claim()+ {+ var seen = ValidLaunch();+ Environment.SetEnvironmentVariable("CLOAKBROWSER_LICENSE_KEY", "cb_env");+ Download.CanPromptOverride = () => throw new InvalidOperationException("must not reach the claim flow");++ await Download.EnsureBinaryAsync();+ Assert.Equal("cb_env", seen["key"]);+ Assert.Empty(_claimBodies);+ }+}diff --git a/dotnet/tests/CloakBrowser.Tests/ConfigTests.cs b/dotnet/tests/CloakBrowser.Tests/ConfigTests.csindex 1b1eacb..3d7e7e6 100644--- a/dotnet/tests/CloakBrowser.Tests/ConfigTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/ConfigTests.cs@@ -5,19 +5,6 @@ namespace CloakBrowser.Tests;public class ConfigTests{- [Fact]- public void ChromiumVersion_IsPinned()- {- Assert.Equal("146.0.7680.177.5", Config.ChromiumVersion);- }-- [Fact]- public void DefaultViewport_Matches_Python()- {- Assert.Equal(1920, Config.DefaultViewportWidth);- Assert.Equal(947, Config.DefaultViewportHeight);- }-[Fact]public void IgnoreDefaultArgs_IsNonEmpty(){@@ -222,87 +209,3 @@ public class ReleaseChannelConfigTests}}}--/// <summary>-/// Config.BinarySupportsHeadlessNoViewport() — parity-critical: Python and JS mirror-/// this gate. Threshold is an unshipped version, so the resolved-version path is a-/// no-op today; the declared-version path is what these tests pin. In env-serial-/// because the override tests mutate CLOAKBROWSER_BINARY_PATH.-/// </summary>-[Collection("env-serial")]-public class HeadlessNoViewportGateTests-{- [Fact]- public void DeclaredBelowThreshold_Off()- {- // Current live Pro version — one build below the threshold => feature OFF.- Assert.False(Config.BinarySupportsHeadlessNoViewport(browserVersion: "148.0.7778.215.3"));- }-- [Fact]- public void DeclaredAtThreshold_On()- {- Assert.True(Config.BinarySupportsHeadlessNoViewport(browserVersion: "148.0.7778.215.4"));- }-- [Fact]- public void DeclaredAboveThreshold_On()- {- Assert.True(Config.BinarySupportsHeadlessNoViewport(browserVersion: "149.0.0.0"));- }-- [Fact]- public void DeclaredWinsOverLocalOverride()- {- var prev = Environment.GetEnvironmentVariable("CLOAKBROWSER_BINARY_PATH");- try- {- Environment.SetEnvironmentVariable("CLOAKBROWSER_BINARY_PATH", "/fake/chrome");- Assert.True(Config.BinarySupportsHeadlessNoViewport(browserVersion: "149.0.0.0"));- }- finally- {- Environment.SetEnvironmentVariable("CLOAKBROWSER_BINARY_PATH", prev);- }- }-- [Fact]- public void LocalOverrideWithoutDeclared_Off()- {- var prev = Environment.GetEnvironmentVariable("CLOAKBROWSER_BINARY_PATH");- try- {- Environment.SetEnvironmentVariable("CLOAKBROWSER_BINARY_PATH", "/fake/chrome");- Assert.False(Config.BinarySupportsHeadlessNoViewport());- }- finally- {- Environment.SetEnvironmentVariable("CLOAKBROWSER_BINARY_PATH", prev);- }- }-}--/// <summary>-/// BinarySupportsMaximizedWindow() — parity-critical: Python and JS mirror this gate.-/// Shares the no_viewport threshold today.-/// </summary>-public class MaximizedWindowGateTests-{- [Fact]- public void DeclaredBelowThreshold_Off()- {- Assert.False(Config.BinarySupportsMaximizedWindow(browserVersion: "148.0.7778.215.3"));- }-- [Fact]- public void DeclaredAtThreshold_On()- {- Assert.True(Config.BinarySupportsMaximizedWindow(browserVersion: "148.0.7778.215.4"));- }-- [Fact]- public void DeclaredAboveThreshold_On()- {- Assert.True(Config.BinarySupportsMaximizedWindow(browserVersion: "149.0.0.0"));- }-}diff --git a/dotnet/tests/CloakBrowser.Tests/DiagnosticsTests.cs b/dotnet/tests/CloakBrowser.Tests/DiagnosticsTests.csindex 4c26b4e..338a8a2 100644--- a/dotnet/tests/CloakBrowser.Tests/DiagnosticsTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/DiagnosticsTests.cs@@ -17,7 +17,7 @@ namespace CloakBrowser.Tests;public class DiagnosticsTests{[Fact]- public void Quick_skips_launch_and_reports_free_license()+ public void Quick_skips_launch_and_reports_no_license(){var tmp = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());Directory.CreateDirectory(tmp);@@ -38,7 +38,7 @@ public class DiagnosticsTestsAssert.Contains("--quick", (string)launch["reason"]!);var license = Assert.IsType<Dictionary<string, object?>>(diag["license"]);- Assert.Equal("free", license["tier"]);+ Assert.Equal("none", license["tier"]);Assert.True(diag.ContainsKey("binary"));Assert.True(diag.ContainsKey("geoip"));diff --git a/dotnet/tests/CloakBrowser.Tests/DownloadConfigTests.cs b/dotnet/tests/CloakBrowser.Tests/DownloadConfigTests.csindex b0cf03e..3c90947 100644--- a/dotnet/tests/CloakBrowser.Tests/DownloadConfigTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/DownloadConfigTests.cs@@ -2,7 +2,6 @@ using System.Formats.Tar;using System.IO;using System.IO.Compression;using System.Net;-using System.Net.Sockets;using System.Runtime.InteropServices;using System.Text;using CloakBrowser;@@ -31,7 +30,8 @@ public class ConfigVersionTests[Fact]public void PlatformTag_is_known_value()- => Assert.Contains(Config.GetPlatformTag(), Config.AvailablePlatforms);+ => Assert.Contains(Config.GetPlatformTag(),+ new[] { "linux-x64", "linux-arm64", "darwin-arm64", "darwin-x64", "windows-x64" });[Fact]public void ArchiveName_uses_tag_and_ext()@@ -42,12 +42,8 @@ public class ConfigVersionTests}[Fact]- public void DownloadUrl_contains_base_and_archive()- {- var url = Config.GetDownloadUrl();- Assert.StartsWith(Config.DownloadBaseUrl, url);- Assert.Contains("cloakbrowser-", url);- }+ public void ProDownloadUrl_pins_version_on_base()+ => Assert.Equal($"{Config.DownloadBaseUrl}/api/download/155.0.1.1", Config.GetProDownloadUrl("155.0.1.1"));}public class ChecksumParseTests@@ -120,30 +116,90 @@ public class WrapperVersionNewerTests/// <summary>/// Concurrent first-run callers of <see cref="Download.EnsureBinaryAsync"/> against one-/// empty cache, with the archive served by a local HttpListener acting as a custom-/// mirror. In env-serial because it sets CLOAKBROWSER_CACHE_DIR and-/// CLOAKBROWSER_DOWNLOAD_URL.+/// empty cache, on the keyed download path: the license and latest version are mocked+/// and the archive is served by a fake <see cref="Download.Http"/> handler, verified+/// against a test-signed manifest. In env-serial because it sets CLOAKBROWSER_CACHE_DIR./// </summary>[Collection("env-serial")]public class ConcurrentFirstRunTests{private const int Callers = 4;private const int FillerFiles = 300;+ private const string Version = "155.0.8059.39.2";private static readonly byte[] BinaryBytes = Encoding.ASCII.GetBytes("#!/bin/sh\necho fake-chrome\n");private static readonly string[] IsolatedEnvNames ={- "CLOAKBROWSER_CACHE_DIR", "CLOAKBROWSER_DOWNLOAD_URL", "CLOAKBROWSER_SKIP_CHECKSUM",- "CLOAKBROWSER_LICENSE_KEY", "CLOAKBROWSER_BINARY_PATH", "CLOAKBROWSER_VERSION",+ "CLOAKBROWSER_CACHE_DIR", "CLOAKBROWSER_LICENSE_KEY", "CLOAKBROWSER_BINARY_PATH",+ "CLOAKBROWSER_VERSION", "CLOAKBROWSER_RELEASE_CHANNEL", "CLOAKBROWSER_AUTO_UPDATE",};+ private sealed class FakeHandler(Func<HttpRequestMessage, Task<HttpResponseMessage>> serve) : HttpMessageHandler+ {+ protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)+ => serve(request);+ }++ private static Task<HttpResponseMessage> Archive(byte[] bytes) =>+ Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(bytes) });++ /// <summary>+ /// Run <paramref name="body"/> with an isolated cache, a valid license, a fixed latest+ /// version and archive downloads answered by <paramref name="serveArchive"/>.+ /// </summary>+ private static async Task WithKeyedDownloads(+ byte[] archiveBytes, Func<HttpRequestMessage, Task<HttpResponseMessage>> serveArchive, Func<string, Task> body)+ {+ var previousEnv = IsolatedEnvNames.ToDictionary(name => name, Environment.GetEnvironmentVariable);+ var cacheDir = Directory.CreateTempSubdirectory("cloakbrowser-concurrent-").FullName;+ var previousHttp = Download.Http;+ var gen = new Org.BouncyCastle.Crypto.Generators.Ed25519KeyPairGenerator();+ gen.Init(new Org.BouncyCastle.Crypto.Parameters.Ed25519KeyGenerationParameters(+ new Org.BouncyCastle.Security.SecureRandom()));+ var pair = gen.GenerateKeyPair();+ var manifest = Encoding.UTF8.GetBytes(+ $"version={Version}\n{Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(archiveBytes)).ToLowerInvariant()} {Config.GetArchiveName()}\n");+ var signer = new Org.BouncyCastle.Crypto.Signers.Ed25519Signer();+ signer.Init(true, pair.Private);+ signer.BlockUpdate(manifest, 0, manifest.Length);+ var sig = Encoding.ASCII.GetBytes(Convert.ToBase64String(signer.GenerateSignature()));+ try+ {+ foreach (var name in IsolatedEnvNames) Environment.SetEnvironmentVariable(name, null);+ Environment.SetEnvironmentVariable("CLOAKBROWSER_CACHE_DIR", cacheDir);+ License.ValidateLicenseOverride = _ => new LicenseInfo(true, "business", null);+ License.ProLatestVersionOverride = () => Version;+ Download.SigningPubkeysOverride = new[]+ {+ Convert.ToBase64String(((Org.BouncyCastle.Crypto.Parameters.Ed25519PublicKeyParameters)pair.Public).GetEncoded()),+ };+ Download.ProSignedManifestOverride = _ => (manifest, sig);+ // Only the archive route is served; anything else (the NuGet update check) is a 404.+ Download.Http = new HttpClient(new FakeHandler(request =>+ request.RequestUri!.AbsolutePath.StartsWith("/api/download/", StringComparison.Ordinal)+ ? serveArchive(request)+ : Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound))));+ await body(cacheDir);+ }+ finally+ {+ Download.Http = previousHttp;+ License.ValidateLicenseOverride = null;+ License.ProLatestVersionOverride = null;+ Download.SigningPubkeysOverride = null;+ Download.ProSignedManifestOverride = null;+ foreach (var (name, value) in previousEnv) Environment.SetEnvironmentVariable(name, value);+ Directory.Delete(cacheDir, recursive: true);+ }+ }+/// <summary>/// An archive with this platform's binary layout plus enough filler files that an/// extraction takes a measurable time./// </summary>private static byte[] CreatePlatformArchive(){- var binaryRelPath = Path.GetRelativePath(Config.GetBinaryDir(), Config.GetBinaryPath());+ var binaryRelPath = Path.GetRelativePath(Config.GetBinaryDir(Version), Config.GetBinaryPath(Version));using var archive = new MemoryStream();using (var gzip = new GZipStream(archive, CompressionLevel.Fastest, leaveOpen: true))using (var tar = new TarWriter(gzip))@@ -173,10 +229,10 @@ public class ConcurrentFirstRunTests{try{- var binaryPath = Config.GetBinaryPath();+ var binaryPath = Config.GetBinaryPath(Version);if (!File.ReadAllBytes(binaryPath).AsSpan().SequenceEqual(BinaryBytes)) return "binary content differs";if (!Config.IsExecutableFile(binaryPath)) return "binary not executable";- var fillerCount = Directory.GetFiles(Path.Combine(Config.GetBinaryDir(), "lib")).Length;+ var fillerCount = Directory.GetFiles(Path.Combine(Config.GetBinaryDir(Version), "lib")).Length;return fillerCount == FillerFiles ? "complete" : $"lib has {fillerCount} files";}catch (IOException err)@@ -185,49 +241,35 @@ public class ConcurrentFirstRunTests}}- private static int FindFreeTcpPort()- {- var probe = new TcpListener(IPAddress.Loopback, 0);- probe.Start();- var port = ((IPEndPoint)probe.LocalEndpoint).Port;- probe.Stop();- return port;- }+ /// <summary>What a keyed first install leaves in the cache (besides dot files).</summary>+ private static string[] ExpectedCacheEntries() =>+ new[] { Path.GetFileName(Config.GetBinaryDir(Version)), $"latest_pro_version_{Config.GetPlatformTag()}" };++ private static IEnumerable<string?> CacheEntries(string cacheDir) =>+ Directory.GetFileSystemEntries(cacheDir).Select(Path.GetFileName)+ .Where(name => !name!.StartsWith('.')).OrderBy(n => n, StringComparer.Ordinal);[Fact]public async Task Install_stays_complete_while_other_callers_finish(){if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return;-- var previousEnv = IsolatedEnvNames.ToDictionary(name => name, Environment.GetEnvironmentVariable);- var cacheDir = Directory.CreateTempSubdirectory("cloakbrowser-concurrent-").FullName;- var mirrorPort = FindFreeTcpPort();- using var mirror = new HttpListener();- mirror.Prefixes.Add($"http://127.0.0.1:{mirrorPort}/");- mirror.Start();- try+ var archiveBytes = CreatePlatformArchive();++ // One caller downloads at once. The others have already seen an empty+ // cache but their downloads are held until the first has returned,+ // which is the state a batch of simultaneous cold launches ends up in.+ var releaseHeldDownloads = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);+ var requestCount = 0;+ async Task<HttpResponseMessage> ServeArchiveAsync(HttpRequestMessage _){- UseLocalMirror(cacheDir, mirrorPort);- var archiveBytes = CreatePlatformArchive();-- // One caller downloads at once. The others have already seen an empty- // cache but their downloads are held until the first has returned,- // which is the state a batch of simultaneous cold launches ends up in.- var releaseHeldDownloads = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);- var requestCount = 0;- async Task ServeArchiveAsync(HttpListenerContext request)- {- if (Interlocked.Increment(ref requestCount) > 1) await releaseHeldDownloads.Task;- await RespondWithArchiveAsync(request, archiveBytes);- }- _ = Task.Run(async () =>- {- for (var i = 0; i < Callers; i++)- _ = ServeArchiveAsync(await mirror.GetContextAsync());- });+ if (Interlocked.Increment(ref requestCount) > 1) await releaseHeldDownloads.Task;+ return await Archive(archiveBytes);+ }- var callers = Enumerable.Range(0, Callers).Select(_ => Download.EnsureBinaryAsync()).ToArray();- Assert.Equal(Config.GetBinaryPath(), await await Task.WhenAny(callers));+ await WithKeyedDownloads(archiveBytes, ServeArchiveAsync, async cacheDir =>+ {+ var callers = Enumerable.Range(0, Callers).Select(_ => Download.EnsureBinaryAsync("cb_test")).ToArray();+ Assert.Equal(Config.GetBinaryPath(Version), await await Task.WhenAny(callers));// The first caller would now exec its binary. Keep reading the install// while the held callers download and extract.@@ -238,81 +280,52 @@ public class ConcurrentFirstRunTestsobservedStates.Add(InspectInstall());foreach (var caller in callers)- Assert.Equal(Config.GetBinaryPath(), await caller);+ Assert.Equal(Config.GetBinaryPath(Version), await caller);Assert.Equal(new[] { "complete" }, observedStates);- Assert.Equal(- new[] { Path.GetFileName(Config.GetBinaryDir()) },- Directory.GetFileSystemEntries(cacheDir).Select(Path.GetFileName).Where(name => !name!.StartsWith('.')));- }- finally- {- mirror.Stop();- foreach (var (name, value) in previousEnv) Environment.SetEnvironmentVariable(name, value);- Directory.Delete(cacheDir, recursive: true);- }+ Assert.Equal(ExpectedCacheEntries().OrderBy(n => n, StringComparer.Ordinal), CacheEntries(cacheDir));+ });}[Fact]public async Task Replaces_partial_install_left_by_interrupted_extraction(){if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return;+ var archiveBytes = CreatePlatformArchive();- var previousEnv = IsolatedEnvNames.ToDictionary(name => name, Environment.GetEnvironmentVariable);- var cacheDir = Directory.CreateTempSubdirectory("cloakbrowser-concurrent-").FullName;- var mirrorPort = FindFreeTcpPort();- using var mirror = new HttpListener();- mirror.Prefixes.Add($"http://127.0.0.1:{mirrorPort}/");- mirror.Start();- try+ await WithKeyedDownloads(archiveBytes, _ => Archive(archiveBytes), async _ =>{- UseLocalMirror(cacheDir, mirrorPort);- var archiveBytes = CreatePlatformArchive();- _ = Task.Run(async () => await RespondWithArchiveAsync(await mirror.GetContextAsync(), archiveBytes));- Directory.CreateDirectory(Path.Combine(Config.GetBinaryDir(), "lib"));- File.WriteAllText(Path.Combine(Config.GetBinaryDir(), "lib", "part-0.bin"), "truncated");+ Directory.CreateDirectory(Path.Combine(Config.GetBinaryDir(Version), "lib"));+ File.WriteAllText(Path.Combine(Config.GetBinaryDir(Version), "lib", "part-0.bin"), "truncated");- Assert.Equal(Config.GetBinaryPath(), await Download.EnsureBinaryAsync());+ Assert.Equal(Config.GetBinaryPath(Version), await Download.EnsureBinaryAsync("cb_test"));Assert.Equal("complete", InspectInstall());- }- finally- {- mirror.Stop();- foreach (var (name, value) in previousEnv) Environment.SetEnvironmentVariable(name, value);- Directory.Delete(cacheDir, recursive: true);- }+ });}[Fact]public async Task Concurrent_callers_replace_partial_install(){if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return;+ var archiveBytes = CreatePlatformArchive();- var previousEnv = IsolatedEnvNames.ToDictionary(name => name, Environment.GetEnvironmentVariable);- var cacheDir = Directory.CreateTempSubdirectory("cloakbrowser-concurrent-").FullName;- var mirrorPort = FindFreeTcpPort();- using var mirror = new HttpListener();- mirror.Prefixes.Add($"http://127.0.0.1:{mirrorPort}/");- mirror.Start();- try+ // Answer only once every caller is downloading, so all of them find the+ // partial install in the way when they move their extraction into place.+ var allDownloading = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);+ var requestCount = 0;+ async Task<HttpResponseMessage> ServeArchiveAsync(HttpRequestMessage _){- UseLocalMirror(cacheDir, mirrorPort);- var archiveBytes = CreatePlatformArchive();+ if (Interlocked.Increment(ref requestCount) == Callers) allDownloading.SetResult();+ await allDownloading.Task;+ return await Archive(archiveBytes);+ }- // Answer only once every caller is downloading, so all of them find the- // partial install in the way when they move their extraction into place.- _ = Task.Run(async () =>- {- var heldRequests = new List<HttpListenerContext>();- for (var i = 0; i < Callers; i++)- heldRequests.Add(await mirror.GetContextAsync());- foreach (var heldRequest in heldRequests)- _ = RespondWithArchiveAsync(heldRequest, archiveBytes);- });- Directory.CreateDirectory(Path.Combine(Config.GetBinaryDir(), "lib"));+ await WithKeyedDownloads(archiveBytes, ServeArchiveAsync, async cacheDir =>+ {+ Directory.CreateDirectory(Path.Combine(Config.GetBinaryDir(Version), "lib"));for (var i = 0; i < FillerFiles; i++)- File.WriteAllText(Path.Combine(Config.GetBinaryDir(), "lib", $"part-{i}.bin"), "truncated");+ File.WriteAllText(Path.Combine(Config.GetBinaryDir(Version), "lib", $"part-{i}.bin"), "truncated");- var callers = Enumerable.Range(0, Callers).Select(_ => Download.EnsureBinaryAsync()).ToArray();+ var callers = Enumerable.Range(0, Callers).Select(_ => Download.EnsureBinaryAsync("cb_test")).ToArray();var outcomes = new List<string>();foreach (var caller in callers){@@ -320,32 +333,9 @@ public class ConcurrentFirstRunTestscatch (Exception err) { outcomes.Add($"{err.GetType().Name}: {err.Message}"); }}- Assert.Equal(Enumerable.Repeat(Config.GetBinaryPath(), Callers), outcomes);+ Assert.Equal(Enumerable.Repeat(Config.GetBinaryPath(Version), Callers), outcomes);Assert.Equal("complete", InspectInstall());- Assert.Equal(- new[] { Path.GetFileName(Config.GetBinaryDir()) },- Directory.GetFileSystemEntries(cacheDir).Select(Path.GetFileName).Where(name => !name!.StartsWith('.')));- }- finally- {- mirror.Stop();- foreach (var (name, value) in previousEnv) Environment.SetEnvironmentVariable(name, value);- Directory.Delete(cacheDir, recursive: true);- }- }-- private static void UseLocalMirror(string cacheDir, int mirrorPort)- {- foreach (var name in IsolatedEnvNames) Environment.SetEnvironmentVariable(name, null);- Environment.SetEnvironmentVariable("CLOAKBROWSER_CACHE_DIR", cacheDir);- Environment.SetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL", $"http://127.0.0.1:{mirrorPort}");- Environment.SetEnvironmentVariable("CLOAKBROWSER_SKIP_CHECKSUM", "true");- }-- private static async Task RespondWithArchiveAsync(HttpListenerContext request, byte[] archiveBytes)- {- request.Response.ContentLength64 = archiveBytes.Length;- await request.Response.OutputStream.WriteAsync(archiveBytes);- request.Response.Close();+ Assert.Equal(ExpectedCacheEntries().OrderBy(n => n, StringComparer.Ordinal), CacheEntries(cacheDir));+ });}}diff --git a/dotnet/tests/CloakBrowser.Tests/EnvSerialCollection.cs b/dotnet/tests/CloakBrowser.Tests/EnvSerialCollection.csindex 00c3ceb..1ad2660 100644--- a/dotnet/tests/CloakBrowser.Tests/EnvSerialCollection.cs+++ b/dotnet/tests/CloakBrowser.Tests/EnvSerialCollection.cs@@ -4,7 +4,7 @@ namespace CloakBrowser.Tests;/// <summary>/// Serializes test classes that mutate process environment variables-/// (CLOAKBROWSER_DOWNLOAD_URL, CLOAKBROWSER_LICENSE_KEY, CLOAKBROWSER_CACHE_DIR, ...)+/// (CLOAKBROWSER_LICENSE_KEY, CLOAKBROWSER_CACHE_DIR, ...)/// so they don't race under xUnit's default cross-collection parallelism./// </summary>[CollectionDefinition("env-serial")]diff --git a/dotnet/tests/CloakBrowser.Tests/FontWarningTests.cs b/dotnet/tests/CloakBrowser.Tests/FontWarningTests.csindex 66fa74c..760b149 100644--- a/dotnet/tests/CloakBrowser.Tests/FontWarningTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/FontWarningTests.cs@@ -68,7 +68,6 @@ public class WelcomeCadenceTestspublic class WelcomeBannerAsciiTests{[Theory]- [InlineData("keyless")][InlineData("free")][InlineData("pro")]public void Banner_is_ascii_only(string tier)diff --git a/dotnet/tests/CloakBrowser.Tests/LicenseTests.cs b/dotnet/tests/CloakBrowser.Tests/LicenseTests.csindex 423721b..36733d4 100644--- a/dotnet/tests/CloakBrowser.Tests/LicenseTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/LicenseTests.cs@@ -28,7 +28,6 @@ public class LicenseTests : IDisposableprivate readonly string _tmp;private readonly string? _prevCacheDir;private readonly string? _prevLicenseEnv;- private readonly string? _prevDownloadUrl;private readonly string? _prevReleaseChannel;public LicenseTests()@@ -37,11 +36,9 @@ public class LicenseTests : IDisposableDirectory.CreateDirectory(_tmp);_prevCacheDir = Environment.GetEnvironmentVariable("CLOAKBROWSER_CACHE_DIR");_prevLicenseEnv = Environment.GetEnvironmentVariable("CLOAKBROWSER_LICENSE_KEY");- _prevDownloadUrl = Environment.GetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL");_prevReleaseChannel = Environment.GetEnvironmentVariable("CLOAKBROWSER_RELEASE_CHANNEL");Environment.SetEnvironmentVariable("CLOAKBROWSER_CACHE_DIR", _tmp);Environment.SetEnvironmentVariable("CLOAKBROWSER_LICENSE_KEY", null);- Environment.SetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL", null);Environment.SetEnvironmentVariable("CLOAKBROWSER_RELEASE_CHANNEL", null);}@@ -49,7 +46,6 @@ public class LicenseTests : IDisposable{Environment.SetEnvironmentVariable("CLOAKBROWSER_CACHE_DIR", _prevCacheDir);Environment.SetEnvironmentVariable("CLOAKBROWSER_LICENSE_KEY", _prevLicenseEnv);- Environment.SetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL", _prevDownloadUrl);Environment.SetEnvironmentVariable("CLOAKBROWSER_RELEASE_CHANNEL", _prevReleaseChannel);License.ValidateLicenseOverride = null;License.ProLatestVersionOverride = null;@@ -209,15 +205,15 @@ public class LicenseTests : IDisposable}// =======================================================================- // EnsureBinary Pro routing - a supplied key that isn't valid aborts,- // never silently downgrades to the free binary.+ // EnsureBinary routing - a supplied key that isn't valid aborts and+ // never falls into the no-key claim flow.// =======================================================================[Fact]public async Task InvalidKey_aborts_not_free(){License.ValidateLicenseOverride = key => new LicenseInfo(false, "solo", null);- var ex = await Assert.ThrowsAsync<InvalidOperationException>(+ var ex = await Assert.ThrowsAsync<CloakBrowserLicenseError>(() => Download.EnsureBinaryAsync("cb_bad"));Assert.Contains("invalid or expired", ex.Message);}@@ -227,7 +223,7 @@ public class LicenseTests : IDisposable{// validate returns null (server unreachable, no cache) -> abort.License.ValidateLicenseOverride = key => null;- var ex = await Assert.ThrowsAsync<InvalidOperationException>(+ var ex = await Assert.ThrowsAsync<CloakBrowserLicenseError>(() => Download.EnsureBinaryAsync("cb_x"));Assert.Contains("could not be validated", ex.Message);}@@ -250,7 +246,7 @@ public class LicenseTests : IDisposablevar completedOnReturn = task.IsCompleted;gate.Set();- await Assert.ThrowsAsync<InvalidOperationException>(() => task);+ await Assert.ThrowsAsync<CloakBrowserLicenseError>(() => task);Assert.False(completedOnReturn);Assert.True(returnedAfter < TimeSpan.FromSeconds(1), $"caller blocked {returnedAfter}");}@@ -749,40 +745,30 @@ public class LicenseTests : IDisposable[Fact]public void BinaryDir_pro_suffix(){- var dir = Config.GetBinaryDir("148.0.7778.215.2", pro: true);+ // Kept as "-pro": existing caches stay valid across the upgrade.+ var dir = Config.GetBinaryDir("148.0.7778.215.2");Assert.EndsWith("chromium-148.0.7778.215.2-pro", dir);}[Fact]- public void BinaryDir_default_no_suffix()- {- var dir = Config.GetBinaryDir("146.0.7680.177.5", pro: false);- Assert.EndsWith("chromium-146.0.7680.177.5", dir);- Assert.DoesNotContain("-pro", Path.GetFileName(dir));- }-- [Fact]- public void EffectiveVersion_pro_marker_without_binary_returns_null()+ public void EffectiveVersion_marker_without_binary_returns_null(){var marker = Path.Combine(_tmp, $"latest_pro_version_{Config.GetPlatformTag()}");File.WriteAllText(marker, "148.0.7778.215.2");- // Marker present but no Pro binary on disk -> null, NOT the- // free base. A valid Pro license must never fall back to the free binary.- Assert.Null(Config.GetEffectiveVersion(pro: true));+ // Marker present but no binary on disk -> null (resolve latest from the server).+ Assert.Null(Config.GetEffectiveVersion());}[Fact]- public void EffectiveVersion_pro_no_marker_returns_null_free_returns_base()+ public void EffectiveVersion_no_marker_returns_null(){- // No Pro marker at all -> null for Pro; free tier still resolves to a version.- Assert.Null(Config.GetEffectiveVersion(pro: true));- Assert.Equal(Config.GetChromiumVersion(), Config.GetEffectiveVersion(pro: false));+ Assert.Null(Config.GetEffectiveVersion());}- // Create a fake cached, executable Pro binary for `version`.+ // Create a fake cached, executable binary for `version`.private static void MakeProBinary(string version){- var p = Config.GetBinaryPath(version, pro: true);+ var p = Config.GetBinaryPath(version);Directory.CreateDirectory(Path.GetDirectoryName(p)!);File.WriteAllText(p, "binary");if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))@@ -802,32 +788,10 @@ public class LicenseTests : IDisposableFile.WriteAllText(Path.Combine(_tmp, $"latest_pro_version_preview_{Config.GetPlatformTag()}"), preview);- Assert.Equal(stable, Config.GetEffectiveVersion(pro: true, releaseChannel: "stable"));- Assert.Equal(preview, Config.GetEffectiveVersion(pro: true, releaseChannel: "preview"));- Assert.False(Config.BinarySupportsHeadlessNoViewport("cb_key", releaseChannel: "stable"));- Assert.True(Config.BinarySupportsHeadlessNoViewport("cb_key", releaseChannel: "preview"));- Assert.True(Config.BinarySupportsMaximizedWindow("cb_key", releaseChannel: "preview"));- Assert.False(Config.BinarySupportsHttpProxyInlineAuth("cb_key", releaseChannel: "stable"));- Assert.True(Config.BinarySupportsHttpProxyInlineAuth("cb_key", releaseChannel: "preview"));+ Assert.Equal(stable, Config.GetEffectiveVersion("stable"));+ Assert.Equal(preview, Config.GetEffectiveVersion("preview"));Assert.Equal(preview, Download.BinaryInfo(releaseChannel: "preview").Version);-- var stableProxy = ProxyResolver.Resolve(- "http://user:pass@host:8080", licenseKey: "cb_key", releaseChannel: "stable");- var previewProxy = ProxyResolver.Resolve(- "http://user:pass@host:8080", licenseKey: "cb_key", releaseChannel: "preview");- Assert.NotNull(stableProxy.PlaywrightProxy);- Assert.Empty(stableProxy.ExtraArgs);- Assert.Null(previewProxy.PlaywrightProxy);- Assert.Single(previewProxy.ExtraArgs);-- var viewport = CloakLauncher.ResolveContextViewport(new LaunchContextOptions- {- Headless = true,- LicenseKey = "cb_key",- ReleaseChannel = "preview",- });- Assert.Equal(-1, viewport!.Width);- Assert.Equal(-1, viewport.Height);+ Assert.Equal(stable, Download.BinaryInfo(releaseChannel: "stable").Version);}[Fact]@@ -857,7 +821,7 @@ public class LicenseTests : IDisposableLicense.ProLatestVersionOverride = () => throw new InvalidOperationException("latest lookup must not run");Assert.Equal(- Config.GetBinaryPath(pinned, pro: true),+ Config.GetBinaryPath(pinned),Download.EnsureBinary("cb_key", pinned, "preview"));Assert.False(File.Exists(Path.Combine(_tmp, $"latest_pro_version_preview_{Config.GetPlatformTag()}")));diff --git a/dotnet/tests/CloakBrowser.Tests/ProxyResolverTests.cs b/dotnet/tests/CloakBrowser.Tests/ProxyResolverTests.csindex 6b0a4d8..14bd15c 100644--- a/dotnet/tests/CloakBrowser.Tests/ProxyResolverTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/ProxyResolverTests.cs@@ -66,26 +66,14 @@ public class ProxyResolverTests}[Fact]- public void Http_With_Creds_Uses_InlineAuth_On_Binary_With_Patch()+ public void Http_With_Creds_Uses_InlineAuth(){- // Pin a version at/above every platform floor → inline on any host.- var r = ProxyResolver.Resolve("http://user:pass@host:8080", "148.0.7778.215.3");+ // Every served build ships inline proxy auth: never Playwright's CDP proxy.+ var r = ProxyResolver.Resolve("http://user:pass@host:8080");Assert.Null(r.PlaywrightProxy);Assert.Equal("--proxy-server=http://user:pass@host:8080", Assert.Single(r.ExtraArgs));}- [Fact]- public void Http_With_Creds_Falls_Back_On_Binary_Without_Patch()- {- // Pin a version below every platform floor → Playwright proxy on any host.- var r = ProxyResolver.Resolve("http://user:pass@host:8080", "146.0.7680.177.3");- Assert.Empty(r.ExtraArgs);- Assert.NotNull(r.PlaywrightProxy);- Assert.Equal("http://host:8080", r.PlaywrightProxy!.Server);- Assert.Equal("user", r.PlaywrightProxy.Username);- Assert.Equal("pass", r.PlaywrightProxy.Password);- }-[Fact]public void ExtractProxyUrl_AddsScheme_For_Bare(){diff --git a/dotnet/tests/CloakBrowser.Tests/SignatureTests.cs b/dotnet/tests/CloakBrowser.Tests/SignatureTests.csindex e135b7b..8accb01 100644--- a/dotnet/tests/CloakBrowser.Tests/SignatureTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/SignatureTests.cs@@ -52,39 +52,23 @@ public class SignatureTestsreturn Convert.ToHexString(sha.ComputeHash(data)).ToLowerInvariant();}- /// <summary>Run an action with overridden pinned keys / manifest, always restoring afterwards.</summary>- private static void WithOverrides(- string[]? pubkeys,- Func<string?, (byte[], byte[])?>? manifest,- Action body)+ /// <summary>Run an action with overridden pinned keys, always restoring afterwards.</summary>+ private static void WithOverrides(string[]? pubkeys, Action body){var prevKeys = Download.SigningPubkeysOverride;- var prevManifest = Download.SignedManifestOverride;- var prevCustomUrl = Environment.GetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL");try{Download.SigningPubkeysOverride = pubkeys;- Download.SignedManifestOverride = manifest;- // Force the official path (no custom mirror).- Environment.SetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL", null);body();}finally{Download.SigningPubkeysOverride = prevKeys;- Download.SignedManifestOverride = prevManifest;- Environment.SetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL", prevCustomUrl);}}private static string Tarball() => Config.GetArchiveName();- private static byte[] Manifest(string body, string? version = null)- {- var v = version ?? Config.GetChromiumVersion();- return Utf8($"version={v}\n{body}");- }-// =======================================================================// TestSignatureVerification - the cryptographic gate over manifest bytes.// =======================================================================@@ -95,7 +79,7 @@ public class SignatureTestsvar (priv, pub) = MakeKey();var manifest = Utf8("abc cloakbrowser-linux-x64.tar.gz\n");var sig = Sign(priv, manifest);- WithOverrides(new[] { pub }, null, () => Download.VerifySignature(manifest, sig));+ WithOverrides(new[] { pub }, () => Download.VerifySignature(manifest, sig));}[Fact]@@ -105,7 +89,7 @@ public class SignatureTestsvar manifest = Utf8("abc cloakbrowser-linux-x64.tar.gz\n");var sig = Sign(priv, manifest);var tampered = Utf8("xyz cloakbrowser-linux-x64.tar.gz\n");- WithOverrides(new[] { pub }, null, () =>+ WithOverrides(new[] { pub }, () =>{var ex = Assert.Throws<InvalidOperationException>(() => Download.VerifySignature(tampered, sig));Assert.Contains("signature verification failed", ex.Message);@@ -119,7 +103,7 @@ public class SignatureTestsvar (_, otherPub) = MakeKey();var manifest = Utf8("data\n");var sig = Sign(priv, manifest);- WithOverrides(new[] { otherPub }, null, () =>+ WithOverrides(new[] { otherPub }, () =>{var ex = Assert.Throws<InvalidOperationException>(() => Download.VerifySignature(manifest, sig));Assert.Contains("signature verification failed", ex.Message);@@ -130,7 +114,7 @@ public class SignatureTestspublic void MalformedSignature_fails(){var (_, pub) = MakeKey();- WithOverrides(new[] { pub }, null, () =>+ WithOverrides(new[] { pub }, () =>{var ex = Assert.Throws<InvalidOperationException>(() => Download.VerifySignature(Utf8("data\n"), Encoding.ASCII.GetBytes("!!!not base64!!!")));@@ -147,7 +131,6 @@ public class SignatureTestsvar sig = Sign(priv, manifest);WithOverrides(new[] { "REPLACE_WITH_REAL_ED25519_PUBLIC_KEY_BASE64", pub },- null,() => Download.VerifySignature(manifest, sig));}@@ -159,7 +142,7 @@ public class SignatureTestsvar (newPriv, newPub) = MakeKey();var manifest = Utf8("rotated\n");var sig = Sign(newPriv, manifest);- WithOverrides(new[] { oldPub, newPub }, null, () => Download.VerifySignature(manifest, sig));+ WithOverrides(new[] { oldPub, newPub }, () => Download.VerifySignature(manifest, sig));}// =======================================================================@@ -173,146 +156,6 @@ public class SignatureTestsreturn path;}- [Fact]- public void ValidManifestAndHash_passes()- {- var (priv, pub) = MakeKey();- var binary = Utf8("the real binary");- var archive = WriteTemp(binary);- var manifest = Manifest($"{Sha256Hex(binary)} {Tarball()}\n");- var sig = Sign(priv, manifest);- try- {- WithOverrides(new[] { pub }, _ => (manifest, sig), () =>- Download.VerifyDownloadChecksum(archive));- }- finally { File.Delete(archive); }- }-- [Fact]- public void TamperedBinary_fails_hash()- {- var (priv, pub) = MakeKey();- var archive = WriteTemp(Utf8("a malicious binary"));- var manifest = Manifest($"{Sha256Hex(Utf8("the real binary"))} {Tarball()}\n");- var sig = Sign(priv, manifest);- try- {- WithOverrides(new[] { pub }, _ => (manifest, sig), () =>- {- var ex = Assert.Throws<InvalidOperationException>(() =>- Download.VerifyDownloadChecksum(archive));- Assert.Contains("Checksum verification failed", ex.Message);- });- }- finally { File.Delete(archive); }- }-- [Fact]- public void WrongVersion_fails_downgrade()- {- var (priv, pub) = MakeKey();- var binary = Utf8("the real binary");- var archive = WriteTemp(binary);- // Manifest declares an old version, but we ask for the current one.- var manifest = Manifest($"{Sha256Hex(binary)} {Tarball()}\n", version: "1.0.0.0");- var sig = Sign(priv, manifest);- try- {- WithOverrides(new[] { pub }, _ => (manifest, sig), () =>- {- var ex = Assert.Throws<InvalidOperationException>(() =>- Download.VerifyDownloadChecksum(archive));- Assert.Contains("Version mismatch", ex.Message);- });- }- finally { File.Delete(archive); }- }-- [Fact]- public void MissingVersionLine_fails()- {- var (priv, pub) = MakeKey();- var binary = Utf8("the real binary");- var archive = WriteTemp(binary);- var manifest = Utf8($"{Sha256Hex(binary)} {Tarball()}\n"); // no version=- var sig = Sign(priv, manifest);- try- {- WithOverrides(new[] { pub }, _ => (manifest, sig), () =>- {- var ex = Assert.Throws<InvalidOperationException>(() =>- Download.VerifyDownloadChecksum(archive));- Assert.Contains("Version mismatch", ex.Message);- });- }- finally { File.Delete(archive); }- }-- [Fact]- public void MissingSignedManifest_fails_closed()- {- var archive = WriteTemp(Utf8("x"));- try- {- WithOverrides(null, _ => null, () =>- {- var ex = Assert.Throws<InvalidOperationException>(() =>- Download.VerifyDownloadChecksum(archive));- Assert.Contains("signed SHA256SUMS", ex.Message);- });- }- finally { File.Delete(archive); }- }-- [Fact]- public void ManifestWithoutEntry_fails()- {- var (priv, pub) = MakeKey();- var archive = WriteTemp(Utf8("x"));- var manifest = Manifest($"{new string('d', 64)} some-other-file.tar.gz\n"); // no entry for our tarball- var sig = Sign(priv, manifest);- try- {- WithOverrides(new[] { pub }, _ => (manifest, sig), () =>- {- var ex = Assert.Throws<InvalidOperationException>(() =>- Download.VerifyDownloadChecksum(archive));- Assert.Contains("no entry for", ex.Message);- });- }- finally { File.Delete(archive); }- }-- [Fact]- public void CustomUrl_uses_plain_checksum_and_skip()- {- // Self-hosted CLOAKBROWSER_DOWNLOAD_URL keeps the legacy skippable path,- // and the signature path must NOT be consulted for a custom mirror.- var archive = WriteTemp(Utf8("x"));- var prevDl = Environment.GetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL");- var prevSkip = Environment.GetEnvironmentVariable("CLOAKBROWSER_SKIP_CHECKSUM");- var prevManifest = Download.SignedManifestOverride;- bool manifestConsulted = false;- try- {- Environment.SetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL", "https://my-mirror.test");- Environment.SetEnvironmentVariable("CLOAKBROWSER_SKIP_CHECKSUM", "true");- Download.SignedManifestOverride = _ => { manifestConsulted = true; return null; };-- // Skip honored, no throw.- Download.VerifyDownloadChecksum(archive);- Assert.False(manifestConsulted, "signature path must not be consulted for a custom mirror");- }- finally- {- Environment.SetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL", prevDl);- Environment.SetEnvironmentVariable("CLOAKBROWSER_SKIP_CHECKSUM", prevSkip);- Download.SignedManifestOverride = prevManifest;- File.Delete(archive);- }- }-// =======================================================================// TestVersionBinding - the 'version=<v>' line.// =======================================================================diff --git a/dotnet/tests/CloakBrowser.Tests/ViewportTests.cs b/dotnet/tests/CloakBrowser.Tests/ViewportTests.csindex ed1927a..1ca2418 100644--- a/dotnet/tests/CloakBrowser.Tests/ViewportTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/ViewportTests.cs@@ -11,8 +11,8 @@ namespace CloakBrowser.Tests;////// Headed launches must NOT layer an emulated viewport on top of the real/// browser window: CDP viewport emulation forces outerWidth < innerWidth, a-/// physically impossible window (= bot tell). Headless keeps a fixed, coherent-/// (outer == inner) DEFAULT_VIEWPORT for deterministic dimensions.+/// physically impossible window (= bot tell). Headless also defaults to no+/// viewport: the binary reports coherent dimensions itself./// </summary>public class ViewportTests{@@ -27,13 +27,11 @@ public class ViewportTests// -----------------------------------------------------------------------[Fact]- public void Headless_unset_viewport_uses_default()+ public void Headless_unset_viewport_uses_no_viewport(){+ // Headless reports coherent dimensions natively: no emulated viewport either.var vp = CloakLauncher.ResolveContextViewport(new LaunchContextOptions { Headless = true });- Assert.NotNull(vp);- Assert.False(IsNoViewport(vp));- Assert.Equal(Config.DefaultViewportWidth, vp!.Width);- Assert.Equal(Config.DefaultViewportHeight, vp.Height);+ Assert.True(IsNoViewport(vp));}[Fact]@@ -97,48 +95,40 @@ public class ViewportTests}// ------------------------------------------------------------------------ // ViewportDefaults.ApplyHeadedNoViewport - the shared headed-default applied- // on EVERY page/context creation path (the raw handle AND the humanize- // wrapper), mirroring Python's _default_no_viewport which patches the browser- // so the default holds regardless of which path creates the page.+ // ViewportDefaults.ApplyNoViewport - the shared default applied on EVERY+ // page/context creation path (the raw handle AND the humanize wrapper),+ // mirroring Python's _default_no_viewport which patches the browser so the+ // default holds regardless of which path creates the page.// -----------------------------------------------------------------------[Fact]- public void HeadedDefault_page_unset_becomes_no_viewport()+ public void Default_page_unset_becomes_no_viewport(){- var o = ViewportDefaults.ApplyHeadedNoViewport((BrowserNewPageOptions?)null, headless: false);+ var o = ViewportDefaults.ApplyNoViewport((BrowserNewPageOptions?)null);Assert.True(IsNoViewport(o.ViewportSize));}[Fact]- public void HeadedDefault_context_unset_becomes_no_viewport()+ public void Default_context_unset_becomes_no_viewport(){- var o = ViewportDefaults.ApplyHeadedNoViewport((BrowserNewContextOptions?)null, headless: false);+ var o = ViewportDefaults.ApplyNoViewport((BrowserNewContextOptions?)null);Assert.True(IsNoViewport(o.ViewportSize));}[Fact]- public void HeadlessDefault_page_left_untouched()- {- // Headless: don't impose no_viewport - Playwright's default stays (coherent there).- var o = ViewportDefaults.ApplyHeadedNoViewport((BrowserNewPageOptions?)null, headless: true);- Assert.Null(o.ViewportSize);- }-- [Fact]- public void HeadedDefault_explicit_viewport_honored()+ public void Default_explicit_viewport_honored(){var input = new BrowserNewPageOptions { ViewportSize = new ViewportSize { Width = 1024, Height = 768 } };- var o = ViewportDefaults.ApplyHeadedNoViewport(input, headless: false);+ var o = ViewportDefaults.ApplyNoViewport(input);Assert.Equal(1024, o.ViewportSize!.Width);Assert.Equal(768, o.ViewportSize.Height);}[Fact]- public void HeadedDefault_explicit_no_viewport_honored()+ public void Default_explicit_no_viewport_honored(){var input = new BrowserNewContextOptions { ViewportSize = ViewportSize.NoViewport };- var o = ViewportDefaults.ApplyHeadedNoViewport(input, headless: false);+ var o = ViewportDefaults.ApplyNoViewport(input);Assert.True(IsNoViewport(o.ViewportSize));}}diff --git a/dotnet/tests/CloakBrowser.Tests/Wrappers/LicenseGuardCompositionTests.cs b/dotnet/tests/CloakBrowser.Tests/Wrappers/LicenseGuardCompositionTests.csindex c809efb..4a210a6 100644--- a/dotnet/tests/CloakBrowser.Tests/Wrappers/LicenseGuardCompositionTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/Wrappers/LicenseGuardCompositionTests.cs@@ -42,7 +42,7 @@ public class LicenseGuardCompositionTests}[Fact]- public void Keyless_context_is_humanized_and_not_guarded()+ public void Context_without_denial_path_is_humanized_and_not_guarded(){var (playwright, _) = Fake.Of<IPlaywright>();var (ctx, _) = Fake.Of<IBrowserContext>();diff --git a/examples/integrations/undetected_chromedriver.py b/examples/integrations/undetected_chromedriver.pyindex dd6c36b..b08b314 100644--- a/examples/integrations/undetected_chromedriver.py+++ b/examples/integrations/undetected_chromedriver.py@@ -8,12 +8,13 @@ Requires: pip install undetected-chromedriver cloakbrowserimport undetected_chromedriver as uc-from cloakbrowser.config import get_chromium_version, get_default_stealth_args+from cloakbrowser import binary_info+from cloakbrowser.config import get_default_stealth_argsfrom cloakbrowser.download import ensure_binarybinary_path = ensure_binary()stealth_args = get_default_stealth_args()-chromium_major = int(get_chromium_version().split(".")[0])+chromium_major = int(binary_info()["version"].split(".")[0]) # the build just ensuredoptions = uc.ChromeOptions()options.binary_location = binary_pathdiff --git a/examples/stealth_test.py b/examples/stealth_test.pyindex b6971f1..ad3da0a 100644--- a/examples/stealth_test.py+++ b/examples/stealth_test.py@@ -13,7 +13,7 @@ Usage:import sysimport time-from cloakbrowser import launch+from cloakbrowser import CloakBrowserLicenseError, launchHEADED = "--headed" in sys.argvSCREENSHOTS = "--no-screenshots" not in sys.argv@@ -133,19 +133,51 @@ def test_deviceandbrowserinfo(page):return results-def test_creepjs_noise_off(page):- """CreepJS — lie detection with fingerprint noise disabled."""+def test_creepjs(page):+ """CreepJS — lies plus like-headless, headless and stealth scores."""page.goto("https://abrahamjuliot.github.io/creepjs/", wait_until="domcontentloaded", timeout=30000)time.sleep(15)return page.evaluate("""() => {const fp = window.Fingerprint;- if (!fp) return {error: 'Fingerprint not ready', totalLies: null};- const lies = fp.lies || {};- return {totalLies: lies.totalLies || 0};+ const text = document.body.innerText;+ const pct = re => { const m = text.match(re); return m ? parseInt(m[1]) : null; };+ return {+ totalLies: fp ? (fp.lies || {}).totalLies || 0 : null,+ likeHeadless: pct(/(\\d+)%\\s*like headless/i),+ headless: pct(/(\\d+)%\\s*headless:/i),+ stealth: pct(/(\\d+)%\\s*stealth:/i),+ };}""")+def test_recaptcha(page):+ """recaptcha-demo.appspot.com — Google's official reCAPTCHA v3 score."""+ page.goto(+ "https://recaptcha-demo.appspot.com/recaptcha-v3-request-scores.php",+ wait_until="domcontentloaded",+ timeout=30000,+ )+ score = None+ for _ in range(15):+ time.sleep(2)+ score = page.evaluate("""() => {+ const match = document.body.innerText.match(/"score":\\s*(\\d+\\.\\d+)/);+ return match ? parseFloat(match[1]) : null;+ }""")+ if score is not None:+ break+ return {"score": score}+++def recaptcha_verdict(r):+ verdict = f"Score: {r.get('score', 'N/A')}"+ # The score is mostly IP reputation, so a datacenter IP can fail a clean browser.+ if (r.get("score") or 0) < 0.7 and not PROXY:+ verdict += " (low scores usually mean a flagged IP, retry with --proxy <residential proxy>)"+ return verdict++TESTS = [{"name": "bot.sannysoft.com",@@ -163,6 +195,8 @@ TESTS = [+ (" — ALL GREEN"if r.get("failed", 0) == 0+ else " (FAILED: WEBDRIVER — false positive, stock Chrome fails it too)"+ if r.get("failedTests") == ["WEBDRIVER"]else f" (FAILED: {', '.join(r.get('failedTests', []))} — known false positives)"if set(r.get("failedTests", [])) <= {"WEBDRIVER", "connectionRTT"}else f" (FAILED: {', '.join(r.get('failedTests', []))})"@@ -196,12 +230,21 @@ TESTS = ["pass": lambda r: r.get("abnormal", 1) == 0,},{- "name": "CreepJS lies (noise=false)",+ "name": "CreepJS","url": "https://abrahamjuliot.github.io/creepjs/",- "runner": test_creepjs_noise_off,- "verdict": lambda r: f"lies: {r.get('totalLies', 'N/A')}",- "pass": lambda r: r.get("totalLies") == 0,- "args": ["--fingerprint-noise=false"],+ "runner": test_creepjs,+ "verdict": lambda r: f"lies: {r['totalLies']}, like-headless: {r['likeHeadless']}%, "+ f"headless: {r['headless']}%, stealth: {r['stealth']}%",+ "pass": lambda r: r["totalLies"] == 0+ and r["headless"] is not None and r["headless"] <= 30+ and r["stealth"] is not None and r["stealth"] <= 30,+ },+ {+ "name": "reCAPTCHA v3 (Google)",+ "url": "https://recaptcha-demo.appspot.com/recaptcha-v3-request-scores.php",+ "runner": test_recaptcha,+ "verdict": recaptcha_verdict,+ "pass": lambda r: (r.get("score") or 0) >= 0.7,},]@@ -216,8 +259,16 @@ def main():print()print("Launching stealth browser...", flush=True)- browser = launch(headless=not HEADED, proxy=PROXY, geoip=True)- shared_browser_closed = False+ try:+ browser = launch(headless=not HEADED, proxy=PROXY, geoip=True, release_channel="preview")+ except CloakBrowserLicenseError as e:+ # No terminal to ask in (e.g. plain `docker run`): a clear message, not a traceback.+ # With no key at all, the claim link is already printed just above.+ if not str(e).startswith("No CloakBrowser license key"):+ print(f"\n{e}")+ print("\nRun it in a terminal to be asked for a key (Docker: add -it),")+ print("or set CLOAKBROWSER_LICENSE_KEY (Docker: -e CLOAKBROWSER_LICENSE_KEY).")+ sys.exit(1)page = browser.new_page()# Show browser fingerprint details@@ -270,16 +321,9 @@ def main():print(f"--- {name} ---")print(f"URL: {test['url']}")- test_browser = browsertest_context = None- test_page = pagetry:- if test.get("args"):- browser.close()- shared_browser_closed = True- test_browser = launch(headless=not HEADED, proxy=PROXY, geoip=True, args=test["args"])-- test_context = test_browser.new_context(viewport={"width": 1920, "height": 1080})+ test_context = browser.new_context()test_page = test_context.new_page()result = test["runner"](test_page)@@ -301,13 +345,10 @@ def main():finally:if test_context is not None:test_context.close()- if test_browser is not browser:- test_browser.close()print()- if not shared_browser_closed:- browser.close()+ browser.close()# Summary tableprint("=" * 60)diff --git a/js/README.md b/js/README.mdindex a7f6225..e7f4518 100644--- a/js/README.md+++ b/js/README.md@@ -15,7 +15,7 @@ Drop-in Playwright/Puppeteer replacement. Same API, same code — just swap the- **0.9 reCAPTCHA v3 score** — human-level, server-verified- **Passes Cloudflare Turnstile**, FingerprintJS, BrowserScan — tested against 50+ detection sites- **`npm install cloakbrowser`** — binary auto-downloads, auto-updates, zero config-- **Latest binary, free to try** — [sign in with GitHub](https://cloakbrowser.dev/free) for a free key, scale to thousands of sessions on Pro+- **Latest binary, free to try** — [get a free key with your email](https://cloakbrowser.dev/free) (or just launch: the first run asks), scale to thousands of sessions on Pro- **Works with any framework** — tested with browser-use, Crawl4AI, Scrapling, Stagehand ([example](examples/stagehand.ts)), LangChain, Selenium, and more## Install@@ -30,6 +30,8 @@ npm install cloakbrowser puppeteer-coreOn first launch, the stealth Chromium binary auto-downloads (~200MB, cached at `~/.cloakbrowser/`).+**License key:** every launch needs one, and a free key takes one email. The first launch in a terminal asks: get a free key (opens the signup page and continues once you confirm your email) or paste a key you have. In CI, Docker, or any run without a terminal, set `CLOAKBROWSER_LICENSE_KEY` (get one with `npx cloakbrowser login` or at [cloakbrowser.dev/free](https://cloakbrowser.dev/free)).+## Usage### Playwright (default)@@ -161,22 +163,22 @@ const context = await launchContext({ proxy: 'http://proxy:8080', geoip: true })Pre-download the binary or check installation status from the command line:```bash-npx cloakbrowser login # Get a free key via GitHub, or save a paid key-npx cloakbrowser logout # Remove the saved key (revert to the free binary)+npx cloakbrowser login # Get a free key by email, or save a key you have+npx cloakbrowser logout # Remove the saved keynpx cloakbrowser install # Download binary with progress outputnpx cloakbrowser info # Show version, path, platformnpx cloakbrowser update # Check for and download newer binarynpx cloakbrowser clear-cache # Remove cached binaries```-`login` with no argument prompts you to paste a license key or press Enter to get a free key via a GitHub sign-in; `login <key>` saves a key directly. Both validate the key, then store it at `~/.cloakbrowser/license.key` so every launch picks it up.+`login` with no argument shows the same menu as a first launch without a key: **1)** get a free key (opens the signup page in your browser, then waits until you confirm your email) or **2)** paste a key you have. `login <key>` saves a key directly. Keys are validated, then stored at `~/.cloakbrowser/license.key` (readable by you only) so every launch picks them up.### Utilities```javascript-import { ensureBinary, clearCache, binaryInfo, checkForUpdate } from 'cloakbrowser';+import { ensureBinary, clearCache, binaryInfo } from 'cloakbrowser';-// Pre-download binary (e.g., during Docker build)+// Pre-download binary (e.g., during Docker build; needs CLOAKBROWSER_LICENSE_KEY set)await ensureBinary();// Check installation@@ -184,10 +186,6 @@ console.log(binaryInfo());// Force re-downloadclearCache();--// Manually check for newer Chromium version-const newVersion = await checkForUpdate();-if (newVersion) console.log(`Updated to ${newVersion}`);```## Test Results@@ -208,11 +206,10 @@ if (newVersion) console.log(`Updated to ${newVersion}`);| Env Variable | Default | Description ||---|---|---|-| `CLOAKBROWSER_BINARY_PATH` | — | Skip download, use a local Chromium binary. Set `CLOAKBROWSER_VERSION` (or `browserVersion`) to that binary's exact version too, or proxy auth and headless viewport fall back to safe defaults |+| `CLOAKBROWSER_LICENSE_KEY` | — | Your license key (free or paid). Overrides `~/.cloakbrowser/license.key`. Required wherever there is no terminal to ask (CI, Docker) |+| `CLOAKBROWSER_BINARY_PATH` | — | Skip download, use a local Chromium binary || `CLOAKBROWSER_CACHE_DIR` | `~/.cloakbrowser` | Binary cache directory |-| `CLOAKBROWSER_DOWNLOAD_URL` | `cloakbrowser.dev` | Custom download URL |-| `CLOAKBROWSER_AUTO_UPDATE` | `true` | Set to `false` to disable background update checks |-| `CLOAKBROWSER_SKIP_CHECKSUM` | `false` | Set to `true` to skip SHA-256 verification after download |+| `CLOAKBROWSER_AUTO_UPDATE` | `true` | Set to `false` to keep the cached build and skip update checks || `CLOAKBROWSER_VERSION` | — | Pin to an exact Chromium version for rollback (e.g. `154.0.8037.57.1`). Paid Pro key only || `CLOAKBROWSER_RELEASE_CHANNEL` | `stable` | Set to `preview` to opt into the Pro Preview binary channel |@@ -230,13 +227,15 @@ const page = await browser.newPage();## Platforms-| Platform | Free | Pro | Status |-|---|---|---|---|-| Linux x86_64 | Chromium 146 (58 patches) | Chromium 155 (87 patches) | ✅ |-| Linux arm64 (RPi, Graviton) | Chromium 146 (58 patches) | Chromium 155 (87 patches) | ✅ |-| macOS arm64 (Apple Silicon) | Chromium 145 (26 patches) | Chromium 155 (87 patches) | ✅ |-| macOS x86_64 (Intel) | Chromium 145 (26 patches) | Chromium 155 (87 patches) | ✅ |-| Windows x86_64 | Chromium 146 (58 patches) | Chromium 155 (87 patches) | ✅ |+| Platform | Binary | Status |+|---|---|---|+| Linux x86_64 | Chromium 155 (87 patches) | ✅ |+| Linux arm64 (RPi, Graviton) | Chromium 155 (87 patches) | ✅ |+| macOS arm64 (Apple Silicon) | Chromium 155 (87 patches) | ✅ |+| macOS x86_64 (Intel) | Chromium 155 (87 patches) | ✅ |+| Windows x86_64 | Chromium 155 (87 patches) | ✅ |++Free and Pro keys get the same build; Pro raises the number of concurrent sessions.## CloakBrowser Pro@@ -244,14 +243,13 @@ The wrappers (Python, JS, .NET) are MIT, free forever. The latest binary is **frAnti-bot systems change every week and an older binary quietly degrades. The latest build is the one that keeps passing. **Try it free, then upgrade when you're running for real.**-- **Free, latest build (Chromium 156)** — the newest binary, the exact one that stays [green against live detection](#test-results). Free with a GitHub sign-in, one concurrent session. [Grab your key](https://cloakbrowser.dev/free) or run `cloakbrowser login`, then point it at the site that's been blocking you.+- **Free, latest build (Chromium 156)** — the newest binary, the exact one that stays [green against live detection](#test-results). Free with your email, one concurrent session. Just launch (the first run asks), run `npx cloakbrowser login`, or [grab your key](https://cloakbrowser.dev/free), then point it at the site that's been blocking you.- **Pro** — when it's part of production scraping, QA, monitoring, or automation: scale to **5, 20, 200, 2,000, or more concurrent sessions**, always first on the newest patches, with hands-on support. Linux, Windows, macOS. **[See plans and pricing →](https://cloakbrowser.dev)**-- **v146** — the older build stays free on [GitHub Releases](https://github.com/CloakHQ/cloakbrowser/releases). A quick first look, but it ages fast as detection evolves.Get a key and activate it:```bash-cloakbrowser login # GitHub sign-in for a free key, or paste a paid key+npx cloakbrowser login # get a free key by email, or paste a key you have# ...or set it directly (env var, licenseKey option, or ~/.cloakbrowser/license.key):export CLOAKBROWSER_LICENSE_KEY=cb_xxxxxxxx```@@ -328,7 +326,7 @@ Or set `CLOAKBROWSER_RELEASE_CHANNEL=preview` for all launches and CLI commands.**New update broke something? Roll back to the previous version**-Pin to an exact binary version (keep current wrapper, use older Chromium). Paid Pro key only. A free GitHub key cannot pin: it ignores the pin and always gets the latest build.+Pin to an exact binary version (keep current wrapper, use older Chromium). Paid Pro key only. A free key cannot pin: it ignores the pin and always gets the latest build.```bashexport CLOAKBROWSER_VERSION=154.0.8037.57.1 # env var for all launches@@ -346,6 +344,10 @@ Or downgrade the wrapper (if a new wrapper release broke something). With a licenpm install [email protected]```+**Can I still use the old keyless v146 build?**++Yes, through the last wrapper release that runs without a key: `npm install [email protected]`. It downloads the old v146 build (v145 on macOS) from [GitHub Releases](https://github.com/CloakHQ/cloakbrowser/releases), with no key. It is no longer updated and ages fast as detection evolves, so the free key on the latest build is the better choice.+## Links- 🌐 [Website](https://cloakbrowser.dev)@@ -357,6 +359,6 @@ npm install [email protected]## License- **Wrapper code** (this repository) — MIT. See [LICENSE](https://github.com/CloakHQ/CloakBrowser/blob/main/LICENSE).-- **CloakBrowser binary** (compiled Chromium) — no redistribution. v146 and earlier: free, no key. v148 and later: requires a license key, free with a GitHub sign-in (one concurrent session) or a paid [CloakBrowser Pro](https://cloakbrowser.dev) subscription. See [BINARY-LICENSE.md](https://github.com/CloakHQ/CloakBrowser/blob/main/BINARY-LICENSE.md).+- **CloakBrowser binary** (compiled Chromium) — requires a license key: free with your email (one concurrent session), or a paid [CloakBrowser Pro](https://cloakbrowser.dev) subscription. Free for personal and commercial use, no redistribution. See [BINARY-LICENSE.md](https://github.com/CloakHQ/CloakBrowser/blob/main/BINARY-LICENSE.md).Use against financial, banking, healthcare, or government authentication systems without authorization is expressly prohibited.diff --git a/js/src/args.ts b/js/src/args.tsindex a803ee0..91c8025 100644--- a/js/src/args.ts+++ b/js/src/args.ts@@ -3,7 +3,7 @@*/import path from "path";import type { LaunchOptions } from "./types.js";-import { getDefaultStealthArgs, binarySupportsMaximizedWindow } from "./config.js";+import { getDefaultStealthArgs } from "./config.js";const DEBUG = /\bcloakbrowser\b/.test(process.env.DEBUG ?? "");@@ -70,8 +70,6 @@ export function buildArgs(options: LaunchOptions): string[] {// Open maximized (real Chrome overwhelmingly runs maximized) so the window// fills the spoofed screen. Skipped if the caller chose a window geometry or an// explicit viewport (Playwright `viewport` / Puppeteer `defaultViewport`).- // Gated to binaries where this stays coherent (see binarySupportsMaximizedWindow)- // — below the gate it would make outerWidth < innerWidth.// viewport lives on LaunchContextOptions; present at runtime for the// persistent-context path, absent for plain launch. Read defensively.const explicitViewport =@@ -80,15 +78,7 @@ export function buildArgs(options: LaunchOptions): string[] {const hasWindowFlag = ["--start-maximized", "--window-size", "--window-position"].some(k => seen.has(k));- if (- !explicitViewport &&- !hasWindowFlag &&- binarySupportsMaximizedWindow(- options.licenseKey,- options.browserVersion,- options.releaseChannel,- )- ) {+ if (!explicitViewport && !hasWindowFlag) {seen.set("--start-maximized", "--start-maximized");}return [...seen.values()];diff --git a/js/src/cli.ts b/js/src/cli.tsindex 40b847e..696cc55 100644--- a/js/src/cli.ts+++ b/js/src/cli.ts@@ -10,7 +10,14 @@* npx cloakbrowser clear-cache # Remove cached binaries*/-import { ensureBinary, checkForUpdate, checkForProUpdate, clearCache } from "./download.js";+import {+ ensureBinary,+ checkForProUpdate,+ clearCache,+ canPrompt,+ promptLicenseKey,+ PromptClosedError,+} from "./download.js";import {getLocalBinaryOverride,getCacheDir,@@ -21,30 +28,33 @@ import {normalizeReleaseChannel,normalizeRequestedVersion,versionNewer,- CHROMIUM_VERSION,WRAPPER_VERSION,} from "./config.js";import { countFontsPresent, WINDOWS_FONT_TELLS, OFFICE_FONT_TELLS, MACOS_FONT_TELLS } from "./fonts.js";import { resolveProxyGeo } from "./geoip.js";-import { resolveLicenseKey, validateLicense, getProLatestRelease, getSessionSeats, type LicenseInfo } from "./license.js";-import { execFileSync, spawn } from "node:child_process";+import {+ resolveLicenseKey,+ saveLicenseKey,+ validateLicense,+ getProLatestRelease,+ getSessionSeats,+ type LicenseInfo,+} from "./license.js";+import { execFileSync } from "node:child_process";import { createRequire } from "node:module";import { pathToFileURL } from "node:url";-import readline from "node:readline";import fs from "node:fs";import os from "node:os";import path from "node:path";const UPGRADE_HINT = "For more than one concurrent session → https://cloakbrowser.dev";-const FREE_LATEST_HINT =- "Get the latest binary free → run 'cloakbrowser login' or https://cloakbrowser.dev/free";-const FREE_LOGIN_URL = "https://cloakbrowser.dev/api/license/free/github/start";+const NO_KEY_HINT = "Get a free key → run 'cloakbrowser login'";const USAGE = `Usage: cloakbrowser <command>Commands:- login Save a license key (or get a free key via GitHub)- logout Remove the saved license key (revert to free binary)+ login Save a license key (or get a free key by email)+ logout Remove the saved license keyinstall Download the Chromium binaryinfo Environment + binary diagnostics (--quick, --json)doctor Alias for info@@ -111,11 +121,8 @@ function missingSharedLibs(binaryPath: string): string[] {/** Resolve + validate the license the way ensureBinary does. */async function resolveLicense(): Promise<{ license: Record<string, unknown>; entitledPro: boolean }> {- let key = resolveLicenseKey();- // ensureBinary disables Pro routing when a custom download URL is set, so the- // diagnostic must report free too (matches download.ts).- if (process.env.CLOAKBROWSER_DOWNLOAD_URL) key = undefined;- if (!key) return { license: { tier: "free" }, entitledPro: false };+ const key = resolveLicenseKey();+ if (!key) return { license: { tier: "none" }, entitledPro: false };try {const lic: LicenseInfo | null = await validateLicense(key);if (lic === null) return { license: { tier: "unknown", error: "could not validate" }, entitledPro: false };@@ -138,7 +145,6 @@ async function effectiveBinary(latest_version: null,pinned: false,tier: "override",- bundled_version: CHROMIUM_VERSION,path: override,installed: fs.existsSync(override),cache_dir: null,@@ -171,7 +177,7 @@ async function effectiveBinary(} else if (entitledPro) {// Mirror ensureBinary: report what the next launch resolves to, while// CLOAKBROWSER_AUTO_UPDATE=false retains an installed channel build.- installedVersion = getEffectiveVersion(true, requestedChannel);+ installedVersion = getEffectiveVersion(requestedChannel);const autoUpdate = (process.env.CLOAKBROWSER_AUTO_UPDATE ?? "true").toLowerCase();const updatesEnabled = autoUpdate !== "false";if (installedVersion && !updatesEnabled) {@@ -182,10 +188,11 @@ async function effectiveBinary(version = installedVersion ?? latestVersion;}} else {- version = getEffectiveVersion(false);+ // No valid key: nothing launches; report only what is cached.+ version = getEffectiveVersion(requestedChannel);installedVersion = version;}- const binPath = version ? getBinaryPath(version, entitledPro) : null;+ const binPath = version ? getBinaryPath(version) : null;return {version,latest_version: latestVersion,@@ -194,11 +201,10 @@ async function effectiveBinary(channel_fallback: channelFallback,installed_version: installedVersion,pinned: Boolean(requested),- tier: entitledPro ? "pro" : "free",- bundled_version: CHROMIUM_VERSION,+ tier: entitledPro ? "pro" : "none",path: binPath,installed: binPath ? fs.existsSync(binPath) : false,- cache_dir: version ? getBinaryDir(version, entitledPro) : null,+ cache_dir: version ? getBinaryDir(version) : null,override: null,};}@@ -457,14 +463,11 @@ function printDiagnostics(diag: Record<string, any>): void {const lic = diag.license;if (lic.tier === "free" && lic.valid) {- // Validated free-tier key (GitHub login): the latest binary, 1 session.console.log("License: Free (latest binary, 1 concurrent session)");console.log(` ${UPGRADE_HINT}`);- } else if (lic.tier === "free") {- // Keyless: running the older free binary — invite the free-latest login.- console.log("License: Free (no key)");- console.log(` ${FREE_LATEST_HINT}`);- console.log(` ${UPGRADE_HINT}`);+ } else if (lic.tier === "none") {+ console.log("License: none (a launch needs a key)");+ console.log(` ${NO_KEY_HINT}`);} else if (lic.error) {console.log(`License: ${lic.tier} (${lic.error})`);} else {@@ -518,20 +521,16 @@ async function cmdInfo(args: string[]): Promise<void> {}async function cmdUpdate(): Promise<void> {- console.error("Checking for updates...");- // A valid Pro license updates the Pro binary; everyone else updates free.const { entitledPro } = await resolveLicense();- let newVersion: string | null;- let label: string;- if (entitledPro) {- newVersion = await checkForProUpdate(resolveLicenseKey()!);- label = "Pro Chromium";- } else {- newVersion = await checkForUpdate();- label = "Chromium";+ const key = resolveLicenseKey();+ if (!entitledPro || !key) {+ console.error(`No valid license key. ${NO_KEY_HINT}`);+ process.exit(1);}+ console.error("Checking for updates...");+ const newVersion = await checkForProUpdate(key);if (newVersion) {- console.log(`Updated to ${label} ${newVersion}`);+ console.log(`Updated to Chromium ${newVersion}`);} else {console.log("Already up to date.");}@@ -547,77 +546,27 @@ function cmdClearCache(): void {console.log("Cache cleared.");}-/** Persist a validated key to <cacheDir>/license.key (0600). */-function saveLicenseKey(key: string): void {- const cacheDir = getCacheDir();- fs.mkdirSync(cacheDir, { recursive: true });- const keyFile = path.join(cacheDir, "license.key");- fs.writeFileSync(keyFile, key.trim() + "\n");- try {- fs.chmodSync(keyFile, 0o600);- } catch {- // Non-fatal- }-}--/** Prompt for a single line of input, resolving "" on EOF. */-function promptLine(question: string): Promise<string> {- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });- return new Promise<string>((resolve) => {- rl.question(question, (answer) => {- rl.close();- resolve(answer.trim());- });- rl.on("close", () => resolve(""));- });-}--/** Best-effort open a URL in the platform browser (silent on failure). */-function openUrl(url: string): void {- try {- const cmd =- process.platform === "darwin"- ? "open"- : process.platform === "win32"- ? "start"- : "xdg-open";- spawn(cmd, [url], {- stdio: "ignore",- detached: true,- shell: process.platform === "win32",- }).unref();- } catch {- // Non-fatal- }-}--/** Open the GitHub free-key page and read back the emailed key. */-async function promptFreeGithubLogin(): Promise<string> {- console.log(`Opening GitHub sign-in: ${FREE_LOGIN_URL}`);- openUrl(FREE_LOGIN_URL);- console.log("If your browser did not open, visit the URL above and authorize with GitHub.");- console.log("We'll email your free CloakBrowser key to your GitHub email.");- return promptLine("Paste the key from that email here: ");-}-/**- * Activate any key. `login <key>` saves a pasted key; bare `login` prompts to- * paste a key or press ENTER to get a free key via GitHub.+ * Activate any key. `login <key>` saves a pasted key; bare `login` shows the+ * same menu as a no-key launch: get a free key by email, or paste one.*/-async function cmdLogin(rest: string[]): Promise<void> {+export async function cmdLogin(rest: string[]): Promise<void> {let key = (rest[0] ?? "").trim();if (!key) {- if (!process.stdin.isTTY) {+ // The menu is on stderr: with stderr redirected the prompt would be invisible.+ if (!canPrompt()) {console.error("Usage: cloakbrowser login <key> (or run it interactively for a free key).");process.exit(2);}- const entered = await promptLine(- "Paste your license key, or press ENTER to get a free key via GitHub: "- );- key = entered || (await promptFreeGithubLogin());+ try {+ key = await promptLicenseKey();+ } catch (e) {+ if (!(e instanceof PromptClosedError)) throw e;+ key = "";+ }}if (!key) {@@ -637,7 +586,12 @@ async function cmdLogin(rest: string[]): Promise<void> {process.exit(1);}- saveLicenseKey(key);+ try {+ saveLicenseKey(key);+ } catch {+ console.error("That is not a CloakBrowser license key (they start with cb_). Nothing was saved.");+ process.exit(1);+ }if (info.plan === "free") {console.log("Saved. Free tier active: latest binary, 1 concurrent session (one browser at a time)."@@ -649,8 +603,10 @@ async function cmdLogin(rest: string[]): Promise<void> {}}-/** Remove the saved license key (revert to the free binary). */-function cmdLogout(): void {+/** Remove the saved license key. */+export function cmdLogout(): void {+ // A pending claim would bring the key back on the next launch.+ fs.rmSync(path.join(getCacheDir(), ".free_claim"), { force: true });const keyFile = path.join(getCacheDir(), "license.key");if (fs.existsSync(keyFile)) {try {@@ -659,7 +615,7 @@ function cmdLogout(): void {console.error(`Could not remove ${keyFile}: ${(err as Error).message}`);process.exit(1);}- console.log("Logged out. Removed the saved key; launches revert to the free binary.");+ console.log("Logged out. Removed the saved key; launches need a key again.");} else {console.log("No saved license key found.");}diff --git a/js/src/config.ts b/js/src/config.tsindex 1a17ae8..7858dd8 100644--- a/js/src/config.ts+++ b/js/src/config.ts@@ -7,7 +7,6 @@ import fs from "node:fs";import os from "node:os";import path from "node:path";import { fileURLToPath } from "node:url";-import { resolveLicenseKey } from "./license.js";// Read wrapper version from package.json (single source of truth)let WRAPPER_VERSION = "0.0.0";@@ -22,22 +21,6 @@ try {}export { WRAPPER_VERSION };-// ----------------------------------------------------------------------------// Chromium version shipped with this release.-// Different platforms may ship different versions during transition periods.-// CHROMIUM_VERSION is the latest across all platforms (for display/reference).-// Use getChromiumVersion() for the current platform's actual version.-// ----------------------------------------------------------------------------export const CHROMIUM_VERSION = "146.0.7680.177.5";--export const PLATFORM_CHROMIUM_VERSIONS: Record<string, string> = {- "linux-x64": "146.0.7680.177.5",- "linux-arm64": "146.0.7680.177.3",- "darwin-arm64": "145.0.7632.109.2",- "darwin-x64": "145.0.7632.109.2",- "windows-x64": "146.0.7680.177.5",-};-// ---------------------------------------------------------------------------// Ed25519 public keys for verifying downloaded binaries.//@@ -62,9 +45,6 @@ const SUPPORTED_PLATFORMS: Record<string, string> = {"win32-x64": "windows-x64",};-// Platforms with pre-built binaries available for download (derived from version map).-const AVAILABLE_PLATFORMS = new Set(Object.keys(PLATFORM_CHROMIUM_VERSIONS));-const VERSION_PIN_RE = /^[0-9]+(?:\.[0-9]+){3,4}$/;export function normalizeReleaseChannel(releaseChannel?: string): "stable" | "preview" {@@ -86,11 +66,6 @@ export function normalizeRequestedVersion(version?: string): string | undefinedreturn normalized;}-export function getChromiumVersion(): string {- const tag = getPlatformTag();- return PLATFORM_CHROMIUM_VERSIONS[tag] ?? CHROMIUM_VERSION;-}-export function getPlatformTag(): string {const platform = process.platform;const arch = process.arch;@@ -121,13 +96,13 @@ export function getCacheDir(): string {return path.join(os.homedir(), ".cloakbrowser");}-export function getBinaryDir(version?: string, pro = false): string {- const suffix = pro ? "-pro" : "";- return path.join(getCacheDir(), `chromium-${version || getChromiumVersion()}${suffix}`);+/** Cache dir for a build. Kept as "-pro" so existing caches stay valid. */+export function getBinaryDir(version: string): string {+ return path.join(getCacheDir(), `chromium-${version}-pro`);}-export function getBinaryPath(version?: string, pro = false): string {- const binaryDir = getBinaryDir(version, pro);+export function getBinaryPath(version: string): string {+ const binaryDir = getBinaryDir(version);if (process.platform === "darwin") {return path.join(binaryDir, "Chromium.app", "Contents", "MacOS", "Chromium");}@@ -137,31 +112,10 @@ export function getBinaryPath(version?: string, pro = false): string {return path.join(binaryDir, "chrome");}-export function checkPlatformAvailable(): void {- if (getLocalBinaryOverride()) return;-- const tag = getPlatformTag(); // throws if unsupported entirely- if (!AVAILABLE_PLATFORMS.has(tag)) {- const available = [...AVAILABLE_PLATFORMS].sort().join(", ");- throw new Error(- `CloakBrowser — Pre-built binaries are currently only available for: ${available}.\n\n` +- `To use CloakBrowser now, set CLOAKBROWSER_BINARY_PATH to a local Chromium binary.`- );- }-}-// ---------------------------------------------------------------------------// Download URL// ----------------------------------------------------------------------------export const DOWNLOAD_BASE_URL =- process.env.CLOAKBROWSER_DOWNLOAD_URL ||- "https://cloakbrowser.dev";--export const GITHUB_API_URL =- "https://api.github.com/repos/CloakHQ/cloakbrowser/releases";--export const GITHUB_DOWNLOAD_BASE_URL =- "https://github.com/CloakHQ/cloakbrowser/releases/download";+export const DOWNLOAD_BASE_URL = "https://cloakbrowser.dev";export function getArchiveExt(): string {return process.platform === "win32" ? ".zip" : ".tar.gz";@@ -171,72 +125,26 @@ export function getArchiveName(tag?: string): string {return `cloakbrowser-${tag || getPlatformTag()}${getArchiveExt()}`;}-export function getDownloadUrl(version?: string): string {- const v = version || getChromiumVersion();- return `${DOWNLOAD_BASE_URL}/chromium-v${v}/${getArchiveName()}`;-}--export function getFallbackDownloadUrl(version?: string): string {- const v = version || getChromiumVersion();- return `${GITHUB_DOWNLOAD_BASE_URL}/chromium-v${v}/${getArchiveName()}`;-}--export function getEffectiveVersion(pro?: false, releaseChannel?: string): string;-export function getEffectiveVersion(pro: boolean, releaseChannel?: string): string | null;-export function getEffectiveVersion(pro = false, releaseChannel?: string): string | null {- const base = getChromiumVersion();- const cacheDir = getCacheDir();-- if (pro) {- // A valid Pro license must NEVER fall back to the free binary, so there is- // deliberately no free-version fallback here — return null when no cached Pro- // binary matches the marker; callers resolve the latest Pro version instead.- const channel = normalizeReleaseChannel(releaseChannel);- const markerPrefix = channel === "preview"- ? "latest_pro_version_preview"- : "latest_pro_version";- const marker = path.join(cacheDir, `${markerPrefix}_${getPlatformTag()}`);- try {- if (fs.existsSync(marker)) {- const version = fs.readFileSync(marker, "utf-8").trim();- if (version) {- const binary = getBinaryPath(version, true);- // Match launch's proBinaryReady (exists AND executable) so `info` never- // reports a build that launch would reject.- if (fs.existsSync(binary)) {- try {- fs.accessSync(binary, fs.constants.X_OK);- return version;- } catch {- // Present but not executable → not launch-ready.- }- }- }- }- } catch {- // Marker unreadable- }- return null;- }-- // Free tier: try platform-scoped marker first, fall back to legacy marker for upgrades from <0.3.0- for (const name of [`latest_version_${getPlatformTag()}`, "latest_version"]) {- const marker = path.join(cacheDir, name);- try {- if (fs.existsSync(marker)) {- const version = fs.readFileSync(marker, "utf-8").trim();- if (version && versionNewer(version, base)) {- const binary = getBinaryPath(version);- if (fs.existsSync(binary)) {- return version;- }- }- }- } catch {- // Marker unreadable — try next- }+/**+ * The cached build the channel's marker names, or null when nothing usable is+ * cached (callers then resolve the latest build from the server).+ */+export function getEffectiveVersion(releaseChannel?: string): string | null {+ const channel = normalizeReleaseChannel(releaseChannel);+ const markerPrefix = channel === "preview"+ ? "latest_pro_version_preview"+ : "latest_pro_version";+ const marker = path.join(getCacheDir(), `${markerPrefix}_${getPlatformTag()}`);+ try {+ const version = fs.readFileSync(marker, "utf-8").trim();+ if (!version) return null;+ // Match launch's proBinaryReady (exists AND executable) so `info` never+ // reports a build that launch would reject.+ fs.accessSync(getBinaryPath(version), fs.constants.X_OK);+ return version;+ } catch {+ return null; // no marker, or its build is missing / not executable}- return base;}export function parseVersion(v: string): number[] {@@ -260,146 +168,6 @@ export function getLocalBinaryOverride(): string | undefined {return process.env.CLOAKBROWSER_BINARY_PATH || undefined;}-// ----------------------------------------------------------------------------// Headless viewport handling by binary version-// ----------------------------------------------------------------------------// First Chromium build that reports coherent headless dimensions without an-// emulated viewport. On these binaries the wrapper launches headless with no-// viewport; older binaries need a fixed DEFAULT_VIEWPORT to stay coherent.-// null => not shipped yet; feature off, behavior byte-identical to today.-// TODO: set to the chromium version string that first ships it.-export const HEADLESS_NO_VIEWPORT_MIN_VERSION: string | null = "148.0.7778.215.4";--/**- * Whether headless can launch without an emulated viewport on the resolved- * binary. Only binaries at or above HEADLESS_NO_VIEWPORT_MIN_VERSION qualify;- * older ones keep DEFAULT_VIEWPORT. A local override binary- * (CLOAKBROWSER_BINARY_PATH) is unknown-version, so stay on the safe path.- */-export function binarySupportsHeadlessNoViewport(- licenseKey?: string,- browserVersion?: string,- releaseChannel?: string,-): boolean {- if (HEADLESS_NO_VIEWPORT_MIN_VERSION === null) return false;- // A declared version (browserVersion arg OR CLOAKBROWSER_VERSION env) wins even- // under a local override — the caller asserts the version (also how internal builds- // opt in). Only an override with no declared version stays on the safe path.- let declared: string | undefined;- try {- declared = normalizeRequestedVersion(browserVersion);- } catch {- declared = undefined;- }- let version: string | null;- if (declared) {- version = declared;- } else if (getLocalBinaryOverride()) {- return false;- } else {- // Full resolution (param > env > ~/.cloakbrowser/license.key) — mirrors Python- // and .NET; a bare env/param check would miss file-based Pro keys.- const pro = Boolean(resolveLicenseKey(licenseKey));- version = getEffectiveVersion(pro, releaseChannel);- }- // No cached Pro build resolvable (getEffectiveVersion returned null) → fail safe.- if (version === null) return false;- try {- // Fail safe (feature OFF) on a malformed version — parseVersion yields NaN- // instead of throwing, so guard explicitly (Python/.NET throw + fail OFF).- if (parseVersion(version).some(Number.isNaN)) return false;- return !versionNewer(HEADLESS_NO_VIEWPORT_MIN_VERSION, version);- } catch {- return false;- }-}--/**- * Whether the wrapper may auto-add `--start-maximized`. Gated on the same- * threshold as the no_viewport shim: only binaries whose headless surface-fix +- * headed screen-clamp make a maximized window coherent (`outer == screen`).- * Below it, maximizing headless while the CDP viewport stays at 1280x720 yields- * `outerWidth < innerWidth` — a bot tell — so the flag must NOT be added. Shares- * HEADLESS_NO_VIEWPORT_MIN_VERSION; own name so the two can diverge later.- * Python, JS and .NET mirror this gate.- */-export function binarySupportsMaximizedWindow(- licenseKey?: string,- browserVersion?: string,- releaseChannel?: string,-): boolean {- return binarySupportsHeadlessNoViewport(licenseKey, browserVersion, releaseChannel);-}--// ----------------------------------------------------------------------------// Inline HTTP proxy authentication by binary version-// ----------------------------------------------------------------------------// First Chromium build, per platform, whose binary can take inline HTTP proxy-// credentials (Chromium-native `--proxy-server=http://user:pass@host`). Below-// the floor the wrapper MUST route credentialed HTTP/HTTPS proxies through-// Playwright's proxy dict / page.authenticate — an older binary treats the-// `user:pass@` authority as an invalid proxy host and drops proxy auth (#182).-// A single global threshold can't model this: the capability landed in-// different build lineages at different points (linux-x64/windows-x64 at-// 146.0.7680.177.5, but the free macOS 145.x and linux-arm64 146.0.7680.177.3-// floors predate it, qualifying only once they resolve to a Pro/newer 148+-// build). Platforms absent from this map are treated as never-inline.-export const HTTP_PROXY_INLINE_AUTH_MIN_VERSION: Record<string, string> = {- "linux-x64": "146.0.7680.177.5",- "windows-x64": "146.0.7680.177.5",- "linux-arm64": "148.0.7778.215.3",- "darwin-arm64": "148.0.7778.215.3",- "darwin-x64": "148.0.7778.215.3",-};--/**- * Whether the resolved binary accepts inline HTTP proxy credentials. The- * capability is a function of the binary version; `licenseKey` only resolves- * which version launches (Pro build vs free default), exactly like- * binarySupportsHeadlessNoViewport. A declared pin wins, else a valid Pro- * license resolves to the Pro build (which ships the patch), else the free- * per-platform default — then it compares to this platform's floor. Below the- * floor, credentialed HTTP proxies fall back to Playwright's proxy dict. A- * local override with no declared version is unknown-version, so fail safe.- * Python, JS and .NET mirror this gate.- */-export function binarySupportsHttpProxyInlineAuth(- licenseKey?: string,- browserVersion?: string,- releaseChannel?: string,-): boolean {- let tag: string;- try {- tag = getPlatformTag();- } catch {- return false;- }- const floor = HTTP_PROXY_INLINE_AUTH_MIN_VERSION[tag];- if (!floor) return false;- let declared: string | undefined;- try {- declared = normalizeRequestedVersion(browserVersion);- } catch {- declared = undefined;- }- let version: string | null;- if (declared) {- version = declared;- } else if (getLocalBinaryOverride()) {- return false;- } else {- const pro = Boolean(resolveLicenseKey(licenseKey));- version = getEffectiveVersion(pro, releaseChannel);- }- if (version === null) return false;- try {- if (parseVersion(version).some(Number.isNaN)) return false;- return !versionNewer(floor, version);- } catch {- return false;- }-}-// ---------------------------------------------------------------------------// Playwright default args to suppress — these leak automation signals.// --enable-automation: exposes navigator.webdriver = true@@ -411,13 +179,6 @@ export const IGNORE_DEFAULT_ARGS = ["--enable-automation", "--enable-unsafe-swif// ---------------------------------------------------------------------------// Default stealth arguments// ----------------------------------------------------------------------------// Default viewport — used for HEADLESS only (headed launches use no viewport so-// the page tracks the real window). Headless has no window chrome, so a fixed-// viewport stays coherent (outer == inner) and gives deterministic dimensions.-// Models a maximized Chrome on 1080p Windows: screen=1920x1080,-// innerHeight=947 (minus ~85px Chrome UI: tabs + address bar + bookmarks).-export const DEFAULT_VIEWPORT = { width: 1920, height: 947 };-export const SEED_MIN = 10000;export const SEED_MAX = 99999;diff --git a/js/src/download.ts b/js/src/download.tsindex 964ccc9..c1ba77b 100644--- a/js/src/download.ts+++ b/js/src/download.ts@@ -4,52 +4,55 @@* Mirrors Python cloakbrowser/download.py.*/-import { execFileSync } from "node:child_process";+import { execFileSync, spawn } from "node:child_process";import { createHash, createPublicKey, randomUUID, verify as cryptoVerify } from "node:crypto";import fs from "node:fs";import path from "node:path";+import readline from "node:readline";+import { isMainThread } from "node:worker_threads";import { createWriteStream } from "node:fs";import { extract as tarExtract } from "tar";import type { BinaryInfo } from "./types.js";import {BINARY_SIGNING_PUBKEYS,- CHROMIUM_VERSION,DOWNLOAD_BASE_URL,- GITHUB_API_URL,- GITHUB_DOWNLOAD_BASE_URL,WRAPPER_VERSION,- checkPlatformAvailable,getArchiveExt,getArchiveName,getBinaryDir,getBinaryPath,getCacheDir,- getChromiumVersion,- getDownloadUrl,getEffectiveVersion,- getFallbackDownloadUrl,getLocalBinaryOverride,getPlatformTag,normalizeReleaseChannel,normalizeRequestedVersion,versionNewer,} from "./config.js";-import { resolveLicenseKey, validateLicense, getProLatestVersion, getProLatestRelease } from "./license.js";+import {+ CloakBrowserLicenseError,+ FreeKeyAlreadyHeld,+ KEY_RE,+ checkClaim,+ claimLink,+ getClaimCode,+ pollClaim,+ resolveLicenseKey,+ saveLicenseKey,+ validateLicense,+ getProLatestVersion,+ getProLatestRelease,+} from "./license.js";const DOWNLOAD_TIMEOUT_MS = 600_000; // 10 minutes-// Seconds, matching the Python/.NET `.last_update_check` marker format so the-// three wrappers share one cache dir without corrupting each other's rate limit.-const UPDATE_CHECK_INTERVAL_SEC = 3600; // 1 hour-// Free-tier welcome banner re-show interval (1 day, in seconds). Free users see+// How long a background claim poll keeps checking for the key (see claimFreeKey).+const CLAIM_POLL_WINDOW_MS = 600_000;+// Free-key welcome banner re-show interval (1 day, in seconds). Free users see// the upsell again after this gap; Pro users see it only once (see showWelcome).// Seconds (not ms) so the shared marker is consistent with the Python/.NET wrappers.// @internal Exported for testing only.export const WELCOME_FREE_INTERVAL_SEC = 1 * 24 * 60 * 60;-// Pro Chromium major shown in the welcome banner. Bump at each Pro major release-// (no local constant to derive it from — the live Pro version comes from the-// network, which we don't call just to print a banner). Mirrors download.py.-const PRO_MAJOR = "155";// Attempts to rename an extraction into place while concurrent callers are// replacing the same partial install (see extractArchive).const INSTALL_RENAME_ATTEMPTS = 5;@@ -62,8 +65,8 @@ const TRANSIENT_RENAME_DELAY_MS = 250;* A downloaded binary could not be authenticated (bad/missing signature,* version mismatch, or checksum failure). Distinct from transient* download/network errors: a verification failure is a tampering signal and- * MUST surface, never silently fall back to another binary. The Pro routing in- * ensureBinary re-throws this rather than downgrading to the free tier.+ * MUST surface, never silently fall back to another binary. The routing in+ * ensureBinary re-throws this rather than falling back to a cached build.*/export class BinaryVerificationError extends Error {constructor(message: string) {@@ -99,119 +102,258 @@ export async function ensureBinary(const requestedVersion = normalizeRequestedVersion(browserVersion);- // Pro license key check (custom download URL overrides Pro path)- const key = resolveLicenseKey(licenseKey);- const effectiveKey = process.env.CLOAKBROWSER_DOWNLOAD_URL ? undefined : key;- if (effectiveKey) {- const info = await validateLicense(effectiveKey);- if (info?.valid) {- // Free tier always gets the latest build. Drop any version pin: the server- // force-serves latest to free keys, so fetching a pinned version's signed- // manifest would mismatch the served bytes and fail checksum verification.- // Paid keys keep pinning/rollback.- const proVersion = info.plan === "free" ? undefined : requestedVersion;- // A valid license is entitled to Pro, so Pro failures surface loudly- // rather than silently substituting the older free binary. (A blip during- // a routine update never reaches here: ensureProBinary returns the cached- // Pro binary and updates in the background.)- try {- return await ensureProBinary(- effectiveKey,- proVersion,- info.plan,- releaseChannel,- );- } catch (e) {- // Authenticity could not be confirmed — surface verbatim.- if (e instanceof BinaryVerificationError) throw e;- // Transient failure with no cached Pro binary to use — surface a clear- // error rather than silently downloading the free binary.- throw new Error(- `Pro binary unavailable: ${e}. Your license is valid but the Pro ` +- `binary could not be downloaded right now. Retry in a moment. To use ` +- `the free binary instead, unset CLOAKBROWSER_LICENSE_KEY.`,- { cause: e }- );- }- } else if (info) {- // Key supplied but rejected — abort, never downgrade to free.- throw new Error(- `CloakBrowser Pro: license key is invalid or expired (plan=${info.plan}). ` +- `Check CLOAKBROWSER_LICENSE_KEY, or unset it to use the free binary.`,- );- } else {- // Key supplied but unvalidatable (server down, no cache) — abort.+ // No key anywhere (param, env, license.key) -> get a free one first.+ const key = resolveLicenseKey(licenseKey) ?? (await claimFreeKey());+ const info = await validateLicense(key);+ if (info?.valid) {+ maybeTriggerUpdateCheck();+ // A free key always gets the latest build. Drop any version pin: the server+ // force-serves latest to free keys, so fetching a pinned version's signed+ // manifest would mismatch the served bytes and fail checksum verification.+ // Paid keys keep pinning/rollback.+ const pinned = info.plan === "free" ? undefined : requestedVersion;+ // (A blip during a routine update never reaches the error below:+ // ensureProBinary returns the cached build and retries next launch.)+ try {+ return await ensureProBinary(key, pinned, info.plan, releaseChannel);+ } catch (e) {+ // Authenticity could not be confirmed — surface verbatim.+ if (e instanceof BinaryVerificationError) throw e;throw new Error(- "CloakBrowser Pro: license could not be validated (server unreachable " +- "and no cached validation). Retry in a moment, or unset " +- "CLOAKBROWSER_LICENSE_KEY to use the free binary.",+ `CloakBrowser binary unavailable: ${e}. Your license is valid but the ` ++ `binary could not be downloaded right now. Retry in a moment.`,+ { cause: e });}}+ if (info) {+ throw new CloakBrowserLicenseError(+ `CloakBrowser: license key is invalid or expired (plan=${info.plan}). ` ++ `Check CLOAKBROWSER_LICENSE_KEY or ~/.cloakbrowser/license.key, or get ` ++ `a free key with: cloakbrowser login`,+ );+ }+ throw new CloakBrowserLicenseError(+ "CloakBrowser: license could not be validated (server unreachable and " ++ "no cached validation). Retry in a moment.",+ );+}- // Fail fast if no binary available for this platform- checkPlatformAvailable();+// ---------------------------------------------------------------------------+// No key: the free-key menu and claim flow (mirrors Python download.py)+// ---------------------------------------------------------------------------- if (requestedVersion) {- const binaryPath = getBinaryPath(requestedVersion);- if (fs.existsSync(binaryPath) && isExecutable(binaryPath)) {- showWelcome();- return binaryPath;- }+export const HAS_KEY_MSG =+ "This email already has a free key. It's in the email we sent when you " ++ "first got it (search your mail for CloakBrowser).";- console.error(- `[cloakbrowser] Stealth Chromium ${requestedVersion} not found. Downloading for ${getPlatformTag()}...`- );- await downloadAndExtract(requestedVersion);+/** stdin closed before the menu got an answer (EOF). */+export class PromptClosedError extends Error {+ constructor() {+ super("stdin closed");+ this.name = "PromptClosedError";+ }+}- if (!fs.existsSync(binaryPath) || !isExecutable(binaryPath)) {- throw new Error(- `Pinned download completed but binary not found at expected path: ${binaryPath}. ` +- `This may indicate a packaging issue. Please report at ` +- `https://github.com/CloakHQ/cloakbrowser/issues`- );- }- showWelcome();- return binaryPath;+/** Cosmetic stderr output that can never break a launch. */+function emit(text: string): void {+ try {+ process.stderr.write(text);+ } catch {+ // A banner or prompt line must never be able to kill a launch.}+}- // Check for auto-updated version first, then fall back to hardcoded- const effective = getEffectiveVersion();- const binaryPath = getBinaryPath(effective);+/** A person is at this terminal (and we're on the main thread). */+export function canPrompt(): boolean {+ return isMainThread && Boolean(process.stdin.isTTY) && Boolean(process.stderr.isTTY);+}- if (fs.existsSync(binaryPath) && isExecutable(binaryPath)) {- showWelcome();- maybeTriggerUpdateCheck();- return binaryPath;+/** Ask one line on stderr (a script's stdout may be its data). */+function ask(question: string): Promise<string> {+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });+ return new Promise<string>((resolve, reject) => {+ let answered = false;+ // Closed without an answer (EOF). close() also pauses stdin, so the+ // interface never keeps the process alive.+ rl.on("close", () => {+ if (!answered) reject(new PromptClosedError());+ });+ // Ctrl+C means stop, like it does everywhere else. Without this listener+ // readline just closes, which would read as EOF and print the link + error.+ rl.on("SIGINT", () => {+ emit("\n");+ process.exit(130);+ });+ rl.question(question, (answer) => {+ answered = true;+ rl.close();+ resolve(answer.trim());+ });+ });+}++/** Best-effort open a URL in the platform browser. */+function openUrl(url: string): boolean {+ try {+ // Windows: `start` is a cmd builtin; call cmd directly (no shell: true, which+ // Node 24 deprecates with args). The empty "" is start's window title.+ const [cmd, args]: [string, string[]] =+ process.platform === "darwin" ? ["open", [url]]+ : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]]+ : ["xdg-open", [url]];+ const child = spawn(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });+ child.on("error", () => { }); // no opener installed: the printed link is enough+ child.unref();+ return true;+ } catch {+ return false;}+}- // Fall back to platform's hardcoded version if effective version binary doesn't exist- const platformVersion = getChromiumVersion();- if (effective !== platformVersion) {- const fallbackPath = getBinaryPath();- if (fs.existsSync(fallbackPath) && isExecutable(fallbackPath)) {- maybeTriggerUpdateCheck();- return fallbackPath;+function emitWelcome(): void {+ emit("\n Welcome to CloakBrowser - stealth Chromium for automation\n");+ emit(" https://github.com/CloakHQ/CloakBrowser\n\n");+ emit(" CloakBrowser needs a license key.\n\n");+}++/**+ * Terminal menu shared by a no-key launch and `cloakbrowser login`: get a free+ * key by email or paste one. Returns a valid key, already saved.+ * Throws PromptClosedError if stdin closes.+ */+export async function promptLicenseKey(): Promise<string> {+ emitWelcome();+ emit(" 1) Get a free key (by email: the latest build, 1 concurrent session)\n");+ emit(" 2) Paste a key I already have\n\n");+ for (;;) {+ const choice = await ask(" Choose 1 or 2 [1]: ");+ if (choice === "" || choice === "1") {+ const key = await getFreeKey();+ if (key) return key;+ emit(`\n ${HAS_KEY_MSG}\n`);+ } else if (choice !== "2") {+ emit(" Please type 1 or 2.\n");+ continue;}+ const key = await pasteKey();+ if (key) return key;}+}- // Download platform's hardcoded version- console.error(- `[cloakbrowser] Stealth Chromium ${platformVersion} not found. Downloading for ${getPlatformTag()}...`- );- await downloadAndExtract();+/** Ask until a valid key is pasted (saved, returned) or the answer is empty. */+async function pasteKey(): Promise<string | undefined> {+ for (;;) {+ const key = await ask(" Paste your key (empty to go back): ");+ if (!key) return undefined;+ if (!KEY_RE.test(key)) {+ emit(" That is not a CloakBrowser key (they start with cb_).\n");+ continue;+ }+ const info = await validateLicense(key);+ if (info === null) {+ emit(" Could not reach the license server. Check your connection and retry.\n");+ } else if (!info.valid) {+ emit(" That key is invalid or expired.\n");+ } else {+ saveLicenseKey(key);+ emit(" Key saved.\n\n");+ // The menu was the welcome; a paid key keeps its one-time Pro banner.+ if (info.plan === "free") markWelcomeShown();+ return key;+ }+ }+}- const downloadedPath = getBinaryPath();- if (!fs.existsSync(downloadedPath)) {- throw new Error(- `Download completed but binary not found at expected path: ${downloadedPath}. ` +- `This may indicate a packaging issue. Please report at ` +- `https://github.com/CloakHQ/cloakbrowser/issues`- );+/**+ * Open the claim link and wait for the key (saved, returned). undefined if the+ * email already has a key, which the server never sends to a claim.+ */+async function getFreeKey(): Promise<string | undefined> {+ const code = getClaimCode();+ const link = claimLink(code);+ emit(`\n Open this link and enter your email:\n ${link}\n`);+ if (openUrl(link)) emit(" (opened in your browser)\n");+ emit("\n Waiting for you to confirm your email... (Ctrl+C to stop)\n");+ let key: string | undefined;+ try {+ key = await pollClaim(code, { overwrite: true });+ } catch (e) {+ if (e instanceof FreeKeyAlreadyHeld) return undefined;+ throw e;}+ emit(" Free key saved.\n\n");+ markWelcomeShown(); // the menu was the welcome: no second banner this launch+ return key;+}- maybeTriggerUpdateCheck();- return downloadedPath;+let claimPollStarted = false;++/** @internal Exported for testing only. */+export function resetClaimPollStarted(): void {+ claimPollStarted = false;+}++/**+ * No key anywhere: get one before launching. A person at a terminal gets the+ * menu (promptLicenseKey). Anything else (CI, Docker, an MCP server, a worker+ * thread) throws with the claim link and keeps polling in the background, so a+ * long-lived process picks the key up and its next launch works.+ */+async function claimFreeKey(): Promise<string> {+ let code = getClaimCode();+ let key: string | undefined;+ try {+ key = await checkClaim(code);+ } catch (e) {+ if (!(e instanceof FreeKeyAlreadyHeld)) throw e;+ if (!canPrompt()) {+ throw new CloakBrowserLicenseError(+ `${HAS_KEY_MSG} Set CLOAKBROWSER_LICENSE_KEY or run: cloakbrowser login`,+ );+ }+ // the menu below starts over with a fresh code+ }+ if (key) {+ // confirmed since an earlier launch printed the link+ saveLicenseKey(key, { overwrite: false });+ return key;+ }+ if (canPrompt()) {+ try {+ return await promptLicenseKey();+ } catch (e) {+ if (!(e instanceof PromptClosedError)) throw e;+ // stdin closed mid-menu: fall through to the link + error+ }+ }+ code = getClaimCode(); // fresh if the old one was retired+ const link = claimLink(code);+ emitWelcome();+ emit(` Get one free (the latest build, 1 concurrent session):\n ${link}\n` ++ " After you confirm, the key is also emailed to you.\n\n");+ startClaimPoll(code);+ throw new CloakBrowserLicenseError(+ `No CloakBrowser license key. Get one free: ${link} ` ++ "(or run: cloakbrowser login), then launch again.",+ );+}++/** Poll for the claimed key in the background, once per process (timers unref'd). */+function startClaimPoll(code: string): void {+ if (claimPollStarted) return;+ claimPollStarted = true;+ pollClaim(code, { deadline: Date.now() + CLAIM_POLL_WINDOW_MS })+ .then((key) => {+ if (key) emit("\n CloakBrowser: free key saved. The next launch uses it.\n");+ })+ .catch((e) => {+ if (e instanceof FreeKeyAlreadyHeld) {+ emit(`\n CloakBrowser: ${HAS_KEY_MSG}\n Set CLOAKBROWSER_LICENSE_KEY or run: cloakbrowser login\n`);+ } else {+ console.warn(`[cloakbrowser] Could not save the claimed free key: ${e}`);+ }+ });}/** Remove all cached binaries. Forces re-download on next launch. */@@ -224,58 +366,27 @@ export function clearCache(): void {}/**- * Return info about the current binary installation.- *- * tier reflects what is actually installed on disk, not merely whether a license- * is cached — a cached license with no Pro binary downloaded yet is still- * effectively running the free binary, and the active key may differ from the- * cached one.+ * Return info about the cached binary installation. browserVersion (or+ * CLOAKBROWSER_VERSION) pins the reported version so the info matches what a+ * pinned launch actually runs, instead of latest. version is null until a+ * build has been downloaded.*/export function binaryInfo(browserVersion?: string,releaseChannel?: string,): BinaryInfo {- // browserVersion (or CLOAKBROWSER_VERSION) pins the reported version so the- // info matches what a pinned launch actually runs, instead of latest.- const requested = normalizeRequestedVersion(browserVersion);- // Prefer Pro only if a Pro binary actually exists on disk. getEffectiveVersion- // returns null for Pro when nothing is cached (it never falls back to free).- const proVersion = requested ?? getEffectiveVersion(true, releaseChannel);- const isPro = proBinaryReady(proVersion);-- const effective = isPro ? proVersion : (requested ?? getEffectiveVersion(false));- const binaryPath = isPro ? getBinaryPath(proVersion, true) : getBinaryPath(effective, false);+ const version = normalizeRequestedVersion(browserVersion) ?? getEffectiveVersion(releaseChannel);+ const preview = normalizeReleaseChannel(releaseChannel) === "preview";return {- version: effective,- bundledVersion: CHROMIUM_VERSION,- tier: isPro ? "pro" : "free",+ version,platform: getPlatformTag(),- binaryPath,- installed: fs.existsSync(binaryPath),- cacheDir: getBinaryDir(effective, isPro),- downloadUrl: isPro- ? `${DOWNLOAD_BASE_URL}/api/download/latest${normalizeReleaseChannel(releaseChannel) === "preview" ? "?channel=preview" : ""}`- : getDownloadUrl(effective),+ binaryPath: version ? getBinaryPath(version) : null,+ installed: proBinaryReady(version),+ cacheDir: version ? getBinaryDir(version) : null,+ downloadUrl: `${DOWNLOAD_BASE_URL}/api/download/latest${preview ? "?channel=preview" : ""}`,};}-/** Manually check for a newer Chromium version. Returns new version or null. */-export async function checkForUpdate(): Promise<string | null> {- const latest = await getLatestChromiumVersion();- if (!latest || !versionNewer(latest, getChromiumVersion())) return null;-- const binaryDir = getBinaryDir(latest);- if (fs.existsSync(binaryDir)) {- writeVersionMarker(latest);- return latest;- }-- console.error(`[cloakbrowser] Downloading Chromium ${latest}...`);- await downloadAndExtract(latest);- writeVersionMarker(latest);- return latest;-}-/*** Move a Pro install to the selected channel's latest. Blocks until complete.* Returns the new version when a newer Pro build is downloaded or an@@ -289,7 +400,7 @@ export async function checkForProUpdate(const latest = await getProLatestVersion(releaseChannel);if (!latest) return null;- const effective = getEffectiveVersion(true, releaseChannel);+ const effective = getEffectiveVersion(releaseChannel);if (effective && !versionNewer(latest, effective) && proBinaryReady(effective)) {// Already on the latest cached Pro build.return null;@@ -298,9 +409,9 @@ export async function checkForProUpdate(if (!proBinaryReady(latest)) {console.error(`[cloakbrowser] Downloading Pro Chromium ${latest}...`);await downloadProBinary(latest, licenseKey);- if (!fs.existsSync(getBinaryPath(latest, true))) {+ if (!fs.existsSync(getBinaryPath(latest))) {throw new Error(- `Pro download completed but binary not found at: ${getBinaryPath(latest, true)}`+ `Pro download completed but binary not found at: ${getBinaryPath(latest)}`);}}@@ -333,16 +444,6 @@ export function welcomeDue(marker: string, pro: boolean): boolean {}}-/**- * Show welcome message on launch. A marker file gates the cadence: a paid (Pro)- * key shows once ever; free (keyless or a free GitHub key) re-shows every- * WELCOME_FREE_INTERVAL_SEC.- *- * tier:- * "pro" — a paid license key (Pro banner + support address)- * "free" — a free GitHub key (latest binary, one concurrent session)- * "keyless" — no key, running the older free binary (invite the free login)- */let previewFallbackWarned = false;/** @internal Exported for testing only. */@@ -362,8 +463,17 @@ function warnPreviewFallback(): void {);}-// Exported for tests only; not re-exported from the package index.-export function showWelcome(tier = "keyless"): void {+/**+ * Show welcome message on launch. A marker file gates the cadence: a paid (Pro)+ * key shows once ever; a free key re-shows every WELCOME_FREE_INTERVAL_SEC.+ *+ * tier:+ * "pro" — a paid license key (Pro banner + support address)+ * "free" — a free key (latest binary, one concurrent session)+ *+ * Exported for tests only; not re-exported from the package index.+ */+export function showWelcome(tier: "pro" | "free"): void {const marker = path.join(getCacheDir(), ".welcome_shown");if (!welcomeDue(marker, tier === "pro")) return;// ASCII-only banner: on a legacy Windows console a non-ASCII glyph can@@ -371,38 +481,29 @@ export function showWelcome(tier = "keyless"): void {// Keep the three wrappers byte-parallel.console.error();console.error(" CloakBrowser - stealth Chromium for automation");- console.error(" https://github.com/CloakHQ/CloakBrowser");- console.error();if (tier === "pro") {- console.error(- ` CloakBrowser Pro active (v${PRO_MAJOR}) - latest binary, newest patches.`,- );+ console.error(" CloakBrowser Pro active.");+ console.error();console.error(" Pro support -> [email protected]");- } else if (tier === "free") {- console.error(- ` CloakBrowser free (v${PRO_MAJOR}): the latest binary, 1 concurrent session.`,- );- console.error(- " For more than one concurrent session -> https://cloakbrowser.dev",- );+ console.error(" Site -> https://cloakbrowser.dev");} else {- const freeMajor = CHROMIUM_VERSION.split(".")[0];- console.error(- ` Running the free binary (v${freeMajor}). ` +- `The latest binary (v${PRO_MAJOR}) is free too, with 1 concurrent session.`,- );- console.error(- " Get your key: run cloakbrowser login or visit https://cloakbrowser.dev/free",- );- console.error(- " For more than one concurrent session -> https://cloakbrowser.dev",- );+ console.error(" CloakBrowser free: 1 concurrent session.");+ console.error();+ console.error(" For more than one concurrent session -> https://cloakbrowser.dev");}+ console.error(" Docs -> https://github.com/CloakHQ/CloakBrowser");console.error(" Star us if CloakBrowser helps your project!");console.error();+ markWelcomeShown();+}++function markWelcomeShown(): void {try {fs.mkdirSync(getCacheDir(), { recursive: true });- fs.writeFileSync(marker, String(Math.floor(Date.now() / 1000)));+ fs.writeFileSync(+ path.join(getCacheDir(), ".welcome_shown"),+ String(Math.floor(Date.now() / 1000)),+ );} catch {// Non-fatal}@@ -412,120 +513,6 @@ export function showWelcome(tier = "keyless"): void {// Internal helpers// ----------------------------------------------------------------------------async function downloadAndExtract(version?: string): Promise<void> {- const primaryUrl = getDownloadUrl(version);- const fallbackUrl = getFallbackDownloadUrl(version);- const binaryDir = getBinaryDir(version);- const binaryPath = getBinaryPath(version);-- // Create cache dir- fs.mkdirSync(path.dirname(binaryDir), { recursive: true });-- // Download to temp file (atomic — no partial downloads in cache)- const tmpPath = path.join(- path.dirname(binaryDir),- `_download_${randomUUID()}${getArchiveExt()}`- );-- try {- // Try primary server, fall back to GitHub Releases (skip fallback if custom URL)- try {- await downloadFile(primaryUrl, tmpPath);- } catch (primaryErr) {- if (process.env.CLOAKBROWSER_DOWNLOAD_URL) {- throw primaryErr;- }- console.warn(- `[cloakbrowser] Primary download failed (${primaryErr instanceof Error ? primaryErr.message : primaryErr}), trying GitHub Releases...`- );- await downloadFile(fallbackUrl, tmpPath);- }-- // Verify the download before extraction. On the official path this is a- // mandatory, non-bypassable Ed25519 signature check (see- // verifyDownloadChecksum); the skip flag only applies to custom- // self-hosted CLOAKBROWSER_DOWNLOAD_URL setups.- await verifyDownloadChecksum(tmpPath, version);-- await extractArchive(tmpPath, binaryDir, binaryPath);- showWelcome();- } finally {- // Clean up temp file- if (fs.existsSync(tmpPath)) {- fs.unlinkSync(tmpPath);- }- }-}--/** @internal Exported for testing only. */-export async function verifyDownloadChecksum(filePath: string, version?: string): Promise<void> {- const tarballName = getArchiveName();-- if (process.env.CLOAKBROWSER_DOWNLOAD_URL) {- // Self-hosted mirror: the pinned signature keys do not apply to a- // third-party server. Preserve the legacy same-origin checksum behavior,- // skippable via CLOAKBROWSER_SKIP_CHECKSUM.- if (process.env.CLOAKBROWSER_SKIP_CHECKSUM?.toLowerCase() === "true") {- console.warn(- "[cloakbrowser] CLOAKBROWSER_SKIP_CHECKSUM set — skipping verification for custom download URL"- );- return;- }- const checksums = await fetchChecksums(version);- if (!checksums) {- console.warn(- "[cloakbrowser] SHA256SUMS not available from custom URL — skipping checksum verification"- );- return;- }- const expectedCustom = checksums.get(tarballName);- if (!expectedCustom) {- console.warn(- `[cloakbrowser] SHA256SUMS found but no entry for ${tarballName} — skipping verification`- );- return;- }- await verifyChecksum(filePath, expectedCustom);- return;- }-- // Official path: signature is the trust root and is non-bypassable.- const manifest = await fetchSignedManifest(version);- if (!manifest) {- throw new Error(- "Could not fetch a signed SHA256SUMS (SHA256SUMS + SHA256SUMS.sig) for " +- "this release — refusing to use an unverified binary. " +- "Retry, or report at https://github.com/CloakHQ/cloakbrowser/issues"- );- }- const { manifestBytes, sigBytes } = manifest;- verifySignature(manifestBytes, sigBytes);- const manifestText = new TextDecoder().decode(manifestBytes);-- // Version binding: the signed manifest must declare the version we asked for.- // The signature proves "we made this manifest", not "this is the version you- // requested" — without this check a mirror could serve a genuinely-signed- // older release in place of the requested one (forced downgrade).- const requested = version || getChromiumVersion();- const declared = parseManifestVersion(manifestText);- if (declared !== requested) {- throw new Error(- `Version mismatch in signed SHA256SUMS: requested ${requested}, ` +- `manifest declares ${declared ?? "none"}. Refusing (possible downgrade).`- );- }-- const checksums = parseChecksums(manifestText);- const expected = checksums.get(tarballName);- if (!expected) {- throw new Error(- `Signature-verified SHA256SUMS has no entry for ${tarballName} — ` +- `cannot confirm binary integrity.`- );- }- await verifyChecksum(filePath, expected);-}-/*** Read the 'version=<v>' line from a signed manifest. null if absent.* The line has no internal whitespace so older wrappers' SHA256SUMS parsers@@ -542,43 +529,6 @@ export function parseManifestVersion(text: string): string | null {return null;}-/**- * Fetch (SHA256SUMS, SHA256SUMS.sig) raw bytes for a version, or null.- * Both files come from the SAME origin so the signature always matches the- * exact manifest bytes it certifies. Primary origin first, then GitHub mirror.- * @internal Exported for testing only.- */-export async function fetchSignedManifest(- version?: string-): Promise<{ manifestBytes: Uint8Array; sigBytes: Uint8Array } | null> {- const v = version || getChromiumVersion();- const bases = [- `${DOWNLOAD_BASE_URL}/chromium-v${v}`,- `${GITHUB_DOWNLOAD_BASE_URL}/chromium-v${v}`,- ];- for (const base of bases) {- try {- const manifestResp = await fetch(`${base}/SHA256SUMS`, {- redirect: "follow",- signal: AbortSignal.timeout(10_000),- });- if (!manifestResp.ok) continue;- const sigResp = await fetch(`${base}/SHA256SUMS.sig`, {- redirect: "follow",- signal: AbortSignal.timeout(10_000),- });- if (!sigResp.ok) continue;- return {- manifestBytes: new Uint8Array(await manifestResp.arrayBuffer()),- sigBytes: new Uint8Array(await sigResp.arrayBuffer()),- };- } catch {- // Try the next manifest origin.- }- }- return null;-}-/*** Verify a detached Ed25519 signature over the raw manifest bytes.* sigB64Bytes is the (base64-text) content of SHA256SUMS.sig. Tries each pinned@@ -628,32 +578,6 @@ export function verifySignature(manifestBytes: Uint8Array, sigB64Bytes: Uint8Arr);}-/** @internal Exported for testing only. */-export async function fetchChecksums(version?: string): Promise<Map<string, string> | null> {- const v = version || getChromiumVersion();- const hasCustomUrl = !!process.env.CLOAKBROWSER_DOWNLOAD_URL;-- // Respect custom URL contract — no GitHub fallback when custom URL is set- const urls = [`${DOWNLOAD_BASE_URL}/chromium-v${v}/SHA256SUMS`];- if (!hasCustomUrl) {- urls.push(`${GITHUB_DOWNLOAD_BASE_URL}/chromium-v${v}/SHA256SUMS`);- }-- for (const url of urls) {- try {- const resp = await fetch(url, {- redirect: "follow",- signal: AbortSignal.timeout(10_000),- });- if (!resp.ok) continue;- return parseChecksums(await resp.text());- } catch {- // Try the next checksum origin.- }- }- return null;-}-/** @internal Exported for testing only. */export function parseChecksums(text: string): Map<string, string> {const result = new Map<string, string>();@@ -771,7 +695,7 @@ async function downloadFile(url: string, dest: string, headers?: Record<string,/** True when a cached, executable Pro binary exists for `version`. */function proBinaryReady(version: string | null): version is string {if (!version) return false;- const p = getBinaryPath(version, true);+ const p = getBinaryPath(version);return fs.existsSync(p) && isExecutable(p);}@@ -789,16 +713,16 @@ function writeProVersionMarker(version: string, releaseChannel?: string): void {fs.renameSync(tmp, marker);}-// A valid Pro license NEVER falls back to the free binary. If the latest Pro build-// cannot be resolved or downloaded and no cached Pro binary exists, the error is-// thrown rather than silently launching the free tier.+// Used for free keys (plan "free") and paid keys alike — both fetch the same+// latest build; the server enforces the concurrency cap. If the latest build+// cannot be resolved or downloaded and none is cached, the error is thrown.async function ensureProBinary(licenseKey: string,requestedVersion?: string,plan?: string,releaseChannel?: string,): Promise<string> {- // Banner tier: a free GitHub key gets the free banner, paid keys the Pro one.+ // Banner tier: a free key gets the free banner, paid keys the Pro one.const welcomeTier = plan === "free" ? "free" : "pro";// Pinned: launch the exact requested version, no server cross-check, no marker@@ -806,13 +730,13 @@ async function ensureProBinary(if (requestedVersion) {if (proBinaryReady(requestedVersion)) {showWelcome(welcomeTier);- return getBinaryPath(requestedVersion, true);+ return getBinaryPath(requestedVersion);}console.error(`[cloakbrowser] Downloading Pro Chromium ${requestedVersion} for ${getPlatformTag()}...`);await downloadProBinary(requestedVersion, licenseKey);- const p = getBinaryPath(requestedVersion, true);+ const p = getBinaryPath(requestedVersion);if (!fs.existsSync(p)) {throw new Error(`Pro download completed but binary not found at: ${p}`);}@@ -821,17 +745,16 @@ async function ensureProBinary(}// Unpinned: track the server's latest selected channel.- const effective = getEffectiveVersion(true, releaseChannel);+ const effective = getEffectiveVersion(releaseChannel);- // Honor CLOAKBROWSER_AUTO_UPDATE=false the way the free path does: frozen AND a- // cached Pro build present → keep it, skip the server check. With no cached build- // we must still fetch one — a valid Pro license never launches the free binary.+ // Honor CLOAKBROWSER_AUTO_UPDATE=false: frozen AND a cached build present →+ // keep it, skip the server check. With no cached build we must still fetch one.// (The `update` CLI ignores this and always acts.)const frozen =(process.env.CLOAKBROWSER_AUTO_UPDATE ?? "").toLowerCase() === "false";if (frozen && proBinaryReady(effective)) {showWelcome(welcomeTier);- return getBinaryPath(effective, true);+ return getBinaryPath(effective);}// getProLatestVersion() is rate-limited to one network call per hour and returns@@ -861,8 +784,8 @@ async function ensureProBinary(}if (version === null) {- // Valid Pro license but nothing resolvable (server unreachable AND no cached- // Pro build). Never downgrade to the free binary — fail loudly.+ // Valid license but nothing resolvable (server unreachable AND no cached+ // build) — fail loudly.throw new Error("Could not determine latest Pro version from server");}@@ -878,11 +801,11 @@ async function ensureProBinary(}}showWelcome(welcomeTier);- return getBinaryPath(version, true);+ return getBinaryPath(version);}// `version` (the server latest) needs downloading. On failure, fall back to a- // cached Pro build if we have one — never the free binary.+ // cached build if we have one.try {console.error(`[cloakbrowser] Downloading Pro Chromium ${version} for ${getPlatformTag()}...`@@ -897,12 +820,12 @@ async function ensureProBinary(`[cloakbrowser] Pro update to ${version} failed; launching cached Pro binary ${effective}`);showWelcome(welcomeTier);- return getBinaryPath(effective, true);+ return getBinaryPath(effective);}throw err;}- const downloadedPath = getBinaryPath(version, true);+ const downloadedPath = getBinaryPath(version);if (!fs.existsSync(downloadedPath)) {throw new Error(`Pro download completed but binary not found at: ${downloadedPath}`@@ -925,8 +848,8 @@ export async function downloadProBinary(version: string, licenseKey: string): Pr// Request the explicit version so the served archive matches the signed// manifest verified in verifyProDownload.const downloadUrl = `${DOWNLOAD_BASE_URL}/api/download/${version}`;- const binaryDir = getBinaryDir(version, true);- const binaryPath = getBinaryPath(version, true);+ const binaryDir = getBinaryDir(version);+ const binaryPath = getBinaryPath(version);const platformTag = getPlatformTag();fs.mkdirSync(path.dirname(binaryDir), { recursive: true });@@ -942,11 +865,7 @@ export async function downloadProBinary(version: string, licenseKey: string): Pr"X-Platform": platformTag,});- // Pro binaries come from cloakbrowser.dev — the same origin as free- // downloads — so the M1 attack the Ed25519 signature defends against- // applies equally. Verify with the same non-bypassable signature check;- // CLOAKBROWSER_SKIP_CHECKSUM does NOT bypass it (parity with the official- // free path).+ // Non-bypassable Ed25519 signature check (M1 defense); no env var skips it.await verifyProDownload(tmpPath, version);await extractArchive(tmpPath, binaryDir, binaryPath);@@ -958,19 +877,17 @@ export async function downloadProBinary(version: string, licenseKey: string): Pr}/**- * Verify a Pro archive with the same non-bypassable Ed25519 signature check as- * official free downloads. Pro binaries are served from cloakbrowser.dev (same- * origin as the free tier), so a tampered same-origin SHA256SUMS could- * otherwise certify a tampered binary (M1, #308). Fetch the Pro SHA256SUMS ++ * Verify a downloaded archive with a non-bypassable Ed25519 signature check.+ * A tampered same-origin SHA256SUMS could otherwise certify a tampered+ * binary (M1, #308). Fetch the Pro SHA256SUMS +* detached SHA256SUMS.sig, verify the signature against the pinned keys FIRST,* bind the manifest to the requested version, then verify the archive's* SHA-256.** An invalid signature, checksum, or version mismatch throws* BinaryVerificationError (a tampering signal the router surfaces verbatim);- * CLOAKBROWSER_SKIP_CHECKSUM cannot bypass it. A failed manifest FETCH is- * transient — nothing was validated — and throws a plain Error. A valid-license- * user is never silently downgraded to the free binary.+ * nothing can bypass it. A failed manifest FETCH is transient — nothing was+ * validated — and throws a plain Error.* @internal Exported for testing only.*/export async function verifyProDownload(filePath: string, version: string): Promise<void> {@@ -1034,10 +951,10 @@ export async function verifyProDownload(filePath: string, version: string): Promasync function extractArchive(archivePath: string,destDir: string,- binaryPath?: string+ binaryPath: string): Promise<void> {console.error(`[cloakbrowser] Extracting to ${destDir}`);- const bp = binaryPath || getBinaryPath();+ const bp = binaryPath;// Extract into a private sibling dir, then rename it into place. Concurrent// first runs (in this process or others) each get their own staging dir, so@@ -1191,64 +1108,9 @@ function isExecutable(filePath: string): boolean {}// ----------------------------------------------------------------------------// Auto-update+// Wrapper update check (the binary updates on the launch path, ensureProBinary)// ----------------------------------------------------------------------------function shouldCheckForUpdate(): boolean {- if (process.env.CLOAKBROWSER_AUTO_UPDATE?.toLowerCase() === "false")- return false;- if (getLocalBinaryOverride()) return false;- if (process.env.CLOAKBROWSER_DOWNLOAD_URL) return false;-- const checkFile = path.join(getCacheDir(), ".last_update_check");- try {- const lastCheck = Number(fs.readFileSync(checkFile, "utf-8").trim());- if (Math.floor(Date.now() / 1000) - lastCheck < UPDATE_CHECK_INTERVAL_SEC)- return false;- } catch {- /* file doesn't exist or unreadable */- }- return true;-}--/** @internal Exported for testing only. */-export async function getLatestChromiumVersion(): Promise<string | null> {- try {- const resp = await fetch(`${GITHUB_API_URL}?per_page=10`, {- signal: AbortSignal.timeout(10_000),- });- if (!resp.ok) return null;- const releases = (await resp.json()) as Array<{- tag_name: string;- draft: boolean;- assets: Array<{ name: string }>;- }>;- const platformTarball = getArchiveName();- for (const release of releases) {- if (release.tag_name.startsWith("chromium-v") && !release.draft) {- const assetNames = new Set(- (release.assets ?? []).map((a) => a.name)- );- if (assetNames.has(platformTarball)) {- return release.tag_name.replace(/^chromium-v/, "");- }- }- }- return null;- } catch {- return null;- }-}--function writeVersionMarker(version: string): void {- const cacheDir = getCacheDir();- fs.mkdirSync(cacheDir, { recursive: true });- const marker = path.join(cacheDir, `latest_version_${getPlatformTag()}`);- const tmp = `${marker}.tmp`;- fs.writeFileSync(tmp, version);- fs.renameSync(tmp, marker);-}-let wrapperUpdateChecked = false;/** @internal Exported for testing only. */@@ -1261,7 +1123,6 @@ export async function checkWrapperUpdate(): Promise<void> {if (wrapperUpdateChecked) return;wrapperUpdateChecked = true;if (process.env.CLOAKBROWSER_AUTO_UPDATE?.toLowerCase() === "false") return;- if (process.env.CLOAKBROWSER_DOWNLOAD_URL) return;try {const resp = await fetch("https://registry.npmjs.org/cloakbrowser/latest", {signal: AbortSignal.timeout(5_000),@@ -1279,50 +1140,10 @@ export async function checkWrapperUpdate(): Promise<void> {}}-async function checkAndDownloadUpdate(): Promise<void> {- try {- // Record check timestamp first (rate limiting)- const cacheDir = getCacheDir();- fs.mkdirSync(cacheDir, { recursive: true });- fs.writeFileSync(- path.join(cacheDir, ".last_update_check"),- String(Math.floor(Date.now() / 1000))- );-- const platformVersion = getChromiumVersion();- const latest = await getLatestChromiumVersion();- if (!latest || !versionNewer(latest, platformVersion)) return;-- // Already downloaded?- if (fs.existsSync(getBinaryDir(latest))) {- writeVersionMarker(latest);- return;- }-- console.error(- `[cloakbrowser] Newer Chromium available: ${latest} (current: ${platformVersion}). Downloading in background...`- );- await downloadAndExtract(latest);- writeVersionMarker(latest);- console.error(- `[cloakbrowser] Background update complete: Chromium ${latest} ready. Will use on next launch.`- );- } catch (err) {- // Background update failed — don't disrupt the user- if (process.env.DEBUG) {- console.error("[cloakbrowser] Background update failed:", err);- }- }-}-+/** Fire-and-forget wrapper update check, once per process. */function maybeTriggerUpdateCheck(): void {- // Wrapper update: once per process, not rate-limitedif (!wrapperUpdateChecked) {checkWrapperUpdate().catch(() => { });}-- // Binary update: rate-limited to once per hour- if (!shouldCheckForUpdate()) return;- checkAndDownloadUpdate().catch(() => { });}diff --git a/js/src/index.ts b/js/src/index.tsindex b108814..b192781 100644--- a/js/src/index.ts+++ b/js/src/index.ts@@ -19,10 +19,10 @@export { launch, launchContext, launchPersistentContext, buildLaunchOptions, buildContextOptions, humanizeBrowser } from "./playwright.js";// Binary management-export { ensureBinary, clearCache, binaryInfo, checkForUpdate } from "./download.js";+export { ensureBinary, clearCache, binaryInfo } from "./download.js";// Config-export { CHROMIUM_VERSION, getDefaultStealthArgs } from "./config.js";+export { getDefaultStealthArgs } from "./config.js";// Licenseexport { validateLicense, CloakBrowserLicenseError } from "./license.js";diff --git a/js/src/license.ts b/js/src/license.tsindex 6cf14ed..c557b67 100644--- a/js/src/license.ts+++ b/js/src/license.ts@@ -6,7 +6,7 @@* and Pro version checks.*/-import { createHash, randomUUID } from "node:crypto";+import { createHash, randomBytes, randomUUID } from "node:crypto";import fs from "node:fs";import os from "node:os";import path from "node:path";@@ -378,6 +378,155 @@ export function resolveLicenseKey(licenseKey?: string): string | undefined {return resolveLicenseKeyWithSource(licenseKey).key;}+// ---------------------------------------------------------------------------+// Free key by email: claim code + key save (mirrors Python license.py)+// ---------------------------------------------------------------------------+export const CLAIM_URL = "https://cloakbrowser.dev/api/license/free/claim";+// A fragment, so the bearer code never reaches server or CDN logs.+export const FREE_CLAIM_LINK = "https://cloakbrowser.dev/#claim=";+export const KEY_RE = /^cb_[A-Za-z0-9_-]+$/;+const CLAIM_CODE_RE = /^[A-Za-z0-9_-]{20,128}$/; // the server's format+const CLAIM_MAX_AGE_MS = 7 * 86_400_000;++/** The claim's email already has a free key. The server never sends an existing+ * key to a claim (anyone can type anyone's email), so the person pastes it. */+export class FreeKeyAlreadyHeld extends Error {+ constructor() {+ super("This email already has a free key");+ this.name = "FreeKeyAlreadyHeld";+ }+}++function tmpPath(target: string): string {+ return `${target}.${randomBytes(8).toString("hex")}.tmp`;+}++/** Write a new file readable by the owner only, from the first byte. */+function writePrivateTmp(target: string, text: string): string {+ const tmp = tmpPath(target);+ fs.writeFileSync(tmp, text, { mode: 0o600, flag: "wx" });+ return tmp;+}++/**+ * Save a key to <cache>/license.key (0600) and retire the claim code.+ * `overwrite: false` (the background claim poll) leaves an existing key alone:+ * the user may have run `cloakbrowser login` meanwhile. Returns true if saved.+ */+export function saveLicenseKey(key: string, { overwrite = true } = {}): boolean {+ key = key.trim();+ if (!KEY_RE.test(key)) throw new Error("not a CloakBrowser license key");+ const cacheDir = getCacheDir();+ fs.mkdirSync(cacheDir, { recursive: true });+ const keyFile = path.join(cacheDir, "license.key");+ // The claim code keeps returning the key, so it must not outlive this call,+ // saved or not: otherwise a later launch (after `logout`) would reinstall it.+ const claimFile = path.join(cacheDir, ".free_claim");+ if (!overwrite && fs.existsSync(keyFile)) {+ fs.rmSync(claimFile, { force: true });+ return false;+ }+ fs.renameSync(writePrivateTmp(keyFile, key + "\n"), keyFile);+ fs.rmSync(claimFile, { force: true });+ return true;+}++/**+ * This install's claim code, from <cache>/.free_claim (0600, 7-day life).+ * Workers launching at once must print the same link, so the code is written+ * whole to a temp file and hard-linked into place: the first one wins.+ */+export function getClaimCode(): string {+ const cacheDir = getCacheDir();+ fs.mkdirSync(cacheDir, { recursive: true });+ const file = path.join(cacheDir, ".free_claim");+ try {+ if (Date.now() - fs.statSync(file).mtimeMs < CLAIM_MAX_AGE_MS) {+ const code = fs.readFileSync(file, "utf-8").trim();+ if (CLAIM_CODE_RE.test(code)) return code;+ }+ fs.rmSync(file, { force: true }); // expired or garbage: start over+ } catch {+ // no code yet+ }+ let code = randomBytes(32).toString("base64url");+ const tmp = writePrivateTmp(file, code);+ try {+ fs.linkSync(tmp, file); // publish without replacing+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code === "EEXIST") {+ code = fs.readFileSync(file, "utf-8").trim();+ } else {+ // ponytail: no hard links (FAT, some network mounts) -> plain replace;+ // a concurrent first launch there may print a different link.+ fs.renameSync(tmp, file);+ }+ } finally {+ fs.rmSync(tmp, { force: true });+ }+ return code;+}++export function claimLink(code: string): string {+ return FREE_CLAIM_LINK + code;+}++/**+ * One poll: the key once the claim's email is confirmed, else undefined.+ * Throws FreeKeyAlreadyHeld (and retires the code) if that email has a key.+ * The code goes in the body, never the URL: it is a bearer secret and URLs+ * land in server logs.+ */+export async function checkClaim(code: string): Promise<string | undefined> {+ let data: { status?: string; license_key?: unknown };+ try {+ const resp = await fetch(CLAIM_URL, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ code }),+ signal: AbortSignal.timeout(5_000),+ });+ const body: unknown = resp.ok ? await resp.json() : {};+ // Anything but a JSON object (null, array, a proxy's odd answer) = pending.+ data = body && typeof body === "object" && !Array.isArray(body) ? (body as typeof data) : {};+ } catch (e) {+ if (/\bcloakbrowser\b/.test(process.env.DEBUG ?? "")) {+ console.debug(`[cloakbrowser] Free-key claim check failed: ${e}`);+ }+ return undefined;+ }+ if (data.status === "has_key") {+ // This code will only ever answer has_key: start fresh next time.+ fs.rmSync(path.join(getCacheDir(), ".free_claim"), { force: true });+ throw new FreeKeyAlreadyHeld();+ }+ const key = data.status === "ready" ? data.license_key : undefined;+ return typeof key === "string" && KEY_RE.test(key.trim()) ? key.trim() : undefined;+}++/**+ * Poll until the key arrives (saved, then returned) or `deadline` (ms epoch)+ * passes. Returns undefined if the key arrived but was not saved (overwrite+ * false and a key already exists). With a deadline it is a background poll: its+ * timers are unref'd so it never keeps a script alive. Without one (someone is+ * waiting at the terminal) the timer must hold the process open.+ */+export async function pollClaim(+ code: string,+ { intervalMs = 15_000, deadline, overwrite = false }:+ { intervalMs?: number; deadline?: number; overwrite?: boolean } = {},+): Promise<string | undefined> {+ for (;;) {+ const key = await checkClaim(code);+ if (key) return saveLicenseKey(key, { overwrite }) ? key : undefined;+ if (deadline !== undefined && Date.now() + intervalMs > deadline) return undefined;+ await new Promise((r) => {+ const t = setTimeout(r, intervalMs);+ if (deadline !== undefined) t.unref();+ });+ }+}+/*** Build a child-process env dict with any needed license key injection.*diff --git a/js/src/playwright.ts b/js/src/playwright.tsindex 547f6a0..84755a4 100644--- a/js/src/playwright.ts+++ b/js/src/playwright.ts@@ -5,11 +5,7 @@import type { Browser, BrowserContext, BrowserContextOptions, LaunchOptions as PlaywrightLaunchOptions } from "playwright-core";import type { LaunchOptions, LaunchContextOptions, LaunchPersistentContextOptions } from "./types.js";-import {- DEFAULT_VIEWPORT,- IGNORE_DEFAULT_ARGS,- binarySupportsHeadlessNoViewport,-} from "./config.js";+import { IGNORE_DEFAULT_ARGS } from "./config.js";import { buildArgs } from "./args.js";import { maybeWarnWindowsFonts } from "./fonts.js";import { ensureBinary } from "./download.js";@@ -65,43 +61,13 @@ function filterStealthCtxOptions(ctx?: BrowserContextOptions): Partial<BrowserCo* Useful when integrating CloakBrowser with an existing Playwright Browser while* keeping the wrapper's stealth-safe defaults for `newContext()`.*/-/**- * Effective headless mode for viewport decisions. buildLaunchOptions() spreads- * `...options.launchOptions` LAST, so a raw `launchOptions.headless` overrides the- * top-level field at the actual chromium.launch() call. Viewport logic must read- * the same effective value — otherwise a headed browser gets a fixed viewport- * (reintroducing the impossible-window tell). Playwright-specific (Puppeteer- * resolves headless the opposite way).- */-function effectiveHeadless(options: LaunchOptions): boolean {- return (- (options.launchOptions as { headless?: boolean } | undefined)?.headless ??- options.headless ??- true- );-}-export function buildContextOptions(options: LaunchContextOptions = {}): BrowserContextOptions {- // Headed: viewport=null (no emulation) so the page tracks the real window and- // outerWidth >= innerWidth stays coherent. Headless on a newer binary: also- // null, since it reports coherent dimensions without emulation. Headless on an- // older binary: a fixed DEFAULT_VIEWPORT keeps dimensions coherent and- // deterministic. Explicit viewport (incl. null) is always honored.- const headless = effectiveHeadless(options);- const headlessNoViewport =- headless && binarySupportsHeadlessNoViewport(- options.licenseKey,- options.browserVersion,- options.releaseChannel,- );- const viewport =- options.viewport !== undefined- ? options.viewport- : headless && !headlessNoViewport- ? DEFAULT_VIEWPORT- : null;+ // Default viewport=null (no emulation): headed, the page tracks the real+ // window (outerWidth >= innerWidth stays coherent); headless, the binary+ // reports coherent dimensions itself. Explicit viewport (incl. null) wins.+ const viewport = options.viewport !== undefined ? options.viewport : null;return {// contextOptions first — explicit wrapper fields below override it.// filterStealthCtxOptions strips locale/timezoneId to prevent CDP detection.@@ -130,12 +96,7 @@ export async function buildLaunchOptions(options.releaseChannel,));const { exitIp, ...resolved } = await maybeResolveGeoip(options);- const { proxyOption, proxyArgs } = resolveProxyConfig(- options.proxy,- options.browserVersion,- options.licenseKey,- options.releaseChannel,- );+ const { proxyOption, proxyArgs } = resolveProxyConfig(options.proxy);let resolvedArgs = await resolveWebrtcArgs(options);resolvedArgs = appendWebrtcExitIp(resolvedArgs, exitIp);const args = buildArgs({ ...options, ...resolved, args: [...(resolvedArgs ?? []), ...proxyArgs] });@@ -194,11 +155,15 @@ export async function humanizeBrowser(*/export async function launch(options: LaunchOptions = {}): Promise<Browser> {const { chromium } = await import("playwright-core");- const denialPath = resolveLicenseKey(options.licenseKey) ? mintDenialFile() : undefined;+ // Only a path (nothing is written). Decided AFTER buildLaunchOptions: with no+ // key, its ensureBinary runs the claim menu that creates one, and the guard must+ // cover that first launch too (Python mints after ensure_binary for the same reason).+ let denialPath = mintDenialFile();let browser: Browser;let launchOptions: PlaywrightLaunchOptions;try {launchOptions = await buildLaunchOptions(options, denialPath);+ if (!resolveLicenseKey(options.licenseKey)) denialPath = undefined;browser = await chromium.launch(launchOptions);} catch (err) {const lic = licenseErrorFrom(err, denialPath);@@ -225,18 +190,8 @@ export async function launch(options: LaunchOptions = {}): Promise<Browser> {// Headed: a bare browser.newPage() would inherit Playwright's emulated 1280x720// viewport -> outerWidth < innerWidth (impossible window = bot tell). Default// newPage()/newContext() to viewport:null so the page tracks the real window.- // Headless on a newer binary also qualifies (coherent dimensions natively);- // older headless keeps Playwright's default viewport. Mirrors Python launch().- if (- !effectiveHeadless(options) ||- binarySupportsHeadlessNoViewport(- options.licenseKey,- options.browserVersion,- options.releaseChannel,- )- ) {- applyDefaultNoViewport(browser);- }+ // Headless qualifies too (coherent dimensions natively). Mirrors Python launch().+ applyDefaultNoViewport(browser);await humanizeBrowser(browser, options);return browser;}@@ -363,12 +318,7 @@ export async function launchPersistentContext(options.releaseChannel,));const { exitIp, ...resolved } = await maybeResolveGeoip(options);- const { proxyOption, proxyArgs } = resolveProxyConfig(- options.proxy,- options.browserVersion,- options.licenseKey,- options.releaseChannel,- );+ const { proxyOption, proxyArgs } = resolveProxyConfig(options.proxy);let resolvedArgs = await resolveWebrtcArgs(options);resolvedArgs = appendWebrtcExitIp(resolvedArgs, exitIp);resolvedArgs = persistentSeedArgs(options.userDataDir, options.stealthArgs, resolvedArgs);diff --git a/js/src/proxy.ts b/js/src/proxy.tsindex 54d973b..fbd660e 100644--- a/js/src/proxy.ts+++ b/js/src/proxy.ts@@ -2,7 +2,6 @@* Shared proxy URL parsing for Playwright and Puppeteer wrappers.*/-import { binarySupportsHttpProxyInlineAuth } from "./config.js";export interface ParsedProxy {server: string;@@ -235,16 +234,11 @@ export function normalizeHttpStringUrl(urlStr: string): string {/*** Resolve proxy into Playwright option and/or Chrome args.*- * Proxies with credentials (SOCKS5 or HTTP/HTTPS on supported platforms) are- * passed via Chrome's --proxy-server flag with inline credentials, bypassing- * Playwright's CDP auth interceptor which breaks on some proxies (#182).+ * Proxies with credentials (SOCKS5 and HTTP/HTTPS) are passed via Chrome's+ * --proxy-server flag with inline credentials, bypassing Playwright's CDP auth+ * interceptor which breaks on some proxies (#182).*/-export function resolveProxyConfig(- proxy: string | ProxyDict | undefined,- browserVersion?: string,- licenseKey?: string,- releaseChannel?: string,-): ProxyConfig {+export function resolveProxyConfig(proxy: string | ProxyDict | undefined): ProxyConfig {if (!proxy) return { proxyArgs: [] };if (isSocksProxy(proxy)) {@@ -260,14 +254,9 @@ export function resolveProxyConfig(return { proxyArgs: args };}- // HTTP/HTTPS with credentials, only on binaries that ship inline proxy auth:- // use Chrome's native proxy authentication path instead of Playwright's CDP- // auth interceptor (#182). Older binaries (free macOS/linux-arm64) can't parse- // inline credentials, so they fall through to the Playwright proxy dict below.- if (- hasCredentials(proxy) &&- binarySupportsHttpProxyInlineAuth(licenseKey, browserVersion, releaseChannel)- ) {+ // HTTP/HTTPS with credentials: use Chrome's native proxy authentication path+ // instead of Playwright's CDP auth interceptor (#182).+ if (hasCredentials(proxy)) {if (typeof proxy === "string") {return { proxyArgs: [`--proxy-server=${normalizeHttpStringUrl(proxy)}`] };}@@ -277,43 +266,13 @@ export function resolveProxyConfig(return { proxyArgs: args };}- // HTTP/HTTPS without credentials (or unsupported platform): use Playwright's proxy dict+ // HTTP/HTTPS without credentials: use Playwright's proxy dictif (typeof proxy === "string") {- return { proxyOption: parseProxyUrl(proxy), proxyArgs: [] };+ return { proxyOption: { server: proxy }, proxyArgs: [] };}return { proxyOption: proxy as ParsedProxy, proxyArgs: [] };}-export function parseProxyUrl(proxy: string): ParsedProxy {- let url: URL;- // Bare format: "user:pass@host:port" — new URL() throws without a scheme.- const normalized =- proxy.includes("@") && !proxy.includes("://") ? `http://${proxy}` : proxy;- try {- url = new URL(normalized);- } catch {- // Not a parseable URL (e.g. bare "host:port") — pass through as-is- return { server: proxy };- }-- if (!url.username) {- return { server: proxy };- }-- // Rebuild server URL without credentials- const server = `${url.protocol}//${url.hostname}${url.port ? `:${url.port}` : ""}`;-- const result: ParsedProxy = {- server,- username: decodeURIComponent(url.username),- };- if (url.password) {- result.password = decodeURIComponent(url.password);- }-- return result;-}-let requestProxyWarned = false;/** @internal Exported for testing only. */diff --git a/js/src/puppeteer.ts b/js/src/puppeteer.tsindex 6efedfc..0fe3024 100644--- a/js/src/puppeteer.ts+++ b/js/src/puppeteer.ts@@ -6,16 +6,11 @@import type { Browser } from "puppeteer-core";import type { LaunchOptions } from "./types.js";-import {- DEFAULT_VIEWPORT,- IGNORE_DEFAULT_ARGS,- binarySupportsHeadlessNoViewport,- binarySupportsHttpProxyInlineAuth,-} from "./config.js";+import { IGNORE_DEFAULT_ARGS } from "./config.js";import { buildArgs } from "./args.js";import { maybeWarnWindowsFonts } from "./fonts.js";import { ensureBinary } from "./download.js";-import { isSocksProxy, normalizeHttpStringUrl, parseProxyUrl, reconstructHttpUrl, resolveProxyConfig } from "./proxy.js";+import { isSocksProxy, normalizeHttpStringUrl, reconstructHttpUrl, resolveProxyConfig } from "./proxy.js";import { maybeResolveGeoip, resolveWebrtcArgs, appendWebrtcExitIp } from "./geoip.js";import {buildLaunchEnv,@@ -30,34 +25,19 @@ import { persistentSeedArgs } from "./profile-seed.js";export { CloakBrowserLicenseError } from "./license.js";/**- * Resolve Puppeteer's defaultViewport. Headed -> null (track the real window so- * outerWidth >= innerWidth stays coherent; Puppeteer otherwise forces an 800x600- * emulated viewport = a physically impossible window = bot tell). Headless has no- * window chrome (outer == inner), so a fixed viewport stays coherent and keeps- * dimensions deterministic. A user-supplied launchOptions.defaultViewport wins.+ * Resolve Puppeteer's defaultViewport: null (no emulation) unless the user+ * supplied one. Headed, the page tracks the real window (Puppeteer otherwise+ * forces an 800x600 viewport = outerWidth < innerWidth = bot tell); headless,+ * the binary reports coherent dimensions itself.*/function resolveDefaultViewport(options: LaunchOptions): { width: number; height: number } | null {const launchOpts = (options.launchOptions ?? {}) as Record<string, unknown>;// A user-supplied defaultViewport wins (incl. explicit null). undefined is NOT- // "supplied" — fall through to our default. Puppeteer sets `headless` AFTER the- // launchOptions spread, so the top-level field wins at launch — match it here.+ // "supplied" — fall through to our default.if (launchOpts.defaultViewport !== undefined) {return launchOpts.defaultViewport as { width: number; height: number } | null;}- const headless = options.headless ?? true;- // Headed and newer headless binaries: null (no emulation, coherent dimensions).- // Older headless binaries: a fixed viewport keeps dimensions coherent.- if (- !headless ||- binarySupportsHeadlessNoViewport(- options.licenseKey,- options.browserVersion,- options.releaseChannel,- )- ) {- return null;- }- return DEFAULT_VIEWPORT;+ return null;}/** Resolve binary path, geoip, webrtc, and build final Chrome args. */@@ -83,81 +63,31 @@ async function resolveArgs(}/**- * Resolve proxy into Chrome CLI args and optional HTTP auth credentials.- * SOCKS5: Chrome handles inline credentials natively (RFC 1929 auth).- * HTTP on binaries with inline proxy auth: inline credentials via --proxy-server.- * HTTP on older binaries (free macOS/linux-arm64): strip credentials, use- * page.authenticate() fallback.+ * Resolve proxy into Chrome CLI args. Credentials go inline via --proxy-server:+ * SOCKS5 natively (RFC 1929), HTTP through the binary's inline proxy auth.*/-function resolveProxy(options: LaunchOptions, args: string[]): { username: string; password: string } | undefined {- if (!options.proxy) return undefined;+function resolveProxy(options: LaunchOptions, args: string[]): void {+ if (!options.proxy) return;if (isSocksProxy(options.proxy)) {- const { proxyArgs } = resolveProxyConfig(- options.proxy,- options.browserVersion,- options.licenseKey,- options.releaseChannel,- );- args.push(...proxyArgs);- return undefined;- }-- // On binaries that ship inline proxy auth: pass full URL with inline creds.- if (- binarySupportsHttpProxyInlineAuth(- options.licenseKey,- options.browserVersion,- options.releaseChannel,- )- ) {- if (typeof options.proxy === "string") {- args.push(`--proxy-server=${normalizeHttpStringUrl(options.proxy)}`);- return undefined;- }- const url = options.proxy.username- ? reconstructHttpUrl(options.proxy)- : options.proxy.server;- args.push(`--proxy-server=${url}`);- if (options.proxy.bypass) {- args.push(`--proxy-bypass-list=${options.proxy.bypass}`);- }- return undefined;+ args.push(...resolveProxyConfig(options.proxy).proxyArgs);+ return;}-- // Older binary: strip credentials, fall back to page.authenticate()if (typeof options.proxy === "string") {- const { server, username, password } = parseProxyUrl(options.proxy);- args.push(`--proxy-server=${server}`);- return username ? { username, password: password ?? "" } : undefined;+ args.push(`--proxy-server=${normalizeHttpStringUrl(options.proxy)}`);+ return;}-- const parsed = parseProxyUrl(options.proxy.server);- args.push(`--proxy-server=${parsed.server}`);+ const url = options.proxy.username+ ? reconstructHttpUrl(options.proxy)+ : options.proxy.server;+ args.push(`--proxy-server=${url}`);if (options.proxy.bypass) {args.push(`--proxy-bypass-list=${options.proxy.bypass}`);}- const username = options.proxy.username ?? parsed.username;- const password = options.proxy.password ?? parsed.password;- return username ? { username, password: password ?? "" } : undefined;}-/** Apply proxy auth fallback (older binaries) and humanize patching. */-async function applyPostLaunch(- browser: Browser,- options: LaunchOptions,- proxyAuth?: { username: string; password: string },-): Promise<void> {- if (proxyAuth) {- const origNewPage = browser.newPage.bind(browser);- const auth = proxyAuth;- browser.newPage = async (...pageArgs: Parameters<typeof origNewPage>) => {- const page = await origNewPage(...pageArgs);- await page.authenticate(auth);- return page;- };- }-+/** Apply humanize patching. */+async function applyPostLaunch(browser: Browser, options: LaunchOptions): Promise<void> {if (options.humanize) {const { patchBrowser } = await import('./human-puppeteer/index.js');const { resolveConfig } = await import('./human/config.js');@@ -186,7 +116,7 @@ async function applyPostLaunch(export async function launch(options: LaunchOptions = {}): Promise<Browser> {const puppeteer = await import("puppeteer-core");const { binaryPath, args } = await resolveArgs(options);- const proxyAuth = resolveProxy(options, args);+ resolveProxy(options, args);// Resolve env for the browser process (license key injection, if needed).const denialPath = resolveLicenseKey(options.licenseKey) ? mintDenialFile() : undefined;@@ -223,7 +153,7 @@ export async function launch(options: LaunchOptions = {}): Promise<Browser> {// who creates their own context is covered too.installLicenseGuard(browser, denialPath);}- await applyPostLaunch(browser, options, proxyAuth);+ await applyPostLaunch(browser, options);return browser;}@@ -250,7 +180,7 @@ export async function launchPersistentContext(): Promise<Browser> {const puppeteer = await import("puppeteer-core");const { binaryPath, args } = await resolveArgs(options);- const proxyAuth = resolveProxy(options, args);+ resolveProxy(options, args);seedWidevineHint(options.userDataDir, binaryPath);@@ -292,6 +222,6 @@ export async function launchPersistentContext(installLicenseGuard(pg, denialPath);}}- await applyPostLaunch(browser, options, proxyAuth);+ await applyPostLaunch(browser, options);return browser;}diff --git a/js/src/types.ts b/js/src/types.tsindex 2f10b36..91958d6 100644--- a/js/src/types.ts+++ b/js/src/types.ts@@ -71,13 +71,11 @@ export interface LaunchPersistentContextOptions extends LaunchContextOptions {}export interface BinaryInfo {- version: string;- /** The wrapper's bundled baseline Chromium version (CHROMIUM_VERSION). */- bundledVersion: string;+ /** The cached build; null until one has been downloaded. */+ version: string | null;platform: string;- tier: "pro" | "free";- binaryPath: string;+ binaryPath: string | null;installed: boolean;- cacheDir: string;+ cacheDir: string | null;downloadUrl: string;}diff --git a/js/tests/claim.test.ts b/js/tests/claim.test.tsnew file mode 100644index 0000000..76af854--- /dev/null+++ b/js/tests/claim.test.ts@@ -0,0 +1,349 @@+/**+ * Free-key claim flow: claim code, key save, the no-key launch path and the+ * shared menu. Mirrors Python tests/test_free_claim.py.+ */+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import readline from "node:readline";++// The menu's "open in browser" must never launch a real browser from a test.+vi.mock("node:child_process", async (importOriginal) => ({+ ...(await importOriginal<typeof import("node:child_process")>()),+ spawn: vi.fn(() => ({ on: vi.fn(), unref: vi.fn() })),+}));++import {+ CLAIM_URL,+ FREE_CLAIM_LINK,+ FreeKeyAlreadyHeld,+ checkClaim,+ getClaimCode,+ saveLicenseKey,+} from "../src/license.js";+import {+ ensureBinary,+ promptLicenseKey,+ resetClaimPollStarted,+} from "../src/download.js";++let cacheDir: string;+const saved: Record<string, string | undefined> = {};+const ttyDesc = {+ stdin: Object.getOwnPropertyDescriptor(process.stdin, "isTTY"),+ stderr: Object.getOwnPropertyDescriptor(process.stderr, "isTTY"),+};++function setTTY(on: boolean): void {+ Object.defineProperty(process.stdin, "isTTY", { value: on, configurable: true });+ Object.defineProperty(process.stderr, "isTTY", { value: on, configurable: true });+}++beforeEach(() => {+ for (const k of ["CLOAKBROWSER_CACHE_DIR", "CLOAKBROWSER_LICENSE_KEY", "CLOAKBROWSER_BINARY_PATH"]) {+ saved[k] = process.env[k];+ }+ cacheDir = fs.mkdtempSync(path.join(os.tmpdir(), "cb-claim-"));+ process.env.CLOAKBROWSER_CACHE_DIR = cacheDir;+ delete process.env.CLOAKBROWSER_LICENSE_KEY;+ delete process.env.CLOAKBROWSER_BINARY_PATH;+ resetClaimPollStarted();+ setTTY(false);+});++afterEach(() => {+ vi.restoreAllMocks();+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ for (const [name, desc] of Object.entries(ttyDesc)) {+ const stream = name === "stdin" ? process.stdin : process.stderr;+ if (desc) Object.defineProperty(stream, "isTTY", desc);+ else delete (stream as { isTTY?: boolean }).isTTY;+ }+ fs.rmSync(cacheDir, { recursive: true, force: true });+});++const mode = (p: string) => fs.statSync(p).mode & 0o777;++/** Route fetch by URL: claim answers come from `claims` in order. */+function mockServer(claims: Array<Record<string, unknown>>, validPlan: string | null = "free") {+ const calls: Array<{ url: string; body: string }> = [];+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {+ const url = String(input);+ calls.push({ url, body: String(init?.body ?? "") });+ if (url === CLAIM_URL) return Response.json(claims.shift() ?? { status: "pending" });+ if (url.includes("/api/license/validate")) {+ if (validPlan === null) throw new Error("server down");+ return Response.json({ valid: true, plan: validPlan, expires: null });+ }+ return new Response("not found", { status: 404 });+ });+ return calls;+}++const CTRL_C = "\x03";++/** Answer the menu's readline questions in order; no answers left = EOF; CTRL_C = SIGINT. */+function answer(...answers: string[]) {+ return vi.spyOn(readline, "createInterface").mockImplementation((() => {+ const handlers: Record<string, () => void> = {};+ return {+ question: (_q: string, cb: (a: string) => void) => {+ const next = answers.shift();+ if (next === undefined) setTimeout(() => handlers.close?.(), 0);+ else if (next === CTRL_C) handlers.SIGINT?.();+ else cb(next);+ },+ on: (event: string, handler: () => void) => {+ handlers[event] = handler;+ },+ close: () => { },+ };+ }) as unknown as typeof readline.createInterface);+}++/** process.exit that throws instead of ending the test run. */+function mockExit() {+ return vi.spyOn(process, "exit").mockImplementation(((code: number) => {+ throw new Error(`exit ${code}`);+ }) as never);+}++describe("claim code", () => {+ it("is reused and owner-only", () => {+ const code = getClaimCode();+ expect(code).toMatch(/^[A-Za-z0-9_-]{20,128}$/);+ expect(getClaimCode()).toBe(code);+ expect(mode(path.join(cacheDir, ".free_claim"))).toBe(0o600);+ });++ it("rotates after seven days", () => {+ const old = getClaimCode();+ const stale = new Date(Date.now() - 8 * 86_400_000);+ fs.utimesSync(path.join(cacheDir, ".free_claim"), stale, stale);+ expect(getClaimCode()).not.toBe(old);+ });++ it("a second caller reads the first caller's code", () => {+ // What a parallel worker that lost the hard-link race sees.+ fs.writeFileSync(path.join(cacheDir, ".free_claim"), "a".repeat(43), { mode: 0o600 });+ expect(getClaimCode()).toBe("a".repeat(43));+ });++ it("the link uses the fragment form (never reaches server logs)", () => {+ expect(FREE_CLAIM_LINK).toBe("https://cloakbrowser.dev/#claim=");+ });+});++describe("saveLicenseKey", () => {+ it("writes the key owner-only and retires the claim code", () => {+ getClaimCode();+ expect(saveLicenseKey("cb_abc")).toBe(true);+ const keyFile = path.join(cacheDir, "license.key");+ expect(fs.readFileSync(keyFile, "utf-8")).toBe("cb_abc\n");+ expect(mode(keyFile)).toBe(0o600);+ expect(fs.existsSync(path.join(cacheDir, ".free_claim"))).toBe(false);+ });++ it("rejects anything that is not a key", () => {+ expect(() => saveLicenseKey("<script>")).toThrow();+ expect(fs.existsSync(path.join(cacheDir, "license.key"))).toBe(false);+ });++ it("the background poll never overwrites an existing key, but retires the claim", () => {+ saveLicenseKey("cb_mine");+ getClaimCode();+ expect(saveLicenseKey("cb_claimed", { overwrite: false })).toBe(false);+ expect(fs.readFileSync(path.join(cacheDir, "license.key"), "utf-8")).toBe("cb_mine\n");+ // A kept claim would reinstall the key on a launch after `logout`.+ expect(fs.existsSync(path.join(cacheDir, ".free_claim"))).toBe(false);+ });++ it("pollClaim reports nothing saved when a key already exists", async () => {+ saveLicenseKey("cb_mine");+ mockServer([{ status: "ready", license_key: "cb_claimed" }]);+ const { pollClaim } = await import("../src/license.js");+ // undefined = the background poller prints no "free key saved"+ expect(await pollClaim(getClaimCode(), { deadline: Date.now() + 60_000 })).toBeUndefined();+ expect(fs.readFileSync(path.join(cacheDir, "license.key"), "utf-8")).toBe("cb_mine\n");+ });+});++describe("checkClaim", () => {+ it.each([+ [{ status: "pending" }, undefined],+ [{ status: "ready", license_key: "cb_ok" }, "cb_ok"],+ [{ status: "ready", license_key: "bad key" }, undefined], // trust boundary+ ])("%j -> %s", async (reply, expected) => {+ const calls = mockServer([reply]);+ expect(await checkClaim("c".repeat(32))).toBe(expected);+ // The code is a bearer secret: body, never the URL.+ expect(calls[0]!.url).toBe(CLAIM_URL);+ expect(JSON.parse(calls[0]!.body)).toEqual({ code: "c".repeat(32) });+ });++ it.each([[null], [[1, 2]], ["ready"]])("non-object JSON %j reads as pending", async (reply) => {+ vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json(reply));+ expect(await checkClaim("c".repeat(32))).toBeUndefined();+ });++ it("a network error reads as pending", async () => {+ vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("down"));+ expect(await checkClaim("c".repeat(32))).toBeUndefined();+ });++ it("has_key throws and retires the code", async () => {+ getClaimCode();+ mockServer([{ status: "has_key" }]);+ await expect(checkClaim("c".repeat(32))).rejects.toBeInstanceOf(FreeKeyAlreadyHeld);+ expect(fs.existsSync(path.join(cacheDir, ".free_claim"))).toBe(false);+ });+});++describe("ensureBinary with no key", () => {+ it("without a terminal throws with the link (stderr only)", async () => {+ mockServer([]);+ const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ const out = vi.spyOn(process.stdout, "write");+ await expect(ensureBinary()).rejects.toThrow(/cloakbrowser\.dev\/#claim=/);+ expect(err.mock.calls.join("")).toContain("#claim=");+ expect(out).not.toHaveBeenCalled(); // MCP servers own stdout+ });++ it("without a terminal, an email that already has a key says so", async () => {+ mockServer([{ status: "has_key" }]);+ vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ await expect(ensureBinary()).rejects.toThrow(/already has a free key/);+ });++ it("picks up a key confirmed since an earlier launch, without the menu", async () => {+ // validate fails afterwards: enough to prove the claimed key was used.+ const calls = mockServer([{ status: "ready", license_key: "cb_ready" }], null);+ const rl = answer();+ await expect(ensureBinary()).rejects.toThrow(/could not be validated/);+ expect(rl).not.toHaveBeenCalled();+ expect(fs.readFileSync(path.join(cacheDir, "license.key"), "utf-8")).toBe("cb_ready\n");+ expect(calls.some((c) => c.body.includes("cb_ready"))).toBe(true);+ });++ it("any key source skips the claim", async () => {+ process.env.CLOAKBROWSER_LICENSE_KEY = "cb_env";+ const calls = mockServer([], null);+ await expect(ensureBinary()).rejects.toThrow(/could not be validated/);+ expect(calls.some((c) => c.url === CLAIM_URL)).toBe(false);+ });++ it("in a terminal, Enter gets a free key by email and launches with it", async () => {+ setTTY(true);+ // first check, then the menu's poll answers ready right away+ const calls = mockServer([{ status: "pending" }, { status: "ready", license_key: "cb_claimed" }], null);+ vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ answer("");+ await expect(ensureBinary()).rejects.toThrow(/could not be validated/);+ expect(fs.readFileSync(path.join(cacheDir, "license.key"), "utf-8")).toBe("cb_claimed\n");+ expect(calls.some((c) => c.body.includes("cb_claimed"))).toBe(true);+ });+});++describe("promptLicenseKey (the menu)", () => {+ it("default option gets a free key and counts as this launch's welcome", async () => {+ mockServer([{ status: "ready", license_key: "cb_claimed" }]);+ const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ answer("");+ expect(await promptLicenseKey()).toBe("cb_claimed");+ const text = err.mock.calls.join("");+ expect(text).toContain("Welcome to CloakBrowser");+ expect(text).toContain("1) Get a free key");+ expect(fs.existsSync(path.join(cacheDir, ".welcome_shown"))).toBe(true);+ });++ it("option 2 pastes a key, asking again on a non-key", async () => {+ mockServer([]);+ vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ answer("2", "hello", "cb_mine");+ expect(await promptLicenseKey()).toBe("cb_mine");+ expect(fs.readFileSync(path.join(cacheDir, "license.key"), "utf-8")).toBe("cb_mine\n");+ });++ it("rejects an invalid pasted key and an unknown choice", async () => {+ vi.spyOn(globalThis, "fetch").mockImplementation(async (_input, init) =>+ Response.json({ valid: String(init?.body).includes("cb_good"), plan: "free", expires: null }),+ );+ vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ answer("7", "2", "cb_bad", "cb_good");+ expect(await promptLicenseKey()).toBe("cb_good");+ });++ it("an email that already has a key switches to the paste prompt", async () => {+ mockServer([{ status: "has_key" }]);+ const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ answer("1", "cb_old");+ expect(await promptLicenseKey()).toBe("cb_old");+ expect(err.mock.calls.join("")).toContain("already has a free key");+ });++ it("stdin closing rejects instead of hanging", async () => {+ vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ answer();+ await expect(promptLicenseKey()).rejects.toThrow(/stdin closed/);+ });++ it("Ctrl+C at the menu exits 130 with no link and no second welcome", async () => {+ setTTY(true);+ mockServer([]);+ const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ const exit = mockExit();+ answer(CTRL_C);+ await expect(ensureBinary()).rejects.toThrow("exit 130");+ expect(exit).toHaveBeenCalledWith(130);+ const text = err.mock.calls.join("");+ expect(text).not.toContain("#claim=");+ expect(text.split("Welcome to CloakBrowser").length - 1).toBe(1);+ });+});++describe("cloakbrowser login", () => {+ it("saves a pasted key owner-only", async () => {+ mockServer([]);+ vi.spyOn(console, "log").mockImplementation(() => { });+ const { cmdLogin } = await import("../src/cli.js");+ await cmdLogin(["cb_free"]);+ const keyFile = path.join(cacheDir, "license.key");+ expect(fs.readFileSync(keyFile, "utf-8")).toBe("cb_free\n");+ expect(mode(keyFile)).toBe(0o600);+ });++ it("refuses text that is not a key", async () => {+ mockServer([]);+ vi.spyOn(console, "error").mockImplementation(() => { });+ vi.spyOn(process, "exit").mockImplementation(((code: number) => {+ throw new Error(`exit ${code}`);+ }) as never);+ const { cmdLogin } = await import("../src/cli.js");+ await expect(cmdLogin(["not a key"])).rejects.toThrow("exit 1");+ expect(fs.existsSync(path.join(cacheDir, "license.key"))).toBe(false);+ });++ it("with stderr redirected, no menu (it would be invisible): usage + exit 2", async () => {+ Object.defineProperty(process.stdin, "isTTY", { value: true, configurable: true });+ vi.spyOn(console, "error").mockImplementation(() => { });+ mockExit();+ const rl = answer();+ const { cmdLogin } = await import("../src/cli.js");+ await expect(cmdLogin([])).rejects.toThrow("exit 2");+ expect(rl).not.toHaveBeenCalled();+ });++ it("logout also retires a pending claim", async () => {+ vi.spyOn(console, "log").mockImplementation(() => { });+ saveLicenseKey("cb_mine");+ getClaimCode();+ const { cmdLogout } = await import("../src/cli.js");+ cmdLogout();+ expect(fs.existsSync(path.join(cacheDir, ".free_claim"))).toBe(false);+ expect(fs.existsSync(path.join(cacheDir, "license.key"))).toBe(false);+ });+});diff --git a/js/tests/cli.test.ts b/js/tests/cli.test.tsindex 4c77a35..fce38fe 100644--- a/js/tests/cli.test.ts+++ b/js/tests/cli.test.ts@@ -29,14 +29,15 @@ afterEach(() => {});describe("collectDiagnostics", () => {- it("skips the launch test with quick=true and reports a free license", async () => {+ it("skips the launch test with quick=true and reports no license", async () => {const { collectDiagnostics } = await import("../src/cli.js");const diag = (await collectDiagnostics(true)) as Record<string, any>;expect(diag.environment.node).toBe(process.version);expect(diag.launch.tested).toBe(false);expect(diag.launch.reason).toContain("--quick");- expect(diag.license.tier).toBe("free");+ expect(diag.license.tier).toBe("none");+ expect(diag.binary.tier).toBe("none");expect(diag.modules).toBeDefined();});diff --git a/js/tests/config.test.ts b/js/tests/config.test.tsindex 182f8b8..a63764c 100644--- a/js/tests/config.test.ts+++ b/js/tests/config.test.ts@@ -1,25 +1,15 @@import { describe, it, expect } from "vitest";import {- CHROMIUM_VERSION,getArchiveExt,- getChromiumVersion,getDefaultStealthArgs,getCacheDir,getBinaryDir,- getDownloadUrl,- getFallbackDownloadUrl,normalizeReleaseChannel,normalizeRequestedVersion,- binarySupportsHeadlessNoViewport,- binarySupportsMaximizedWindow,} from "../src/config.js";import { _buildArgsForTest, resolveTimezone } from "../src/playwright.js";describe("config", () => {- it("CHROMIUM_VERSION matches expected format", () => {- expect(CHROMIUM_VERSION).toMatch(/^\d+\.\d+\.\d+\.\d+(\.\d+)?$/);- });-it("getDefaultStealthArgs returns expected flags", () => {const args = getDefaultStealthArgs();const isMac = process.platform === "darwin";@@ -68,17 +58,8 @@ describe("config", () => {}});- it("getBinaryDir includes platform version", () => {- const dir = getBinaryDir();- expect(dir).toContain(`chromium-${getChromiumVersion()}`);- });-- it("getDownloadUrl contains platform version and platform tag", () => {- const url = getDownloadUrl();- expect(url).toContain(getChromiumVersion());- expect(url).toContain("cloakbrowser-");- expect(url).toContain(".tar.gz");- expect(url).toContain("cloakbrowser.dev");+ it("getBinaryDir keeps the -pro suffix so existing caches stay valid", () => {+ expect(getBinaryDir("155.0.8059.39.2")).toMatch(/chromium-155\.0\.8059\.39\.2-pro$/);});});@@ -154,16 +135,6 @@ describe("archive helpers", () => {}});- it("getFallbackDownloadUrl uses GitHub Releases", () => {- const url = getFallbackDownloadUrl("145.0.0.0");- expect(url).toContain("github.com/CloakHQ/cloakbrowser/releases/download");- expect(url).toContain("chromium-v145.0.0.0");- });-- it("getFallbackDownloadUrl uses default version", () => {- const url = getFallbackDownloadUrl();- expect(url).toContain(`chromium-v${getChromiumVersion()}`);- });});describe("buildArgs timezone/locale", () => {@@ -296,76 +267,20 @@ describe("resolveTimezone alias", () => {});});-describe("binarySupportsHeadlessNoViewport", () => {- // Parity-critical: Python and .NET mirror this gate. Threshold is an unshipped- // version, so the resolved-version path is a no-op today; the declared-version- // path is what these tests pin.- it("is OFF one build below the threshold (current live Pro version)", () => {- expect(binarySupportsHeadlessNoViewport(undefined, "148.0.7778.215.3")).toBe(false);- });-- it("is ON at the threshold", () => {- expect(binarySupportsHeadlessNoViewport(undefined, "148.0.7778.215.4")).toBe(true);- });-- it("is ON above the threshold", () => {- expect(binarySupportsHeadlessNoViewport(undefined, "149.0.0.0")).toBe(true);- });-- it("declared version wins over a local override", () => {- const prev = process.env.CLOAKBROWSER_BINARY_PATH;- process.env.CLOAKBROWSER_BINARY_PATH = "/fake/chrome";- try {- expect(binarySupportsHeadlessNoViewport(undefined, "149.0.0.0")).toBe(true);- } finally {- if (prev === undefined) delete process.env.CLOAKBROWSER_BINARY_PATH;- else process.env.CLOAKBROWSER_BINARY_PATH = prev;- }- });-- it("is OFF for a local override with no declared version", () => {+describe("buildArgs --start-maximized", () => {+ it("adds --start-maximized by default (an unversioned override too)", () => {+ expect(_buildArgsForTest({})).toContain("--start-maximized");const prev = process.env.CLOAKBROWSER_BINARY_PATH;process.env.CLOAKBROWSER_BINARY_PATH = "/fake/chrome";try {- expect(binarySupportsHeadlessNoViewport()).toBe(false);+ expect(_buildArgsForTest({})).toContain("--start-maximized");} finally {if (prev === undefined) delete process.env.CLOAKBROWSER_BINARY_PATH;else process.env.CLOAKBROWSER_BINARY_PATH = prev;}});-- it("fails OFF on a malformed declared version", () => {- // parseVersion yields NaN rather than throwing — the gate must still fail safe.- expect(binarySupportsHeadlessNoViewport(undefined, "not.a.version")).toBe(false);- });-});--describe("binarySupportsMaximizedWindow", () => {- // Parity-critical: Python and .NET mirror this gate. Shares the no_viewport- // threshold today.- it("is OFF one build below the threshold", () => {- expect(binarySupportsMaximizedWindow(undefined, "148.0.7778.215.3")).toBe(false);- });- it("is ON at the threshold", () => {- expect(binarySupportsMaximizedWindow(undefined, "148.0.7778.215.4")).toBe(true);- });- it("is ON above the threshold", () => {- expect(binarySupportsMaximizedWindow(undefined, "149.0.0.0")).toBe(true);- });-});--describe("buildArgs --start-maximized", () => {- it("adds --start-maximized when the binary is gated ON", () => {- const args = _buildArgsForTest({ browserVersion: "148.0.7778.215.4" });- expect(args).toContain("--start-maximized");- });- it("does not add it below the gate", () => {- const args = _buildArgsForTest({ browserVersion: "148.0.7778.215.3" });- expect(args).not.toContain("--start-maximized");- });it("is suppressed by a user --window-size", () => {const args = _buildArgsForTest({- browserVersion: "148.0.7778.215.4",args: ["--window-size=1000,800"],});expect(args).not.toContain("--start-maximized");@@ -373,14 +288,12 @@ describe("buildArgs --start-maximized", () => {});it("is suppressed by an explicit viewport", () => {const args = _buildArgsForTest({- browserVersion: "148.0.7778.215.4",viewport: { width: 800, height: 600 },} as Parameters<typeof _buildArgsForTest>[0]);expect(args).not.toContain("--start-maximized");});it("does not double a user-supplied --start-maximized", () => {const args = _buildArgsForTest({- browserVersion: "148.0.7778.215.4",args: ["--start-maximized"],});expect(args.filter(a => a === "--start-maximized")).toHaveLength(1);diff --git a/js/tests/launch.test.ts b/js/tests/launch.test.tsindex 110af21..73b4664 100644--- a/js/tests/launch.test.ts+++ b/js/tests/launch.test.ts@@ -2,29 +2,28 @@ import { describe, it, expect, vi, afterEach, beforeEach } from "vitest";import fs from "node:fs";import path from "node:path";import { binaryInfo } from "../src/download.js";-import { DEFAULT_VIEWPORT, getBinaryPath, getChromiumVersion, getPlatformTag } from "../src/config.js";+import { getBinaryPath, getPlatformTag } from "../src/config.js";describe("binaryInfo", () => {- it("returns correct structure", () => {+ it("returns correct structure (nothing cached yet)", () => {const orig = process.env.CLOAKBROWSER_CACHE_DIR;process.env.CLOAKBROWSER_CACHE_DIR = `/tmp/cloakbrowser-test-${Date.now()}`;try {const info = binaryInfo();- expect(info.version).toBe(getChromiumVersion());- expect(info.bundledVersion).toBeTruthy();+ expect(info.version).toBeNull();expect(info.platform).toMatch(/^(linux|darwin|windows)-(x64|arm64)$/);- expect(info.binaryPath).toBeTruthy();- expect(typeof info.installed).toBe("boolean");- expect(info.cacheDir).toContain("cloakbrowser");+ expect(info.binaryPath).toBeNull();+ expect(info.installed).toBe(false);+ expect(info.downloadUrl).toMatch(/\/api\/download\/latest$/);} finally {if (orig) process.env.CLOAKBROWSER_CACHE_DIR = orig;else delete process.env.CLOAKBROWSER_CACHE_DIR;}});- it("reports tier from the installed binary, not a cached license", () => {- // A valid, fresh license is cached but NO Pro binary is on disk → free.+ it("reports the installed binary, not a cached license", () => {+ // A valid, fresh license is cached but NO binary is on disk.const orig = process.env.CLOAKBROWSER_CACHE_DIR;const dir = `/tmp/cloakbrowser-test-${Date.now()}-tier`;fs.mkdirSync(dir, { recursive: true });@@ -40,16 +39,16 @@ describe("binaryInfo", () => {validated_at: Date.now() / 1000,}));- expect(binaryInfo().tier).toBe("free");+ expect(binaryInfo().installed).toBe(false);- // Now drop a Pro binary on disk → pro.+ // Now drop a binary on disk.fs.writeFileSync(path.join(dir, `latest_pro_version_${getPlatformTag()}`), "147.0.5555.1");- const bp = getBinaryPath("147.0.5555.1", true);+ const bp = getBinaryPath("147.0.5555.1");fs.mkdirSync(path.dirname(bp), { recursive: true });fs.writeFileSync(bp, "fake");fs.chmodSync(bp, 0o755);const info = binaryInfo();- expect(info.tier).toBe("pro");+ expect(info.installed).toBe(true);expect(info.version).toBe("147.0.5555.1");} finally {fs.rmSync(dir, { recursive: true, force: true });@@ -67,7 +66,7 @@ describe("binaryInfo", () => {// Same cached Pro binary satisfies both channels (version-keyed cache dir).fs.writeFileSync(path.join(dir, `latest_pro_version_preview_${getPlatformTag()}`), "151.0.7900.10.1");fs.writeFileSync(path.join(dir, `latest_pro_version_${getPlatformTag()}`), "151.0.7900.10.1");- const bp = getBinaryPath("151.0.7900.10.1", true);+ const bp = getBinaryPath("151.0.7900.10.1");fs.mkdirSync(path.dirname(bp), { recursive: true });fs.writeFileSync(bp, "fake");fs.chmodSync(bp, 0o755);@@ -154,78 +153,41 @@ describe("composable Playwright launch helpers", () => {expect(warnSpy).toHaveBeenCalledTimes(2);});- it("buildContextOptions applies DEFAULT_VIEWPORT by default and allows null viewport", async () => {+ it("buildContextOptions uses no viewport (null) by default, headed or headless", async () => {const { buildContextOptions } = await import("../src/index.js");- expect(buildContextOptions().viewport).toEqual(DEFAULT_VIEWPORT);- expect(buildContextOptions({ viewport: null }).viewport).toBeNull();- });-- it("buildContextOptions uses no viewport (null) when headed, so the page tracks the real window", async () => {- const { buildContextOptions } = await import("../src/index.js");-- // Headed: no emulated viewport (CDP emulation would force outerWidth < innerWidth).+ // Headed: CDP emulation would force outerWidth < innerWidth; headless: the+ // binary reports coherent dimensions itself.+ expect(buildContextOptions().viewport).toBeNull();expect(buildContextOptions({ headless: false }).viewport).toBeNull();- // Headless keeps the deterministic default.- expect(buildContextOptions({ headless: true }).viewport).toEqual(DEFAULT_VIEWPORT);- // Explicit viewport always honored, even headed.+ expect(buildContextOptions({ headless: true }).viewport).toBeNull();+ expect(buildContextOptions({ launchOptions: { headless: true } }).viewport).toBeNull();+ // Explicit viewport always honored.const custom = { width: 800, height: 600 };expect(buildContextOptions({ headless: false, viewport: custom }).viewport).toEqual(custom);+ expect(buildContextOptions({ viewport: null }).viewport).toBeNull();});- it("buildContextOptions reads effective headless from launchOptions.headless", async () => {- const { buildContextOptions } = await import("../src/index.js");+ it("buildLaunchOptions returns Playwright options without launching a browser", async () => {+ const { buildLaunchOptions } = await import("../src/index.js");- // buildLaunchOptions spreads launchOptions LAST, so launchOptions.headless wins- // at the actual launch. Viewport must follow it — a raw headless:false (browser- // actually headed) must NOT get a fixed viewport (would reintroduce outer<inner).- expect(buildContextOptions({ launchOptions: { headless: false } }).viewport).toBeNull();- // And launchOptions.headless:true forces the deterministic viewport even if the- // top-level field said headed.- expect(- buildContextOptions({ headless: false, launchOptions: { headless: true } }).viewport,- ).toEqual(DEFAULT_VIEWPORT);- });+ const options = await buildLaunchOptions({+ headless: false,+ proxy: "http://user:[email protected]:8080",+ args: ["--custom-flag"],+ launchOptions: { timeout: 1234 },+ });- it("buildLaunchOptions returns Playwright options without launching a browser", async () => {- // Free macOS lacks inline proxy auth → credentialed HTTP proxy goes through- // Playwright's proxy dict. Drive the platform via process.platform/arch since- // getPlatformTag reads them at call time (a config spy can't reach the- // intra-config gate call).- const origPlatform = Object.getOwnPropertyDescriptor(process, "platform")!;- const origArch = Object.getOwnPropertyDescriptor(process, "arch")!;- Object.defineProperty(process, "platform", { value: "darwin", configurable: true });- Object.defineProperty(process, "arch", { value: "arm64", configurable: true });- try {- const { buildLaunchOptions } = await import("../src/index.js");-- const options = await buildLaunchOptions({- headless: false,- proxy: "http://user:[email protected]:8080",- args: ["--custom-flag"],- launchOptions: { timeout: 1234 },- });-- expect(options.executablePath).toBe("/fake/chrome");- expect(options.headless).toBe(false);- expect(options.args).toContain("--custom-flag");- expect(options.ignoreDefaultArgs).toContain("--enable-automation");- expect(options.proxy).toEqual({- server: "http://proxy.example:8080",- username: "user",- password: "pass",- });- expect(options.args).not.toContain(- "--proxy-server=http://user:[email protected]:8080",- );- expect(options.timeout).toBe(1234);- // No license key -> env is not injected- expect(options.env).toBeUndefined();- } finally {- Object.defineProperty(process, "platform", origPlatform);- Object.defineProperty(process, "arch", origArch);- vi.restoreAllMocks();- }+ expect(options.executablePath).toBe("/fake/chrome");+ expect(options.headless).toBe(false);+ expect(options.args).toContain("--custom-flag");+ expect(options.ignoreDefaultArgs).toContain("--enable-automation");+ // Credentialed HTTP proxy goes inline (every served build ships inline auth).+ expect(options.proxy).toBeUndefined();+ expect(options.args).toContain("--proxy-server=http://user:[email protected]:8080");+ expect(options.timeout).toBe(1234);+ // No license key -> env is not injected+ expect(options.env).toBeUndefined();});it("buildLaunchOptions injects env with license key", async () => {@@ -307,6 +269,7 @@ describe.skipIf(!process.env.CLOAKBROWSER_BINARY_PATH)(describe("launchContext (unit)", () => {let mockContext: any;let mockBrowser: any;+ let newContextMock: any;let mockChromium: any;const origEnv = process.env.CLOAKBROWSER_BINARY_PATH;@@ -314,8 +277,12 @@ describe("launchContext (unit)", () => {process.env.CLOAKBROWSER_BINARY_PATH = "/fake/chrome";const origClose = vi.fn();mockContext = { close: origClose, _origClose: origClose };+ // launch() wraps browser.newContext (no-viewport default), so keep the+ // original mock to read its calls.+ newContextMock = vi.fn().mockResolvedValue(mockContext);mockBrowser = {- newContext: vi.fn().mockResolvedValue(mockContext),+ newContext: newContextMock,+ newPage: vi.fn(),close: vi.fn(),};mockChromium = { launch: vi.fn().mockResolvedValue(mockBrowser) };@@ -333,12 +300,35 @@ describe("launchContext (unit)", () => {}});- it("applies DEFAULT_VIEWPORT when no viewport given", async () => {+ it("guards the first launch whose key the no-key menu just created", async () => {+ // No key before launch; ensureBinary's claim menu saves one. The license+ // status file must still reach the browser (decided after ensureBinary).+ delete process.env.CLOAKBROWSER_BINARY_PATH;+ const origKey = process.env.CLOAKBROWSER_LICENSE_KEY;+ delete process.env.CLOAKBROWSER_LICENSE_KEY;+ const ensureBinary = vi.fn().mockImplementation(async () => {+ process.env.CLOAKBROWSER_LICENSE_KEY = "cb_from_menu";+ return "/fake/chrome";+ });+ vi.doMock("../src/download.js", () => ({ ensureBinary }));+ try {+ const { launch } = await import("../src/playwright.js");+ await launch();+ const env = mockChromium.launch.mock.calls[0][0].env;+ expect(env.CLOAKBROWSER_LICENSE_STATUS_FILE).toMatch(/denials/);+ } finally {+ vi.doUnmock("../src/download.js");+ if (origKey === undefined) delete process.env.CLOAKBROWSER_LICENSE_KEY;+ else process.env.CLOAKBROWSER_LICENSE_KEY = origKey;+ }+ });++ it("uses no emulated viewport when none given (headless too)", async () => {const { launchContext } = await import("../src/playwright.js");await launchContext();- const ctxArgs = mockBrowser.newContext.mock.calls[0][0];- expect(ctxArgs.viewport).toEqual(DEFAULT_VIEWPORT);+ const ctxArgs = newContextMock.mock.calls[0][0];+ expect(ctxArgs.viewport).toBeNull();});it("uses custom viewport when provided", async () => {@@ -346,7 +336,7 @@ describe("launchContext (unit)", () => {const custom = { width: 1280, height: 720 };await launchContext({ viewport: custom });- const ctxArgs = mockBrowser.newContext.mock.calls[0][0];+ const ctxArgs = newContextMock.mock.calls[0][0];expect(ctxArgs.viewport).toEqual(custom);});@@ -354,7 +344,7 @@ describe("launchContext (unit)", () => {const { launchContext } = await import("../src/playwright.js");await launchContext({ userAgent: "Custom/1.0" });- const ctxArgs = mockBrowser.newContext.mock.calls[0][0];+ const ctxArgs = newContextMock.mock.calls[0][0];expect(ctxArgs.userAgent).toBe("Custom/1.0");});@@ -370,7 +360,7 @@ describe("launchContext (unit)", () => {expect(hasTimezoneFlag).toBe(true);// NOT in newContext() — no CDP emulation- const ctxArgs = mockBrowser.newContext.mock.calls[0][0];+ const ctxArgs = newContextMock.mock.calls[0][0];expect(ctxArgs.timezoneId).toBeUndefined();});@@ -378,7 +368,7 @@ describe("launchContext (unit)", () => {const { launchContext } = await import("../src/playwright.js");await launchContext({ colorScheme: "dark" });- const ctxArgs = mockBrowser.newContext.mock.calls[0][0];+ const ctxArgs = newContextMock.mock.calls[0][0];expect(ctxArgs.colorScheme).toBe("dark");});@@ -420,7 +410,7 @@ describe("launchContext (unit)", () => {},});- const ctxArgs = mockBrowser.newContext.mock.calls[0][0];+ const ctxArgs = newContextMock.mock.calls[0][0];expect(ctxArgs.storageState).toBe("state.json");expect(ctxArgs.permissions).toEqual(["geolocation"]);});@@ -438,7 +428,7 @@ describe("launchContext (unit)", () => {},});- const ctxArgs = mockBrowser.newContext.mock.calls[0][0];+ const ctxArgs = newContextMock.mock.calls[0][0];expect(ctxArgs.userAgent).toBe("Explicit/1.0");expect(ctxArgs.viewport).toEqual({ width: 1280, height: 720 });expect(ctxArgs.colorScheme).toBe("dark");@@ -455,7 +445,7 @@ describe("launchContext (unit)", () => {},});- const ctxArgs = mockBrowser.newContext.mock.calls[0][0];+ const ctxArgs = newContextMock.mock.calls[0][0];// Stealth-sensitive keys stripped — they would reintroduce detectable CDP emulation.expect(ctxArgs.locale).toBeUndefined();expect(ctxArgs.timezoneId).toBeUndefined();@@ -565,12 +555,12 @@ describe("launchPersistentContext (unit)", () => {expect(requestProxyWarnings(warnSpy)).toBe(0);});- it("applies DEFAULT_VIEWPORT", async () => {+ it("uses no emulated viewport by default (headless too)", async () => {const { launchPersistentContext } = await import("../src/playwright.js");await launchPersistentContext({ userDataDir: "/tmp/profile" });const args = mockChromium.launchPersistentContext.mock.calls[0][1];- expect(args.viewport).toEqual(DEFAULT_VIEWPORT);+ expect(args.viewport).toBeNull();});it("passes timezone and locale via binary args, not CDP context", async () => {@@ -590,32 +580,16 @@ describe("launchPersistentContext (unit)", () => {expect(args.locale).toBeUndefined();});- it("forwards proxy string", async () => {- // Free macOS → credentialed HTTP proxy via Playwright's proxy dict, not- // inline --proxy-server. Drive platform via process.platform/arch.- const origPlatform = Object.getOwnPropertyDescriptor(process, "platform")!;- const origArch = Object.getOwnPropertyDescriptor(process, "arch")!;- Object.defineProperty(process, "platform", { value: "darwin", configurable: true });- Object.defineProperty(process, "arch", { value: "arm64", configurable: true });- try {- const { launchPersistentContext } = await import("../src/playwright.js");- await launchPersistentContext({- userDataDir: "/tmp/profile",- proxy: "http://user:pass@proxy:8080",- });-- const args = mockChromium.launchPersistentContext.mock.calls[0][1];- expect(args.proxy).toEqual({- server: "http://proxy:8080",- username: "user",- password: "pass",- });- expect(args.args).not.toContain("--proxy-server=http://user:pass@proxy:8080");- } finally {- Object.defineProperty(process, "platform", origPlatform);- Object.defineProperty(process, "arch", origArch);- vi.restoreAllMocks();- }+ it("forwards a credentialed proxy string inline via --proxy-server", async () => {+ const { launchPersistentContext } = await import("../src/playwright.js");+ await launchPersistentContext({+ userDataDir: "/tmp/profile",+ proxy: "http://user:pass@proxy:8080",+ });++ const args = mockChromium.launchPersistentContext.mock.calls[0][1];+ expect(args.proxy).toBeUndefined();+ expect(args.args).toContain("--proxy-server=http://user:pass@proxy:8080");});it("forwards userAgent and colorScheme", async () => {diff --git a/js/tests/license.test.ts b/js/tests/license.test.tsindex e70ca7e..1f5edf6 100644--- a/js/tests/license.test.ts+++ b/js/tests/license.test.ts@@ -486,17 +486,9 @@ describe("getProLatestVersion", () => {// ── Config pro parameter ──────────────────────────────-describe("config pro parameter", () => {- it("getBinaryDir adds -pro suffix", () => {- const normal = config.getBinaryDir("147.0.0.0");- const pro = config.getBinaryDir("147.0.0.0", true);- expect(normal).toMatch(/chromium-147\.0\.0\.0$/);- expect(pro).toMatch(/chromium-147\.0\.0\.0-pro$/);- });-- it("getBinaryDir default has no suffix", () => {- const normal = config.getBinaryDir("147.0.0.0");- expect(normal).not.toMatch(/-pro$/);+describe("config cache dir", () => {+ it("getBinaryDir keeps the -pro suffix (existing caches stay valid)", () => {+ expect(config.getBinaryDir("147.0.0.0")).toMatch(/chromium-147\.0\.0\.0-pro$/);});});diff --git a/js/tests/profile-seed.test.ts b/js/tests/profile-seed.test.tsindex f52cceb..a619588 100644--- a/js/tests/profile-seed.test.ts+++ b/js/tests/profile-seed.test.ts@@ -107,7 +107,7 @@ describe("launchers use the stored seed", () => {it("playwright launchPersistentContext reuses the seed, launch() stays random", async () => {const chromium = {launchPersistentContext: vi.fn().mockResolvedValue({ close: vi.fn(), pages: () => [] }),- launch: vi.fn().mockResolvedValue({ close: vi.fn(), on: vi.fn(), contexts: () => [] }),+ launch: vi.fn().mockResolvedValue({ close: vi.fn(), on: vi.fn(), contexts: () => [], newContext: vi.fn(), newPage: vi.fn() }),};vi.doMock("playwright-core", () => ({ chromium }));const { launchPersistentContext, launch } = await import("../src/playwright.js");@@ -153,7 +153,7 @@ describe("launchers use the stored seed", () => {it("playwright launchContext stays random and writes nothing", async () => {const context = { close: vi.fn(), pages: () => [], on: vi.fn() };const chromium = {- launch: vi.fn().mockResolvedValue({ close: vi.fn(), on: vi.fn(), contexts: () => [], newContext: vi.fn().mockResolvedValue(context) }),+ launch: vi.fn().mockResolvedValue({ close: vi.fn(), on: vi.fn(), contexts: () => [], newContext: vi.fn().mockResolvedValue(context), newPage: vi.fn() }),};vi.doMock("playwright-core", () => ({ chromium }));const cwd = process.cwd();diff --git a/js/tests/proxy.test.ts b/js/tests/proxy.test.tsindex d684f52..8635513 100644--- a/js/tests/proxy.test.ts+++ b/js/tests/proxy.test.ts@@ -1,54 +1,17 @@import { describe, it, expect, vi } from "vitest";-import fs from "node:fs";-import path from "node:path";-import { parseProxyUrl, isSocksProxy, resolveProxyConfig } from "../src/proxy.js";-import * as config from "../src/config.js";+import { isSocksProxy, resolveProxyConfig } from "../src/proxy.js";import type { LaunchOptions } from "../src/types.js";-describe("parseProxyUrl", () => {- it("passes through URL without credentials", () => {- expect(parseProxyUrl("http://proxy:8080")).toEqual({- server: "http://proxy:8080",- });- });-- it("extracts credentials from URL", () => {- expect(parseProxyUrl("http://user:pass@proxy:8080")).toEqual({- server: "http://proxy:8080",- username: "user",- password: "pass",+describe("proxy without credentials", () => {+ it("passes the string through as the Playwright server", () => {+ expect(resolveProxyConfig("http://proxy:8080")).toEqual({+ proxyOption: { server: "http://proxy:8080" },+ proxyArgs: [],});});- it("decodes URL-encoded special chars", () => {- const result = parseProxyUrl("http://user:p%40ss%3Aword@proxy:8080");- expect(result.password).toBe("p@ss:word");- expect(result.username).toBe("user");- expect(result.server).toBe("http://proxy:8080");- });-- it("handles socks5 protocol", () => {- const result = parseProxyUrl("socks5://user:pass@proxy:1080");- expect(result.server).toBe("socks5://proxy:1080");- expect(result.username).toBe("user");- expect(result.password).toBe("pass");- });-- it("handles URL without port", () => {- const result = parseProxyUrl("http://user:pass@proxy");- expect(result.server).toBe("http://proxy");- expect(result.username).toBe("user");- });-- it("handles username only (no password)", () => {- const result = parseProxyUrl("http://user@proxy:8080");- expect(result.server).toBe("http://proxy:8080");- expect(result.username).toBe("user");- expect(result.password).toBeUndefined();- });-- it("passes through unparseable string", () => {- expect(parseProxyUrl("not-a-url")).toEqual({ server: "not-a-url" });+ it("passes an unparseable string through", () => {+ expect(resolveProxyConfig("not-a-url").proxyOption).toEqual({ server: "not-a-url" });});});@@ -86,36 +49,9 @@ describe("proxy dict type", () => {});});-describe("bare proxy format (user:pass@host:port)", () => {- it("extracts credentials from bare format", () => {- expect(parseProxyUrl("user:pass@proxy:8080")).toEqual({- server: "http://proxy:8080",- username: "user",- password: "pass",- });- });-- it("credentials not in server", () => {- const r = parseProxyUrl("user:[email protected]:5610");- expect(r.server).not.toContain("user");- expect(r.server).not.toContain("pass");- });-- it("bare username only", () => {- const r = parseProxyUrl("user@proxy:8080");- expect(r.username).toBe("user");- expect(r.password).toBeUndefined();- expect(r.server).toBe("http://proxy:8080");- });-- it("bare no port", () => {- const r = parseProxyUrl("user:[email protected]");- expect(r.username).toBe("user");- expect(r.server).toBe("http://proxy.example.com");- });-+describe("bare proxy format (no scheme)", () => {it("bare no credentials passes through unchanged", () => {- expect(parseProxyUrl("proxy:8080")).toEqual({ server: "proxy:8080" });+ expect(resolveProxyConfig("proxy:8080").proxyOption).toEqual({ server: "proxy:8080" });});});@@ -150,10 +86,8 @@ describe("isSocksProxy", () => {});describe("resolveProxyConfig", () => {- // binarySupportsHttpProxyInlineAuth reads getPlatformTag() intra-config, which- // a vi.spyOn(config, ...) can't intercept (ESM live binding). getPlatformTag- // derives from process.platform/arch at call time, so override those instead —- // this correctly drives the per-platform floor lookup and version resolution.+ // getPlatformTag derives from process.platform/arch at call time, so override+ // those to prove no platform falls back to Playwright's proxy dict.const origPlatform = Object.getOwnPropertyDescriptor(process, "platform")!;const origArch = Object.getOwnPropertyDescriptor(process, "arch")!;function setPlatform(platform: string, arch: string): void {@@ -171,14 +105,20 @@ describe("resolveProxyConfig", () => {expect(proxyArgs).toEqual([]);});- it("falls back to playwright dict for http string on free macOS", () => {- setPlatform("darwin", "arm64");+ it.each([+ ["linux", "x64"], ["linux", "arm64"], ["darwin", "arm64"], ["darwin", "x64"], ["win32", "x64"],+ ])("sends http creds inline on %s-%s (every served build ships inline auth)", (platform, arch) => {+ setPlatform(platform, arch);+ const prev = process.env.CLOAKBROWSER_BINARY_PATH;+ process.env.CLOAKBROWSER_BINARY_PATH = "/x/chrome"; // an unversioned override tootry {const { proxyOption, proxyArgs } = resolveProxyConfig("http://user:pass@proxy:8080");- expect(proxyOption).toEqual({ server: "http://proxy:8080", username: "user", password: "pass" });- expect(proxyArgs).toEqual([]);+ expect(proxyOption).toBeUndefined();+ expect(proxyArgs).toEqual(["--proxy-server=http://user:pass@proxy:8080"]);} finally {restorePlatform();+ if (prev === undefined) delete process.env.CLOAKBROWSER_BINARY_PATH;+ else process.env.CLOAKBROWSER_BINARY_PATH = prev;}});@@ -345,161 +285,31 @@ describe("resolveProxyConfig", () => {}});- // --- HTTP with credentials → --proxy-server (supported platform + version) ----- // Supported cases pass the version via the browserVersion param (declared-pin- // path) so resolution is deterministic; setPlatform drives the floor lookup.- it("routes http string with creds through --proxy-server on linux-x64 v177.5", () => {- setPlatform("linux", "x64");- try {- const { proxyOption, proxyArgs } = resolveProxyConfig(- "http://user:pass@proxy:8080",- "146.0.7680.177.5",- );- expect(proxyOption).toBeUndefined();- expect(proxyArgs).toEqual(["--proxy-server=http://user:pass@proxy:8080"]);- } finally {- restorePlatform();- }- });-- it("routes http dict with creds through --proxy-server on linux-x64 v177.5", () => {- setPlatform("linux", "x64");- try {- const { proxyOption, proxyArgs } = resolveProxyConfig(- {- server: "http://proxy:8080",- username: "user",- password: "pass",- },- "146.0.7680.177.5",- );- expect(proxyOption).toBeUndefined();- expect(proxyArgs).toEqual(["--proxy-server=http://user:pass@proxy:8080"]);- } finally {- restorePlatform();- }- });+ // --- HTTP with credentials → always inline via --proxy-server ---- it("includes bypass for http dict with creds on windows-x64 v177.5", () => {- setPlatform("win32", "x64");- try {- const { proxyArgs } = resolveProxyConfig(- {- server: "http://proxy:8080",- username: "user",- password: "pass",- bypass: ".google.com",- },- "146.0.7680.177.5",- );- expect(proxyArgs).toContain("--proxy-server=http://user:pass@proxy:8080");- expect(proxyArgs).toContain("--proxy-bypass-list=.google.com");- } finally {- restorePlatform();- }- });-- it("encodes special chars in http proxy password on supported platform v177.5", () => {- setPlatform("linux", "x64");- try {- const { proxyArgs } = resolveProxyConfig(- "http://user:pass=123@proxy:8080",- "146.0.7680.177.5",- );- expect(proxyArgs).toEqual(["--proxy-server=http://user:pass%3D123@proxy:8080"]);- } finally {- restorePlatform();- }- });-- it("falls back to playwright dict with an old pinned version", () => {- setPlatform("linux", "x64");- try {- const { proxyOption, proxyArgs } = resolveProxyConfig(- "http://user:pass@proxy:8080",- "146.0.7680.177.3",- );- expect(proxyOption).toEqual({ server: "http://proxy:8080", username: "user", password: "pass" });- expect(proxyArgs).toEqual([]);- } finally {- restorePlatform();- }- });-- it("inline auth for http with creds on a new pinned darwin-arm64 build", () => {- setPlatform("darwin", "arm64");- try {- const { proxyOption, proxyArgs } = resolveProxyConfig(- "http://user:pass@proxy:8080",- "148.0.7778.215.3",- );- expect(proxyOption).toBeUndefined();- expect(proxyArgs).toEqual(["--proxy-server=http://user:pass@proxy:8080"]);- } finally {- restorePlatform();- }+ it("sends an http dict with creds inline", () => {+ const { proxyOption, proxyArgs } = resolveProxyConfig({+ server: "http://proxy:8080",+ username: "user",+ password: "pass",+ });+ expect(proxyOption).toBeUndefined();+ expect(proxyArgs).toEqual(["--proxy-server=http://user:pass@proxy:8080"]);});- it("falls back to playwright dict for http with creds on free linux-arm64", () => {- setPlatform("linux", "arm64");- try {- const { proxyOption, proxyArgs } = resolveProxyConfig(- "http://user:pass@proxy:8080",- "146.0.7680.177.3",- );- expect(proxyOption).toBeDefined();- expect(proxyArgs).toEqual([]);- } finally {- restorePlatform();- }+ it("keeps the bypass list for an http dict with creds", () => {+ const { proxyArgs } = resolveProxyConfig({+ server: "http://proxy:8080",+ username: "user",+ password: "pass",+ bypass: ".google.com",+ });+ expect(proxyArgs).toContain("--proxy-server=http://user:pass@proxy:8080");+ expect(proxyArgs).toContain("--proxy-bypass-list=.google.com");});- it("uses the selected release channel for inline-auth gating", () => {- const originalCacheDir = process.env.CLOAKBROWSER_CACHE_DIR;- const cacheDir = `/tmp/cloakbrowser-proxy-preview-${Date.now()}`;- process.env.CLOAKBROWSER_CACHE_DIR = cacheDir;- try {- for (const [channel, version] of [- ["stable", "145.0.1000.1"],- ["preview", "148.0.7778.215.4"],- ] as const) {- const binaryPath = config.getBinaryPath(version, true);- fs.mkdirSync(path.dirname(binaryPath), { recursive: true });- fs.writeFileSync(binaryPath, "fake");- fs.chmodSync(binaryPath, 0o755);- const markerPrefix = channel === "preview"- ? "latest_pro_version_preview"- : "latest_pro_version";- fs.writeFileSync(- path.join(cacheDir, `${markerPrefix}_${config.getPlatformTag()}`),- version,- );- }-- const stable = resolveProxyConfig(- "http://user:pass@proxy:8080",- undefined,- "cb_test",- "stable",- );- const preview = resolveProxyConfig(- "http://user:pass@proxy:8080",- undefined,- "cb_test",- "preview",- );-- expect(stable.proxyOption).toBeDefined();- expect(stable.proxyArgs).toEqual([]);- expect(preview.proxyOption).toBeUndefined();- expect(preview.proxyArgs).toEqual([- "--proxy-server=http://user:pass@proxy:8080",- ]);- } finally {- fs.rmSync(cacheDir, { recursive: true, force: true });- if (originalCacheDir === undefined) delete process.env.CLOAKBROWSER_CACHE_DIR;- else process.env.CLOAKBROWSER_CACHE_DIR = originalCacheDir;- }+ it("encodes special chars in an inline http proxy password", () => {+ const { proxyArgs } = resolveProxyConfig("http://user:pass=123@proxy:8080");+ expect(proxyArgs).toEqual(["--proxy-server=http://user:pass%3D123@proxy:8080"]);});});diff --git a/js/tests/puppeteer.test.ts b/js/tests/puppeteer.test.tsindex 646a395..fd5f593 100644--- a/js/tests/puppeteer.test.ts+++ b/js/tests/puppeteer.test.ts@@ -83,15 +83,14 @@ describe("puppeteer launch", () => {expect(callArgs.args.some((a: string) => a.startsWith("--fingerprint="))).toBe(false);});- it("headless (default) uses a fixed defaultViewport; headed uses null", async () => {- const { DEFAULT_VIEWPORT } = await import("../src/config.js");+ it("uses a null defaultViewport, headless (default) or headed", async () => {const { launch } = await import("../src/puppeteer.js");- // Headless (default): deterministic viewport.+ // Headless (default): the binary reports coherent dimensions itself.await launch();expect(vi.mocked(puppeteerMock.default.launch).mock.calls[0][0].defaultViewport- ).toEqual(DEFAULT_VIEWPORT);+ ).toBeNull();// Headed: null so the page tracks the real window (else Puppeteer forces 800x600).vi.mocked(puppeteerMock.default.launch).mockClear();@@ -110,7 +109,7 @@ describe("puppeteer launch", () => {vi.mocked(puppeteerMock.default.launch).mock.calls[0][0].defaultViewport).toEqual(custom);- // Explicit null honored even in headless (would otherwise default to DEFAULT_VIEWPORT).+ // Explicit null honored.vi.mocked(puppeteerMock.default.launch).mockClear();await launch({ headless: true, launchOptions: { defaultViewport: null } });expect(@@ -119,15 +118,13 @@ describe("puppeteer launch", () => {});it("Puppeteer headless precedence: top-level headless wins over launchOptions.headless", async () => {- const { DEFAULT_VIEWPORT } = await import("../src/config.js");const { launch } = await import("../src/puppeteer.js");- // Puppeteer sets headless AFTER the launchOptions spread, so top-level wins at- // launch — the viewport decision must follow the same (top-level) value.+ // Puppeteer sets headless AFTER the launchOptions spread, so top-level wins.await launch({ headless: true, launchOptions: { headless: false } });const opts = vi.mocked(puppeteerMock.default.launch).mock.calls[0][0];expect(opts.headless).toBe(true);- expect(opts.defaultViewport).toEqual(DEFAULT_VIEWPORT);+ expect(opts.defaultViewport).toBeNull();});it("adds --proxy-server for string proxy", async () => {@@ -149,9 +146,7 @@ describe("puppeteer launch", () => {expect(callArgs.args).toContain("--proxy-bypass-list=.google.com,localhost");});- it("uses page.authenticate fallback for http proxy on free macOS", async () => {- // Free macOS lacks inline proxy auth → strip creds, use page.authenticate.- // getPlatformTag reads process.platform/arch at call time.+ it("passes inline creds via --proxy-server on every platform (no page.authenticate)", async () => {const origPlatform = Object.getOwnPropertyDescriptor(process, "platform")!;const origArch = Object.getOwnPropertyDescriptor(process, "arch")!;Object.defineProperty(process, "platform", { value: "darwin", configurable: true });@@ -160,29 +155,6 @@ describe("puppeteer launch", () => {const { launch } = await import("../src/puppeteer.js");const browser = await launch({ proxy: "http://user:pass@proxy:8080" });- const callArgs = vi.mocked(puppeteerMock.default.launch).mock.calls[0][0];- expect(callArgs.args).toContain("--proxy-server=http://proxy:8080");- const page = await browser.newPage();- expect(page.authenticate).toHaveBeenCalledWith({ username: "user", password: "pass" });- } finally {- Object.defineProperty(process, "platform", origPlatform);- Object.defineProperty(process, "arch", origArch);- vi.restoreAllMocks();- }- });-- it("passes inline creds via --proxy-server on supported platform (no page.authenticate)", async () => {- const origPlatform = Object.getOwnPropertyDescriptor(process, "platform")!;- const origArch = Object.getOwnPropertyDescriptor(process, "arch")!;- Object.defineProperty(process, "platform", { value: "linux", configurable: true });- Object.defineProperty(process, "arch", { value: "x64", configurable: true });- try {- const { launch } = await import("../src/puppeteer.js");- const browser = await launch({- proxy: "http://user:pass@proxy:8080",- browserVersion: "146.0.7680.177.5",- });-const callArgs = vi.mocked(puppeteerMock.default.launch).mock.calls[0][0];expect(callArgs.args).toContain("--proxy-server=http://user:pass@proxy:8080");@@ -317,8 +289,7 @@ describe("puppeteer launchPersistentContext", () => {expect(callArgs.args.some((a: string) => a.startsWith("--fingerprint="))).toBe(true);});- it("headed persistent context uses null defaultViewport (tracks real window)", async () => {- const { DEFAULT_VIEWPORT } = await import("../src/config.js");+ it("persistent context uses null defaultViewport, headed or headless", async () => {const { launchPersistentContext } = await import("../src/puppeteer.js");await launchPersistentContext({ userDataDir: "./my-profile", headless: false });@@ -330,10 +301,10 @@ describe("puppeteer launchPersistentContext", () => {await launchPersistentContext({ userDataDir: "./my-profile", headless: true });expect(vi.mocked(puppeteerMock.default.launch).mock.calls[0][0].defaultViewport- ).toEqual(DEFAULT_VIEWPORT);+ ).toBeNull();});- it("uses page.authenticate fallback in persistent context on free macOS", async () => {+ it("passes inline http creds in a persistent context on macOS (no page.authenticate)", async () => {const origPlatform = Object.getOwnPropertyDescriptor(process, "platform")!;const origArch = Object.getOwnPropertyDescriptor(process, "arch")!;Object.defineProperty(process, "platform", { value: "darwin", configurable: true });@@ -346,9 +317,9 @@ describe("puppeteer launchPersistentContext", () => {});const callArgs = vi.mocked(puppeteerMock.default.launch).mock.calls[0][0];- expect(callArgs.args).toContain("--proxy-server=http://proxy:8080");+ expect(callArgs.args).toContain("--proxy-server=http://user:pass@proxy:8080");const page = await browser.newPage();- expect(page.authenticate).toHaveBeenCalledWith({ username: "user", password: "pass" });+ expect(page.authenticate).not.toHaveBeenCalled();} finally {Object.defineProperty(process, "platform", origPlatform);Object.defineProperty(process, "arch", origArch);diff --git a/js/tests/setup.ts b/js/tests/setup.tsindex f475007..500aabf 100644--- a/js/tests/setup.ts+++ b/js/tests/setup.ts@@ -1,9 +1,9 @@/*** Keep the suite away from the developer's real ~/.cloakbrowser.*- * A license.key (or a cached Pro version marker) there resolves the machine as- * Pro, which flips version-gated defaults such as the headless no-viewport shim- * — tests then assert against whatever the developer happens to have installed.+ * A license.key (or a cached version marker) there changes how a launch resolves+ * its key and build — tests would then assert against whatever the developer+ * happens to have installed.* A fixed path (not mkdtemp) so parallel workers share one dir instead of each* stranding its own.*/diff --git a/js/tests/signature.test.ts b/js/tests/signature.test.tsindex b6981e2..e1e4b22 100644--- a/js/tests/signature.test.ts+++ b/js/tests/signature.test.ts@@ -28,14 +28,12 @@ vi.mock("../src/config.js", async (importActual) => {import {BinaryVerificationError,downloadProBinary,- fetchSignedManifest,parseChecksums,parseManifestVersion,- verifyDownloadChecksum,verifyProDownload,verifySignature,} from "../src/download.js";-import { DOWNLOAD_BASE_URL, getArchiveName, getChromiumVersion } from "../src/config.js";+import { DOWNLOAD_BASE_URL, getArchiveName } from "../src/config.js";/** Produce SHA256SUMS.sig content (base64 text bytes) for a manifest. */function sign(manifest: Uint8Array): Uint8Array {@@ -94,88 +92,6 @@ describe("verifySignature", () => {});});-describe("verifyDownloadChecksum (official path, fail-closed)", () => {- afterEach(() => {- vi.restoreAllMocks();- delete process.env.CLOAKBROWSER_DOWNLOAD_URL;- delete process.env.CLOAKBROWSER_SKIP_CHECKSUM;- });-- function tmpFile(bytes: Buffer): string {- const p = path.join(os.tmpdir(), `cloak-sig-${process.pid}-${bytes.length}-${bytes[0]}`);- fs.writeFileSync(p, bytes);- return p;- }-- /** Mock fetch to serve a signed manifest for the official URLs. */- function mockManifest(manifestBytes: Uint8Array) {- const sig = sign(manifestBytes);- vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {- const url = typeof input === "string" ? input : (input as URL).toString();- const body = url.endsWith(".sig") ? sig : manifestBytes;- return { ok: true, arrayBuffer: async () => body.buffer } as Response;- });- }-- /** Manifest body with the bound version line prepended (defaults to current). */- const body = (lines: string, version = getChromiumVersion()) =>- enc(`version=${version}\n${lines}`);-- it("passes when signature is valid and hash matches", async () => {- const data = Buffer.from("the real binary");- const file = tmpFile(data);- const hash = createHash("sha256").update(data).digest("hex");- mockManifest(body(`${hash} ${getArchiveName()}\n`));- await expect(verifyDownloadChecksum(file)).resolves.toBeUndefined();- });-- it("fails when the binary is tampered (hash mismatch)", async () => {- const file = tmpFile(Buffer.from("a malicious binary"));- const goodHash = createHash("sha256").update(Buffer.from("the real binary")).digest("hex");- mockManifest(body(`${goodHash} ${getArchiveName()}\n`));- await expect(verifyDownloadChecksum(file)).rejects.toThrow(/Checksum verification failed/);- });-- it("fails on a signed manifest for the wrong version (downgrade)", async () => {- const data = Buffer.from("the real binary");- const file = tmpFile(data);- const hash = createHash("sha256").update(data).digest("hex");- // Genuinely signed, but declares an old version we did not request.- mockManifest(body(`${hash} ${getArchiveName()}\n`, "1.0.0.0"));- await expect(verifyDownloadChecksum(file)).rejects.toThrow(/Version mismatch/);- });-- it("fails when the version line is missing (binding required)", async () => {- const data = Buffer.from("the real binary");- const file = tmpFile(data);- const hash = createHash("sha256").update(data).digest("hex");- mockManifest(enc(`${hash} ${getArchiveName()}\n`)); // no version= line- await expect(verifyDownloadChecksum(file)).rejects.toThrow(/Version mismatch/);- });-- it("fails closed when no signed manifest can be fetched", async () => {- const file = tmpFile(Buffer.from("x"));- vi.spyOn(globalThis, "fetch").mockResolvedValue({ ok: false, status: 404 } as Response);- await expect(verifyDownloadChecksum(file)).rejects.toThrow(/signed SHA256SUMS/);- });-- it("fails when the signed manifest has no entry for this platform", async () => {- const file = tmpFile(Buffer.from("x"));- const someHash = "0".repeat(64);- mockManifest(body(`${someHash} some-other-file.tar.gz\n`));- await expect(verifyDownloadChecksum(file)).rejects.toThrow(/no entry for/);- });-- it("custom download URL keeps the legacy skippable path (no signature fetch)", async () => {- const file = tmpFile(Buffer.from("x"));- process.env.CLOAKBROWSER_DOWNLOAD_URL = "https://my-mirror.test";- process.env.CLOAKBROWSER_SKIP_CHECKSUM = "true";- const spy = vi.spyOn(globalThis, "fetch");- await expect(verifyDownloadChecksum(file)).resolves.toBeUndefined();- expect(spy).not.toHaveBeenCalled();- });-});-describe("downloadProBinary (version-pinned URL)", () => {afterEach(() => vi.restoreAllMocks());@@ -294,43 +210,3 @@ describe("version binding", () => {expect(result.has("cloakbrowser-linux-x64.tar.gz")).toBe(true);});});--describe("fetchSignedManifest", () => {- afterEach(() => {- vi.restoreAllMocks();- });-- const mockPair = (manifest: string, sig: string, failPrimarySig = false) =>- vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {- const url = typeof input === "string" ? input : (input as URL).toString();- const isSig = url.endsWith(".sig");- if (url.includes("cloakbrowser.dev") && isSig && failPrimarySig) {- return { ok: false, status: 404 } as Response;- }- return {- ok: true,- arrayBuffer: async () =>- new TextEncoder().encode(isSig ? sig : manifest).buffer,- } as Response;- });-- it("returns manifest + sig from the primary origin", async () => {- mockPair("MANIFEST", "U0lH");- const result = await fetchSignedManifest("1.2.3.4");- expect(new TextDecoder().decode(result!.manifestBytes)).toBe("MANIFEST");- expect(new TextDecoder().decode(result!.sigBytes)).toBe("U0lH");- });-- it("falls back to GitHub when the primary .sig is missing", async () => {- const spy = mockPair("MANIFEST", "U0lH", true);- const result = await fetchSignedManifest("1.2.3.4");- expect(result).not.toBeNull();- // primary SHA256SUMS + primary .sig (404) + github SHA256SUMS + github .sig- expect(spy.mock.calls.length).toBeGreaterThanOrEqual(3);- });-- it("returns null when everything fails", async () => {- vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("network"));- expect(await fetchSignedManifest("1.2.3.4")).toBeNull();- });-});diff --git a/js/tests/update.test.ts b/js/tests/update.test.tsindex 766865d..d215dd0 100644--- a/js/tests/update.test.ts+++ b/js/tests/update.test.ts@@ -6,14 +6,12 @@ import type { AddressInfo } from "node:net";import * as os from "node:os";import * as path from "node:path";import { promisify } from "node:util";+import { createHash, generateKeyPairSync, sign as cryptoSign } from "node:crypto";import {- binarySupportsHeadlessNoViewport,- binarySupportsHttpProxyInlineAuth,- binarySupportsMaximizedWindow,- getChromiumVersion,+ BINARY_SIGNING_PUBKEYS,+ getArchiveName,getBinaryDir,getBinaryPath,- getDownloadUrl,getEffectiveVersion,getPlatformTag,parseVersion,@@ -21,12 +19,9 @@ import {} from "../src/config.js";import {checkForProUpdate,- checkForUpdate,checkWrapperUpdate,clearCache,ensureBinary,- fetchChecksums,- getLatestChromiumVersion,parseChecksums,resetWrapperUpdateChecked,resetPreviewFallbackWarned,@@ -75,111 +70,15 @@ describe("version comparison", () => {});});-describe("download URL", () => {- it("uses chromium-v prefix and cloakbrowser repo", () => {- const url = getDownloadUrl();- expect(url).toContain("cloakbrowser.dev");- expect(url).toContain(`chromium-v${getChromiumVersion()}`);- expect(url.endsWith(".tar.gz")).toBe(true);- });-- it("accepts custom version", () => {- const url = getDownloadUrl("145.0.7718.0");- expect(url).toContain("chromium-v145.0.7718.0");- });-- it("does not reference old repo", () => {- const url = getDownloadUrl();- expect(url).not.toContain("chromium-stealth-builds");- });-});--describe("latest version (platform-aware)", () => {- function makeAssets(platforms: string[]) {- return platforms.map((p) => ({ name: `cloakbrowser-${p}.tar.gz` }));- }-- function mockFetch(releases: Array<Record<string, unknown>>) {- return vi.spyOn(globalThis, "fetch").mockResolvedValue({- ok: true,- json: async () => releases,- } as Response);- }-- afterEach(() => {- vi.restoreAllMocks();- });-- it("returns version when release has platform asset", async () => {- mockFetch([- {- tag_name: "chromium-v145.0.7718.0",- draft: false,- assets: makeAssets(["linux-x64", "darwin-arm64", "darwin-x64", "windows-x64"]),- },- ]);- expect(await getLatestChromiumVersion()).toBe("145.0.7718.0");- });-- it("skips release without platform asset", async () => {- mockFetch([- {- tag_name: "chromium-v145.0.7718.0",- draft: false,- assets: makeAssets(["linux-x64"]), // Linux only- },- {- tag_name: "chromium-v142.0.7444.175",- draft: false,- assets: makeAssets(["linux-x64", "darwin-arm64", "darwin-x64", "windows-x64"]),- },- ]);- const result = await getLatestChromiumVersion();- const tag = getPlatformTag();- if (tag === "linux-x64") {- expect(result).toBe("145.0.7718.0");- } else {- expect(result).toBe("142.0.7444.175");- }- });-- it("returns null when no release has platform asset", async () => {- mockFetch([- {- tag_name: "chromium-v145.0.7718.0",- draft: false,- assets: [{ name: "cloakbrowser-freebsd-x64.tar.gz" }],- },- ]);- expect(await getLatestChromiumVersion()).toBeNull();- });-- it("skips draft releases", async () => {- const all = ["linux-x64", "darwin-arm64", "darwin-x64", "windows-x64"];- mockFetch([- { tag_name: "chromium-v999.0.0.0", draft: true, assets: makeAssets(all) },- { tag_name: "chromium-v145.0.7718.0", draft: false, assets: makeAssets(all) },- ]);- expect(await getLatestChromiumVersion()).toBe("145.0.7718.0");- });-- it("returns null on network error", async () => {- vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("timeout"));- expect(await getLatestChromiumVersion()).toBeNull();- });-});-describe("wrapper update check", () => {beforeEach(() => {resetWrapperUpdateChecked();delete process.env.CLOAKBROWSER_AUTO_UPDATE;- delete process.env.CLOAKBROWSER_DOWNLOAD_URL;});afterEach(() => {vi.restoreAllMocks();delete process.env.CLOAKBROWSER_AUTO_UPDATE;- delete process.env.CLOAKBROWSER_DOWNLOAD_URL;});it("warns when newer version available", async () => {@@ -217,15 +116,6 @@ describe("wrapper update check", () => {expect(spy).not.toHaveBeenCalled();});- it("disabled by CLOAKBROWSER_DOWNLOAD_URL", async () => {- process.env.CLOAKBROWSER_DOWNLOAD_URL = "https://mirror.example.com";- const spy = vi.spyOn(globalThis, "fetch");-- await checkWrapperUpdate();-- expect(spy).not.toHaveBeenCalled();- });-it("silent on network error", async () => {vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("timeout"));const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});@@ -280,81 +170,19 @@ describe("parseChecksums", () => {});});-describe("download fallback", () => {- afterEach(() => {- vi.restoreAllMocks();- delete process.env.CLOAKBROWSER_DOWNLOAD_URL;- });-- it("checksum fetch falls back to GitHub on primary 429", async () => {- const HASH =- "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";- const checksumText = `${HASH} cloakbrowser-${getPlatformTag()}.tar.gz`;-- vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {- const url =- typeof input === "string"- ? input- : input instanceof URL- ? input.toString()- : (input as Request).url;- if (url.includes("cloakbrowser.dev")) {- return {- ok: false,- status: 429,- statusText: "Too Many Requests",- } as Response;- }- // GitHub fallback- return { ok: true, text: async () => checksumText } as Response;- });-- const result = await fetchChecksums();- expect(result).not.toBeNull();- expect(- result!.has(`cloakbrowser-${getPlatformTag()}.tar.gz`)- ).toBe(true);- });-- it("checksum fetch returns null when both sources fail", async () => {- vi.spyOn(globalThis, "fetch").mockResolvedValue({- ok: false,- status: 429,- statusText: "Too Many Requests",- } as Response);-- const result = await fetchChecksums();- expect(result).toBeNull();- });-});-describe("effective version", () => {- it("returns platform version when no marker exists", () => {- const orig = process.env.CLOAKBROWSER_CACHE_DIR;- process.env.CLOAKBROWSER_CACHE_DIR = `/tmp/cloakbrowser-test-${Date.now()}`;- try {- expect(getEffectiveVersion()).toBe(getChromiumVersion());- } finally {- if (orig) process.env.CLOAKBROWSER_CACHE_DIR = orig;- else delete process.env.CLOAKBROWSER_CACHE_DIR;- }- });-- // A valid Pro license must NEVER fall back to the free binary.- it("returns null for Pro when nothing is cached (never the free base)", () => {+ it("returns null when nothing is cached", () => {const orig = process.env.CLOAKBROWSER_CACHE_DIR;process.env.CLOAKBROWSER_CACHE_DIR = `/tmp/cloakbrowser-test-${Date.now()}-pro`;try {- expect(getEffectiveVersion(true)).toBeNull();- // Free tier still resolves to a concrete version.- expect(getEffectiveVersion(false)).toBe(getChromiumVersion());+ expect(getEffectiveVersion()).toBeNull();} finally {if (orig) process.env.CLOAKBROWSER_CACHE_DIR = orig;else delete process.env.CLOAKBROWSER_CACHE_DIR;}});- it("returns null for Pro when the marker's binary is missing", () => {+ it("returns null when the marker's binary is missing", () => {const orig = process.env.CLOAKBROWSER_CACHE_DIR;const dir = `/tmp/cloakbrowser-test-${Date.now()}-promarker`;process.env.CLOAKBROWSER_CACHE_DIR = dir;@@ -364,8 +192,8 @@ describe("effective version", () => {path.join(dir, `latest_pro_version_${getPlatformTag()}`),"148.0.7778.215.5");- // Marker present, but no binary on disk → null, not the free base.- expect(getEffectiveVersion(true)).toBeNull();+ // Marker present, but no binary on disk → null.+ expect(getEffectiveVersion()).toBeNull();} finally {fs.rmSync(dir, { recursive: true, force: true });if (orig) process.env.CLOAKBROWSER_CACHE_DIR = orig;@@ -379,7 +207,7 @@ describe("preview Pro selection", () => {let originalCacheDir: string | undefined;function createProBinary(version: string): string {- const binaryPath = getBinaryPath(version, true);+ const binaryPath = getBinaryPath(version);fs.mkdirSync(path.dirname(binaryPath), { recursive: true });fs.writeFileSync(binaryPath, "fake");fs.chmodSync(binaryPath, 0o755);@@ -402,27 +230,6 @@ describe("preview Pro selection", () => {delete process.env.CLOAKBROWSER_RELEASE_CHANNEL;});- it("uses the selected channel for binary capability gates", () => {- const stable = "145.0.1000.1";- const preview = "148.0.7778.215.4";- createProBinary(stable);- createProBinary(preview);- fs.writeFileSync(- path.join(cacheDir, `latest_pro_version_${getPlatformTag()}`),- stable,- );- fs.writeFileSync(- path.join(cacheDir, `latest_pro_version_preview_${getPlatformTag()}`),- preview,- );-- expect(binarySupportsHeadlessNoViewport("cb_test", undefined, "stable")).toBe(false);- expect(binarySupportsHeadlessNoViewport("cb_test", undefined, "preview")).toBe(true);- expect(binarySupportsMaximizedWindow("cb_test", undefined, "preview")).toBe(true);- expect(binarySupportsHttpProxyInlineAuth("cb_test", undefined, "stable")).toBe(false);- expect(binarySupportsHttpProxyInlineAuth("cb_test", undefined, "preview")).toBe(true);- });-it("keeps a pinned preview launch isolated from latest markers", async () => {const pinned = "151.0.1000.1";const binaryPath = createProBinary(pinned);@@ -553,8 +360,7 @@ describe("preview Pro selection", () => {).toBe(false);});- it("aborts (never free) when the server rejects the key", async () => {- delete process.env.CLOAKBROWSER_DOWNLOAD_URL;+ it("aborts when the server rejects the key", async () => {vi.spyOn(globalThis, "fetch").mockResolvedValue({ok: true,json: async () => ({ valid: false, plan: "solo", expires: null }),@@ -563,8 +369,7 @@ describe("preview Pro selection", () => {await expect(ensureBinary("cb_bad")).rejects.toThrow(/invalid or expired/);});- it("aborts (never free) when the key cannot be validated (server down, no cache)", async () => {- delete process.env.CLOAKBROWSER_DOWNLOAD_URL;+ it("aborts when the key cannot be validated (server down, no cache)", async () => {vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("network down"));await expect(ensureBinary("cb_test")).rejects.toThrow(/could not be validated/);@@ -602,25 +407,6 @@ describe("clearCache", () => {});});-describe("checkForUpdate", () => {- afterEach(() => {- vi.restoreAllMocks();- });-- it("returns null when no newer version", async () => {- vi.spyOn(globalThis, "fetch").mockResolvedValue({- ok: true,- json: async () => [],- } as Response);- expect(await checkForUpdate()).toBeNull();- });-- it("returns null on network error", async () => {- vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("timeout"));- expect(await checkForUpdate()).toBeNull();- });-});-describe("welcome banner cadence", () => {let tmpDir: string;@@ -669,9 +455,16 @@ describe("concurrent first-run download", () => {const CALLERS = 4;const FILLER_FILES = 300;const PARTIAL_INSTALL_FILES = 2000;+ const VERSION = "155.0.8059.39.2";const binaryBytes = Buffer.from("#!/bin/sh\necho fake-chrome\n");+ // A throwaway signing key, pinned for these tests: the keyed download path+ // always verifies the signed manifest (nothing can skip it).+ const { publicKey, privateKey } = generateKeyPairSync("ed25519");+ const testPubB64 = Buffer.from(publicKey.export({ format: "jwk" }).x!, "base64url").toString("base64");let cacheDir: string;let archiveBytes: Buffer;+ let manifest: Buffer;+ let manifestSig: Buffer;let originalCacheDir: string | undefined;beforeEach(async () => {@@ -679,15 +472,14 @@ describe("concurrent first-run download", () => {originalCacheDir = process.env.CLOAKBROWSER_CACHE_DIR;cacheDir = fs.mkdtempSync(path.join(os.tmpdir(), "cloakbrowser-concurrent-"));process.env.CLOAKBROWSER_CACHE_DIR = cacheDir;- process.env.CLOAKBROWSER_DOWNLOAD_URL = "https://mirror.invalid";- process.env.CLOAKBROWSER_SKIP_CHECKSUM = "true";delete process.env.CLOAKBROWSER_BINARY_PATH;delete process.env.CLOAKBROWSER_VERSION;+ BINARY_SIGNING_PUBKEYS.push(testPubB64);// A small archive with the platform's binary layout plus enough filler// files that concurrent extractions overlap in time.const staging = fs.mkdtempSync(path.join(os.tmpdir(), "cloakbrowser-archive-"));- const binaryRelPath = path.relative(getBinaryDir(), getBinaryPath());+ const binaryRelPath = path.relative(getBinaryDir(VERSION), getBinaryPath(VERSION));fs.mkdirSync(path.join(staging, path.dirname(binaryRelPath)), { recursive: true });fs.writeFileSync(path.join(staging, binaryRelPath), binaryBytes, { mode: 0o755 });fs.mkdirSync(path.join(staging, "lib"));@@ -699,30 +491,55 @@ describe("concurrent first-run download", () => {archiveBytes = fs.readFileSync(archivePath);fs.rmSync(staging, { recursive: true, force: true });fs.rmSync(archivePath, { force: true });+ const hash = createHash("sha256").update(archiveBytes).digest("hex");+ manifest = Buffer.from(`version=${VERSION}\n${hash} ${getArchiveName()}\n`);+ manifestSig = Buffer.from(cryptoSign(null, manifest, privateKey).toString("base64"));});afterEach(() => {vi.restoreAllMocks();+ BINARY_SIGNING_PUBKEYS.splice(BINARY_SIGNING_PUBKEYS.indexOf(testPubB64), 1);fs.rmSync(cacheDir, { recursive: true, force: true });if (originalCacheDir === undefined) delete process.env.CLOAKBROWSER_CACHE_DIR;else process.env.CLOAKBROWSER_CACHE_DIR = originalCacheDir;- delete process.env.CLOAKBROWSER_DOWNLOAD_URL;- delete process.env.CLOAKBROWSER_SKIP_CHECKSUM;});+ /** The server, by path: license check, latest version, signed manifest, archive. */+ async function serve(pathname: string, downloadHold?: () => Promise<void>): Promise<Response> {+ if (pathname.endsWith("/api/license/validate")) {+ return Response.json({ valid: true, plan: "business", expires: null });+ }+ if (pathname.endsWith("/api/download/version")) return Response.json({ version: VERSION });+ if (pathname.endsWith("/SHA256SUMS")) return new Response(manifest);+ if (pathname.endsWith("/SHA256SUMS.sig")) return new Response(manifestSig);+ if (pathname.endsWith(`/api/download/${VERSION}`)) {+ await downloadHold?.();+ return new Response(archiveBytes);+ }+ return new Response("not found", { status: 404 }); // e.g. the npm update check+ }++ const urlPath = (input: unknown) =>+ new URL(input instanceof Request ? input.url : String(input)).pathname;+// Reads the install the way a launch would. Returns what is wrong with it, or "complete".function inspectInstall(): string {try {- const binaryPath = getBinaryPath();+ const binaryPath = getBinaryPath(VERSION);if (!fs.readFileSync(binaryPath).equals(binaryBytes)) return "binary content differs";if ((fs.statSync(binaryPath).mode & 0o111) === 0) return "binary not executable";- const fillerCount = fs.readdirSync(path.join(getBinaryDir(), "lib")).length;+ const fillerCount = fs.readdirSync(path.join(getBinaryDir(VERSION), "lib")).length;return fillerCount === FILLER_FILES ? "complete" : `lib has ${fillerCount} files`;} catch (err) {return (err as NodeJS.ErrnoException).code ?? String(err);}}+ const cacheEntries = () =>+ fs.readdirSync(cacheDir).filter((name) => !name.startsWith(".")).sort();+ const expectedEntries = () =>+ [path.basename(getBinaryDir(VERSION)), `latest_pro_version_${getPlatformTag()}`].sort();+it.skipIf(process.platform === "win32")("an install stays complete while other first-run callers finish",async () => {@@ -731,17 +548,18 @@ describe("concurrent first-run download", () => {// is the state a batch of simultaneous cold launches ends up in.let releaseHeldDownloads!: () => void;const heldDownloads = new Promise<void>((resolve) => (releaseHeldDownloads = resolve));- let fetchCount = 0;- vi.spyOn(globalThis, "fetch").mockImplementation(async () => {- if (fetchCount++ > 0) await heldDownloads;- return new Response(archiveBytes);- });+ let downloadCount = 0;+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input) =>+ serve(urlPath(input), async () => {+ if (downloadCount++ > 0) await heldDownloads;+ }),+ );vi.spyOn(console, "log").mockImplementation(() => {});vi.spyOn(console, "error").mockImplementation(() => {});- const callers = Array.from({ length: CALLERS }, () => ensureBinary());+ const callers = Array.from({ length: CALLERS }, () => ensureBinary("cb_test"));const firstBinaryPath = await callers[0];- expect(firstBinaryPath).toBe(getBinaryPath());+ expect(firstBinaryPath).toBe(getBinaryPath(VERSION));// Caller 0 would now exec its binary. Keep reading the install while// the held callers download and extract.@@ -757,24 +575,22 @@ describe("concurrent first-run download", () => {observedStates.add(inspectInstall());for (const outcome of await otherCallers) {- expect(outcome).toEqual({ status: "fulfilled", value: getBinaryPath() });+ expect(outcome).toEqual({ status: "fulfilled", value: getBinaryPath(VERSION) });}expect([...observedStates]).toEqual(["complete"]);- expect(fs.readdirSync(cacheDir).filter((name) => !name.startsWith("."))).toEqual([- path.basename(getBinaryDir()),- ]);+ expect(cacheEntries()).toEqual(expectedEntries());},);it.skipIf(process.platform === "win32")("replaces a partial install left by an interrupted extraction",async () => {- vi.spyOn(globalThis, "fetch").mockImplementation(async () => new Response(archiveBytes));+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => serve(urlPath(input)));vi.spyOn(console, "error").mockImplementation(() => {});- fs.mkdirSync(path.join(getBinaryDir(), "lib"), { recursive: true });- fs.writeFileSync(path.join(getBinaryDir(), "lib", "part-0.bin"), "truncated");+ fs.mkdirSync(path.join(getBinaryDir(VERSION), "lib"), { recursive: true });+ fs.writeFileSync(path.join(getBinaryDir(VERSION), "lib", "part-0.bin"), "truncated");- expect(await ensureBinary()).toBe(getBinaryPath());+ expect(await ensureBinary("cb_test")).toBe(getBinaryPath(VERSION));expect(inspectInstall()).toBe("complete");},);@@ -783,12 +599,12 @@ describe("concurrent first-run download", () => {it.skipIf(process.platform === "win32")("first-run download writes nothing to stdout",async () => {- vi.spyOn(globalThis, "fetch").mockImplementation(async () => new Response(archiveBytes));+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => serve(urlPath(input)));vi.spyOn(console, "error").mockImplementation(() => {});const consoleLog = vi.spyOn(console, "log").mockImplementation(() => {});const stdoutWrite = vi.spyOn(process.stdout, "write");- expect(await ensureBinary()).toBe(getBinaryPath());+ expect(await ensureBinary("cb_test")).toBe(getBinaryPath(VERSION));expect(inspectInstall()).toBe("complete");expect(consoleLog).not.toHaveBeenCalled();expect(stdoutWrite).not.toHaveBeenCalled();@@ -799,35 +615,46 @@ describe("concurrent first-run download", () => {"concurrent processes replace a partial install left by an interrupted extraction",async () => {// Enough files that deleting the partial install overlaps other callers.- fs.mkdirSync(path.join(getBinaryDir(), "lib"), { recursive: true });+ fs.mkdirSync(path.join(getBinaryDir(VERSION), "lib"), { recursive: true });for (let i = 0; i < PARTIAL_INSTALL_FILES; i++) {- fs.writeFileSync(path.join(getBinaryDir(), "lib", `part-${i}.bin`), "truncated");+ fs.writeFileSync(path.join(getBinaryDir(VERSION), "lib", `part-${i}.bin`), "truncated");}- // Answer only once every caller is downloading, so all of them find the- // partial install in the way when they move their extraction into place.- const heldResponses: http.ServerResponse[] = [];- const mirror = http.createServer((_request, response) => {- heldResponses.push(response);- if (heldResponses.length === CALLERS) {- for (const heldResponse of heldResponses) heldResponse.end(archiveBytes);- }+ // A local stand-in for the server. The archive is answered only once every+ // caller is downloading, so all of them find the partial install in the+ // way when they move their extraction into place.+ const heldDownloads: Array<() => void> = [];+ const mirror = http.createServer(async (request, response) => {+ const reply = await serve(new URL(request.url!, "http://x").pathname, () =>+ new Promise<void>((resolve) => {+ heldDownloads.push(resolve);+ if (heldDownloads.length === CALLERS) heldDownloads.forEach((release) => release());+ }),+ );+ response.writeHead(reply.status, { "content-type": reply.headers.get("content-type") ?? "" });+ response.end(Buffer.from(await reply.arrayBuffer()));});await new Promise<void>((resolve) => mirror.listen(0, "127.0.0.1", resolve));const mirrorUrl = `http://127.0.0.1:${(mirror.address() as AddressInfo).port}`;// Callers in one process cannot interleave inside extractArchive's// synchronous rename and cleanup, so each caller is a separate process- // running the built dist/ (npm run build first, as CI does).- const downloadModuleUrl = new URL("../dist/download.js", import.meta.url).href;+ // running the built dist/ (npm run build first, as CI does). Each pins+ // the test key and sends every request to the local server.+ const distUrl = (name: string) => new URL(`../dist/${name}`, import.meta.url).href;const callerScript =- `const { ensureBinary } = await import(${JSON.stringify(downloadModuleUrl)});` +- `console.log("BINARY_PATH=" + (await ensureBinary()));`;+ `const cfg = await import(${JSON.stringify(distUrl("config.js"))});` ++ `cfg.BINARY_SIGNING_PUBKEYS.push(${JSON.stringify(testPubB64)});` ++ `const realFetch = globalThis.fetch;` ++ `globalThis.fetch = (input, init) => { const u = new URL(String(input));` ++ ` return realFetch(${JSON.stringify(mirrorUrl)} + u.pathname + u.search, init); };` ++ `const { ensureBinary } = await import(${JSON.stringify(distUrl("download.js"))});` ++ `console.log("BINARY_PATH=" + (await ensureBinary("cb_test")));`;try {const callers = await Promise.allSettled(Array.from({ length: CALLERS }, () =>promisify(execFile)(process.execPath, ["--input-type=module", "-e", callerScript], {- env: { ...process.env, CLOAKBROWSER_DOWNLOAD_URL: mirrorUrl },+ env: process.env,}),),);@@ -836,14 +663,12 @@ describe("concurrent first-run download", () => {? caller.value.stdout.trim().split("\n").at(-1): String(caller.reason),);- expect(outcomes).toEqual(Array(CALLERS).fill(`BINARY_PATH=${getBinaryPath()}`));+ expect(outcomes).toEqual(Array(CALLERS).fill(`BINARY_PATH=${getBinaryPath(VERSION)}`));} finally {mirror.close();}expect(inspectInstall()).toBe("complete");- expect(fs.readdirSync(cacheDir).filter((name) => !name.startsWith("."))).toEqual([- path.basename(getBinaryDir()),- ]);+ expect(cacheEntries()).toEqual(expectedEntries());},);});diff --git a/js/tests/welcome.test.ts b/js/tests/welcome.test.tsindex 779cd3f..7a676dd 100644--- a/js/tests/welcome.test.ts+++ b/js/tests/welcome.test.ts@@ -26,7 +26,7 @@ describe("welcome banner", () => {fs.rmSync(cacheDir, { recursive: true, force: true });});- for (const tier of ["keyless", "free", "pro"]) {+ for (const tier of ["free", "pro"] as const) {it(`${tier} banner is ASCII-only`, () => {showWelcome(tier);const out = errSpy.mock.calls.map((c) => String(c[0] ?? "")).join("\n");diff --git a/tests/conftest.py b/tests/conftest.pyindex b4a284e..09542e1 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -8,14 +8,14 @@ def isolated_cache_dir(request, tmp_path_factory, monkeypatch):"""Keep the suite away from the developer's real ``~/.cloakbrowser``.A ``license.key`` (or a cached Pro version marker) in the real cache dir- resolves the machine as Pro, which flips version-gated defaults such as the- headless ``no_viewport`` shim and inline proxy auth — tests then assert- against whatever the developer happens to have installed. ``monkeypatch``+ would skip the no-key claim flow and point at the developer's cached+ builds — tests then assert against whatever the developer happens to have+ installed. ``monkeypatch``means a test setting its own ``CLOAKBROWSER_CACHE_DIR`` still wins.Real-browser tests (``slow`` / ``real_browser``) opt out and run like a usermachine: the developer's key and latest binary, at a stable path. A fresh- temp cache per test re-downloads the keyless binary every test, and its new+ temp cache per test re-downloads the binary every test, and its newpath re-prompts path-keyed firewalls (LuLu) since the binary is ad-hoc signed."""if request.node.get_closest_marker("slow") or request.node.get_closest_marker("real_browser"):diff --git a/tests/test_cli.py b/tests/test_cli.pyindex aee3499..3dd6986 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -16,14 +16,15 @@ from cloakbrowser.license import LicenseInfo, ProReleaseInfo, SessionSeatsdef _run(args, *, key=None, license_info=None, sessions=None):"""Run cmd_info with license resolution mocked and the real downloaders patched.- key=None -> no license -> free binary.- key set -> validate_license returns license_info (entitled to Pro if valid).+ key=None -> no license key.+ key set -> validate_license returns license_info (entitled if valid).sessions -> the SessionSeats the seat lookup reports (it is mocked out, so anon-quick Pro run never reaches the network). None defaults to aserver-cannot-count result, which keeps unrelated tests offline.- Returns (download_free_mock, download_pro_mock, session_count_mock) so callers- can assert the command never triggers a binary download or an unwanted lookup.+ Returns (claim_mock, download_mock, session_count_mock) so callers can assert+ the command never starts the free-key claim, a binary download or an+ unwanted lookup."""with (patch("cloakbrowser.license.resolve_license_key", return_value=key),@@ -32,7 +33,7 @@ def _run(args, *, key=None, license_info=None, sessions=None):"cloakbrowser.license.get_session_seats",return_value=sessions if sessions is not None else SessionSeats(state="unknown"),) as mock_sessions,- patch("cloakbrowser.download._download_and_extract") as mock_dl_free,+ patch("cloakbrowser.download._claim_free_key") as mock_dl_free,patch("cloakbrowser.download._download_pro_binary") as mock_dl_pro,):cmd_info(args)@@ -47,7 +48,7 @@ def test_info_text_never_downloads(capsys):assert "CloakBrowser diagnostics" in outassert "Python:" in outassert "Platform:" in out- assert "License: Free" in out+ assert "License: none" in outassert "Modules:" in out@@ -105,12 +106,13 @@ def test_info_proxy_resolution_failure_is_reported_not_fatal(capsys):assert "proxy refused" in out-def test_keyless_reports_free_binary(capsys):- """No license key -> the binary section reflects the FREE binary."""- _run(Namespace(quick=True, json=True))+def test_no_key_reports_none(capsys):+ """No license key -> nothing launches without one; info says so."""+ claim, _, _ = _run(Namespace(quick=True, json=True))+ claim.assert_not_called() # info never starts the claim flowdata = json.loads(capsys.readouterr().out)- assert data["binary"]["tier"] == "free"- assert data["license"]["tier"] == "free"+ assert data["binary"]["tier"] == "none"+ assert data["license"]["tier"] == "none"def test_valid_key_reports_pro_binary(capsys):@@ -158,12 +160,12 @@ def test_info_reports_preview_stable_fallback(capsys):assert "Channel: Preview → Stable fallback" in capsys.readouterr().out-def test_invalid_key_falls_back_to_free(capsys):- """A key the server rejects -> not entitled -> free binary, not Pro."""+def test_invalid_key_is_not_entitled(capsys):+ """A key the server rejects -> not entitled."""invalid = LicenseInfo(valid=False, plan="solo", expires=None)_run(Namespace(quick=True, json=True), key="cb_bad", license_info=invalid)data = json.loads(capsys.readouterr().out)- assert data["binary"]["tier"] == "free"+ assert data["binary"]["tier"] == "none"assert data["license"]["tier"] == "invalid"@@ -270,8 +272,8 @@ def test_quick_skips_the_seat_lookup(capsys):assert "sessions" not in data["license"]-def test_free_tier_never_looks_up_seats(capsys):- """A free tier holds no seats — don't ask the server about it."""+def test_no_key_never_looks_up_seats(capsys):+ """No key holds no seats — don't ask the server about it."""_, _, mock_sessions = _run(Namespace(quick=False, json=True))data = json.loads(capsys.readouterr().out)mock_sessions.assert_not_called()@@ -296,14 +298,19 @@ def test_info_json_is_valid(capsys):assert "cloakbrowser.dev" not in out-def test_free_license_shows_upgrade_hint(capsys):+def test_no_key_shows_login_hint(capsys):_run(Namespace(quick=True, json=False))out = capsys.readouterr().out- # Keyless free: invite the free-latest login + point at paid for more sessions.- assert "License: Free (no key)" in out+ assert "License: none" in outassert "cloakbrowser login" in out+++def test_free_key_shows_upgrade_hint(capsys):+ free = LicenseInfo(valid=True, plan="free", expires=None)+ _run(Namespace(quick=True, json=False), key="cb_free", license_info=free)+ out = capsys.readouterr().out+ assert "License: Free (latest binary, 1 concurrent session)" in outassert "For more than one concurrent session" in out- assert "cloakbrowser.dev" in out# ---------------------------------------------------------------------------@@ -460,7 +467,7 @@ def test_launch_section_runs_binary_without_downloading(tmp_path, capsys):with (patch("cloakbrowser.license.resolve_license_key", return_value=None),patch("cloakbrowser.__main__._effective_binary", return_value=fake_binary),- patch("cloakbrowser.download._download_and_extract") as mock_dl_free,+ patch("cloakbrowser.download._claim_free_key") as mock_dl_free,patch("cloakbrowser.download._download_pro_binary") as mock_dl_pro,):cmd_info(Namespace(quick=False, json=True))diff --git a/tests/test_config.py b/tests/test_config.pyindex 12a3dc1..a0b8cc3 100644--- a/tests/test_config.py+++ b/tests/test_config.py@@ -6,15 +6,11 @@ from unittest.mock import patchimport pytestfrom cloakbrowser.config import (- binary_supports_headless_no_viewport,- binary_supports_maximized_window,get_archive_ext,get_archive_name,get_binary_path,get_cache_dir,- get_chromium_version,get_default_stealth_args,- get_fallback_download_url,get_platform_tag,normalize_requested_version,)@@ -29,19 +25,19 @@ class TestGetBinaryPath:def test_linux(self):with patch("cloakbrowser.config.platform.system", return_value="Linux"):path = get_binary_path("145.0.0.0")- assert str(path).endswith("chromium-145.0.0.0/chrome")+ assert str(path).endswith("chromium-145.0.0.0-pro/chrome")def test_darwin(self):with patch("cloakbrowser.config.platform.system", return_value="Darwin"):path = get_binary_path("145.0.0.0")assert str(path).endswith(- "chromium-145.0.0.0/Chromium.app/Contents/MacOS/Chromium"+ "chromium-145.0.0.0-pro/Chromium.app/Contents/MacOS/Chromium")def test_windows(self):with patch("cloakbrowser.config.platform.system", return_value="Windows"):path = get_binary_path("145.0.0.0")- assert str(path).endswith("chromium-145.0.0.0/chrome.exe")+ assert str(path).endswith("chromium-145.0.0.0-pro/chrome.exe")# ---------------------------------------------------------------------------@@ -69,23 +65,6 @@ class TestArchive:assert "cloakbrowser-linux-x64" in name-# ----------------------------------------------------------------------------# Download URLs-# ------------------------------------------------------------------------------class TestFallbackUrl:- def test_github_releases_format(self):- url = get_fallback_download_url("145.0.0.0")- assert "github.com/CloakHQ/cloakbrowser/releases/download" in url- assert "chromium-v145.0.0.0" in url-- def test_default_version(self):- url = get_fallback_download_url()- version = get_chromium_version()- assert f"chromium-v{version}" in url--# ---------------------------------------------------------------------------# Version pin# ---------------------------------------------------------------------------@@ -174,67 +153,3 @@ class TestStealthArgs:# GPU flags removed — binary auto-generates from seed + platformassert not any("fingerprint-gpu-vendor" in a for a in args)assert not any("fingerprint-gpu-renderer" in a for a in args)---# ----------------------------------------------------------------------------# Headless no_viewport version gate-# ------------------------------------------------------------------------------class TestHeadlessNoViewportGate:- """binary_supports_headless_no_viewport() — parity-critical: JS and .NET mirror this.-- Threshold is HEADLESS_NO_VIEWPORT_MIN_VERSION (an unshipped version), so the- resolved-version path is a no-op today; the declared-version path is what these- tests pin.- """-- def test_declared_below_threshold_off(self):- # Current live Pro version — one build below the threshold => feature OFF.- assert binary_supports_headless_no_viewport(browser_version="148.0.7778.215.3") is False-- def test_declared_at_threshold_on(self):- assert binary_supports_headless_no_viewport(browser_version="148.0.7778.215.4") is True-- def test_declared_above_threshold_on(self):- assert binary_supports_headless_no_viewport(browser_version="149.0.0.0") is True-- def test_declared_wins_over_local_override(self):- # An explicit version asserts the binary even under CLOAKBROWSER_BINARY_PATH.- with patch.dict(os.environ, {"CLOAKBROWSER_BINARY_PATH": "/fake/chrome"}):- assert binary_supports_headless_no_viewport(browser_version="149.0.0.0") is True-- def test_local_override_without_declared_off(self):- # Unknown-version override => stay on the safe fixed-viewport path.- with patch.dict(os.environ, {"CLOAKBROWSER_BINARY_PATH": "/fake/chrome"}):- assert binary_supports_headless_no_viewport() is False-- def test_resolved_free_version_off(self):- # No key, no override, no declared version => free version, below threshold.- with patch.dict(os.environ, {}, clear=False):- os.environ.pop("CLOAKBROWSER_BINARY_PATH", None)- os.environ.pop("CLOAKBROWSER_LICENSE_KEY", None)- os.environ.pop("CLOAKBROWSER_VERSION", None)- assert binary_supports_headless_no_viewport() is False---class TestMaximizedWindowGate:- """binary_supports_maximized_window() — parity-critical: JS and .NET mirror this.-- Shares HEADLESS_NO_VIEWPORT_MIN_VERSION today, so it tracks the same threshold- as the no_viewport gate: below it, auto --start-maximized would make headless- report outerWidth < innerWidth (a bot tell), so the flag must stay off.- """-- def test_declared_below_threshold_off(self):- assert binary_supports_maximized_window(browser_version="148.0.7778.215.3") is False-- def test_declared_at_threshold_on(self):- assert binary_supports_maximized_window(browser_version="148.0.7778.215.4") is True-- def test_declared_above_threshold_on(self):- assert binary_supports_maximized_window(browser_version="149.0.0.0") is True-- def test_local_override_without_declared_off(self):- with patch.dict(os.environ, {"CLOAKBROWSER_BINARY_PATH": "/fake/chrome"}):- assert binary_supports_maximized_window() is Falsediff --git a/tests/test_extract.py b/tests/test_extract.pyindex 74cfb28..02f1c07 100644--- a/tests/test_extract.py+++ b/tests/test_extract.py@@ -5,15 +5,16 @@ import osimport platformimport queueimport shutil-import statimport tarfileimport threadingimport zipfile+from pathlib import Pathimport pytestimport cloakbrowser.download as download-from cloakbrowser.config import get_binary_dir, get_binary_path+import cloakbrowser.license as license_mod+from cloakbrowser.config import get_binary_dir, get_binary_path, get_platform_tagfrom cloakbrowser.download import (_extract_tar,_extract_zip,@@ -182,11 +183,13 @@ class TestConcurrentFirstRun:CALLERS = 4FILLER_FILES = 300BINARY_BYTES = b"#!/bin/sh\necho fake-chrome\n"+ VERSION = "155.0.8059.39.2"+ KEY = "cb_test"def _create_platform_archive(self, tmp_path):"""An archive with this platform's binary layout plus enough fillerfiles that an extraction spans many thread switches."""- binary_rel_path = get_binary_path().relative_to(get_binary_dir()).as_posix()+ binary_rel_path = get_binary_path(self.VERSION).relative_to(get_binary_dir(self.VERSION)).as_posix()members = {binary_rel_path: self.BINARY_BYTES}for i in range(self.FILLER_FILES):members[f"lib/part-{i}.bin"] = bytes([i % 256]) * 16 * 1024@@ -203,30 +206,48 @@ class TestConcurrentFirstRun:"""Reads the install the way a launch would. Returns what is wrongwith it, or "complete"."""try:- binary_path = get_binary_path()+ binary_path = get_binary_path(self.VERSION)if binary_path.read_bytes() != self.BINARY_BYTES:return "binary content differs"if not _is_executable(binary_path):return "binary not executable"- filler_count = len(os.listdir(get_binary_dir() / "lib"))+ filler_count = len(os.listdir(get_binary_dir(self.VERSION) / "lib"))if filler_count != self.FILLER_FILES:return f"lib has {filler_count} files"return "complete"except OSError as err:return type(err).__name__- def _use_local_mirror(self, cache_dir, monkeypatch):+ def _use_keyed_install(self, cache_dir, monkeypatch):+ """Route ensure_binary(KEY) through the real keyed download + extraction,+ with only the network edges stubbed (license check, latest lookup,+ signature fetch, wrapper update check)."""monkeypatch.setenv("CLOAKBROWSER_CACHE_DIR", str(cache_dir))- monkeypatch.setenv("CLOAKBROWSER_DOWNLOAD_URL", "https://mirror.invalid")- monkeypatch.setenv("CLOAKBROWSER_SKIP_CHECKSUM", "true")- for name in ("CLOAKBROWSER_LICENSE_KEY", "CLOAKBROWSER_BINARY_PATH", "CLOAKBROWSER_VERSION"):+ for name in (+ "CLOAKBROWSER_LICENSE_KEY",+ "CLOAKBROWSER_BINARY_PATH",+ "CLOAKBROWSER_VERSION",+ "CLOAKBROWSER_RELEASE_CHANNEL",+ "CLOAKBROWSER_AUTO_UPDATE",+ ):monkeypatch.delenv(name, raising=False)+ monkeypatch.setattr(+ license_mod,+ "validate_license",+ lambda key: license_mod.LicenseInfo(valid=True, plan="business", expires=None),+ )+ monkeypatch.setattr(license_mod, "get_pro_latest_version", lambda channel=None: self.VERSION)+ monkeypatch.setattr(download, "_verify_pro_download", lambda path, version: None)+ monkeypatch.setattr(download, "_maybe_trigger_update_check", lambda: None)++ def _expected_cache_entries(self):+ return sorted([get_binary_dir(self.VERSION).name, f"latest_pro_version_{get_platform_tag()}"])@pytest.mark.skipif(platform.system() == "Windows", reason="POSIX exec semantics")def test_install_stays_complete_while_other_callers_finish(self, tmp_path, monkeypatch):archive = self._create_platform_archive(tmp_path)cache_dir = tmp_path / "cache"- self._use_local_mirror(cache_dir, monkeypatch)+ self._use_keyed_install(cache_dir, monkeypatch)# One caller downloads at once. The others have already seen an empty# cache but their downloads are held until the first has returned,@@ -245,7 +266,7 @@ class TestConcurrentFirstRun:def run_caller():try:- caller_outcomes.put(("returned", download.ensure_binary()))+ caller_outcomes.put(("returned", download.ensure_binary(license_key=self.KEY)))except Exception as err:caller_outcomes.put(("raised", repr(err)))@@ -254,7 +275,7 @@ class TestConcurrentFirstRun:caller.start()outcomes = [caller_outcomes.get(timeout=60)]- assert outcomes[0] == ("returned", str(get_binary_path()))+ assert outcomes[0] == ("returned", str(get_binary_path(self.VERSION)))# The first caller would now exec its binary. Keep reading the install# while the held callers download and extract.@@ -266,30 +287,30 @@ class TestConcurrentFirstRun:while not caller_outcomes.empty():outcomes.append(caller_outcomes.get())- assert outcomes == [("returned", str(get_binary_path()))] * self.CALLERS+ assert outcomes == [("returned", str(get_binary_path(self.VERSION)))] * self.CALLERSassert observed_states == {"complete"}- assert [p.name for p in cache_dir.iterdir() if not p.name.startswith(".")] == [- get_binary_dir().name- ]+ assert sorted(+ p.name for p in cache_dir.iterdir() if not p.name.startswith(".")+ ) == self._expected_cache_entries()@pytest.mark.skipif(platform.system() == "Windows", reason="POSIX exec semantics")def test_replaces_partial_install_left_by_interrupted_extraction(self, tmp_path, monkeypatch):archive = self._create_platform_archive(tmp_path)- self._use_local_mirror(tmp_path / "cache", monkeypatch)+ self._use_keyed_install(tmp_path / "cache", monkeypatch)monkeypatch.setattr(download, "_download_file", lambda url, dest, headers=None: shutil.copyfile(archive, dest))- (get_binary_dir() / "lib").mkdir(parents=True)- (get_binary_dir() / "lib" / "part-0.bin").write_bytes(b"truncated")+ (get_binary_dir(self.VERSION) / "lib").mkdir(parents=True)+ (get_binary_dir(self.VERSION) / "lib" / "part-0.bin").write_bytes(b"truncated")- assert download.ensure_binary() == str(get_binary_path())+ assert download.ensure_binary(license_key=self.KEY) == str(get_binary_path(self.VERSION))assert self._inspect_install() == "complete"@pytest.mark.skipif(platform.system() == "Windows", reason="POSIX exec semantics")def test_concurrent_callers_replace_partial_install(self, tmp_path, monkeypatch):archive = self._create_platform_archive(tmp_path)cache_dir = tmp_path / "cache"- self._use_local_mirror(cache_dir, monkeypatch)+ self._use_keyed_install(cache_dir, monkeypatch)# Every caller downloads at the same moment, so all of them find the# partial install in the way when they move their extraction into place.@@ -300,15 +321,15 @@ class TestConcurrentFirstRun:shutil.copyfile(archive, dest)monkeypatch.setattr(download, "_download_file", fake_download_file)- (get_binary_dir() / "lib").mkdir(parents=True)+ (get_binary_dir(self.VERSION) / "lib").mkdir(parents=True)for i in range(self.FILLER_FILES):- (get_binary_dir() / "lib" / f"part-{i}.bin").write_bytes(b"truncated")+ (get_binary_dir(self.VERSION) / "lib" / f"part-{i}.bin").write_bytes(b"truncated")caller_outcomes: queue.Queue = queue.Queue()def run_caller():try:- caller_outcomes.put(("returned", download.ensure_binary()))+ caller_outcomes.put(("returned", download.ensure_binary(license_key=self.KEY)))except Exception as err:caller_outcomes.put(("raised", repr(err)))@@ -319,8 +340,8 @@ class TestConcurrentFirstRun:caller.join(timeout=60)outcomes = [caller_outcomes.get_nowait() for _ in range(caller_outcomes.qsize())]- assert outcomes == [("returned", str(get_binary_path()))] * self.CALLERS+ assert outcomes == [("returned", str(get_binary_path(self.VERSION)))] * self.CALLERSassert self._inspect_install() == "complete"- assert [p.name for p in cache_dir.iterdir() if not p.name.startswith(".")] == [- get_binary_dir().name- ]+ assert sorted(+ p.name for p in cache_dir.iterdir() if not p.name.startswith(".")+ ) == self._expected_cache_entries()diff --git a/tests/test_free_claim.py b/tests/test_free_claim.pynew file mode 100644index 0000000..3892c0d--- /dev/null+++ b/tests/test_free_claim.py@@ -0,0 +1,316 @@+"""Free-key claim flow: claim code, key save, and the no-key launch path."""+import os+import stat+import threading+import time+from unittest import mock++import httpx+import pytest++from cloakbrowser import download, license as lic+from cloakbrowser.license import CloakBrowserLicenseError, LicenseInfo+++def cache(tmp_path, monkeypatch):+ monkeypatch.setenv("CLOAKBROWSER_CACHE_DIR", str(tmp_path))+ monkeypatch.delenv("CLOAKBROWSER_LICENSE_KEY", raising=False)+ monkeypatch.delenv("CLOAKBROWSER_BINARY_PATH", raising=False)+ monkeypatch.setattr(download, "_claim_poll_started", False)+ return tmp_path+++def _mode(path):+ return stat.S_IMODE(path.stat().st_mode)+++# ── claim code ──────────────────────────────────────────────────────────────+++def test_claim_code_is_reused_and_private(cache):+ code = lic.get_claim_code()+ assert lic.CLAIM_CODE_RE.fullmatch(code)+ assert lic.get_claim_code() == code+ assert _mode(cache / ".free_claim") == 0o600+++def test_claim_code_rotates_after_seven_days(cache):+ old = lic.get_claim_code()+ stale = time.time() - lic.CLAIM_MAX_AGE - 1+ os.utime(cache / ".free_claim", (stale, stale))+ assert lic.get_claim_code() != old+++def test_parallel_workers_share_one_code(cache):+ """Concurrent first launches must print the same link."""+ codes, start = [], threading.Barrier(8)++ def worker():+ start.wait()+ codes.append(lic.get_claim_code())++ threads = [threading.Thread(target=worker) for _ in range(8)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()+ assert len(set(codes)) == 1+++# ── key save ────────────────────────────────────────────────────────────────+++def test_save_key_is_private_and_retires_claim(cache):+ lic.get_claim_code()+ assert lic.save_license_key("cb_abc") is True+ assert (cache / "license.key").read_text() == "cb_abc\n"+ assert _mode(cache / "license.key") == 0o600+ assert not (cache / ".free_claim").exists()+++def test_save_key_rejects_non_keys(cache):+ with pytest.raises(ValueError):+ lic.save_license_key("<script>")+ assert not (cache / "license.key").exists()+++def test_poller_never_overwrites_an_existing_key(cache):+ lic.save_license_key("cb_mine")+ assert lic.save_license_key("cb_claimed", overwrite=False) is False+ assert (cache / "license.key").read_text() == "cb_mine\n"+++# ── check_claim ─────────────────────────────────────────────────────────────+++def _resp(status, payload):+ return httpx.Response(status, json=payload, request=httpx.Request("POST", lic.CLAIM_URL))+++ "payload, expected",+ [+ ({"status": "pending"}, None),+ ({"status": "ready", "license_key": "cb_ok"}, "cb_ok"),+ ({"status": "ready", "license_key": "bad key"}, None), # trust boundary+ ],+)+def test_check_claim_answers(payload, expected):+ with mock.patch("httpx.post", return_value=_resp(200, payload)) as post:+ assert lic.check_claim("c" * 32) == expected+ # The code is a bearer secret: body, never the URL.+ assert post.call_args.args[0] == lic.CLAIM_URL+ assert post.call_args.kwargs["json"] == {"code": "c" * 32}++[email protected]("payload", [None, [], "ready", 7])+def test_check_claim_non_object_json_is_pending(payload):+ with mock.patch("httpx.post", return_value=_resp(200, payload)):+ assert lic.check_claim("c" * 32) is None+++def test_ready_claim_is_retired_even_when_a_key_is_kept(cache):+ """A ready claim must not linger: after `logout` it would re-save the key."""+ lic.save_license_key("cb_mine")+ lic.get_claim_code()+ with mock.patch.object(lic, "check_claim", return_value="cb_claimed"):+ assert lic.poll_claim("c" * 32, overwrite=False) is None # nothing saved+ assert (cache / "license.key").read_text() == "cb_mine\n"+ assert not (cache / ".free_claim").exists()+++def test_background_poll_starts_once_under_concurrency(cache, monkeypatch):+ started, gate = [], threading.Barrier(8)++ def go():+ gate.wait()+ download._start_claim_poll("c" * 32)++ # Real threads race the check; the poller thread itself is mocked.+ real = threading.Thread+ with mock.patch.object(download.threading, "Thread", side_effect=lambda **kw: started.append(1) or mock.Mock()):+ ts = [real(target=go) for _ in range(8)]+ for t in ts:+ t.start()+ for t in ts:+ t.join()+ assert len(started) == 1++[email protected]("env, expected", [({}, False), ({"DISPLAY": ":0"}, True), ({"WAYLAND_DISPLAY": "w"}, True)])+def test_no_browser_open_without_display_on_linux(monkeypatch, env, expected):+ monkeypatch.setattr(download.sys, "platform", "linux")+ monkeypatch.delenv("DISPLAY", raising=False)+ monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)+ for k, v in env.items():+ monkeypatch.setenv(k, v)+ assert download._has_display() is expected+++def test_check_claim_network_error_is_pending():+ with mock.patch("httpx.post", side_effect=httpx.ConnectError("down")):+ assert lic.check_claim("c" * 32) is None+++# ── ensure_binary with no key ───────────────────────────────────────────────+++def _valid_launch(monkeypatch):+ seen = {}++ def fake_validate(key):+ seen["key"] = key+ return LicenseInfo(valid=True, plan="free", expires=None)++ monkeypatch.setattr(lic, "validate_license", fake_validate)+ monkeypatch.setattr(download, "_ensure_pro_binary", lambda key, **kw: "/bin/chrome")+ monkeypatch.setattr(download, "_maybe_trigger_update_check", lambda: None)+ return seen+++def test_no_key_without_terminal_raises_with_link_and_polls(cache, monkeypatch, capsys):+ monkeypatch.setattr(lic, "check_claim", lambda code: None)+ monkeypatch.setattr(download, "_isatty", lambda s: False)+ with mock.patch.object(download, "_start_claim_poll") as poll:+ with pytest.raises(CloakBrowserLicenseError, match=r"cloakbrowser\.dev/#claim="):+ download.ensure_binary()+ poll.assert_called_once()+ assert "#claim=" in capsys.readouterr().err # stderr only: MCP owns stdout+++def test_no_key_off_main_thread_never_waits(cache, monkeypatch):+ """launch_async runs ensure_binary on a worker thread Ctrl+C can't reach."""+ monkeypatch.setattr(lic, "check_claim", lambda code: None)+ monkeypatch.setattr(download, "_isatty", lambda s: True)+ errors = []++ def run():+ with mock.patch.object(download, "_start_claim_poll"):+ try:+ download.ensure_binary()+ except CloakBrowserLicenseError as e:+ errors.append(e)++ t = threading.Thread(target=run)+ t.start()+ t.join(timeout=5)+ assert not t.is_alive() and len(errors) == 1+++def test_no_key_in_terminal_menu_default_gets_free_key(cache, monkeypatch, capsys):+ answers = iter([None, None, "cb_claimed"]) # first check, then two polls+ monkeypatch.setattr(lic, "check_claim", lambda code: next(answers))+ monkeypatch.setattr(lic.time, "sleep", lambda s: None)+ monkeypatch.setattr(download, "_isatty", lambda s: True)+ seen = _valid_launch(monkeypatch)+ with mock.patch("builtins.input", return_value="") as ask, \+ mock.patch("webbrowser.open", return_value=True) as opened:+ assert download.ensure_binary() == "/bin/chrome"+ assert ask.call_count == 1 # Enter = option 1+ assert opened.call_args.args[0].startswith(lic.FREE_CLAIM_LINK)+ assert seen["key"] == "cb_claimed"+ assert (cache / "license.key").read_text() == "cb_claimed\n"+ err = capsys.readouterr().err+ assert "Welcome to CloakBrowser" in err and "1) Get a free key" in err+ # The menu was the welcome: the regular banner must not repeat this launch.+ download._show_welcome("free")+ assert capsys.readouterr().err == ""+++def test_no_key_in_terminal_menu_paste_key(cache, monkeypatch):+ monkeypatch.setattr(lic, "check_claim", lambda code: None)+ monkeypatch.setattr(download, "_isatty", lambda s: True)+ seen = _valid_launch(monkeypatch)+ # 2, then a non-key (asked again), then the real key.+ with mock.patch("builtins.input", side_effect=["2", "hello", "cb_mine"]), \+ mock.patch("webbrowser.open") as opened:+ assert download.ensure_binary() == "/bin/chrome"+ opened.assert_not_called()+ assert seen["key"] == "cb_mine"+ assert (cache / "license.key").read_text() == "cb_mine\n"+++def test_menu_rejects_invalid_pasted_key(cache, monkeypatch):+ monkeypatch.setattr(+ lic, "validate_license",+ lambda key: LicenseInfo(valid=key == "cb_good", plan="free", expires=None),+ )+ with mock.patch("builtins.input", side_effect=["7", "2", "cb_bad", "cb_good"]):+ assert download.prompt_license_key() == "cb_good"+ assert (cache / "license.key").read_text() == "cb_good\n"+++def test_check_claim_has_key_raises_and_retires_code(cache):+ lic.get_claim_code()+ with mock.patch("httpx.post", return_value=_resp(200, {"status": "has_key"})):+ with pytest.raises(lic.FreeKeyAlreadyHeld):+ lic.check_claim("c" * 32)+ assert not (cache / ".free_claim").exists()+++def test_menu_email_already_has_key_switches_to_paste(cache, monkeypatch, capsys):+ """The server never sends an existing key to a claim: stop waiting, ask to paste."""+ def claim(code):+ raise lic.FreeKeyAlreadyHeld++ monkeypatch.setattr(lic, "check_claim", claim)+ monkeypatch.setattr(+ lic, "validate_license", lambda key: LicenseInfo(valid=True, plan="free", expires=None)+ )+ with mock.patch("builtins.input", side_effect=["1", "cb_old"]), \+ mock.patch("webbrowser.open"):+ assert download.prompt_license_key() == "cb_old"+ assert "already has a free key" in capsys.readouterr().err+ assert (cache / "license.key").read_text() == "cb_old\n"+++def test_no_terminal_email_already_has_key_says_so(cache, monkeypatch):+ def claim(code):+ raise lic.FreeKeyAlreadyHeld++ monkeypatch.setattr(lic, "check_claim", claim)+ monkeypatch.setattr(download, "_isatty", lambda s: False)+ with pytest.raises(CloakBrowserLicenseError, match="already has a free key"):+ download.ensure_binary()+++def test_ctrl_c_at_menu_exits_quietly(cache, monkeypatch):+ monkeypatch.setattr(lic, "check_claim", lambda code: None)+ monkeypatch.setattr(download, "_isatty", lambda s: True)+ with mock.patch("builtins.input", side_effect=KeyboardInterrupt):+ with pytest.raises(SystemExit) as e:+ download.ensure_binary()+ assert e.value.code == 130+++def test_menu_eof_falls_back_to_link_error(cache, monkeypatch):+ monkeypatch.setattr(lic, "check_claim", lambda code: None)+ monkeypatch.setattr(download, "_isatty", lambda s: True)+ with mock.patch("builtins.input", side_effect=EOFError), \+ mock.patch.object(download, "_start_claim_poll"):+ with pytest.raises(CloakBrowserLicenseError, match=r"#claim="):+ download.ensure_binary()+++def test_key_confirmed_since_last_launch_is_picked_up(cache, monkeypatch, capsys):+ monkeypatch.setattr(lic, "check_claim", lambda code: "cb_ready")+ seen = _valid_launch(monkeypatch)+ assert download.ensure_binary() == "/bin/chrome"+ assert seen["key"] == "cb_ready"+ assert "#claim=" not in capsys.readouterr().err # no link once it's ready+++def test_any_key_source_skips_the_claim(cache, monkeypatch):+ monkeypatch.setenv("CLOAKBROWSER_LICENSE_KEY", "cb_env")+ seen = _valid_launch(monkeypatch)+ with mock.patch.object(download, "_claim_free_key", side_effect=AssertionError):+ download.ensure_binary()+ assert seen["key"] == "cb_env"+++def test_background_poll_runs_once_per_process(cache, monkeypatch):+ with mock.patch("threading.Thread") as thread:+ download._start_claim_poll("c" * 32)+ download._start_claim_poll("c" * 32)+ assert thread.call_count == 1diff --git a/tests/test_free_version_pin.py b/tests/test_free_version_pin.pyindex 2ef8136..880ed70 100644--- a/tests/test_free_version_pin.py+++ b/tests/test_free_version_pin.py@@ -7,7 +7,6 @@ from cloakbrowser.license import LicenseInfodef _run(monkeypatch, plan):- monkeypatch.delenv("CLOAKBROWSER_DOWNLOAD_URL", raising=False)monkeypatch.setattr(dl, "get_local_binary_override", lambda: None)monkeypatch.setattr(dl, "normalize_requested_version", lambda v: v)captured = {}diff --git a/tests/test_launch.py b/tests/test_launch.pyindex 8ae9675..f7ff3a4 100644--- a/tests/test_launch.py+++ b/tests/test_launch.py@@ -8,7 +8,6 @@ from cloakbrowser import (launch_persistent_context,binary_info,)-from cloakbrowser.config import get_chromium_versionpytestmark = pytest.mark.real_browser@@ -33,17 +32,16 @@ def test_removed_backend_kwarg_raises(env, monkeypatch):def test_binary_info(tmp_path, monkeypatch):"""binary_info() returns expected structure.- Isolate the cache dir: with no cached Pro binary present, binary_info reports- the free base version. (Without isolation this reads the developer's real- ~/.cloakbrowser, which may hold a cached Pro build and flip the version.)+ Isolate the cache dir: with nothing cached, no version is known yet.+ (Without isolation this reads the developer's real ~/.cloakbrowser.)"""monkeypatch.setenv("CLOAKBROWSER_CACHE_DIR", str(tmp_path))info = binary_info()- assert "version" in infoassert "platform" in info- assert "binary_path" in info- assert "installed" in info- assert info["version"] == get_chromium_version()+ assert "download_url" in info+ assert info["version"] is None+ assert info["binary_path"] is None+ assert info["installed"] is Falsedef test_launch_and_close():diff --git a/tests/test_launch_context.py b/tests/test_launch_context.pyindex 8f244ee..b92fd74 100644--- a/tests/test_launch_context.py+++ b/tests/test_launch_context.py@@ -4,9 +4,6 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest-from cloakbrowser.config import DEFAULT_VIEWPORT--# All tests mock launch() to avoid needing a binary.# launch_context() calls launch() internally, then browser.new_context().@@ -22,15 +19,16 @@ def _make_mock_browser():@patch("cloakbrowser.browser.ensure_binary", return_value="/fake/chrome")@patch("cloakbrowser.browser.launch")def test_default_viewport(mock_launch, _mock_bin):- """DEFAULT_VIEWPORT applied when no viewport given."""+ """No emulated viewport when none is given, headless included."""browser, context = _make_mock_browser()mock_launch.return_value = browserfrom cloakbrowser.browser import launch_contextlaunch_context()- ctx_kwargs = browser.new_context.call_args- assert ctx_kwargs[1]["viewport"] == DEFAULT_VIEWPORT+ ctx_kwargs = browser.new_context.call_args[1]+ assert ctx_kwargs.get("no_viewport") is True+ assert "viewport" not in ctx_kwargs@patch("cloakbrowser.browser.ensure_binary", return_value="/fake/chrome")@@ -125,7 +123,7 @@ def test_conflicting_viewport_kwargs_deduped(mock_launch, _mock_bin):@patch("cloakbrowser.browser.ensure_binary", return_value="/fake/chrome")@patch("cloakbrowser.browser.launch")def test_custom_viewport(mock_launch, _mock_bin):- """Custom viewport overrides DEFAULT_VIEWPORT."""+ """Custom viewport is honored."""browser, context = _make_mock_browser()mock_launch.return_value = browser@@ -394,15 +392,16 @@ async def test_async_storage_state_forwarded(mock_launch_async, _mock_bin):@patch("cloakbrowser.browser.ensure_binary", return_value="/fake/chrome")@patch("cloakbrowser.browser.launch_async")async def test_async_default_viewport(mock_launch_async, _mock_bin):- """DEFAULT_VIEWPORT applied when no viewport given (async)."""+ """No emulated viewport when none is given (async)."""browser, context = _make_mock_async_browser()mock_launch_async.return_value = browserfrom cloakbrowser.browser import launch_context_asyncawait launch_context_async()- ctx_kwargs = browser.new_context.call_args- assert ctx_kwargs[1]["viewport"] == DEFAULT_VIEWPORT+ ctx_kwargs = browser.new_context.call_args[1]+ assert ctx_kwargs.get("no_viewport") is True+ assert "viewport" not in ctx_kwargs@pytest.mark.asynciodiff --git a/tests/test_license.py b/tests/test_license.pyindex 289601a..0060dfa 100644--- a/tests/test_license.py+++ b/tests/test_license.py@@ -682,22 +682,11 @@ class TestGetSessionSeats:class TestConfigPro:def test_binary_dir_pro_suffix(self, tmp_path):+ # Kept as "-pro": existing caches stay valid across the upgrade.from cloakbrowser.config import get_binary_dirwith patch.dict(os.environ, {"CLOAKBROWSER_CACHE_DIR": str(tmp_path)}):- normal = get_binary_dir("147.0.0.0")- pro = get_binary_dir("147.0.0.0", pro=True)-- assert str(normal).endswith("chromium-147.0.0.0")- assert str(pro).endswith("chromium-147.0.0.0-pro")-- def test_binary_dir_default_no_suffix(self, tmp_path):- from cloakbrowser.config import get_binary_dir-- with patch.dict(os.environ, {"CLOAKBROWSER_CACHE_DIR": str(tmp_path)}):- normal = get_binary_dir("147.0.0.0")-- assert not str(normal).endswith("-pro")+ assert str(get_binary_dir("147.0.0.0")).endswith("chromium-147.0.0.0-pro")def test_effective_version_pro_marker(self, tmp_path):from cloakbrowser.config import get_effective_version, get_platform_tag@@ -709,12 +698,12 @@ class TestConfigPro:# Create the binary so effective version returns itfrom cloakbrowser.config import get_binary_path- bp = get_binary_path("147.0.5555.1", pro=True)+ bp = get_binary_path("147.0.5555.1")bp.parent.mkdir(parents=True, exist_ok=True)bp.write_text("fake")- bp.chmod(0o755) # get_effective_version(pro) requires an executable binary+ bp.chmod(0o755) # get_effective_version requires an executable binary- version = get_effective_version(pro=True)+ version = get_effective_version()assert version == "147.0.5555.1"@@ -723,10 +712,10 @@ class TestConfigPro:class TestBinaryInfoTier:- """binary_info() reports tier from the binary actually on disk — NOT from a- cached license, which can disagree with what's installed or the active key."""+ """binary_info() reports the build actually on disk — NOT a cached license,+ which can disagree with what's installed."""- def test_free_when_no_pro_binary_even_if_license_cached(self, tmp_path):+ def test_nothing_installed_even_if_license_cached(self, tmp_path):from cloakbrowser.download import binary_infowith patch.dict(os.environ, {"CLOAKBROWSER_CACHE_DIR": str(tmp_path)}, clear=False):@@ -736,25 +725,26 @@ class TestBinaryInfoTier:"valid": True, "plan": "solo", "expires": None,"validated_at": time.time(),}))- # ...but no Pro binary is on disk → must report free, not pro.+ # ...but no binary is on disk.info = binary_info()- assert info["tier"] == "free"+ assert info["installed"] is False+ assert info["version"] is None- def test_pro_when_pro_binary_installed(self, tmp_path):+ def test_reports_installed_binary(self, tmp_path):from cloakbrowser.config import get_binary_path, get_platform_tagfrom cloakbrowser.download import binary_infowith patch.dict(os.environ, {"CLOAKBROWSER_CACHE_DIR": str(tmp_path)}, clear=False):tag = get_platform_tag()(tmp_path / f"latest_pro_version_{tag}").write_text("147.0.5555.1")- bp = get_binary_path("147.0.5555.1", pro=True)+ bp = get_binary_path("147.0.5555.1")bp.parent.mkdir(parents=True, exist_ok=True)bp.write_text("fake")bp.chmod(0o755)info = binary_info()- assert info["tier"] == "pro"+ assert info["installed"] is Trueassert info["version"] == "147.0.5555.1"def test_preview_pro_download_url_carries_channel(self, tmp_path):@@ -767,7 +757,7 @@ class TestBinaryInfoTier:# only the reported download URL should differ by channel.(tmp_path / f"latest_pro_version_preview_{tag}").write_text("151.0.7900.10.1")(tmp_path / f"latest_pro_version_{tag}").write_text("151.0.7900.10.1")- bp = get_binary_path("151.0.7900.10.1", pro=True)+ bp = get_binary_path("151.0.7900.10.1")bp.parent.mkdir(parents=True, exist_ok=True)bp.write_text("fake")bp.chmod(0o755)@@ -783,89 +773,84 @@ class TestBinaryInfoTier:class TestEnsureBinaryProRouting:- """A valid-license user is NEVER silently downgraded to the free binary. Both- a tampering signal (verification failure) and a transient failure- (network/server) surface a clear error — they differ only in the message:- tampering is re-raised verbatim (security, no 'retry'); transient is rewrapped- as an actionable 'Pro binary unavailable, retry' error carrying the cause."""+ """A supplied key never falls into the no-key claim flow. Both a tampering+ signal (verification failure) and a transient failure (network/server)+ surface a clear error — they differ only in the message: tampering is+ re-raised verbatim (security, no 'retry'); transient is rewrapped as an+ actionable 'binary unavailable, retry' error carrying the cause."""def test_verification_failure_propagates_verbatim(self):"""A BinaryVerificationError must surface verbatim — never reach free."""- with patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}, clear=False), \- patch("cloakbrowser.download.get_local_binary_override", return_value=None), \+ with patch("cloakbrowser.download.get_local_binary_override", return_value=None), \patch("cloakbrowser.license.resolve_license_key", return_value="cb_x"), \patch("cloakbrowser.license.validate_license",return_value=LicenseInfo(valid=True, plan="solo", expires=None)), \patch("cloakbrowser.download._ensure_pro_binary",side_effect=BinaryVerificationError("bad signature")), \- patch("cloakbrowser.download.check_platform_available",- side_effect=AssertionError("MUST NOT reach the free-tier path")):+ patch("cloakbrowser.download._claim_free_key",+ side_effect=AssertionError("MUST NOT reach the no-key path")):with pytest.raises(BinaryVerificationError, match="bad signature"):ensure_binary("cb_x")- def test_transient_failure_hard_errors_not_free(self):+ def test_transient_failure_hard_errors(self):"""A transient Pro failure must surface a clear, actionable error carrying- the underlying cause — NOT silently download the free binary."""- with patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}, clear=False), \- patch("cloakbrowser.download.get_local_binary_override", return_value=None), \+ the underlying cause."""+ with patch("cloakbrowser.download.get_local_binary_override", return_value=None), \patch("cloakbrowser.license.resolve_license_key", return_value="cb_x"), \patch("cloakbrowser.license.validate_license",return_value=LicenseInfo(valid=True, plan="solo", expires=None)), \patch("cloakbrowser.download._ensure_pro_binary",side_effect=RuntimeError("network blip")), \- patch("cloakbrowser.download.check_platform_available",- side_effect=AssertionError("MUST NOT reach the free-tier path")):- with pytest.raises(RuntimeError, match="Pro binary unavailable: network blip"):+ patch("cloakbrowser.download._claim_free_key",+ side_effect=AssertionError("MUST NOT reach the no-key path")):+ with pytest.raises(RuntimeError, match="binary unavailable: network blip"):ensure_binary("cb_x")- def test_macos_pro_404_hard_errors_not_free(self):+ def test_macos_pro_404_hard_errors(self):"""macOS now has a Pro binary, so a 404 on the Pro download is a real error- and must hard-fail like every other platform — NOT silently fall back to the- free binary (the v0.4.2 darwin-404→free stopgap was reverted in v0.4.3)."""+ and must hard-fail like every other platform (the v0.4.2 darwin-404 stopgap+ was reverted in v0.4.3)."""import httpxreq = httpx.Request("GET", "https://example.com/download")not_found = httpx.HTTPStatusError("404 Not Found", request=req, response=httpx.Response(404, request=req))- with patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}, clear=False), \- patch("cloakbrowser.download.get_local_binary_override", return_value=None), \+ with patch("cloakbrowser.download.get_local_binary_override", return_value=None), \patch("cloakbrowser.download.get_platform_tag", return_value="darwin-x64"), \patch("cloakbrowser.license.resolve_license_key", return_value="cb_x"), \patch("cloakbrowser.license.validate_license",return_value=LicenseInfo(valid=True, plan="solo", expires=None)), \patch("cloakbrowser.download._ensure_pro_binary", side_effect=not_found), \- patch("cloakbrowser.download.check_platform_available",- side_effect=AssertionError("MUST NOT reach the free-tier path on macOS")):- with pytest.raises(RuntimeError, match="Pro binary unavailable"):+ patch("cloakbrowser.download._claim_free_key",+ side_effect=AssertionError("MUST NOT reach the no-key path")):+ with pytest.raises(RuntimeError, match="binary unavailable"):ensure_binary("cb_x")- def test_invalid_key_aborts_not_free(self):+ def test_invalid_key_aborts(self):"""A supplied key the server rejects (valid=False) must abort with a clear- license error — NOT silently downgrade to the free binary."""- with patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}, clear=False), \- patch("cloakbrowser.download.get_local_binary_override", return_value=None), \+ license error."""+ with patch("cloakbrowser.download.get_local_binary_override", return_value=None), \patch("cloakbrowser.license.resolve_license_key", return_value="cb_bad"), \patch("cloakbrowser.license.validate_license",return_value=LicenseInfo(valid=False, plan="solo", expires=None)), \patch("cloakbrowser.download._ensure_pro_binary",side_effect=AssertionError("MUST NOT reach the Pro path")), \- patch("cloakbrowser.download.check_platform_available",- side_effect=AssertionError("MUST NOT reach the free-tier path")):+ patch("cloakbrowser.download._claim_free_key",+ side_effect=AssertionError("MUST NOT reach the no-key path")):with pytest.raises(CloakBrowserLicenseError, match="invalid or expired"):ensure_binary("cb_bad")- def test_unvalidatable_key_aborts_not_free(self):+ def test_unvalidatable_key_aborts(self):"""A supplied key that can't be validated (server unreachable, no cache →validate_license returns None) must abort — NOT silently downgrade."""- with patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}, clear=False), \- patch("cloakbrowser.download.get_local_binary_override", return_value=None), \+ with patch("cloakbrowser.download.get_local_binary_override", return_value=None), \patch("cloakbrowser.license.resolve_license_key", return_value="cb_x"), \patch("cloakbrowser.license.validate_license", return_value=None), \patch("cloakbrowser.download._ensure_pro_binary",side_effect=AssertionError("MUST NOT reach the Pro path")), \- patch("cloakbrowser.download.check_platform_available",- side_effect=AssertionError("MUST NOT reach the free-tier path")):+ patch("cloakbrowser.download._claim_free_key",+ side_effect=AssertionError("MUST NOT reach the no-key path")):with pytest.raises(CloakBrowserLicenseError, match="could not be validated"):ensure_binary("cb_x")diff --git a/tests/test_login.py b/tests/test_login.pyindex 2a82494..4270f5a 100644--- a/tests/test_login.py+++ b/tests/test_login.py@@ -1,5 +1,6 @@"""Tests for `cloakbrowser login` / `logout` (key activation, no network/binary)."""import argparse+import sysfrom unittest import mockimport pytest@@ -64,6 +65,46 @@ def test_login_no_key_non_interactive_exits(cache_dir):assert e.value.code == 2+def test_login_enter_claims_free_key_by_email(cache_dir):+ """ENTER opens this install's claim link, waits for the key, then saves it."""+ with mock.patch("cloakbrowser.download._isatty", return_value=True), \+ mock.patch("builtins.input", return_value=""), \+ mock.patch("webbrowser.open") as opened, \+ mock.patch("cloakbrowser.license.check_claim", side_effect=[None, "cb_claimed"]), \+ mock.patch("cloakbrowser.license.time.sleep"), \+ _validate(return_value=LicenseInfo(valid=True, plan="free", expires=None)):+ m.cmd_login(argparse.Namespace(key=None))+ code = (cache_dir / ".free_claim")+ assert not code.exists() # retired once the key is saved+ link = opened.call_args.args[0]+ assert link.startswith("https://cloakbrowser.dev/#claim=")+ key_file = cache_dir / "license.key"+ assert key_file.read_text().strip() == "cb_claimed"+ assert oct(key_file.stat().st_mode)[-3:] == "600"+++def test_login_rejects_non_key_text(cache_dir):+ with _validate(return_value=LicenseInfo(valid=True, plan="free", expires=None)):+ with pytest.raises(SystemExit) as e:+ m.cmd_login(argparse.Namespace(key="not a key"))+ assert e.value.code == 1+ assert not (cache_dir / "license.key").exists()+++def test_login_needs_stderr_terminal_too(cache_dir):+ """`login 2>log` would print the menu into the file and wait invisibly."""+ with mock.patch("cloakbrowser.download._isatty", side_effect=lambda s: s is not sys.stderr):+ with pytest.raises(SystemExit) as e:+ m.cmd_login(argparse.Namespace(key=None))+ assert e.value.code == 2+++def test_logout_retires_pending_claim(cache_dir):+ (cache_dir / ".free_claim").write_text("c" * 32)+ m.cmd_logout(argparse.Namespace())+ assert not (cache_dir / ".free_claim").exists()++def test_logout_removes_key(cache_dir):with _validate(return_value=LicenseInfo(valid=True, plan="free", expires=None)):m.cmd_login(argparse.Namespace(key="cb_free"))diff --git a/tests/test_persistent_context.py b/tests/test_persistent_context.pyindex f9d72ff..67d7efe 100644--- a/tests/test_persistent_context.py+++ b/tests/test_persistent_context.py@@ -7,9 +7,6 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest-from cloakbrowser.config import DEFAULT_VIEWPORT--@pytest.fixture(autouse=True)def _no_seed_file():"""These tests use fixed fake profile paths; keep the seed file off disk.@@ -52,7 +49,7 @@ def test_persistent_context_args_built(_mock_geoip, _mock_bin):@patch("cloakbrowser.browser.ensure_binary", return_value="/fake/chrome")@patch("cloakbrowser.browser.maybe_resolve_geoip", return_value=(None, None, None))def test_persistent_context_default_viewport(_mock_geoip, _mock_bin):- """DEFAULT_VIEWPORT applied when no viewport given."""+ """Headless default: no emulated viewport (the binary reports coherent dimensions)."""pw_cm, pw, context = _make_mock_pw_and_context()with patch("playwright.sync_api.sync_playwright", return_value=pw_cm):@@ -60,14 +57,15 @@ def test_persistent_context_default_viewport(_mock_geoip, _mock_bin):launch_persistent_context("/tmp/profile")call_kwargs = pw.chromium.launch_persistent_context.call_args[1]- assert call_kwargs["viewport"] == DEFAULT_VIEWPORT+ assert call_kwargs.get("no_viewport") is True+ assert "viewport" not in call_kwargs@patch("cloakbrowser.browser.ensure_binary", return_value="/fake/chrome")@patch("cloakbrowser.browser.maybe_resolve_geoip", return_value=(None, None, None))def test_persistent_context_headed_no_viewport(_mock_geoip, _mock_bin):- """Headed (headless=False): no_viewport=True instead of DEFAULT_VIEWPORT so the- page tracks the real window (avoids the outerWidth < innerWidth tell)."""+ """Headed (headless=False): no_viewport=True so the page tracks the real+ window (avoids the outerWidth < innerWidth tell)."""pw_cm, pw, context = _make_mock_pw_and_context()with patch("playwright.sync_api.sync_playwright", return_value=pw_cm):@@ -82,7 +80,7 @@ def test_persistent_context_headed_no_viewport(_mock_geoip, _mock_bin):@patch("cloakbrowser.browser.ensure_binary", return_value="/fake/chrome")@patch("cloakbrowser.browser.maybe_resolve_geoip", return_value=(None, None, None))def test_persistent_context_custom_viewport(_mock_geoip, _mock_bin):- """Custom viewport overrides DEFAULT_VIEWPORT."""+ """Custom viewport is honored."""pw_cm, pw, context = _make_mock_pw_and_context()custom = {"width": 1280, "height": 720}@@ -189,11 +187,10 @@ def test_persistent_context_close_stops_pw(_mock_geoip, _mock_bin):pw.stop.assert_called_once()-@patch("cloakbrowser.config.get_platform_tag", return_value="darwin-arm64")@patch("cloakbrowser.browser.ensure_binary", return_value="/fake/chrome")@patch("cloakbrowser.browser.maybe_resolve_geoip", return_value=(None, None, None))-def test_persistent_context_proxy_string(_mock_geoip, _mock_bin, _mock_platform):- """Proxy string parsed and passed (unsupported platform → Playwright dict)."""+def test_persistent_context_proxy_string(_mock_geoip, _mock_bin):+ """Credentialed proxy string goes inline via --proxy-server, not Playwright's dict."""pw_cm, pw, context = _make_mock_pw_and_context()with patch("playwright.sync_api.sync_playwright", return_value=pw_cm):@@ -201,9 +198,8 @@ def test_persistent_context_proxy_string(_mock_geoip, _mock_bin, _mock_platform)launch_persistent_context("/tmp/profile", proxy="http://user:pass@proxy:8080")call_kwargs = pw.chromium.launch_persistent_context.call_args[1]- assert call_kwargs["proxy"]["server"] == "http://proxy:8080"- assert call_kwargs["proxy"]["username"] == "user"- assert call_kwargs["proxy"]["password"] == "pass"+ assert "proxy" not in call_kwargs+ assert "--proxy-server=http://user:pass@proxy:8080" in call_kwargs["args"]@patch("cloakbrowser.browser.ensure_binary", return_value="/fake/chrome")diff --git a/tests/test_proxy.py b/tests/test_proxy.pyindex 2fb6f76..1a67a3b 100644--- a/tests/test_proxy.py+++ b/tests/test_proxy.py@@ -7,45 +7,12 @@ import pytestfrom cloakbrowser.browser import (_is_socks_proxy,- _parse_proxy_url,_resolve_proxy_config,_warn_on_request_client_use,maybe_resolve_geoip,)-class TestParseProxyUrl:- def test_no_credentials(self):- assert _parse_proxy_url("http://proxy:8080") == {"server": "http://proxy:8080"}-- def test_with_credentials(self):- result = _parse_proxy_url("http://user:pass@proxy:8080")- assert result == {"server": "http://proxy:8080", "username": "user", "password": "pass"}-- def test_url_encoded_password(self):- result = _parse_proxy_url("http://user:p%40ss%3Aword@proxy:8080")- assert result["password"] == "p@ss:word"- assert result["username"] == "user"- assert result["server"] == "http://proxy:8080"-- def test_socks5(self):- result = _parse_proxy_url("socks5://user:pass@proxy:1080")- assert result["server"] == "socks5://proxy:1080"- assert result["username"] == "user"- assert result["password"] == "pass"-- def test_no_port(self):- result = _parse_proxy_url("http://user:pass@proxy")- assert result["server"] == "http://proxy"- assert result["username"] == "user"-- def test_username_only(self):- result = _parse_proxy_url("http://user@proxy:8080")- assert result["server"] == "http://proxy:8080"- assert result["username"] == "user"- assert "password" not in result--class TestBuildProxyKwargs:"""Tests for _resolve_proxy_config (formerly _build_proxy_kwargs) HTTP path."""@@ -59,8 +26,6 @@ class TestBuildProxyKwargs:assert kwargs == {"proxy": {"server": "http://proxy:8080"}}assert args == []- @patch("cloakbrowser.config.get_chromium_version", return_value="146.0.7680.177.5")- @patch("cloakbrowser.config.get_platform_tag", return_value="linux-x64")def test_proxy_with_auth(self, *_):kwargs, args = _resolve_proxy_config("http://user:pass@proxy:8080")assert kwargs == {}@@ -72,30 +37,6 @@ class TestBuildProxyKwargs:assert kwargs == {"proxy": proxy_dict}assert args == []- @patch("cloakbrowser.config.get_platform_tag", return_value="linux-x64")- def test_pinned_old_version_disables_inline_auth(self, _mock):- # Pin a binary BELOW the inline-auth floor (146.0.7680.177.5) on a- # platform that otherwise supports it. The gate must read the pin — an- # older binary lacks inline proxy auth — and fall back to Playwright's- # dict, else rolled-back binaries break proxy auth (#182).- kwargs, args = _resolve_proxy_config(- "http://user:pass@proxy:8080", browser_version="146.0.7680.177.3"- )- assert args == []- assert kwargs == {"proxy": {"server": "http://proxy:8080", "username": "user", "password": "pass"}}-- @patch("cloakbrowser.config.get_chromium_version", return_value="146.0.7680.177.5")- @patch("cloakbrowser.config.get_platform_tag", return_value="linux-x64")- def test_pinned_new_version_keeps_inline_auth(self, *_):- # Pinning a version at/above the floor keeps inline credentials.- kwargs, args = _resolve_proxy_config(- "http://user:pass@proxy:8080", browser_version="146.0.7680.177.5"- )- assert kwargs == {}- assert args == ["--proxy-server=http://user:pass@proxy:8080"]-- @patch("cloakbrowser.config.get_chromium_version", return_value="146.0.7680.177.5")- @patch("cloakbrowser.config.get_platform_tag", return_value="linux-x64")def test_proxy_dict_with_auth(self, *_):proxy_dict = {"server": "http://proxy:8080",@@ -195,38 +136,12 @@ class TestMaybeResolveGeoip:class TestBareProxyFormat:- """_parse_proxy_url must handle bare 'user:pass@host:port' strings (no scheme)."""-- def test_bare_with_credentials(self):- r = _parse_proxy_url("user:pass@proxy:8080")- assert r["username"] == "user"- assert r["password"] == "pass"- assert r["server"] == "http://proxy:8080"-- def test_bare_credentials_not_in_server(self):- r = _parse_proxy_url("user:[email protected]:5610")- assert "user" not in r["server"]- assert "pass" not in r["server"]-- def test_bare_username_only(self):- r = _parse_proxy_url("user@proxy:8080")- assert r["username"] == "user"- assert "password" not in r- assert r["server"] == "http://proxy:8080"-- def test_bare_no_port(self):- r = _parse_proxy_url("user:[email protected]")- assert r["username"] == "user"- assert r["password"] == "pass"- assert r["server"] == "http://proxy.example.com"+ """Bare proxy strings (no scheme)."""def test_bare_no_credentials_passthrough(self):# "host:port" without @ — no scheme, no creds — pass through unchanged- r = _parse_proxy_url("proxy:8080")- assert r == {"server": "proxy:8080"}+ assert _resolve_proxy_config("proxy:8080") == ({"proxy": {"server": "proxy:8080"}}, [])- @patch("cloakbrowser.config.get_chromium_version", return_value="146.0.7680.177.5")- @patch("cloakbrowser.config.get_platform_tag", return_value="linux-x64")def test_resolve_proxy_config_bare(self, *_):kwargs, args = _resolve_proxy_config("user:pass@proxy:8080")assert kwargs == {}@@ -262,8 +177,6 @@ class TestResolveProxyConfig:assert kwargs == {}assert args == []- @patch("cloakbrowser.config.get_chromium_version", return_value="146.0.7680.177.5")- @patch("cloakbrowser.config.get_platform_tag", return_value="linux-x64")def test_http_string_with_creds_returns_chrome_arg(self, *_):kwargs, args = _resolve_proxy_config("http://user:pass@proxy:8080")assert kwargs == {}@@ -424,26 +337,20 @@ class TestResolveProxyConfig:_, args = _resolve_proxy_config("socks5://user:pass=1@host:0")assert args[0] == "--proxy-server=socks5://user:pass%3D1@host:0"- # --- HTTP with credentials → --proxy-server (supported platforms + version) ---+ # --- HTTP with credentials → --proxy-server ---- @patch("cloakbrowser.config.get_chromium_version", return_value="146.0.7680.177.5")- @patch("cloakbrowser.config.get_platform_tag", return_value="linux-x64")- def test_http_string_with_creds_on_supported_platform(self, *_):+ def test_http_string_with_creds(self):kwargs, args = _resolve_proxy_config("http://user:pass@proxy:8080")assert kwargs == {}assert args == ["--proxy-server=http://user:pass@proxy:8080"]- @patch("cloakbrowser.config.get_chromium_version", return_value="146.0.7680.177.5")- @patch("cloakbrowser.config.get_platform_tag", return_value="linux-x64")- def test_http_dict_with_creds_on_supported_platform(self, *_):+ def test_http_dict_with_creds(self):proxy = {"server": "http://proxy:8080", "username": "user", "password": "pass"}kwargs, args = _resolve_proxy_config(proxy)assert kwargs == {}assert args == ["--proxy-server=http://user:pass@proxy:8080"]- @patch("cloakbrowser.config.get_chromium_version", return_value="146.0.7680.177.5")- @patch("cloakbrowser.config.get_platform_tag", return_value="linux-x64")- def test_http_dict_with_creds_and_bypass(self, *_):+ def test_http_dict_with_creds_and_bypass(self):proxy = {"server": "http://proxy:8080","username": "user",@@ -455,57 +362,23 @@ class TestResolveProxyConfig:assert "--proxy-server=http://user:pass@proxy:8080" in argsassert "--proxy-bypass-list=.google.com" in args- @patch("cloakbrowser.config.get_chromium_version", return_value="146.0.7680.177.5")- @patch("cloakbrowser.config.get_platform_tag", return_value="linux-x64")def test_http_string_encodes_special_chars_in_password(self, *_):_, args = _resolve_proxy_config("http://user:pass=123@proxy:8080")assert args == ["--proxy-server=http://user:pass%3D123@proxy:8080"]- @patch("cloakbrowser.config.get_chromium_version", return_value="146.0.7680.177.5")- @patch("cloakbrowser.config.get_platform_tag", return_value="linux-x64")def test_http_string_encoding_idempotent(self, *_):_, args = _resolve_proxy_config("http://user:pass%3D123@proxy:8080")assert args == ["--proxy-server=http://user:pass%3D123@proxy:8080"]- @patch("cloakbrowser.config.get_chromium_version", return_value="146.0.7680.177.5")- @patch("cloakbrowser.config.get_platform_tag", return_value="windows-x64")- def test_http_string_with_creds_on_windows(self, *_):- kwargs, args = _resolve_proxy_config("http://user:pass@proxy:8080")- assert kwargs == {}- assert args == ["--proxy-server=http://user:pass@proxy:8080"]-- # --- HTTP with credentials on binaries without inline proxy auth → fallback ---- # Free macOS (145.x) and linux-arm64 (146.0.7680.177.3) predate the inline- # proxy-auth patch, so their credentialed HTTP proxies route through- # Playwright's proxy dict instead of --proxy-server.-- @patch("cloakbrowser.config.get_platform_tag", return_value="darwin-arm64")- def test_http_string_with_creds_on_macos_falls_back(self, _mock):- kwargs, args = _resolve_proxy_config("http://user:pass@proxy:8080")- assert "proxy" in kwargs- assert kwargs["proxy"]["username"] == "user"- assert args == []-- @patch("cloakbrowser.config.get_platform_tag", return_value="darwin-arm64")- def test_http_dict_with_creds_on_macos_falls_back(self, _mock):- proxy = {"server": "http://proxy:8080", "username": "user", "password": "pass"}- kwargs, args = _resolve_proxy_config(proxy)- assert kwargs == {"proxy": proxy}- assert args == []-- @patch("cloakbrowser.config.get_platform_tag", return_value="linux-arm64")- def test_http_string_with_creds_on_linux_arm_falls_back(self, _mock):- kwargs, args = _resolve_proxy_config("http://user:pass@proxy:8080")- assert "proxy" in kwargs- assert args == []-- @patch("cloakbrowser.config.get_platform_tag", return_value="darwin-arm64")- def test_http_with_creds_on_macos_inline_when_pinned_new(self, _mock):- # A macOS binary at/above the floor (e.g. a pinned 148 build with the- # inline proxy-auth patch) uses --proxy-server, not the fallback.- kwargs, args = _resolve_proxy_config(- "http://user:pass@proxy:8080", browser_version="148.0.7778.215.3"- )+ @pytest.mark.parametrize(+ "tag", ["linux-x64", "linux-arm64", "darwin-arm64", "darwin-x64", "windows-x64"]+ )+ def test_http_with_creds_inline_on_every_platform(self, tag):+ # Every served build ships inline proxy auth: no platform falls back to+ # Playwright's CDP proxy dict, an unversioned local override included.+ with patch("cloakbrowser.config.get_platform_tag", return_value=tag), \+ patch.dict("os.environ", {"CLOAKBROWSER_BINARY_PATH": "/x/chrome"}):+ kwargs, args = _resolve_proxy_config("http://user:pass@proxy:8080")assert kwargs == {}assert args == ["--proxy-server=http://user:pass@proxy:8080"]diff --git a/tests/test_update.py b/tests/test_update.pyindex a23ee50..57d77c2 100644--- a/tests/test_update.py+++ b/tests/test_update.py@@ -13,30 +13,21 @@ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKeyfrom cloakbrowser.config import (_version_newer,_version_tuple,- get_chromium_version,- get_download_url,+ get_archive_name,get_effective_version,get_platform_tag,)from cloakbrowser.download import (BinaryVerificationError,_check_wrapper_update,- _download_and_extract,_download_pro_binary,_ensure_pro_binary,- _fetch_checksums,- _fetch_signed_manifest,- _get_latest_chromium_version,_parse_checksums,_parse_manifest_version,- _should_check_for_update,_verify_checksum,- _verify_download_checksum,_verify_pro_download,_verify_signature,- _write_version_marker,check_for_pro_update,- check_for_update,clear_cache,ensure_binary,)@@ -78,211 +69,6 @@ class TestVersionComparison:assert _version_newer("146.0.0.0", "145.0.7632.109.2") is True-class TestDownloadUrl:- def test_default_url_format(self):- url = get_download_url()- assert "cloakbrowser.dev" in url- assert f"chromium-v{get_chromium_version()}" in url- assert url.endswith(".tar.gz")-- def test_custom_version_url(self):- url = get_download_url("145.0.7718.0")- assert "chromium-v145.0.7718.0" in url-- def test_no_old_repo_reference(self):- url = get_download_url()- assert "chromium-stealth-builds" not in url---class TestShouldCheckForUpdate:- def test_disabled_by_env(self):- with patch.dict(os.environ, {"CLOAKBROWSER_AUTO_UPDATE": "false"}):- assert _should_check_for_update() is False-- def test_disabled_by_env_case_insensitive(self):- with patch.dict(os.environ, {"CLOAKBROWSER_AUTO_UPDATE": "False"}):- assert _should_check_for_update() is False-- def test_disabled_by_binary_override(self):- with patch.dict(os.environ, {"CLOAKBROWSER_BINARY_PATH": "/some/path"}):- assert _should_check_for_update() is False-- def test_disabled_by_custom_download_url(self):- with patch.dict(- os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": "https://my-mirror.com"}- ):- assert _should_check_for_update() is False-- def test_rate_limited(self, tmp_path):- import time-- with patch.dict(- os.environ,- {- "CLOAKBROWSER_CACHE_DIR": str(tmp_path),- "CLOAKBROWSER_BINARY_PATH": "",- "CLOAKBROWSER_AUTO_UPDATE": "",- "CLOAKBROWSER_DOWNLOAD_URL": "",- },- ):- check_file = tmp_path / ".last_update_check"- check_file.write_text(str(time.time()))- assert _should_check_for_update() is False-- def test_stale_rate_limit_allows_check(self, tmp_path):- import time-- with patch.dict(- os.environ,- {- "CLOAKBROWSER_CACHE_DIR": str(tmp_path),- "CLOAKBROWSER_BINARY_PATH": "",- "CLOAKBROWSER_AUTO_UPDATE": "",- "CLOAKBROWSER_DOWNLOAD_URL": "",- },- ):- check_file = tmp_path / ".last_update_check"- check_file.write_text(str(time.time() - 7200)) # 2 hours ago- assert _should_check_for_update() is True---class TestEffectiveVersion:- def test_no_marker_returns_platform_version(self, tmp_path):- with patch.dict(os.environ, {"CLOAKBROWSER_CACHE_DIR": str(tmp_path)}):- assert get_effective_version() == get_chromium_version()-- def test_marker_with_newer_version(self, tmp_path):- with patch.dict(os.environ, {"CLOAKBROWSER_CACHE_DIR": str(tmp_path)}):- marker = tmp_path / f"latest_version_{get_platform_tag()}"- marker.write_text("999.0.0.0")- # Binary doesn't exist, so should fall back- assert get_effective_version() == get_chromium_version()-- def test_marker_with_older_version_ignored(self, tmp_path):- with patch.dict(os.environ, {"CLOAKBROWSER_CACHE_DIR": str(tmp_path)}):- marker = tmp_path / f"latest_version_{get_platform_tag()}"- marker.write_text("100.0.0.0")- assert get_effective_version() == get_chromium_version()---class TestGetLatestVersion:- """Tests for _get_latest_chromium_version with platform-aware asset checking."""-- def _make_assets(self, platforms: list[str]) -> list[dict]:- """Helper to build asset list from platform tags."""- return [{"name": f"cloakbrowser-{p}.tar.gz"} for p in platforms]-- def _platform_tarball(self) -> str:- return f"cloakbrowser-{get_platform_tag()}.tar.gz"-- def test_parses_chromium_tag_with_platform_asset(self):- mock_response = MagicMock()- mock_response.json.return_value = [- {- "tag_name": "chromium-v145.0.7718.0",- "draft": False,- "assets": self._make_assets(- ["linux-x64", "darwin-arm64", "darwin-x64", "windows-x64"]- ),- },- ]- mock_response.raise_for_status = MagicMock()-- with patch("cloakbrowser.download.httpx.get", return_value=mock_response):- result = _get_latest_chromium_version()- assert result == "145.0.7718.0"-- def test_skips_release_without_platform_asset(self):- """If latest release has no asset for our platform, fall back to older release."""- mock_response = MagicMock()- mock_response.json.return_value = [- {- "tag_name": "chromium-v145.0.7718.0",- "draft": False,- "assets": self._make_assets(["linux-x64"]), # Linux only- },- {- "tag_name": "chromium-v142.0.7444.175",- "draft": False,- "assets": self._make_assets(- ["linux-x64", "darwin-arm64", "darwin-x64", "windows-x64"]- ),- },- ]- mock_response.raise_for_status = MagicMock()-- with patch("cloakbrowser.download.httpx.get", return_value=mock_response):- result = _get_latest_chromium_version()- tag = get_platform_tag()- if tag == "linux-x64":- assert result == "145.0.7718.0"- else:- assert result == "142.0.7444.175"-- def test_skips_draft_releases(self):- mock_response = MagicMock()- all_platforms = ["linux-x64", "darwin-arm64", "darwin-x64", "windows-x64"]- mock_response.json.return_value = [- {- "tag_name": "chromium-v999.0.0.0",- "draft": True,- "assets": self._make_assets(all_platforms),- },- {- "tag_name": "chromium-v145.0.7718.0",- "draft": False,- "assets": self._make_assets(all_platforms),- },- ]- mock_response.raise_for_status = MagicMock()-- with patch("cloakbrowser.download.httpx.get", return_value=mock_response):- result = _get_latest_chromium_version()- assert result == "145.0.7718.0"-- def test_skips_non_chromium_tags(self):- mock_response = MagicMock()- all_platforms = ["linux-x64", "darwin-arm64", "darwin-x64", "windows-x64"]- mock_response.json.return_value = [- {- "tag_name": "v0.2.0",- "draft": False,- "assets": self._make_assets(all_platforms),- },- {- "tag_name": "chromium-v145.0.7718.0",- "draft": False,- "assets": self._make_assets(all_platforms),- },- ]- mock_response.raise_for_status = MagicMock()-- with patch("cloakbrowser.download.httpx.get", return_value=mock_response):- result = _get_latest_chromium_version()- assert result == "145.0.7718.0"-- def test_returns_none_when_no_platform_assets(self):- """If no release has our platform, return None."""- mock_response = MagicMock()- mock_response.json.return_value = [- {- "tag_name": "chromium-v145.0.7718.0",- "draft": False,- "assets": [{"name": "cloakbrowser-freebsd-x64.tar.gz"}],- },- ]- mock_response.raise_for_status = MagicMock()-- with patch("cloakbrowser.download.httpx.get", return_value=mock_response):- result = _get_latest_chromium_version()- assert result is None-- def test_network_error_returns_none(self):- with patch("cloakbrowser.download.httpx.get", side_effect=Exception("timeout")):- result = _get_latest_chromium_version()- assert result is None--class TestWrapperUpdateCheck:"""Tests for _check_wrapper_update (PyPI version check)."""@@ -324,14 +110,6 @@ class TestWrapperUpdateCheck:_check_wrapper_update()mock_get.assert_not_called()- def test_disabled_by_custom_download_url(self):- with patch.dict(- os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": "https://mirror.example.com"}- ):- with patch("cloakbrowser.download.httpx.get") as mock_get:- _check_wrapper_update()- mock_get.assert_not_called()-def test_network_error_silent(self, caplog):with patch("cloakbrowser.download.httpx.get", side_effect=Exception("timeout")):import logging@@ -417,54 +195,6 @@ class TestClearCache:clear_cache() # Should not raise-class TestCheckForUpdate:- @patch("cloakbrowser.download._maybe_trigger_update_check")- def test_returns_none_when_current(self, _mock_update):- with patch(- "cloakbrowser.download._get_latest_chromium_version", return_value=None- ):- assert check_for_update() is None-- @patch("cloakbrowser.download._maybe_trigger_update_check")- def test_returns_none_on_network_error(self, _mock_update):- with patch(- "cloakbrowser.download._get_latest_chromium_version",- side_effect=Exception("timeout"),- ):- # _get_latest_chromium_version catches exceptions internally, but- # check_for_update itself can also fail — test graceful None return- with patch(- "cloakbrowser.download._get_latest_chromium_version", return_value=None- ):- assert check_for_update() is None-- @patch("cloakbrowser.download._maybe_trigger_update_check")- def test_returns_version_when_newer(self, _mock_update, tmp_path):- with patch.dict(os.environ, {"CLOAKBROWSER_CACHE_DIR": str(tmp_path)}):- with patch(- "cloakbrowser.download._get_latest_chromium_version",- return_value="999.0.0.0",- ):- with patch("cloakbrowser.download._download_and_extract"):- result = check_for_update()- assert result == "999.0.0.0"-- @patch("cloakbrowser.download._maybe_trigger_update_check")- def test_skips_download_if_already_cached(self, _mock_update, tmp_path):- with patch.dict(os.environ, {"CLOAKBROWSER_CACHE_DIR": str(tmp_path)}):- # Create the binary dir so it looks already downloaded- binary_dir = tmp_path / "chromium-999.0.0.0"- binary_dir.mkdir()- with patch(- "cloakbrowser.download._get_latest_chromium_version",- return_value="999.0.0.0",- ):- with patch("cloakbrowser.download._download_and_extract") as mock_dl:- result = check_for_update()- assert result == "999.0.0.0"- mock_dl.assert_not_called()--class TestEnsureBinary:@patch("cloakbrowser.download._maybe_trigger_update_check")def test_local_override(self, _mock_update, tmp_path):@@ -482,60 +212,6 @@ class TestEnsureBinary:with pytest.raises(FileNotFoundError, match="does not exist"):ensure_binary()- @patch("cloakbrowser.download._maybe_trigger_update_check")- def test_cached_binary_found(self, _mock_update, tmp_path):- with patch.dict(- os.environ,- {- "CLOAKBROWSER_CACHE_DIR": str(tmp_path),- "CLOAKBROWSER_BINARY_PATH": "",- },- ):- # Create a fake cached binary- with patch("cloakbrowser.download.get_binary_path") as mock_path:- fake_binary = tmp_path / "chrome"- fake_binary.write_bytes(b"binary")- fake_binary.chmod(0o755)- mock_path.return_value = fake_binary- with patch("cloakbrowser.download.check_platform_available"):- result = ensure_binary()- assert result == str(fake_binary)-- @patch("cloakbrowser.download._maybe_trigger_update_check")- def test_pinned_free_version_uses_exact_download(self, _mock_update, tmp_path):- with patch.dict(- os.environ,- {- "CLOAKBROWSER_CACHE_DIR": str(tmp_path),- "CLOAKBROWSER_BINARY_PATH": "",- },- ):- requested = "146.0.7680.177.5"- fake_binary = tmp_path / "chrome"- with patch("cloakbrowser.download.check_platform_available"):- with patch(- "cloakbrowser.download.get_binary_path", return_value=fake_binary- ):-- def fake_download(version):- assert version == requested- fake_binary.write_bytes(b"binary")- fake_binary.chmod(0o755)-- with patch(- "cloakbrowser.download._download_and_extract",- side_effect=fake_download,- ) as mock_dl:- result = ensure_binary(browser_version=requested)- mock_dl.assert_called_once_with(requested)- assert result == str(fake_binary)- # A pinned (rollback) download must NOT write the 'latest'- # marker — an unpinned launch must still resolve to latest.- assert not (- tmp_path / f"latest_version_{get_platform_tag()}"- ).exists()- assert not (tmp_path / "latest_version").exists()-def test_pinned_pro_version_skips_latest_marker(self, tmp_path):# A pinned Pro (rollback) download must NOT write latest_pro_version_*,# so an unpinned Pro launch still resolves to the latest build.@@ -571,7 +247,7 @@ class TestEnsureBinary:assert not marker.exists()@patch("cloakbrowser.download._maybe_trigger_update_check")- def test_pinned_free_env_rejects_unsafe_version(self, _mock_update, tmp_path):+ def test_env_pin_rejects_unsafe_version(self, _mock_update, tmp_path):with patch.dict(os.environ,{@@ -583,39 +259,12 @@ class TestEnsureBinary:with pytest.raises(ValueError, match="Invalid browser version pin"):ensure_binary()- @patch("cloakbrowser.download._maybe_trigger_update_check")- def test_downloads_when_missing(self, _mock_update, tmp_path):- with patch.dict(- os.environ,- {- "CLOAKBROWSER_CACHE_DIR": str(tmp_path),- "CLOAKBROWSER_BINARY_PATH": "",- },- ):- fake_binary = tmp_path / "chrome"- with patch("cloakbrowser.download.check_platform_available"):- with patch("cloakbrowser.download.get_binary_path") as mock_path:- # effective == platform_version (no marker), so fallback block skipped.- # Call 1: get_binary_path(effective) → nonexistent (triggers download)- # Call 2: get_binary_path() → fake_binary (post-download verify)- mock_path.side_effect = [- tmp_path / "nonexistent", # pre-download: not cached- fake_binary, # post-download: binary ready- ]- with patch(- "cloakbrowser.download._download_and_extract"- ) as mock_dl:- fake_binary.write_bytes(b"binary")- result = ensure_binary()- mock_dl.assert_called_once()- assert result == str(fake_binary)-def _make_pro_binary(version: str):"""Create a fake cached, executable Pro binary for `version`."""from cloakbrowser.config import get_binary_path- bp = get_binary_path(version, pro=True)+ bp = get_binary_path(version)bp.parent.mkdir(parents=True, exist_ok=True)bp.write_bytes(b"binary")bp.chmod(0o755)@@ -623,8 +272,8 @@ def _make_pro_binary(version: str):class TestUnpinnedProUpgrade:- """An unpinned Pro launch must track the server's latest stable,- never roll down to a stale cached build, and never fall back to the free binary."""+ """An unpinned keyed launch must track the server's latest stable and never+ roll down to a stale cached build."""OLD = "148.0.7778.215.3"NEW = "148.0.7778.215.5"@@ -653,7 +302,7 @@ class TestUnpinnedProUpgrade:result = _ensure_pro_binary("cb_key")mock_dl.assert_called_once()- assert result == str(get_binary_path(self.NEW, pro=True))+ assert result == str(get_binary_path(self.NEW))assert marker.read_text() == self.NEW # marker advanced, not stuckdef test_preview_uses_server_version_and_preview_marker(self, tmp_path):@@ -680,7 +329,7 @@ class TestUnpinnedProUpgrade:result = _ensure_pro_binary("cb_key", release_channel="preview")- expected_path = str(get_binary_path(self.NEW, pro=True))+ expected_path = str(get_binary_path(self.NEW))mock_latest.assert_called_once_with("preview")mock_dl.assert_called_once_with(self.NEW, "cb_key")@@ -759,7 +408,7 @@ class TestUnpinnedProUpgrade:result = _ensure_pro_binary("cb_key")mock_dl.assert_not_called() # already cached, no download- assert result == str(get_binary_path(self.NEW, pro=True))+ assert result == str(get_binary_path(self.NEW))assert marker.read_text() == self.NEW # marker advanced, no stale divergencedef test_steady_state_no_download(self, tmp_path):@@ -779,10 +428,10 @@ class TestUnpinnedProUpgrade:result = _ensure_pro_binary("cb_key")mock_dl.assert_not_called()- assert result == str(get_binary_path(self.NEW, pro=True))+ assert result == str(get_binary_path(self.NEW))def test_server_down_uses_cached_pro(self, tmp_path):- """Server unreachable → launch the cached Pro build, never fail, never free."""+ """Server unreachable → launch the cached Pro build, never fail."""with patch.dict(os.environ, {"CLOAKBROWSER_CACHE_DIR": str(tmp_path)}):(tmp_path / f"latest_pro_version_{get_platform_tag()}").write_text(self.OLD)_make_pro_binary(self.OLD)@@ -797,10 +446,10 @@ class TestUnpinnedProUpgrade:result = _ensure_pro_binary("cb_key")mock_dl.assert_not_called()- assert result == str(get_binary_path(self.OLD, pro=True))+ assert result == str(get_binary_path(self.OLD))def test_download_failure_falls_back_to_cached(self, tmp_path):- """A failed upgrade download falls back to the cached Pro build, not free."""+ """A failed upgrade download falls back to the cached Pro build."""with patch.dict(os.environ, {"CLOAKBROWSER_CACHE_DIR": str(tmp_path)}):(tmp_path / f"latest_pro_version_{get_platform_tag()}").write_text(self.OLD)_make_pro_binary(self.OLD)@@ -818,7 +467,7 @@ class TestUnpinnedProUpgrade:from cloakbrowser.config import get_binary_pathresult = _ensure_pro_binary("cb_key")- assert result == str(get_binary_path(self.OLD, pro=True))+ assert result == str(get_binary_path(self.OLD))def test_verification_error_surfaces_not_cached_fallback(self, tmp_path):"""A tampering signal (BinaryVerificationError) must propagate verbatim, even@@ -840,8 +489,8 @@ class TestUnpinnedProUpgrade:with pytest.raises(BinaryVerificationError, match="checksum mismatch"):_ensure_pro_binary("cb_key")- def test_no_cache_no_server_raises_never_free(self, tmp_path):- """No cached Pro build AND no server → hard error, never the free binary."""+ def test_no_cache_no_server_raises(self, tmp_path):+ """No cached Pro build AND no server → hard error."""with patch.dict(os.environ, {"CLOAKBROWSER_CACHE_DIR": str(tmp_path)}):with (patch(@@ -855,7 +504,7 @@ class TestUnpinnedProUpgrade:def test_auto_update_false_keeps_cached_no_server_check(self, tmp_path):"""CLOAKBROWSER_AUTO_UPDATE=false + a cached Pro build → keep it, no upgrade,- no server check (parity with the free path's freeze semantics)."""+ no server check."""with patch.dict(os.environ,{@@ -878,16 +527,16 @@ class TestUnpinnedProUpgrade:result = _ensure_pro_binary("cb_key")mock_dl.assert_not_called()mock_latest.assert_not_called() # frozen → no server check at all- assert result == str(get_binary_path(self.OLD, pro=True))+ assert result == str(get_binary_path(self.OLD))- def test_missing_cache_downloads_latest_never_free(self, tmp_path):- """Marker names a build whose binary is gone → fetch latest Pro, never 146.x."""+ def test_missing_cache_downloads_latest(self, tmp_path):+ """Marker names a build whose binary is gone → fetch latest Pro."""marker = tmp_path / f"latest_pro_version_{get_platform_tag()}"with patch.dict(os.environ, {"CLOAKBROWSER_CACHE_DIR": str(tmp_path)}):marker.write_text(self.OLD) # marker present, but NO binary on diskdef fake_download(version, key):- assert version == self.NEW # never the free base (146.x)+ assert version == self.NEW_make_pro_binary(self.NEW)with (@@ -903,7 +552,7 @@ class TestUnpinnedProUpgrade:from cloakbrowser.config import get_binary_pathresult = _ensure_pro_binary("cb_key")- assert result == str(get_binary_path(self.NEW, pro=True))+ assert result == str(get_binary_path(self.NEW))class TestCheckForProUpdate:@@ -957,122 +606,28 @@ class TestCheckForProUpdate:assert check_for_pro_update("cb_key") is None-class TestEffectiveVersionProNoFreeFallback:- """get_effective_version(pro=True) must return None — never the free base —- when no cached Pro binary matches the marker."""+class TestEffectiveVersion:+ """get_effective_version() returns None when no cached binary matches the marker."""- def test_none_when_no_cached_pro_binary(self, tmp_path):+ def test_none_when_no_cached_binary(self, tmp_path):with patch.dict(os.environ, {"CLOAKBROWSER_CACHE_DIR": str(tmp_path)}):# Marker points at a version whose binary is not on disk.(tmp_path / f"latest_pro_version_{get_platform_tag()}").write_text("148.0.7778.215.5")- assert get_effective_version(pro=True) is None+ assert get_effective_version() is Nonedef test_none_when_no_marker(self, tmp_path):with patch.dict(os.environ, {"CLOAKBROWSER_CACHE_DIR": str(tmp_path)}):- assert get_effective_version(pro=True) is None- # Free tier still resolves to a concrete version.- assert get_effective_version(pro=False) == get_chromium_version()-+ assert get_effective_version() is None-class TestWriteVersionMarker:- def test_creates_file(self, tmp_path):+ def test_returns_cached_marker_version(self, tmp_path):with patch.dict(os.environ, {"CLOAKBROWSER_CACHE_DIR": str(tmp_path)}):- _write_version_marker("999.0.0.0")- marker = tmp_path / f"latest_version_{get_platform_tag()}"- assert marker.exists()- assert marker.read_text() == "999.0.0.0"---class TestDownloadFallback:- """Verify primary server (cloakbrowser.dev) → GitHub Releases fallback on HTTP errors."""-- def test_binary_download_falls_back_on_http_error(self, tmp_path):- """HTTP error from primary triggers GitHub Releases fallback for binary download."""- with patch.dict(- os.environ,- {- "CLOAKBROWSER_CACHE_DIR": str(tmp_path),- "CLOAKBROWSER_DOWNLOAD_URL": "",- },- ):- urls_called = []-- def mock_download_file(url, dest):- urls_called.append(url)- if "cloakbrowser.dev" in url:- raise Exception("HTTP 429 Too Many Requests")- # GitHub fallback succeeds- dest.write_bytes(b"fake")-- # This test exercises URL fallback, not verification — stub the- # (now signature-based, non-bypassable) verify step.- with (- patch(- "cloakbrowser.download._download_file",- side_effect=mock_download_file,- ),- patch("cloakbrowser.download._verify_download_checksum"),- patch("cloakbrowser.download._extract_archive"),- patch("cloakbrowser.download._show_welcome"),- ):- _download_and_extract()-- assert len(urls_called) == 2- assert "cloakbrowser.dev" in urls_called[0]- assert "github.com" in urls_called[1]-- def test_binary_download_no_fallback_with_custom_url(self, tmp_path):- """Custom CLOAKBROWSER_DOWNLOAD_URL disables GitHub fallback — error propagates."""- with patch.dict(- os.environ,- {- "CLOAKBROWSER_CACHE_DIR": str(tmp_path),- "CLOAKBROWSER_DOWNLOAD_URL": "https://my-mirror.com/releases",- "CLOAKBROWSER_SKIP_CHECKSUM": "true",- },- ):- with patch(- "cloakbrowser.download._download_file", side_effect=Exception("503")- ):- with pytest.raises(Exception, match="503"):- _download_and_extract()-- def test_checksum_fetch_falls_back_on_http_error(self):- """HTTP error from primary checksum URL triggers GitHub fallback."""- valid_checksums = (- "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"- " cloakbrowser-linux-x64.tar.gz\n"- )-- def mock_get(url, **kwargs):- resp = MagicMock()- if "cloakbrowser.dev" in url:- resp.raise_for_status.side_effect = Exception("HTTP 429")- return resp- # GitHub URL succeeds- resp.text = valid_checksums- resp.raise_for_status = MagicMock()- return resp-- with patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}):- with patch("cloakbrowser.download.httpx.get", side_effect=mock_get):- result = _fetch_checksums()-- assert result is not None- assert "cloakbrowser-linux-x64.tar.gz" in result-- def test_checksum_fetch_returns_none_when_both_fail(self):- """Both primary and GitHub checksum URLs fail → returns None (skip verification)."""- with patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}):- with patch(- "cloakbrowser.download.httpx.get",- side_effect=Exception("network error"),- ):- result = _fetch_checksums()-- assert result is None+ (tmp_path / f"latest_pro_version_{get_platform_tag()}").write_text(+ "148.0.7778.215.5"+ )+ _make_pro_binary("148.0.7778.215.5")+ assert get_effective_version() == "148.0.7778.215.5"# ---------------------------------------------------------------------------@@ -1150,146 +705,9 @@ class TestSignatureVerification:_verify_signature(manifest, sig) # no raise-class TestVerifyDownloadChecksumSigned:- """_verify_download_checksum on the official path: signature + version + hash, fail-closed."""-- def _hash(self, data: bytes) -> str:- return hashlib.sha256(data).hexdigest()-- def _manifest(self, body: str, version: str | None = None) -> bytes:- """Build a signed-manifest body with the bound version line prepended."""- v = version if version is not None else get_chromium_version()- return f"version={v}\n{body}".encode()-- def test_valid_manifest_and_hash_passes(self, tmp_path):- priv, pub_b64 = _make_key()- archive = tmp_path / "binary"- archive.write_bytes(b"the real binary")- tarball = get_download_url().rsplit("/", 1)[-1]- manifest = self._manifest(f"{self._hash(b'the real binary')} {tarball}\n")- sig = _sign(priv, manifest)-- with (- patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}),- patch("cloakbrowser.download.BINARY_SIGNING_PUBKEYS", [pub_b64]),- patch(- "cloakbrowser.download._fetch_signed_manifest",- return_value=(manifest, sig),- ),- ):- _verify_download_checksum(archive) # no raise-- def test_tampered_binary_fails_hash(self, tmp_path):- priv, pub_b64 = _make_key()- archive = tmp_path / "binary"- archive.write_bytes(b"a malicious binary") # different bytes- tarball = get_download_url().rsplit("/", 1)[-1]- manifest = self._manifest(f"{self._hash(b'the real binary')} {tarball}\n")- sig = _sign(priv, manifest)-- with (- patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}),- patch("cloakbrowser.download.BINARY_SIGNING_PUBKEYS", [pub_b64]),- patch(- "cloakbrowser.download._fetch_signed_manifest",- return_value=(manifest, sig),- ),- ):- with pytest.raises(RuntimeError, match="Checksum verification failed"):- _verify_download_checksum(archive)-- def test_wrong_version_fails_downgrade(self, tmp_path):- """A genuinely-signed manifest for a DIFFERENT version is rejected (downgrade)."""- priv, pub_b64 = _make_key()- archive = tmp_path / "binary"- archive.write_bytes(b"the real binary")- tarball = get_download_url().rsplit("/", 1)[-1]- # Manifest declares an old version, but we ask for get_chromium_version().- manifest = self._manifest(- f"{self._hash(b'the real binary')} {tarball}\n", version="1.0.0.0"- )- sig = _sign(priv, manifest)- with (- patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}),- patch("cloakbrowser.download.BINARY_SIGNING_PUBKEYS", [pub_b64]),- patch(- "cloakbrowser.download._fetch_signed_manifest",- return_value=(manifest, sig),- ),- ):- with pytest.raises(RuntimeError, match="Version mismatch"):- _verify_download_checksum(archive)-- def test_missing_version_line_fails(self, tmp_path):- """A signed manifest without a version line is rejected (binding required)."""- priv, pub_b64 = _make_key()- archive = tmp_path / "binary"- archive.write_bytes(b"the real binary")- tarball = get_download_url().rsplit("/", 1)[-1]- manifest = (- f"{self._hash(b'the real binary')} {tarball}\n".encode()- ) # no version=- sig = _sign(priv, manifest)- with (- patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}),- patch("cloakbrowser.download.BINARY_SIGNING_PUBKEYS", [pub_b64]),- patch(- "cloakbrowser.download._fetch_signed_manifest",- return_value=(manifest, sig),- ),- ):- with pytest.raises(RuntimeError, match="Version mismatch"):- _verify_download_checksum(archive)-- def test_missing_signed_manifest_fails_closed(self, tmp_path):- archive = tmp_path / "binary"- archive.write_bytes(b"x")- with (- patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}),- patch("cloakbrowser.download._fetch_signed_manifest", return_value=None),- ):- with pytest.raises(RuntimeError, match="signed SHA256SUMS"):- _verify_download_checksum(archive)-- def test_manifest_without_entry_fails(self, tmp_path):- priv, pub_b64 = _make_key()- archive = tmp_path / "binary"- archive.write_bytes(b"x")- manifest = self._manifest(- "deadbeef some-other-file.tar.gz\n"- ) # no entry for our tarball- sig = _sign(priv, manifest)- with (- patch.dict(os.environ, {"CLOAKBROWSER_DOWNLOAD_URL": ""}),- patch("cloakbrowser.download.BINARY_SIGNING_PUBKEYS", [pub_b64]),- patch(- "cloakbrowser.download._fetch_signed_manifest",- return_value=(manifest, sig),- ),- ):- with pytest.raises(RuntimeError, match="no entry for"):- _verify_download_checksum(archive)-- def test_custom_url_uses_plain_checksum_and_skip(self, tmp_path):- """Self-hosted CLOAKBROWSER_DOWNLOAD_URL keeps the legacy skippable path."""- archive = tmp_path / "binary"- archive.write_bytes(b"x")- with patch.dict(- os.environ,- {- "CLOAKBROWSER_DOWNLOAD_URL": "https://my-mirror.test",- "CLOAKBROWSER_SKIP_CHECKSUM": "true",- },- ):- # Signature path must NOT be consulted for a custom mirror.- with patch("cloakbrowser.download._fetch_signed_manifest") as mocked:- _verify_download_checksum(archive) # skip honored, no raise- mocked.assert_not_called()--class TestVerifyProDownloadSigned:- """_verify_pro_download: Pro binaries get the SAME non-bypassable signature- check as the free official path (parity — closes the Pro M1 gap)."""+ """_verify_pro_download: downloads get a non-bypassable signature check+ (closes M1)."""PRO_VERSION = "147.0.1.0"@@ -1297,7 +715,7 @@ class TestVerifyProDownloadSigned:return hashlib.sha256(data).hexdigest()def _tarball(self) -> str:- return get_download_url().rsplit("/", 1)[-1]+ return get_archive_name()def _mock_fetch(self, manifest: bytes, sig: bytes):"""httpx.get stub: returns the .sig for *.sig URLs, manifest otherwise."""@@ -1350,7 +768,7 @@ class TestVerifyProDownloadSigned:_verify_pro_download(archive, self.PRO_VERSION)def test_missing_manifest_is_transient_not_tampering(self, tmp_path):- """A failed manifest FETCH is transient (router falls back to free), so it+ """A failed manifest FETCH is transient (router falls back to a cached build), so itmust be a plain RuntimeError — NOT a BinaryVerificationError, which therouter re-raises as a hard failure."""archive = tmp_path / "binary"@@ -1446,41 +864,8 @@ class TestVersionBinding:assert result == {"cloakbrowser-linux-x64.tar.gz": h}-class TestFetchSignedManifest:- """_fetch_signed_manifest pairs SHA256SUMS + .sig from the same origin."""-- def test_fetches_both_from_primary(self):- def mock_get(url, **kwargs):- resp = MagicMock()- resp.raise_for_status = MagicMock()- resp.content = b"SIG" if url.endswith(".sig") else b"MANIFEST"- return resp-- with patch("cloakbrowser.download.httpx.get", side_effect=mock_get):- result = _fetch_signed_manifest("1.2.3.4")- assert result == (b"MANIFEST", b"SIG")-- def test_falls_back_to_github_when_primary_missing_sig(self):- def mock_get(url, **kwargs):- resp = MagicMock()- resp.content = b"SIG" if url.endswith(".sig") else b"MANIFEST"- if "cloakbrowser.dev" in url and url.endswith(".sig"):- resp.raise_for_status.side_effect = Exception("404")- else:- resp.raise_for_status = MagicMock()- return resp-- with patch("cloakbrowser.download.httpx.get", side_effect=mock_get):- result = _fetch_signed_manifest("1.2.3.4")- assert result == (b"MANIFEST", b"SIG")-- def test_returns_none_when_all_fail(self):- with patch("cloakbrowser.download.httpx.get", side_effect=Exception("network")):- assert _fetch_signed_manifest("1.2.3.4") is None--# ----------------------------------------------------------------------------# Welcome-banner cadence: free re-shows every 3 days, Pro shows once ever.+# Welcome-banner cadence: a free key re-shows daily, Pro shows once ever.# ---------------------------------------------------------------------------class TestWelcomeCadence:def test_pro_shows_once_then_never(self, tmp_path):diff --git a/tests/test_welcome_banner.py b/tests/test_welcome_banner.pyindex 40b042e..a51c7e4 100644--- a/tests/test_welcome_banner.py+++ b/tests/test_welcome_banner.py@@ -1,4 +1,4 @@-"""Tier-aware launch banner: keyless (v146) / free key / paid, + cadence."""+"""Tier-aware launch banner: free key / paid, + cadence."""import ioimport sysimport time@@ -20,14 +20,6 @@ def _banner(capsys, tier):return capsys.readouterr().err-def test_keyless_banner(cache, capsys):- out = _banner(capsys, "keyless")- assert "Running the free binary" in out- assert "cloakbrowser login" in out # invite the free login- assert "For more than one concurrent session" in out- assert "Pro active" not in out--def test_free_key_banner(cache, capsys):out = _banner(capsys, "free")assert "CloakBrowser free" in out@@ -57,7 +49,7 @@ def test_free_reshows_after_interval(cache, capsys):assert _banner(capsys, "free") != "" # interval passed -> shows again[email protected]("tier", ["keyless", "free", "pro"])[email protected]("tier", ["free", "pro"])def test_banner_is_ascii_only(cache, capsys, tier):"""Banner must be pure ASCII so a legacy Windows console (cp1252/strict)can always encode it. Regression for the '->' glyph."""@@ -67,7 +59,7 @@ def test_banner_is_ascii_only(cache, capsys, tier):assert non_ascii == [], f"non-ASCII in {tier} banner: {non_ascii!r}"[email protected]("tier", ["keyless", "free", "pro"])[email protected]("tier", ["free", "pro"])def test_banner_never_raises_on_cp1252_stderr(cache, monkeypatch, tier):"""Even if a future glyph slips in, a cp1252/strict stderr must not abortthe launch — the banner is cosmetic. Reproduces that crash path."""@@ -79,9 +71,9 @@ def test_banner_never_raises_on_cp1252_stderr(cache, monkeypatch, tier):def test_ensure_pro_binary_maps_plan_to_tier(monkeypatch):"""A free-plan key shows the free banner; any other plan shows Pro."""seen = []- monkeypatch.setattr(download, "_show_welcome", lambda tier="keyless": seen.append(tier))+ monkeypatch.setattr(download, "_show_welcome", lambda tier: seen.append(tier))monkeypatch.setattr(download, "_pro_binary_ready", lambda v: True)- monkeypatch.setattr(download, "get_binary_path", lambda v, pro=False: Path("/tmp/chrome"))+ monkeypatch.setattr(download, "get_binary_path", lambda v: Path("/tmp/chrome"))# Pinned + cached path returns immediately after the banner call.download._ensure_pro_binary("cb_x", requested_version="150.0.7871.114.3", plan="free")