Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b98455bf8a | ||
|
|
2e0adbde33 | ||
|
|
cf59e98fa9 | ||
|
|
22b1171518 | ||
|
|
acd568f5d3 | ||
|
|
5f0ba5d659 | ||
|
|
a0b61d1abf | ||
|
|
1eb3d5f55a | ||
|
|
567717dfd7 | ||
|
|
f1f3148d8f | ||
|
|
7f7a791564 | ||
|
|
f7b5e86793 |
No files matched your search
@@ -0,0 +1,31 @@
|
||||
#!/bin/sh
|
||||
# Pre-push hook: blocks push if the test suite isn't fully green.
|
||||
#
|
||||
# Enable once with:
|
||||
# git config core.hooksPath .githooks
|
||||
#
|
||||
# Bypass for a known-broken WIP push (NOT for releases):
|
||||
# git push --no-verify
|
||||
# The --no-verify flag is the only escape hatch. Use it sparingly and never
|
||||
# for branches that feed into a release.
|
||||
|
||||
set -e
|
||||
|
||||
echo "[pre-push] running unit + integration tests before push..."
|
||||
|
||||
# Run from this script's directory so it works regardless of where the user
|
||||
# invoked git push from.
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
# Default pyproject addopts skip slow/e2e. That's the gate we want for every
|
||||
# push — fast feedback. e2e is reserved for explicit release runs.
|
||||
if ! python -m pytest -q --tb=short; then
|
||||
echo ""
|
||||
echo "[pre-push] TESTS FAILED — push aborted."
|
||||
echo "[pre-push] Either fix the failure or use 'git push --no-verify' if"
|
||||
echo "[pre-push] you really know what you're doing (NOT for release branches)."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[pre-push] all tests green — push proceeding."
|
||||
exit 0
|
||||
@@ -6,6 +6,60 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.1.6] - 2026-05-21
|
||||
|
||||
### Added
|
||||
- `profile_dir=` kwarg on `InvisiblePlaywright` (sync + async). When set, the session uses `firefox.launch_persistent_context()` so cookies, localStorage, sessionStorage, extensions, cache and prefs are kept on disk between runs. `__enter__` returns a `BrowserContext` directly: `with InvisiblePlaywright(profile_dir=p) as ctx: ctx.new_page()`. Pair with a stable `seed=` to also pin the fingerprint identity across runs. First run creates the dir; subsequent runs reuse it.
|
||||
|
||||
### Fixed
|
||||
- `launch_persistent_context(timezone_id="…")` no longer times out at 180s. Root cause: `juggler/content/main.js` calls `docShell.overrideTimezone(...)` on every navigation; the patched Firefox up to firefox-4 didn't expose that IDL method on `nsIDocShell`, so the call threw `TypeError: docShell.overrideTimezone is not a function`. On the non-persistent path the error fired *after* launch and was harmless; on the persistent path it blocked the launch handshake. `firefox-5` ships the C++ method (see `patch.md` section 19); this release removes the firefox-4 era Python workaround that was filtering `locale`/`timezone_id` out of the persistent context kwargs.
|
||||
|
||||
### Changed
|
||||
- `BINARY_VERSION` bumped from `firefox-4` to `firefox-5`. The Python source delta is JS/Python only; the new Firefox build adds 50 lines of C++ in `docshell/base/nsIDocShell.idl` + `nsDocShell.cpp`.
|
||||
|
||||
## [0.1.5] - 2026-05-20
|
||||
|
||||
### Fixed
|
||||
- [#15](https://github.com/feder-cr/invisible_playwright/pull/15): `python -m invisible_playwright fetch` raised `RuntimeError: no SHA256 for firefox-150.0.1-stealth-linux-x86_64.tar.gz in checksums.txt` for every user because the parser kept the `*` binary-mode prefix that `sha256sum` writes in front of filenames. Now `.lstrip("*")` is applied to the key. Reporter + patch: [@LostBoxArt](https://github.com/LostBoxArt). Unrelated to the `firefox-N` binary; existing caches still work, only first-time fetches were broken.
|
||||
|
||||
## [0.1.4] - 2026-05-20
|
||||
|
||||
### Fixed
|
||||
- [#13](https://github.com/feder-cr/invisible_playwright/issues/13): every page that threw an uncaught JS error (e.g. bunny.net) crashed the Playwright client with `TypeError: Cannot read properties of undefined (reading 'url')`. Root cause: upstream Playwright Juggler added a required `location` field to the `Page.uncaughtError` event in the 2026-05-07 roll ([microsoft/playwright@c8604ec](https://github.com/microsoft/playwright/commit/c8604ecd97)); our fork was carrying the pre-roll schema in every `firefox-N` build. Fix matches upstream — Runtime.js builds the `errorLocation`, PageAgent.js forwards it on both worker and runtime error paths, Protocol.js declares the schema field. Reporter: [@dionorgua](https://github.com/dionorgua).
|
||||
|
||||
### Changed
|
||||
- `BINARY_VERSION` bumped from `firefox-3` to `firefox-4`. JS-only change inside `chrome/juggler/`; `xul.dll` and `firefox.exe` are byte-identical to `firefox-3`.
|
||||
|
||||
## [0.1.3] - 2026-05-19
|
||||
|
||||
### Changed
|
||||
- `BINARY_VERSION` bumped from `firefox-2` to `firefox-3`. The new archives on both Windows and Linux are built from a clean clone of [feder-cr/invisible-firefox#stealth/150](https://github.com/feder-cr/invisible-firefox/tree/stealth/150) — the consolidated source-of-truth fork (renamed from `feder-cr/firefox`; the companion `feder-cr/firefox-stealth` patches repo was deleted, all patches now live as commits on top of `mozilla-firefox/firefox`).
|
||||
- The patched Firefox archive now ships the **proper C++ implementation** of `windowUtils.jugglerSendMouseEvent`, replacing the JS shim from 0.1.2.
|
||||
|
||||
### C++ fixes landed in this release
|
||||
- **C1+C2**: `setDownloadInterceptor` IDL + cpp (re-landed for FF150).
|
||||
- **C4**: 5 `nsIDocShell` stealth attributes (`fileInputInterceptionEnabled`, `overrideHasFocus`, `bypassCSPEnabled`, `forceActiveState`, `disallowBFCache`).
|
||||
- **C5**: `LauncherProcessWin.cpp` + `nsWindowsWMain.cpp` juggler-pipe handle inheritance — without this, the Playwright pipe disconnects immediately on launch.
|
||||
- **C6**: `juggler-navigation-started-renderer` / `-browser` observer notifications in `nsDocShell.cpp` and `CanonicalBrowsingContext.cpp` — without these, `Page.ready` never fires and `ctx.new_page()` hangs.
|
||||
- **C7 (partial)**: storage stub for `nsIDocShell.languageOverride`. Workaround `InvisiblePlaywright(locale="")` recommended until full BC FIELD port lands.
|
||||
|
||||
### Verified
|
||||
- Both archives built from same source: feder-cr/invisible-firefox commit `68906f1f9c55`.
|
||||
- Windows + Linux smoke suite green: launch, `ctx.new_page()`, `page.mouse.{move,down,up,click,wheel}`, `navigator.webdriver=false`, sannysoft 32/33 PASS.
|
||||
- SHA256 published in `checksums.txt` on the `firefox-3` release.
|
||||
|
||||
### Notes
|
||||
- This is the first release with a native Linux build of the patched binary (previous `firefox-3` draft mentioned shipping the Linux firefox-2 archive byte-for-byte; that no longer applies — Linux now has the full C++ patch series).
|
||||
|
||||
## [0.1.2] - 2026-05-18
|
||||
|
||||
### Changed
|
||||
- `BINARY_VERSION` bumped from `firefox-1` to `firefox-2`. The patched Firefox archive on GitHub Releases now contains the JS fix from 0.1.1 (every `page.mouse.*` / `page.click()` / `locator.click()` / `mouse.wheel()` failure on the FF150 binary). Users on 0.1.1 must run `python -m invisible_playwright clear-cache && python -m invisible_playwright fetch` to pick up the new archive.
|
||||
|
||||
### Verified
|
||||
- Archive integrity tests on both platforms: Windows zip extracted + booted via Playwright (`mouse.move + click + page.click(selector)` all succeed end-to-end), Linux tarball file-level checks (firefox/libxul.so sizes, byte-identity of patched JS files against Windows source). 21/21 assertions pass.
|
||||
- SHA256 published in `checksums.txt` on the `firefox-2` release.
|
||||
|
||||
## [0.1.1] - 2026-05-18
|
||||
|
||||
### Fixed
|
||||
|
||||
+3
-3
@@ -7,7 +7,7 @@ Thanks for your interest in improving this project. Contributions are welcome vi
|
||||
- **Bug?** Open a [bug report](https://github.com/feder-cr/invisible_playwright/issues/new?template=bug_report.yml).
|
||||
- **Idea?** Open a [feature request](https://github.com/feder-cr/invisible_playwright/issues/new?template=feature_request.yml).
|
||||
- **Security issue?** Do **not** open a public issue — see [SECURITY.md](SECURITY.md).
|
||||
- **The C++ patches** live in the companion repo [feder-cr/firefox-stealth](https://github.com/feder-cr/firefox-stealth). Bugs in fingerprint spoofing usually belong there.
|
||||
- **The C++ patches** live in the companion repo [feder-cr/invisible-firefox](https://github.com/feder-cr/invisible-firefox) (branch `stealth/150`). Bugs in fingerprint spoofing usually belong there.
|
||||
|
||||
## Scope
|
||||
|
||||
@@ -18,7 +18,7 @@ This repository ships the **Python wrapper** (`invisible_playwright`) around a p
|
||||
- Binary download/caching, CLI, proxy plumbing
|
||||
- Tests, docs, examples, packaging
|
||||
|
||||
Out of scope (belongs in `firefox-stealth`):
|
||||
Out of scope (belongs in `invisible-firefox`):
|
||||
|
||||
- Changes to the Firefox C++ source
|
||||
- New preferences exposed by the patched binary
|
||||
@@ -65,7 +65,7 @@ Before opening, please:
|
||||
|
||||
- Search [existing issues](https://github.com/feder-cr/invisible_playwright/issues) — the bug may already be tracked.
|
||||
- Reproduce on the **latest release** if possible.
|
||||
- Confirm the issue is in the Python wrapper, not the patched Firefox itself. If a fingerprint is leaking or a detector flags the browser, open the issue at `feder-cr/firefox-stealth` instead.
|
||||
- Confirm the issue is in the Python wrapper, not the patched Firefox itself. If a fingerprint is leaking or a detector flags the browser, open the issue at `feder-cr/invisible-firefox` instead.
|
||||
|
||||
Include:
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ Every row green: WebDriver not present, Chrome-only properties absent, plugin/mi
|
||||
|
||||
**invisible_playwright patches Firefox at the C++ level.** The spoofed values come back out through the normal Gecko paths - there is no JS shim, no override, no `Object.defineProperty`. **From the page's point of view, the browser is just telling the truth.** Anti-bot lie-detectors have nothing to latch onto.
|
||||
|
||||
invisible_playwright spoofs **all the layers that matter, together, coherently** — Navigator, screen, GPU/WebGL, Canvas, fonts, audio, WebRTC, timezone, DevTools detection, SOCKS5 auth, and the rest. See [feder-cr/firefox-stealth](https://github.com/feder-cr/firefox-stealth) for the full per-layer breakdown of which C++ files are patched and why.
|
||||
invisible_playwright spoofs **all the layers that matter, together, coherently** — Navigator, screen, GPU/WebGL, Canvas, fonts, audio, WebRTC, timezone, DevTools detection, SOCKS5 auth, and the rest. See [feder-cr/invisible-firefox](https://github.com/feder-cr/invisible-firefox) for the full per-layer breakdown of which C++ files are patched and why.
|
||||
|
||||
Everything is driven by preferences - no hardcoded values in the binary. You change one pref, you change the spoofed value.
|
||||
|
||||
@@ -203,6 +203,24 @@ invisible_playwright version # wrapper and binary versions
|
||||
invisible_playwright clear-cache # remove all cached binaries
|
||||
```
|
||||
|
||||
## Known issues
|
||||
|
||||
### `headless=True` on Windows can cause tab crashes on sites with heavy cross-process navigation
|
||||
|
||||
Reported as [#18](https://github.com/feder-cr/invisible_playwright/issues/18) (`id.sky.com` and similar). On Windows, `headless=True` runs Firefox headed on a hidden alt-desktop created via `CreateDesktop`. Some sites (id.sky.com, anything else loading Adobe AppMeasurement in a way that triggers cross-process navigation) end up firing `page.on('crash')` after about 10 seconds. The cause is a window-parenting interaction between the alt-desktop and the GPU/content processes; the workaround is one of:
|
||||
|
||||
```python
|
||||
# Option A — keep the visible window (no alt-desktop)
|
||||
with InvisiblePlaywright(seed=42, headless=False) as browser:
|
||||
...
|
||||
|
||||
# Option B — run inside Xvfb on Linux (alt-desktop bug is Windows-only)
|
||||
```
|
||||
|
||||
The visible window case works on every site we've tested. Linux + Xvfb is unaffected.
|
||||
|
||||
---
|
||||
|
||||
## Related projects
|
||||
|
||||
invisible_playwright takes a different angle than the major Firefox-hardening projects but stands on their shoulders:
|
||||
@@ -215,4 +233,4 @@ invisible_playwright takes a different angle than the major Firefox-hardening pr
|
||||
|
||||
## License
|
||||
|
||||
MIT - see [LICENSE](LICENSE). The patched Firefox binary is distributed under the MPL-2.0 (Firefox upstream license). The C++ patches against mozilla-central that produce that binary are at [feder-cr/firefox-stealth](https://github.com/feder-cr/firefox-stealth).
|
||||
MIT - see [LICENSE](LICENSE). The patched Firefox binary is distributed under the MPL-2.0 (Firefox upstream license). The C++ patches against mozilla-central that produce that binary are at [feder-cr/invisible-firefox](https://github.com/feder-cr/invisible-firefox).
|
||||
+1
-1
@@ -41,7 +41,7 @@ In scope:
|
||||
|
||||
Out of scope here (report to the relevant project):
|
||||
|
||||
- Vulnerabilities in the patched Firefox C++ source — open a private report at [feder-cr/firefox-stealth](https://github.com/feder-cr/firefox-stealth/security/advisories/new)
|
||||
- Vulnerabilities in the patched Firefox C++ source — open a private report at [feder-cr/invisible-firefox](https://github.com/feder-cr/invisible-firefox/security/advisories/new)
|
||||
- Vulnerabilities in upstream Firefox / mozilla-central — report to Mozilla per https://www.mozilla.org/security/
|
||||
- Vulnerabilities in third-party dependencies (`playwright`, `requests`, etc.) — report to those projects directly
|
||||
|
||||
|
||||
+7
-1
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "invisible-playwright"
|
||||
version = "0.1.1"
|
||||
version = "0.1.6"
|
||||
description = "Playwright wrapper for a patched Firefox with deterministic stealth profile."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
@@ -39,6 +39,12 @@ markers = [
|
||||
"linux_only: tests that require Linux platform",
|
||||
]
|
||||
addopts = "-m 'not slow and not e2e'"
|
||||
# tests/playwright-upstream/ is a vendored Microsoft Playwright test suite
|
||||
# used for compatibility verification on demand. It has its own deps
|
||||
# (pixelmatch with API not matching our version) and a conftest that fails
|
||||
# collection in our env. Run it explicitly with --override-ini for compat
|
||||
# audits, not on every push.
|
||||
norecursedirs = ["playwright-upstream"]
|
||||
|
||||
[project.scripts]
|
||||
invisible-playwright = "invisible_playwright.cli:main"
|
||||
|
||||
@@ -3,9 +3,10 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional, Union
|
||||
|
||||
from playwright.async_api import Browser, Playwright, async_playwright
|
||||
from playwright.async_api import Browser, BrowserContext, Playwright, async_playwright
|
||||
|
||||
from ._fpforge import Profile, generate_profile
|
||||
from ._headless import make_virtual_display
|
||||
@@ -49,6 +50,7 @@ class InvisiblePlaywright:
|
||||
timezone: str = "",
|
||||
extra_prefs: Optional[Dict[str, Any]] = None,
|
||||
binary_path: Optional[str] = None,
|
||||
profile_dir: Optional[Union[str, Path]] = None,
|
||||
) -> None:
|
||||
# See sync launcher: `zoom.stealth.fpp.hw_seed` is int32_t — clamp.
|
||||
self.seed: int = int(seed) if seed is not None else secrets.randbits(31)
|
||||
@@ -61,12 +63,14 @@ class InvisiblePlaywright:
|
||||
self._timezone = timezone
|
||||
self._extra_prefs = extra_prefs
|
||||
self._binary_path = binary_path
|
||||
self._profile_dir: Optional[Path] = Path(profile_dir) if profile_dir else None
|
||||
self._profile: Profile = generate_profile(self.seed, pin=self._pin)
|
||||
self._pw: Optional[Playwright] = None
|
||||
self._browser: Optional[Browser] = None
|
||||
self._persistent_context: Optional[BrowserContext] = None
|
||||
self._virtual_display: Any = None
|
||||
|
||||
async def __aenter__(self) -> Browser:
|
||||
async def __aenter__(self) -> Union[Browser, BrowserContext]:
|
||||
import sys as _sys
|
||||
executable = self._binary_path or ensure_binary()
|
||||
prefs = translate_profile_to_prefs(
|
||||
@@ -85,6 +89,24 @@ class InvisiblePlaywright:
|
||||
env = self._build_env()
|
||||
try:
|
||||
self._pw = await async_playwright().start()
|
||||
if self._profile_dir is not None:
|
||||
# See sync launcher for the persistent-context rationale.
|
||||
self._profile_dir.mkdir(parents=True, exist_ok=True)
|
||||
# firefox-5 ships the C++ overrideTimezone IDL method (C7
|
||||
# chiusura), so locale + timezone_id now propagate cleanly
|
||||
# to the persistent context without hanging the launch.
|
||||
self._persistent_context = await self._pw.firefox.launch_persistent_context(
|
||||
user_data_dir=str(self._profile_dir),
|
||||
executable_path=str(executable),
|
||||
headless=pw_headless,
|
||||
firefox_user_prefs=prefs,
|
||||
proxy=playwright_proxy,
|
||||
args=self._extra_args,
|
||||
env=env,
|
||||
**self._default_context_kwargs(),
|
||||
)
|
||||
_patch_new_page_sleep(self._persistent_context)
|
||||
return self._persistent_context
|
||||
self._browser = await self._pw.firefox.launch(
|
||||
executable_path=str(executable),
|
||||
headless=pw_headless,
|
||||
@@ -134,6 +156,12 @@ class InvisiblePlaywright:
|
||||
await self._teardown()
|
||||
|
||||
async def _teardown(self) -> None:
|
||||
if self._persistent_context is not None:
|
||||
try:
|
||||
await self._persistent_context.close()
|
||||
except Exception:
|
||||
pass
|
||||
self._persistent_context = None
|
||||
if self._browser is not None:
|
||||
try:
|
||||
await self._browser.close()
|
||||
|
||||
@@ -7,7 +7,7 @@ bugfixes don't force a multi-hour Firefox rebuild.
|
||||
from __future__ import annotations
|
||||
|
||||
# Bump this when a new patched Firefox build is released on GitHub.
|
||||
BINARY_VERSION: str = "firefox-1"
|
||||
BINARY_VERSION: str = "firefox-5"
|
||||
|
||||
# Underlying Firefox version (for display only; does not drive downloads).
|
||||
FIREFOX_UPSTREAM_VERSION: str = "150.0.1"
|
||||
|
||||
@@ -96,7 +96,9 @@ def _parse_checksums(text: str) -> dict[str, str]:
|
||||
continue
|
||||
parts = line.split()
|
||||
if len(parts) >= 2:
|
||||
out[parts[-1]] = parts[0]
|
||||
# sha256sum uses ' *' or ' ' prefix for binary vs text mode
|
||||
key = parts[-1].lstrip("*")
|
||||
out[key] = parts[0]
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional, Union
|
||||
|
||||
from playwright.sync_api import Browser, Playwright, sync_playwright
|
||||
from playwright.sync_api import Browser, BrowserContext, Playwright, sync_playwright
|
||||
|
||||
from ._fpforge import Profile, generate_profile
|
||||
from ._headless import make_virtual_display
|
||||
@@ -111,6 +112,7 @@ class InvisiblePlaywright:
|
||||
timezone: str = "",
|
||||
extra_prefs: Optional[Dict[str, Any]] = None,
|
||||
binary_path: Optional[str] = None,
|
||||
profile_dir: Optional[Union[str, Path]] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Args:
|
||||
@@ -137,6 +139,15 @@ class InvisiblePlaywright:
|
||||
extra_prefs: Optional dict of Firefox prefs overlayed on top
|
||||
of the generated profile — useful for niche tweaks
|
||||
without monkey-patching the package.
|
||||
profile_dir: Path to a persistent Firefox profile directory.
|
||||
When set, the session uses ``launch_persistent_context()``
|
||||
so cookies, localStorage, sessionStorage, extensions, cache
|
||||
and prefs are kept on disk between runs. ``__enter__``
|
||||
returns a ``BrowserContext`` (not a ``Browser``) — use it
|
||||
directly: ``with InvisiblePlaywright(profile_dir=p) as ctx:
|
||||
page = ctx.new_page()``. First run creates the dir;
|
||||
subsequent runs reuse it. Pair with a stable ``seed=`` to
|
||||
also pin the fingerprint identity across runs.
|
||||
"""
|
||||
# Constrain to int31 — Firefox's `zoom.stealth.fpp.hw_seed` and
|
||||
# related stealth prefs are declared as ``int32_t`` in
|
||||
@@ -154,12 +165,14 @@ class InvisiblePlaywright:
|
||||
self._timezone = timezone
|
||||
self._extra_prefs = extra_prefs
|
||||
self._binary_path = binary_path
|
||||
self._profile_dir: Optional[Path] = Path(profile_dir) if profile_dir else None
|
||||
self._profile: Profile = generate_profile(self.seed, pin=self._pin)
|
||||
self._pw: Optional[Playwright] = None
|
||||
self._browser: Optional[Browser] = None
|
||||
self._persistent_context: Optional[BrowserContext] = None
|
||||
self._virtual_display: Any = None
|
||||
|
||||
def __enter__(self) -> Browser:
|
||||
def __enter__(self) -> Union[Browser, BrowserContext]:
|
||||
executable = self._binary_path or ensure_binary()
|
||||
prefs = self._build_prefs()
|
||||
playwright_proxy = _configure_proxy_shared(self._proxy, prefs)
|
||||
@@ -168,6 +181,25 @@ class InvisiblePlaywright:
|
||||
|
||||
try:
|
||||
self._pw = sync_playwright().start()
|
||||
if self._profile_dir is not None:
|
||||
# Persistent context — cookies / localStorage / extensions /
|
||||
# prefs all live on disk between runs. Stealth prefs are
|
||||
# re-injected via firefox_user_prefs on every launch (Playwright
|
||||
# writes them to user.js, which overrides anything in
|
||||
# prefs.js inside the persistent dir).
|
||||
self._profile_dir.mkdir(parents=True, exist_ok=True)
|
||||
self._persistent_context = self._pw.firefox.launch_persistent_context(
|
||||
user_data_dir=str(self._profile_dir),
|
||||
executable_path=str(executable),
|
||||
headless=pw_headless,
|
||||
firefox_user_prefs=prefs,
|
||||
proxy=playwright_proxy,
|
||||
args=self._extra_args,
|
||||
env=env,
|
||||
**self._persistent_context_kwargs(),
|
||||
)
|
||||
_patch_sync_new_page_sleep(self._persistent_context)
|
||||
return self._persistent_context
|
||||
self._browser = self._pw.firefox.launch(
|
||||
executable_path=str(executable),
|
||||
headless=pw_headless,
|
||||
@@ -185,6 +217,22 @@ class InvisiblePlaywright:
|
||||
self._patch_new_context_defaults(self._browser)
|
||||
return self._browser
|
||||
|
||||
def _persistent_context_kwargs(self) -> Dict[str, Any]:
|
||||
"""Context-level kwargs accepted by launch_persistent_context.
|
||||
|
||||
Identical to ``_default_context_kwargs``: viewport / screen / DPR /
|
||||
color-scheme / locale / timezone_id. Up to firefox-4 we had to drop
|
||||
locale and timezone_id because Playwright's per-realm overrides
|
||||
called IDL methods (``docShell.languageOverride``,
|
||||
``docShell.overrideTimezone``) that weren't exposed by our patched
|
||||
build, causing launch_persistent_context to hang for 180s. From
|
||||
firefox-5 (C7 chiusura), the C++ ``overrideTimezone`` method is
|
||||
present and ``languageOverride`` was already there, so the
|
||||
per-realm overrides land and the persistent context starts in
|
||||
~20s like the non-persistent path.
|
||||
"""
|
||||
return self._default_context_kwargs()
|
||||
|
||||
def _patch_new_context_defaults(self, browser: Browser) -> None:
|
||||
"""Wrap ``browser.new_context`` so its defaults derive from the
|
||||
profile (viewport, screen, DPR, color-scheme). Users get a
|
||||
@@ -226,6 +274,12 @@ class InvisiblePlaywright:
|
||||
self._teardown()
|
||||
|
||||
def _teardown(self) -> None:
|
||||
if self._persistent_context is not None:
|
||||
try:
|
||||
self._persistent_context.close()
|
||||
except Exception:
|
||||
pass
|
||||
self._persistent_context = None
|
||||
if self._browser is not None:
|
||||
try:
|
||||
self._browser.close()
|
||||
|
||||
@@ -384,6 +384,21 @@ _WIN_VIRT_DESKTOP_WORKAROUNDS: Dict[str, Any] = {
|
||||
# Bugzilla refs: 1798091, 1524591, 1229829. Lowering the GPU sandbox to 0
|
||||
# restores hardware compositor + functional WebGL on alt desktops.
|
||||
"security.sandbox.gpu.level": 0,
|
||||
# Same root cause as above, content process side. Wrapper repo issue #18
|
||||
# (id.sky.com tab crash). Sandbox content level > 4 puts content processes
|
||||
# on the sandbox's own kAlternateWinstation (see
|
||||
# security/sandbox/win/src/sandboxbroker/sandboxBroker.cpp line 1113-1114:
|
||||
# `if (aSandboxLevel > 4) config->SetDesktop(kAlternateWinstation)`).
|
||||
# Combined with our CreateDesktop alt-desktop, that puts browser process
|
||||
# and content processes on DIFFERENT desktops. Cross-process navigation
|
||||
# (Adobe AppMeasurement → new origin → new content process on a new
|
||||
# desktop) then fails window parenting between parent and child → content
|
||||
# process exits cleanly (exitCode=0, signal=null) and Playwright fires
|
||||
# page.on('crash') ~10s after page load. Lowering content sandbox to 4
|
||||
# keeps content processes on the same desktop as the browser process,
|
||||
# which is what we want here (and is still tight enough — level 4
|
||||
# blocks file/registry write, network calls, hardware access).
|
||||
"security.sandbox.content.level": 4,
|
||||
}
|
||||
|
||||
|
||||
|
||||
+148
-1
@@ -1,6 +1,13 @@
|
||||
import pytest
|
||||
|
||||
from invisible_playwright.constants import ARCHIVE_NAME, BINARY_BASENAME, BINARY_VERSION
|
||||
from invisible_playwright.constants import (
|
||||
ARCHIVE_NAME,
|
||||
BINARY_BASENAME,
|
||||
BINARY_ENTRY_REL,
|
||||
BINARY_VERSION,
|
||||
FIREFOX_UPSTREAM_VERSION,
|
||||
RELEASE_URL_TEMPLATE,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -33,3 +40,143 @@ def test_archive_name_unsupported_raises():
|
||||
def test_binary_basename_format():
|
||||
assert "firefox" in BINARY_BASENAME.lower()
|
||||
assert "stealth" in BINARY_BASENAME.lower()
|
||||
|
||||
|
||||
# ---- Comprehensive ARCHIVE_NAME edge cases -------------------------------- #
|
||||
# Same risk shape as bug #15: a missed format assumption (sha256sum binary
|
||||
# mode) silently produced wrong output. Same class of bug here would be
|
||||
# uppercase platform string or odd machine value passing through to a
|
||||
# wrong-named asset on the CDN and 404-ing.
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("platform_key,machine,expected_substring", [
|
||||
("win32", "AMD64", "win-x86_64.zip"), # Windows reports AMD64
|
||||
("win32", "amd64", "win-x86_64.zip"), # lowercase variant
|
||||
("win32", "x86_64", "win-x86_64.zip"), # mingw-style
|
||||
("linux", "x86_64", "linux-x86_64.tar.gz"), # standard Linux
|
||||
("linux", "AMD64", "linux-x86_64.tar.gz"), # odd but plausible
|
||||
("Linux", "x86_64", "linux-x86_64.tar.gz"), # case-insensitive platform
|
||||
("WIN32", "AMD64", "win-x86_64.zip"), # ALL CAPS platform
|
||||
])
|
||||
def test_archive_name_accepts_case_variations(platform_key, machine, expected_substring):
|
||||
"""sys.platform / platform.machine() return inconsistent casing across
|
||||
OS versions and Python versions. The asset filename must be stable
|
||||
regardless — otherwise the CDN 404s."""
|
||||
assert ARCHIVE_NAME(platform_key, machine).endswith(expected_substring)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("machine", ["i386", "i686", "ppc64le", "armv7l", "riscv64"])
|
||||
def test_archive_name_rejects_unsupported_arches(machine):
|
||||
"""Unsupported arches must raise NotImplementedError with the bad value
|
||||
in the message — silent fallback to a default arch would download the
|
||||
wrong binary, run, and fingerprint differently."""
|
||||
with pytest.raises(NotImplementedError, match=machine):
|
||||
ARCHIVE_NAME("linux", machine)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("machine", ["arm64", "aarch64"])
|
||||
def test_archive_name_arm64_not_yet_supported(machine):
|
||||
"""ARM64 is a frequent request (issue #6). Until binaries exist for it,
|
||||
ARCHIVE_NAME should hard-fail rather than silently degrade. If this test
|
||||
starts failing because someone shipped ARM64 builds, replace it with the
|
||||
positive case."""
|
||||
with pytest.raises(NotImplementedError):
|
||||
ARCHIVE_NAME("linux", machine)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("platform_key", ["darwin", "freebsd", "cygwin", "openbsd"])
|
||||
def test_archive_name_rejects_unsupported_platforms(platform_key):
|
||||
"""Same logic — non-Linux/non-Windows platforms must raise, not silently
|
||||
pick one of the two."""
|
||||
with pytest.raises(NotImplementedError, match=platform_key):
|
||||
ARCHIVE_NAME(platform_key, "x86_64")
|
||||
|
||||
|
||||
# ---- ARCHIVE_NAME ↔ BINARY_ENTRY_REL invariant ---------------------------- #
|
||||
# For every supported platform there MUST be an entry in BINARY_ENTRY_REL,
|
||||
# otherwise ensure_binary() will raise NotImplementedError AFTER having
|
||||
# already downloaded a 110 MB tarball — terrible UX.
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_binary_entry_rel_covers_every_supported_platform():
|
||||
"""If ARCHIVE_NAME accepts a platform key, BINARY_ENTRY_REL must declare
|
||||
where the executable lives inside the archive for it."""
|
||||
for plat in ["win32", "linux"]:
|
||||
ARCHIVE_NAME(plat, "x86_64") # must not raise
|
||||
assert plat in BINARY_ENTRY_REL, (
|
||||
f"ARCHIVE_NAME accepts {plat!r} but BINARY_ENTRY_REL has no entry "
|
||||
f"— ensure_binary() will fail late after a 110 MB download."
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_binary_entry_rel_extension_matches_platform():
|
||||
"""firefox.exe on Windows, plain `firefox` on Linux."""
|
||||
assert BINARY_ENTRY_REL["win32"].endswith(".exe")
|
||||
assert not BINARY_ENTRY_REL["linux"].endswith(".exe")
|
||||
assert BINARY_ENTRY_REL["linux"] == "firefox"
|
||||
|
||||
|
||||
# ---- RELEASE_URL_TEMPLATE shape ------------------------------------------- #
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_release_url_template_is_https():
|
||||
"""No http://. GitHub redirects http but we never accept the redirect."""
|
||||
assert RELEASE_URL_TEMPLATE.startswith("https://github.com/")
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_release_url_template_has_required_placeholders():
|
||||
"""{tag} and {asset} must both be present, otherwise _resolve_asset_url
|
||||
won't format a usable URL and downloads fail with confusing 404s."""
|
||||
assert "{tag}" in RELEASE_URL_TEMPLATE
|
||||
assert "{asset}" in RELEASE_URL_TEMPLATE
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_release_url_template_formats_cleanly():
|
||||
"""Confirm .format() actually substitutes — catches typos like {tags}."""
|
||||
url = RELEASE_URL_TEMPLATE.format(tag="firefox-99", asset="thing.zip")
|
||||
assert "{" not in url and "}" not in url
|
||||
assert "firefox-99" in url
|
||||
assert "thing.zip" in url
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_release_url_points_at_owned_repo():
|
||||
"""The template MUST point at an owner/repo the maintainer actually
|
||||
controls. A typo here would direct everyone's downloads at a stranger's
|
||||
GitHub account — silent supply-chain risk."""
|
||||
assert "/feder-cr/invisible_playwright/" in RELEASE_URL_TEMPLATE, (
|
||||
f"RELEASE_URL_TEMPLATE was changed to point elsewhere: "
|
||||
f"{RELEASE_URL_TEMPLATE!r}. Update this test only if the move is intentional."
|
||||
)
|
||||
|
||||
|
||||
# ---- Firefox upstream version sanity -------------------------------------- #
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_firefox_upstream_version_is_three_part_semver():
|
||||
parts = FIREFOX_UPSTREAM_VERSION.split(".")
|
||||
assert len(parts) >= 2, f"version too short: {FIREFOX_UPSTREAM_VERSION!r}"
|
||||
for p in parts:
|
||||
assert p.isdigit(), f"non-numeric segment in {FIREFOX_UPSTREAM_VERSION!r}"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_binary_basename_includes_upstream_version():
|
||||
"""The basename references the upstream version, so the asset filename
|
||||
on the CDN encodes which Firefox was patched. Bumping FIREFOX_UPSTREAM_VERSION
|
||||
without rebuilding would leave stale binaries — this guards against
|
||||
accidentally desyncing the two."""
|
||||
assert FIREFOX_UPSTREAM_VERSION in BINARY_BASENAME
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("plat", ["win32", "linux"])
|
||||
def test_archive_name_includes_upstream_version(plat):
|
||||
"""Same desync guard, from the other direction."""
|
||||
assert FIREFOX_UPSTREAM_VERSION in ARCHIVE_NAME(plat, "x86_64")
|
||||
+458
-1
@@ -4,15 +4,20 @@ import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
import responses
|
||||
|
||||
from invisible_playwright.constants import BINARY_VERSION
|
||||
from invisible_playwright.constants import BINARY_VERSION, RELEASE_URL_TEMPLATE
|
||||
from invisible_playwright.download import (
|
||||
_download_file,
|
||||
_extract,
|
||||
_github_token,
|
||||
_parse_checksums,
|
||||
_parse_owner_repo,
|
||||
_resolve_asset_url,
|
||||
_sha256_file,
|
||||
cache_dir_for_version,
|
||||
cache_root,
|
||||
ensure_binary,
|
||||
)
|
||||
|
||||
@@ -161,6 +166,166 @@ def test_parse_checksums_uses_last_token_as_filename():
|
||||
assert "some/nested/file.zip" in out
|
||||
|
||||
|
||||
# DL3 regression — issue #15 (LostBoxArt).
|
||||
# GNU coreutils `sha256sum` (and `shasum -b`) print filenames in BINARY MODE
|
||||
# with a leading `*`: "hash *filename". The parser used parts[-1] verbatim
|
||||
# so the key became "*filename" and lookups by bare filename returned None,
|
||||
# raising `RuntimeError: no SHA256 for {asset}` on every first-time fetch.
|
||||
@pytest.mark.unit
|
||||
def test_parse_checksums_strips_star_prefix_binary_mode():
|
||||
"""`sha256sum -b` format (default on Linux when reading actual files)."""
|
||||
text = "abc123 *firefox.tar.gz\n"
|
||||
out = _parse_checksums(text)
|
||||
assert out == {"firefox.tar.gz": "abc123"}, (
|
||||
"binary-mode '*' prefix must be stripped from the filename key"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_parse_checksums_handles_mixed_binary_and_text_mode():
|
||||
"""A single checksums.txt with one binary-mode line and one text-mode line.
|
||||
Both keys must be normalized (no `*` prefix) so consumers can use the bare
|
||||
filename as the lookup key regardless of how each line was produced."""
|
||||
text = (
|
||||
"aaa111 *firefox-win.zip\n"
|
||||
"bbb222 firefox-linux.tar.gz\n"
|
||||
)
|
||||
out = _parse_checksums(text)
|
||||
assert out == {"firefox-win.zip": "aaa111", "firefox-linux.tar.gz": "bbb222"}
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_parse_checksums_handles_multiple_leading_stars():
|
||||
"""`.lstrip("*")` strips any run of leading asterisks. Not a real sha256sum
|
||||
format but defensive — guarantees no `*` survives in any key."""
|
||||
text = "abc123 **doubled.zip\n"
|
||||
out = _parse_checksums(text)
|
||||
assert "doubled.zip" in out
|
||||
assert "**doubled.zip" not in out
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_parse_checksums_handles_crlf_line_endings():
|
||||
"""sha256sum.exe on Windows writes CRLF. The .strip() on each line should
|
||||
consume the \\r so the key doesn't end up as 'firefox.zip\\r'."""
|
||||
text = "abc123 *firefox.zip\r\ndef456 other.tar.gz\r\n"
|
||||
out = _parse_checksums(text)
|
||||
assert out == {"firefox.zip": "abc123", "other.tar.gz": "def456"}
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_parse_checksums_handles_utf8_bom_at_start():
|
||||
"""Some Windows tools prepend a UTF-8 BOM. The first line shouldn't be lost."""
|
||||
text = "abc123 *firefox.zip\n"
|
||||
out = _parse_checksums(text)
|
||||
# The BOM stays attached to the hash field as a non-fatal artifact;
|
||||
# what matters is that the FILENAME key is parsed and normalized.
|
||||
keys = list(out.keys())
|
||||
assert "firefox.zip" in keys, f"BOM caused first line to be lost: keys={keys}"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_parse_checksums_handles_indented_lines():
|
||||
"""Leading whitespace on a data line must not break parsing."""
|
||||
text = " abc123 *indented.zip\n"
|
||||
out = _parse_checksums(text)
|
||||
assert out == {"indented.zip": "abc123"}
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_parse_checksums_handles_trailing_whitespace():
|
||||
"""Trailing spaces on a line shouldn't end up in the key."""
|
||||
text = "abc123 *trailing.zip \n"
|
||||
out = _parse_checksums(text)
|
||||
# After .strip() the trailing spaces are gone, so the key is clean
|
||||
assert out == {"trailing.zip": "abc123"}
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_parse_checksums_real_world_sha256sum_b_output(tmp_path):
|
||||
"""End-to-end: invoke the actual `sha256sum` (or its Python equivalent)
|
||||
on a real file and verify the parser handles that output verbatim.
|
||||
|
||||
We can't depend on sha256sum being on PATH on Windows, so we synthesize
|
||||
the exact byte sequence that GNU coreutils 9.x produces."""
|
||||
fake_archive = tmp_path / "release.tar.gz"
|
||||
fake_archive.write_bytes(b"some content")
|
||||
sha = hashlib.sha256(fake_archive.read_bytes()).hexdigest()
|
||||
# Exact format coreutils prints in binary mode (default for files):
|
||||
# "<hash><SP>*<filename>\n"
|
||||
coreutils_output = f"{sha} *{fake_archive.name}\n"
|
||||
|
||||
out = _parse_checksums(coreutils_output)
|
||||
assert out == {"release.tar.gz": sha}
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_parse_checksums_text_mode_two_space_separator():
|
||||
"""`sha256sum --text` format uses two spaces. Must also parse cleanly
|
||||
and the key must be identical to the binary-mode case."""
|
||||
text = "abc123 textmode.zip\n"
|
||||
out = _parse_checksums(text)
|
||||
assert out == {"textmode.zip": "abc123"}
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_parse_checksums_empty_file_returns_empty_dict():
|
||||
assert _parse_checksums("") == {}
|
||||
assert _parse_checksums("\n\n\n") == {}
|
||||
assert _parse_checksums(" \n\t\n") == {}
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_parse_checksums_all_comment_file_returns_empty_dict():
|
||||
"""A file with only comments shouldn't crash and shouldn't produce keys."""
|
||||
text = "# generated by release script\n# 2026-05-20\n"
|
||||
assert _parse_checksums(text) == {}
|
||||
|
||||
|
||||
# DL3 regression — full integration via ensure_binary: confirm the parser
|
||||
# bug from #15 cannot regress when the live release format is mimicked exactly.
|
||||
@pytest.mark.unit
|
||||
@responses.activate
|
||||
def test_ensure_binary_accepts_binary_mode_checksums(tmp_path, monkeypatch):
|
||||
"""Reproduce the EXACT format the GitHub release ships:
|
||||
<sha> *<filename>
|
||||
Before the #15 fix this raised
|
||||
RuntimeError: no SHA256 for {asset} in checksums.txt
|
||||
even though the asset and SHA were both present."""
|
||||
cache = tmp_path / "cache"
|
||||
monkeypatch.setattr("invisible_playwright.download.cache_root", lambda: cache)
|
||||
|
||||
archive_path = tmp_path / "archive.zip"
|
||||
archive_bytes = _make_zip(archive_path, "firefox.exe", b"PEX!")
|
||||
archive_sha = hashlib.sha256(archive_bytes).hexdigest()
|
||||
from invisible_playwright.constants import ARCHIVE_NAME
|
||||
asset = ARCHIVE_NAME("win32", "AMD64")
|
||||
|
||||
url_archive = (
|
||||
f"https://github.com/feder-cr/invisible_playwright/releases/download/"
|
||||
f"{BINARY_VERSION}/{asset}"
|
||||
)
|
||||
url_sums = (
|
||||
f"https://github.com/feder-cr/invisible_playwright/releases/download/"
|
||||
f"{BINARY_VERSION}/checksums.txt"
|
||||
)
|
||||
|
||||
responses.add(responses.GET, url_archive, body=archive_bytes, status=200,
|
||||
content_type="application/zip")
|
||||
# Binary-mode format (note the `*`): regression sentinel for #15.
|
||||
responses.add(
|
||||
responses.GET, url_sums,
|
||||
body=f"{archive_sha} *{asset}\n",
|
||||
status=200,
|
||||
)
|
||||
|
||||
# Force the platform branch the test mocks:
|
||||
monkeypatch.setattr("sys.platform", "win32")
|
||||
out = ensure_binary()
|
||||
# No RuntimeError means the parser accepted the `*`-prefixed key.
|
||||
assert out.exists()
|
||||
|
||||
|
||||
# DL4: unknown archive format (.rar) raises RuntimeError
|
||||
@pytest.mark.unit
|
||||
def test_extract_unknown_format_raises(tmp_path):
|
||||
@@ -375,3 +540,295 @@ def test_ensure_binary_missing_entry_after_extract_raises_linux(tmp_path, monkey
|
||||
|
||||
with pytest.raises(RuntimeError, match="binary not found after extraction"):
|
||||
ensure_binary()
|
||||
|
||||
|
||||
# ========================================================================== #
|
||||
# _resolve_asset_url — public-repo direct URL vs private-repo API resolution
|
||||
# ========================================================================== #
|
||||
# This function chooses between two code paths based on whether a GitHub
|
||||
# token is set. Both paths produce a downloadable URL but via different
|
||||
# mechanisms, and a regression here would surface as 404 / 403 / wrong
|
||||
# binary downloaded.
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_resolve_asset_url_public_returns_direct_url(monkeypatch):
|
||||
"""No token → return the direct releases/download URL verbatim."""
|
||||
monkeypatch.delenv("STEALTHFOX_GITHUB_TOKEN", raising=False)
|
||||
monkeypatch.delenv("GITHUB_TOKEN", raising=False)
|
||||
url = _resolve_asset_url("firefox-4", "thing.zip")
|
||||
assert url == RELEASE_URL_TEMPLATE.format(tag="firefox-4", asset="thing.zip")
|
||||
assert "api.github.com" not in url # public path must skip the API
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_resolve_asset_url_public_url_format_is_stable(monkeypatch):
|
||||
"""The exact URL shape is what GitHub clients have learned to cache.
|
||||
Changing it without bumping BINARY_VERSION would 404 on first fetch
|
||||
for every existing user — guard against accidental drift."""
|
||||
monkeypatch.delenv("STEALTHFOX_GITHUB_TOKEN", raising=False)
|
||||
monkeypatch.delenv("GITHUB_TOKEN", raising=False)
|
||||
url = _resolve_asset_url("firefox-4", "abc.tar.gz")
|
||||
assert url == (
|
||||
"https://github.com/feder-cr/invisible_playwright/releases/"
|
||||
"download/firefox-4/abc.tar.gz"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@responses.activate
|
||||
def test_resolve_asset_url_private_uses_api_with_token(monkeypatch):
|
||||
"""Token set → hit the API and return the asset.url (which 302s with
|
||||
Accept: application/octet-stream). The direct release URL would 404
|
||||
for a private repo even with the token in headers."""
|
||||
monkeypatch.setenv("STEALTHFOX_GITHUB_TOKEN", "ghp_fake")
|
||||
monkeypatch.delenv("GITHUB_TOKEN", raising=False)
|
||||
|
||||
api_url = (
|
||||
"https://api.github.com/repos/feder-cr/invisible_playwright"
|
||||
"/releases/tags/firefox-4"
|
||||
)
|
||||
responses.add(
|
||||
responses.GET, api_url,
|
||||
json={"assets": [
|
||||
{"name": "other.zip", "url": "https://api.github.com/.../1"},
|
||||
{"name": "wanted.zip", "url": "https://api.github.com/.../2"},
|
||||
]},
|
||||
status=200,
|
||||
)
|
||||
url = _resolve_asset_url("firefox-4", "wanted.zip")
|
||||
assert url == "https://api.github.com/.../2"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@responses.activate
|
||||
def test_resolve_asset_url_private_raises_when_asset_missing(monkeypatch):
|
||||
"""If the asset name isn't on the release, raise — better to fail fast
|
||||
with the asset name in the message than to download something else."""
|
||||
monkeypatch.setenv("STEALTHFOX_GITHUB_TOKEN", "ghp_fake")
|
||||
api_url = (
|
||||
"https://api.github.com/repos/feder-cr/invisible_playwright"
|
||||
"/releases/tags/firefox-4"
|
||||
)
|
||||
responses.add(
|
||||
responses.GET, api_url,
|
||||
json={"assets": [{"name": "other.zip", "url": "x"}]},
|
||||
status=200,
|
||||
)
|
||||
with pytest.raises(RuntimeError, match="not-here.zip"):
|
||||
_resolve_asset_url("firefox-4", "not-here.zip")
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@responses.activate
|
||||
def test_resolve_asset_url_private_propagates_api_4xx(monkeypatch):
|
||||
"""If the API returns 404 (release doesn't exist) or 401 (bad token),
|
||||
don't swallow it silently — raise so the user sees the real reason."""
|
||||
monkeypatch.setenv("STEALTHFOX_GITHUB_TOKEN", "ghp_fake")
|
||||
api_url = (
|
||||
"https://api.github.com/repos/feder-cr/invisible_playwright"
|
||||
"/releases/tags/firefox-99"
|
||||
)
|
||||
responses.add(responses.GET, api_url, status=404)
|
||||
with pytest.raises(requests.HTTPError):
|
||||
_resolve_asset_url("firefox-99", "thing.zip")
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@responses.activate
|
||||
def test_resolve_asset_url_private_sends_auth_header(monkeypatch):
|
||||
"""The API call MUST include `Authorization: token <ghp_...>`, otherwise
|
||||
a private repo returns 404 and the user thinks the release is missing."""
|
||||
monkeypatch.setenv("STEALTHFOX_GITHUB_TOKEN", "ghp_secret")
|
||||
api_url = (
|
||||
"https://api.github.com/repos/feder-cr/invisible_playwright"
|
||||
"/releases/tags/firefox-4"
|
||||
)
|
||||
|
||||
captured = {}
|
||||
def callback(request):
|
||||
captured["auth"] = request.headers.get("Authorization")
|
||||
return (200, {}, '{"assets":[{"name":"x.zip","url":"https://x/y"}]}')
|
||||
responses.add_callback(responses.GET, api_url, callback=callback,
|
||||
content_type="application/json")
|
||||
_resolve_asset_url("firefox-4", "x.zip")
|
||||
assert captured["auth"] == "token ghp_secret"
|
||||
|
||||
|
||||
# ========================================================================== #
|
||||
# _download_file — file streaming + error propagation
|
||||
# ========================================================================== #
|
||||
|
||||
@pytest.mark.unit
|
||||
@responses.activate
|
||||
def test_download_file_writes_full_payload_to_disk(tmp_path):
|
||||
"""A 200 OK returns the full body; the file on disk matches byte-for-byte."""
|
||||
url = "https://example.com/some-large.bin"
|
||||
payload = bytes(range(256)) * 1024 # 256 KB, varied bytes
|
||||
responses.add(responses.GET, url, body=payload, status=200)
|
||||
|
||||
dst = tmp_path / "downloaded.bin"
|
||||
_download_file(url, dst)
|
||||
assert dst.exists()
|
||||
assert dst.read_bytes() == payload
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@responses.activate
|
||||
def test_download_file_creates_parent_directories(tmp_path):
|
||||
"""The dst's parent may not exist yet — _download_file is expected to
|
||||
mkdir -p before writing. Without this, the first fetch on a clean
|
||||
machine raises FileNotFoundError because the cache dir doesn't exist."""
|
||||
url = "https://example.com/x.bin"
|
||||
responses.add(responses.GET, url, body=b"data", status=200)
|
||||
|
||||
deep = tmp_path / "a" / "b" / "c" / "x.bin"
|
||||
_download_file(url, deep)
|
||||
assert deep.exists()
|
||||
assert deep.read_bytes() == b"data"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@responses.activate
|
||||
def test_download_file_propagates_http_404(tmp_path):
|
||||
"""404s from the CDN must raise — silent 404 → empty file → SHA mismatch
|
||||
is a much worse failure mode."""
|
||||
url = "https://example.com/missing.bin"
|
||||
responses.add(responses.GET, url, status=404)
|
||||
with pytest.raises(requests.HTTPError):
|
||||
_download_file(url, tmp_path / "out.bin")
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@responses.activate
|
||||
def test_download_file_propagates_http_500(tmp_path):
|
||||
"""Server errors must surface, not be swallowed as 'empty download'."""
|
||||
url = "https://example.com/broken.bin"
|
||||
responses.add(responses.GET, url, status=500)
|
||||
with pytest.raises(requests.HTTPError):
|
||||
_download_file(url, tmp_path / "out.bin")
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@responses.activate
|
||||
def test_download_file_adds_auth_for_api_urls(monkeypatch, tmp_path):
|
||||
"""When downloading from api.github.com (private-repo flow), the
|
||||
request MUST include `Authorization: token <...>` and
|
||||
`Accept: application/octet-stream` — otherwise the API returns the
|
||||
asset JSON instead of the binary."""
|
||||
monkeypatch.setenv("STEALTHFOX_GITHUB_TOKEN", "ghp_secret")
|
||||
url = "https://api.github.com/repos/x/y/releases/assets/123"
|
||||
|
||||
captured = {}
|
||||
def callback(request):
|
||||
captured["auth"] = request.headers.get("Authorization")
|
||||
captured["accept"] = request.headers.get("Accept")
|
||||
return (200, {}, b"BIN!")
|
||||
responses.add_callback(responses.GET, url, callback=callback)
|
||||
|
||||
_download_file(url, tmp_path / "out.bin")
|
||||
assert captured["auth"] == "token ghp_secret"
|
||||
assert captured["accept"] == "application/octet-stream"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@responses.activate
|
||||
def test_download_file_does_not_send_auth_for_non_api_urls(monkeypatch, tmp_path):
|
||||
"""Public-repo flow hits github.com/.../releases/download/... directly.
|
||||
Sending an auth header to that URL is unnecessary and would leak the
|
||||
token in CDN access logs."""
|
||||
monkeypatch.setenv("STEALTHFOX_GITHUB_TOKEN", "ghp_secret")
|
||||
url = "https://github.com/feder-cr/invisible_playwright/releases/download/firefox-4/x.zip"
|
||||
|
||||
captured = {}
|
||||
def callback(request):
|
||||
captured["auth"] = request.headers.get("Authorization")
|
||||
return (200, {}, b"BIN!")
|
||||
responses.add_callback(responses.GET, url, callback=callback)
|
||||
|
||||
_download_file(url, tmp_path / "out.bin")
|
||||
assert captured["auth"] is None, (
|
||||
"Auth header leaked to a public CDN URL — would expose the token "
|
||||
"in GitHub's access logs."
|
||||
)
|
||||
|
||||
|
||||
# ========================================================================== #
|
||||
# cache_root + cache_dir_for_version — path resolution
|
||||
# ========================================================================== #
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_cache_root_returns_path():
|
||||
"""Must return a Path, not a string — downstream code uses .mkdir() etc."""
|
||||
p = cache_root()
|
||||
assert isinstance(p, Path)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_cache_root_contains_package_name():
|
||||
"""The cache dir should be identifiable as ours so users can `rm -rf`
|
||||
it without nuking other tools' caches."""
|
||||
p = cache_root()
|
||||
assert "invisible-playwright" in str(p).lower()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_cache_dir_for_version_appends_version_segment():
|
||||
"""Each binary version gets its own subdir so multiple versions can
|
||||
coexist (useful for downgrade / A-B testing)."""
|
||||
p = cache_dir_for_version("firefox-99")
|
||||
assert p.name == "firefox-99"
|
||||
assert p.parent == cache_root()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_cache_dir_for_version_defaults_to_current_binary_version():
|
||||
"""No-arg call uses the pinned BINARY_VERSION."""
|
||||
p = cache_dir_for_version()
|
||||
assert p.name == BINARY_VERSION
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_cache_dir_isolation_between_versions():
|
||||
"""firefox-3 and firefox-4 must NEVER share a directory — extraction
|
||||
would clobber one with the other and break downgrade."""
|
||||
a = cache_dir_for_version("firefox-3")
|
||||
b = cache_dir_for_version("firefox-4")
|
||||
assert a != b
|
||||
assert a.parent == b.parent # but they share the same root
|
||||
|
||||
|
||||
# ========================================================================== #
|
||||
# _parse_owner_repo — more edge cases
|
||||
# ========================================================================== #
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_parse_owner_repo_extracts_from_canonical_template():
|
||||
"""Must work against the exact template stored in constants.py."""
|
||||
owner, repo = _parse_owner_repo(RELEASE_URL_TEMPLATE)
|
||||
assert owner and repo # something extracted
|
||||
assert "/" not in owner and "/" not in repo # no slashes in either segment
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("bad_template", [
|
||||
"http://github.com/x/y/releases/", # http, not https
|
||||
"https://gitlab.com/x/y/releases/", # wrong host
|
||||
"https://github.com/onlyone/releases/", # missing repo segment
|
||||
"", # empty
|
||||
"github.com/x/y/releases/", # missing scheme
|
||||
])
|
||||
def test_parse_owner_repo_rejects_malformed_urls(bad_template):
|
||||
"""Any URL that doesn't match the canonical shape must raise — silent
|
||||
None/empty extraction would build broken API URLs and confuse the user."""
|
||||
with pytest.raises(RuntimeError, match="cannot parse"):
|
||||
_parse_owner_repo(bad_template)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_parse_owner_repo_handles_repos_with_dashes_and_underscores():
|
||||
"""Repo names with -, _, . are valid on GitHub; the regex must accept them."""
|
||||
owner, repo = _parse_owner_repo(
|
||||
"https://github.com/my-org/my_cool.repo/releases/download/x/y.zip"
|
||||
)
|
||||
assert owner == "my-org"
|
||||
assert repo == "my_cool.repo"
|
||||
@@ -0,0 +1,547 @@
|
||||
"""Fingerprint consistency / lie-detection tests.
|
||||
|
||||
Complementary to test_fingerprint_surface.py: those tests ask "do you
|
||||
look like a real browser?" — these ask "are your fingerprint surfaces
|
||||
INTERNALLY CONSISTENT?"
|
||||
|
||||
Anti-bot systems catch spoofers not by checking each signal in
|
||||
isolation but by cross-checking related signals. If you spoof UA to
|
||||
"Windows" but leave navigator.platform as "Linux x86_64", or you spoof
|
||||
WebGL renderer in the main thread but not in a Web Worker, the
|
||||
inconsistency proves the spoof is fake.
|
||||
|
||||
Sources studied (all FOSS, MIT-licensed):
|
||||
- creepjs/src/lies/index.ts — the canonical lie detector
|
||||
- creepjs/src/worker/index.ts — main-vs-worker scope cross-check
|
||||
- creepjs/src/math/index.ts — Math.x(p) deterministic equality
|
||||
- creepjs/src/navigator/index.ts — UA/platform/oscpu invariants
|
||||
- niespodd/browser-fingerprinting README — worker hwConcurrency,
|
||||
plugin chain, perf.timeOrigin
|
||||
|
||||
Everything runs against `about:blank` with NO network and NO proxy.
|
||||
|
||||
Run only this file:
|
||||
pytest tests/test_fingerprint_consistency.py -m e2e -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
from invisible_playwright.constants import BINARY_ENTRY_REL
|
||||
|
||||
|
||||
PIN = {
|
||||
"screen.width": 1920,
|
||||
"screen.height": 1080,
|
||||
"screen.avail_width": 1920,
|
||||
"screen.avail_height": 1040,
|
||||
"screen.dpr": 1.0,
|
||||
"hardware.concurrency": 8,
|
||||
"audio.sample_rate": 48000,
|
||||
"audio.max_channel_count": 2,
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def firefox_binary():
|
||||
"""See test_fingerprint_surface.firefox_binary for the lookup chain."""
|
||||
import os
|
||||
env_path = os.environ.get("INVPW_BINARY_PATH")
|
||||
if env_path:
|
||||
from pathlib import Path
|
||||
if Path(env_path).exists():
|
||||
return env_path
|
||||
pytest.skip(f"INVPW_BINARY_PATH={env_path!r} does not exist")
|
||||
if sys.platform not in BINARY_ENTRY_REL:
|
||||
pytest.skip(f"unsupported platform: {sys.platform}")
|
||||
from invisible_playwright.download import cache_dir_for_version
|
||||
entry = cache_dir_for_version() / BINARY_ENTRY_REL[sys.platform]
|
||||
if not entry.exists():
|
||||
pytest.skip(
|
||||
"patched Firefox not cached; run "
|
||||
"`python -m invisible_playwright fetch` first, or set "
|
||||
"INVPW_BINARY_PATH to a local build"
|
||||
)
|
||||
return str(entry)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def page(firefox_binary):
|
||||
with InvisiblePlaywright(
|
||||
seed=42,
|
||||
pin=PIN,
|
||||
binary_path=firefox_binary,
|
||||
headless=True,
|
||||
) as browser:
|
||||
ctx = browser.new_context()
|
||||
p = ctx.new_page()
|
||||
p.goto("about:blank", timeout=30_000)
|
||||
yield p
|
||||
|
||||
|
||||
def _ev(page, expr):
|
||||
return page.evaluate(expr)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 1. Math determinism — same input MUST yield same output
|
||||
# Source: creepjs/src/math/index.ts
|
||||
# A wrapper that adds noise to Math.* (canvas-spoofing prefs) exposes
|
||||
# itself here: two consecutive calls with the same input must be
|
||||
# byte-identical.
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.parametrize("fn,arg", [
|
||||
("cos", "1e308"),
|
||||
("acos", "0.5"),
|
||||
("asin", "0.5"),
|
||||
("atan", "Math.PI"),
|
||||
("atanh", "0.5"),
|
||||
("cbrt", "Math.PI"),
|
||||
("cosh", "Math.PI"),
|
||||
("exp", "Math.PI"),
|
||||
("expm1", "Math.PI"),
|
||||
("log", "Math.PI"),
|
||||
("log1p", "Math.PI"),
|
||||
("log10", "Math.PI"),
|
||||
("sin", "Math.PI"),
|
||||
("sinh", "Math.PI"),
|
||||
("sqrt", "Math.PI"),
|
||||
("tan", "Math.PI"),
|
||||
("tanh", "Math.PI"),
|
||||
])
|
||||
def test_math_determinism(page, fn, arg):
|
||||
"""Math.<fn>(<arg>) must return the same value across 100 calls."""
|
||||
first, last, all_equal = _ev(page, f"""() => {{
|
||||
const r = [];
|
||||
for (let i = 0; i < 100; i++) r.push(Math.{fn}({arg}));
|
||||
return [r[0], r[99], r.every(x => Object.is(x, r[0]))];
|
||||
}}""")
|
||||
assert all_equal, (
|
||||
f"Math.{fn}({arg}) drifts across calls: first={first}, last={last}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_math_pow_two_arg_determinism(page):
|
||||
ok = _ev(page, """() => {
|
||||
const a = Math.pow(Math.PI, 2);
|
||||
for (let i = 0; i < 50; i++) {
|
||||
if (!Object.is(Math.pow(Math.PI, 2), a)) return false;
|
||||
}
|
||||
return true;
|
||||
}""")
|
||||
assert ok
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 2. Worker scope vs main thread — navigator properties MUST agree
|
||||
# Source: creepjs/src/worker/index.ts
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
def _worker_navigator_dict(page, props):
|
||||
expr = """async (props) => {
|
||||
const code = `
|
||||
self.onmessage = (e) => {
|
||||
const out = {};
|
||||
for (const p of e.data) {
|
||||
try { out[p] = self.navigator[p]; }
|
||||
catch (err) { out[p] = '<error: ' + err.message + '>'; }
|
||||
}
|
||||
if (out.languages && Array.isArray(out.languages)) {
|
||||
out.languages = [...out.languages];
|
||||
}
|
||||
self.postMessage(out);
|
||||
};
|
||||
`;
|
||||
const blob = new Blob([code], { type: 'application/javascript' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const worker = new Worker(url);
|
||||
try {
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
worker.onmessage = (e) => resolve(e.data);
|
||||
worker.onerror = (e) => reject(new Error(e.message));
|
||||
worker.postMessage(props);
|
||||
setTimeout(() => reject(new Error('worker timeout')), 5000);
|
||||
});
|
||||
return result;
|
||||
} finally {
|
||||
worker.terminate();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
}"""
|
||||
return page.evaluate(expr, list(props))
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_worker_userAgent_matches_main(page):
|
||||
main = _ev(page, "navigator.userAgent")
|
||||
worker = _worker_navigator_dict(page, ("userAgent",))
|
||||
assert worker["userAgent"] == main, (
|
||||
f"UA drift main vs worker:\n main: {main!r}\n worker: {worker['userAgent']!r}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_worker_hardwareConcurrency_matches_main(page):
|
||||
main = _ev(page, "navigator.hardwareConcurrency")
|
||||
worker = _worker_navigator_dict(page, ("hardwareConcurrency",))
|
||||
assert worker["hardwareConcurrency"] == main
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_worker_language_matches_main(page):
|
||||
main = _ev(page, "navigator.language")
|
||||
worker = _worker_navigator_dict(page, ("language",))
|
||||
assert worker["language"] == main
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_worker_languages_matches_main(page):
|
||||
main = _ev(page, "[...navigator.languages]")
|
||||
worker = _worker_navigator_dict(page, ("languages",))
|
||||
assert list(worker["languages"]) == list(main)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_worker_platform_matches_main(page):
|
||||
main = _ev(page, "navigator.platform")
|
||||
worker = _worker_navigator_dict(page, ("platform",))
|
||||
assert worker["platform"] == main
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 3. Iframe scope vs window scope
|
||||
# Source: creepjs/src/lies/index.ts (getBehemothIframe pattern)
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
def _iframe_navigator_dict(page, props):
|
||||
expr = """(props) => {
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.style.display = 'none';
|
||||
document.body.appendChild(iframe);
|
||||
const out = {};
|
||||
for (const p of props) {
|
||||
try { out[p] = iframe.contentWindow.navigator[p]; }
|
||||
catch (e) { out[p] = '<error: ' + e.message + '>'; }
|
||||
}
|
||||
if (Array.isArray(out.languages)) out.languages = [...out.languages];
|
||||
document.body.removeChild(iframe);
|
||||
return out;
|
||||
}"""
|
||||
return page.evaluate(expr, list(props))
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_iframe_userAgent_matches_window(page):
|
||||
main = _ev(page, "navigator.userAgent")
|
||||
iframe = _iframe_navigator_dict(page, ("userAgent",))
|
||||
assert iframe["userAgent"] == main
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_iframe_language_matches_window(page):
|
||||
main = _ev(page, "navigator.language")
|
||||
iframe = _iframe_navigator_dict(page, ("language",))
|
||||
assert iframe["language"] == main
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_iframe_hardwareConcurrency_matches_window(page):
|
||||
main = _ev(page, "navigator.hardwareConcurrency")
|
||||
iframe = _iframe_navigator_dict(page, ("hardwareConcurrency",))
|
||||
assert iframe["hardwareConcurrency"] == main
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_iframe_screen_matches_window(page):
|
||||
main = _ev(page, "[screen.width, screen.height]")
|
||||
iframe = _ev(page, """() => {
|
||||
const f = document.createElement('iframe');
|
||||
f.style.display = 'none';
|
||||
document.body.appendChild(f);
|
||||
const v = [f.contentWindow.screen.width, f.contentWindow.screen.height];
|
||||
document.body.removeChild(f);
|
||||
return v;
|
||||
}""")
|
||||
assert iframe == main
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 4. UA self-consistency (creepjs/src/navigator/index.ts)
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_navigator_platform_matches_userAgent_OS(page):
|
||||
ua = _ev(page, "navigator.userAgent")
|
||||
platform = _ev(page, "navigator.platform")
|
||||
if "Windows" in ua:
|
||||
assert "Win" in platform
|
||||
elif "Mac" in ua:
|
||||
assert "Mac" in platform
|
||||
elif "Linux" in ua or "X11" in ua:
|
||||
assert "Linux" in platform or "X11" in platform
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_navigator_oscpu_matches_userAgent(page):
|
||||
"""Firefox-only: navigator.oscpu must correlate with UA OS."""
|
||||
ua = _ev(page, "navigator.userAgent")
|
||||
oscpu = _ev(page, "navigator.oscpu || ''")
|
||||
if not oscpu:
|
||||
pytest.skip("navigator.oscpu not exposed")
|
||||
if "Windows" in ua:
|
||||
assert "Windows" in oscpu
|
||||
elif "Linux" in ua:
|
||||
assert "Linux" in oscpu
|
||||
elif "Mac" in ua:
|
||||
assert "Mac" in oscpu
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_userAgent_contains_appVersion_chromium_only(page):
|
||||
"""Chromium invariant: UA contains appVersion. Firefox uses a short
|
||||
appVersion form so the check is gated on `'chrome' in window`."""
|
||||
if not _ev(page, "'chrome' in window"):
|
||||
pytest.skip("Chromium-only invariant")
|
||||
ua = _ev(page, "navigator.userAgent")
|
||||
av = _ev(page, "navigator.appVersion")
|
||||
assert av in ua
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 5. Native function self-toString (creepjs/src/lies/index.ts hasKnownToString)
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
def _is_native_toString(text, fn_name):
|
||||
"""Mirror of CreepJS hasKnownToString — accept the engine-specific
|
||||
native patterns (single-line on V8, multi-line on SpiderMonkey)."""
|
||||
import re as _re
|
||||
name = _re.escape(fn_name)
|
||||
patterns = [
|
||||
rf"^function {name}\(\) \{{ \[native code\] \}}$",
|
||||
rf"^function get {name}\(\) \{{ \[native code\] \}}$",
|
||||
rf"^function {name}\(\) \{{[\s\S]*\[native code\][\s\S]*\}}$",
|
||||
rf"^function get {name}\(\) \{{[\s\S]*\[native code\][\s\S]*\}}$",
|
||||
]
|
||||
return any(_re.match(p, text) for p in patterns)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.parametrize("native_fn,name", [
|
||||
("Function.prototype.toString", "toString"),
|
||||
("Function.prototype.bind", "bind"),
|
||||
("Function.prototype.call", "call"),
|
||||
("Function.prototype.apply", "apply"),
|
||||
("Object.getOwnPropertyDescriptor", "getOwnPropertyDescriptor"),
|
||||
("Object.defineProperty", "defineProperty"),
|
||||
("Array.prototype.slice", "slice"),
|
||||
("JSON.stringify", "stringify"),
|
||||
])
|
||||
def test_native_function_self_toString_matches(page, native_fn, name):
|
||||
"""Each native function's `.toString()` must match its engine's
|
||||
native pattern. A Proxy wrapper or function-rewrite leaks here."""
|
||||
text = _ev(page, f"{native_fn}.toString()")
|
||||
assert _is_native_toString(text, name), (
|
||||
f"{native_fn}.toString() not native-shape: {text!r}"
|
||||
)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 6. AudioContext / WebGL determinism
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_audio_offline_context_deterministic(page):
|
||||
"""OfflineAudioContext: same graph → byte-identical output."""
|
||||
ok = _ev(page, """async () => {
|
||||
async function render() {
|
||||
const ctx = new (window.OfflineAudioContext ||
|
||||
window.webkitOfflineAudioContext)(1, 5000, 44100);
|
||||
const osc = ctx.createOscillator();
|
||||
osc.connect(ctx.destination);
|
||||
osc.start(0);
|
||||
const buf = await ctx.startRendering();
|
||||
return Array.from(buf.getChannelData(0).slice(0, 50));
|
||||
}
|
||||
const a = await render();
|
||||
const b = await render();
|
||||
return JSON.stringify(a) === JSON.stringify(b);
|
||||
}""")
|
||||
assert ok
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_webgl_getParameter_deterministic(page):
|
||||
"""WebGL parameters must not drift across reads."""
|
||||
ok = _ev(page, """() => {
|
||||
const c = document.createElement('canvas');
|
||||
const gl = c.getContext('webgl');
|
||||
if (!gl) return false;
|
||||
const params = [gl.MAX_TEXTURE_SIZE, gl.MAX_VIEWPORT_DIMS,
|
||||
gl.MAX_RENDERBUFFER_SIZE, gl.MAX_VERTEX_ATTRIBS];
|
||||
const ref = JSON.stringify(params.map(p => gl.getParameter(p)));
|
||||
for (let i = 0; i < 50; i++) {
|
||||
if (JSON.stringify(params.map(p => gl.getParameter(p))) !== ref) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}""")
|
||||
assert ok
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 7. Locale ↔ Intl cross-consistency
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_navigator_language_matches_Intl_locale(page):
|
||||
"""navigator.language base must agree with Intl.DateTimeFormat locale."""
|
||||
nav = _ev(page, "navigator.language").split("-")[0]
|
||||
intl = _ev(page,
|
||||
"Intl.DateTimeFormat().resolvedOptions().locale").split("-")[0]
|
||||
assert nav == intl, (
|
||||
f"navigator.language base={nav!r} vs Intl={intl!r}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_navigator_language_matches_Intl_NumberFormat(page):
|
||||
nav = _ev(page, "navigator.language").split("-")[0]
|
||||
num = _ev(page,
|
||||
"Intl.NumberFormat().resolvedOptions().locale").split("-")[0]
|
||||
assert nav == num
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_navigator_language_matches_Intl_Collator(page):
|
||||
nav = _ev(page, "navigator.language").split("-")[0]
|
||||
col = _ev(page,
|
||||
"(new Intl.Collator()).resolvedOptions().locale").split("-")[0]
|
||||
assert nav == col
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 8. Property descriptor shape lies
|
||||
# Spoofers using Object.defineProperty(navigator, prop, {value: ...})
|
||||
# leave a 'value' field on the descriptor — real native props use a getter.
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
_DESCRIPTOR_NATIVE_PROPS = [
|
||||
"userAgent", "platform", "hardwareConcurrency", "language", "languages",
|
||||
"vendor", "appVersion", "appName", "appCodeName", "doNotTrack",
|
||||
"cookieEnabled", "onLine", "product", "productSub", "buildID", "oscpu",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.parametrize("prop", _DESCRIPTOR_NATIVE_PROPS)
|
||||
def test_navigator_property_descriptor_is_getter_not_value(page, prop):
|
||||
"""Each spoofable navigator.* property must be defined via a native
|
||||
getter — NOT Object.defineProperty(..., {value: x}). The value-field
|
||||
descriptor is the lazy spoof leak CreepJS catches."""
|
||||
has_lie = _ev(page, f"""() => {{
|
||||
let proto = navigator;
|
||||
let descriptor = null;
|
||||
while (proto && !descriptor) {{
|
||||
descriptor = Object.getOwnPropertyDescriptor(proto, {prop!r});
|
||||
proto = Object.getPrototypeOf(proto);
|
||||
}}
|
||||
if (!descriptor) return null;
|
||||
return 'value' in descriptor;
|
||||
}}""")
|
||||
if has_lie is None:
|
||||
pytest.skip(f"navigator.{prop} not exposed")
|
||||
assert has_lie is False, (
|
||||
f"navigator.{prop} descriptor exposes 'value' field — lazy spoof"
|
||||
)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 9. performance.timeOrigin + monotonic
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_performance_timeOrigin_stable(page):
|
||||
assert _ev(page,
|
||||
"performance.timeOrigin === performance.timeOrigin")
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_performance_now_monotonic(page):
|
||||
ok = _ev(page, """() => {
|
||||
let prev = performance.now();
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const cur = performance.now();
|
||||
if (cur < prev) return false;
|
||||
prev = cur;
|
||||
}
|
||||
return true;
|
||||
}""")
|
||||
assert ok
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 10. Window dimension invariants
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_window_inner_not_larger_than_outer(page):
|
||||
inner, outer = _ev(page, "[window.innerWidth, window.outerWidth]")
|
||||
assert inner <= outer
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_screen_avail_not_larger_than_screen(page):
|
||||
aw, w = _ev(page, "[screen.availWidth, screen.width]")
|
||||
ah, h = _ev(page, "[screen.availHeight, screen.height]")
|
||||
assert aw <= w and ah <= h
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 11. Firefox UA invariants
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_firefox_UA_implies_empty_vendor(page):
|
||||
"""Firefox: navigator.vendor === ''"""
|
||||
if "Firefox" not in _ev(page, "navigator.userAgent"):
|
||||
pytest.skip("Firefox-only invariant")
|
||||
if "Chrome" in _ev(page, "navigator.userAgent"):
|
||||
pytest.skip("Chrome+Firefox UA — likely synthetic")
|
||||
assert _ev(page, "navigator.vendor") == ""
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_firefox_appVersion_short_form(page):
|
||||
"""Real Firefox's appVersion is '5.0 (Windows)' form, not the full UA."""
|
||||
if "Firefox" not in _ev(page, "navigator.userAgent"):
|
||||
pytest.skip("Firefox-only invariant")
|
||||
av = _ev(page, "navigator.appVersion")
|
||||
ua = _ev(page, "navigator.userAgent")
|
||||
assert av.startswith("5.0 (")
|
||||
assert len(av) < len(ua)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_firefox_UA_implies_appName_Netscape(page):
|
||||
"""navigator.appName === 'Netscape' (historical invariant)."""
|
||||
if "Firefox" not in _ev(page, "navigator.userAgent"):
|
||||
pytest.skip("Firefox-only invariant")
|
||||
assert _ev(page, "navigator.appName") == "Netscape"
|
||||
@@ -0,0 +1,430 @@
|
||||
"""Fingerprint surface tests — replicate the checks performed by the canonical
|
||||
anti-bot detection libraries against an OFFLINE browser session.
|
||||
|
||||
Each test asserts the SAME thing the upstream detector would flag. A pass
|
||||
here means our patched build appears human to that detector; a fail
|
||||
means a real stealth hole that anti-bot kits would exploit in production.
|
||||
|
||||
Detector libraries studied (all FOSS, MIT-licensed):
|
||||
- github.com/fingerprintjs/BotD — 19 detectors, the most
|
||||
widely deployed client-side
|
||||
bot detector
|
||||
- github.com/abrahamjuliot/creepjs — headless / stealth / lies
|
||||
modules
|
||||
- github.com/fingerprintjs/fingerprintjs — canvas / audio / color /
|
||||
touch consistency
|
||||
- github.com/antoinevastel/fpscanner — UA / platform / oscpu
|
||||
cross-checks
|
||||
- bot.sannysoft.com — classic Puppeteer harness
|
||||
|
||||
Everything runs against `about:blank` with NO network and NO proxy. The
|
||||
suite is intended to be part of the release-gate: pre-push hook runs
|
||||
`pytest -m e2e` and these tests must be green on every release.
|
||||
|
||||
Run only this file:
|
||||
pytest tests/test_fingerprint_surface.py -m e2e -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
from invisible_playwright.constants import BINARY_ENTRY_REL
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────────────
|
||||
# Inline PIN — a coherent mid-range Windows desktop. Not user-config:
|
||||
# these specific values are what the surface tests assert against.
|
||||
# Keep PIN small (only fields that JS exposes) and stable across runs.
|
||||
# ────────────────────────────────────────────────────────────────────
|
||||
|
||||
PIN = {
|
||||
"screen.width": 1920,
|
||||
"screen.height": 1080,
|
||||
"screen.avail_width": 1920,
|
||||
"screen.avail_height": 1040,
|
||||
"screen.dpr": 1.0,
|
||||
"hardware.concurrency": 8,
|
||||
"audio.sample_rate": 48000,
|
||||
"audio.max_channel_count": 2,
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def firefox_binary():
|
||||
"""Locate the patched Firefox binary. Three lookup paths:
|
||||
1. ``INVPW_BINARY_PATH`` env var (for dev iteration against a local build)
|
||||
2. Cached binary under ``cache_dir_for_version()`` (post-fetch)
|
||||
3. Skip cleanly (no implicit network download)."""
|
||||
import os
|
||||
env_path = os.environ.get("INVPW_BINARY_PATH")
|
||||
if env_path:
|
||||
from pathlib import Path
|
||||
if Path(env_path).exists():
|
||||
return env_path
|
||||
pytest.skip(f"INVPW_BINARY_PATH={env_path!r} does not exist")
|
||||
if sys.platform not in BINARY_ENTRY_REL:
|
||||
pytest.skip(f"unsupported platform: {sys.platform}")
|
||||
from invisible_playwright.download import cache_dir_for_version
|
||||
entry = cache_dir_for_version() / BINARY_ENTRY_REL[sys.platform]
|
||||
if not entry.exists():
|
||||
pytest.skip(
|
||||
"patched Firefox not cached; run "
|
||||
"`python -m invisible_playwright fetch` first, or set "
|
||||
"INVPW_BINARY_PATH to a local build"
|
||||
)
|
||||
return str(entry)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def page(firefox_binary):
|
||||
"""One headless browser shared across the whole module.
|
||||
~20s startup paid once, then every test runs in ~50ms."""
|
||||
with InvisiblePlaywright(
|
||||
seed=42,
|
||||
pin=PIN,
|
||||
binary_path=firefox_binary,
|
||||
headless=True,
|
||||
) as browser:
|
||||
ctx = browser.new_context()
|
||||
p = ctx.new_page()
|
||||
p.goto("about:blank", timeout=30_000)
|
||||
yield p
|
||||
|
||||
|
||||
def _ev(page, expr):
|
||||
return page.evaluate(expr)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# BotD detectors (github.com/fingerprintjs/BotD/tree/main/src/detectors)
|
||||
# Each detector becomes one pytest. The failure name maps to the BotKind
|
||||
# constant BotD would emit on the wire.
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_botd_webdriver_property_is_falsey(page):
|
||||
"""BotD: navigator.webdriver === true → HeadlessChrome verdict."""
|
||||
assert not _ev(page, "navigator.webdriver"), (
|
||||
"navigator.webdriver is truthy — instant HeadlessChrome verdict"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_botd_app_version_no_headless_token(page):
|
||||
"""BotD detectAppVersion: /headless|electron|slimerjs/i in appVersion."""
|
||||
av = _ev(page, "navigator.appVersion")
|
||||
for token in ("headless", "electron", "slimerjs"):
|
||||
assert not re.search(token, av, re.I), (
|
||||
f"navigator.appVersion contains {token!r}: {av!r}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_botd_user_agent_no_headless_or_selenium_token(page):
|
||||
"""BotD: /headless|selenium|phantom/i in UA."""
|
||||
ua = _ev(page, "navigator.userAgent")
|
||||
for token in ("headless", "selenium", "phantom"):
|
||||
assert not re.search(token, ua, re.I), (
|
||||
f"navigator.userAgent contains {token!r}: {ua!r}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_botd_function_bind_is_function(page):
|
||||
"""BotD detectFunctionBind: missing Function.prototype.bind = PhantomJS."""
|
||||
assert _ev(page, "typeof Function.prototype.bind === 'function'")
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_botd_product_sub_is_gecko_value(page):
|
||||
"""BotD detectProductSub: Firefox must return '20100101'; '20030107'
|
||||
on a Firefox UA = Chrome-stub leaked under spoof."""
|
||||
assert _ev(page, "navigator.productSub") == "20100101", (
|
||||
"navigator.productSub must be '20100101' on Firefox"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_botd_no_process_global(page):
|
||||
"""BotD detectProcess: window.process indicates Electron."""
|
||||
assert not _ev(page,
|
||||
"typeof window.process !== 'undefined' && "
|
||||
"window.process.type === 'renderer'"
|
||||
)
|
||||
assert not _ev(page,
|
||||
"typeof window.process !== 'undefined' && "
|
||||
"window.process.versions != null && "
|
||||
"typeof window.process.versions.electron !== 'undefined'"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_botd_eval_length_matches_engine(page):
|
||||
"""BotD detectEvalLengthInconsistency: `eval.toString().length` must be
|
||||
37 on Gecko (33 on Chromium, 39 on IE). Mismatch = engine spoof."""
|
||||
assert _ev(page, "eval.toString().length") == 37
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_botd_languages_array_non_empty(page):
|
||||
"""BotD detectLanguagesLengthInconsistency: empty navigator.languages
|
||||
is the classic HeadlessChrome tell."""
|
||||
assert _ev(page, "navigator.languages.length") > 0
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_botd_plugins_instance_of_PluginArray(page):
|
||||
"""BotD detectPluginsArray: navigator.plugins must be a real PluginArray."""
|
||||
assert _ev(page, "navigator.plugins instanceof PluginArray")
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_botd_mime_types_consistent_prototype_chain(page):
|
||||
"""BotD areMimeTypesConsistent: navigator.mimeTypes and each entry
|
||||
must have proper prototype chain. Spoofers using plain arrays fail."""
|
||||
consistent = _ev(page, """() => {
|
||||
if (typeof navigator.mimeTypes === 'undefined' ||
|
||||
typeof MimeTypeArray === 'undefined') return false;
|
||||
let ok = Object.getPrototypeOf(navigator.mimeTypes) === MimeTypeArray.prototype;
|
||||
for (let i = 0; i < navigator.mimeTypes.length; i++) {
|
||||
ok = ok && Object.getPrototypeOf(navigator.mimeTypes[i]) === MimeType.prototype;
|
||||
}
|
||||
return ok;
|
||||
}""")
|
||||
assert consistent, "navigator.mimeTypes prototype chain inconsistent"
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_botd_no_distinctive_window_props(page):
|
||||
"""BotD checkDistinctiveProperties: scan window for automation globals."""
|
||||
DISTINCTIVE = [
|
||||
"awesomium", "RunPerfTest", "CefSharp", "fmget_targets", "geb",
|
||||
"__nightmare", "nightmare", "__phantomas", "callPhantom", "_phantom",
|
||||
"wdioElectron", "__webdriverFunc", "_WEBDRIVER_ELEM_CACHE",
|
||||
"ChromeDriverw", "domAutomation", "domAutomationController",
|
||||
]
|
||||
leaks = [n for n in DISTINCTIVE
|
||||
if _ev(page, f"typeof window[{n!r}] !== 'undefined'")]
|
||||
assert not leaks, f"Distinctive bot globals leaked: {leaks}"
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_botd_no_distinctive_document_props(page):
|
||||
"""BotD: document-side automation globals (webdriver/selenium/cdc)."""
|
||||
DOC_LEAKS = [
|
||||
"__webdriver_evaluate", "__selenium_evaluate",
|
||||
"__webdriver_script_function", "__webdriver_script_func",
|
||||
"__webdriver_script_fn", "__fxdriver_evaluate",
|
||||
"__driver_unwrapped", "__webdriver_unwrapped",
|
||||
"__driver_evaluate", "__selenium_unwrapped",
|
||||
"__fxdriver_unwrapped",
|
||||
"$cdc_asdjflasutopfhvcZLmcf", "$cdc_asdjflasutopfhvcZLmcfl_",
|
||||
"$chrome_asyncScriptInfo", "__$webdriverAsyncExecutor",
|
||||
]
|
||||
leaks = [n for n in DOC_LEAKS
|
||||
if _ev(page, f"typeof document[{n!r}] !== 'undefined'")]
|
||||
assert not leaks, f"document carries automation property names: {leaks}"
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_botd_document_html_attributes_clean(page):
|
||||
"""BotD detectDocumentAttributes: html element attrs contain 'selenium'
|
||||
/ 'webdriver' / 'driver' → Selenium verdict."""
|
||||
attrs = _ev(page,
|
||||
"Array.from(document.documentElement.attributes).map(a => a.name + '=' + a.value)")
|
||||
bad = [a for a in attrs if any(t in a.lower()
|
||||
for t in ("selenium", "webdriver", "driver"))]
|
||||
assert not bad, f"HTML attributes contain bot tokens: {bad}"
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_botd_window_size_nonzero(page):
|
||||
"""BotD detectWindowSize: headless without window manager → 0x0."""
|
||||
ow = _ev(page, "window.outerWidth")
|
||||
oh = _ev(page, "window.outerHeight")
|
||||
assert ow > 0 and oh > 0, (
|
||||
f"outerWidth/Height = {ow}/{oh} — headless without window manager"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_botd_webgl_debug_renderer_info_available(page):
|
||||
"""BotD detectWebGL: WEBGL_debug_renderer_info extension must exist."""
|
||||
has_ext = _ev(page, """() => {
|
||||
const c = document.createElement('canvas');
|
||||
const gl = c.getContext('webgl') || c.getContext('experimental-webgl');
|
||||
return !!gl && !!gl.getExtension('WEBGL_debug_renderer_info');
|
||||
}""")
|
||||
assert has_ext
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# sannysoft.com — classic Puppeteer detection harness
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_sannysoft_chrome_object_consistency(page):
|
||||
"""Firefox UA + window.chrome present = bot-framework leak."""
|
||||
if "Firefox" in _ev(page, "navigator.userAgent"):
|
||||
assert not _ev(page, "typeof window.chrome !== 'undefined'")
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_sannysoft_permissions_query_works(page):
|
||||
"""navigator.permissions.query() must return a proper PermissionStatus."""
|
||||
ok = _ev(page, """async () => {
|
||||
if (!navigator.permissions || !navigator.permissions.query) return false;
|
||||
try {
|
||||
const r = await navigator.permissions.query({name: 'notifications'});
|
||||
return r && typeof r.state === 'string';
|
||||
} catch (e) { return false; }
|
||||
}""")
|
||||
assert ok
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_sannysoft_iframe_chrome_not_leaked(page):
|
||||
"""iframe.contentWindow.chrome must not leak on Firefox UA."""
|
||||
if "Firefox" not in _ev(page, "navigator.userAgent"):
|
||||
pytest.skip("Firefox-only invariant")
|
||||
leaks = _ev(page, """() => {
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.style.display = 'none';
|
||||
document.body.appendChild(iframe);
|
||||
const is = typeof iframe.contentWindow.chrome !== 'undefined';
|
||||
document.body.removeChild(iframe);
|
||||
return is;
|
||||
}""")
|
||||
assert not leaks
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_sannysoft_iframe_languages_not_empty(page):
|
||||
"""Iframe-scope navigator.languages must have ≥1 entry."""
|
||||
n = _ev(page, """() => {
|
||||
const f = document.createElement('iframe');
|
||||
f.style.display = 'none';
|
||||
document.body.appendChild(f);
|
||||
const len = f.contentWindow.navigator.languages.length;
|
||||
document.body.removeChild(f);
|
||||
return len;
|
||||
}""")
|
||||
assert n > 0
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# FingerprintJS — fingerprint surface coherence
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_fpjs_canvas_2d_context_returns_valid(page):
|
||||
ok = _ev(page, """() => {
|
||||
const c = document.createElement('canvas');
|
||||
c.width = 100; c.height = 100;
|
||||
const ctx = c.getContext('2d');
|
||||
if (!ctx) return false;
|
||||
ctx.fillText('test', 10, 10);
|
||||
const data = c.toDataURL();
|
||||
return data.length > 100 && data.startsWith('data:image/png;base64');
|
||||
}""")
|
||||
assert ok
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_fpjs_audio_context_works(page):
|
||||
ok = _ev(page, """async () => {
|
||||
try {
|
||||
const ctx = new (window.OfflineAudioContext ||
|
||||
window.webkitOfflineAudioContext)(1, 5000, 44100);
|
||||
const osc = ctx.createOscillator();
|
||||
osc.connect(ctx.destination);
|
||||
osc.start(0);
|
||||
const buf = await ctx.startRendering();
|
||||
return buf && buf.length > 0;
|
||||
} catch (e) { return false; }
|
||||
}""")
|
||||
assert ok
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_fpjs_color_gamut_query_works(page):
|
||||
"""matchMedia('(color-gamut: ...)') must match at least srgb."""
|
||||
ok = _ev(page, """matchMedia('(color-gamut: srgb)').matches ||
|
||||
matchMedia('(color-gamut: p3)').matches ||
|
||||
matchMedia('(color-gamut: rec2020)').matches""")
|
||||
assert ok
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_fpjs_screen_color_depth_realistic(page):
|
||||
"""Atypical color depths are headless-distinctive."""
|
||||
cd = _ev(page, "screen.colorDepth")
|
||||
assert cd in (24, 30, 32)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# PIN-locked surfaces (the values declared in PIN above)
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_pin_screen_width_lands_in_screen_object(page):
|
||||
assert _ev(page, "screen.width") == PIN["screen.width"]
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_pin_screen_height_lands_in_screen_object(page):
|
||||
assert _ev(page, "screen.height") == PIN["screen.height"]
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_pin_hardware_concurrency_lands_in_navigator(page):
|
||||
assert (_ev(page, "navigator.hardwareConcurrency")
|
||||
== PIN["hardware.concurrency"])
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_pin_audio_sample_rate_lands_in_AudioContext(page):
|
||||
assert _ev(page,
|
||||
"(new (window.AudioContext||window.webkitAudioContext)()).sampleRate"
|
||||
) == PIN["audio.sample_rate"]
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_pin_audio_max_channels_lands_in_destination(page):
|
||||
assert _ev(page,
|
||||
"(new (window.AudioContext||window.webkitAudioContext)())"
|
||||
".destination.maxChannelCount"
|
||||
) == PIN["audio.max_channel_count"]
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# fpscanner-style cross-checks
|
||||
# ===========================================================================
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_fpscanner_ua_vs_platform_consistent(page):
|
||||
"""UA OS substring must agree with navigator.platform OS substring."""
|
||||
ua = _ev(page, "navigator.userAgent")
|
||||
platform = _ev(page, "navigator.platform")
|
||||
if "Windows" in ua:
|
||||
assert "Win" in platform, f"UA Win but platform={platform!r}"
|
||||
elif "Mac" in ua:
|
||||
assert "Mac" in platform
|
||||
elif "Linux" in ua:
|
||||
assert "Linux" in platform or "X11" in platform
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_fpscanner_no_userAgentData_on_firefox(page):
|
||||
"""navigator.userAgentData is Chromium-only. Presence on Firefox UA = bot."""
|
||||
if "Firefox" in _ev(page, "navigator.userAgent"):
|
||||
assert not _ev(page, "'userAgentData' in navigator")
|
||||
@@ -55,3 +55,217 @@ def test_invisible_playwright_constructs_without_launching():
|
||||
assert obj is not None
|
||||
obj2 = InvisiblePlaywright(seed=42, headless=True)
|
||||
assert obj2 is not None
|
||||
|
||||
|
||||
# ─── profile_dir kwarg — persistent context support ─────────────────────── #
|
||||
|
||||
import pytest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_profile_dir_none_by_default():
|
||||
"""No persistent profile unless explicitly opted in. Prevents accidental
|
||||
state-leak between scripts that share the same seed."""
|
||||
obj = InvisiblePlaywright(seed=42)
|
||||
assert obj._profile_dir is None
|
||||
assert obj._persistent_context is None
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_profile_dir_string_is_coerced_to_path(tmp_path):
|
||||
"""Accept str or Path. Always store as Path internally."""
|
||||
obj = InvisiblePlaywright(seed=42, profile_dir=str(tmp_path))
|
||||
assert isinstance(obj._profile_dir, Path)
|
||||
assert obj._profile_dir == tmp_path
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_profile_dir_path_is_stored_as_is(tmp_path):
|
||||
obj = InvisiblePlaywright(seed=42, profile_dir=tmp_path)
|
||||
assert obj._profile_dir == tmp_path
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_profile_dir_does_not_create_dir_until_enter(tmp_path):
|
||||
"""Construction must not touch the filesystem. Directory creation only
|
||||
happens when the user actually enters the context manager — otherwise
|
||||
a typo at instantiation would silently spawn dirs."""
|
||||
target = tmp_path / "nonexistent"
|
||||
assert not target.exists()
|
||||
InvisiblePlaywright(seed=42, profile_dir=target)
|
||||
assert not target.exists()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_persistent_context_kwargs_match_default_exactly():
|
||||
"""Persistent kwargs must be IDENTICAL to non-persistent default
|
||||
kwargs. From firefox-5 (C7 closure) the docShell.overrideTimezone
|
||||
method is present in the patched binary, so the per-realm overrides
|
||||
Playwright applies for `locale=`/`timezone_id=` land successfully and
|
||||
no longer hang the persistent context launch handshake.
|
||||
|
||||
Before firefox-5 we had to filter these out (180s timeout otherwise).
|
||||
A future refactor that re-introduces that filter would silently lose
|
||||
timezone/locale isolation in persistent sessions — this test is the
|
||||
sentinel that catches the regression at the unit level."""
|
||||
obj = InvisiblePlaywright(seed=42, locale="en-GB", timezone="Europe/London",
|
||||
profile_dir="/tmp/x")
|
||||
persistent = obj._persistent_context_kwargs()
|
||||
default = obj._default_context_kwargs()
|
||||
assert persistent == default, (
|
||||
"persistent_context kwargs must match default_context kwargs since "
|
||||
f"firefox-5.\n persistent: {persistent!r}\n default: {default!r}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_persistent_context_kwargs_INCLUDES_locale_and_timezone():
|
||||
"""Sentinel for the C7 closure: firefox-5 ships the C++ overrideTimezone
|
||||
IDL method, so locale + timezone_id MUST be passed through to
|
||||
launch_persistent_context. If they're not, the wrapper is silently
|
||||
dropping per-context isolation — two sessions with different
|
||||
`timezone=` would end up sharing whatever TZ the env var set.
|
||||
|
||||
Regression-defense: do NOT re-add the firefox-4-era filter."""
|
||||
obj = InvisiblePlaywright(seed=42, locale="en-GB", timezone="Europe/London",
|
||||
profile_dir="/tmp/x")
|
||||
kw = obj._persistent_context_kwargs()
|
||||
assert kw.get("locale") == "en-GB", (
|
||||
f"locale must be in persistent kwargs (firefox-5+ supports it via "
|
||||
f"docShell.languageOverride). Got: {kw.get('locale')!r}"
|
||||
)
|
||||
assert kw.get("timezone_id") == "Europe/London", (
|
||||
f"timezone_id must be in persistent kwargs (firefox-5+ supports it "
|
||||
f"via docShell.overrideTimezone IDL method, patch.md section 19). "
|
||||
f"Got: {kw.get('timezone_id')!r}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_persistent_context_kwargs_omits_timezone_when_empty_string():
|
||||
"""Empty timezone='' is the 'use host TZ' sentinel — must NOT pass
|
||||
timezone_id to Playwright in that case (would pin to literal '' and
|
||||
break Intl)."""
|
||||
obj = InvisiblePlaywright(seed=42, timezone="", profile_dir="/tmp/x")
|
||||
kw = obj._persistent_context_kwargs()
|
||||
assert "timezone_id" not in kw
|
||||
|
||||
|
||||
# ─── Mocked __enter__ flow — confirms the right Playwright call is made ── #
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_enter_with_profile_dir_calls_launch_persistent_context(tmp_path, monkeypatch):
|
||||
"""When profile_dir is set, __enter__ must call
|
||||
`firefox.launch_persistent_context(user_data_dir=...)` and NOT
|
||||
`firefox.launch(...)`. This is the structural test that the persistent
|
||||
branch is wired correctly — without it, profile_dir would be silently
|
||||
accepted but ignored."""
|
||||
from unittest.mock import MagicMock
|
||||
# Mock ensure_binary so we don't hit the network
|
||||
monkeypatch.setattr("invisible_playwright.launcher.ensure_binary",
|
||||
lambda: tmp_path / "firefox")
|
||||
|
||||
# Mock sync_playwright().start() → fake playwright with our recording firefox
|
||||
fake_ctx = MagicMock(name="persistent_context")
|
||||
fake_firefox = MagicMock()
|
||||
fake_firefox.launch_persistent_context.return_value = fake_ctx
|
||||
fake_playwright = MagicMock()
|
||||
fake_playwright.firefox = fake_firefox
|
||||
fake_pw = MagicMock()
|
||||
fake_pw.start.return_value = fake_playwright
|
||||
|
||||
monkeypatch.setattr("invisible_playwright.launcher.sync_playwright",
|
||||
lambda: fake_pw)
|
||||
|
||||
profile = tmp_path / "myprofile"
|
||||
obj = InvisiblePlaywright(seed=42, profile_dir=profile)
|
||||
returned = obj.__enter__()
|
||||
|
||||
# The persistent branch was taken
|
||||
fake_firefox.launch_persistent_context.assert_called_once()
|
||||
fake_firefox.launch.assert_not_called()
|
||||
|
||||
# The user_data_dir was passed verbatim
|
||||
call_kwargs = fake_firefox.launch_persistent_context.call_args.kwargs
|
||||
assert call_kwargs["user_data_dir"] == str(profile)
|
||||
|
||||
# The directory was created on disk (Playwright fails otherwise)
|
||||
assert profile.exists() and profile.is_dir()
|
||||
|
||||
# __enter__ returned the BrowserContext, not a Browser
|
||||
assert returned is fake_ctx
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_enter_without_profile_dir_calls_launch_not_persistent(tmp_path, monkeypatch):
|
||||
"""Default path: profile_dir=None → firefox.launch, not
|
||||
launch_persistent_context. Sentinel that the non-persistent flow
|
||||
isn't accidentally rerouted."""
|
||||
from unittest.mock import MagicMock
|
||||
monkeypatch.setattr("invisible_playwright.launcher.ensure_binary",
|
||||
lambda: tmp_path / "firefox")
|
||||
|
||||
fake_browser = MagicMock(name="browser")
|
||||
fake_browser.new_context = MagicMock()
|
||||
fake_firefox = MagicMock()
|
||||
fake_firefox.launch.return_value = fake_browser
|
||||
fake_playwright = MagicMock()
|
||||
fake_playwright.firefox = fake_firefox
|
||||
fake_pw = MagicMock()
|
||||
fake_pw.start.return_value = fake_playwright
|
||||
|
||||
monkeypatch.setattr("invisible_playwright.launcher.sync_playwright",
|
||||
lambda: fake_pw)
|
||||
|
||||
obj = InvisiblePlaywright(seed=42)
|
||||
returned = obj.__enter__()
|
||||
|
||||
fake_firefox.launch.assert_called_once()
|
||||
fake_firefox.launch_persistent_context.assert_not_called()
|
||||
assert returned is fake_browser
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_persistent_context_user_data_dir_is_created_if_missing(tmp_path, monkeypatch):
|
||||
"""First-run scenario: the directory the user names doesn't exist yet.
|
||||
__enter__ must mkdir -p it (Playwright won't, and would crash with
|
||||
'user_data_dir does not exist')."""
|
||||
from unittest.mock import MagicMock
|
||||
monkeypatch.setattr("invisible_playwright.launcher.ensure_binary",
|
||||
lambda: tmp_path / "firefox")
|
||||
fake_pw = MagicMock()
|
||||
fake_pw.start.return_value = MagicMock()
|
||||
fake_pw.start.return_value.firefox.launch_persistent_context = MagicMock(
|
||||
return_value=MagicMock()
|
||||
)
|
||||
monkeypatch.setattr("invisible_playwright.launcher.sync_playwright",
|
||||
lambda: fake_pw)
|
||||
|
||||
nested = tmp_path / "a" / "b" / "c" / "profile"
|
||||
assert not nested.parent.exists() # parent doesn't exist either
|
||||
obj = InvisiblePlaywright(seed=42, profile_dir=nested)
|
||||
obj.__enter__()
|
||||
assert nested.is_dir()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_teardown_closes_persistent_context(tmp_path, monkeypatch):
|
||||
"""The teardown must close the persistent context. Forgetting this
|
||||
leaves Firefox + Playwright running until the parent process exits,
|
||||
which on long-running tools (job orchestrators, MCP servers) leaks
|
||||
handles indefinitely."""
|
||||
from unittest.mock import MagicMock
|
||||
monkeypatch.setattr("invisible_playwright.launcher.ensure_binary",
|
||||
lambda: tmp_path / "firefox")
|
||||
fake_ctx = MagicMock(name="persistent_context")
|
||||
fake_pw = MagicMock()
|
||||
fake_pw.start.return_value.firefox.launch_persistent_context.return_value = fake_ctx
|
||||
monkeypatch.setattr("invisible_playwright.launcher.sync_playwright",
|
||||
lambda: fake_pw)
|
||||
|
||||
obj = InvisiblePlaywright(seed=42, profile_dir=tmp_path / "p")
|
||||
obj.__enter__()
|
||||
obj.__exit__(None, None, None)
|
||||
fake_ctx.close.assert_called_once()
|
||||
@@ -0,0 +1,253 @@
|
||||
"""End-to-end release tests.
|
||||
|
||||
These exercise the FULL user install path against the LIVE GitHub release.
|
||||
They are slow (download a ~110 MB binary, launch Firefox) and require network
|
||||
access — marked `e2e` so they're excluded from the default suite. Run them
|
||||
BEFORE announcing a release:
|
||||
|
||||
pytest tests/test_release_e2e.py -m e2e -v
|
||||
|
||||
Or to target a specific git revision (default is current HEAD on origin/main):
|
||||
|
||||
INVPW_E2E_REV=v0.1.5 pytest tests/test_release_e2e.py -m e2e -v
|
||||
|
||||
What each test verifies and why it exists:
|
||||
|
||||
test_clean_install_from_git_main:
|
||||
Spawns a fresh venv and pip-installs the wrapper from git HEAD. Confirms
|
||||
the package has no broken metadata, missing deps, or import errors in a
|
||||
pristine environment. Catches the "works on my machine because I already
|
||||
have the dev deps" class of bug.
|
||||
|
||||
test_fetch_against_live_release:
|
||||
After the install, runs `python -m invisible_playwright fetch --force`,
|
||||
which downloads the live tarball + checksums.txt for the pinned
|
||||
BINARY_VERSION from the production GitHub release. This is THE test that
|
||||
would have caught LostBoxArt's #15 — the checksums.txt parser bug only
|
||||
manifested against the real binary-mode format the release ships, not
|
||||
against unit-test mocks.
|
||||
|
||||
test_version_command_after_fetch:
|
||||
Confirms `python -m invisible_playwright --version` resolves the binary
|
||||
and reports the expected `firefox-N` tag. Sanity check that the binary
|
||||
landed in the cache and the wrapper can find it.
|
||||
|
||||
test_playwright_launch_against_real_site (linux-only by default):
|
||||
Launches the patched Firefox under the wrapper, navigates to a stable
|
||||
public URL, and reads a known DOM property. This is the full stack:
|
||||
wrapper init → Firefox launch → Juggler handshake → page.goto →
|
||||
page.evaluate. If anything along the way regresses (Juggler protocol
|
||||
schema drift, prefs typo, sandbox issue, …) this fails loudly.
|
||||
|
||||
The tests use a temp cache dir per run (env var
|
||||
`INVISIBLE_PLAYWRIGHT_CACHE_DIR`) so they never poison the developer's real
|
||||
cache and never get false positives from a previously-cached binary.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
REPO_URL = "https://github.com/feder-cr/invisible_playwright.git"
|
||||
REV = os.environ.get("INVPW_E2E_REV", "main")
|
||||
|
||||
|
||||
# ---------- helpers --------------------------------------------------------- #
|
||||
|
||||
|
||||
def _run(cmd: list[str], *, env: dict | None = None, cwd: Path | None = None,
|
||||
timeout: int = 300, check: bool = True) -> subprocess.CompletedProcess:
|
||||
"""Run a subprocess with full output captured. Fail with both streams shown."""
|
||||
result = subprocess.run(
|
||||
cmd, env=env, cwd=cwd, timeout=timeout,
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
if check and result.returncode != 0:
|
||||
raise AssertionError(
|
||||
f"{' '.join(cmd)} exited {result.returncode}\n"
|
||||
f"--- stdout ---\n{result.stdout[-3000:]}\n"
|
||||
f"--- stderr ---\n{result.stderr[-3000:]}"
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _venv_python(venv: Path) -> Path:
|
||||
if os.name == "nt":
|
||||
return venv / "Scripts" / "python.exe"
|
||||
return venv / "bin" / "python"
|
||||
|
||||
|
||||
# ---------- fixtures -------------------------------------------------------- #
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def workspace() -> Path:
|
||||
"""A single temp dir reused across the module so we don't re-create the
|
||||
venv + re-download the 110 MB tarball for every individual test."""
|
||||
root = Path(tempfile.mkdtemp(prefix="invpw-e2e-"))
|
||||
yield root
|
||||
shutil.rmtree(root, ignore_errors=True)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def clean_venv(workspace: Path) -> Path:
|
||||
"""A fresh venv, pip upgraded. Returns its python executable path."""
|
||||
venv_dir = workspace / "venv"
|
||||
_run([sys.executable, "-m", "venv", str(venv_dir)], timeout=180)
|
||||
py = _venv_python(venv_dir)
|
||||
assert py.exists(), f"venv python not found at {py}"
|
||||
_run([str(py), "-m", "pip", "install", "--upgrade", "pip", "--quiet"], timeout=180)
|
||||
return py
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def isolated_cache_env(workspace: Path) -> dict:
|
||||
"""Environment dict pointing the wrapper at a private cache dir so this
|
||||
test never reads or pollutes the developer's real cache."""
|
||||
cache = workspace / "cache"
|
||||
cache.mkdir(exist_ok=True)
|
||||
env = os.environ.copy()
|
||||
env["INVISIBLE_PLAYWRIGHT_CACHE_DIR"] = str(cache)
|
||||
env["XDG_CACHE_HOME"] = str(cache)
|
||||
return env
|
||||
|
||||
|
||||
# ---------- tests ----------------------------------------------------------- #
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_clean_install_from_git_main(clean_venv: Path):
|
||||
"""The package installs cleanly from git+HTTPS in a pristine venv."""
|
||||
url = f"git+{REPO_URL}@{REV}"
|
||||
_run([str(clean_venv), "-m", "pip", "install", url], timeout=600)
|
||||
|
||||
# Importability check — catches missing __init__ exports, broken syntax,
|
||||
# missing runtime deps.
|
||||
out = _run(
|
||||
[str(clean_venv), "-c",
|
||||
"import invisible_playwright as ip; "
|
||||
"print('OK', ip.__name__)"],
|
||||
timeout=30,
|
||||
)
|
||||
assert "OK invisible_playwright" in out.stdout
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_version_command_reports_wrapper_and_binary(clean_venv: Path):
|
||||
"""`python -m invisible_playwright --version` runs and reports both the
|
||||
wrapper version and the BINARY_VERSION it'll try to fetch."""
|
||||
out = _run(
|
||||
[str(clean_venv), "-m", "invisible_playwright", "--version"],
|
||||
timeout=30,
|
||||
)
|
||||
text = out.stdout + out.stderr
|
||||
assert "firefox-" in text, f"BINARY_VERSION not reported: {text!r}"
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_fetch_against_live_release(clean_venv: Path, isolated_cache_env: dict):
|
||||
"""Hit the LIVE GitHub release: download tarball + checksums.txt, parse,
|
||||
SHA256-verify, extract. This is the regression sentinel for #15.
|
||||
|
||||
If checksums.txt is shipped in `*`-prefixed (binary) format and the parser
|
||||
keeps the `*` in the key, this raises
|
||||
RuntimeError: no SHA256 for {asset} in checksums.txt
|
||||
"""
|
||||
out = _run(
|
||||
[str(clean_venv), "-m", "invisible_playwright", "fetch", "--force"],
|
||||
env=isolated_cache_env,
|
||||
timeout=900, # 110 MB download + extract on slow connections
|
||||
)
|
||||
output = out.stdout + out.stderr
|
||||
# Anti-regression for #15: this exact string would surface if the parser
|
||||
# broke again. Spell it out so a future failure is grep-able to the issue.
|
||||
assert "no SHA256 for" not in output, (
|
||||
"Issue #15 regression: parser couldn't find SHA for the asset.\n"
|
||||
f"Output:\n{output[-2000:]}"
|
||||
)
|
||||
assert "SHA256 mismatch" not in output, (
|
||||
"Tarball SHA doesn't match the published checksums.txt — "
|
||||
"either the upload was corrupted or the release was re-packed "
|
||||
"without updating checksums.txt."
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_binary_executes_after_fetch(clean_venv: Path, isolated_cache_env: dict):
|
||||
"""After fetch, the binary cache contains a launchable Firefox."""
|
||||
out = _run(
|
||||
[str(clean_venv), "-c",
|
||||
"from invisible_playwright.download import ensure_binary; "
|
||||
"p = ensure_binary(); print('BINARY', p)"],
|
||||
env=isolated_cache_env,
|
||||
timeout=60,
|
||||
)
|
||||
binary_line = [l for l in out.stdout.splitlines() if l.startswith("BINARY ")]
|
||||
assert binary_line, f"ensure_binary() didn't print path: {out.stdout!r}"
|
||||
binary_path = Path(binary_line[0].split(" ", 1)[1])
|
||||
assert binary_path.exists(), f"binary missing: {binary_path}"
|
||||
|
||||
# `firefox --version` exit code is enough; output format differs across
|
||||
# platforms (Win shows nothing on stdout, Linux prints to stdout).
|
||||
# On Linux invoke via WSL when running from Windows.
|
||||
if os.name == "nt" and binary_path.suffix == "":
|
||||
# Linux binary path on Windows host — skip launch, the previous
|
||||
# ensure_binary() already proved cache landed correctly.
|
||||
pytest.skip("Cross-platform binary launch from Windows requires WSL.")
|
||||
r = subprocess.run([str(binary_path), "--version"],
|
||||
capture_output=True, text=True, timeout=30)
|
||||
text = (r.stdout + r.stderr).lower()
|
||||
assert "firefox" in text and "150." in text, (
|
||||
f"binary --version didn't report Firefox 150: rc={r.returncode} "
|
||||
f"out={r.stdout!r} err={r.stderr!r}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.linux_only
|
||||
def test_playwright_launch_against_real_site(clean_venv: Path,
|
||||
isolated_cache_env: dict):
|
||||
"""Full stack: launch the patched Firefox via the wrapper, navigate to a
|
||||
real URL, evaluate JS. Catches Juggler protocol drift, profile-generation
|
||||
bugs, locale handling regressions, prefs typos."""
|
||||
if sys.platform.startswith("win"):
|
||||
pytest.skip("Headless launch path requires display server (skip on Win).")
|
||||
|
||||
script = (
|
||||
"from invisible_playwright import InvisiblePlaywright\n"
|
||||
"with InvisiblePlaywright(headless=True, seed=42) as browser:\n"
|
||||
" ctx = browser.new_context()\n"
|
||||
" page = ctx.new_page()\n"
|
||||
" page.goto('https://example.com', timeout=30000)\n"
|
||||
" title = page.title()\n"
|
||||
" ua = page.evaluate('navigator.userAgent')\n"
|
||||
" print('TITLE=' + title)\n"
|
||||
" print('UA=' + ua)\n"
|
||||
)
|
||||
out = _run([str(clean_venv), "-c", script],
|
||||
env=isolated_cache_env, timeout=180)
|
||||
assert "TITLE=Example Domain" in out.stdout, (
|
||||
f"page.title() didn't return expected text:\n{out.stdout[-1000:]}"
|
||||
)
|
||||
assert "UA=" in out.stdout and "Firefox/150" in out.stdout, (
|
||||
"navigator.userAgent doesn't report Firefox/150 — UA spoofing "
|
||||
f"regression?\n{out.stdout[-1000:]}"
|
||||
)
|
||||
|
||||
|
||||
# ---------- meta: verify the test markers themselves work ------------------- #
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_e2e_marker_is_excluded_by_default():
|
||||
"""Sanity check on pyproject.toml's `addopts = '-m not e2e'` — this test
|
||||
only runs when `-m e2e` is passed explicitly. If you're reading this in
|
||||
a normal pytest run, the addopts filter is broken."""
|
||||
assert True
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Service worker interception regression tests — issue #18 root cause.
|
||||
|
||||
The bug: `juggler/content/NetworkObserver.js:channelIntercepted` called
|
||||
`interceptedChannel.interceptAfterServiceWorkerResets()` — an IDL method
|
||||
that upstream Playwright adds via a C++ patch (InterceptedHttpChannel.cpp
|
||||
+ nsINetworkInterceptController.idl). Our fork was missing those patches
|
||||
until firefox-6, so the call threw TypeError → C++ NetworkObserver was
|
||||
left in an inconsistent state → content process disposal manifested as
|
||||
"page crash" on sites whose service workers fall through to the network
|
||||
(e.g., id.sky.com).
|
||||
|
||||
These tests inline-serve a service worker via data: URLs / blob URLs
|
||||
where possible — no external network required. They assert the page
|
||||
stays alive across SW registration + fetch lifecycle.
|
||||
|
||||
Run:
|
||||
pytest tests/test_service_worker.py -m e2e -v
|
||||
|
||||
For dev iteration:
|
||||
INVPW_BINARY_PATH=/path/to/firefox.exe pytest tests/test_service_worker.py -m e2e -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import os
|
||||
import socketserver
|
||||
import sys
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
from invisible_playwright.constants import BINARY_ENTRY_REL
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def firefox_binary():
|
||||
env_path = os.environ.get("INVPW_BINARY_PATH")
|
||||
if env_path:
|
||||
from pathlib import Path
|
||||
if Path(env_path).exists():
|
||||
return env_path
|
||||
pytest.skip(f"INVPW_BINARY_PATH={env_path!r} does not exist")
|
||||
if sys.platform not in BINARY_ENTRY_REL:
|
||||
pytest.skip(f"unsupported platform: {sys.platform}")
|
||||
from invisible_playwright.download import cache_dir_for_version
|
||||
entry = cache_dir_for_version() / BINARY_ENTRY_REL[sys.platform]
|
||||
if not entry.exists():
|
||||
pytest.skip(
|
||||
"patched Firefox not cached; run `python -m invisible_playwright fetch` "
|
||||
"or set INVPW_BINARY_PATH"
|
||||
)
|
||||
return str(entry)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Local HTTP fixture server — service workers need a real http(s) origin
|
||||
# (data: and about:blank are opaque-origin, no SW registration possible).
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _SWFixtureHandler(http.server.BaseHTTPRequestHandler):
|
||||
"""Serves a tiny set of routes for SW lifecycle testing."""
|
||||
|
||||
PAGES = {
|
||||
"/": (200, "text/html", b"""<!doctype html>
|
||||
<html><head><title>sw-host</title></head>
|
||||
<body>
|
||||
<script>
|
||||
window.__swState = 'loading';
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.register('/sw.js')
|
||||
.then(reg => { window.__swState = 'registered'; })
|
||||
.catch(err => { window.__swState = 'failed:' + err.message; });
|
||||
} else {
|
||||
window.__swState = 'unsupported';
|
||||
}
|
||||
</script>
|
||||
</body></html>
|
||||
"""),
|
||||
"/sw.js": (200, "application/javascript", b"""
|
||||
self.addEventListener('install', e => self.skipWaiting());
|
||||
self.addEventListener('activate', e => e.waitUntil(clients.claim()));
|
||||
self.addEventListener('fetch', e => {
|
||||
if (e.request.url.endsWith('/from-sw')) {
|
||||
e.respondWith(new Response('hello from SW', {
|
||||
headers: {'content-type': 'text/plain'},
|
||||
}));
|
||||
}
|
||||
// Fall through for everything else - exercises the
|
||||
// interceptAfterServiceWorkerResets path that was broken pre-firefox-6.
|
||||
});
|
||||
"""),
|
||||
"/from-sw": (200, "text/plain", b"network-fallback"),
|
||||
"/from-network": (200, "text/plain", b"net-only"),
|
||||
}
|
||||
|
||||
def do_GET(self):
|
||||
path = self.path.split("?", 1)[0]
|
||||
if path in self.PAGES:
|
||||
status, ctype, body = self.PAGES[path]
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
# SW requires HTTPS or localhost — we're on localhost so plain http is fine
|
||||
self.send_header("Service-Worker-Allowed", "/")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
else:
|
||||
self.send_response(404)
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *args, **kwargs):
|
||||
pass # silence stdout
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fixture_server():
|
||||
"""Spin up a localhost HTTP server with SW-friendly headers. Yields
|
||||
the base URL (e.g., 'http://127.0.0.1:54321')."""
|
||||
httpd = socketserver.TCPServer(("127.0.0.1", 0), _SWFixtureHandler)
|
||||
port = httpd.server_address[1]
|
||||
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
yield f"http://127.0.0.1:{port}"
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def page(firefox_binary):
|
||||
with InvisiblePlaywright(
|
||||
seed=42,
|
||||
binary_path=firefox_binary,
|
||||
headless=True,
|
||||
) as browser:
|
||||
ctx = browser.new_context()
|
||||
p = ctx.new_page()
|
||||
yield p
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Regression tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_service_worker_registration_does_not_crash_page(page, fixture_server):
|
||||
"""Navigate to a page that registers a SW. The page must survive the
|
||||
registration. Pre-firefox-6 this crashed if the SW path hit the missing
|
||||
`interceptAfterServiceWorkerResets()` IDL method."""
|
||||
crashed = {"v": False}
|
||||
page.on("crash", lambda p: crashed.__setitem__("v", True))
|
||||
|
||||
page.goto(f"{fixture_server}/", timeout=15_000)
|
||||
# Wait for SW to register (or fail cleanly)
|
||||
page.wait_for_function(
|
||||
"window.__swState !== 'loading'", timeout=10_000
|
||||
)
|
||||
state = page.evaluate("window.__swState")
|
||||
assert not crashed["v"], f"page crashed during SW registration (state={state!r})"
|
||||
# state should be 'registered' or 'failed:...' (Firefox supports SW)
|
||||
assert state in ("registered",) or state.startswith("failed:"), (
|
||||
f"unexpected SW state: {state!r}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_page_with_sw_can_navigate_repeatedly(page, fixture_server):
|
||||
"""Once a SW is registered, repeated navigations exercise the
|
||||
interception path on every request. Pre-firefox-6, this hit the C++
|
||||
crash after a few cycles."""
|
||||
crashed = {"v": False}
|
||||
page.on("crash", lambda p: crashed.__setitem__("v", True))
|
||||
|
||||
page.goto(f"{fixture_server}/", timeout=15_000)
|
||||
page.wait_for_function("window.__swState !== 'loading'", timeout=10_000)
|
||||
|
||||
# 5 reloads — the SW fetch handler runs each time
|
||||
for _ in range(5):
|
||||
page.reload(timeout=15_000)
|
||||
assert not crashed["v"]
|
||||
assert page.evaluate("document.title") == "sw-host"
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_fetch_through_sw_returns_sw_synthesized_response(page, fixture_server):
|
||||
"""The SW intercepts `/from-sw` and synthesizes a response without
|
||||
hitting the network. Verifies the SW fetch path is functional — this
|
||||
is the exact flow that crashed in id.sky.com."""
|
||||
page.goto(f"{fixture_server}/", timeout=15_000)
|
||||
page.wait_for_function("window.__swState === 'registered'", timeout=10_000)
|
||||
|
||||
# First request to /from-sw routes through the SW
|
||||
body = page.evaluate("""async (base) => {
|
||||
const r = await fetch(base + '/from-sw');
|
||||
return await r.text();
|
||||
}""", fixture_server)
|
||||
# Either the SW served 'hello from SW' (intercepted) or the network
|
||||
# served 'network-fallback' (if SW didn't claim yet). Both are OK —
|
||||
# the regression we test is that it doesn't CRASH.
|
||||
assert body in ("hello from SW", "network-fallback"), (
|
||||
f"unexpected /from-sw response body: {body!r}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_sw_fall_through_to_network_does_not_crash(page, fixture_server):
|
||||
"""Request a URL the SW doesn't handle → falls through to network.
|
||||
This is the `interceptAfterServiceWorkerResets()` code path: the SW
|
||||
decides not to handle, the channel goes back to network. Without the
|
||||
C++ patch, this is where the C++ side ended up in an inconsistent
|
||||
state."""
|
||||
crashed = {"v": False}
|
||||
page.on("crash", lambda p: crashed.__setitem__("v", True))
|
||||
|
||||
page.goto(f"{fixture_server}/", timeout=15_000)
|
||||
page.wait_for_function("window.__swState === 'registered'", timeout=10_000)
|
||||
|
||||
# /from-network is NOT intercepted by SW — exercises the fall-through
|
||||
body = page.evaluate("""async (base) => {
|
||||
const r = await fetch(base + '/from-network');
|
||||
return await r.text();
|
||||
}""", fixture_server)
|
||||
assert body == "net-only"
|
||||
assert not crashed["v"]
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_sw_unregister_then_register_again(page, fixture_server):
|
||||
"""Unregistering then re-registering exercises lifecycle bookkeeping
|
||||
in the C++ InterceptedHttpChannel state machine."""
|
||||
crashed = {"v": False}
|
||||
page.on("crash", lambda p: crashed.__setitem__("v", True))
|
||||
|
||||
page.goto(f"{fixture_server}/", timeout=15_000)
|
||||
page.wait_for_function("window.__swState === 'registered'", timeout=10_000)
|
||||
|
||||
# Unregister all SWs then register again
|
||||
result = page.evaluate("""async () => {
|
||||
const regs = await navigator.serviceWorker.getRegistrations();
|
||||
for (const r of regs) await r.unregister();
|
||||
const r2 = await navigator.serviceWorker.register('/sw.js');
|
||||
return r2.scope;
|
||||
}""")
|
||||
assert "/" in result
|
||||
assert not crashed["v"]
|
||||
Reference in new issue
Block a user